refactor(repo)!: move apps, shared packages, and patch definitions
Everything sat in packages/: two programs next to the small libraries
they use, and the patch data loose at the root. The programs now live in
apps/ and the shared libraries in packages/:
apps/server the local server (was packages/local-service),
package @wto/server
packages/patcher builds the game copy (was packages/build),
package @wto/patcher
patches/exe exe patch definitions (was exe-patches)
patches/gui GUI script patches (was gui-patches)
Inside the server, the network layer folder becomes transport/ so it is
not server/server/, the entry module is server.ts, and startLocalService
and its types become startServer, ServerOptions and RunningServer. The
health answer names the app wto-server, and the TLS files in the data
folder are server.key and server.crt (made again on the next start).
Comments, logs and tool texts say "local server".
The patcher no longer reaches into the server's folder. It read the
default tuning/store.jsonc by a relative path to register bundle GUIDs
for the multi-vehicle packs, which also ignored the player's overrides
in <data>/tuning/. It now takes the pack ids from its caller; the
server exports multiVehiclePackIds(dataFolder), which reads them the way
the running server does. rebuildGuiPack takes the patch folder from its
caller as well.
The development build moves out of the patcher to
scripts/build-game-copy.ts, since it uses both the server and the
patcher. It needs --data (the folder the server will run with) and
defaults the patch folders and the hook library to this repository.
Checked with the root typecheck, check-patches, check-gui,
check-offsets, the native build, a run of build-game-copy.ts into a
scratch folder (12 exe patches, 35 GUI patches, 496 bundle GUIDs as
before) and a server start from apps/server answering wto-server.
BREAKING CHANGE: Use @wto/server and @wto/patcher from the new workspace paths. Run the development build with scripts/build-game-copy.ts and pass --data.
This commit is contained in:
1 parent
9c813ccf7d
commit
930ea07630
476 files changed
+275
-251
No files matched your search
@@ -0,0 +1,197 @@
|
||||
/**
|
||||
* What the player's active boosters (rateBooster items, config/items.blk rateBoosterParams) add
|
||||
* to a battle, and how much of each the battle uses up. Online the server applies them; the
|
||||
* client only shows the result (debriefing column "booster", log affectedBoosters).
|
||||
*
|
||||
* Rules and where they come from:
|
||||
* - A booster adds its percent of the base reward (without premium account or talisman): the
|
||||
* percents of booster, premium account and talisman are added, not multiplied (official wiki
|
||||
* "Boosters" https://wiki.warthunder.com/awards/5028-boosters : "1.42 x (100% + 500% + 50%)").
|
||||
* - Stacking (scripts globals/ranks_common_shared.nut calc_public_boost, used for personal and
|
||||
* "(all allies)" boosters alike; items/boosterEffect.nut getBoostersEffects): boosters are grouped
|
||||
* by event type (none, kill, kill_ground, assist) and by personal / all allies; within a group
|
||||
* the percents, largest first, count x1, x0.6, x0.4, x0.2, then x0.1 (at least 1 point each),
|
||||
* rounded to a whole percent; the groups add up. The wiki's "penalty in order of increasing
|
||||
* bonus" says the same.
|
||||
* - Battles used (stop type sessionsStarted): a battle counts once, and with spentInSessionTimeMin
|
||||
* every such span counts as one more (items/itemsClasses/itemBooster.nut getLeftStopSessions;
|
||||
* wiki: "in a battle that lasted 1 hour and 20 minutes, a booster for 1 battle will only be
|
||||
* effective for the first 30 minutes of the battle ... 3 battles will be deducted"). So a booster
|
||||
* with R battles left covers the first R spans of the battle.
|
||||
* - Event boosters (rateBoosterParams/event kill, kill_ground, assist with targetIsPlayer) add only
|
||||
* to the reward of that event. The event names are the client's expEvent names (ExpEvent.KILL,
|
||||
* KILL_GROUND, ASSIST; inferred). Their stop killedPlayers / killedGround ends them after N kills;
|
||||
* which kills count is inferred: killedPlayers = kills of players, killedGround = kills of ground
|
||||
* vehicles. Event-free boosters add to every reward of the battle, including the mission reward
|
||||
* (lang "for all battle actions and mission reward").
|
||||
* - Not boosted (offline design; nothing official found): battle awards (streaks), the skill bonus.
|
||||
* Other stop types (none in 2.61.0.37) count the battle once.
|
||||
*/
|
||||
import type { BoosterDefinition } from '../game-data/datasets/item-catalogue.ts';
|
||||
import { ExpEvent } from './battle-economy.ts';
|
||||
import type { BattleReport, ReportedCombatEvent } from './battle-report.ts';
|
||||
|
||||
export interface ActiveBooster {
|
||||
readonly uid: string;
|
||||
readonly id: string;
|
||||
readonly booster: BoosterDefinition;
|
||||
/** Stop condition progress before the battle (items/<uid>/progress). */
|
||||
readonly progress: number;
|
||||
}
|
||||
|
||||
export interface BoosterPercent {
|
||||
readonly wp: number;
|
||||
readonly rp: number;
|
||||
}
|
||||
|
||||
export interface BoosterUse {
|
||||
readonly booster: ActiveBooster;
|
||||
/** Stop condition progress after the battle. */
|
||||
readonly progress: number;
|
||||
/** The stop condition is reached: the booster is used up. */
|
||||
readonly finished: boolean;
|
||||
}
|
||||
|
||||
/** Rates the settlement asks for (battle-rewards.ts). */
|
||||
export interface BoosterRates {
|
||||
/** Percents for the reward of one combat event. */
|
||||
forEvent(event: ReportedCombatEvent): BoosterPercent;
|
||||
/** Percents averaged over time spans, for rewards earned over time. */
|
||||
overSpans(spans: readonly { readonly start: number; readonly end: number }[]): BoosterPercent;
|
||||
}
|
||||
|
||||
export const NO_BOOSTER: BoosterPercent = { wp: 0, rp: 0 };
|
||||
|
||||
const STACK_FACTORS = [1.0, 0.6, 0.4, 0.2, 0.1] as const;
|
||||
const EVENT_CODES: Readonly<Record<string, number>> = { kill: ExpEvent.KILL, kill_ground: ExpEvent.KILL_GROUND, assist: ExpEvent.ASSIST };
|
||||
const KILL_CODES: ReadonlySet<number> = new Set([ExpEvent.KILL, ExpEvent.KILL_GROUND, ExpEvent.KILL_HUMAN]);
|
||||
|
||||
/** One booster in one battle: until when it covers, and what it applies to. */
|
||||
interface Coverage {
|
||||
readonly booster: ActiveBooster;
|
||||
/** The event code it is limited to; undefined for every reward. */
|
||||
readonly eventCode?: number;
|
||||
/** An event booster that requires the target to be a player. */
|
||||
readonly playersOnly: boolean;
|
||||
/** Mission time up to which it covers. */
|
||||
readonly end: number;
|
||||
/** The end itself is covered (kill-counted boosters cover the kill that ends them). */
|
||||
readonly endCovered: boolean;
|
||||
readonly used: number;
|
||||
}
|
||||
|
||||
export class BattleBoosters implements BoosterRates {
|
||||
readonly #coverage: readonly Coverage[];
|
||||
|
||||
constructor(boosters: readonly ActiveBooster[], report: Pick<BattleReport, 'sessionStart' | 'sessionEnd' | 'events'>) {
|
||||
this.#coverage = boosters.flatMap((booster) => {
|
||||
const coverage = coverageOf(booster, report);
|
||||
return coverage ? [coverage] : [];
|
||||
});
|
||||
}
|
||||
|
||||
/** The boosters that took part in the battle (log affectedBoosters). */
|
||||
get applied(): readonly ActiveBooster[] {
|
||||
return this.#coverage.map((coverage) => coverage.booster);
|
||||
}
|
||||
|
||||
/** What the battle used of each booster. */
|
||||
get uses(): readonly BoosterUse[] {
|
||||
return this.#coverage.map(({ booster, used }) => {
|
||||
const progress = booster.progress + used;
|
||||
return { booster, progress, finished: progress >= booster.booster.stop.count };
|
||||
});
|
||||
}
|
||||
|
||||
forEvent(event: ReportedCombatEvent): BoosterPercent {
|
||||
if (event.friendly) return NO_BOOSTER;
|
||||
const active = this.#coverage.filter((coverage) =>
|
||||
covers(coverage, event.time)
|
||||
&& (coverage.eventCode === undefined || (coverage.eventCode === event.code && (!coverage.playersOnly || event.victimIsPlayer))));
|
||||
return percentOf(active);
|
||||
}
|
||||
|
||||
overSpans(spans: readonly { readonly start: number; readonly end: number }[]): BoosterPercent {
|
||||
const general = this.#coverage.filter((coverage) => coverage.eventCode === undefined);
|
||||
let length = 0;
|
||||
let wp = 0;
|
||||
let rp = 0;
|
||||
for (const span of spans) {
|
||||
const cuts = [span.start, ...general.map((c) => c.end).filter((t) => t > span.start && t < span.end), span.end].sort((a, b) => a - b);
|
||||
for (let i = 0; i + 1 < cuts.length; i++) {
|
||||
const from = cuts[i]!;
|
||||
const to = cuts[i + 1]!;
|
||||
if (to <= from) continue;
|
||||
const percent = percentOf(general.filter((c) => covers(c, (from + to) / 2)));
|
||||
length += to - from;
|
||||
wp += percent.wp * (to - from);
|
||||
rp += percent.rp * (to - from);
|
||||
}
|
||||
}
|
||||
return length > 0 ? { wp: wp / length, rp: rp / length } : NO_BOOSTER;
|
||||
}
|
||||
}
|
||||
|
||||
function coverageOf(booster: ActiveBooster, report: Pick<BattleReport, 'sessionStart' | 'sessionEnd' | 'events'>): Coverage | undefined {
|
||||
const def = booster.booster;
|
||||
const left = def.stop.count - booster.progress;
|
||||
if (left <= 0 || (def.wpPercent <= 0 && def.rpPercent <= 0)) return undefined;
|
||||
const eventType = def.event?.type;
|
||||
const eventCode = eventType === undefined ? undefined : EVENT_CODES[eventType];
|
||||
if (eventType !== undefined && eventCode === undefined) return undefined;
|
||||
const playersOnly = def.event?.conditions.some((condition) => condition.type === 'targetIsPlayer') ?? false;
|
||||
const base = { booster, ...(eventCode !== undefined ? { eventCode } : {}), playersOnly };
|
||||
|
||||
if (def.stop.type === 'killedPlayers' || def.stop.type === 'killedGround') {
|
||||
const kills = report.events
|
||||
.filter((e) => !e.friendly && (def.stop.type === 'killedPlayers' ? KILL_CODES.has(e.code) && e.victimIsPlayer : e.code === ExpEvent.KILL_GROUND))
|
||||
.map((e) => e.time)
|
||||
.sort((a, b) => a - b);
|
||||
const last = kills[left - 1];
|
||||
return { ...base, end: last ?? Infinity, endCovered: true, used: Math.min(left, kills.length) };
|
||||
}
|
||||
const duration = Math.max(0, report.sessionEnd - report.sessionStart);
|
||||
if (def.stop.type !== 'sessionsStarted' || def.minutesPerBattle <= 0) {
|
||||
return { ...base, end: Infinity, endCovered: true, used: 1 };
|
||||
}
|
||||
const span = def.minutesPerBattle * 60;
|
||||
return {
|
||||
...base,
|
||||
end: report.sessionStart + left * span,
|
||||
endCovered: false,
|
||||
used: Math.min(left, 1 + Math.floor(duration / span)),
|
||||
};
|
||||
}
|
||||
|
||||
function covers(coverage: Coverage, time: number): boolean {
|
||||
return time < coverage.end || (coverage.endCovered && time === coverage.end);
|
||||
}
|
||||
|
||||
function percentOf(active: readonly Coverage[]): BoosterPercent {
|
||||
const groups = new Map<string, { wp: number[]; rp: number[] }>();
|
||||
for (const { booster, eventCode } of active) {
|
||||
const key = `${eventCode ?? ''}/${booster.booster.personal}`;
|
||||
let group = groups.get(key);
|
||||
if (!group) groups.set(key, group = { wp: [], rp: [] });
|
||||
if (booster.booster.wpPercent > 0) group.wp.push(booster.booster.wpPercent);
|
||||
if (booster.booster.rpPercent > 0) group.rp.push(booster.booster.rpPercent);
|
||||
}
|
||||
let wp = 0;
|
||||
let rp = 0;
|
||||
for (const group of groups.values()) {
|
||||
wp += stacked(group.wp);
|
||||
rp += stacked(group.rp);
|
||||
}
|
||||
return { wp, rp };
|
||||
}
|
||||
|
||||
/** calc_public_boost (= calc_personal_boost) of scripts globals/ranks_common_shared.nut. */
|
||||
export function stacked(percents: readonly number[]): number {
|
||||
const last = STACK_FACTORS[STACK_FACTORS.length - 1]!;
|
||||
let total = 0;
|
||||
[...percents].sort((a, b) => b - a).forEach((percent, i) => {
|
||||
if (i < STACK_FACTORS.length) total += STACK_FACTORS[i]! * percent;
|
||||
else total += last * percent > 1 ? last * percent : 1;
|
||||
});
|
||||
return Math.round(total);
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
/**
|
||||
* Authentic nation coalition pairing for Arcade, Realistic, and Simulator battles.
|
||||
*
|
||||
* Filters eligible countries by tech-tree vehicle availability in the match's BR window,
|
||||
* assigns the player uniformly to Team 1 (`allies`) or Team 2 (`axis`), and builds
|
||||
* per-team bare country lists (`"usa"`, `"germany"`, ...) with `playerCountry` at index 0
|
||||
* of the player's team array.
|
||||
*/
|
||||
import { randomInt } from 'node:crypto';
|
||||
import type { CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.ts';
|
||||
import type { ModeDifficulty, UnitClass } from '../game-modes/catalogue/game-mode-declaration.ts';
|
||||
import { stripCountryPrefix, unitClassOfExpClass, vehicleMrank } from './battle-ranks.ts';
|
||||
import type { BattleTuning } from './battle-tuning.ts';
|
||||
|
||||
const SIM_WW2_ALLIES: readonly string[] = ['usa', 'ussr', 'britain', 'china', 'france', 'israel'];
|
||||
const SIM_WW2_AXIS: readonly string[] = ['germany', 'japan', 'italy', 'sweden'];
|
||||
const SIM_CW_WEST: readonly string[] = ['usa', 'germany', 'britain', 'japan', 'italy', 'france', 'sweden', 'israel'];
|
||||
const SIM_CW_EAST: readonly string[] = ['ussr', 'china'];
|
||||
|
||||
export interface CoalitionPairingInput {
|
||||
readonly vehicles: readonly CatalogueVehicle[];
|
||||
readonly knownCountries: readonly string[];
|
||||
readonly playerCountry: string;
|
||||
readonly difficulty: ModeDifficulty;
|
||||
readonly requiredClass: UnitClass;
|
||||
readonly playerMrank: number;
|
||||
readonly minMrank: number;
|
||||
readonly maxMrank: number;
|
||||
readonly tuning: BattleTuning;
|
||||
}
|
||||
|
||||
export interface CoalitionPairing {
|
||||
readonly playerTeam: 1 | 2;
|
||||
readonly countryAllies: string;
|
||||
readonly countryAxis: string;
|
||||
readonly countriesAllies: readonly string[];
|
||||
readonly countriesAxis: readonly string[];
|
||||
readonly symmetricTeams: boolean;
|
||||
}
|
||||
|
||||
export function selectBattleCoalitions(input: CoalitionPairingInput): CoalitionPairing {
|
||||
const playerCountry = stripCountryPrefix(input.playerCountry);
|
||||
const eligible = eligibleCountriesForBracket(input, playerCountry);
|
||||
const playerTeam: 1 | 2 = randomInt(2) === 0 ? 1 : 2;
|
||||
const sides = input.difficulty === 'arcade'
|
||||
? buildArcadeSides(eligible, playerCountry)
|
||||
: input.difficulty === 'simulator'
|
||||
? buildSimulatorSides(eligible, playerCountry, input.playerMrank, input.tuning.simColdWarMinMrank)
|
||||
: buildRealisticSides(eligible, playerCountry, input.requiredClass, input.tuning);
|
||||
|
||||
const countriesAllies = playerTeam === 1 ? sides.playerSide : sides.enemySide;
|
||||
const countriesAxis = playerTeam === 2 ? sides.playerSide : sides.enemySide;
|
||||
return {
|
||||
playerTeam,
|
||||
countryAllies: countriesAllies[0] ?? playerCountry,
|
||||
countryAxis: countriesAxis[0] ?? playerCountry,
|
||||
countriesAllies,
|
||||
countriesAxis,
|
||||
symmetricTeams: sides.symmetricTeams,
|
||||
};
|
||||
}
|
||||
|
||||
interface TeamSides {
|
||||
readonly playerSide: readonly string[];
|
||||
readonly enemySide: readonly string[];
|
||||
readonly symmetricTeams: boolean;
|
||||
}
|
||||
|
||||
function eligibleCountriesForBracket(input: CoalitionPairingInput, playerCountry: string): string[] {
|
||||
const knownBare = [...new Set(input.knownCountries.map(stripCountryPrefix).filter((c) => c.length > 0))];
|
||||
const knownSet = new Set(knownBare);
|
||||
const inWindow = new Set<string>();
|
||||
const inClass = new Set<string>();
|
||||
|
||||
for (const vehicle of input.vehicles) {
|
||||
if (!isStandardTreeVehicle(vehicle, input.requiredClass)) continue;
|
||||
const bare = stripCountryPrefix(vehicle.country);
|
||||
if (!knownSet.has(bare)) continue;
|
||||
inClass.add(bare);
|
||||
const mrank = vehicleMrank(vehicle, input.difficulty, input.requiredClass);
|
||||
if (mrank >= input.minMrank && mrank <= input.maxMrank) inWindow.add(bare);
|
||||
}
|
||||
|
||||
inWindow.add(playerCountry);
|
||||
if (inWindow.size >= 2) return knownBare.filter((c) => inWindow.has(c));
|
||||
inClass.add(playerCountry);
|
||||
if (inClass.size >= 2) return knownBare.filter((c) => inClass.has(c));
|
||||
return knownBare.includes(playerCountry) ? knownBare : [playerCountry, ...knownBare];
|
||||
}
|
||||
|
||||
function isStandardTreeVehicle(vehicle: CatalogueVehicle, requiredClass: UnitClass): boolean {
|
||||
return vehicle.inTechTree
|
||||
&& !vehicle.onlyShownWhenOwned
|
||||
&& !vehicle.premiumPack
|
||||
&& !vehicle.gift
|
||||
&& !vehicle.event
|
||||
&& vehicle.researchType === undefined
|
||||
&& unitClassOfExpClass(vehicle.unitClass) === requiredClass;
|
||||
}
|
||||
|
||||
function buildArcadeSides(eligible: readonly string[], playerCountry: string): TeamSides {
|
||||
const playerSide = placeFirst(shuffle(eligible), playerCountry);
|
||||
const enemySide = shuffle(eligible);
|
||||
return { playerSide, enemySide, symmetricTeams: true };
|
||||
}
|
||||
|
||||
function buildSimulatorSides(
|
||||
eligible: readonly string[],
|
||||
playerCountry: string,
|
||||
playerMrank: number,
|
||||
coldWarMinMrank: number,
|
||||
): TeamSides {
|
||||
const eligibleSet = new Set(eligible);
|
||||
const blocA = (playerMrank < coldWarMinMrank ? SIM_WW2_ALLIES : SIM_CW_WEST).filter((c) => eligibleSet.has(c));
|
||||
const blocB = (playerMrank < coldWarMinMrank ? SIM_WW2_AXIS : SIM_CW_EAST).filter((c) => eligibleSet.has(c));
|
||||
|
||||
const playerInB = blocB.includes(playerCountry);
|
||||
const rawPlayerBloc = playerInB ? [...blocB] : [...blocA];
|
||||
const rawEnemyBloc = playerInB ? [...blocA] : [...blocB];
|
||||
if (!rawPlayerBloc.includes(playerCountry)) rawPlayerBloc.unshift(playerCountry);
|
||||
|
||||
const playerOthers = shuffle(rawPlayerBloc.filter((c) => c !== playerCountry));
|
||||
let enemySide = shuffle(rawEnemyBloc.filter((c) => c !== playerCountry));
|
||||
if (enemySide.length === 0 && playerOthers.length > 0) {
|
||||
enemySide = [playerOthers.pop()!];
|
||||
}
|
||||
if (enemySide.length === 0) {
|
||||
const fallback = eligible.find((c) => c !== playerCountry) ?? playerCountry;
|
||||
enemySide = [fallback];
|
||||
}
|
||||
return {
|
||||
playerSide: [playerCountry, ...playerOthers],
|
||||
enemySide,
|
||||
symmetricTeams: false,
|
||||
};
|
||||
}
|
||||
|
||||
function buildRealisticSides(
|
||||
eligible: readonly string[],
|
||||
playerCountry: string,
|
||||
requiredClass: UnitClass,
|
||||
tuning: BattleTuning,
|
||||
): TeamSides {
|
||||
const mixedChance = requiredClass === 'tank'
|
||||
? tuning.rbGroundMixedChance
|
||||
: requiredClass === 'ship'
|
||||
? tuning.rbNavalMixedChance
|
||||
: tuning.rbAirMixedChance;
|
||||
const roll = randomInt(1_000_000) / 1_000_000;
|
||||
if (roll >= mixedChance && eligible.length >= 2) {
|
||||
return buildDisjointRealisticSides(eligible, playerCountry, tuning);
|
||||
}
|
||||
return buildMixedRealisticSides(eligible, playerCountry, tuning);
|
||||
}
|
||||
|
||||
function buildDisjointRealisticSides(
|
||||
eligible: readonly string[],
|
||||
playerCountry: string,
|
||||
tuning: BattleTuning,
|
||||
): TeamSides {
|
||||
const others = shuffle(eligible.filter((c) => c !== playerCountry));
|
||||
const total = eligible.length;
|
||||
const minC = tuning.rbCoalitionMinCountries;
|
||||
const maxC = tuning.rbCoalitionMaxCountries;
|
||||
const playerMax = total >= minC * 2 ? Math.min(maxC, total - minC) : Math.min(maxC, total - 1);
|
||||
const playerMin = total >= minC * 2 ? Math.min(minC, playerMax) : 1;
|
||||
const playerCount = randomRangeInclusive(playerMin, playerMax);
|
||||
const remaining = total - playerCount;
|
||||
const enemyMax = Math.min(maxC, remaining);
|
||||
const enemyMin = Math.min(minC, enemyMax);
|
||||
const enemyCount = randomRangeInclusive(enemyMin, enemyMax);
|
||||
return {
|
||||
playerSide: [playerCountry, ...others.slice(0, playerCount - 1)],
|
||||
enemySide: others.slice(playerCount - 1, playerCount - 1 + enemyCount),
|
||||
symmetricTeams: false,
|
||||
};
|
||||
}
|
||||
|
||||
function buildMixedRealisticSides(
|
||||
eligible: readonly string[],
|
||||
playerCountry: string,
|
||||
tuning: BattleTuning,
|
||||
): TeamSides {
|
||||
if (eligible.length < 2 || randomInt(2) === 0) {
|
||||
return buildArcadeSides(eligible, playerCountry);
|
||||
}
|
||||
const total = eligible.length;
|
||||
const minCount = Math.min(tuning.rbCoalitionMinCountries, total);
|
||||
const maxCount = Math.min(tuning.rbCoalitionMaxCountries, total);
|
||||
const playerCount = randomRangeInclusive(minCount, maxCount);
|
||||
const enemyCount = randomRangeInclusive(minCount, maxCount);
|
||||
const others = shuffle(eligible.filter((c) => c !== playerCountry));
|
||||
const playerSide = [playerCountry, ...others.slice(0, playerCount - 1)];
|
||||
const shared = playerSide[randomInt(playerSide.length)]!;
|
||||
const enemyPool = shuffle(eligible.filter((c) => c !== shared));
|
||||
const enemySide = shuffle([shared, ...enemyPool.slice(0, enemyCount - 1)]);
|
||||
return {
|
||||
playerSide,
|
||||
enemySide,
|
||||
symmetricTeams: sameCountrySet(playerSide, enemySide),
|
||||
};
|
||||
}
|
||||
|
||||
function placeFirst(countries: readonly string[], first: string): string[] {
|
||||
return [first, ...countries.filter((c) => c !== first)];
|
||||
}
|
||||
|
||||
function sameCountrySet(a: readonly string[], b: readonly string[]): boolean {
|
||||
if (a.length !== b.length) return false;
|
||||
const setB = new Set(b);
|
||||
return a.every((item) => setB.has(item));
|
||||
}
|
||||
|
||||
function randomRangeInclusive(min: number, max: number): number {
|
||||
return max <= min ? min : min + randomInt(max - min + 1);
|
||||
}
|
||||
|
||||
function shuffle<T>(items: readonly T[]): T[] {
|
||||
const copy = [...items];
|
||||
for (let i = copy.length - 1; i > 0; i--) {
|
||||
const j = randomInt(i + 1);
|
||||
const tmp = copy[i]!;
|
||||
copy[i] = copy[j]!;
|
||||
copy[j] = tmp;
|
||||
}
|
||||
return copy;
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
/**
|
||||
* The debriefing table of a settled battle, in the shape of `stat_get_exp()` (aces.exe 0x1053b70,
|
||||
* which serializes the battle's SessionStatsNet; online the battle server fills it). The client's
|
||||
* settlement patch puts it in `debriefingResult.exp` in place of the empty local statistics.
|
||||
*
|
||||
* Root and every `aircrafts.<vehicle>`:
|
||||
* num<Row>:i wp<Row>:i exp<Row>:i tbl<Row>{ noBonusWp noBonusExp premAccWp premAccExp premModExp boosterWp boosterExp }
|
||||
* tblTotal{ ... } wpTotal:i expTotal:i sessionTime:r battleTime:r
|
||||
* Root only: result:i activity:r expFree:i expSkillBonusTotal:i expSkillBonusLevel:i
|
||||
* investUnitName<Type>:t expInvestUnit<Type>:i expInvestUnitTotal<Type>: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 { emptyRowRewards, type BattleRewards, type RewardRow, type 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;
|
||||
|
||||
/** Battle awards (streaks) of the battle, shown in the root-only row "Unlocks" (debriefingFull.nut). */
|
||||
export interface UnlockRewards {
|
||||
readonly count: number;
|
||||
readonly wp: number;
|
||||
readonly exp: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* `compensation`: the premium account's expense compensation, the root-only row
|
||||
* "ExpensesCompensation" (debriefingFull.nut).
|
||||
*/
|
||||
export function debriefingTable(name: string, rewards: BattleRewards, research: BattleRpResult, unlocks: UnlockRewards, compensation: number): BlkBlock {
|
||||
const root = emptyBlock(name);
|
||||
const rootRows = new Map<RewardRow, RowRewards>();
|
||||
for (const vehicle of rewards.vehicles) {
|
||||
for (const [row, amounts] of vehicle.rows) {
|
||||
const sum = rootRows.get(row) ?? emptyRowRewards();
|
||||
for (const key of Object.keys(sum) as (keyof RowRewards)[]) sum[key] += amounts[key];
|
||||
rootRows.set(row, sum);
|
||||
}
|
||||
}
|
||||
setParam(root, 'result', { type: 'int', value: rewards.win ? STATS_RESULT_SUCCESS : STATS_RESULT_FAIL });
|
||||
setParam(root, 'activity', { type: 'real', value: rewards.activity });
|
||||
setParam(root, 'sessionTime', { type: 'real', value: rewards.sessionTime });
|
||||
setParam(root, 'battleTime', { type: 'real', value: rewards.battleTime });
|
||||
if (unlocks.count > 0) {
|
||||
rootRows.set('Unlocks', { ...emptyRowRewards(), count: unlocks.count, noBonusWp: unlocks.wp, noBonusExp: unlocks.exp });
|
||||
}
|
||||
if (compensation > 0) rootRows.set('ExpensesCompensation', { ...emptyRowRewards(), count: 1, noBonusWp: compensation });
|
||||
writeRows(root, rootRows, rewards.wpTotal + unlocks.wp + compensation, rewards.expTotal + unlocks.exp);
|
||||
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 research.branches) {
|
||||
setParam(root, `investUnitName${branch.type}`, { type: 'string', value: branch.unit });
|
||||
setParam(root, `expInvestUnit${branch.type}`, { type: 'int', value: branch.invested });
|
||||
setParam(root, `expInvestUnitTotal${branch.type}`, { type: 'int', value: branch.total });
|
||||
}
|
||||
|
||||
const aircrafts = emptyBlock('aircrafts');
|
||||
for (const vehicle of rewards.vehicles) {
|
||||
const block = emptyBlock(vehicle.vehicle);
|
||||
setParam(block, 'sessionTime', { type: 'real', value: vehicle.sessionTime });
|
||||
setParam(block, 'battleTime', { type: 'real', value: vehicle.sessionTime });
|
||||
writeRows(block, vehicle.rows, vehicle.wpTotal, vehicle.expTotal);
|
||||
setParam(block, 'expSkillBonus', { type: 'int', value: vehicle.skillBonusExp });
|
||||
setParam(block, 'expSkillBonusTotal', { type: 'int', value: vehicle.skillBonusExp });
|
||||
// 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);
|
||||
return root;
|
||||
}
|
||||
|
||||
function writeRows(block: BlkBlock, rows: ReadonlyMap<RewardRow, RowRewards>, wpTotal: number, expTotal: number): void {
|
||||
const total: RowRewards = emptyRowRewards();
|
||||
for (const [row, amounts] of rows) {
|
||||
setParam(block, `num${row}`, { type: 'int', value: amounts.count });
|
||||
setParam(block, `wp${row}`, { type: 'int', value: amounts.noBonusWp + amounts.premAccWp + amounts.boosterWp });
|
||||
setParam(block, `exp${row}`, { type: 'int', value: amounts.noBonusExp + amounts.premAccExp + amounts.premModExp + amounts.boosterExp });
|
||||
block.blocks.push(rowTable(`tbl${row}`, amounts));
|
||||
for (const key of Object.keys(total) as (keyof RowRewards)[]) total[key] += amounts[key];
|
||||
}
|
||||
setParam(block, 'wpTotal', { type: 'int', value: wpTotal });
|
||||
setParam(block, 'expTotal', { type: 'int', value: expTotal });
|
||||
block.blocks.push(rowTable('tblTotal', total));
|
||||
}
|
||||
|
||||
function rowTable(name: string, amounts: RowRewards): BlkBlock {
|
||||
const table = emptyBlock(name);
|
||||
setParam(table, 'noBonusWp', { type: 'int', value: amounts.noBonusWp });
|
||||
setParam(table, 'noBonusExp', { type: 'int', value: amounts.noBonusExp });
|
||||
setParam(table, 'premAccWp', { type: 'int', value: amounts.premAccWp });
|
||||
setParam(table, 'premAccExp', { type: 'int', value: amounts.premAccExp });
|
||||
setParam(table, 'premModExp', { type: 'int', value: amounts.premModExp });
|
||||
setParam(table, 'boosterWp', { type: 'int', value: amounts.boosterWp });
|
||||
setParam(table, 'boosterExp', { type: 'int', value: amounts.boosterExp });
|
||||
return table;
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* Typed reader for `tuning/battle-economy.jsonc`: the mission score of each combat event and the
|
||||
* offline choices the game files do not carry (see the file for the source of every value).
|
||||
*/
|
||||
import { TuningError, type TuningReader } from '../tuning/tuning-reader.ts';
|
||||
|
||||
export const VICTIM_GROUPS = ['ground', 'air', 'naval', 'human'] as const;
|
||||
export type VictimGroup = (typeof VICTIM_GROUPS)[number];
|
||||
|
||||
export const SCORED_EVENTS = ['kill', 'assist', 'severeDamage', 'criticalHit', 'hit'] as const;
|
||||
export type ScoredEvent = (typeof SCORED_EVENTS)[number];
|
||||
|
||||
export interface BattleEconomyTuning {
|
||||
/** Destroyed-unit expClass -> victim group; classes not listed are "ground". */
|
||||
readonly victimGroups: ReadonlyMap<string, VictimGroup>;
|
||||
readonly eventScores: Readonly<Record<VictimGroup, Readonly<Record<ScoredEvent, number>>>>;
|
||||
readonly captureZoneScore: Readonly<Record<VictimGroup, number>>;
|
||||
readonly navalDamageScorePerPoint: number;
|
||||
readonly referenceScore: Readonly<Record<VictimGroup, number>>;
|
||||
readonly friendlyKillPenaltyMul: number;
|
||||
}
|
||||
|
||||
export function readBattleEconomyTuning(reader: TuningReader): BattleEconomyTuning {
|
||||
const groups = reader.object('victimGroups');
|
||||
const victimGroups = new Map<string, VictimGroup>();
|
||||
for (const group of groups.keys()) {
|
||||
if (!isVictimGroup(group) || group === 'ground') {
|
||||
throw new TuningError(`tuning file battle-economy.jsonc: victimGroups.${group} is not one of air, naval, human`);
|
||||
}
|
||||
for (const expClass of groups.stringList(group)) victimGroups.set(expClass, group);
|
||||
}
|
||||
const scores = reader.object('eventScores');
|
||||
const perGroup = (key: string, min: number): Record<VictimGroup, number> => {
|
||||
const table = reader.object(key);
|
||||
return Object.fromEntries(VICTIM_GROUPS.map((group) => [group, table.number(group, { min, max: 100000 })])) as Record<VictimGroup, number>;
|
||||
};
|
||||
return {
|
||||
victimGroups,
|
||||
eventScores: Object.fromEntries(VICTIM_GROUPS.map((group) => {
|
||||
const table = scores.object(group);
|
||||
return [group, Object.fromEntries(SCORED_EVENTS.map((event) => [event, table.number(event, { min: 0, max: 100000 })]))];
|
||||
})) as Record<VictimGroup, Record<ScoredEvent, number>>,
|
||||
captureZoneScore: perGroup('captureZoneScore', 0),
|
||||
navalDamageScorePerPoint: reader.number('navalDamageScorePerPoint', { min: 0, max: 100 }),
|
||||
referenceScore: perGroup('referenceScore', 1),
|
||||
friendlyKillPenaltyMul: reader.number('friendlyKillPenaltyMul', { min: 0, max: 100 }),
|
||||
};
|
||||
}
|
||||
|
||||
function isVictimGroup(value: string): value is VictimGroup {
|
||||
return (VICTIM_GROUPS as readonly string[]).includes(value);
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
/**
|
||||
* Prices the local player's combat events: the one place battle rewards are computed.
|
||||
*
|
||||
* The in-battle banner and the settlement use the same two steps, so what the banner shows is
|
||||
* what the settlement pays:
|
||||
* 1. baseReward(vehicle, event, victim group): Silver Lions and Research Points of the event
|
||||
* before the destroyed unit's class factor (sent to the client at launch, `bannerParams`);
|
||||
* 2. x class factor of the victim's expClass (warpoints.blk / rank.blk units{}), x aiKillK when
|
||||
* the victim is not a player, x damage points for naval damage.
|
||||
* The formula and the source of every factor are in tuning/battle-economy.jsonc.
|
||||
*/
|
||||
import type { BattleEconomyData, EconomyDifficulty, VehicleEconomy } from '../game-data/datasets/battle-economy.ts';
|
||||
import type { ModeDifficulty } from '../game-modes/catalogue/game-mode-declaration.ts';
|
||||
import { SCORED_EVENTS, VICTIM_GROUPS, type BattleEconomyTuning, type ScoredEvent, type VictimGroup } from './battle-economy-tuning.ts';
|
||||
|
||||
/** EXP_EVENT_* codes the LocalMP host reports (gui.vromfs.bin globalScripts/expEventConsts.nut). */
|
||||
export const ExpEvent = {
|
||||
CAPTURE_ZONE: 2,
|
||||
KILL: 5,
|
||||
KILL_GROUND: 6,
|
||||
ASSIST: 9,
|
||||
CRITICAL_HIT: 10,
|
||||
HIT: 13,
|
||||
UNIT_DAMAGE: 24,
|
||||
SEVERE_DAMAGE: 35,
|
||||
KILL_HUMAN: 39,
|
||||
} as const;
|
||||
|
||||
/** Debriefing rows (`stat_get_exp()` `num<Row>`/`wp<Row>`/`exp<Row>`, aces.exe 0x1053b70) an event lands in. */
|
||||
export type DebriefingRow =
|
||||
| 'AirKills' | 'GroundKills' | 'NavalKills' | 'HumanKills' | 'FriendlyKills'
|
||||
| 'Assist' | 'AirSevereDamage' | 'ShipSevereDamage' | 'Critical' | 'Hit'
|
||||
| 'Captures' | 'AwardDamage';
|
||||
|
||||
/** What the client reports for one combat event (patches/gui/battle/record-local-battle-awards). */
|
||||
export interface CombatEventFact {
|
||||
readonly code: number;
|
||||
readonly expClass: string;
|
||||
readonly victimIsPlayer: boolean;
|
||||
readonly friendly: boolean;
|
||||
readonly damage: number;
|
||||
}
|
||||
|
||||
export interface PricedEvent {
|
||||
readonly row: DebriefingRow;
|
||||
/** How much the row's counter grows: 1, or the damage points for AwardDamage. */
|
||||
readonly count: number;
|
||||
readonly wp: number;
|
||||
readonly exp: number;
|
||||
}
|
||||
|
||||
export interface RewardPair {
|
||||
readonly wp: number;
|
||||
readonly exp: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Launch-time parameters of the in-battle banner (`battle.awards` of the launch message):
|
||||
* vehicles.<name>["<code>:<group>"] = [wp, exp] before the class factor; capture uses the group
|
||||
* "own". The client multiplies by slClass/rpClass of the victim's expClass, by aiKillK for a
|
||||
* victim that is not a player, by the damage points for naval damage, and shows a friendly kill as
|
||||
* -wp x friendlyKillPenaltyMul.
|
||||
*/
|
||||
export interface BannerParams {
|
||||
readonly vehicles: Readonly<Record<string, Readonly<Record<string, readonly [number, number]>>>>;
|
||||
readonly groups: Readonly<Record<string, VictimGroup>>;
|
||||
readonly slClass: Readonly<Record<string, number>>;
|
||||
readonly rpClass: Readonly<Record<string, number>>;
|
||||
readonly aiKillK: number;
|
||||
readonly friendlyKillPenaltyMul: number;
|
||||
}
|
||||
|
||||
export interface RewardMultipliers {
|
||||
readonly silverLions: number;
|
||||
readonly researchPoints: number;
|
||||
}
|
||||
|
||||
export function economyDifficulty(difficulty: ModeDifficulty): EconomyDifficulty {
|
||||
return difficulty === 'arcade' ? 'arcade' : difficulty === 'realistic' ? 'historical' : 'simulation';
|
||||
}
|
||||
|
||||
export class BattleEconomy {
|
||||
readonly data: BattleEconomyData;
|
||||
readonly #tuning: BattleEconomyTuning;
|
||||
readonly #multipliers: RewardMultipliers;
|
||||
readonly #premiumVehicles: ReadonlySet<string>;
|
||||
|
||||
/** `premiumVehicles`: vehicles the client counts as special (isUnitSpecial: costGold > 0 or premPackAir). */
|
||||
constructor(
|
||||
data: BattleEconomyData,
|
||||
tuning: BattleEconomyTuning,
|
||||
multipliers: RewardMultipliers,
|
||||
premiumVehicles: ReadonlySet<string>,
|
||||
) {
|
||||
this.data = data;
|
||||
this.#tuning = tuning;
|
||||
this.#multipliers = multipliers;
|
||||
this.#premiumVehicles = premiumVehicles;
|
||||
}
|
||||
|
||||
/** Premium vehicles earn the talisman research bonus without a talisman (scripts/airinfo.nut hasTalisman). */
|
||||
isPremiumVehicle(name: string): boolean {
|
||||
return this.#premiumVehicles.has(name);
|
||||
}
|
||||
|
||||
get multipliers(): RewardMultipliers {
|
||||
return this.#multipliers;
|
||||
}
|
||||
|
||||
vehicle(name: string): VehicleEconomy | undefined {
|
||||
return this.data.vehicles[name];
|
||||
}
|
||||
|
||||
victimGroup(expClass: string): VictimGroup {
|
||||
return this.#tuning.victimGroups.get(expClass) ?? 'ground';
|
||||
}
|
||||
|
||||
/** Reward of one event before the victim's class factor; undefined for an event that pays nothing. */
|
||||
baseReward(vehicle: string, difficulty: EconomyDifficulty, code: number, group: VictimGroup): RewardPair | undefined {
|
||||
const economy = this.vehicle(vehicle);
|
||||
if (!economy) return undefined;
|
||||
const score = this.#score(code, group);
|
||||
if (score === undefined) return undefined;
|
||||
const reference = this.#tuning.referenceScore[code === ExpEvent.UNIT_DAMAGE ? 'naval' : group];
|
||||
return {
|
||||
wp: this.data.killSilverLions * economy.rewardMul[difficulty] * (score / reference) * this.#multipliers.silverLions,
|
||||
exp: score * economy.expMul * this.#multipliers.researchPoints,
|
||||
};
|
||||
}
|
||||
|
||||
price(vehicle: string, difficulty: EconomyDifficulty, fact: CombatEventFact): PricedEvent | undefined {
|
||||
const economy = this.vehicle(vehicle);
|
||||
if (!economy) return undefined;
|
||||
const isCapture = fact.code === ExpEvent.CAPTURE_ZONE;
|
||||
const group = isCapture ? this.victimGroup(economy.unitClass) : this.victimGroup(fact.expClass);
|
||||
const row = debriefingRow(fact, group);
|
||||
const base = this.baseReward(vehicle, difficulty, fact.code, group);
|
||||
if (!row || !base) return undefined;
|
||||
const count = fact.code === ExpEvent.UNIT_DAMAGE ? Math.max(0, Math.trunc(fact.damage)) : 1;
|
||||
const ai = isCapture || fact.victimIsPlayer ? 1 : this.data.aiKillK;
|
||||
const slClass = isCapture ? 1 : this.data.silverLionsClassFactors[fact.expClass] ?? 1;
|
||||
const rpClass = isCapture ? 1 : this.data.researchClassFactors[fact.expClass] ?? 1;
|
||||
if (fact.friendly) {
|
||||
return { row: 'FriendlyKills', count: 1, wp: -Math.round(base.wp * slClass * ai * this.#tuning.friendlyKillPenaltyMul), exp: 0 };
|
||||
}
|
||||
return {
|
||||
row,
|
||||
count,
|
||||
wp: Math.round(base.wp * slClass * ai * count),
|
||||
exp: Math.round(base.exp * rpClass * ai * count),
|
||||
};
|
||||
}
|
||||
|
||||
bannerParams(vehicles: Iterable<string>, difficulty: EconomyDifficulty): BannerParams {
|
||||
const table: Record<string, Record<string, [number, number]>> = {};
|
||||
for (const name of vehicles) {
|
||||
const economy = this.vehicle(name);
|
||||
if (!economy || table[name]) continue;
|
||||
const entries: Record<string, [number, number]> = {};
|
||||
for (const code of Object.values(ExpEvent)) {
|
||||
const groups: readonly (VictimGroup | 'own')[] = code === ExpEvent.CAPTURE_ZONE ? ['own'] : ['ground', 'air', 'naval', 'human'];
|
||||
for (const group of groups) {
|
||||
const priceGroup = group === 'own' ? this.victimGroup(economy.unitClass) : group;
|
||||
const base = this.baseReward(name, difficulty, code, priceGroup);
|
||||
if (base) entries[`${code}:${group}`] = [base.wp, base.exp];
|
||||
}
|
||||
}
|
||||
table[name] = entries;
|
||||
}
|
||||
return {
|
||||
vehicles: table,
|
||||
groups: Object.fromEntries(this.#tuning.victimGroups),
|
||||
slClass: this.data.silverLionsClassFactors,
|
||||
rpClass: this.data.researchClassFactors,
|
||||
aiKillK: this.data.aiKillK,
|
||||
friendlyKillPenaltyMul: this.#tuning.friendlyKillPenaltyMul,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The scoreboard score of each combat event, for the mission settings block customScoreParams
|
||||
* that the native LocalMP bridge reads (native/wto-net/src/local_mp_scores.c lists the keys):
|
||||
* the official mission scores of tuning/battle-economy.jsonc, and aiKillK for victims that are
|
||||
* not players, as in the rewards.
|
||||
*/
|
||||
missionScores(): Readonly<Record<string, number>> {
|
||||
const scores: Record<string, number> = {};
|
||||
for (const group of VICTIM_GROUPS) {
|
||||
for (const event of SCORED_EVENTS) scores[`wtoScore_${event}_${group}`] = this.#tuning.eventScores[group][event];
|
||||
scores[`wtoScore_capture_${group}`] = this.#tuning.captureZoneScore[group];
|
||||
}
|
||||
scores.wtoScore_damagePerPoint = this.#tuning.navalDamageScorePerPoint;
|
||||
scores.wtoScore_aiMul = this.data.aiKillK;
|
||||
return scores;
|
||||
}
|
||||
|
||||
#score(code: number, group: VictimGroup): number | undefined {
|
||||
const scored = (event: ScoredEvent): number => this.#tuning.eventScores[group][event];
|
||||
switch (code) {
|
||||
case ExpEvent.KILL:
|
||||
case ExpEvent.KILL_GROUND:
|
||||
case ExpEvent.KILL_HUMAN: return scored('kill');
|
||||
case ExpEvent.ASSIST: return scored('assist');
|
||||
case ExpEvent.CRITICAL_HIT: return scored('criticalHit');
|
||||
case ExpEvent.HIT: return scored('hit');
|
||||
case ExpEvent.SEVERE_DAMAGE: return scored('severeDamage');
|
||||
case ExpEvent.CAPTURE_ZONE: return this.#tuning.captureZoneScore[group];
|
||||
case ExpEvent.UNIT_DAMAGE: return this.#tuning.navalDamageScorePerPoint;
|
||||
default: return undefined;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function debriefingRow(fact: CombatEventFact, group: VictimGroup): DebriefingRow | undefined {
|
||||
switch (fact.code) {
|
||||
case ExpEvent.KILL:
|
||||
case ExpEvent.KILL_GROUND:
|
||||
case ExpEvent.KILL_HUMAN:
|
||||
if (fact.friendly) return 'FriendlyKills';
|
||||
return group === 'air' ? 'AirKills' : group === 'naval' ? 'NavalKills' : group === 'human' ? 'HumanKills' : 'GroundKills';
|
||||
case ExpEvent.ASSIST: return 'Assist';
|
||||
case ExpEvent.CRITICAL_HIT: return 'Critical';
|
||||
case ExpEvent.HIT: return 'Hit';
|
||||
case ExpEvent.SEVERE_DAMAGE: return group === 'naval' ? 'ShipSevereDamage' : 'AirSevereDamage';
|
||||
case ExpEvent.CAPTURE_ZONE: return 'Captures';
|
||||
case ExpEvent.UNIT_DAMAGE: return 'AwardDamage';
|
||||
default: return undefined;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
/**
|
||||
* The extra vehicles a battle adds to the player's lineup (online the battle server adds them):
|
||||
*
|
||||
* - Support plane (the nuclear carrier): gameplay.blk missionSupportPlane, keyed by the game mode
|
||||
* name; the preset whose rankRange holds the session's top rank, the unit of the player's
|
||||
* country, with its fixed weapon and its spawnScoreToUse as a fixed spawn cost.
|
||||
* - Strike UCAV: wpcost.blk ucav_*_killstreak of the player's country. The game files have no rule
|
||||
* for when it is offered or what it costs; both are in tuning/battle.jsonc (the cost as seen in
|
||||
* the live game, the offer rule offline design).
|
||||
* - Extra vehicles from gameplay.blk RandomSpawnUnits, keyed by the event economic name: one
|
||||
* vehicle per group of the player's country (ground RB: a tank and an SPAA), drawn at launch and
|
||||
* shown in the lineup as a plain vehicle, as the live game does (a 12.7 US lineup received an
|
||||
* M1A1 12.0 and an ADATS 12.0, no dice; screenshot of the live game). Rules from the official
|
||||
* changelog ("Line of Contact", 2025-12-16): offered to lineups of BR 9.3 and higher (the
|
||||
* groups' minPlayerMRank), with no condition on what the lineup holds; the vehicle depends on the
|
||||
* player's BR and the session's BR and is never of the session's top BR; when no vehicle fits,
|
||||
* lower BR vehicles are used. Worked examples there: in a 9.7-10.7 session a player at 10.7 gets
|
||||
* 9.7-10.3 and a player at 9.7 gets 9.3-10.0. The window formula is not published;
|
||||
* `randomWindow` is fitted to those examples with the group's own parameters (inferred). Their
|
||||
* spawn cost comes from the stock spawn score formula (the live screenshot's 110 and 80 match it).
|
||||
*/
|
||||
import { randomInt } from 'node:crypto';
|
||||
import type {
|
||||
BattleSpawnRulesData,
|
||||
RandomSpawnGroup,
|
||||
RandomSpawnUnit,
|
||||
SupportPlanePreset,
|
||||
} from '../game-data/datasets/battle-spawn-rules.ts';
|
||||
import type { CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.ts';
|
||||
import type { GameModeDeclaration } from '../game-modes/catalogue/game-mode-declaration.ts';
|
||||
import type { BattleTuning } from './battle-tuning.ts';
|
||||
import { vehicleMrank } from './battle-ranks.ts';
|
||||
|
||||
/** The LocalMP host tracks crew slots in a 32-bit mask (native LMP_MP_OFF_BROKEN_SLOTS_MASK). */
|
||||
const MAX_BATTLE_CREW_SLOTS = 32;
|
||||
|
||||
export interface ExtraBattleSlot {
|
||||
readonly unitName: string;
|
||||
/** Fixed spawn cost (mission customSpawnScore.persistent_costs); absent = the stock formula. */
|
||||
readonly persistentCost?: number;
|
||||
/** Every modification of the unit is enabled. */
|
||||
readonly allModifications: boolean;
|
||||
/** The modifications enabled when not `allModifications`; the unit is otherwise stock. */
|
||||
readonly modifications: readonly string[];
|
||||
readonly forceWeapon?: string;
|
||||
/** The RandomSpawnUnits group the vehicle was drawn from. */
|
||||
readonly groupName?: string;
|
||||
}
|
||||
|
||||
export interface ExtraBattleSlotsInput {
|
||||
readonly country: string;
|
||||
readonly slotVehicles: readonly string[];
|
||||
readonly declaration: GameModeDeclaration;
|
||||
/** The lineup's mrank the session was matched on. */
|
||||
readonly playerMrank: number;
|
||||
readonly sessionMaxMrank: number;
|
||||
readonly vehiclesByName: ReadonlyMap<string, CatalogueVehicle>;
|
||||
readonly rules: BattleSpawnRulesData;
|
||||
readonly tuning: Pick<BattleTuning, 'strikeUcavModes' | 'strikeUcavSessionMrankAllowance' | 'strikeUcavSpawnScore'>;
|
||||
}
|
||||
|
||||
export function selectExtraBattleSlots(input: ExtraBattleSlotsInput): readonly ExtraBattleSlot[] {
|
||||
const room = MAX_BATTLE_CREW_SLOTS - input.slotVehicles.length;
|
||||
if (input.declaration.multiSlot === false || room <= 0) return [];
|
||||
|
||||
const supportSlots: ExtraBattleSlot[] = [];
|
||||
const supportPlane = supportPlaneSlot(input);
|
||||
if (supportPlane) supportSlots.push(supportPlane);
|
||||
const ucav = strikeUcavSlot(input);
|
||||
if (ucav) supportSlots.push(ucav);
|
||||
|
||||
// Keep room for fixed support vehicles while displaying random vehicle groups first.
|
||||
const slots: ExtraBattleSlot[] = [];
|
||||
for (const group of input.rules.randomSpawnUnits[input.declaration.economicName]?.[input.country] ?? []) {
|
||||
if (slots.length + supportSlots.length >= room) break;
|
||||
const options = randomGroupOptions(group, input);
|
||||
if (options.length === 0) continue;
|
||||
const chosen = options[randomInt(options.length)]!;
|
||||
slots.push({
|
||||
unitName: chosen.unitName,
|
||||
allModifications: false,
|
||||
modifications: chosen.addModifications,
|
||||
...(chosen.forceWeapon ? { forceWeapon: chosen.forceWeapon } : {}),
|
||||
groupName: group.name,
|
||||
});
|
||||
}
|
||||
|
||||
return [...slots, ...supportSlots].slice(0, room);
|
||||
}
|
||||
|
||||
function supportPlaneSlot(input: ExtraBattleSlotsInput): ExtraBattleSlot | undefined {
|
||||
const presets: readonly SupportPlanePreset[] = input.rules.supportPlanes[input.declaration.name] ?? [];
|
||||
const preset = presets.find((p) => input.sessionMaxMrank >= p.minMrank && input.sessionMaxMrank <= p.maxMrank);
|
||||
const unit = preset?.units[input.country];
|
||||
if (!preset || !unit) return undefined;
|
||||
return {
|
||||
unitName: unit.unitName,
|
||||
persistentCost: preset.spawnScoreToUse,
|
||||
allModifications: true,
|
||||
modifications: [],
|
||||
forceWeapon: unit.weapon,
|
||||
};
|
||||
}
|
||||
|
||||
function strikeUcavSlot(input: ExtraBattleSlotsInput): ExtraBattleSlot | undefined {
|
||||
if (!input.tuning.strikeUcavModes.includes(input.declaration.name)) return undefined;
|
||||
const ucav = input.rules.strikeUcavs.find((entry) => entry.country === input.country);
|
||||
const vehicle = ucav && input.vehiclesByName.get(ucav.unitName);
|
||||
if (!ucav || !vehicle) return undefined;
|
||||
const ucavMrank = vehicleMrank(vehicle, input.declaration.difficulty, input.declaration.requiredClass);
|
||||
if (input.sessionMaxMrank < ucavMrank - input.tuning.strikeUcavSessionMrankAllowance) return undefined;
|
||||
// Offline design: the UCAV comes fully upgraded and keeps its weapon choice (the game files force no preset).
|
||||
return {
|
||||
unitName: ucav.unitName,
|
||||
persistentCost: input.tuning.strikeUcavSpawnScore,
|
||||
allModifications: true,
|
||||
modifications: [],
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The options of one random group: the group's vehicles inside `randomWindow`, or, when none fits,
|
||||
* those of the highest rank below it. Vehicles already in the lineup are left out (offline
|
||||
* design: the lineup does not hold the same vehicle twice).
|
||||
*/
|
||||
function randomGroupOptions(group: RandomSpawnGroup, input: ExtraBattleSlotsInput): RandomSpawnUnit[] {
|
||||
if (input.playerMrank < group.minPlayerMrank) return [];
|
||||
const { low, high } = randomWindow(group, input.playerMrank, input.sessionMaxMrank);
|
||||
const lineup = new Set(input.slotVehicles);
|
||||
const ranked = group.units.flatMap((unit) => {
|
||||
const vehicle = input.vehiclesByName.get(unit.unitName);
|
||||
if (!vehicle || lineup.has(unit.unitName)) return [];
|
||||
const mrank = vehicleMrank(vehicle, input.declaration.difficulty, input.declaration.requiredClass);
|
||||
return mrank <= high ? [{ unit, mrank }] : [];
|
||||
});
|
||||
const inWindow = ranked.filter((entry) => entry.mrank >= low);
|
||||
if (inWindow.length > 0) return inWindow.map((entry) => entry.unit);
|
||||
const best = Math.max(...ranked.map((entry) => entry.mrank));
|
||||
return ranked.filter((entry) => entry.mrank === best).map((entry) => entry.unit);
|
||||
}
|
||||
|
||||
/**
|
||||
* Inferred window (the formula is not published): the top option is the player's rank, raised to
|
||||
* at least `maxDiffBetweenTopUnitAndSessionRank` below the session's top rank and capped one rank
|
||||
* below it; the window spans `mRanksCount` ranks under the top option. With the stock values
|
||||
* (2 and 2) this gives both official examples: session 10.7 (mrank 29), player 10.7 (29) ->
|
||||
* mranks 26-28 = BR 9.7-10.3; player 9.7 (26) -> mranks 25-27 = BR 9.3-10.0.
|
||||
*/
|
||||
function randomWindow(group: RandomSpawnGroup, playerMrank: number, sessionMaxMrank: number) {
|
||||
const high = Math.min(Math.max(playerMrank, sessionMaxMrank - group.maxDiffBetweenTopUnitAndSessionRank), sessionMaxMrank - 1);
|
||||
return { low: Math.max(0, high - group.mranksCount), high };
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
/**
|
||||
* The player's boosters and wager in a battle's settlement, on the profile side: which are active
|
||||
* (profile/profile-items.ts), what the battle used of them and the user logs the client shows.
|
||||
*
|
||||
* Boosters: items/<uid>/progress:i is the stop condition's progress (client reader aces.exe
|
||||
* 2.61.0.37 0x946360; the scripts read invBlk.progress, itemBooster.nut). A used-up booster is
|
||||
* removed with an EULT_REMOVE_ITEM log (reason "consumed", which the client words "Item ... has
|
||||
* been consumed"; inferred that the server uses it for boosters).
|
||||
* Wager: items/<uid>/numWins:i numBattles:i wager:i lastWinRoomId:i64 (reader 0x969c40). Every
|
||||
* counted battle logs EULT_CHARD_AWARD { rewardType id uid numWins numFails [wpEarned goldEarned] }
|
||||
* in the battle's room (debriefingFull.nut getDebriefingActiveWager reads it; userlogData.nut
|
||||
* shows it as a popup); "name" = "<rewardType>Desc", the lang keys userlog/WagerWinDesc ... (inferred).
|
||||
* An ended wager is removed with an EULT_REMOVE_ITEM log { itemType="wager" wpEarned goldEarned }
|
||||
* (userlogviewdata.nut shows its "Award").
|
||||
*/
|
||||
import { setParam, type BlkBlock, type BlkParam } from '@wto/blk';
|
||||
import type { WagerDefinition } from '../game-data/datasets/item-catalogue.ts';
|
||||
import type { ItemCatalogue } from '../items/item-catalogue.ts';
|
||||
import { addGoldenEagles, addSilverLions } from '../profile/profile-currency.ts';
|
||||
import { activeUids, itemRecord, ownedItem, removeItem } from '../profile/profile-items.ts';
|
||||
import { addFreeResearchPoints } from '../profile/profile-research-points.ts';
|
||||
import { appendUserLog, EULT_CHARD_AWARD, EULT_REMOVE_ITEM } from '../profile/profile-trophies-log.ts';
|
||||
import { intField } from '../profile/blk-fields.ts';
|
||||
import type { ActiveBooster, BoosterUse } from './battle-boosters.ts';
|
||||
import type { WagerBattleOutcome, WagerState } from './battle-wager.ts';
|
||||
|
||||
export interface LogTarget {
|
||||
readonly timeSec: number;
|
||||
readonly roomId: bigint;
|
||||
}
|
||||
|
||||
export function activeBattleBoosters(profile: BlkBlock, catalogue: ItemCatalogue): ActiveBooster[] {
|
||||
return activeUids(profile, 'itemActiveBoosters').flatMap((uid): ActiveBooster[] => {
|
||||
const owned = ownedItem(profile, uid);
|
||||
const booster = owned && catalogue.item(owned.id)?.booster;
|
||||
const record = itemRecord(profile, uid);
|
||||
if (!owned || !booster || !record) return [];
|
||||
return [{ uid, id: owned.id, booster, progress: intField(record, 'progress') }];
|
||||
});
|
||||
}
|
||||
|
||||
export function recordBoosterUses(profile: BlkBlock, uses: readonly BoosterUse[], log: LogTarget): void {
|
||||
for (const { booster, progress, finished } of uses) {
|
||||
if (finished) {
|
||||
removeItem(profile, booster.uid);
|
||||
appendUserLog(profile, { type: EULT_REMOVE_ITEM, timeSec: log.timeSec, roomId: log.roomId, bodyParams: [
|
||||
str('id', booster.id), str('uid', booster.uid), str('itemType', 'rateBooster'), str('reason', 'consumed'),
|
||||
] });
|
||||
} else {
|
||||
const record = itemRecord(profile, booster.uid);
|
||||
if (record) setParam(record, 'progress', { type: 'int', value: progress });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export interface ActiveWager {
|
||||
readonly uid: string;
|
||||
readonly id: string;
|
||||
readonly wager: WagerDefinition;
|
||||
readonly state: WagerState;
|
||||
}
|
||||
|
||||
export function activeWager(profile: BlkBlock, catalogue: ItemCatalogue): ActiveWager | undefined {
|
||||
const uid = activeUids(profile, 'itemActiveWagers')[0];
|
||||
const owned = uid === undefined ? undefined : ownedItem(profile, uid);
|
||||
const wager = owned && catalogue.item(owned.id)?.wager;
|
||||
const record = uid === undefined ? undefined : itemRecord(profile, uid);
|
||||
if (!uid || !owned || !wager || !record) return undefined;
|
||||
return {
|
||||
uid,
|
||||
id: owned.id,
|
||||
wager,
|
||||
state: { stake: intField(record, 'wager'), numWins: intField(record, 'numWins'), numBattles: intField(record, 'numBattles') },
|
||||
};
|
||||
}
|
||||
|
||||
/** Writes the battle's wager outcome, pays an ended wager's reward and logs it. */
|
||||
export function recordWagerBattle(profile: BlkBlock, wager: ActiveWager, outcome: WagerBattleOutcome, log: LogTarget): void {
|
||||
const { reward } = outcome;
|
||||
const earned: BlkParam[] = [
|
||||
...(reward.wp ? [int('wpEarned', reward.wp)] : []),
|
||||
...(reward.gold ? [int('goldEarned', reward.gold)] : []),
|
||||
];
|
||||
appendUserLog(profile, { type: EULT_CHARD_AWARD, timeSec: log.timeSec, roomId: log.roomId, bodyParams: [
|
||||
str('rewardType', outcome.result), str('name', `${outcome.result}Desc`), str('id', wager.id), str('uid', wager.uid),
|
||||
int('numWins', outcome.numWins), int('numFails', outcome.numFails), ...earned,
|
||||
] });
|
||||
if (!outcome.ended) {
|
||||
const record = itemRecord(profile, wager.uid);
|
||||
if (!record) return;
|
||||
setParam(record, 'numWins', { type: 'int', value: outcome.numWins });
|
||||
setParam(record, 'numBattles', { type: 'int', value: outcome.numBattles });
|
||||
if (outcome.numWins > wager.state.numWins) setParam(record, 'lastWinRoomId', { type: 'int64', value: log.roomId });
|
||||
return;
|
||||
}
|
||||
if (reward.wp) addSilverLions(profile, reward.wp);
|
||||
if (reward.gold) addGoldenEagles(profile, reward.gold);
|
||||
if (reward.freeRp) addFreeResearchPoints(profile, reward.freeRp);
|
||||
// rpRewardParams: no 2.61.0.37 wager has it, and where such points would go is not known.
|
||||
removeItem(profile, wager.uid);
|
||||
appendUserLog(profile, { type: EULT_REMOVE_ITEM, timeSec: log.timeSec, roomId: log.roomId, bodyParams: [
|
||||
str('id', wager.id), str('uid', wager.uid), str('itemType', 'wager'), str('reason', 'consumed'), ...earned,
|
||||
] });
|
||||
}
|
||||
|
||||
function str(name: string, value: string): BlkParam {
|
||||
return { name, value: { type: 'string', value } };
|
||||
}
|
||||
|
||||
function int(name: string, value: number): BlkParam {
|
||||
return { name, value: { type: 'int', value } };
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* What the local player's client reports while a LocalMP battle runs (matching request
|
||||
* `wto_battle.fact`, matching/battle-live-requests.ts), kept to announce battle awards the moment
|
||||
* they are earned, as the battle server does online. The settlement does not use it: it settles
|
||||
* the full report the client sends after the battle (battle-report.ts), so a lost live message
|
||||
* only costs a banner.
|
||||
*/
|
||||
import type { ReportedCombatEvent, BattleLife, FeedKill } from './battle-report.ts';
|
||||
|
||||
export interface LiveBattleLog {
|
||||
readonly events: ReportedCombatEvent[];
|
||||
readonly lives: BattleLife[];
|
||||
readonly feed: FeedKill[];
|
||||
readonly nuclearStrikes: number[];
|
||||
/** Keys of the awards already announced (battle-streaks.ts AwardedStreak.key). */
|
||||
readonly announced: Set<string>;
|
||||
}
|
||||
|
||||
export class BattleLiveLogs {
|
||||
readonly #logs = new Map<string, LiveBattleLog>();
|
||||
readonly #maxRetained: number;
|
||||
|
||||
constructor(maxRetained: number) {
|
||||
this.#maxRetained = Math.max(1, maxRetained);
|
||||
}
|
||||
|
||||
of(sessionId: string): LiveBattleLog {
|
||||
let log = this.#logs.get(sessionId);
|
||||
if (!log) {
|
||||
log = { events: [], lives: [], feed: [], nuclearStrikes: [], announced: new Set() };
|
||||
this.#logs.set(sessionId, log);
|
||||
while (this.#logs.size > this.#maxRetained) this.#logs.delete(this.#logs.keys().next().value!);
|
||||
}
|
||||
return log;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,302 @@
|
||||
/**
|
||||
* Pure local-battle matchmaking rules (`match.enqueue`):
|
||||
* validates the chosen PvP mode and country, computes the player's lineup BR, selects a
|
||||
* two-sided multiplayer mission honoring banned/disliked map preferences, pairs AB/RB/SB
|
||||
* nation coalitions, builds the `customBots` pool and extra battle slots, and records a
|
||||
* `BattleSession`.
|
||||
*/
|
||||
import { randomInt } from 'node:crypto';
|
||||
import type { BattleSpawnRulesData } from '../game-data/datasets/battle-spawn-rules.ts';
|
||||
import type { MissionHeader } from '../game-data/datasets/multiplayer-missions.ts';
|
||||
import type { CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.ts';
|
||||
import type { GameModes, OfferedGameMode } from '../game-modes/game-modes.ts';
|
||||
import { MISSION_DIFFICULTY } from '../game-modes/mode-definition.ts';
|
||||
import { serverTimeNow, serverTimeToUnixSeconds } from '../profile/server-time.ts';
|
||||
import { selectBattleCoalitions, type CoalitionPairing } from './battle-coalitions.ts';
|
||||
import { selectExtraBattleSlots, type ExtraBattleSlot } from './battle-extra-slots.ts';
|
||||
import {
|
||||
lineupMrank,
|
||||
selectCustomBots,
|
||||
unitClassOfExpClass,
|
||||
vehicleMrank,
|
||||
type CustomBotsPool,
|
||||
} from './battle-ranks.ts';
|
||||
import type { BattleSessionStore } from './battle-session-store.ts';
|
||||
import { battleSpawnScore, type BattleSpawnScore } from './battle-spawn-score.ts';
|
||||
import type { BattleTuning } from './battle-tuning.ts';
|
||||
|
||||
export interface EnqueueBattleInput {
|
||||
readonly userId: string;
|
||||
readonly mode: OfferedGameMode;
|
||||
readonly modes?: readonly OfferedGameMode[];
|
||||
readonly country: string;
|
||||
readonly slotVehicles: readonly string[];
|
||||
readonly selectedSlotVehicle?: string;
|
||||
readonly bannedMissions: ReadonlySet<string>;
|
||||
readonly dislikedMissions: ReadonlySet<string>;
|
||||
}
|
||||
|
||||
export interface BattleLaunchPlan {
|
||||
readonly sessionId: string;
|
||||
readonly modeId: number;
|
||||
readonly modeName: string;
|
||||
readonly economicName: string;
|
||||
readonly missionName: string;
|
||||
/** The mission as the game describes it, including the parameters copied into the mission settings. */
|
||||
readonly mission: MissionHeader;
|
||||
readonly missionFile: string;
|
||||
readonly missionType: string;
|
||||
readonly level?: string;
|
||||
readonly environment?: string;
|
||||
readonly weather?: string;
|
||||
readonly difficulty: string;
|
||||
readonly country: string;
|
||||
readonly playerTeam: 1 | 2;
|
||||
readonly countryAllies: string;
|
||||
readonly countryAxis: string;
|
||||
readonly countriesAllies: readonly string[];
|
||||
readonly countriesAxis: readonly string[];
|
||||
readonly symmetricTeams: boolean;
|
||||
readonly minMrank: number;
|
||||
readonly maxMrank: number;
|
||||
readonly maxPlayers: number;
|
||||
readonly maxBots: number;
|
||||
readonly tankBotRespawns: number;
|
||||
readonly airBotRespawns: number;
|
||||
readonly useTankBots: boolean;
|
||||
readonly useShipBots: boolean;
|
||||
readonly useSpawnScore: boolean;
|
||||
readonly spawnScore?: BattleSpawnScore;
|
||||
readonly customBots: CustomBotsPool;
|
||||
readonly extraBattleSlots: readonly ExtraBattleSlot[];
|
||||
}
|
||||
|
||||
export type MatchmakeOutcome =
|
||||
| { readonly ok: true; readonly launch: BattleLaunchPlan }
|
||||
| { readonly ok: false; readonly error: string };
|
||||
|
||||
export class BattleMatchmaker {
|
||||
readonly #gameModes: GameModes;
|
||||
readonly #vehicles: readonly CatalogueVehicle[];
|
||||
readonly #vehiclesByName: ReadonlyMap<string, CatalogueVehicle>;
|
||||
readonly #sessions: BattleSessionStore;
|
||||
readonly #tuning: BattleTuning;
|
||||
readonly #spawnRules: BattleSpawnRulesData;
|
||||
|
||||
constructor(
|
||||
gameModes: GameModes,
|
||||
vehicles: readonly CatalogueVehicle[],
|
||||
sessions: BattleSessionStore,
|
||||
tuning: BattleTuning,
|
||||
spawnRules: BattleSpawnRulesData,
|
||||
) {
|
||||
this.#gameModes = gameModes;
|
||||
this.#vehicles = vehicles;
|
||||
this.#vehiclesByName = new Map(vehicles.map((vehicle) => [vehicle.name, vehicle]));
|
||||
this.#sessions = sessions;
|
||||
this.#tuning = tuning;
|
||||
this.#spawnRules = spawnRules;
|
||||
}
|
||||
|
||||
enqueue(input: EnqueueBattleInput): MatchmakeOutcome {
|
||||
const knownCountries = this.#gameModes.countries();
|
||||
if (!knownCountries.includes(input.country)) return { ok: false, error: 'BAD_PARAMS' };
|
||||
|
||||
const candidates = input.modes && input.modes.length > 0 ? input.modes : [input.mode];
|
||||
const chosenMode = this.#pickQueuedMode(candidates, input.slotVehicles, input.selectedSlotVehicle);
|
||||
if (!chosenMode) return { ok: false, error: 'PVE_NOT_SUPPORTED' };
|
||||
|
||||
const { declaration } = chosenMode;
|
||||
const activeVehicles = activeVehiclesForMode(declaration, input.slotVehicles, input.selectedSlotVehicle, this.#vehiclesByName);
|
||||
const playerMrank = lineupMrank(
|
||||
activeVehicles, this.#vehiclesByName, declaration.difficulty, declaration.requiredClass, declaration.allowedClasses,
|
||||
);
|
||||
const minMrank = Math.max(declaration.minQueueMrank ?? 0, playerMrank - this.#tuning.brSpreadMrank);
|
||||
const maxMrank = Math.max(minMrank, playerMrank + this.#tuning.brSpreadMrank);
|
||||
const mission = pickMission(twoSidedMissionsOf(chosenMode), input.bannedMissions, input.dislikedMissions);
|
||||
const coalitions = selectBattleCoalitions({
|
||||
vehicles: this.#vehicles,
|
||||
knownCountries,
|
||||
playerCountry: input.country,
|
||||
difficulty: declaration.difficulty,
|
||||
requiredClass: declaration.requiredClass,
|
||||
playerMrank,
|
||||
minMrank,
|
||||
maxMrank,
|
||||
tuning: this.#tuning,
|
||||
});
|
||||
const customBots = selectCustomBots(this.#vehicles, {
|
||||
difficulty: declaration.difficulty,
|
||||
requiredClass: declaration.requiredClass,
|
||||
allowedClasses: declaration.allowedClasses,
|
||||
countries: [...coalitions.countriesAllies, ...coalitions.countriesAxis],
|
||||
centerMrank: playerMrank,
|
||||
minMrank,
|
||||
maxMrank,
|
||||
limitPerType: this.#tuning.botPoolLimitPerType,
|
||||
});
|
||||
return {
|
||||
ok: true,
|
||||
launch: this.#buildLaunchPlan(input, chosenMode, mission, coalitions, playerMrank, minMrank, maxMrank, customBots),
|
||||
};
|
||||
}
|
||||
|
||||
#pickQueuedMode(
|
||||
candidates: readonly OfferedGameMode[],
|
||||
slotVehicles: readonly string[],
|
||||
selectedSlotVehicle: string | undefined,
|
||||
): OfferedGameMode | undefined {
|
||||
const pvpModes = candidates.filter(
|
||||
(mode) => mode.declaration.displayType !== 'pve_battle' && twoSidedMissionsOf(mode).length > 0,
|
||||
);
|
||||
if (pvpModes.length === 0) return undefined;
|
||||
const eligible = pvpModes.filter((mode) =>
|
||||
isModeEligibleForLineup(mode.declaration, slotVehicles, selectedSlotVehicle, this.#vehiclesByName));
|
||||
const pool = eligible.length > 0 ? eligible : pvpModes.filter((mode) => !mode.declaration.tag);
|
||||
if (pool.length === 0) return pvpModes[0];
|
||||
const classics = pool.filter((mode) => !mode.declaration.tag);
|
||||
const subModes = pool.filter((mode) => Boolean(mode.declaration.tag));
|
||||
if (subModes.length > 0 && classics.length > 0) {
|
||||
const useSubMode = randomInt(1_000_000) < Math.round(this.#tuning.subModeChance * 1_000_000);
|
||||
const bucket = useSubMode ? subModes : classics;
|
||||
return bucket[randomInt(bucket.length)];
|
||||
}
|
||||
return pool[randomInt(pool.length)];
|
||||
}
|
||||
|
||||
#buildLaunchPlan(
|
||||
input: EnqueueBattleInput,
|
||||
chosenMode: OfferedGameMode,
|
||||
mission: MissionHeader,
|
||||
coalitions: CoalitionPairing,
|
||||
playerMrank: number,
|
||||
minMrank: number,
|
||||
maxMrank: number,
|
||||
customBots: CustomBotsPool,
|
||||
): BattleLaunchPlan {
|
||||
const { declaration } = chosenMode;
|
||||
const desiredPlayers = declaration.isSmallTeams ? this.#tuning.smallTeamsMaxPlayers : this.#tuning.maxPlayers;
|
||||
const maxPlayers = Math.min(desiredPlayers, maxSlotsForMission(mission, desiredPlayers));
|
||||
const maxBots = Math.min(this.#tuning.maxBots, Math.max(1, maxPlayers - 1));
|
||||
const missionLocName = resolveMissionLocName(mission);
|
||||
const environment = declaration.environmentOverride ?? mission.environment;
|
||||
const session = this.#sessions.create({
|
||||
userId: input.userId,
|
||||
modeId: declaration.gameModeId,
|
||||
modeName: declaration.name,
|
||||
economicName: declaration.economicName,
|
||||
difficulty: declaration.difficulty,
|
||||
requiredClass: declaration.requiredClass,
|
||||
randomBattle: declaration.displayType === 'random_battle',
|
||||
missionName: mission.name,
|
||||
missionPath: mission.path,
|
||||
...(missionLocName !== undefined ? { missionLocName } : {}),
|
||||
country: input.country,
|
||||
startedAtSec: serverTimeToUnixSeconds(serverTimeNow()),
|
||||
});
|
||||
const allowedSet = new Set(declaration.allowedClasses);
|
||||
const extraBattleSlots = selectExtraBattleSlots({
|
||||
country: input.country,
|
||||
slotVehicles: input.slotVehicles,
|
||||
declaration,
|
||||
playerMrank,
|
||||
sessionMaxMrank: maxMrank,
|
||||
vehiclesByName: this.#vehiclesByName,
|
||||
rules: this.#spawnRules,
|
||||
tuning: this.#tuning,
|
||||
});
|
||||
const useSpawnScore = declaration.requiredClass === 'tank' && declaration.difficulty === 'realistic';
|
||||
return {
|
||||
sessionId: session.sessionId,
|
||||
modeId: declaration.gameModeId,
|
||||
modeName: declaration.name,
|
||||
economicName: declaration.economicName,
|
||||
missionName: mission.name,
|
||||
mission,
|
||||
missionFile: mission.path,
|
||||
missionType: mission.type ?? 'domination',
|
||||
...(mission.level !== undefined ? { level: mission.level } : {}),
|
||||
...(environment !== undefined ? { environment } : {}),
|
||||
...(mission.weather !== undefined ? { weather: mission.weather } : {}),
|
||||
difficulty: MISSION_DIFFICULTY[declaration.difficulty],
|
||||
country: input.country,
|
||||
playerTeam: coalitions.playerTeam,
|
||||
countryAllies: coalitions.countryAllies,
|
||||
countryAxis: coalitions.countryAxis,
|
||||
countriesAllies: coalitions.countriesAllies,
|
||||
countriesAxis: coalitions.countriesAxis,
|
||||
symmetricTeams: coalitions.symmetricTeams,
|
||||
minMrank,
|
||||
maxMrank,
|
||||
maxPlayers,
|
||||
maxBots,
|
||||
tankBotRespawns: this.#tuning.tankBotRespawns,
|
||||
airBotRespawns: this.#tuning.airBotRespawns,
|
||||
useTankBots: allowedSet.has('tank'),
|
||||
useShipBots: allowedSet.has('ship'),
|
||||
useSpawnScore,
|
||||
...(useSpawnScore ? {
|
||||
spawnScore: battleSpawnScore(input.slotVehicles, extraBattleSlots, maxMrank, this.#vehiclesByName, this.#spawnRules.spawnScore),
|
||||
} : {}),
|
||||
customBots,
|
||||
extraBattleSlots,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function twoSidedMissionsOf(mode: OfferedGameMode): MissionHeader[] {
|
||||
return mode.missions.filter((m) => m.playerSlots.teamA > 0 && m.playerSlots.teamB > 0);
|
||||
}
|
||||
|
||||
function activeVehiclesForMode(
|
||||
declaration: OfferedGameMode['declaration'],
|
||||
slotVehicles: readonly string[],
|
||||
selectedSlotVehicle: string | undefined,
|
||||
byName: ReadonlyMap<string, CatalogueVehicle>,
|
||||
): readonly string[] {
|
||||
if (declaration.multiSlot !== false || !selectedSlotVehicle) return slotVehicles;
|
||||
const selected = byName.get(selectedSlotVehicle);
|
||||
return selected && unitClassOfExpClass(selected.unitClass) === declaration.requiredClass
|
||||
? [selectedSlotVehicle]
|
||||
: slotVehicles;
|
||||
}
|
||||
|
||||
function isModeEligibleForLineup(
|
||||
declaration: OfferedGameMode['declaration'],
|
||||
slotVehicles: readonly string[],
|
||||
selectedSlotVehicle: string | undefined,
|
||||
byName: ReadonlyMap<string, CatalogueVehicle>,
|
||||
): boolean {
|
||||
if (!declaration.tag) return true;
|
||||
const active = activeVehiclesForMode(declaration, slotVehicles, selectedSlotVehicle, byName);
|
||||
const minMrank = declaration.minQueueMrank ?? 0;
|
||||
const minCrafts = declaration.minCraftsToPlay ?? 1;
|
||||
const matchingCount = active.filter((name) => {
|
||||
const vehicle = byName.get(name);
|
||||
if (!vehicle || unitClassOfExpClass(vehicle.unitClass) !== declaration.requiredClass) return false;
|
||||
return vehicleMrank(vehicle, declaration.difficulty, declaration.requiredClass) >= minMrank;
|
||||
}).length;
|
||||
return matchingCount >= minCrafts;
|
||||
}
|
||||
|
||||
function pickMission(missions: readonly MissionHeader[], banned: ReadonlySet<string>, disliked: ReadonlySet<string>): MissionHeader {
|
||||
const unbanned = missions.filter((mission) => !banned.has(mission.name));
|
||||
const poolAfterBan = unbanned.length > 0 ? unbanned : missions;
|
||||
const preferred = poolAfterBan.filter((mission) => !disliked.has(mission.name));
|
||||
const pool = preferred.length > 0 ? preferred : poolAfterBan;
|
||||
return pool[randomInt(pool.length)]!;
|
||||
}
|
||||
|
||||
function maxSlotsForMission(mission: MissionHeader, desiredMaxPlayers: number): number {
|
||||
const { teamA, teamB } = mission.playerSlots;
|
||||
return Math.max(2, Math.min(desiredMaxPlayers, Math.min(teamA, teamB) * 2));
|
||||
}
|
||||
|
||||
function resolveMissionLocName(mission: MissionHeader): string | undefined {
|
||||
if (mission.locName && mission.locName.length > 0) return mission.locName;
|
||||
if (mission.postfix && mission.postfix.length > 0 && mission.name.endsWith(mission.postfix)) {
|
||||
const baseName = mission.name.slice(0, -mission.postfix.length);
|
||||
if (baseName.length > 0) return `missions/${mission.postfix};missions/${baseName}`;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
/**
|
||||
* Mission settings for a local battle: the block the client hands to the native
|
||||
* `select_training_mission` (guiMission) to host the battle as an in-process LocalMP session.
|
||||
*
|
||||
* The client loads the mission file itself, but does not copy the localization keys or the
|
||||
* ticket and capture rules of `mission_settings.mission` into its MissionSettings; they are
|
||||
* copied here from the mission file, base values first and then the sub-block for the battle's
|
||||
* difficulty. `_gameMode` is left to the client, which takes it from its own native constants.
|
||||
*/
|
||||
import { emptyBlock, ensureBlock, setParam, appendParam, type BlkBlock, type BlkParam, type BlkValue } from '@wto/blk';
|
||||
import type { ExtraBattleSlot } from './battle-extra-slots.ts';
|
||||
import type { BattleLaunchPlan } from './battle-matchmaker.ts';
|
||||
import type { CustomBotsPool } from './battle-ranks.ts';
|
||||
|
||||
/** Mission localization keys the client reads from MissionSettings (missionsText.nut). */
|
||||
const LOCALIZATION_KEYS: readonly string[] = [
|
||||
'locName', 'locDesc', 'locNameTeamA', 'locNameTeamB', 'locDescTeamA', 'locDescTeamB', 'loc_name', 'postfix', 'restoreType',
|
||||
];
|
||||
|
||||
/** Ticket, capture and time rules of the mission. */
|
||||
const RULE_KEYS: readonly string[] = [
|
||||
'scoreLimit', 'timeLimit', 'killLimit', 'deathPenaltyMul',
|
||||
'ctaCaptureZoneEqualPenaltyMul', 'ctaCaptureZonePenaltyMul', 'captureZonePenaltyMul', 'scorePerSec',
|
||||
'ctaInstantDecreaseTicketsWhenNoRespawn', 'randomSpawnTeams', 'remapAiTankModels', 'useAlternativeMapCoord',
|
||||
];
|
||||
|
||||
/** Game type switches of a versus battle with tickets, capture zones and session rewards. */
|
||||
const VERSUS_SWITCHES: readonly string[] = [
|
||||
'gt_versus', 'gt_mp_tickets', 'gt_mp_capture', 'gt_use_wp', 'gt_use_xp', 'gt_use_stats', 'gt_use_unlocks',
|
||||
'allowSpare', 'isLimitedAmmo', 'allowUseArtillerySupport', 'isBotsAllowed', 'autoBalance',
|
||||
];
|
||||
|
||||
/**
|
||||
* `scores`: the scoreboard score table (BattleEconomy.missionScores) for the native LocalMP bridge,
|
||||
* written into the stock mission block customScoreParams, which the client copies into its
|
||||
* MissionSettings without reading it (native/wto-net/src/local_mp_scores.c).
|
||||
*/
|
||||
export function battleMissionSettings(plan: BattleLaunchPlan, scores: Readonly<Record<string, number>>): BlkBlock {
|
||||
const settings = emptyBlock();
|
||||
copyMissionParams(settings, plan);
|
||||
if (plan.level !== undefined) setParam(settings, 'level', text(plan.level));
|
||||
if (plan.environment !== undefined) setParam(settings, 'environment', text(plan.environment));
|
||||
if (plan.weather !== undefined) setParam(settings, 'weather', text(plan.weather));
|
||||
|
||||
setParam(settings, 'localMP', flag(true));
|
||||
setParam(settings, 'name', text(plan.missionName));
|
||||
setParam(settings, 'economicName', text(plan.economicName));
|
||||
// The 2.61.0.37 mission loader keeps gameModeName (MissionSettings+0x48) and looks up the
|
||||
// gameplay.blk missionSupportPlane preset by it (0x1269aff), which drives the native nuclear
|
||||
// carrier: assignment at the show threshold, the action bar item and the support unit spawn.
|
||||
setParam(settings, 'gameModeName', text(plan.modeName));
|
||||
setParam(settings, 'mis_file', text(plan.missionFile));
|
||||
setParam(settings, 'chapter', text('skirmish'));
|
||||
setParam(settings, 'type', text(plan.missionType));
|
||||
setParam(settings, 'difficulty', text(plan.difficulty));
|
||||
setParam(settings, 'country_allies', text(plan.countryAllies));
|
||||
setParam(settings, 'country_axis', text(plan.countryAxis));
|
||||
setParam(settings, 'arcadeCountry', flag(true));
|
||||
setParam(settings, 'symmetricTeams', flag(plan.symmetricTeams));
|
||||
setParam(settings, 'gt_mp_solo', flag(false));
|
||||
for (const name of VERSUS_SWITCHES) setParam(settings, name, flag(true));
|
||||
setParam(settings, 'useSpawnScore', flag(plan.useSpawnScore));
|
||||
setParam(settings, 'useTankBots', flag(plan.useTankBots));
|
||||
setParam(settings, 'useShipBots', flag(plan.useShipBots));
|
||||
setParam(settings, 'maxPlayers', integer(plan.maxPlayers));
|
||||
setParam(settings, 'maxBots', integer(plan.maxBots));
|
||||
|
||||
addPersistentSpawnCosts(settings, plan.extraBattleSlots);
|
||||
const scoreParams = ensureBlock(settings, 'customScoreParams');
|
||||
for (const [name, value] of Object.entries(scores)) setParam(scoreParams, name, real(value));
|
||||
for (const name of ['ranks', 'forcedRanks']) {
|
||||
const ranks = ensureBlock(settings, name);
|
||||
setParam(ranks, 'min', integer(plan.minMrank));
|
||||
setParam(ranks, 'max', integer(plan.maxMrank));
|
||||
}
|
||||
// The 2.61.0.37 mission loader copies customRules at 0x126db82 and reads customBots
|
||||
// from that block at 0x126f074.
|
||||
ensureBlock(settings, 'customRules').blocks.push(customBotsBlock(plan));
|
||||
return settings;
|
||||
}
|
||||
|
||||
function copyMissionParams(settings: BlkBlock, plan: BattleLaunchPlan): void {
|
||||
const wanted = new Set([...LOCALIZATION_KEYS, ...RULE_KEYS]);
|
||||
const copy = (params: readonly BlkParam[] | undefined, keys: ReadonlySet<string>): void => {
|
||||
for (const param of params ?? []) {
|
||||
if (keys.has(param.name)) setParam(settings, param.name, param.value);
|
||||
}
|
||||
};
|
||||
copy(plan.mission.missionParams, wanted);
|
||||
copy(plan.mission.difficultyParams[plan.difficulty], new Set(RULE_KEYS));
|
||||
}
|
||||
|
||||
/** Fixed spawn costs of extra slots, read back by the spawn score respondents (customSpawnScore). */
|
||||
function addPersistentSpawnCosts(settings: BlkBlock, slots: readonly ExtraBattleSlot[]): void {
|
||||
const costed = slots.flatMap((slot) =>
|
||||
slot.persistentCost !== undefined && slot.persistentCost > 0 && slot.unitName !== ''
|
||||
? [{ unitName: slot.unitName, cost: slot.persistentCost }]
|
||||
: []);
|
||||
if (costed.length === 0) return;
|
||||
const costs = ensureBlock(ensureBlock(settings, 'customSpawnScore'), 'persistent_costs');
|
||||
for (const slot of costed) setParam(costs, slot.unitName, integer(slot.cost));
|
||||
}
|
||||
|
||||
/** AI vehicle pool in the layout of config/bots.blk; repeated entries are separate blocks. */
|
||||
function customBotsBlock(plan: BattleLaunchPlan): BlkBlock {
|
||||
const bots = emptyBlock('customBots');
|
||||
setParam(bots, 'wtoPlayerTeam', text(String(plan.playerTeam)));
|
||||
setParam(bots, 'wtoTeamACountries', text(plan.countriesAllies.join(';')));
|
||||
setParam(bots, 'wtoTeamBCountries', text(plan.countriesAxis.join(';')));
|
||||
setParam(bots, 'numBotRespawnsInMultiSlot', integer(plan.airBotRespawns));
|
||||
setParam(bots, 'numTankBotRespawnsInMultiSlot', integer(plan.tankBotRespawns));
|
||||
setParam(bots, 'numBotRespawnsInVersus', integer(plan.airBotRespawns));
|
||||
setParam(bots, 'numTankBotRespawnsInVersus', integer(plan.tankBotRespawns));
|
||||
bots.blocks.push(
|
||||
poolBlock('allowedTanks', 'tank', plan.customBots.tanks),
|
||||
poolBlock('allowedAircrafts', 'aircraft', plan.customBots.aircrafts),
|
||||
poolBlock('allowedShips', 'ship', plan.customBots.ships),
|
||||
);
|
||||
return bots;
|
||||
}
|
||||
|
||||
function poolBlock(name: string, entryName: string, entries: CustomBotsPool['tanks']): BlkBlock {
|
||||
const pool = emptyBlock(name);
|
||||
for (const entry of entries) {
|
||||
const block = emptyBlock(entryName);
|
||||
appendParam(block, 'name', text(entry.name));
|
||||
appendParam(block, 'weight', { type: 'real', value: entry.weight });
|
||||
appendParam(block, 'country', text(entry.country));
|
||||
pool.blocks.push(block);
|
||||
}
|
||||
return pool;
|
||||
}
|
||||
|
||||
function text(value: string): BlkValue {
|
||||
return { type: 'string', value };
|
||||
}
|
||||
|
||||
function integer(value: number): BlkValue {
|
||||
return { type: 'int', value: Math.trunc(value) };
|
||||
}
|
||||
|
||||
function flag(value: boolean): BlkValue {
|
||||
return { type: 'bool', value };
|
||||
}
|
||||
|
||||
function real(value: number): BlkValue {
|
||||
return { type: 'real', value };
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
/**
|
||||
* Pure matchmaking rank (`mrank`) calculation and deterministic BR-matched `customBots`
|
||||
* vehicle-pool selection (`scripts/slotbar/slotbarpresets/calcranks.nut`).
|
||||
*
|
||||
* `BotSystem` (`aces.exe` `0x11af3f0`) reads `MissionSettings.customBots` using bare country
|
||||
* names (`"usa"`, `"germany"`, ...) and three sub-blocks: `allowedTanks` (`tank`),
|
||||
* `allowedAircrafts` (`aircraft`), and `allowedShips` (`ship`).
|
||||
*/
|
||||
import type { CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.ts';
|
||||
import type { ModeDifficulty, UnitClass } from '../game-modes/catalogue/game-mode-declaration.ts';
|
||||
import { vehicleTypeById, vehicleTypeOfClass, type VehicleType } from '../research/vehicle-types.ts';
|
||||
|
||||
const COUNTRY_PREFIX = 'country_';
|
||||
|
||||
export interface CraftRankEntry {
|
||||
readonly unitClass: UnitClass | undefined;
|
||||
readonly mrank: number;
|
||||
}
|
||||
|
||||
export interface BotPoolEntry {
|
||||
readonly name: string;
|
||||
readonly country: string;
|
||||
readonly weight: number;
|
||||
}
|
||||
|
||||
export interface CustomBotsPool {
|
||||
readonly tanks: readonly BotPoolEntry[];
|
||||
readonly aircrafts: readonly BotPoolEntry[];
|
||||
readonly ships: readonly BotPoolEntry[];
|
||||
}
|
||||
|
||||
export interface BotPoolQuery {
|
||||
readonly difficulty: ModeDifficulty;
|
||||
readonly requiredClass: UnitClass;
|
||||
readonly allowedClasses: readonly UnitClass[];
|
||||
readonly countries: readonly string[];
|
||||
readonly centerMrank: number;
|
||||
readonly minMrank: number;
|
||||
readonly maxMrank: number;
|
||||
readonly limitPerType: number;
|
||||
}
|
||||
|
||||
export function stripCountryPrefix(country: string): string {
|
||||
return country.startsWith(COUNTRY_PREFIX) ? country.slice(COUNTRY_PREFIX.length) : country;
|
||||
}
|
||||
|
||||
export function unitClassOfExpClass(expClass: string): UnitClass | undefined {
|
||||
return unitClassOfVehicleType(vehicleTypeOfClass(expClass));
|
||||
}
|
||||
|
||||
export function unitClassOfTypeCode(unitTypeCode: number): UnitClass | undefined {
|
||||
return unitClassOfVehicleType(vehicleTypeById(unitTypeCode));
|
||||
}
|
||||
|
||||
export function vehicleMrank(vehicle: CatalogueVehicle, difficulty: ModeDifficulty, requiredClass: UnitClass): number {
|
||||
if (difficulty === 'arcade') return vehicle.economicRankArcade;
|
||||
if (difficulty === 'simulator') {
|
||||
return requiredClass === 'tank' && vehicle.economicRankTankSimulation !== undefined
|
||||
? vehicle.economicRankTankSimulation
|
||||
: vehicle.economicRankSimulation;
|
||||
}
|
||||
return requiredClass === 'tank' && vehicle.economicRankTankHistorical !== undefined
|
||||
? vehicle.economicRankTankHistorical
|
||||
: vehicle.economicRankHistorical;
|
||||
}
|
||||
|
||||
/**
|
||||
* Maximum `mrank` among crafts allowed in the mode (`calcranks.nut` `filterCrafts` +
|
||||
* `specialShipsFilter`: in naval modes, aircraft above `maxShipMrank + 1` are ignored).
|
||||
*/
|
||||
export function maxModeMrank(
|
||||
crafts: readonly CraftRankEntry[],
|
||||
requiredClass: UnitClass,
|
||||
allowedClasses: readonly UnitClass[],
|
||||
): number {
|
||||
const allowedSet = new Set(allowedClasses);
|
||||
const matching = crafts.filter((craft) => craft.unitClass !== undefined && allowedSet.has(craft.unitClass));
|
||||
if (!matching.some((craft) => craft.unitClass === requiredClass)) return 0;
|
||||
|
||||
let filtered = matching;
|
||||
if (requiredClass === 'ship') {
|
||||
const maxShip = matching
|
||||
.filter((craft) => craft.unitClass === 'ship')
|
||||
.reduce((max, craft) => Math.max(max, craft.mrank), 0);
|
||||
filtered = matching.filter((craft) => craft.unitClass !== 'aircraft' || craft.mrank <= maxShip + 1);
|
||||
}
|
||||
return filtered.reduce((max, craft) => Math.max(max, Math.max(0, Math.trunc(craft.mrank))), 0);
|
||||
}
|
||||
|
||||
export function lineupMrank(
|
||||
vehicleNames: readonly string[],
|
||||
byName: ReadonlyMap<string, CatalogueVehicle>,
|
||||
difficulty: ModeDifficulty,
|
||||
requiredClass: UnitClass,
|
||||
allowedClasses: readonly UnitClass[],
|
||||
): number {
|
||||
const crafts: CraftRankEntry[] = vehicleNames.flatMap((name) => {
|
||||
const vehicle = byName.get(name);
|
||||
if (!vehicle) return [];
|
||||
return [{
|
||||
unitClass: unitClassOfExpClass(vehicle.unitClass),
|
||||
mrank: vehicleMrank(vehicle, difficulty, requiredClass),
|
||||
}];
|
||||
});
|
||||
return maxModeMrank(crafts, requiredClass, allowedClasses);
|
||||
}
|
||||
|
||||
export function selectCustomBots(vehicles: readonly CatalogueVehicle[], query: BotPoolQuery): CustomBotsPool {
|
||||
const allowed = new Set(query.allowedClasses);
|
||||
const orderedCountries = [...new Set(query.countries.map((c) => (c.startsWith(COUNTRY_PREFIX) ? c : `${COUNTRY_PREFIX}${c}`)))];
|
||||
return {
|
||||
tanks: allowed.has('tank') ? pickCategoryPool(vehicles, orderedCountries, 'tank', query) : [],
|
||||
aircrafts: allowed.has('aircraft') ? pickCategoryPool(vehicles, orderedCountries, 'aircraft', query) : [],
|
||||
ships: allowed.has('ship') ? pickCategoryPool(vehicles, orderedCountries, 'ship', query) : [],
|
||||
};
|
||||
}
|
||||
|
||||
function pickCategoryPool(
|
||||
vehicles: readonly CatalogueVehicle[],
|
||||
orderedCountries: readonly string[],
|
||||
category: 'tank' | 'aircraft' | 'ship',
|
||||
query: BotPoolQuery,
|
||||
): BotPoolEntry[] {
|
||||
const countrySet = new Set(orderedCountries);
|
||||
const eligible = vehicles.filter((vehicle) =>
|
||||
vehicle.inTechTree
|
||||
&& !vehicle.onlyShownWhenOwned
|
||||
&& !vehicle.premiumPack
|
||||
&& !vehicle.gift
|
||||
&& !vehicle.event
|
||||
&& vehicle.researchType === undefined
|
||||
&& countrySet.has(vehicle.country)
|
||||
&& unitClassOfExpClass(vehicle.unitClass) === category);
|
||||
if (eligible.length === 0) return [];
|
||||
|
||||
const sortedByCloseness = [...eligible].sort((a, b) => {
|
||||
const distA = Math.abs(vehicleMrank(a, query.difficulty, query.requiredClass) - query.centerMrank);
|
||||
const distB = Math.abs(vehicleMrank(b, query.difficulty, query.requiredClass) - query.centerMrank);
|
||||
return distA !== distB ? distA - distB : a.name.localeCompare(b.name);
|
||||
});
|
||||
const inWindow = sortedByCloseness.filter((vehicle) => {
|
||||
const mrank = vehicleMrank(vehicle, query.difficulty, query.requiredClass);
|
||||
return mrank >= query.minMrank && mrank <= query.maxMrank;
|
||||
});
|
||||
const source = inWindow.length > 0 ? inWindow : sortedByCloseness.slice(0, query.limitPerType);
|
||||
return roundRobinByCountry(source, orderedCountries, query.limitPerType);
|
||||
}
|
||||
|
||||
function roundRobinByCountry(
|
||||
vehicles: readonly CatalogueVehicle[],
|
||||
orderedCountries: readonly string[],
|
||||
limit: number,
|
||||
): BotPoolEntry[] {
|
||||
const buckets = new Map<string, CatalogueVehicle[]>(orderedCountries.map((country) => [country, []]));
|
||||
for (const vehicle of vehicles) buckets.get(vehicle.country)?.push(vehicle);
|
||||
const out: BotPoolEntry[] = [];
|
||||
for (let index = 0; out.length < limit; index++) {
|
||||
let added = false;
|
||||
for (const country of orderedCountries) {
|
||||
const vehicle = buckets.get(country)?.[index];
|
||||
if (!vehicle) continue;
|
||||
out.push({ name: vehicle.name, country: stripCountryPrefix(country), weight: 1 });
|
||||
added = true;
|
||||
if (out.length >= limit) break;
|
||||
}
|
||||
if (!added) break;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function unitClassOfVehicleType(type: VehicleType | undefined): UnitClass | undefined {
|
||||
if (type === 'Tank') return 'tank';
|
||||
if (type === 'Aircraft') return 'aircraft';
|
||||
if (type === 'Helicopter') return 'helicopter';
|
||||
if (type === 'Ship' || type === 'Boat') return 'ship';
|
||||
return undefined;
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
/**
|
||||
* Vehicle damage, automatic repair and premium expense compensation of a settled battle. Online
|
||||
* the server does this; the client shows the result in the battle log (userlogviewdata.nut:
|
||||
* aircrafts{<vehicle>:r=hp} below 1 lists it as damaged, container.aircraftsRepaired{aname<i>
|
||||
* cost<i>} the automatic repair (a negative cost: not enough Silver Lions), autoRepairWasOn,
|
||||
* container.wpExpensesCompensation) and in the hangar (repair cost and time from hp).
|
||||
*
|
||||
* Rules (official "Following the Roadmap: Sons of Attila", 2023-09-19, Changes to Silver Lion
|
||||
* mechanics; "Compensation of Battle Expenses, Free Backups and More", 2023-07-25):
|
||||
* - A destroyed vehicle costs a per-minute share of its lifetime (repairCostPerMin<Mode>), at most
|
||||
* the full repair cost of the stat card. Whole minutes started (inferred: "calculated per
|
||||
* minute").
|
||||
* - Leaving a vehicle by yourself costs the full repair cost, however long it lived. A life that
|
||||
* ended without the vehicle being destroyed before the battle ended, or in a battle the player
|
||||
* left, counts as that (inferred). A vehicle still alive at the end costs nothing (inferred).
|
||||
* - Destroyed by an ally (the HUD kill log names a teammate as the killer): no repair cost.
|
||||
* - Several lives of one vehicle add up, at most the full cost (offline design).
|
||||
* - The cost becomes damage: hp = 1 - cost / full cost, so that the client's own repair cost
|
||||
* (1 - hp) x full cost (repair/repair-rules.ts) is that cost.
|
||||
* - One available free repair covers the vehicle's new damage at settlement. Consuming it
|
||||
* once per damaged vehicle per battle, regardless of the paid auto-repair setting, is inferred.
|
||||
* Reserve vehicles have no repair cost, so they never need to spend an allowance.
|
||||
* - "Automatically repair all vehicles after the battle" (autoRepairAircrafts, on by default,
|
||||
* aces.exe 0x90b6a0) repairs the vehicles damaged in the battle when the Silver Lions suffice.
|
||||
* - Premium account insurance: with automatic repair and automatic ammunition purchase on, when
|
||||
* the repair and ammunition expenses exceed what the battle earned (friendly fire penalties
|
||||
* not counted), the difference is paid back.
|
||||
*/
|
||||
import type { BlkBlock } from '@wto/blk';
|
||||
import type { RepairMode } from '../game-data/datasets/vehicle-repair.ts';
|
||||
import { canAfford, pay } from '../profile/profile-currency.ts';
|
||||
import { clearVehicleDamage, setVehicleDamage, vehicleCondition } from '../profile/profile-vehicle-condition.ts';
|
||||
import { consumeFreeRepair } from '../profile/profile-vehicle-state.ts';
|
||||
import type { ServerTime } from '../profile/server-time.ts';
|
||||
import { gameModeIndexOf, type RepairRules } from '../repair/repair-rules.ts';
|
||||
import type { BattleReport } from './battle-report.ts';
|
||||
|
||||
/** Seconds between a death and its kill log entry that still match (both come from the same frame in practice). */
|
||||
const KILL_LOG_TOLERANCE_SEC = 2;
|
||||
/** A life ending this close to the battle's end ended with the battle. */
|
||||
const BATTLE_END_TOLERANCE_SEC = 1;
|
||||
|
||||
export interface VehicleDamage {
|
||||
readonly vehicle: string;
|
||||
/** Condition after the battle and any free repair, before a paid repair. */
|
||||
readonly hp: number;
|
||||
}
|
||||
|
||||
export interface AutoRepair {
|
||||
readonly vehicle: string;
|
||||
/** Paid; negative when the player could not pay it and the vehicle stays damaged. */
|
||||
readonly cost: number;
|
||||
}
|
||||
|
||||
/** Damages the vehicles of the battle; returns each vehicle's condition after it. */
|
||||
export function damageBattleVehicles(
|
||||
profile: BlkBlock,
|
||||
report: BattleReport,
|
||||
mode: RepairMode,
|
||||
rules: RepairRules,
|
||||
now: ServerTime,
|
||||
): VehicleDamage[] {
|
||||
const costs = new Map<string, number>();
|
||||
for (const life of report.lives) {
|
||||
costs.set(life.unit, (costs.get(life.unit) ?? 0) + lifeCost(profile, report, life, mode, rules));
|
||||
}
|
||||
const damages: VehicleDamage[] = [];
|
||||
for (const [vehicle, cost] of costs) {
|
||||
const full = rules.fullCost(profile, vehicle, mode);
|
||||
const before = vehicleCondition(profile, vehicle)?.hp ?? 1;
|
||||
const hp = full > 0 ? Math.max(0, before - Math.min(full, cost) / full) : before;
|
||||
if (hp < before) {
|
||||
if (consumeFreeRepair(profile, vehicle, rules.vehicle(vehicle)?.freeRepairs ?? 0)) {
|
||||
clearVehicleDamage(profile, vehicle);
|
||||
damages.push({ vehicle, hp: 1 });
|
||||
continue;
|
||||
}
|
||||
setVehicleDamage(profile, vehicle, hp, gameModeIndexOf(mode), now);
|
||||
}
|
||||
damages.push({ vehicle, hp });
|
||||
}
|
||||
return damages;
|
||||
}
|
||||
|
||||
function lifeCost(profile: BlkBlock, report: BattleReport, life: BattleReport['lives'][number], mode: RepairMode, rules: RepairRules): number {
|
||||
const full = rules.fullCost(profile, life.unit, mode);
|
||||
if (full <= 0) return 0;
|
||||
if (!life.died) {
|
||||
const endedWithBattle = report.outcome !== 'running' && life.end >= report.sessionEnd - BATTLE_END_TOLERANCE_SEC;
|
||||
return endedWithBattle ? 0 : full;
|
||||
}
|
||||
if (killedByAlly(report, life.end)) return 0;
|
||||
const minutes = Math.max(1, Math.ceil((life.end - life.start) / 60));
|
||||
return Math.min(full, Math.round(rules.costPerMinute(profile, life.unit, mode) * minutes));
|
||||
}
|
||||
|
||||
function killedByAlly(report: BattleReport, time: number): boolean {
|
||||
return report.feed.some((kill) =>
|
||||
kill.victim === report.localPlayerId
|
||||
&& kill.killer >= 0 && kill.killer !== report.localPlayerId
|
||||
&& kill.killerTeam === report.localTeam
|
||||
&& Math.abs(kill.time - time) <= KILL_LOG_TOLERANCE_SEC);
|
||||
}
|
||||
|
||||
/** Pays the repair of each damaged vehicle of the battle the player can afford, in name order. */
|
||||
export function autoRepairVehicles(profile: BlkBlock, damages: readonly VehicleDamage[], rules: RepairRules): AutoRepair[] {
|
||||
const repairs: AutoRepair[] = [];
|
||||
for (const { vehicle } of [...damages].sort((a, b) => a.vehicle.localeCompare(b.vehicle))) {
|
||||
const cost = rules.currentCost(profile, vehicle);
|
||||
if (cost <= 0) continue;
|
||||
const price = { silverLions: cost, goldenEagles: 0 };
|
||||
if (canAfford(profile, price)) {
|
||||
pay(profile, price);
|
||||
clearVehicleDamage(profile, vehicle);
|
||||
repairs.push({ vehicle, cost });
|
||||
} else {
|
||||
repairs.push({ vehicle, cost: -cost });
|
||||
}
|
||||
}
|
||||
return repairs;
|
||||
}
|
||||
|
||||
/** The premium account's compensation of the battle's expenses. */
|
||||
export function expensesCompensation(earnedWithoutPenalties: number, expenses: number): number {
|
||||
return Math.max(0, Math.round(expenses - Math.max(0, earnedWithoutPenalties)));
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
/**
|
||||
* The battle report of `cln_wto_finish_battle` (patches/gui/battle/report-local-battle-settlement):
|
||||
* what happened in the battle, as facts only. The client sends no money; the local server
|
||||
* prices every event (battle-economy.ts).
|
||||
*
|
||||
* sessionId:t outcome:t ("win" | "lose" | "running") localTeam:i
|
||||
* teamAScore:i teamBScore:i sessionStart:r sessionEnd:r (mission time, seconds)
|
||||
* localPlayerId:i the local player's MPlayer id
|
||||
* lives{ life{ unit:t start:r end:r died:b } ... } one per spawn of the local player
|
||||
* events{ e{ time:r unit:t code:i expClass:t victim:t victimIsPlayer:b friendly:b
|
||||
* modifier:t damage:i } ... } the local player's combat events
|
||||
* feed{ k{ time:r killer:i killerTeam:i victim:i victimTeam:i } ... }
|
||||
* every kill of the HUD kill log
|
||||
* (HUD_MSG_MULTIPLAYER_DMG, isKill)
|
||||
* players{ p{ id:i team:i score:i kills:i groundKills:i humanKills:i navalKills:i aiKills:i
|
||||
* aiGroundKills:i aiNavalKills:i assists:i deaths:i } ... }
|
||||
* the final scoreboard
|
||||
* strikes{ s{ time:r } ... } explosions of the local player's
|
||||
* nuclear bombs (native local_mp_nuke.c)
|
||||
* spares{ <unit>:i ... } backup vehicles used
|
||||
*/
|
||||
import { findBlock, type BlkBlock } from '@wto/blk';
|
||||
import type { CombatEventFact } from './battle-economy.ts';
|
||||
|
||||
export type BattleOutcomeKind = 'win' | 'lose' | 'running';
|
||||
|
||||
export interface BattleLife {
|
||||
readonly unit: string;
|
||||
readonly start: number;
|
||||
readonly end: number;
|
||||
/** The life ended with the vehicle destroyed (not with the battle's end or a vehicle change). */
|
||||
readonly died: boolean;
|
||||
}
|
||||
|
||||
/** One kill of the HUD kill log; ids are MPlayer ids, -1 when the unit had no player. */
|
||||
export interface FeedKill {
|
||||
readonly time: number;
|
||||
readonly killer: number;
|
||||
readonly killerTeam: number;
|
||||
readonly victim: number;
|
||||
readonly victimTeam: number;
|
||||
}
|
||||
|
||||
/** One row of the final scoreboard (the stock mplayer fields, scripts/mplayerParamType.nut). */
|
||||
export interface ScoreboardPlayer {
|
||||
readonly id: number;
|
||||
readonly team: number;
|
||||
readonly score: number;
|
||||
readonly kills: number;
|
||||
readonly groundKills: number;
|
||||
readonly humanKills: number;
|
||||
readonly navalKills: number;
|
||||
readonly aiKills: number;
|
||||
readonly aiGroundKills: number;
|
||||
readonly aiNavalKills: number;
|
||||
readonly assists: number;
|
||||
readonly deaths: number;
|
||||
}
|
||||
|
||||
const SCOREBOARD_FIELDS = [
|
||||
'score', 'kills', 'groundKills', 'humanKills', 'navalKills', 'aiKills', 'aiGroundKills', 'aiNavalKills', 'assists', 'deaths',
|
||||
] as const;
|
||||
|
||||
export interface ReportedCombatEvent extends CombatEventFact {
|
||||
readonly time: number;
|
||||
readonly unit: string;
|
||||
readonly victim: string;
|
||||
readonly modifier: string;
|
||||
}
|
||||
|
||||
export interface BattleReport {
|
||||
readonly sessionId: string;
|
||||
readonly outcome: BattleOutcomeKind;
|
||||
readonly localTeam: number;
|
||||
readonly teamAScore: number;
|
||||
readonly teamBScore: number;
|
||||
readonly sessionStart: number;
|
||||
readonly sessionEnd: number;
|
||||
readonly localPlayerId: number;
|
||||
readonly lives: readonly BattleLife[];
|
||||
readonly events: readonly ReportedCombatEvent[];
|
||||
readonly feed: readonly FeedKill[];
|
||||
readonly players: readonly ScoreboardPlayer[];
|
||||
/** Mission times at which the local player's nuclear bombs exploded. */
|
||||
readonly nuclearStrikes: readonly number[];
|
||||
readonly usedSpares: Readonly<Record<string, number>>;
|
||||
}
|
||||
|
||||
/** Undefined when the report is malformed; lives and events that make no sense are dropped. */
|
||||
export function parseBattleReport(payload: BlkBlock): BattleReport | undefined {
|
||||
const sessionId = strOf(payload, 'sessionId');
|
||||
if (!sessionId || !/^[0-9a-f]{16}$/i.test(sessionId)) return undefined;
|
||||
const rawOutcome = strOf(payload, 'outcome');
|
||||
const sessionStart = Math.max(0, realOf(payload, 'sessionStart'));
|
||||
const sessionEnd = Math.max(sessionStart, realOf(payload, 'sessionEnd'));
|
||||
const lives = (findBlock(payload, 'lives')?.blocks ?? []).flatMap((block): BattleLife[] => {
|
||||
const unit = strOf(block, 'unit');
|
||||
const start = Math.max(sessionStart, realOf(block, 'start'));
|
||||
const end = Math.min(sessionEnd, Math.max(start, realOf(block, 'end')));
|
||||
return unit ? [{ unit, start, end, died: boolOf(block, 'died') }] : [];
|
||||
});
|
||||
const livedUnits = new Set(lives.map((life) => life.unit));
|
||||
const events = (findBlock(payload, 'events')?.blocks ?? []).flatMap((block): ReportedCombatEvent[] => {
|
||||
const unit = strOf(block, 'unit');
|
||||
if (!unit || !livedUnits.has(unit)) return [];
|
||||
return [{
|
||||
time: realOf(block, 'time'),
|
||||
unit,
|
||||
code: intOf(block, 'code'),
|
||||
expClass: strOf(block, 'expClass') ?? '',
|
||||
victim: strOf(block, 'victim') ?? '',
|
||||
victimIsPlayer: boolOf(block, 'victimIsPlayer'),
|
||||
friendly: boolOf(block, 'friendly'),
|
||||
modifier: strOf(block, 'modifier') ?? '',
|
||||
damage: Math.max(0, intOf(block, 'damage')),
|
||||
}];
|
||||
});
|
||||
return {
|
||||
sessionId: sessionId.toLowerCase(),
|
||||
outcome: rawOutcome === 'win' || rawOutcome === 'lose' ? rawOutcome : 'running',
|
||||
localTeam: intOf(payload, 'localTeam', 1),
|
||||
teamAScore: intOf(payload, 'teamAScore'),
|
||||
teamBScore: intOf(payload, 'teamBScore'),
|
||||
sessionStart,
|
||||
sessionEnd,
|
||||
localPlayerId: intOf(payload, 'localPlayerId', -1),
|
||||
lives,
|
||||
events,
|
||||
feed: (findBlock(payload, 'feed')?.blocks ?? []).map((block) => ({
|
||||
time: realOf(block, 'time'),
|
||||
killer: intOf(block, 'killer', -1),
|
||||
killerTeam: intOf(block, 'killerTeam'),
|
||||
victim: intOf(block, 'victim', -1),
|
||||
victimTeam: intOf(block, 'victimTeam'),
|
||||
})).sort((a, b) => a.time - b.time),
|
||||
players: (findBlock(payload, 'players')?.blocks ?? []).map((block): ScoreboardPlayer => ({
|
||||
id: intOf(block, 'id', -1),
|
||||
team: intOf(block, 'team'),
|
||||
...Object.fromEntries(SCOREBOARD_FIELDS.map((field) => [field, Math.max(0, intOf(block, field))])) as Record<(typeof SCOREBOARD_FIELDS)[number], number>,
|
||||
})),
|
||||
nuclearStrikes: (findBlock(payload, 'strikes')?.blocks ?? []).map((block) => realOf(block, 'time')).sort((a, b) => a - b),
|
||||
usedSpares: parseSpareMap(findBlock(payload, 'spares')),
|
||||
};
|
||||
}
|
||||
|
||||
function parseSpareMap(sparesBlk: BlkBlock | undefined): Record<string, number> {
|
||||
const out: Record<string, number> = {};
|
||||
for (const param of sparesBlk?.params ?? []) {
|
||||
const count = param.value.type === 'int' ? param.value.value : 0;
|
||||
if (param.name && count > 0) out[param.name] = count;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function strOf(block: BlkBlock, name: string): string | undefined {
|
||||
const value = block.params.find((p) => p.name === name)?.value;
|
||||
return value?.type === 'string' && value.value !== '' ? value.value : undefined;
|
||||
}
|
||||
|
||||
function intOf(block: BlkBlock, name: string, fallback = 0): number {
|
||||
const value = block.params.find((p) => p.name === name)?.value;
|
||||
if (value?.type === 'int') return value.value;
|
||||
if (value?.type === 'int64') return Number(value.value);
|
||||
return fallback;
|
||||
}
|
||||
|
||||
function realOf(block: BlkBlock, name: string): number {
|
||||
const value = block.params.find((p) => p.name === name)?.value;
|
||||
if (value?.type === 'real' || value?.type === 'int') return Number.isFinite(value.value) ? value.value : 0;
|
||||
return 0;
|
||||
}
|
||||
|
||||
function boolOf(block: BlkBlock, name: string): boolean {
|
||||
const value = block.params.find((p) => p.name === name)?.value;
|
||||
return value?.type === 'bool' ? value.value : value?.type === 'int' ? value.value !== 0 : false;
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
/**
|
||||
* The `EULT_SESSION_RESULT` (type 2) user log of a settled battle, in the shape the client's battle
|
||||
* log reads (gui.vromfs.bin scripts/userlog/userlogviewdata.nut, getuserlogbattlerewardstable.nut),
|
||||
* plus the debriefing table (`wtoDebriefing`, battle-debriefing.ts) the settlement patch shows.
|
||||
* The boosters and wager of the battle: body affectedBoosters{ activeBooster{ itemId:t } ... } and
|
||||
* container.affectedWagers{ itemId:t } (debriefingFull.nut getDebriefingActiveBoosters /
|
||||
* getDebriefingActiveWager, userlogviewdata.nut "used items"); itemId is the items.blk name.
|
||||
* Repair (battle-repair.ts): aircrafts{ <vehicle>:r=<hp after the battle> }, autoRepairWasOn:b,
|
||||
* container.aircraftsRepaired{ aname<i>:t cost<i>:i } and container.wpExpensesCompensation:i
|
||||
* (userlogviewdata.nut "damaged vehicles", "automatic repair", "expenses compensation").
|
||||
*/
|
||||
import { emptyBlock, setParam, type BlkBlock, type BlkParam } from '@wto/blk';
|
||||
import { appendUserLog, EULT_SESSION_RESULT } from '../profile/profile-trophies-log.ts';
|
||||
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 { AutoRepair, VehicleDamage } from './battle-repair.ts';
|
||||
import type { BattleSession } from './battle-session-store.ts';
|
||||
|
||||
export interface EarnedRpItem {
|
||||
readonly unit: string;
|
||||
readonly modification?: string;
|
||||
readonly rp: number;
|
||||
readonly excessRp?: number;
|
||||
}
|
||||
|
||||
export interface BattleResultSummary {
|
||||
readonly country: string;
|
||||
readonly rewards: BattleRewards;
|
||||
/** Silver Lions of the battle awards (streaks), logged separately as EULT_NEW_STREAK. */
|
||||
readonly unlocksWp: number;
|
||||
readonly weaponRefillSl: number;
|
||||
readonly usedSpares: Readonly<Record<string, number>>;
|
||||
readonly rpItems: readonly EarnedRpItem[];
|
||||
readonly researchUnits: readonly ResearchPointsUnit[];
|
||||
readonly affectedBoosters: readonly string[];
|
||||
readonly affectedWagers: readonly string[];
|
||||
readonly damages: readonly VehicleDamage[];
|
||||
readonly autoRepair: boolean;
|
||||
readonly repairs: readonly AutoRepair[];
|
||||
readonly compensation: number;
|
||||
readonly debriefing: BlkBlock;
|
||||
}
|
||||
|
||||
const NO_BONUSES: Bonuses = { premAccWp: 0, premAccExp: 0, premModExp: 0, boosterWp: 0, boosterExp: 0 };
|
||||
|
||||
/** Container list of each debriefing row's events (getuserlogbattlerewardstable.nut ids). */
|
||||
const CONTAINER_OF_ROW: Readonly<Record<DebriefingRow, string | undefined>> = {
|
||||
AirKills: 'eventKill',
|
||||
GroundKills: 'eventKillGround',
|
||||
NavalKills: 'eventKillGround',
|
||||
HumanKills: 'eventKillHuman',
|
||||
FriendlyKills: undefined,
|
||||
Assist: 'eventAssist',
|
||||
AirSevereDamage: 'eventSevereDamage',
|
||||
ShipSevereDamage: 'eventSevereDamage',
|
||||
Critical: 'eventCriticalHit',
|
||||
Hit: 'eventHit',
|
||||
Captures: 'eventCaptureZone',
|
||||
// No user log list carries naval damage awards; they show in the debriefing table only.
|
||||
AwardDamage: undefined,
|
||||
};
|
||||
|
||||
export function mergeEarnedRpItems(items: readonly EarnedRpItem[]): EarnedRpItem[] {
|
||||
const byKey = new Map<string, EarnedRpItem>();
|
||||
for (const item of items) {
|
||||
if (item.rp <= 0 && (item.excessRp ?? 0) <= 0) continue;
|
||||
const key = `${item.unit}\0${item.modification ?? ''}`;
|
||||
const existing = byKey.get(key);
|
||||
if (existing) {
|
||||
const mergedExcess = (existing.excessRp ?? 0) + (item.excessRp ?? 0);
|
||||
byKey.set(key, {
|
||||
unit: existing.unit,
|
||||
...(existing.modification ? { modification: existing.modification } : {}),
|
||||
rp: existing.rp + item.rp,
|
||||
...(mergedExcess > 0 ? { excessRp: mergedExcess } : {}),
|
||||
});
|
||||
} else {
|
||||
byKey.set(key, item);
|
||||
}
|
||||
}
|
||||
return [...byKey.values()];
|
||||
}
|
||||
|
||||
export function appendBattleResultLog(profile: BlkBlock, session: BattleSession, summary: BattleResultSummary): void {
|
||||
const { rewards } = summary;
|
||||
const friendlyFirePenalty = rewards.events
|
||||
.filter((settled) => settled.priced.row === 'FriendlyKills')
|
||||
.reduce((sum, settled) => sum + settled.priced.wp, 0);
|
||||
const bodyParams: BlkParam[] = [
|
||||
{ name: 'win', value: { type: 'bool', value: rewards.win } },
|
||||
{ name: 'mission', value: { type: 'string', value: session.missionName } },
|
||||
...(session.missionLocName ? [{ name: 'locName', value: { type: 'string' as const, value: session.missionLocName } }] : []),
|
||||
{ name: 'country', value: { type: 'string', value: summary.country } },
|
||||
{ name: 'eventId', value: { type: 'string', value: session.modeName } },
|
||||
{ name: 'wpEarned', value: { type: 'int', value: rewards.wpTotal + summary.unlocksWp } },
|
||||
{ name: 'xpEarned', value: { type: 'int', value: rewards.expTotal } },
|
||||
{ name: 'activity', value: { type: 'real', value: rewards.activity } },
|
||||
{ name: 'autoRepairWasOn', value: { type: 'bool', value: summary.autoRepair } },
|
||||
...(friendlyFirePenalty !== 0 ? [{ name: 'friendlyFirePenalty', value: { type: 'int' as const, value: friendlyFirePenalty } }] : []),
|
||||
{ name: 'wtoSessionId', value: { type: 'string', value: session.sessionId } },
|
||||
];
|
||||
const bodyBlocks: BlkBlock[] = [buildContainerBlock(summary), summary.debriefing];
|
||||
if (summary.affectedBoosters.length > 0) {
|
||||
bodyBlocks.push({ name: 'affectedBoosters', params: [], blocks: summary.affectedBoosters.map((itemId) => itemIdBlock('activeBooster', itemId)) });
|
||||
}
|
||||
const aircrafts = emptyBlock('aircrafts');
|
||||
const hpAfter = new Map(summary.damages.map((damage) => [damage.vehicle, damage.hp]));
|
||||
for (const vehicle of rewards.vehicles) setParam(aircrafts, vehicle.vehicle, { type: 'real', value: hpAfter.get(vehicle.vehicle) ?? 1.0 });
|
||||
if (aircrafts.params.length > 0) bodyBlocks.push(aircrafts);
|
||||
const spare = buildSpareBlock(summary.usedSpares);
|
||||
if (spare) bodyBlocks.push(spare);
|
||||
const rpEarned = buildRpEarnedBlock(summary.rpItems);
|
||||
if (rpEarned) bodyBlocks.push(rpEarned);
|
||||
|
||||
appendUserLog(profile, {
|
||||
type: EULT_SESSION_RESULT,
|
||||
timeSec: serverTimeToUnixSeconds(serverTimeNow()),
|
||||
roomId: session.roomId,
|
||||
bodyParams,
|
||||
bodyBlocks,
|
||||
});
|
||||
}
|
||||
|
||||
function buildContainerBlock(summary: BattleResultSummary): BlkBlock {
|
||||
const container = emptyBlock('container');
|
||||
const { rewards } = summary;
|
||||
if (summary.weaponRefillSl > 0) setParam(container, 'wpCostWeaponRefill', { type: 'int', value: summary.weaponRefillSl });
|
||||
|
||||
const lists = new Map<string, BlkBlock[]>();
|
||||
const push = (id: string, event: BlkBlock): void => {
|
||||
const list = lists.get(id);
|
||||
if (list) list.push(event);
|
||||
else lists.set(id, [event]);
|
||||
};
|
||||
for (const { event, priced, bonuses } of rewards.events) {
|
||||
const id = CONTAINER_OF_ROW[priced.row];
|
||||
if (!id) continue;
|
||||
const block = emptyBlock('event');
|
||||
setParam(block, 'offenderUnit', { type: 'string', value: event.unit });
|
||||
if (event.victim) setParam(block, 'victimUnit', { type: 'string', value: event.victim });
|
||||
if (priced.row === 'NavalKills' || priced.row === 'ShipSevereDamage') {
|
||||
setParam(block, 'victimUnitFileName', { type: 'string', value: 'ships/' });
|
||||
}
|
||||
writeAmounts(block, priced.wp, priced.exp, bonuses);
|
||||
push(id, block);
|
||||
}
|
||||
|
||||
let missionWp = 0;
|
||||
for (const vehicle of rewards.vehicles) {
|
||||
if (vehicle.sessionTime > 0) {
|
||||
const block = emptyBlock('event');
|
||||
setParam(block, 'unit', { type: 'string', value: vehicle.vehicle });
|
||||
setParam(block, 'lifetime', { type: 'int', value: Math.round(vehicle.sessionTime) });
|
||||
writeAmounts(block, 0, 0, NO_BONUSES);
|
||||
push('unitSessionAward', block);
|
||||
}
|
||||
const time = vehicle.rows.get('BattleTime');
|
||||
if (time) {
|
||||
const block = emptyBlock('event');
|
||||
setParam(block, 'offenderUnit', { type: 'string', value: vehicle.vehicle });
|
||||
writeAmounts(block, time.noBonusWp, time.noBonusExp, time);
|
||||
push('eventBattletime', block);
|
||||
}
|
||||
const timed = vehicle.rows.get('TimedAward');
|
||||
if (timed) {
|
||||
const block = emptyBlock('event');
|
||||
setParam(block, 'offenderUnit', { type: 'string', value: vehicle.vehicle });
|
||||
writeAmounts(block, timed.noBonusWp, 0, timed);
|
||||
push('eventTimedAward', block);
|
||||
}
|
||||
const mission = vehicle.rows.get('Mission');
|
||||
if (mission) missionWp += mission.noBonusWp + mission.premAccWp + mission.boosterWp;
|
||||
}
|
||||
for (const [id, events] of lists) container.blocks.push({ name: id, params: [], blocks: events });
|
||||
if (missionWp > 0) setParam(container, 'wpMissionEndAward', { type: 'int', value: missionWp });
|
||||
|
||||
const skillUnits = rewards.vehicles.filter((vehicle) => vehicle.skillBonusExp > 0).map((vehicle) => {
|
||||
const unit = emptyBlock('unit');
|
||||
setParam(unit, 'unit', { type: 'string', value: vehicle.vehicle });
|
||||
setParam(unit, 'bonusLevel', { type: 'int', value: rewards.skillBonusLevel });
|
||||
setParam(unit, 'exp', { type: 'int', value: vehicle.skillBonusExp });
|
||||
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) });
|
||||
}
|
||||
if (summary.repairs.length > 0) {
|
||||
const repaired = emptyBlock('aircraftsRepaired');
|
||||
summary.repairs.forEach((repair, index) => {
|
||||
setParam(repaired, `aname${index}`, { type: 'string', value: repair.vehicle });
|
||||
setParam(repaired, `cost${index}`, { type: 'int', value: repair.cost });
|
||||
});
|
||||
container.blocks.push(repaired);
|
||||
}
|
||||
if (summary.compensation > 0) setParam(container, 'wpExpensesCompensation', { type: 'int', value: summary.compensation });
|
||||
if (summary.affectedWagers.length > 0) {
|
||||
const wagers = emptyBlock('affectedWagers');
|
||||
for (const itemId of summary.affectedWagers) wagers.params.push({ name: 'itemId', value: { type: 'string', value: itemId } });
|
||||
container.blocks.push(wagers);
|
||||
}
|
||||
return container;
|
||||
}
|
||||
|
||||
function itemIdBlock(name: string, itemId: string): BlkBlock {
|
||||
const block = emptyBlock(name);
|
||||
setParam(block, 'itemId', { type: 'string', value: itemId });
|
||||
return block;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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('boosterExpTotal', unit.boosterExpTotal);
|
||||
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 });
|
||||
if (bonuses.premAccWp) setParam(block, 'wpPremAcc', { type: 'int', value: bonuses.premAccWp });
|
||||
if (bonuses.premAccExp) setParam(block, 'expPremAcc', { type: 'int', value: bonuses.premAccExp });
|
||||
if (bonuses.premModExp) setParam(block, 'expPremMod', { type: 'int', value: bonuses.premModExp });
|
||||
if (bonuses.boosterWp) setParam(block, 'wpBooster', { type: 'int', value: bonuses.boosterWp });
|
||||
if (bonuses.boosterExp) setParam(block, 'expBooster', { type: 'int', value: bonuses.boosterExp });
|
||||
}
|
||||
|
||||
function buildSpareBlock(usedSpares: Readonly<Record<string, number>>): BlkBlock | undefined {
|
||||
const entries = Object.entries(usedSpares).filter(([unit, count]) => unit.length > 0 && count > 0);
|
||||
if (entries.length === 0) return undefined;
|
||||
const blk = emptyBlock('spare');
|
||||
for (const [unit, count] of entries) setParam(blk, unit, { type: 'int', value: Math.trunc(count) });
|
||||
return blk;
|
||||
}
|
||||
|
||||
function buildRpEarnedBlock(items: readonly EarnedRpItem[]): BlkBlock | undefined {
|
||||
if (items.length === 0) return undefined;
|
||||
const rpEarned = emptyBlock('rpEarned');
|
||||
items.forEach((item, index) => {
|
||||
setParam(rpEarned, `aname${index}`, { type: 'string', value: item.unit });
|
||||
if (item.modification) setParam(rpEarned, `mname${index}`, { type: 'string', value: item.modification });
|
||||
setParam(rpEarned, `mrp${index}`, { type: 'int', value: item.rp });
|
||||
if (item.excessRp && item.excessRp > 0) setParam(rpEarned, `merp${index}`, { type: 'int', value: item.excessRp });
|
||||
});
|
||||
return rpEarned;
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
/**
|
||||
* Settles a battle report into rewards, row by row as the debriefing shows them (pure: reads no
|
||||
* profile, writes nothing).
|
||||
*
|
||||
* - Combat events: priced by battle-economy.ts against the vehicle the player was in.
|
||||
* - BattleTime: Silver Lions = battleTimeAward x active minutes x activity (offline: the game
|
||||
* files do not say what battleTimeAward measures; the client labels the sibling timedAward
|
||||
* "per minute"); Research Points = active seconds x expForVictoryVersusPerSec (win) or
|
||||
* expForPlayingVersusPerSec x expMul x activity (rank.blk; the per-second rates match the
|
||||
* official numbers).
|
||||
* - TimedAward: timedAward (Silver Lions per minute, client label "max_timed_reward") x active minutes.
|
||||
* - Mission: winK or defeatK (warpoints.blk) x the vehicle's other Silver Lions; a battle the player
|
||||
* left before it ended counts as a defeat.
|
||||
* - Activity: time spent in a vehicle / time in the battle (offline: the online formula is not published).
|
||||
* - Premium account: + (wpMultiplier - 1) Silver Lions and + (xpMultiplier - 1) Research Points on
|
||||
* every row; premium vehicle or talisman: + (goldPlaneExpMul - 1) Research Points (the same terms
|
||||
* as the client's vehicle card, scripts/airinfo.nut).
|
||||
* - Boosters: + the stacked booster percent of each row's base reward (battle-boosters.ts): per
|
||||
* event for combat events, averaged over the vehicle's lives for time rows, and for the mission
|
||||
* reward the share its other rows were boosted with.
|
||||
* - Skill bonus: rank.blk ExpSkillBonus of the mode's economic name, by kills of players (or naval
|
||||
* damage), as a percentage of the Research Points without bonuses.
|
||||
* - Free Research Points: total Research Points / denominateFreeExp (rank.blk; how the server uses
|
||||
* it is inferred from the name, not verified).
|
||||
*/
|
||||
import type { EconomyDifficulty } from '../game-data/datasets/battle-economy.ts';
|
||||
import { NO_BOOSTER, type BoosterPercent, type BoosterRates } from './battle-boosters.ts';
|
||||
import { BattleEconomy, ExpEvent, type DebriefingRow, type PricedEvent } from './battle-economy.ts';
|
||||
import type { BattleReport, ReportedCombatEvent } from './battle-report.ts';
|
||||
|
||||
export type RewardRow = DebriefingRow | 'BattleTime' | 'TimedAward' | 'Mission' | 'Unlocks' | 'ExpensesCompensation';
|
||||
|
||||
export interface RowRewards {
|
||||
count: number;
|
||||
noBonusWp: number;
|
||||
noBonusExp: number;
|
||||
premAccWp: number;
|
||||
premAccExp: number;
|
||||
premModExp: number;
|
||||
boosterWp: number;
|
||||
boosterExp: number;
|
||||
}
|
||||
|
||||
export function emptyRowRewards(): RowRewards {
|
||||
return { count: 0, noBonusWp: 0, noBonusExp: 0, premAccWp: 0, premAccExp: 0, premModExp: 0, boosterWp: 0, boosterExp: 0 };
|
||||
}
|
||||
|
||||
export interface VehicleRewards {
|
||||
readonly vehicle: string;
|
||||
/** Seconds the player spent in this vehicle. */
|
||||
readonly sessionTime: number;
|
||||
readonly rows: ReadonlyMap<RewardRow, RowRewards>;
|
||||
readonly skillBonusExp: number;
|
||||
readonly wpTotal: number;
|
||||
readonly expTotal: number;
|
||||
}
|
||||
|
||||
export interface Bonuses {
|
||||
readonly premAccWp: number;
|
||||
readonly premAccExp: number;
|
||||
readonly premModExp: number;
|
||||
readonly boosterWp: number;
|
||||
readonly boosterExp: number;
|
||||
}
|
||||
|
||||
export interface SettledEvent {
|
||||
readonly event: ReportedCombatEvent;
|
||||
readonly priced: PricedEvent;
|
||||
readonly bonuses: Bonuses;
|
||||
}
|
||||
|
||||
export interface BattleRewards {
|
||||
readonly win: boolean;
|
||||
readonly activity: number;
|
||||
readonly sessionTime: number;
|
||||
readonly battleTime: number;
|
||||
readonly vehicles: readonly VehicleRewards[];
|
||||
readonly events: readonly SettledEvent[];
|
||||
readonly skillBonusLevel: number;
|
||||
readonly wpTotal: number;
|
||||
readonly expTotal: number;
|
||||
readonly expFree: number;
|
||||
}
|
||||
|
||||
export interface RewardContext {
|
||||
readonly difficulty: EconomyDifficulty;
|
||||
/** The mode's economic name, which selects rank.blk ExpSkillBonus. */
|
||||
readonly economicName: string;
|
||||
readonly premiumAccount: boolean;
|
||||
/** Premium vehicle (costGold or premPackAir) or talisman installed. */
|
||||
readonly hasTalisman: (vehicle: string) => boolean;
|
||||
/** The player's active boosters in this battle. */
|
||||
readonly boosters: BoosterRates;
|
||||
}
|
||||
|
||||
export function computeBattleRewards(report: BattleReport, economy: BattleEconomy, ctx: RewardContext): BattleRewards {
|
||||
const win = report.outcome === 'win';
|
||||
const sessionTime = Math.max(0, report.sessionEnd - report.sessionStart);
|
||||
const timeByVehicle = new Map<string, number>();
|
||||
for (const life of report.lives) {
|
||||
if (!economy.vehicle(life.unit)) continue;
|
||||
timeByVehicle.set(life.unit, (timeByVehicle.get(life.unit) ?? 0) + (life.end - life.start));
|
||||
}
|
||||
const battleTime = [...timeByVehicle.values()].reduce((sum, seconds) => sum + seconds, 0);
|
||||
const activity = sessionTime > 0 ? Math.min(1, battleTime / sessionTime) : 0;
|
||||
|
||||
const { data, multipliers } = economy;
|
||||
const bonusesOf = (vehicle: string, wp: number, exp: number, booster: BoosterPercent): Bonuses => ({
|
||||
premAccWp: ctx.premiumAccount ? Math.max(0, Math.round(wp * (data.premiumSilverLionsMul - 1))) : 0,
|
||||
premAccExp: ctx.premiumAccount ? Math.round(exp * (data.premiumResearchMul - 1)) : 0,
|
||||
premModExp: ctx.hasTalisman(vehicle) ? Math.round(exp * (data.talismanResearchMul - 1)) : 0,
|
||||
boosterWp: Math.max(0, Math.round(wp * booster.wp / 100)),
|
||||
boosterExp: Math.max(0, Math.round(exp * booster.rp / 100)),
|
||||
});
|
||||
const rowsByVehicle = new Map<string, Map<RewardRow, RowRewards>>();
|
||||
const add = (vehicle: string, row: RewardRow, count: number, wp: number, exp: number, booster: BoosterPercent): Bonuses => {
|
||||
let rows = rowsByVehicle.get(vehicle);
|
||||
if (!rows) rowsByVehicle.set(vehicle, rows = new Map());
|
||||
let amounts = rows.get(row);
|
||||
if (!amounts) rows.set(row, amounts = emptyRowRewards());
|
||||
const bonuses = bonusesOf(vehicle, wp, exp, booster);
|
||||
amounts.count += count;
|
||||
amounts.noBonusWp += wp;
|
||||
amounts.noBonusExp += exp;
|
||||
amounts.premAccWp += bonuses.premAccWp;
|
||||
amounts.premAccExp += bonuses.premAccExp;
|
||||
amounts.premModExp += bonuses.premModExp;
|
||||
amounts.boosterWp += bonuses.boosterWp;
|
||||
amounts.boosterExp += bonuses.boosterExp;
|
||||
return bonuses;
|
||||
};
|
||||
for (const vehicle of timeByVehicle.keys()) rowsByVehicle.set(vehicle, new Map());
|
||||
|
||||
const events: SettledEvent[] = [];
|
||||
for (const event of report.events) {
|
||||
const priced = economy.price(event.unit, ctx.difficulty, event);
|
||||
if (!priced) continue;
|
||||
events.push({ event, priced, bonuses: add(event.unit, priced.row, priced.count, priced.wp, priced.exp, ctx.boosters.forEvent(event)) });
|
||||
}
|
||||
|
||||
for (const [vehicle, seconds] of timeByVehicle) {
|
||||
const veh = economy.vehicle(vehicle)!;
|
||||
const minutes = seconds / 60;
|
||||
const booster = ctx.boosters.overSpans(report.lives.filter((life) => life.unit === vehicle));
|
||||
const timeWp = Math.round(veh.battleTimeAward[ctx.difficulty] * minutes * activity * multipliers.silverLions);
|
||||
const timeRp = Math.round(seconds * (win ? data.researchPerSecondWin : data.researchPerSecondPlaying)
|
||||
* veh.expMul * activity * multipliers.researchPoints);
|
||||
if (timeWp > 0 || timeRp > 0) add(vehicle, 'BattleTime', Math.round(seconds), timeWp, timeRp, booster);
|
||||
const timedWp = Math.round(veh.timedAward[ctx.difficulty] * minutes * multipliers.silverLions);
|
||||
if (timedWp > 0) add(vehicle, 'TimedAward', 1, timedWp, 0, booster);
|
||||
}
|
||||
for (const [vehicle, rows] of rowsByVehicle) {
|
||||
const earned = [...rows.values()].reduce((sum, amounts) => sum + Math.max(0, amounts.noBonusWp), 0);
|
||||
const boosted = [...rows.values()].reduce((sum, amounts) => sum + amounts.boosterWp, 0);
|
||||
const missionWp = Math.round(earned * (win ? data.winK : data.defeatK));
|
||||
const missionBooster = earned > 0 ? { wp: boosted / earned * 100, rp: 0 } : NO_BOOSTER;
|
||||
if (missionWp > 0) add(vehicle, 'Mission', 1, missionWp, 0, missionBooster);
|
||||
}
|
||||
|
||||
const { level: skillBonusLevel, percent: skillBonusPercent } = skillBonus(report.events, economy, ctx.economicName);
|
||||
const vehicles: VehicleRewards[] = [];
|
||||
for (const [vehicle, rows] of rowsByVehicle) {
|
||||
let wpTotal = 0;
|
||||
let baseExp = 0;
|
||||
let expTotal = 0;
|
||||
for (const amounts of rows.values()) {
|
||||
wpTotal += amounts.noBonusWp + amounts.premAccWp + amounts.boosterWp;
|
||||
baseExp += amounts.noBonusExp;
|
||||
expTotal += amounts.noBonusExp + amounts.premAccExp + amounts.premModExp + amounts.boosterExp;
|
||||
}
|
||||
const skillBonusExp = Math.round(baseExp * skillBonusPercent / 100);
|
||||
expTotal += skillBonusExp;
|
||||
vehicles.push({ vehicle, sessionTime: timeByVehicle.get(vehicle) ?? 0, rows, skillBonusExp, wpTotal, expTotal });
|
||||
}
|
||||
|
||||
const wpTotal = vehicles.reduce((sum, v) => sum + v.wpTotal, 0);
|
||||
const expTotal = vehicles.reduce((sum, v) => sum + v.expTotal, 0);
|
||||
return {
|
||||
win,
|
||||
activity,
|
||||
sessionTime,
|
||||
battleTime,
|
||||
vehicles,
|
||||
events,
|
||||
skillBonusLevel,
|
||||
wpTotal,
|
||||
expTotal,
|
||||
expFree: data.freeResearchDivisor > 0 ? Math.round(expTotal / data.freeResearchDivisor) : 0,
|
||||
};
|
||||
}
|
||||
|
||||
function skillBonus(
|
||||
events: readonly ReportedCombatEvent[],
|
||||
economy: BattleEconomy,
|
||||
economicName: string,
|
||||
): { level: number; percent: number } {
|
||||
const levels = economy.data.skillBonus[economicName] ?? [];
|
||||
let level = 0;
|
||||
let percent = 0;
|
||||
for (const rule of levels) {
|
||||
const value = rule.metric === 'damage'
|
||||
? events.reduce((sum, e) => sum + (e.code === ExpEvent.UNIT_DAMAGE && !e.friendly ? e.damage : 0), 0)
|
||||
: events.filter((e) => isKill(e.code) && e.victimIsPlayer && !e.friendly).length;
|
||||
if (value >= rule.threshold) {
|
||||
level = rule.level;
|
||||
percent = rule.bonusPercent;
|
||||
}
|
||||
}
|
||||
return { level, percent };
|
||||
}
|
||||
|
||||
function isKill(code: number): boolean {
|
||||
return code === ExpEvent.KILL || code === ExpEvent.KILL_GROUND || code === ExpEvent.KILL_HUMAN;
|
||||
}
|
||||
@@ -0,0 +1,423 @@
|
||||
/**
|
||||
* 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/<unit>/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.<country>.exp<Type>: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.
|
||||
* - Destination branch: with "Research of helicopters by playing ground vehicles" on (profile
|
||||
* researchUnits/<country>/destTypeRP<type>, profile/profile-dest-rp.ts) the vehicle's branch is
|
||||
* the destination one: "Research points earned in battles by playing on the ground vehicles of
|
||||
* this country will be fully invested in the research of helicopters. Ground vehicles will not
|
||||
* be researched.", modifications are researched as usual (lang
|
||||
* shop/research_helicopters_by_ground_vehicles_tooltip, _confirm). The rank penalty is taken
|
||||
* against the helicopter target like any other (inferred). Once the destination branch has
|
||||
* nothing left to research the RP goes to the vehicle's own branch again (inferred; the option
|
||||
* cannot be switched on then, shop.nut onMoveExpToHelicoptersChange).
|
||||
* - Crews: an expert crew's RP with the vehicle adds up in expertToAceProgress (the stock tooltip:
|
||||
* "Crew experience with selected vehicle"; the battle's total RP is used, inferred) and lowers
|
||||
* the ace price by the expert_to_ace_cost_reduce stages; at train3Cost_exp the crew becomes ace
|
||||
* ("...or obtained for free when the crew gets {expAmount} with the current vehicle",
|
||||
* crew/qualification/specDescriptionPart; promoted at once, inferred).
|
||||
*
|
||||
* 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';
|
||||
import { isModuleResearched, ModuleStatus, vehicleModuleState } from '../modifications/module-status.ts';
|
||||
import { addExpertToAceRp, clearExpertToAceRp, expertToAceRp, setSpecialization, specializationOf } from '../profile/profile-crew-skills.ts';
|
||||
import { crewForVehicleInCountry } from '../profile/profile-crews.ts';
|
||||
import { destinationRpDomain, 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,
|
||||
researchTarget,
|
||||
setBranchExcessRp,
|
||||
setFinishedResearch,
|
||||
setResearchTarget,
|
||||
} from '../profile/profile-research-targets.ts';
|
||||
import { researchPointsOf } from '../profile/profile-vehicle-research.ts';
|
||||
import {
|
||||
finishedModuleResearch,
|
||||
moduleResearchTarget,
|
||||
setFinishedModuleResearch,
|
||||
setModuleResearchTarget,
|
||||
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';
|
||||
|
||||
const EXPERT = 1;
|
||||
const ACE = 2;
|
||||
|
||||
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 noBonusExp: number;
|
||||
readonly premAccExp: number;
|
||||
readonly premModExp: number;
|
||||
readonly boosterExp: number;
|
||||
readonly skillBonusExp: number;
|
||||
/** The sum of the five. */
|
||||
readonly total: number;
|
||||
}
|
||||
|
||||
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 boosterExpTotal: 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);
|
||||
const owned = ownedVehicles(profile);
|
||||
const units: ResearchPointsUnit[] = [];
|
||||
const rpItems: EarnedRpItem[] = [];
|
||||
const pools = new Map<string, BranchPool>();
|
||||
|
||||
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);
|
||||
}
|
||||
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)!);
|
||||
}
|
||||
|
||||
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 { units, branches, rpItems };
|
||||
}
|
||||
|
||||
/** 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<string>,
|
||||
ctx: RpContext,
|
||||
deps: BattleRpDeps,
|
||||
): Omit<ResearchPointsUnit, 'invModuleExp' | 'moduleTotal' | 'invModuleName'> {
|
||||
const base = {
|
||||
unit: rp.vehicle,
|
||||
noBonusExpTotal: rp.noBonusExp,
|
||||
premAccExpTotal: rp.premAccExp,
|
||||
premModExpTotal: rp.premModExp,
|
||||
boosterExpTotal: rp.boosterExp,
|
||||
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,
|
||||
vehicle: string,
|
||||
ctx: RpContext,
|
||||
): { country: string; type: string } | undefined {
|
||||
const played = research.techTree.vehicle(vehicle);
|
||||
if (played) return { country: played.country, type: redirectedBranch(profile, research, played.country, played.type) };
|
||||
const fallback = fallbackBranch(profile, ctx.country, ctx.requiredClass);
|
||||
return { country: ctx.country, type: redirectedBranch(profile, research, ctx.country, fallback) };
|
||||
}
|
||||
|
||||
function redirectedBranch(profile: BlkBlock, research: ResearchRules, country: string, type: VehicleDomain): VehicleDomain {
|
||||
const destination = destinationRpDomain(profile, country, type);
|
||||
return destination && hasUnresearchedBranchVehicle(profile, research, country, destination) ? destination : type;
|
||||
}
|
||||
|
||||
function fallbackBranch(profile: BlkBlock, country: string, requiredClass: UnitClass): VehicleDomain {
|
||||
const preferred: Readonly<Record<UnitClass, readonly VehicleDomain[]>> = {
|
||||
tank: ['Tank', 'Aircraft', 'Helicopter', 'Boat', 'Ship'],
|
||||
aircraft: ['Aircraft', 'Helicopter', 'Tank', 'Boat', 'Ship'],
|
||||
helicopter: ['Helicopter', 'Aircraft', 'Tank', 'Boat', 'Ship'],
|
||||
ship: ['Ship', 'Boat', 'Aircraft', 'Tank', 'Helicopter'],
|
||||
};
|
||||
return preferred[requiredClass].find((branch) => Boolean(researchTarget(profile, country, branch)))
|
||||
?? 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(
|
||||
profile: BlkBlock,
|
||||
catalogue: EquipmentCatalogue,
|
||||
vehicleName: string,
|
||||
amount: number,
|
||||
): EarnedRpItem | undefined {
|
||||
const equipment = catalogue.vehicle(vehicleName);
|
||||
if (!equipment || amount <= 0) return undefined;
|
||||
const state = vehicleModuleState(profile, equipment);
|
||||
let targetName = moduleResearchTarget(profile, vehicleName);
|
||||
if (targetName && state.statuses.get(targetName) !== ModuleStatus.CAN_RESEARCH) {
|
||||
targetName = '';
|
||||
setModuleResearchTarget(profile, vehicleName, '');
|
||||
}
|
||||
if (!targetName && finishedModuleResearch(profile, vehicleName) === '' && vehicleExcessRp(profile, vehicleName) === 0) {
|
||||
targetName = pickDefaultResearchableModule(equipment, state);
|
||||
if (targetName) setModuleResearchTarget(profile, vehicleName, targetName);
|
||||
}
|
||||
if (!targetName) {
|
||||
if (!hasUnresearchedModification(profile, vehicleName, equipment.modifications)) return undefined;
|
||||
setVehicleExcessRp(profile, vehicleName, vehicleExcessRp(profile, vehicleName) + amount);
|
||||
return { unit: vehicleName, rp: 0, excessRp: amount };
|
||||
}
|
||||
|
||||
const modFacts = catalogue.modification(vehicleName, targetName);
|
||||
if (!modFacts || modFacts.researchPoints <= 0) return undefined;
|
||||
const before = moduleResearchPoints(profile, vehicleName, targetName);
|
||||
const invested = Math.min(amount, Math.max(0, modFacts.researchPoints - before));
|
||||
const leftover = amount - invested;
|
||||
if (invested > 0) setModuleResearchPoints(profile, vehicleName, targetName, before + invested);
|
||||
|
||||
let bankedExcess = 0;
|
||||
if (before + invested >= modFacts.researchPoints) {
|
||||
setModuleResearchTarget(profile, vehicleName, '');
|
||||
setFinishedModuleResearch(profile, vehicleName, targetName);
|
||||
if (hasUnresearchedModification(profile, vehicleName, equipment.modifications)) {
|
||||
if (leftover > 0) {
|
||||
setVehicleExcessRp(profile, vehicleName, vehicleExcessRp(profile, vehicleName) + leftover);
|
||||
bankedExcess = leftover;
|
||||
}
|
||||
} else {
|
||||
setVehicleExcessRp(profile, vehicleName, 0);
|
||||
}
|
||||
}
|
||||
return {
|
||||
unit: vehicleName,
|
||||
modification: targetName,
|
||||
rp: invested,
|
||||
...(bankedExcess > 0 ? { excessRp: bankedExcess } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function hasUnresearchedModification(
|
||||
profile: BlkBlock,
|
||||
vehicle: string,
|
||||
modifications: readonly Parameters<typeof isModuleResearched>[2][],
|
||||
): boolean {
|
||||
return modifications.some((mod) => isResearchable(mod) && !isModuleResearched(profile, vehicle, mod));
|
||||
}
|
||||
|
||||
function hasUnresearchedBranchVehicle(
|
||||
profile: BlkBlock,
|
||||
research: ResearchRules,
|
||||
country: string,
|
||||
branchType: string,
|
||||
): boolean {
|
||||
const owned = ownedVehicles(profile);
|
||||
for (const vehicle of research.techTree.all()) {
|
||||
if (vehicle.kind !== 'research' || vehicle.country !== country || vehicle.type !== branchType) continue;
|
||||
if (!owned.has(vehicle.name) && researchPointsOf(profile, vehicle.name) < vehicle.researchPoints) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function investAceCrewRp(
|
||||
profile: BlkBlock,
|
||||
catalogue: CrewSkillCatalogue,
|
||||
country: string,
|
||||
vehicleName: string,
|
||||
amount: number,
|
||||
): void {
|
||||
const targetRp = catalogue.training(vehicleName)?.aceResearchPoints ?? 0;
|
||||
if (targetRp <= 0) return;
|
||||
const crew = crewForVehicleInCountry(profile, country, vehicleName);
|
||||
if (!crew || specializationOf(crew, vehicleName) !== EXPERT) return;
|
||||
addExpertToAceRp(crew, vehicleName, amount, targetRp);
|
||||
if (expertToAceRp(crew, vehicleName) >= targetRp) {
|
||||
setSpecialization(crew, vehicleName, ACE);
|
||||
clearExpertToAceRp(crew, vehicleName);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
/**
|
||||
* In-memory registry of battle sessions created by `match.enqueue` and settled once by
|
||||
* `cln_wto_finish_battle`.
|
||||
*
|
||||
* Each session gets a non-zero positive 63-bit integer `roomId` formatted as a 16-character
|
||||
* lowercase hexadecimal `sessionId`, matching `userlogs` `roomId:i64` (`aces.exe` `0x1799d30`).
|
||||
*/
|
||||
import { randomBytes } from 'node:crypto';
|
||||
import type { ModeDifficulty, UnitClass } from '../game-modes/catalogue/game-mode-declaration.ts';
|
||||
|
||||
export interface BattleSession {
|
||||
readonly sessionId: string;
|
||||
readonly roomId: bigint;
|
||||
readonly userId: string;
|
||||
readonly modeId: number;
|
||||
readonly modeName: string;
|
||||
readonly economicName: string;
|
||||
readonly difficulty: ModeDifficulty;
|
||||
readonly requiredClass: UnitClass;
|
||||
/** A random battle (the mode's displayType random_battle), as opposed to an event. */
|
||||
readonly randomBattle: boolean;
|
||||
readonly missionName: string;
|
||||
readonly missionPath: string;
|
||||
readonly missionLocName?: string;
|
||||
readonly country: string;
|
||||
readonly startedAtSec: number;
|
||||
settled: boolean;
|
||||
}
|
||||
|
||||
export interface NewBattleSession {
|
||||
readonly userId: string;
|
||||
readonly modeId: number;
|
||||
readonly modeName: string;
|
||||
readonly economicName: string;
|
||||
readonly difficulty: ModeDifficulty;
|
||||
readonly requiredClass: UnitClass;
|
||||
readonly randomBattle: boolean;
|
||||
readonly missionName: string;
|
||||
readonly missionPath: string;
|
||||
readonly missionLocName?: string;
|
||||
readonly country: string;
|
||||
readonly startedAtSec: number;
|
||||
}
|
||||
|
||||
export class BattleSessionStore {
|
||||
readonly #sessions = new Map<string, BattleSession>();
|
||||
readonly #pendingByUser = new Map<string, string>();
|
||||
readonly #maxRetained: number;
|
||||
|
||||
constructor(maxRetained: number) {
|
||||
this.#maxRetained = Math.max(1, maxRetained);
|
||||
}
|
||||
|
||||
create(input: NewBattleSession): BattleSession {
|
||||
const roomId = generateRoomId(this.#sessions);
|
||||
const sessionId = roomId.toString(16).padStart(16, '0');
|
||||
const session: BattleSession = { ...input, sessionId, roomId, settled: false };
|
||||
this.#sessions.set(sessionId, session);
|
||||
this.#pendingByUser.set(input.userId, sessionId);
|
||||
this.#trim();
|
||||
return session;
|
||||
}
|
||||
|
||||
/** Cancel a queued session if the player leaves the queue before entering flight. */
|
||||
cancelPendingForUser(userId: string): void {
|
||||
this.#pendingByUser.delete(userId);
|
||||
}
|
||||
|
||||
isPending(userId: string, sessionId: string): boolean {
|
||||
return this.#pendingByUser.get(userId) === sessionId;
|
||||
}
|
||||
|
||||
clearPending(userId: string, sessionId: string): void {
|
||||
if (this.#pendingByUser.get(userId) === sessionId) {
|
||||
this.#pendingByUser.delete(userId);
|
||||
}
|
||||
}
|
||||
|
||||
findForUser(sessionId: string, userId: string): BattleSession | undefined {
|
||||
const session = this.#sessions.get(sessionId);
|
||||
return session && session.userId === userId ? session : undefined;
|
||||
}
|
||||
|
||||
markSettled(sessionId: string): void {
|
||||
const session = this.#sessions.get(sessionId);
|
||||
if (session) {
|
||||
session.settled = true;
|
||||
this.clearPending(session.userId, sessionId);
|
||||
}
|
||||
}
|
||||
|
||||
#trim(): void {
|
||||
while (this.#sessions.size > this.#maxRetained) {
|
||||
const oldestKey = this.#sessions.keys().next().value;
|
||||
if (oldestKey === undefined) break;
|
||||
this.#sessions.delete(oldestKey);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function generateRoomId(existing: ReadonlyMap<string, BattleSession>): bigint {
|
||||
for (;;) {
|
||||
const raw = randomBytes(8).readBigUInt64BE(0) & 0x7fffffffffffffffn;
|
||||
const roomId = raw === 0n ? 1n : raw;
|
||||
const hex = roomId.toString(16).padStart(16, '0');
|
||||
if (!existing.has(hex)) return roomId;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
/**
|
||||
* Static spawn scores for the player's Ground Realistic lineup and support vehicles.
|
||||
* The parameter order and BR conversion follow globals/ranks_common_shared.nut
|
||||
* (get_spawn_score_param, get_unit_blk_economic_rank_by_mode, calcBattleRatingFromRank).
|
||||
* The linear BR discount and ten-point rounding are inferred from the data and observed
|
||||
* costs. Changing weapon and ammunition multipliers remain the stock client's job.
|
||||
*/
|
||||
import type { SpawnScoreRules } from '../game-data/datasets/battle-spawn-rules.ts';
|
||||
import type { CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.ts';
|
||||
import { vehicleTypeOfClass, type VehicleType } from '../research/vehicle-types.ts';
|
||||
import type { ExtraBattleSlot } from './battle-extra-slots.ts';
|
||||
import { vehicleMrank } from './battle-ranks.ts';
|
||||
|
||||
export interface BattleSpawnScore {
|
||||
readonly maxScore: number;
|
||||
readonly unitCosts: Readonly<Record<string, number>>;
|
||||
}
|
||||
|
||||
/** Spawn score types used by ranks_common_shared.nut (boat and ship share one type). */
|
||||
const SPAWN_TYPES: Readonly<Record<VehicleType, string>> = {
|
||||
Aircraft: 'Air',
|
||||
Helicopter: 'Air',
|
||||
Tank: 'Tank',
|
||||
Ship: 'Ship',
|
||||
Boat: 'Ship',
|
||||
Human: 'Human',
|
||||
Transport: 'Transport',
|
||||
};
|
||||
|
||||
export function battleSpawnScore(
|
||||
lineup: readonly string[],
|
||||
extraSlots: readonly ExtraBattleSlot[],
|
||||
sessionMaxMrank: number,
|
||||
vehicles: ReadonlyMap<string, CatalogueVehicle>,
|
||||
rules: SpawnScoreRules,
|
||||
): BattleSpawnScore {
|
||||
const override = rules.overrides.find(({ minMrank, maxMrank }) => sessionMaxMrank >= minMrank && sessionMaxMrank <= maxMrank);
|
||||
const params = {
|
||||
...rules.common,
|
||||
...rules.tankHistorical.classCosts,
|
||||
...rules.tankHistorical.parameters,
|
||||
...override?.classCosts,
|
||||
...override?.parameters,
|
||||
};
|
||||
const base = params.base_respawn_points_coef ?? 450;
|
||||
const maxScore = Math.max(0, Math.round(base * (params.maxRespawnPointsMul ?? 1)));
|
||||
const maxBrDiff = params.max_br_diff ?? 1;
|
||||
const sessionBr = battleRating(sessionMaxMrank);
|
||||
const unitCosts: Record<string, number> = {};
|
||||
for (const unit of new Set([...lineup, ...extraSlots.map((slot) => slot.unitName)])) {
|
||||
if (unit === '') continue;
|
||||
const vehicle = vehicles.get(unit);
|
||||
const unitClass = vehicle?.unitClass || 'exp_zero';
|
||||
const multiplier = params[unit] ?? params[unitClass] ?? 0;
|
||||
if (multiplier <= 0) {
|
||||
unitCosts[unit] = 0;
|
||||
continue;
|
||||
}
|
||||
const type = vehicleTypeOfClass(unitClass);
|
||||
const spawnType = unitClass === 'exp_ai_sam_tracking_radar' ? 'Tank' : type ? SPAWN_TYPES[type] : 'Invalid';
|
||||
const rank = vehicle ? vehicleMrank(vehicle, 'realistic', 'tank') : sessionMaxMrank;
|
||||
const brDiff = Math.min(Math.max(0, sessionBr - battleRating(rank)), maxBrDiff);
|
||||
const discount = maxBrDiff > 0 ? (params[`br_diff_mul_${spawnType}`] ?? 0) * brDiff / maxBrDiff : 0;
|
||||
unitCosts[unit] = Math.max(1, Math.round(base * multiplier * (1 - discount) / 10) * 10);
|
||||
}
|
||||
for (const { unitName, persistentCost } of extraSlots) {
|
||||
if (persistentCost !== undefined && persistentCost > 0) unitCosts[unitName] = persistentCost;
|
||||
}
|
||||
return { maxScore, unitCosts };
|
||||
}
|
||||
|
||||
function battleRating(mrank: number): number {
|
||||
return Math.round((mrank / 3 + 1) * 10) / 10;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
/**
|
||||
* The `EULT_NEW_STREAK` user logs of a settled battle's awards. The stock debriefing lists them
|
||||
* on its left (scripts/debriefing/debriefingModal.nut awardsListsConfig.streaks: type
|
||||
* EULT_NEW_STREAK, unlockType UNLOCKABLE_STREAK) and builds each from the body's unlockId,
|
||||
* unlockType, stage, wp and exp (scripts/unlocks/unlocks.nut buildLogUnlockData).
|
||||
*
|
||||
* Constants registered by aces.exe 2.61.0.37: EULT_NEW_STREAK = 18 (0x1a5577f),
|
||||
* UNLOCKABLE_STREAK = 21 (0x1a55185).
|
||||
*/
|
||||
import type { BlkBlock, BlkParam } from '@wto/blk';
|
||||
import { appendUserLog } from '../profile/profile-trophies-log.ts';
|
||||
import { serverTimeNow, serverTimeToUnixSeconds } from '../profile/server-time.ts';
|
||||
import type { BattleSession } from './battle-session-store.ts';
|
||||
import type { AwardedStreak } from './battle-streaks.ts';
|
||||
|
||||
const EULT_NEW_STREAK = 18;
|
||||
const UNLOCKABLE_STREAK = 21;
|
||||
|
||||
export function appendStreakLogs(profile: BlkBlock, session: Pick<BattleSession, 'roomId'>, streaks: readonly AwardedStreak[]): void {
|
||||
const timeSec = serverTimeToUnixSeconds(serverTimeNow());
|
||||
for (const streak of streaks) {
|
||||
const bodyParams: BlkParam[] = [
|
||||
{ name: 'unlockId', value: { type: 'string', value: streak.id } },
|
||||
{ name: 'unlockType', value: { type: 'int', value: UNLOCKABLE_STREAK } },
|
||||
...(streak.stage !== undefined ? [{ name: 'stage', value: { type: 'int' as const, value: streak.stage } }] : []),
|
||||
{ name: 'wp', value: { type: 'int', value: streak.wp } },
|
||||
{ name: 'exp', value: { type: 'int', value: streak.exp } },
|
||||
];
|
||||
appendUserLog(profile, { type: EULT_NEW_STREAK, timeSec, roomId: session.roomId, bodyParams });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,471 @@
|
||||
/**
|
||||
* Battle awards ("streaks", char.vromfs.bin config/unlocks.blk, dataset battle-streaks): which of
|
||||
* them the local player earned, from the facts of the battle (pure; online the battle server does
|
||||
* this and the client only shows the result).
|
||||
*
|
||||
* The meaning of each mode comes from the game's own award texts (lang.vromfs.bin, "streaks/<id>/desc"),
|
||||
* e.g. multi_kill_air "Destroyed %d player vehicles in a row" with mode killedPlayersTimed and
|
||||
* delay 10/30/30 s, heroic_fighter "Destroyed the most aircraft" with minVal 12 and mul 1/2/3,
|
||||
* trophy_near_fighter "... If several players have equal number ..., the award is given to the
|
||||
* one with a bigger score". Where the texts leave a point open the choice is marked "inferred".
|
||||
*
|
||||
* Supported modes:
|
||||
* killedPlayersTimed, killedGroundTimed kills in a chain, each within `delay` of the previous;
|
||||
* ground: AI ground units (ships when isShip)
|
||||
* killedPlayers kills of players, `mul` per kill, `inRow` = no death between
|
||||
* assistUnits, assistAir, assistPlayers assists, `inRow` as above
|
||||
* captures zone captures
|
||||
* missionsWon after the battle: the battle is won
|
||||
* firstKill the battle's first kill of an enemy (HUD kill log)
|
||||
* killLastOffender, killLastTeamOffender killing the enemy who last killed you / a teammate
|
||||
* killedAirBest, killedGroundBest,
|
||||
* killedPlayersBest, assistAirBest after the battle: the most of it on the scoreboard
|
||||
* (not those limited by battle rating, e.g. heroic_punisher)
|
||||
* unlocks `num` of the listed awards earned in the battle (all when
|
||||
* num is missing, as scripts unlocksConditions.nut counts)
|
||||
* killStreakNuclearSuccess each explosion of the local player's nuclear bomb
|
||||
* (killStreak_bomber_nuclear_success)
|
||||
* Not supported (the facts are not reported): finalBlow, lastManStanding, killWithoutHit,
|
||||
* hitWithoutDeath, killWithoutMiss, landings, scout / repair / extinguish help, squad awards,
|
||||
* other kill-streak support vehicles, shell interception, specified naval damage, event missions; and
|
||||
* any award with a condition on weapon, distance, head shot, scouting, death reason, offender
|
||||
* flags, unit tags or the awards' platform-free "customOnline" / "mission". Their awards are
|
||||
* never given.
|
||||
*
|
||||
* In a LocalMP battle the other side's crews are AI-driven MPlayers standing in for players; they
|
||||
* count as players (offline design), mission AI units do not.
|
||||
*/
|
||||
import type { EconomyDifficulty } from '../game-data/datasets/battle-economy.ts';
|
||||
import type { StreakCondition, StreakDefinition, StreakParams } from '../game-data/datasets/battle-streaks.ts';
|
||||
import type { CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.ts';
|
||||
import type { UnitClass } from '../game-modes/catalogue/game-mode-declaration.ts';
|
||||
import { economyDifficulty, ExpEvent, type BattleEconomy } from './battle-economy.ts';
|
||||
import { vehicleMrank } from './battle-ranks.ts';
|
||||
import type { BattleLife, BattleOutcomeKind, FeedKill, ReportedCombatEvent, ScoreboardPlayer } from './battle-report.ts';
|
||||
import type { BattleSession } from './battle-session-store.ts';
|
||||
|
||||
export interface StreakFacts {
|
||||
readonly events: readonly ReportedCombatEvent[];
|
||||
readonly lives: readonly BattleLife[];
|
||||
readonly feed: readonly FeedKill[];
|
||||
/** Mission times at which the local player's nuclear bombs exploded. */
|
||||
readonly nuclearStrikes: readonly number[];
|
||||
readonly localPlayerId: number;
|
||||
readonly localTeam: number;
|
||||
/** The final scoreboard; absent while the battle runs (after-battle awards are then skipped). */
|
||||
readonly players?: readonly ScoreboardPlayer[];
|
||||
/** How the battle ended; absent while it runs. */
|
||||
readonly outcome?: BattleOutcomeKind;
|
||||
readonly sessionEnd: number;
|
||||
}
|
||||
|
||||
export interface StreakContext {
|
||||
readonly difficulty: EconomyDifficulty;
|
||||
/** The mission's ediff (unit type x 3 + difficulty), which conditions "missionType" list. */
|
||||
readonly ediff: number;
|
||||
readonly missionName: string;
|
||||
/** wpcost.blk unitClass of a vehicle. */
|
||||
readonly classOf: (vehicle: string) => string | undefined;
|
||||
/** Battle rating of a vehicle in this battle's mode. */
|
||||
readonly battleRatingOf: (vehicle: string) => number | undefined;
|
||||
}
|
||||
|
||||
export interface AwardedStreak {
|
||||
readonly id: string;
|
||||
/** A hidden award: not shown or logged, only judged for wagers that name it. */
|
||||
readonly hidden: boolean;
|
||||
/** Stage of a multi-stage award (0 = the first), undefined for a single-stage one. */
|
||||
readonly stage?: number;
|
||||
/** The number the award text shows (%d): the stage's count. */
|
||||
readonly stageParam: number;
|
||||
readonly time: number;
|
||||
readonly wp: number;
|
||||
readonly exp: number;
|
||||
/** Unique within the battle: id and occurrence. */
|
||||
readonly key: string;
|
||||
}
|
||||
|
||||
const DIFFICULTY_INDEX: Readonly<Record<EconomyDifficulty, 0 | 1 | 2>> = { arcade: 0, historical: 1, simulation: 2 };
|
||||
const MUL_NAMES = ['mulArcade', 'mulRealistic', 'mulHardcore'] as const;
|
||||
const KILL_CODES: ReadonlySet<number> = new Set([ExpEvent.KILL, ExpEvent.KILL_GROUND, ExpEvent.KILL_HUMAN]);
|
||||
const SATISFIED_CONDITIONS = new Set(['online', 'playerPlatform', '', 'offenderIsPlayerControlled']);
|
||||
/** Tolerance of the BR thresholds written as 2.0000999 etc. in unlocks.blk. */
|
||||
const BR_EPSILON = 0.001;
|
||||
|
||||
type Group = 'air' | 'ground' | 'naval' | 'human';
|
||||
|
||||
const CLASS_GROUP: Readonly<Record<string, Group>> = {
|
||||
exp_fighter: 'air', exp_bomber: 'air', exp_assault: 'air', exp_helicopter: 'air',
|
||||
exp_tank: 'ground', exp_heavy_tank: 'ground', exp_tank_destroyer: 'ground', exp_SPAA: 'ground',
|
||||
exp_ship: 'naval', exp_destroyer: 'naval', exp_cruiser: 'naval', exp_torpedo_boat: 'naval', exp_gun_boat: 'naval',
|
||||
exp_torpedo_gun_boat: 'naval', exp_submarine_chaser: 'naval', exp_naval_ferry_barge: 'naval',
|
||||
exp_human: 'human',
|
||||
};
|
||||
|
||||
/** The unitType names conditions use, by the wpcost.blk classes they cover. */
|
||||
const UNIT_TYPE_CLASSES: Readonly<Record<string, readonly string[]>> = {
|
||||
aircraft: ['exp_fighter', 'exp_bomber', 'exp_assault'],
|
||||
typeFighter: ['exp_fighter'],
|
||||
typeBomber: ['exp_bomber'],
|
||||
typeStormovik: ['exp_assault'],
|
||||
typeHelicopter: ['exp_helicopter'],
|
||||
tank: ['exp_tank', 'exp_heavy_tank', 'exp_tank_destroyer', 'exp_SPAA'],
|
||||
ship: ['exp_ship', 'exp_destroyer', 'exp_cruiser'],
|
||||
boat: ['exp_torpedo_boat', 'exp_gun_boat', 'exp_torpedo_gun_boat', 'exp_submarine_chaser', 'exp_naval_ferry_barge'],
|
||||
human: ['exp_human'],
|
||||
};
|
||||
|
||||
/** A kill or assist of the local player, with what conditions look at. */
|
||||
interface Action {
|
||||
readonly time: number;
|
||||
readonly unit: string;
|
||||
readonly victim: string;
|
||||
readonly victimClass: string;
|
||||
readonly victimIsPlayer: boolean;
|
||||
}
|
||||
|
||||
export function evaluateStreaks(definitions: readonly StreakDefinition[], facts: StreakFacts, ctx: StreakContext): AwardedStreak[] {
|
||||
const diff = DIFFICULTY_INDEX[ctx.difficulty];
|
||||
const awarded: AwardedStreak[] = [];
|
||||
const occurrences = new Map<string, number>();
|
||||
const award = (def: StreakDefinition, time: number, stageParam: number, stage?: number): void => {
|
||||
const n = occurrences.get(def.id) ?? 0;
|
||||
occurrences.set(def.id, n + 1);
|
||||
const reward = rewardOf(def, stage, diff);
|
||||
awarded.push({ id: def.id, hidden: def.hidden, ...(stage !== undefined ? { stage } : {}), stageParam, time, ...reward, key: `${def.id}#${n}` });
|
||||
};
|
||||
|
||||
const deaths = facts.lives.filter((life) => life.died).map((life) => life.end);
|
||||
const kills = actions(facts.events, (e) => KILL_CODES.has(e.code) && !e.friendly);
|
||||
const assists = actions(facts.events, (e) => e.code === ExpEvent.ASSIST && !e.friendly);
|
||||
const captures = facts.events.filter((e) => e.code === ExpEvent.CAPTURE_ZONE).map((e) => e.time);
|
||||
const deferred: StreakDefinition[] = [];
|
||||
|
||||
for (const def of definitions) {
|
||||
const mode = def.mode;
|
||||
if (!mode || !mode.conditions.every((c) => isSupportedCondition(c))) continue;
|
||||
if (def.afterFlight && !facts.players) continue;
|
||||
if (!mode.conditions.every((c) => battleConditionHolds(c, ctx))) continue;
|
||||
const p = mode.params;
|
||||
const actionHolds = (a: Action): boolean => mode.conditions.every((c) => actionConditionHolds(c, a, ctx));
|
||||
switch (mode.type) {
|
||||
case 'killedPlayersTimed':
|
||||
chainAwards(def, kills.filter((a) => a.victimIsPlayer && actionHolds(a)), delayOf(p, diff), award);
|
||||
break;
|
||||
case 'killedGroundTimed':
|
||||
chainAwards(def, kills.filter((a) => !a.victimIsPlayer && isGroundTarget(a, p) && actionHolds(a)), delayOf(p, diff), award);
|
||||
break;
|
||||
case 'killedPlayers':
|
||||
countAwards(def, kills.filter((a) => a.victimIsPlayer && actionHolds(a)).map((a) => a.time), mulOf(p, diff), flag(p, 'inRow'), deaths, award);
|
||||
break;
|
||||
case 'assistUnits':
|
||||
case 'assistPlayers':
|
||||
countAwards(def, assists.filter((a) => a.victimIsPlayer && actionHolds(a)).map((a) => a.time), 1, flag(p, 'inRow'), deaths, award);
|
||||
break;
|
||||
case 'assistAir':
|
||||
countAwards(def, assists.filter((a) => groupOf(a.victimClass) === 'air' && actionHolds(a)).map((a) => a.time), mulOf(p, diff), flag(p, 'inRow'), deaths, award);
|
||||
break;
|
||||
case 'captures':
|
||||
countAwards(def, captures, 1, flag(p, 'inRow'), deaths, award);
|
||||
break;
|
||||
case 'missionsWon':
|
||||
if (facts.outcome === 'win') award(def, facts.sessionEnd, 1);
|
||||
break;
|
||||
case 'killStreakNuclearSuccess':
|
||||
for (const time of facts.nuclearStrikes) award(def, time, 1);
|
||||
break;
|
||||
case 'firstKill': {
|
||||
const first = facts.feed.find((k) => k.killerTeam !== k.victimTeam);
|
||||
if (first && first.killer === facts.localPlayerId) award(def, first.time, 1);
|
||||
break;
|
||||
}
|
||||
case 'killLastOffender':
|
||||
case 'killLastTeamOffender':
|
||||
avengeAwards(def, facts, mode.type === 'killLastOffender', award);
|
||||
break;
|
||||
case 'killedAirBest':
|
||||
case 'killedGroundBest':
|
||||
case 'killedPlayersBest':
|
||||
case 'assistAirBest':
|
||||
if (facts.players && mode.conditions.every((c) => bestConditionHolds(c, ctx))) bestAward(def, facts, diff, award);
|
||||
break;
|
||||
case 'unlocks':
|
||||
deferred.push(def);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
for (const def of deferred) {
|
||||
const listed = (def.mode?.params.unlock ?? []).map(String);
|
||||
const earned = listed.filter((id) => occurrences.has(id)).length;
|
||||
if (listed.length > 0 && earned >= (numberParam(def.mode?.params ?? {}, 'num') ?? listed.length)) award(def, facts.sessionEnd, 1);
|
||||
}
|
||||
return awarded.sort((a, b) => a.time - b.time);
|
||||
}
|
||||
|
||||
function actions(events: readonly ReportedCombatEvent[], keep: (e: ReportedCombatEvent) => boolean): Action[] {
|
||||
return events.filter(keep).map((e) => ({
|
||||
time: e.time, unit: e.unit, victim: e.victim, victimClass: e.expClass, victimIsPlayer: e.victimIsPlayer,
|
||||
})).sort((a, b) => a.time - b.time);
|
||||
}
|
||||
|
||||
/** Chains of actions each within `delay` seconds of the previous; one award per stage reached. */
|
||||
function chainAwards(def: StreakDefinition, list: readonly Action[], delay: number, award: AwardFn): void {
|
||||
let length = 0;
|
||||
let last = -Infinity;
|
||||
for (const action of list) {
|
||||
length = action.time - last <= delay ? length + 1 : 1;
|
||||
last = action.time;
|
||||
stageAward(def, length, action.time, award);
|
||||
}
|
||||
}
|
||||
|
||||
/** A running count (reset by a death when `inRow`); one award per stage or per `num` reached. */
|
||||
function countAwards(
|
||||
def: StreakDefinition,
|
||||
times: readonly number[],
|
||||
mul: number,
|
||||
inRow: boolean,
|
||||
deaths: readonly number[],
|
||||
award: AwardFn,
|
||||
): void {
|
||||
let count = 0;
|
||||
let deathIndex = 0;
|
||||
for (const time of times) {
|
||||
if (inRow) {
|
||||
while (deathIndex < deaths.length && deaths[deathIndex]! <= time) {
|
||||
deathIndex++;
|
||||
count = 0;
|
||||
}
|
||||
}
|
||||
const before = count;
|
||||
count += mul;
|
||||
if (def.multiStage) {
|
||||
for (let reached = Math.floor(before) + 1; reached <= Math.floor(count); reached++) stageAward(def, reached, time, award);
|
||||
} else {
|
||||
const num = numOf(def);
|
||||
if (num > 0 && Math.floor(count / num) > Math.floor(before / num)) award(def, time, num);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Multi-stage: stage n at count = stage.param + n. Single-stage: once per `num` reached. */
|
||||
function stageAward(def: StreakDefinition, count: number, time: number, award: AwardFn): void {
|
||||
if (def.multiStage) {
|
||||
const first = def.stage?.param ?? 1;
|
||||
if (count >= first) award(def, time, count, count - first);
|
||||
return;
|
||||
}
|
||||
const num = numOf(def);
|
||||
if (num > 0 && count === num) award(def, time, num);
|
||||
}
|
||||
|
||||
function avengeAwards(def: StreakDefinition, facts: StreakFacts, self: boolean, award: AwardFn): void {
|
||||
let offender: number | undefined;
|
||||
for (const kill of facts.feed) {
|
||||
if (kill.killer === facts.localPlayerId && kill.victimTeam !== facts.localTeam && offender !== undefined && kill.victim === offender) {
|
||||
stageAward(def, 1, kill.time, award);
|
||||
offender = undefined;
|
||||
continue;
|
||||
}
|
||||
const victimIsOurs = self
|
||||
? kill.victim === facts.localPlayerId
|
||||
: kill.victimTeam === facts.localTeam && kill.victim !== facts.localPlayerId;
|
||||
if (victimIsOurs && kill.killerTeam !== facts.localTeam && kill.killer >= 0) offender = kill.killer;
|
||||
}
|
||||
}
|
||||
|
||||
/** Scoreboard counter each "Best" mode ranks players by. */
|
||||
function bestValueOf(def: StreakDefinition, player: ScoreboardPlayer): number {
|
||||
const mode = def.mode!;
|
||||
const aiOnly = mode.conditions.some((c) => c.type === 'targetIsPlayer' && c.params.includePlayers?.[0] === false);
|
||||
const humans = flag(mode.params, 'includeHumans');
|
||||
switch (mode.type) {
|
||||
case 'killedAirBest':
|
||||
return aiOnly ? player.aiKills : player.kills;
|
||||
case 'killedGroundBest':
|
||||
if (humans) return player.humanKills;
|
||||
if (flag(mode.params, 'isShip')) return aiOnly ? player.aiNavalKills : player.navalKills;
|
||||
return aiOnly ? player.aiGroundKills : player.groundKills;
|
||||
case 'killedPlayersBest':
|
||||
return humans ? player.humanKills : player.kills + player.groundKills + player.navalKills + player.humanKills;
|
||||
default:
|
||||
return player.assists;
|
||||
}
|
||||
}
|
||||
|
||||
/** The player with the most of the counter (ties: the higher score) is the local player, within minVal / maxVal. */
|
||||
function bestAward(def: StreakDefinition, facts: StreakFacts, diff: 0 | 1 | 2, award: AwardFn): void {
|
||||
const p = def.mode!.params;
|
||||
const mul = mulOf(p, diff);
|
||||
const noDeaths = flag(p, 'noDeaths');
|
||||
const candidates = facts.players!.filter((player) => !noDeaths || player.deaths === 0);
|
||||
let best: ScoreboardPlayer | undefined;
|
||||
for (const player of candidates) {
|
||||
const value = bestValueOf(def, player);
|
||||
const bestValue = best ? bestValueOf(def, best) : -1;
|
||||
if (value > bestValue || (value === bestValue && best && player.score > best.score)) best = player;
|
||||
}
|
||||
if (!best || best.id !== facts.localPlayerId) return;
|
||||
const value = bestValueOf(def, best) * mul;
|
||||
if (value <= 0) return;
|
||||
const minVal = numberParam(p, 'minVal');
|
||||
const maxVal = numberParam(p, 'maxVal');
|
||||
if (minVal !== undefined && value < minVal) return;
|
||||
if (maxVal !== undefined && value > maxVal) return;
|
||||
award(def, facts.sessionEnd, 1);
|
||||
}
|
||||
|
||||
type AwardFn = (def: StreakDefinition, time: number, stageParam: number, stage?: number) => void;
|
||||
|
||||
/**
|
||||
* Reward of an award. Single-stage: amount_warpoints / amount_exp. Multi-stage (inferred: the
|
||||
* formula is server-side): the first stage pays stage.amount_*, each later stage n pays
|
||||
* wpA + wpB x n (expA + expB x n).
|
||||
*/
|
||||
function rewardOf(def: StreakDefinition, stage: number | undefined, diff: 0 | 1 | 2): { wp: number; exp: number } {
|
||||
if (stage === undefined) return { wp: def.wp[diff], exp: def.exp[diff] };
|
||||
if (stage === 0 && def.stage) return { wp: def.stage.wp[diff], exp: def.stage.exp[diff] };
|
||||
return { wp: Math.round(def.wpA[diff] + def.wpB[diff] * stage), exp: Math.round(def.expA[diff] + def.expB[diff] * stage) };
|
||||
}
|
||||
|
||||
function isSupportedCondition(condition: StreakCondition): boolean {
|
||||
return SATISFIED_CONDITIONS.has(condition.type) || [
|
||||
'targetIsPlayer', 'missionType', 'missionPostfix', 'targetType', 'offenderType', 'higherBR', 'sameUnitType',
|
||||
].includes(condition.type);
|
||||
}
|
||||
|
||||
/** Conditions on the battle itself. */
|
||||
function battleConditionHolds(condition: StreakCondition, ctx: StreakContext): boolean {
|
||||
const p = condition.params;
|
||||
switch (condition.type) {
|
||||
case 'missionType':
|
||||
return (p.missionType ?? []).includes(ctx.ediff);
|
||||
case 'missionPostfix': {
|
||||
const listed = (p.postfix ?? []).some((postfix) => ctx.missionName.endsWith(String(postfix)));
|
||||
return p.allowed?.[0] === false ? !listed : listed;
|
||||
}
|
||||
default:
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/** Conditions on one kill or assist. */
|
||||
function actionConditionHolds(condition: StreakCondition, action: Action, ctx: StreakContext): boolean {
|
||||
const p = condition.params;
|
||||
switch (condition.type) {
|
||||
case 'targetIsPlayer':
|
||||
return action.victimIsPlayer ? p.includePlayers?.[0] !== false : p.includeAI?.[0] === true;
|
||||
case 'targetType':
|
||||
return matchesUnitType(action.victimClass, p.unitType ?? []);
|
||||
case 'offenderType':
|
||||
return matchesUnitType(ctx.classOf(action.unit) ?? '', p.unitType ?? []);
|
||||
case 'sameUnitType':
|
||||
return groupOf(action.victimClass) !== undefined && groupOf(action.victimClass) === groupOf(ctx.classOf(action.unit) ?? '');
|
||||
case 'higherBR': {
|
||||
const own = ctx.battleRatingOf(action.unit);
|
||||
const victim = ctx.battleRatingOf(action.victim);
|
||||
if (own === undefined || victim === undefined) return false;
|
||||
const diff = victim - own;
|
||||
const min = numberParam(p, 'diffBR') ?? 0;
|
||||
const max = numberParam(p, 'diffBRMax');
|
||||
return diff >= min - BR_EPSILON && (max === undefined || diff <= max + BR_EPSILON);
|
||||
}
|
||||
default:
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A "Best" award ranks players by a scoreboard counter, so only conditions the counters reflect
|
||||
* can hold: the target kind (players / AI, humans) picks the counter (bestValueOf), and the
|
||||
* offender's type holds when it is the mission's unit type. Per-kill conditions (battle rating
|
||||
* difference, target or vehicle type of each kill) cannot be checked for other players.
|
||||
*/
|
||||
function bestConditionHolds(condition: StreakCondition, ctx: StreakContext): boolean {
|
||||
switch (condition.type) {
|
||||
case 'targetIsPlayer':
|
||||
return true;
|
||||
case 'targetType':
|
||||
return (condition.params.unitType ?? []).every((type) => type === 'human');
|
||||
case 'offenderType':
|
||||
return (condition.params.unitType ?? []).some((type) => MISSION_UNIT_TYPES[Math.floor(ctx.ediff / 3)]?.includes(String(type)));
|
||||
case 'higherBR':
|
||||
case 'sameUnitType':
|
||||
return false;
|
||||
default:
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/** The unitType names of each ediff group (0 air, 1 ground, 2 naval, 3 helicopter). */
|
||||
const MISSION_UNIT_TYPES: readonly (readonly string[])[] = [['aircraft'], ['tank'], ['ship', 'boat'], ['typeHelicopter']];
|
||||
|
||||
function isGroundTarget(action: Action, p: StreakParams): boolean {
|
||||
const group = groupOf(action.victimClass);
|
||||
if (flag(p, 'isShip')) return group === 'naval';
|
||||
return group === 'ground' || (group === 'human' && flag(p, 'includeHumans'));
|
||||
}
|
||||
|
||||
function matchesUnitType(expClass: string, unitTypes: readonly unknown[]): boolean {
|
||||
return unitTypes.some((type) => UNIT_TYPE_CLASSES[String(type)]?.includes(expClass));
|
||||
}
|
||||
|
||||
function groupOf(expClass: string): Group | undefined {
|
||||
return CLASS_GROUP[expClass];
|
||||
}
|
||||
|
||||
function delayOf(p: StreakParams, diff: 0 | 1 | 2): number {
|
||||
const values = (p.delay ?? []).filter((v): v is number => typeof v === 'number');
|
||||
return values[diff] ?? values[0] ?? 0;
|
||||
}
|
||||
|
||||
/** mulArcade / mulRealistic / mulHardcore of the difficulty; 1 when absent. */
|
||||
function mulOf(p: StreakParams, diff: 0 | 1 | 2): number {
|
||||
return numberParam(p, MUL_NAMES[diff]) ?? 1;
|
||||
}
|
||||
|
||||
function numOf(def: StreakDefinition): number {
|
||||
return numberParam(def.mode?.params ?? {}, 'num') ?? 1;
|
||||
}
|
||||
|
||||
function numberParam(p: StreakParams, name: string): number | undefined {
|
||||
const value = p[name]?.[0];
|
||||
return typeof value === 'number' ? value : undefined;
|
||||
}
|
||||
|
||||
function flag(p: StreakParams, name: string): boolean {
|
||||
return p[name]?.[0] === true;
|
||||
}
|
||||
|
||||
|
||||
/** ediff of the mission's unit type (unit type x 3 + difficulty, as unlocks.blk "missionType" lists it). */
|
||||
const EDIFF_BASE: Readonly<Record<UnitClass, number>> = { aircraft: 0, tank: 3, ship: 6, helicopter: 9 };
|
||||
|
||||
/** The battle awards of the game data, bound to the vehicles they are judged on. */
|
||||
export class BattleStreaks {
|
||||
readonly #definitions: readonly StreakDefinition[];
|
||||
readonly #vehicles: ReadonlyMap<string, CatalogueVehicle>;
|
||||
readonly #economy: BattleEconomy;
|
||||
|
||||
constructor(definitions: readonly StreakDefinition[], vehicles: readonly CatalogueVehicle[], economy: BattleEconomy) {
|
||||
this.#definitions = definitions;
|
||||
this.#vehicles = new Map(vehicles.map((vehicle) => [vehicle.name, vehicle]));
|
||||
this.#economy = economy;
|
||||
}
|
||||
|
||||
evaluate(facts: StreakFacts, session: Pick<BattleSession, 'difficulty' | 'requiredClass' | 'missionName'>): AwardedStreak[] {
|
||||
const difficulty = economyDifficulty(session.difficulty);
|
||||
return evaluateStreaks(this.#definitions, facts, {
|
||||
difficulty,
|
||||
ediff: EDIFF_BASE[session.requiredClass] + DIFFICULTY_INDEX[difficulty],
|
||||
missionName: session.missionName,
|
||||
classOf: (vehicle) => this.#economy.vehicle(vehicle)?.unitClass,
|
||||
battleRatingOf: (vehicle) => {
|
||||
const known = this.#vehicles.get(vehicle);
|
||||
return known ? vehicleMrank(known, session.difficulty, session.requiredClass) / 3 + 1 : undefined;
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
/**
|
||||
* The mission support planes (gameplay.blk missionSupportPlane, the nuclear carriers: the unit the
|
||||
* action bar launches and the lineup's support plane slot spawns) earn nothing in a battle: online
|
||||
* the time flown in one and its kills are not settled, other aircraft are (player observation of
|
||||
* the live game). Their lives and combat events are taken out of the battle facts before awards
|
||||
* and the settlement; the nuclear strike itself is a separate fact and stays.
|
||||
*/
|
||||
import type { BattleSpawnRulesData } from '../game-data/datasets/battle-spawn-rules.ts';
|
||||
import type { BattleLife, ReportedCombatEvent } from './battle-report.ts';
|
||||
|
||||
export function supportPlaneUnits(rules: Pick<BattleSpawnRulesData, 'supportPlanes'>): ReadonlySet<string> {
|
||||
return new Set(Object.values(rules.supportPlanes).flatMap((presets) =>
|
||||
presets.flatMap((preset) => Object.values(preset.units).map((unit) => unit.unitName))));
|
||||
}
|
||||
|
||||
/** The facts without the support planes' lives and combat events. */
|
||||
export function withoutSupportPlanes<T extends { readonly lives: readonly BattleLife[]; readonly events: readonly ReportedCombatEvent[] }>(
|
||||
facts: T,
|
||||
supportPlanes: ReadonlySet<string>,
|
||||
): T {
|
||||
return {
|
||||
...facts,
|
||||
lives: facts.lives.filter((life) => !supportPlanes.has(life.unit)),
|
||||
events: facts.events.filter((event) => !supportPlanes.has(event.unit)),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
/**
|
||||
* Typed reader for `tuning/battle.jsonc`: offline Silver Lions and Research Points
|
||||
* multipliers, LocalMP slot and bot counts, matchmaking BR window, coalition pairing rules and
|
||||
* the strike UCAV extra slot.
|
||||
*/
|
||||
import { TuningError, type TuningReader } from '../tuning/tuning-reader.ts';
|
||||
|
||||
export interface BattleTuning {
|
||||
readonly rewardMultiplierSilverLions: number;
|
||||
readonly rewardMultiplierResearchPoints: number;
|
||||
readonly maxPlayers: number;
|
||||
readonly maxBots: number;
|
||||
readonly smallTeamsMaxPlayers: number;
|
||||
readonly subModeChance: number;
|
||||
readonly brSpreadMrank: number;
|
||||
readonly botPoolLimitPerType: number;
|
||||
readonly rbCoalitionMinCountries: number;
|
||||
readonly rbCoalitionMaxCountries: number;
|
||||
readonly rbGroundMixedChance: number;
|
||||
readonly rbAirMixedChance: number;
|
||||
readonly rbNavalMixedChance: number;
|
||||
readonly simColdWarMinMrank: number;
|
||||
readonly strikeUcavModes: readonly string[];
|
||||
readonly strikeUcavSessionMrankAllowance: number;
|
||||
readonly strikeUcavSpawnScore: number;
|
||||
readonly tankBotRespawns: number;
|
||||
readonly airBotRespawns: number;
|
||||
}
|
||||
|
||||
export function readBattleTuning(reader: TuningReader): BattleTuning {
|
||||
const maxPlayers = reader.int('maxPlayers', { min: 2, max: 64 });
|
||||
const maxBots = reader.int('maxBots', { min: 1, max: 63 });
|
||||
if (maxBots >= maxPlayers) {
|
||||
throw new TuningError(`tuning file battle.jsonc: maxBots (${maxBots}) must be less than maxPlayers (${maxPlayers})`);
|
||||
}
|
||||
const smallTeamsMaxPlayers = reader.int('smallTeamsMaxPlayers', { min: 2, max: 64 });
|
||||
if (smallTeamsMaxPlayers > maxPlayers) {
|
||||
throw new TuningError(
|
||||
`tuning file battle.jsonc: smallTeamsMaxPlayers (${smallTeamsMaxPlayers}) must not exceed maxPlayers (${maxPlayers})`,
|
||||
);
|
||||
}
|
||||
const rbCoalitionMinCountries = reader.int('rbCoalitionMinCountries', { min: 1, max: 10 });
|
||||
const rbCoalitionMaxCountries = reader.int('rbCoalitionMaxCountries', { min: 1, max: 10 });
|
||||
if (rbCoalitionMaxCountries < rbCoalitionMinCountries) {
|
||||
throw new TuningError(
|
||||
`tuning file battle.jsonc: rbCoalitionMaxCountries (${rbCoalitionMaxCountries}) must be at least rbCoalitionMinCountries (${rbCoalitionMinCountries})`,
|
||||
);
|
||||
}
|
||||
return {
|
||||
rewardMultiplierSilverLions: reader.number('rewardMultiplierSilverLions', { min: 0, max: 100 }),
|
||||
rewardMultiplierResearchPoints: reader.number('rewardMultiplierResearchPoints', { min: 0, max: 100 }),
|
||||
maxPlayers,
|
||||
maxBots,
|
||||
smallTeamsMaxPlayers,
|
||||
subModeChance: reader.number('subModeChance', { min: 0, max: 1 }),
|
||||
brSpreadMrank: reader.int('brSpreadMrank', { min: 0, max: 12 }),
|
||||
botPoolLimitPerType: reader.int('botPoolLimitPerType', { min: 4, max: 200 }),
|
||||
rbCoalitionMinCountries,
|
||||
rbCoalitionMaxCountries,
|
||||
rbGroundMixedChance: reader.number('rbGroundMixedChance', { min: 0, max: 1 }),
|
||||
rbAirMixedChance: reader.number('rbAirMixedChance', { min: 0, max: 1 }),
|
||||
rbNavalMixedChance: reader.number('rbNavalMixedChance', { min: 0, max: 1 }),
|
||||
simColdWarMinMrank: reader.int('simColdWarMinMrank', { min: 0, max: 40 }),
|
||||
strikeUcavModes: reader.stringList('strikeUcavModes'),
|
||||
strikeUcavSessionMrankAllowance: reader.int('strikeUcavSessionMrankAllowance', { min: 0, max: 12 }),
|
||||
strikeUcavSpawnScore: reader.int('strikeUcavSpawnScore', { min: 1, max: 10000 }),
|
||||
tankBotRespawns: reader.int('tankBotRespawns', { min: 1, max: 10 }),
|
||||
airBotRespawns: reader.int('airBotRespawns', { min: 1, max: 10 }),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
/**
|
||||
* How one battle moves the player's wager (wager items, config/items.blk wagerParams; started by
|
||||
* cln_set_current_wager, items/item-activation.ts). Pure: the settlement writes the result
|
||||
* (battle-items.ts). Online the server does this; the client shows the stage (EULT_CHARD_AWARD
|
||||
* WagerStageWin / WagerStageFail / WagerWin / WagerFail) and the stake table.
|
||||
*
|
||||
* - A battle counts when wagerParams/active holds. Its mode maxUnitsRankOnStartMission means, as the
|
||||
* client describes it (scripts unlocks/unlocksConditions.nut), that at least one crew-slot vehicle
|
||||
* has rank >= minRank and none has rank > maxRank. Conditions: "online" holds (a LocalMP battle
|
||||
* stands in for an online one, offline design); eventMode is_event:b=no holds in random battles;
|
||||
* missionPostfix as for battle awards; "inSquad" never holds (no squads offline); unknown ones do not.
|
||||
* - A counted battle completes a stage when wagerParams/win holds in it ("The above conditions must
|
||||
* be fulfilled within a single battle"): missionsWon = the battle is won; killedPlayersScore =
|
||||
* kills of players x mulArcade / mulRealistic / mulHardcore >= num; unlocks = at least num
|
||||
* (all when num is missing, as the client counts it) of the listed battle awards, hidden ones
|
||||
* included. Otherwise it is a failed battle ("Battles in which a new stage was not achieved").
|
||||
* - The wager ends at maxWins stages (WagerWin) or maxFails failed battles (WagerFail). Either way
|
||||
* it pays the reward of the stages reached (community descriptions; the official text is not
|
||||
* found): the winParams reward with the highest param <= stages, each kind a x stake x stages^b + c
|
||||
* (itemWager.nut getRewardValueByNumWins). The stake is not returned.
|
||||
*/
|
||||
import type { WagerDefinition, WagerRewardKind } from '../game-data/datasets/item-catalogue.ts';
|
||||
import type { StreakCondition } from '../game-data/datasets/battle-streaks.ts';
|
||||
import type { EconomyDifficulty } from '../game-data/datasets/battle-economy.ts';
|
||||
import { ExpEvent } from './battle-economy.ts';
|
||||
import type { ReportedCombatEvent } from './battle-report.ts';
|
||||
|
||||
export type WagerStageResult = 'WagerStageWin' | 'WagerStageFail' | 'WagerWin' | 'WagerFail';
|
||||
|
||||
export interface WagerBattleFacts {
|
||||
readonly won: boolean;
|
||||
readonly events: readonly ReportedCombatEvent[];
|
||||
/** Ids of the battle awards earned, hidden ones included. */
|
||||
readonly awards: ReadonlyMap<string, number>;
|
||||
readonly difficulty: EconomyDifficulty;
|
||||
readonly missionName: string;
|
||||
readonly randomBattle: boolean;
|
||||
/** Ranks of the vehicles in the battle country's crew slots. */
|
||||
readonly lineupRanks: readonly number[];
|
||||
}
|
||||
|
||||
export interface WagerState {
|
||||
readonly stake: number;
|
||||
readonly numWins: number;
|
||||
readonly numBattles: number;
|
||||
}
|
||||
|
||||
export interface WagerBattleOutcome {
|
||||
readonly result: WagerStageResult;
|
||||
readonly numWins: number;
|
||||
readonly numBattles: number;
|
||||
readonly numFails: number;
|
||||
readonly ended: boolean;
|
||||
/** Paid when the wager ended. */
|
||||
readonly reward: Readonly<Partial<Record<WagerRewardKind, number>>>;
|
||||
}
|
||||
|
||||
const KILL_CODES: ReadonlySet<number> = new Set([ExpEvent.KILL, ExpEvent.KILL_GROUND, ExpEvent.KILL_HUMAN]);
|
||||
const MUL_NAMES: Readonly<Record<EconomyDifficulty, string>> = { arcade: 'mulArcade', historical: 'mulRealistic', simulation: 'mulHardcore' };
|
||||
|
||||
/** Undefined when the battle does not count for the wager. */
|
||||
export function wagerBattle(def: WagerDefinition, state: WagerState, facts: WagerBattleFacts): WagerBattleOutcome | undefined {
|
||||
if (!isCounted(def, facts)) return undefined;
|
||||
const stageWon = isStageWon(def, facts);
|
||||
const numWins = state.numWins + (stageWon ? 1 : 0);
|
||||
const numBattles = state.numBattles + 1;
|
||||
const numFails = numBattles - numWins;
|
||||
const won = def.maxWins > 0 && numWins >= def.maxWins;
|
||||
const failed = !won && def.maxFails > 0 && numFails >= def.maxFails;
|
||||
const ended = won || failed;
|
||||
return {
|
||||
result: won ? 'WagerWin' : failed ? 'WagerFail' : stageWon ? 'WagerStageWin' : 'WagerStageFail',
|
||||
numWins,
|
||||
numBattles,
|
||||
numFails,
|
||||
ended,
|
||||
reward: ended ? wagerReward(def, numWins, state.stake) : {},
|
||||
};
|
||||
}
|
||||
|
||||
export function wagerReward(def: WagerDefinition, stages: number, stake: number): Partial<Record<WagerRewardKind, number>> {
|
||||
const entry = [...def.rewards].reverse().find((reward) => reward.stage <= stages);
|
||||
if (!entry || stages < 1) return {};
|
||||
const out: Partial<Record<WagerRewardKind, number>> = {};
|
||||
for (const [kind, terms] of Object.entries(entry.terms) as [WagerRewardKind, readonly [number, number, number]][]) {
|
||||
const [a, b, c] = terms;
|
||||
const value = Math.round(a * stake * stages ** b + c);
|
||||
if (value > 0) out[kind] = value;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function isCounted(def: WagerDefinition, facts: WagerBattleFacts): boolean {
|
||||
const active = def.active;
|
||||
if (!active) return true;
|
||||
if (active.type === 'maxUnitsRankOnStartMission') {
|
||||
const minRank = numberParam(active.params, 'minRank') ?? 0;
|
||||
const maxRank = numberParam(active.params, 'maxRank');
|
||||
if (facts.lineupRanks.length === 0) return false;
|
||||
if (maxRank !== undefined && Math.max(...facts.lineupRanks) > maxRank) return false;
|
||||
if (!facts.lineupRanks.some((rank) => rank >= minRank)) return false;
|
||||
} else if (active.type !== '') {
|
||||
return false;
|
||||
}
|
||||
return active.conditions.every((condition) => conditionHolds(condition, facts));
|
||||
}
|
||||
|
||||
function conditionHolds(condition: StreakCondition, facts: WagerBattleFacts): boolean {
|
||||
const p = condition.params;
|
||||
switch (condition.type) {
|
||||
case 'online':
|
||||
return true;
|
||||
case 'eventMode':
|
||||
if ((p.event_name ?? []).length > 0 || p.for_clans_only?.[0] === true) return false;
|
||||
return p.is_event?.[0] === false ? facts.randomBattle : !facts.randomBattle;
|
||||
case 'missionPostfix': {
|
||||
const listed = (p.postfix ?? []).some((postfix) => facts.missionName.endsWith(String(postfix)));
|
||||
return p.allowed?.[0] === false ? !listed : listed;
|
||||
}
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function isStageWon(def: WagerDefinition, facts: WagerBattleFacts): boolean {
|
||||
const win = def.win;
|
||||
if (!win) return false;
|
||||
const p = win.params;
|
||||
switch (win.type) {
|
||||
case 'missionsWon':
|
||||
return facts.won;
|
||||
case 'killedPlayersScore': {
|
||||
const kills = facts.events.filter((e) => KILL_CODES.has(e.code) && e.victimIsPlayer && !e.friendly).length;
|
||||
return kills * (numberParam(p, MUL_NAMES[facts.difficulty]) ?? 1) >= (numberParam(p, 'num') ?? 1);
|
||||
}
|
||||
case 'unlocks': {
|
||||
const listed = (p.unlock ?? []).map(String);
|
||||
const earned = listed.filter((id) => (facts.awards.get(id) ?? 0) > 0).length;
|
||||
return listed.length > 0 && earned >= (numberParam(p, 'num') ?? listed.length);
|
||||
}
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function numberParam(p: Readonly<Record<string, readonly unknown[]>>, name: string): number | undefined {
|
||||
const value = p[name]?.[0];
|
||||
return typeof value === 'number' ? value : undefined;
|
||||
}
|
||||
Reference in new issue
Block a user