Split the repository into apps, packages and patches

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.
This commit is contained in:
N0VAN0M4LY committed 2026-11-29 03:20:54 +08:00
1 parent f6cdab7ec7
commit 27fc535301
476 files changed
+275 -251

No files matched your search

+99
View File
@@ -0,0 +1,99 @@
/**
* Local accounts behind the login service.
*
* Signing in with a login name that does not exist yet registers it with the password given;
* later sign-ins must use the same password. Accounts are kept in <data>/accounts.json.
*/
import { existsSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { writeFileAtomic } from '../storage/atomic-file.ts';
import { hashPassword, verifyPassword } from './password.ts';
export interface Account {
/** What the player types into the login window; matched without regard to case. */
readonly login: string;
/** Decimal user id, as the login service and the char service exchange it. */
readonly userId: string;
readonly nick: string;
readonly passwordHash: string;
readonly created: string;
}
export type SignInResult =
| { readonly kind: 'signed-in'; readonly account: Account; readonly registered: boolean }
| { readonly kind: 'wrong-password' };
interface AccountFile {
formatVersion: 1;
nextUserId: number;
accounts: Account[];
}
const FIRST_USER_ID = 100000001;
const NICK_MAX_LENGTH = 16;
export class AccountStore {
readonly #path: string;
#file: AccountFile;
#lastSignedInUserId: string | undefined;
constructor(dataFolder: string) {
this.#path = join(dataFolder, 'accounts.json');
this.#file = existsSync(this.#path) ? readAccountFile(this.#path) : { formatVersion: 1, nextUserId: FIRST_USER_ID, accounts: [] };
}
signIn(login: string, password: string): SignInResult {
const existing = this.#find(login);
if (existing) {
if (!verifyPassword(password, existing.passwordHash)) return { kind: 'wrong-password' };
this.#lastSignedInUserId = existing.userId;
return { kind: 'signed-in', account: existing, registered: false };
}
const userId = String(this.#file.nextUserId);
const account: Account = { login, userId, nick: nickFromLogin(login, userId), passwordHash: hashPassword(password), created: new Date().toISOString() };
this.#file = { ...this.#file, nextUserId: this.#file.nextUserId + 1, accounts: [...this.#file.accounts, account] };
writeFileAtomic(this.#path, JSON.stringify(this.#file, null, 2));
this.#lastSignedInUserId = userId;
return { kind: 'signed-in', account, registered: true };
}
/**
* The account that most recently signed in during this service run (for defaulting the initial
* read-only account dropdown in the built-in browser; never used as a fallback on mutations).
*/
lastSignedIn(): Account | undefined {
return this.#lastSignedInUserId ? this.byUserId(this.#lastSignedInUserId) : undefined;
}
all(): readonly Account[] {
return this.#file.accounts;
}
byUserId(userId: string): Account | undefined {
return this.#file.accounts.find((account) => account.userId === userId);
}
/** The account with this login, compared without regard to case. */
byLogin(login: string): Account | undefined {
return this.#find(login);
}
#find(login: string): Account | undefined {
const key = login.toLowerCase();
return this.#file.accounts.find((account) => account.login.toLowerCase() === key);
}
}
function readAccountFile(path: string): AccountFile {
const file = JSON.parse(readFileSync(path, 'utf8')) as AccountFile;
if (file.formatVersion !== 1) throw new Error(`${path}: unsupported account file version ${String(file.formatVersion)}`);
return file;
}
/** A login is often an e-mail address; the nick is its readable part. */
function nickFromLogin(login: string, userId: string): string {
const local = login.split('@')[0] ?? '';
const cleaned = local.replace(/[^A-Za-z0-9_\-]/g, '').slice(0, NICK_MAX_LENGTH);
return cleaned || `Player${userId}`;
}
+17
View File
@@ -0,0 +1,17 @@
/** Password hashes for local accounts (scrypt, per-account random salt). */
import { randomBytes, scryptSync, timingSafeEqual } from 'node:crypto';
const KEY_LENGTH = 32;
export function hashPassword(password: string): string {
const salt = randomBytes(16);
return `scrypt$${salt.toString('hex')}$${scryptSync(password, salt, KEY_LENGTH).toString('hex')}`;
}
export function verifyPassword(password: string, stored: string): boolean {
const [scheme, saltHex, hashHex] = stored.split('$');
if (scheme !== 'scrypt' || !saltHex || !hashHex) return false;
const expected = Buffer.from(hashHex, 'hex');
const actual = scryptSync(password, Buffer.from(saltHex, 'hex'), expected.length);
return timingSafeEqual(actual, expected);
}
+70
View File
@@ -0,0 +1,70 @@
/**
* Build an optional asset pack by downloading the public images that the local
* pages use into <data folder>/asset-pack/, so the pages show official pictures without a network
* connection. Run it on a machine that can reach the official sites; nothing is shipped with
* the project, every player makes their own copy.
*
* node apps/server/src/asset-pack-cli.ts --data <data folder> [--concurrency 6]
*
* Sources: official marketplace art and vehicle renders, plus store covers and screenshots.
* The storefront links videos directly.
* Files keep their host/path layout (static-ggc.gaijin.net/units/x.png); index.json lists them.
* The pages read the pack first (web-ui/web/common.js `sourcesFor`).
*/
import { existsSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { parseArgs } from 'node:util';
import { writeFileAtomic } from './storage/atomic-file.ts';
const MARKET_IMAGES = new URL('./web-ui/web/official-images.json', import.meta.url);
const STORE_MEDIA = new URL('./web-ui/web/official-store-media.json', import.meta.url);
async function main(): Promise<number> {
const { values } = parseArgs({ options: { data: { type: 'string' }, concurrency: { type: 'string', default: '6' } } });
if (!values.data) {
console.error('usage: asset-pack-cli.ts --data <data folder> [--concurrency 6]');
return 2;
}
const packDir = join(values.data, 'asset-pack');
const table = JSON.parse(readFileSync(MARKET_IMAGES, 'utf8')) as { base: string; byKey: Record<string, string> };
const store = JSON.parse(readFileSync(STORE_MEDIA, 'utf8')) as {
base: string;
byProduct: Record<string, { cover: string; screenshots?: string[] }>;
};
const urls = new Set<string>();
for (const [key, path] of Object.entries(table.byKey)) {
urls.add(table.base + path);
if (path.startsWith('units/')) urls.add(`https://static.encyclopedia.warthunder.com/images/${key.toLowerCase()}.png`);
}
for (const { cover, screenshots = [] } of Object.values(store.byProduct)) {
urls.add(store.base + cover);
for (const screenshot of screenshots) urls.add(store.base + screenshot);
}
const indexFile = join(packDir, 'index.json');
const done = new Set<string>(existsSync(indexFile) ? JSON.parse(readFileSync(indexFile, 'utf8')) as string[] : []);
const queue = [...urls].filter((url) => !done.has(url.replace(/^https?:\/\//, '')));
let failed = 0;
const worker = async (): Promise<void> => {
for (let url = queue.shift(); url; url = queue.shift()) {
const relative = url.replace(/^https?:\/\//, '');
try {
const response = await fetch(url, { signal: AbortSignal.timeout(15000) });
if (!response.ok || !response.headers.get('content-type')?.startsWith('image/')) {
await response.body?.cancel();
failed += 1;
continue;
}
writeFileAtomic(join(packDir, relative), Buffer.from(await response.arrayBuffer()));
done.add(relative);
} catch {
failed += 1;
}
}
};
await Promise.all(Array.from({ length: Math.max(1, Number(values.concurrency)) }, worker));
writeFileAtomic(indexFile, JSON.stringify([...done].sort()));
console.log(`asset pack: ${done.size} file(s) in ${packDir}; ${failed} not available`);
return 0;
}
process.exitCode = await main();
+197
View File
@@ -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);
}
+227
View File
@@ -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;
}
+109
View File
@@ -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);
}
+229
View File
@@ -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 };
}
+112
View File
@@ -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 } };
}
+36
View File
@@ -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;
}
}
+302
View File
@@ -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 };
}
+177
View File
@@ -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;
}
+126
View File
@@ -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)));
}
+176
View File
@@ -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;
}
+273
View File
@@ -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;
}
+214
View File
@@ -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;
}
}
+180
View File
@@ -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 });
}
}
+471
View File
@@ -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)),
};
}
+70
View File
@@ -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 }),
};
}
+149
View File
@@ -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;
}
@@ -0,0 +1,10 @@
/** Resolving the player a char request is for (the uidhint header, implementation notes). */
import type { Account, AccountStore } from '../../accounts/account-store.ts';
import type { CharAnswer } from '../char-answers.ts';
import type { CharActionContext } from '../char-action.ts';
/** Run the handler for the request's account; an unknown or missing user id is an authorisation error. */
export function withAccount(context: CharActionContext, accounts: AccountStore, run: (account: Account) => CharAnswer): CharAnswer {
const account = context.userId === undefined ? undefined : accounts.byUserId(context.userId);
return account ? run(account) : { kind: 'error', code: 'AUTH_REQ_ERROR' };
}
@@ -0,0 +1,202 @@
/** Char action names mapped to their protocol handlers (full list of names: implementation notes). */
import type { AccountStore } from '../../accounts/account-store.ts';
import type { ClanStore } from '../../clans/clan-store.ts';
import type { CloudSettingsStore } from '../../cloud-settings/cloud-settings-store.ts';
import type { CrewSkillCatalogue } from '../../crew/crew-skill-rules.ts';
import type { DecorShop } from '../../decor/decor-purchase.ts';
import type { ClanEconomy } from '../../game-data/datasets/clan-economy.ts';
import type { InventoryCatalogue } from '../../inventory/itemdef-catalogue.ts';
import type { TrophyCatalogue } from '../../inventory/trophy-catalogue.ts';
import type { ItemCatalogue } from '../../items/item-catalogue.ts';
import type { EquipmentCatalogue } from '../../modifications/equipment-catalogue.ts';
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
import type { ResearchRules } from '../../research/research-rules.ts';
import type { StoreCatalogue } from '../../store/store-catalogue.ts';
import type { UnlockShop } from '../../unlocks/unlock-purchase.ts';
import type { CharActionHandler } from '../char-action.ts';
import { acceptEula } from './agreement-actions.ts';
import {
clanChangeInfoAction,
clanCreateAction,
clanDisbandAction,
clanFindByPrefixAction,
clanGetAction,
clanGetLeaderboardAction,
clanGetLogAction,
clanLeaveAction,
clanMembershipRequestAction,
clanMembersUpgradeAction,
clansListShortInfoAction,
clanSetMembershipReqAction,
clanSyncProfileAction,
clanUpgradeAction,
} from './clan-actions.ts';
import {
clanAcceptCandidateAction,
clanChangeMemberRoleAction,
clanDismissMemberAction,
clanEditBlacklistAction,
clanRejectCandidateAction,
setClanBestRewardsAction,
} from './clan-moderation-actions.ts';
import { clientUpdateAction } from './client-update-actions.ts';
import { bulkSetGblkAction, getGeneralBlkAction, getMetaBlkAction, setGeneralBlkAction } from './cloud-settings-actions.ts';
import { bulkTrainCrews, trainCrew } from './crew-actions.ts';
import { purchaseSkillPointsAction, specializeCrewAction, upgradeCrewAction } from './crew-skill-actions.ts';
import { buyResourceAction } from './decor-actions.ts';
import { saveDecorLayoutsAction } from './decor-layout-actions.ts';
import {
buyTrophyAction,
consumeInventoryItemAction,
inventoryExchangeAction,
multiConsumeInventoryItemsAction,
purchaseInventoryItemAction,
recycleItemsAction,
} from './inventory-actions.ts';
import { activateBoosterAction, activateDiscountAction, applySpareItemAction, buyItemAction, startWagerAction } from './item-actions.ts';
import {
buyAllModificationsAction,
buyModificationAction,
buySparesAction,
buyWeaponsAction,
enableModificationsAction,
saveWeaponPresetsAction,
} from './modification-actions.ts';
import { entitlementsFull, initialMeta, legacyUserData } from './online-init-actions.ts';
import { savePilotAppearanceAction, saveShowcaseAction, selectTitleAction, showcasesAction, usersTerseInfoAction } from './player-card-actions.ts';
import { priceEx } from './price-actions.ts';
import { buyAircraft, buySlot } from './purchase-actions.ts';
import { convertExp, moveExpToModuleAction, moveExpToUnitAction, resetResearchable, setResearchable } from './research-actions.ts';
import { buyNotResearchedClanUnitAction, flushClanExpToUnitAction, setResearchClanUnitAction } from './squadron-research-actions.ts';
import { setStartingInfo } from './starting-info-actions.ts';
import { buyEntitlementAction, entitlementsPriceEx } from './store-actions.ts';
import { buyUnlockAction } from './unlock-actions.ts';
import type { RepairRules } from '../../repair/repair-rules.ts';
import { finishBattleAction, type BattleActionDependencies } from './battle-actions.ts';
import { hangarMiscActionEntries } from './hangar-misc-actions.ts';
export interface ClanActionDependencies {
readonly store: ClanStore;
readonly economy: ClanEconomy;
}
export interface ActionDependencies {
readonly profiles: PlayerProfiles;
readonly accounts: AccountStore;
readonly research: ResearchRules;
readonly equipment: EquipmentCatalogue;
readonly crew: CrewSkillCatalogue;
readonly decor: DecorShop;
readonly unlocks: UnlockShop;
readonly items: ItemCatalogue;
readonly repair: RepairRules;
readonly store: StoreCatalogue;
readonly inventory: InventoryCatalogue;
readonly trophies: TrophyCatalogue;
readonly clans?: ClanActionDependencies;
readonly cloudSettings?: CloudSettingsStore;
readonly battle?: BattleActionDependencies;
readonly notifyInventoryChanged?: () => void;
}
export function actionTable(deps: ActionDependencies): ReadonlyMap<string, CharActionHandler> {
const entries: Array<[string, CharActionHandler]> = [
...coreActionEntries(deps),
...hangarMiscActionEntries(deps),
...(deps.clans ? clanActionEntries(deps, deps.clans) : []),
...(deps.cloudSettings ? cloudActionEntries(deps.accounts, deps.cloudSettings) : []),
...(deps.battle ? [['cln_wto_finish_battle', finishBattleAction(deps, deps.battle)] as [string, CharActionHandler]] : []),
];
return new Map<string, CharActionHandler>(entries);
}
function coreActionEntries(deps: ActionDependencies): Array<[string, CharActionHandler]> {
const notifyInventory = deps.notifyInventoryChanged ?? (() => {});
const { techTree } = deps.research;
return [
['cln_get_initial_meta', initialMeta(deps.accounts, deps.cloudSettings)],
['cln_upd_entitlements_full', entitlementsFull(deps.profiles, deps.accounts)],
['cln_legacy_get_userdata', legacyUserData(deps.profiles, deps.accounts)],
['cln_update', clientUpdateAction(deps.profiles, deps.accounts)],
['cln_accept_eula', acceptEula(deps.profiles, deps.accounts)],
['cln_set_starting_info', setStartingInfo(deps.profiles, deps.accounts)],
['cln_bulk_train_aircraft', bulkTrainCrews(deps.profiles, deps.accounts, deps.crew)],
['cln_train_aircraft', trainCrew(deps.profiles, deps.accounts, deps.crew)],
['cln_set_researchable', setResearchable(deps.profiles, deps.accounts, deps.research, deps.equipment)],
['cln_reset_researchable', resetResearchable(deps.profiles, deps.accounts, deps.research)],
['cln_convert_exp', convertExp(deps.profiles, deps.accounts, deps.research)],
['cln_move_exp_to_unit', moveExpToUnitAction(deps.profiles, deps.accounts, deps.research)],
['cln_move_exp_to_module', moveExpToModuleAction(deps.profiles, deps.accounts, deps.equipment)],
['cln_buy_aircraft', buyAircraft(deps.profiles, deps.accounts, deps.research)],
['cln_buy_slot', buySlot(deps.profiles, deps.accounts, deps.research)],
['cln_get_price_ex', priceEx({ techTree, equipment: deps.equipment, decor: deps.decor, crew: deps.crew, unlocks: deps.unlocks, items: deps.items, trophies: deps.trophies, repair: deps.repair })],
['cln_buy_modification', buyModificationAction(deps.profiles, deps.accounts, deps.equipment)],
['cln_buy_all_modification', buyAllModificationsAction(deps.profiles, deps.accounts, deps.equipment)],
['cln_buy_spare_aircrafts', buySparesAction(deps.profiles, deps.accounts, deps.equipment)],
['cln_buy_unlock', buyUnlockAction(deps.profiles, deps.accounts, deps.unlocks)],
['cln_buy_weapon', buyWeaponsAction(deps.profiles, deps.accounts, deps.equipment)],
['cln_save_weapon_presets', saveWeaponPresetsAction(deps.profiles, deps.accounts, deps.equipment)],
['cln_enable_modifications', enableModificationsAction(deps.profiles, deps.accounts, deps.equipment)],
['cln_upgrade_crew', upgradeCrewAction(deps.profiles, deps.accounts, deps.crew)],
['cln_purchase_skill_points', purchaseSkillPointsAction(deps.profiles, deps.accounts, deps.crew)],
['cln_specialize_crew', specializeCrewAction(deps.profiles, deps.accounts, deps.crew)],
['cln_select_title', selectTitleAction(deps.profiles, deps.accounts)],
['cln_save_pilot_appearance', savePilotAppearanceAction(deps.profiles, deps.accounts)],
['cln_get_users_terse_info', usersTerseInfoAction(deps.profiles, deps.accounts, techTree, deps.clans?.store)],
['cln_save_profile_showcase', saveShowcaseAction(deps.profiles, deps.accounts)],
['cln_get_showcases', showcasesAction(deps.profiles, deps.accounts, techTree)],
['cln_buy_resource', buyResourceAction(deps.profiles, deps.accounts, deps.decor)],
['cln_save_decals', saveDecorLayoutsAction(deps.profiles, deps.accounts, 'decals')],
['cln_save_attachables', saveDecorLayoutsAction(deps.profiles, deps.accounts, 'attachables')],
['cln_buy_item', buyItemAction(deps.profiles, deps.accounts, deps.items)],
['cln_set_current_booster', activateBoosterAction(deps.profiles, deps.accounts)],
['cln_set_current_personal_discount', activateDiscountAction(deps.profiles, deps.accounts, deps.items)],
['cln_set_current_wager', startWagerAction(deps.profiles, deps.accounts, deps.items)],
['cln_apply_spare_item', applySpareItemAction(deps.profiles, deps.accounts, deps.items, techTree)],
['cln_get_entitlements_price_ex', entitlementsPriceEx(deps.store)],
['cln_buy_entitlement', buyEntitlementAction(deps.profiles, deps.accounts, deps.store)],
['cln_consume_inventory_item', consumeInventoryItemAction(deps.profiles, deps.accounts, deps.inventory, deps.items, notifyInventory)],
['cln_multi_consume_inventory_item_json', multiConsumeInventoryItemsAction(deps.profiles, deps.accounts, deps.inventory, deps.items, notifyInventory)],
['cln_inventory_purchase_item', purchaseInventoryItemAction(deps.profiles, deps.accounts, deps.inventory, notifyInventory)],
['cln_recycle_items', recycleItemsAction(deps.profiles, deps.accounts, deps.items, notifyInventory)],
['cln_inventory_exchange_items', inventoryExchangeAction(deps.profiles, deps.accounts, deps.inventory)],
['cln_buy_trophy', buyTrophyAction(deps.profiles, deps.accounts, deps.trophies, deps.items)],
];
}
function clanActionEntries(deps: ActionDependencies, clans: ClanActionDependencies): Array<[string, CharActionHandler]> {
return [
['cln_clan_get', clanGetAction(deps.accounts, clans.store)],
['cln_clan_get_leaderboard', clanGetLeaderboardAction(clans.store)],
['cln_clan_find_by_prefix', clanFindByPrefixAction(clans.store)],
['cln_clans_list_get_short_info', clansListShortInfoAction(clans.store)],
['cln_clan_get_log', clanGetLogAction(deps.accounts, clans.store)],
['cln_clan_create', clanCreateAction(deps.profiles, deps.accounts, clans.store, clans.economy)],
['cln_clan_change_info', clanChangeInfoAction(deps.profiles, deps.accounts, clans.store, clans.economy)],
['cln_clan_upgrade', clanUpgradeAction(deps.profiles, deps.accounts, clans.store, clans.economy)],
['cln_clan_members_upgrade', clanMembersUpgradeAction(deps.profiles, deps.accounts, clans.store, clans.economy)],
['cln_clan_set_membership_requirements', clanSetMembershipReqAction(deps.accounts, clans.store)],
['cln_clan_membership_request', clanMembershipRequestAction(deps.profiles, deps.accounts, clans.store)],
['cln_clan_leave', clanLeaveAction(deps.profiles, deps.accounts, clans.store)],
['cln_clan_disband', clanDisbandAction(deps.profiles, deps.accounts, clans.store)],
['cln_clan_sync_profile_and_clan', clanSyncProfileAction(deps.profiles, deps.accounts, clans.store)],
['ano_clan_accept_membership_request', clanAcceptCandidateAction(deps.profiles, deps.accounts, clans.store)],
['ano_clan_reject_membership_request', clanRejectCandidateAction(deps.profiles, deps.accounts, clans.store)],
['ano_clan_dismiss_member', clanDismissMemberAction(deps.profiles, deps.accounts, clans.store)],
['ano_clan_change_member_role', clanChangeMemberRoleAction(deps.profiles, deps.accounts, clans.store)],
['ano_clan_edit_blacklist', clanEditBlacklistAction(deps.accounts, clans.store)],
['cln_set_clan_best_rewards', setClanBestRewardsAction(deps.accounts, clans.store)],
['cln_set_research_clan_unit', setResearchClanUnitAction(deps.profiles, deps.accounts, clans.store, deps.research)],
['cln_flush_clan_exp_to_unit', flushClanExpToUnitAction(deps.profiles, deps.accounts, clans.store, deps.research)],
['cln_buy_not_researched_clans_unit', buyNotResearchedClanUnitAction(deps.profiles, deps.accounts, clans.store, deps.research)],
];
}
function cloudActionEntries(accounts: AccountStore, cloudSettings: CloudSettingsStore): Array<[string, CharActionHandler]> {
return [
['cln_get_meta_blk', getMetaBlkAction(accounts, cloudSettings)],
['cln_get_general_blk', getGeneralBlkAction(accounts, cloudSettings)],
['cln_set_general_blk', setGeneralBlkAction(accounts, cloudSettings)],
['cln_bulk_set_gblk', bulkSetGblkAction(accounts, cloudSettings)],
];
}
@@ -0,0 +1,57 @@
/**
* The player's acceptance of the end-user licence agreement.
*
* The client keeps the accepted version in its save object (offset 0xe970, read by the
* script function getAgreedEulaVersion at aces.exe 2.61.0.37 0x1c3e580) and fills it from
* exactly two places:
* - the profile's top-level int eulaVersionAccepted, when a profile is loaded (0x917870,
* called by the profile serializer 0x917740);
* - the answer to cln_accept_eula: GameSaveData::onAsyncEconTransComplete (0xeb5f60) reads
* eulaVersionAccepted and ndaVersionAccepted from the answer's top level when the job
* (type 12) succeeds (0xeb79bd..0xeb7a05).
* The stock login script (scripts/login/loginpseudothreadsconfig.nut) waits until the
* accepted version reaches the current one, so the acceptance has to be stored in the save
* and sent back.
*/
import { emptyBlock, findParam, setParam, type BlkBlock } from '@wto/blk';
import type { AccountStore } from '../../accounts/account-store.ts';
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
import type { CharActionHandler } from '../char-action.ts';
import { withAccount } from './account-context.ts';
const EULA_VERSION = 'eulaVersionAccepted';
const NDA_VERSION = 'ndaVersionAccepted';
/**
* The only sender is the script function setAgreedEulaVersion (0x1c3e560), which always
* passes agreement type 0 (the EULA) to the request builder 0x298ea0; the body is
* {version:i, type:i}. Other types have no sender in 2.61.0.37 and are refused.
*/
const EULA_AGREEMENT_TYPE = 0;
/** cln_accept_eula: store the accepted EULA version and answer with the accepted versions. */
export function acceptEula(profiles: PlayerProfiles, accounts: AccountStore): CharActionHandler {
return (context) => withAccount(context, accounts, (account) => {
const version = intParam(context.payload, 'version');
const type = intParam(context.payload, 'type');
if (version === undefined || type !== EULA_AGREEMENT_TYPE) return { kind: 'error', code: 'BAD_PARAMS' };
const profile = profiles.update(account.userId, (saved) => {
setParam(saved, EULA_VERSION, { type: 'int', value: version });
});
return { kind: 'data', blk: acceptedVersions(profile) };
});
}
/** Both versions, because the client overwrites both from the answer (a missing one reads as 0). */
function acceptedVersions(profile: BlkBlock): BlkBlock {
const answer = emptyBlock();
setParam(answer, EULA_VERSION, { type: 'int', value: intParam(profile, EULA_VERSION) ?? 0 });
setParam(answer, NDA_VERSION, { type: 'int', value: intParam(profile, NDA_VERSION) ?? 0 });
return answer;
}
function intParam(block: BlkBlock | undefined, name: string): number | undefined {
const value = block ? findParam(block, name)?.value : undefined;
return value?.type === 'int' ? value.value : undefined;
}
@@ -0,0 +1,69 @@
/**
* Char action `cln_wto_finish_battle`: receives the facts of a local battle (battle-report.ts),
* settles them into the player's save (battle-settlement.ts) and answers the updated profile,
* whose new `EULT_SESSION_RESULT` log carries the debriefing table.
*/
import type { AccountStore } from '../../accounts/account-store.ts';
import { parseBattleReport } from '../../battle/battle-report.ts';
import type { BattleSessionStore } from '../../battle/battle-session-store.ts';
import { settleBattle, type BattleSettlementDeps } from '../../battle/battle-settlement.ts';
import type { BattleEconomy } from '../../battle/battle-economy.ts';
import type { BattleStreaks } from '../../battle/battle-streaks.ts';
import { withoutSupportPlanes } from '../../battle/battle-support-planes.ts';
import type { CrewSkillCatalogue } from '../../crew/crew-skill-rules.ts';
import type { ItemCatalogue } from '../../items/item-catalogue.ts';
import type { EquipmentCatalogue } from '../../modifications/equipment-catalogue.ts';
import { clientProfile } from '../../profile/client-profile.ts';
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
import type { ResearchEfficiency } from '../../research/research-efficiency.ts';
import type { RepairRules } from '../../repair/repair-rules.ts';
import type { ResearchRules } from '../../research/research-rules.ts';
import type { CharActionHandler } from '../char-action.ts';
import { withAccount } from './account-context.ts';
export interface BattleActionDependencies {
readonly sessions: BattleSessionStore;
readonly economy: BattleEconomy;
readonly efficiency: ResearchEfficiency;
readonly streaks: BattleStreaks;
/** Units whose lives and events are not settled (battle-support-planes.ts). */
readonly supportPlanes: ReadonlySet<string>;
}
export interface FinishBattleContext {
readonly profiles: PlayerProfiles;
readonly accounts: AccountStore;
readonly research: ResearchRules;
readonly equipment: EquipmentCatalogue;
readonly crew: CrewSkillCatalogue;
readonly items: ItemCatalogue;
readonly repair: RepairRules;
}
export function finishBattleAction(ctx: FinishBattleContext, battle: BattleActionDependencies): CharActionHandler {
const settlementDeps: BattleSettlementDeps = {
research: ctx.research,
efficiency: battle.efficiency,
equipment: ctx.equipment,
crew: ctx.crew,
economy: battle.economy,
streaks: battle.streaks,
items: ctx.items,
repair: ctx.repair,
};
return (context) => withAccount(context, ctx.accounts, (account) => {
const parsed = context.payload && parseBattleReport(context.payload);
if (!parsed) return { kind: 'error', code: 'BAD_PARAMS' };
const report = withoutSupportPlanes(parsed, battle.supportPlanes);
const session = battle.sessions.findForUser(report.sessionId, account.userId);
if (!session) return { kind: 'error', code: 'BAD_PARAMS' };
if (session.settled) {
return { kind: 'data', blk: clientProfile(ctx.profiles.profileOf(account.userId), account) };
}
const updated = ctx.profiles.update(account.userId, (profile) => {
settleBattle(profile, report, session, settlementDeps);
});
battle.sessions.markSettled(session.sessionId);
return { kind: 'data', blk: clientProfile(updated, account) };
});
}
@@ -0,0 +1,224 @@
/**
* Char action handlers for squadron (clan) directory, creation, upgrades, and player
* membership requests. Officer moderation and squadron vehicle
* research live in `clan-moderation-actions.ts` and `squadron-research-actions.ts`.
*/
import { emptyBlock, findBlock, type BlkBlock } from '@wto/blk';
import type { Account, AccountStore } from '../../accounts/account-store.ts';
import {
toClanInfoBlk,
toClanLeaderboardRowBlk,
toClanLogBlk,
toClanShortInfoBlk,
} from '../../clans/clan-blk.ts';
import type { ClanStore } from '../../clans/clan-store.ts';
import type { ClanEconomy } from '../../game-data/datasets/clan-economy.ts';
import { clientProfile } from '../../profile/client-profile.ts';
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
import type { Price } from '../../profile/profile-currency.ts';
import type { RuleOutcome } from '../../research/rule-outcome.ts';
import type { CharActionContext, CharActionHandler } from '../char-action.ts';
import { withAccount } from './account-context.ts';
import {
boolParam,
headerOrPayloadBool,
headerOrPayloadId,
headerOrPayloadInt,
headerOrPayloadString,
intParam,
stringParam,
} from './payload-params.ts';
export function priceFromClanPayload(payload: BlkBlock): Price {
return {
silverLions: intParam(payload, 'cost') ?? 0,
goldenEagles: intParam(payload, 'costGold') ?? 0,
};
}
export function clanProfileRuleAction(
profiles: PlayerProfiles,
accounts: AccountStore,
_clans: ClanStore,
run: (context: CharActionContext, profile: BlkBlock, account: Account) => RuleOutcome,
): CharActionHandler {
return (context) => withAccount(context, accounts, (account) => {
let outcome: RuleOutcome = { ok: false, refusal: 'BAD_PARAMS' };
const updated = profiles.updateWhen(account.userId, (saved) => {
outcome = run(context, saved, account);
return outcome.ok;
});
if (!updated) return { kind: 'error', code: outcome.ok ? 'BAD_PARAMS' : outcome.refusal };
return { kind: 'data', blk: clientProfile(updated, account) };
});
}
export function clanGetAction(accounts: AccountStore, clans: ClanStore): CharActionHandler {
return (context) => withAccount(context, accounts, (account) => {
const clanId = headerOrPayloadId(context, 'clanId') ?? headerOrPayloadId(context, '_id');
const clanName = headerOrPayloadString(context, 'clanName');
const clanTag = headerOrPayloadString(context, 'clanTag');
const clan = (!clanId && !clanName && !clanTag)
? clans.clanOfUser(account.userId)?.clan
: clans.findClan({ clanId, clanName, clanTag });
if (!clan) return { kind: 'error', code: 'CLAN_NOT_FOUND' };
return { kind: 'data', blk: toClanInfoBlk(clan, clans.tuning) };
});
}
export function clanGetLeaderboardAction(clans: ClanStore): CharActionHandler {
return (context) => {
const rows = clans.queryLeaderboard({
start: headerOrPayloadInt(context, 'start') ?? 0,
count: headerOrPayloadInt(context, 'count') ?? 20,
sortField: headerOrPayloadString(context, 'sortField') ?? 'dr_era5_hist',
clanId: headerOrPayloadId(context, 'clanId'),
filterOpen: headerOrPayloadBool(context, 'filterOpen') ?? false,
filterNotFull: headerOrPayloadBool(context, 'filterNotFull') ?? false,
filterAutoAccept: headerOrPayloadBool(context, 'filterAutoAccept') ?? false,
});
return { kind: 'data', blk: { name: '', params: [], blocks: rows.map((r) => toClanLeaderboardRowBlk(r.clan, r.pos, clans.tuning)) } };
};
}
export function clanFindByPrefixAction(clans: ClanStore): CharActionHandler {
return (context) => {
const prefix = headerOrPayloadString(context, 'namePrefix') ?? headerOrPayloadString(context, 'tagPrefix') ?? '';
const rows = clans.queryLeaderboard({
start: headerOrPayloadInt(context, 'start') ?? 0,
count: headerOrPayloadInt(context, 'count') ?? 20,
sortField: 'activity',
prefix,
filterOpen: headerOrPayloadBool(context, 'filterOpen') ?? false,
filterNotFull: headerOrPayloadBool(context, 'filterNotFull') ?? false,
filterAutoAccept: headerOrPayloadBool(context, 'filterAutoAccept') ?? false,
});
return { kind: 'data', blk: { name: '', params: [], blocks: rows.map((r) => toClanLeaderboardRowBlk(r.clan, r.pos, clans.tuning)) } };
};
}
export function clansListShortInfoAction(clans: ClanStore): CharActionHandler {
return (context) => {
const body = context.payload && findBlock(context.payload, 'body');
const requestedIds = (body?.params ?? [])
.filter((p) => p.name === 'clanId' && p.value.type === 'string')
.map((p) => (p.value as { type: 'string'; value: string }).value);
const blocks = requestedIds.flatMap((id) => {
const clan = clans.byId(id);
return clan ? [toClanShortInfoBlk(clan, clans.tuning)] : [];
});
return { kind: 'data', blk: { name: '', params: [], blocks } };
};
}
export function clanGetLogAction(accounts: AccountStore, clans: ClanStore): CharActionHandler {
return (context) => withAccount(context, accounts, (account) => {
const clanId = headerOrPayloadId(context, '_id') ?? headerOrPayloadId(context, 'clanId');
const clan = clanId && clanId !== '-1' ? clans.byId(clanId) : clans.clanOfUser(account.userId)?.clan;
if (!clan) return { kind: 'data', blk: emptyBlock() };
const count = headerOrPayloadInt(context, 'count') ?? 20;
const events = headerOrPayloadString(context, 'events');
const last = headerOrPayloadString(context, 'last');
return { kind: 'data', blk: toClanLogBlk(clan, count, events, last) };
});
}
export function clanCreateAction(profiles: PlayerProfiles, accounts: AccountStore, clans: ClanStore, clanEconomy: ClanEconomy): CharActionHandler {
return clanProfileRuleAction(profiles, accounts, clans, (context, profile, account) => {
const payload = context.payload;
const offered = payload && priceFromClanPayload(payload);
const rawType = payload && stringParam(payload, 'type');
if (!payload || !offered || (rawType !== 'normal' && rawType !== 'battalion')) {
return { ok: false, refusal: 'BAD_PARAMS' };
}
return clans.createClan(profile, account, clanEconomy, {
name: stringParam(payload, 'name') ?? '',
tag: stringParam(payload, 'tag') ?? '',
slogan: stringParam(payload, 'slogan') ?? '',
region: stringParam(payload, 'region') ?? '',
desc: stringParam(payload, 'desc') ?? '',
announcement: stringParam(payload, 'announcement') ?? '',
type: rawType,
offered,
});
});
}
export function clanChangeInfoAction(profiles: PlayerProfiles, accounts: AccountStore, clans: ClanStore, clanEconomy: ClanEconomy): CharActionHandler {
return clanProfileRuleAction(profiles, accounts, clans, (context, profile, account) => {
const payload = context.payload;
if (!payload) return { ok: false, refusal: 'BAD_PARAMS' };
const clanId = headerOrPayloadId(context, '_id') ?? '-1';
const rawStatus = stringParam(payload, 'status');
return clans.editClanInfo(profile, account, clanEconomy, clanId, {
name: stringParam(payload, 'name'),
tag: stringParam(payload, 'tag'),
desc: stringParam(payload, 'desc'),
slogan: stringParam(payload, 'slogan'),
announcement: stringParam(payload, 'announcement'),
region: stringParam(payload, 'region'),
status: rawStatus === 'closed' ? 'closed' : rawStatus === 'open' ? 'open' : undefined,
});
});
}
export function clanUpgradeAction(profiles: PlayerProfiles, accounts: AccountStore, clans: ClanStore, clanEconomy: ClanEconomy): CharActionHandler {
return clanProfileRuleAction(profiles, accounts, clans, (context, profile, account) => {
const payload = context.payload;
if (!payload) return { ok: false, refusal: 'BAD_PARAMS' };
const clanId = headerOrPayloadId(context, '_id') ?? '-1';
return clans.upgradeClanToNormal(profile, account, clanEconomy, clanId, {
tag: stringParam(payload, 'tag') ?? '',
desc: stringParam(payload, 'desc') ?? '',
announcement: stringParam(payload, 'announcement') ?? '',
});
});
}
export function clanMembersUpgradeAction(profiles: PlayerProfiles, accounts: AccountStore, clans: ClanStore, clanEconomy: ClanEconomy): CharActionHandler {
return clanProfileRuleAction(profiles, accounts, clans, (context, profile, account) => {
const clanId = headerOrPayloadId(context, '_id') ?? '-1';
return clans.upgradeMembersLimit(profile, account, clanEconomy, clanId);
});
}
export function clanSetMembershipReqAction(accounts: AccountStore, clans: ClanStore): CharActionHandler {
return (context) => withAccount(context, accounts, (account) => {
const payload = context.payload;
const clanId = headerOrPayloadId(context, '_id') ?? '-1';
const reqBlk = payload && findBlock(payload, 'membership_req');
const autoaccept = (payload && boolParam(payload, 'autoaccept')) ?? false;
if (!clans.setMembershipRequirements(clanId, account, reqBlk, autoaccept)) {
return { kind: 'error', code: 'NOT_AVAILABLE' };
}
return { kind: 'done' };
});
}
export function clanMembershipRequestAction(profiles: PlayerProfiles, accounts: AccountStore, clans: ClanStore): CharActionHandler {
return clanProfileRuleAction(profiles, accounts, clans, (context, profile, account) => {
const clanId = headerOrPayloadId(context, '_id') ?? headerOrPayloadId(context, 'requestedClanId');
const clanName = headerOrPayloadString(context, 'name');
const clanTag = headerOrPayloadString(context, 'tag');
const cancel = headerOrPayloadBool(context, 'cancelRequest') ?? false;
const comment = headerOrPayloadString(context, 'comments');
return clans.requestOrCancelMembership(profile, account, { clanId, clanName, clanTag, cancel, comment });
});
}
export function clanLeaveAction(profiles: PlayerProfiles, accounts: AccountStore, clans: ClanStore): CharActionHandler {
return clanProfileRuleAction(profiles, accounts, clans, (_context, profile, account) =>
clans.leaveClan(profile, account));
}
export function clanDisbandAction(profiles: PlayerProfiles, accounts: AccountStore, clans: ClanStore): CharActionHandler {
return clanProfileRuleAction(profiles, accounts, clans, (context, profile, account) =>
clans.disbandClan(profile, account, headerOrPayloadId(context, 'requestedClanId') ?? headerOrPayloadId(context, '_id')));
}
export function clanSyncProfileAction(profiles: PlayerProfiles, accounts: AccountStore, _clans: ClanStore): CharActionHandler {
return (context) => withAccount(context, accounts, (account) => {
const updated = profiles.profileOf(account.userId);
return { kind: 'data', blk: clientProfile(updated, account) };
});
}
@@ -0,0 +1,125 @@
/**
* Char action handlers for squadron officer moderation, blacklist, and best-rewards metadata
* (`ano_clan_*`, `cln_set_clan_best_rewards`; implementation notes; aces.exe 0x29d150, 0x29d540).
*/
import type { AccountStore } from '../../accounts/account-store.ts';
import type { ClanStore } from '../../clans/clan-store.ts';
import { ClanRole, roleCodeFromString, type ClanBestReward } from '../../clans/clan-types.ts';
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
import type { CharActionContext, CharActionHandler } from '../char-action.ts';
import { withAccount } from './account-context.ts';
import { headerOrPayloadId, headerOrPayloadInt, headerOrPayloadString } from './payload-params.ts';
export function clanAcceptCandidateAction(
profiles: PlayerProfiles,
accounts: AccountStore,
clans: ClanStore,
): CharActionHandler {
return (context) => withAccount(context, accounts, (account) => {
const targetUid = headerOrPayloadId(context, 'userid') ?? '';
const clanId = headerOrPayloadId(context, '_id');
const role = parseRoleParam(context) ?? ClanRole.REGULAR;
const targetAccount = accounts.byUserId(targetUid);
if (!targetUid || !clans.acceptCandidate(account, clanId, targetUid, targetAccount?.nick ?? `Pilot_${targetUid}`, role)) {
return { kind: 'error', code: 'NOT_AVAILABLE' };
}
if (targetAccount) profiles.profileOf(targetAccount.userId);
return { kind: 'done' };
});
}
export function clanRejectCandidateAction(
profiles: PlayerProfiles,
accounts: AccountStore,
clans: ClanStore,
): CharActionHandler {
return (context) => withAccount(context, accounts, (account) => {
const targetUid = headerOrPayloadId(context, 'userid') ?? '';
const clanId = headerOrPayloadId(context, '_id');
const comments = headerOrPayloadString(context, 'comments') ?? '';
if (!targetUid || !clans.rejectCandidate(account, clanId, targetUid, comments)) {
return { kind: 'error', code: 'NOT_AVAILABLE' };
}
const targetAccount = accounts.byUserId(targetUid);
if (targetAccount) profiles.profileOf(targetAccount.userId);
return { kind: 'done' };
});
}
export function clanDismissMemberAction(
profiles: PlayerProfiles,
accounts: AccountStore,
clans: ClanStore,
): CharActionHandler {
return (context) => withAccount(context, accounts, (account) => {
const targetUid = headerOrPayloadId(context, 'userid') ?? '';
const comments = headerOrPayloadString(context, 'comments') ?? '';
if (!targetUid || !clans.dismissMember(account, targetUid, comments)) {
return { kind: 'error', code: 'NOT_AVAILABLE' };
}
const targetAccount = accounts.byUserId(targetUid);
if (targetAccount) profiles.profileOf(targetAccount.userId);
return { kind: 'done' };
});
}
export function clanChangeMemberRoleAction(
profiles: PlayerProfiles,
accounts: AccountStore,
clans: ClanStore,
): CharActionHandler {
return (context) => withAccount(context, accounts, (account) => {
const targetUid = headerOrPayloadId(context, 'userid') ?? '';
const newRole = parseRoleParam(context);
if (!targetUid || newRole === undefined || !clans.changeMemberRole(account, targetUid, newRole)) {
return { kind: 'error', code: 'NOT_AVAILABLE' };
}
const targetAccount = accounts.byUserId(targetUid);
if (targetAccount) profiles.profileOf(targetAccount.userId);
return { kind: 'done' };
});
}
export function clanEditBlacklistAction(accounts: AccountStore, clans: ClanStore): CharActionHandler {
return (context) => withAccount(context, accounts, (account) => {
const targetUid = headerOrPayloadId(context, 'userid') ?? '';
const clanId = headerOrPayloadId(context, '_id');
const mode = headerOrPayloadString(context, 'mode');
if (mode !== 'addToBlackList' && mode !== 'delFromBlackList') {
return { kind: 'error', code: 'BAD_PARAMS' };
}
const comments = headerOrPayloadString(context, 'comments') ?? '';
const targetNick = accounts.byUserId(targetUid)?.nick ?? '';
if (!targetUid || !clans.editBlacklist(account, clanId, targetUid, targetNick, mode === 'addToBlackList', comments)) {
return { kind: 'error', code: 'NOT_AVAILABLE' };
}
return { kind: 'done' };
});
}
export function setClanBestRewardsAction(accounts: AccountStore, clans: ClanStore): CharActionHandler {
return (context) => withAccount(context, accounts, (account) => {
let parsed: { clanId?: string; bestRewards?: ClanBestReward[] };
try {
parsed = JSON.parse(context.rawText || '{}') as { clanId?: string; bestRewards?: ClanBestReward[] };
} catch {
return { kind: 'error', code: 'BAD_JSON' };
}
const clanId = parsed.clanId ?? clans.clanOfUser(account.userId)?.clan.id;
if (!clanId || !Array.isArray(parsed.bestRewards) || !clans.setBestRewards(clanId, account.userId, parsed.bestRewards)) {
return { kind: 'error', code: 'NOT_AVAILABLE' };
}
return { kind: 'done' };
});
}
/**
* Native `0x29d150` and `0x29d540` write `role:i=<ECMR_*>` into the request DataBlock; also
* accept role name strings in case a script caller passes `"REGULAR"` / `"OFFICER"` in headers.
*/
function parseRoleParam(context: CharActionContext): number | undefined {
const intRole = headerOrPayloadInt(context, 'role');
if (intRole !== undefined && intRole >= 1 && intRole <= 6) return intRole;
const strRole = headerOrPayloadString(context, 'role');
return strRole ? roleCodeFromString(strRole) : undefined;
}
@@ -0,0 +1,20 @@
/**
* `cln_update` (aces.exe 2.61.0.37 0x29f3ee, job type 3 -> `onUpdateProfile`):
* triggered by `save_online_single_job` when the client marks seen user logs as disabled
* (`scripts/userLog/userlogUtils.nut` `disableSeenUserlogs`, tag 223) or updates hangar
* auto-repair / auto-refill / auto-buy-modifications and map preferences. Answers the whole
* updated profile.
*/
import type { AccountStore } from '../../accounts/account-store.ts';
import { applyClientProfileUpdate } from '../../profile/profile-client-settings.ts';
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
import { ACCEPTED } from '../../research/rule-outcome.ts';
import type { CharActionHandler } from '../char-action.ts';
import { ruleAction } from './rule-answer.ts';
export function clientUpdateAction(profiles: PlayerProfiles, accounts: AccountStore): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => (profile) => {
applyClientProfileUpdate(profile, payload);
return ACCEPTED;
});
}
@@ -0,0 +1,81 @@
/**
* Char actions for `online_storage` / `generalBlk` cloud settings sync (implementation notes;
* aces.exe 2.61.0.37: `cln_get_meta_blk` 0x4662b3f, `cln_get_general_blk` 0x46677df,
* `cln_set_general_blk` 0x4666c51, `cln_bulk_set_gblk` 0x4663cfd).
*/
import { emptyBlock } from '@wto/blk';
import type { AccountStore } from '../../accounts/account-store.ts';
import { isSupportedGeneralBlkType, type CloudSettingsStore } from '../../cloud-settings/cloud-settings-store.ts';
import type { CharActionHandler } from '../char-action.ts';
import {
buildContainerBlk,
computeContentHash,
isPbbdStream,
normalizeContainerBlk,
parsePbbdBulkUploads,
unpackCloudBlk,
} from '../pbbd-stream.ts';
import { withAccount } from './account-context.ts';
import { headerOrPayloadInt, headerOrPayloadString } from './payload-params.ts';
/**
* `cln_get_meta_blk`: returns schema, compression negotiation, and saved block versions/hashes.
* `GetMetaHandler::handleResponse` (0x46659c0 -> 0x3280a50) parses the raw HTTP body directly
* with `DataBlock::loadFromStream` without stripping the `'i'` char compression marker.
*/
export function getMetaBlkAction(accounts: AccountStore, cloudSettings: CloudSettingsStore): CharActionHandler {
return (context) => withAccount(context, accounts, (account) => ({
kind: 'raw-blk',
blk: cloudSettings.buildMetaBlk(account.userId),
}));
}
/**
* `cln_get_general_blk`: returns `ContainerBlk` (`version:i`, `content { ... }`) for a valid `blkType`.
* `LoadingHandler::handleResponse` (0x4667930 -> `ContainerBlk::load` 0x466a9e0 -> 0x3280a50)
* likewise reads bare binary BLK directly from the HTTP response buffer.
*/
export function getGeneralBlkAction(accounts: AccountStore, cloudSettings: CloudSettingsStore): CharActionHandler {
return (context) => withAccount(context, accounts, (account) => {
const blkType = headerOrPayloadString(context, 'blkType');
if (!blkType || !isSupportedGeneralBlkType(blkType)) return { kind: 'error', code: 'BAD_PARAM' };
const stored = cloudSettings.loadContainer(account.userId, blkType) ?? buildContainerBlk(1, emptyBlock('content'));
return { kind: 'raw-blk', blk: stored };
});
}
/** `cln_set_general_blk`: stores a single `ContainerBlk` uploaded by the client and answers `!OK`. */
export function setGeneralBlkAction(accounts: AccountStore, cloudSettings: CloudSettingsStore): CharActionHandler {
return (context) => withAccount(context, accounts, (account) => {
const blkType = headerOrPayloadString(context, 'type') ?? headerOrPayloadString(context, 'blkType');
if (!blkType || !isSupportedGeneralBlkType(blkType)) return { kind: 'error', code: 'BAD_PARAM' };
const rawVer = headerOrPayloadInt(context, 'version');
const headerVersion = rawVer !== undefined && rawVer > 0 ? rawVer : 1;
const rawBody = context.rawBody ?? new Uint8Array(0);
const decoded = unpackCloudBlk(rawBody, context.headerParam('compr')) ?? context.payload;
if (!decoded) return { kind: 'error', code: 'BAD_PARAM' };
const normalized = normalizeContainerBlk(decoded, headerVersion);
const contentHash = headerOrPayloadString(context, 'contentHash') ?? computeContentHash(normalized.content);
const ok = cloudSettings.saveUpload(account.userId, {
blkType,
version: normalized.version,
contentHash,
container: normalized.container,
});
return ok ? { kind: 'done' } : { kind: 'error', code: 'BAD_PARAM' };
});
}
/** `cln_bulk_set_gblk`: unpacks a `PBBD` batch stream (`store_gblk` / `bigquery` / `logout`) and answers `!OK`. */
export function bulkSetGblkAction(accounts: AccountStore, cloudSettings: CloudSettingsStore): CharActionHandler {
return (context) => withAccount(context, accounts, (account) => {
const rawBody = context.rawBody ?? new Uint8Array(0);
if (rawBody.byteLength === 0 || !isPbbdStream(rawBody)) return { kind: 'error', code: 'BAD_PARAM' };
const uploads = parsePbbdBulkUploads(rawBody);
if (uploads.length > 0) cloudSettings.saveBulkUploads(account.userId, uploads);
return { kind: 'done' };
});
}
@@ -0,0 +1,70 @@
/**
* Crew actions. The client applies the answer to each as a profile update (aces.exe
* 2.61.0.37 GameSaveData::onAsyncEconTransComplete 0xeb5f60: job types 11 and 13 are both in
* the profile set, mask 0x301800822fbf at 0xeb61c4), so each answers the whole updated profile.
*
* cln_bulk_train_aircraft (job type 13, sent with char_send_blk, 0x2991f0): put vehicles into
* several crew slots at once; the stock slotbar sends it when the player applies a slotbar
* preset (gui.vromfs.bin scripts/crew/crewTrain.nut batchTrainCrew). Body: the crew slot list
* (crew-slots-payload.ts).
*
* cln_train_aircraft (job type 11, sent by the native chard.trainCrewAircraft, 0x299b40):
* take a vehicle into one crew slot, or clear the slot (scripts/crew/crewTakeUnitProcess.nut),
* or only train the crew for it (scripts/crew/crewActionsWithMsgBox.nut
* trainCrewUnitWithoutSwitchCurrUnit). Body:
* aircraft:t the vehicle; "" clears the slot
* idx:i the crew id
* keep_curr:b yes: train the crew for the vehicle, leave the slot as it is
*/
import { findParam, type BlkBlock } from '@wto/blk';
import type { AccountStore } from '../../accounts/account-store.ts';
import type { CrewSkillCatalogue } from '../../crew/crew-skill-rules.ts';
import { trainingFee } from '../../crew/crew-training.ts';
import { clientProfile } from '../../profile/client-profile.ts';
import { assignCrewSlots, canAssignCrewSlots, trainCrewKeepingSlot, type CrewSlotAssignment } from '../../profile/crew-slots.ts';
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
import { canAfford, pay } from '../../profile/profile-currency.ts';
import type { CharActionHandler } from '../char-action.ts';
import { withAccount } from './account-context.ts';
import { readCrewSlots } from './crew-slots-payload.ts';
export function bulkTrainCrews(profiles: PlayerProfiles, accounts: AccountStore, crew: CrewSkillCatalogue): CharActionHandler {
return (context) => withAccount(context, accounts, (account) => {
const assignments = context.payload && readCrewSlots(context.payload);
const current = profiles.profileOf(account.userId);
if (!assignments || !canAssignCrewSlots(current, assignments)) return { kind: 'error', code: 'BAD_PARAMS' };
const fee = trainingFee(current, crew, assignments);
if (!canAfford(current, fee)) return { kind: 'error', code: 'NOT_ENOUGH_MONEY' };
const profile = profiles.update(account.userId, (saved) => {
pay(saved, fee);
assignCrewSlots(saved, assignments);
});
return { kind: 'data', blk: clientProfile(profile, account) };
});
}
export function trainCrew(profiles: PlayerProfiles, accounts: AccountStore, crew: CrewSkillCatalogue): CharActionHandler {
return (context) => withAccount(context, accounts, (account) => {
const request = context.payload && readTrainCrew(context.payload);
if (!request || (request.keepCurrent && request.vehicle === '')) return { kind: 'error', code: 'BAD_PARAMS' };
const { keepCurrent, ...assignment } = request;
const current = profiles.profileOf(account.userId);
if (!canAssignCrewSlots(current, [assignment])) return { kind: 'error', code: 'BAD_PARAMS' };
const fee = trainingFee(current, crew, [assignment]);
if (!canAfford(current, fee)) return { kind: 'error', code: 'NOT_ENOUGH_MONEY' };
const profile = profiles.update(account.userId, (saved) => {
pay(saved, fee);
if (keepCurrent) trainCrewKeepingSlot(saved, assignment);
else assignCrewSlots(saved, [assignment]);
});
return { kind: 'data', blk: clientProfile(profile, account) };
});
}
function readTrainCrew(payload: BlkBlock): (CrewSlotAssignment & { readonly keepCurrent: boolean }) | undefined {
const vehicle = findParam(payload, 'aircraft')?.value;
const crewId = findParam(payload, 'idx')?.value;
const keepCurrent = findParam(payload, 'keep_curr')?.value;
if (vehicle?.type !== 'string' || crewId?.type !== 'int') return undefined;
return { crewId: crewId.value, vehicle: vehicle.value, keepCurrent: keepCurrent?.type === 'bool' && keepCurrent.value };
}
@@ -0,0 +1,42 @@
/**
* Crew skill actions. All three are sent by native functions with job
* type 1, a profile update, so each answers the whole profile. The crew is id:i (crews/c<id>).
*
* cln_upgrade_crew (shop_upgrade_crew, aces.exe 0x29aad0): <page>{ <skill>:i=levels to add } ... id:i
* cln_purchase_skill_points (shop_purchase_skillpoints, 0x29e220): id:i pack:t
* cln_specialize_crew (shop_specialize_crew, 0x29ad40): id:i aircraft:t
*/
import type { AccountStore } from '../../accounts/account-store.ts';
import { buySkillPoints, specializeCrew, upgradeCrewSkills, type CrewSkillCatalogue, type SkillRaise } from '../../crew/crew-skill-rules.ts';
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
import type { CharActionHandler } from '../char-action.ts';
import { intParam, stringParam } from './payload-params.ts';
import { ruleAction } from './rule-answer.ts';
export function upgradeCrewAction(profiles: PlayerProfiles, accounts: AccountStore, crew: CrewSkillCatalogue): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => {
const crewId = intParam(payload, 'id');
if (crewId === undefined) return undefined;
const raises: SkillRaise[] = payload.blocks.flatMap((page) => page.params.flatMap((param) =>
param.value.type === 'int' && param.value.value > 0 ? [{ page: page.name, skill: param.name, levels: param.value.value }] : []));
return (profile) => upgradeCrewSkills(profile, crew, crewId, raises);
});
}
export function purchaseSkillPointsAction(profiles: PlayerProfiles, accounts: AccountStore, crew: CrewSkillCatalogue): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => {
const crewId = intParam(payload, 'id');
const pack = stringParam(payload, 'pack');
if (crewId === undefined || pack === undefined) return undefined;
return (profile) => buySkillPoints(profile, crew, crewId, pack);
});
}
export function specializeCrewAction(profiles: PlayerProfiles, accounts: AccountStore, crew: CrewSkillCatalogue): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => {
const crewId = intParam(payload, 'id');
const vehicle = stringParam(payload, 'aircraft');
if (crewId === undefined || vehicle === undefined) return undefined;
return (profile) => specializeCrew(profile, crew, crewId, vehicle);
});
}
@@ -0,0 +1,26 @@
/**
* The crew slot list in a char request body, written by the stock scripts
* (gui.vromfs.bin scripts/crew/crewTrain.nut createBatchTrainCrewRequestBlk):
*
* batchTrainCrew{
* trainCrew{ crewId:i=10 unitName:t="cr_32" }
* trainCrew{ crewId:i=11 unitName:t="" } empty: leave the slot empty
* }
*/
import { findBlock, findParam, type BlkBlock } from '@wto/blk';
import type { CrewSlotAssignment } from '../../profile/crew-slots.ts';
/** The list, empty when the body has none, or undefined when an entry is malformed. */
export function readCrewSlots(payload: BlkBlock): CrewSlotAssignment[] | undefined {
const batch = findBlock(payload, 'batchTrainCrew');
if (!batch) return [];
const result: CrewSlotAssignment[] = [];
for (const entry of batch.blocks) {
if (entry.name !== 'trainCrew') continue;
const crewId = findParam(entry, 'crewId')?.value;
const vehicle = findParam(entry, 'unitName')?.value;
if (crewId?.type !== 'int' || vehicle?.type !== 'string') return undefined;
result.push({ crewId: crewId.value, vehicle: vehicle.value });
}
return result;
}
@@ -0,0 +1,27 @@
/**
* Buying decorations. cln_buy_resource is sent with char_send_blk (job
* type 13), so the answer is the whole profile.
*
* cln_buy_resource (scripts customization/decoratorAcquire.nut buyResourceImpl):
* name:t the skin, decal or attachable
* type:t skin | decal | attachable
* unitName:t the vehicle (skins)
* cost:i costGold:i
*/
import type { AccountStore } from '../../accounts/account-store.ts';
import { buyDecoration, decorKey, isDecorKind, type DecorShop } from '../../decor/decor-purchase.ts';
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
import type { CharActionHandler } from '../char-action.ts';
import { intParam, stringParam } from './payload-params.ts';
import { ruleAction } from './rule-answer.ts';
export function buyResourceAction(profiles: PlayerProfiles, accounts: AccountStore, decor: DecorShop): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => {
const name = stringParam(payload, 'name');
const type = stringParam(payload, 'type');
if (name === undefined || type === undefined || !isDecorKind(type)) return undefined;
const key = decorKey(type, name, stringParam(payload, 'unitName') ?? '');
const offered = { silverLions: intParam(payload, 'cost') ?? 0, goldenEagles: intParam(payload, 'costGold') ?? 0 };
return (profile) => buyDecoration(profile, decor, type, key, offered);
});
}
@@ -0,0 +1,23 @@
/**
* Saving decal and attachable layouts. Both are sent by native functions
* whose job types are not profile updates: cln_save_decals is type 0x1f (aces.exe 0x2a1910),
* cln_save_attachables type 0x20 (0x2a1c30); the client takes the whole answer as its decals or
* attachables block (GameSaveData::onAsyncEconTransComplete 0xeb7a14 / 0xeb7a45). So each answers
* the full block of its kind after storing the request.
*
* Request (lab round 21): <vehicle>{ <skin>{ ... } }
*/
import type { AccountStore } from '../../accounts/account-store.ts';
import { decorLayouts, saveDecorLayouts, type DecorLayoutKind } from '../../profile/profile-decor-layouts.ts';
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
import type { CharActionHandler } from '../char-action.ts';
import { withAccount } from './account-context.ts';
export function saveDecorLayoutsAction(profiles: PlayerProfiles, accounts: AccountStore, kind: DecorLayoutKind): CharActionHandler {
return (context) => withAccount(context, accounts, (account) => {
const changes = context.payload;
if (!changes) return { kind: 'error', code: 'BAD_PARAMS' };
const profile = profiles.update(account.userId, (saved) => saveDecorLayouts(saved, kind, changes));
return { kind: 'data', blk: decorLayouts(profile, kind) };
});
}
@@ -0,0 +1,221 @@
/**
* Miscellaneous hangar char actions that mutate the player's profile and return the full
* updated clientProfile:
* - GameSaveData::onAsyncEconTransComplete (aces.exe 2.61.0.37 0xeb5f60, profile mask
* 0x301800822fbf at 0xeb61c4) applies both job type 13 (char_send_blk, 0x2991f0) and job
* type 7 (shop_repair_all 0x29a370 / shop_repair_aircraft 0x29a610) as full profile updates.
*
* Covered actions:
* - cln_set_dest_rp_unit_type (scripts/shop/shop.nut:2353, job type 13)
* - cln_unlock_crew (scripts/crew/crewActions.nut:18, job type 13)
* - cln_prepare_aircraft (scripts/unit/unitActions.nut:147 job 13; 0x29a610 job 7)
* - cln_repair_all (shop_repair_all 0x29a370, job type 7)
* - cln_repair_all_in_slots (shop_repair_all 0x29a370, job type 7)
* The repair requests carry no price (0x29a370 sends country, 0x29a610 name and weapon): the
* repair costs what the client shows for it (repair/repair-rules.ts currentCost).
* - cln_add_to_wish_list (scripts/wishlist/wishlistManager.nut:39, job type 13)
* - cln_remove_from_wish_list (scripts/wishlist/wishlistManager.nut:48, job type 13)
*/
import { findBlock, type BlkBlock } from '@wto/blk';
import type { AccountStore } from '../../accounts/account-store.ts';
import { int64Field, removeParam } from '../../profile/blk-fields.ts';
import { clientProfile } from '../../profile/client-profile.ts';
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
import { allCrews, crewOf, crewVehiclesOfCountry } from '../../profile/profile-crews.ts';
import { canAfford, pay } from '../../profile/profile-currency.ts';
import { applySetDestinationRpRule } from '../../profile/profile-dest-rp.ts';
import { ownsVehicle } from '../../profile/profile-hangar.ts';
import {
addWishlistUnit,
DEFAULT_WISHLIST_LIMITS,
removeWishlistUnit,
type WishlistLimits,
} from '../../profile/profile-wishlist.ts';
import { serverTimeNow, serverTimeToUnixSeconds } from '../../profile/server-time.ts';
import { clearVehicleDamage, isDamaged } from '../../profile/profile-vehicle-condition.ts';
import type { RepairRules } from '../../repair/repair-rules.ts';
import type { ResearchRules } from '../../research/research-rules.ts';
import { ACCEPTED, refused, type RuleOutcome } from '../../research/rule-outcome.ts';
import type { TechTree } from '../../research/tech-tree.ts';
import type { CharActionContext, CharActionHandler } from '../char-action.ts';
import { withAccount } from './account-context.ts';
import {
headerOrPayloadBool,
headerOrPayloadInt,
headerOrPayloadString,
} from './payload-params.ts';
export type ActionEntry = [string, CharActionHandler];
export interface HangarMiscActionDependencies {
readonly profiles: PlayerProfiles;
readonly accounts: AccountStore;
readonly research: ResearchRules;
readonly repair: RepairRules;
readonly wishlistLimits?: WishlistLimits;
}
const HANGAR_BLOCK = 'hangar';
const ALL_COUNTRIES = 'all';
const WISHLIST_UNIT_TYPE = 'unit';
export function hangarMiscActionEntries(deps: HangarMiscActionDependencies): ActionEntry[] {
const { profiles, accounts, research, repair } = deps;
const { techTree } = research;
const limits = deps.wishlistLimits ?? DEFAULT_WISHLIST_LIMITS;
return [
['cln_set_dest_rp_unit_type', setDestRpUnitTypeAction(profiles, accounts, techTree)],
['cln_unlock_crew', unlockCrewAction(profiles, accounts)],
['cln_prepare_aircraft', prepareAircraftAction(profiles, accounts, repair)],
['cln_repair_all', repairVehiclesAction(profiles, accounts, techTree, repair, false)],
['cln_repair_all_in_slots', repairVehiclesAction(profiles, accounts, techTree, repair, true)],
['cln_add_to_wish_list', addToWishlistAction(profiles, accounts, techTree, limits)],
['cln_remove_from_wish_list', removeFromWishlistAction(profiles, accounts)],
];
}
function runProfileRule(
context: CharActionContext,
profiles: PlayerProfiles,
accounts: AccountStore,
rule: (profile: BlkBlock) => RuleOutcome,
) {
return withAccount(context, accounts, (account) => {
let outcome: RuleOutcome = refused('BAD_PARAMS');
const updated = profiles.updateWhen(account.userId, (saved) => {
outcome = rule(saved);
return outcome.ok;
});
if (updated) return { kind: 'data', blk: clientProfile(updated, account) };
return { kind: 'error', code: outcome.ok ? 'BAD_PARAMS' : outcome.refusal };
});
}
function setDestRpUnitTypeAction(profiles: PlayerProfiles, accounts: AccountStore, techTree: TechTree): CharActionHandler {
return (context) => {
const country = headerOrPayloadString(context, 'country');
const srcType = headerOrPayloadInt(context, 'srcType');
const destType = headerOrPayloadInt(context, 'destType');
if (!country || srcType === undefined || destType === undefined) return { kind: 'error', code: 'BAD_PARAMS' };
return runProfileRule(context, profiles, accounts, (saved) =>
applySetDestinationRpRule(saved, techTree, country, srcType, destType));
};
}
function unlockCrewAction(profiles: PlayerProfiles, accounts: AccountStore): CharActionHandler {
return (context) => {
const crewId = headerOrPayloadInt(context, 'crew');
const byGold = headerOrPayloadBool(context, 'gold') ?? false;
const cost = headerOrPayloadInt(context, 'cost') ?? 0;
const costGold = headerOrPayloadInt(context, 'costGold') ?? 0;
if (crewId === undefined || crewId < 0 || cost < 0 || costGold < 0) return { kind: 'error', code: 'BAD_PARAMS' };
return runProfileRule(context, profiles, accounts, (saved) => {
const crew = crewOf(saved, crewId);
if (!crew) return refused('BAD_PARAMS');
const nowSec = BigInt(serverTimeToUnixSeconds(serverTimeNow()));
const lockedTill = int64Field(crew, 'lockedTill', 0n);
if (lockedTill > nowSec) {
const price = { silverLions: byGold ? 0 : cost, goldenEagles: byGold ? costGold : 0 };
if (!canAfford(saved, price)) return refused('NOT_ENOUGH_MONEY');
pay(saved, price);
}
// Crew lock state in profile.blk (aces.exe 0x8fa632, 0x93ae07..0x93ae1b): lockedTill:i64, lockedRoomId:i64.
removeParam(crew, 'lockedTill');
removeParam(crew, 'lockedRoomId');
return ACCEPTED;
});
};
}
function prepareAircraftAction(profiles: PlayerProfiles, accounts: AccountStore, repair: RepairRules): CharActionHandler {
return (context) => {
const unit = headerOrPayloadString(context, 'name') ?? headerOrPayloadString(context, 'aircraft');
if (!unit) return { kind: 'error', code: 'BAD_PARAMS' };
return runProfileRule(context, profiles, accounts, (saved) => {
if (!ownsVehicle(saved, unit)) return refused('NOT_AVAILABLE');
if (!isDamaged(saved, unit)) return ACCEPTED;
const price = { silverLions: repair.currentCost(saved, unit), goldenEagles: 0 };
if (!canAfford(saved, price)) return refused('NOT_ENOUGH_MONEY');
pay(saved, price);
clearVehicleDamage(saved, unit);
return ACCEPTED;
});
};
}
function repairVehiclesAction(
profiles: PlayerProfiles,
accounts: AccountStore,
techTree: TechTree,
repair: RepairRules,
inSlotsOnly: boolean,
): CharActionHandler {
return (context) => {
const rawCountry = headerOrPayloadString(context, 'country');
const country = rawCountry && rawCountry.length > 0 ? rawCountry : ALL_COUNTRIES;
if (country !== ALL_COUNTRIES && !techTree.hasCountry(country)) return { kind: 'error', code: 'BAD_PARAMS' };
return runProfileRule(context, profiles, accounts, (saved) => {
const hangar = findBlock(saved, HANGAR_BLOCK);
if (!hangar) return ACCEPTED;
const targets = [...collectRepairTargetUnits(saved, hangar, techTree, country, inSlotsOnly)].filter((unit) => isDamaged(saved, unit));
const price = { silverLions: targets.reduce((sum, unit) => sum + repair.currentCost(saved, unit), 0), goldenEagles: 0 };
if (!canAfford(saved, price)) return refused('NOT_ENOUGH_MONEY');
pay(saved, price);
for (const unit of targets) clearVehicleDamage(saved, unit);
return ACCEPTED;
});
};
}
function collectRepairTargetUnits(
profile: BlkBlock,
hangar: BlkBlock,
techTree: TechTree,
country: string,
inSlotsOnly: boolean,
): Set<string> {
if (inSlotsOnly) {
if (country !== ALL_COUNTRIES) return new Set(crewVehiclesOfCountry(profile, country));
const slotted = new Set<string>();
for (const crew of allCrews(profile)) {
const current = findBlock(crew, 'aircrafts')?.params.find((param) => param.name === 'current')?.value;
if (current?.type === 'string' && current.value.length > 0) slotted.add(current.value);
}
return slotted;
}
if (country === ALL_COUNTRIES) return new Set(hangar.blocks.map((entry) => entry.name));
return new Set(
hangar.blocks
.filter((entry) => techTree.vehicle(entry.name)?.country === country)
.map((entry) => entry.name),
);
}
function addToWishlistAction(
profiles: PlayerProfiles,
accounts: AccountStore,
techTree: TechTree,
limits: WishlistLimits,
): CharActionHandler {
return (context) => {
const itemType = headerOrPayloadString(context, 'type') ?? WISHLIST_UNIT_TYPE;
const unit = headerOrPayloadString(context, 'unit');
const comment = headerOrPayloadString(context, 'comment') ?? '';
if (itemType !== WISHLIST_UNIT_TYPE || !unit) return { kind: 'error', code: 'BAD_PARAMS' };
const nowSec = serverTimeToUnixSeconds(serverTimeNow());
return runProfileRule(context, profiles, accounts, (saved) =>
addWishlistUnit(saved, techTree, unit, comment, nowSec, limits));
};
}
function removeFromWishlistAction(profiles: PlayerProfiles, accounts: AccountStore): CharActionHandler {
return (context) => {
const itemType = headerOrPayloadString(context, 'type') ?? WISHLIST_UNIT_TYPE;
const unit = headerOrPayloadString(context, 'unit');
if (itemType !== WISHLIST_UNIT_TYPE || !unit) return { kind: 'error', code: 'BAD_PARAMS' };
return runProfileRule(context, profiles, accounts, (saved) => removeWishlistUnit(saved, unit));
};
}
@@ -0,0 +1,202 @@
/**
* Char actions for external inventory, item recycling, and classic trophies
*:
* - cln_consume_inventory_item itemId:i quantity:i -> full profile
* - cln_multi_consume_inventory_item_json text BLK items{ item{ itemId:i quantity:i } } -> JSON {"revertedItems":[]}
* - cln_inventory_purchase_item key:t itemDefId:i wpCost:i goldCost:i [amount:i] -> full profile
* - cln_recycle_items items{ item{ itemId:t [count:i] } } -> full profile
* - cln_inventory_exchange_items JSON { outputitemdefid, quantity, materials } -> JSON item_json delta
* - cln_buy_trophy name:t index:i cost:i costGold:i -> full profile
*/
import type { BlkBlock } from '@wto/blk';
import type { AccountStore } from '../../accounts/account-store.ts';
import {
consumeInventoryCoupon,
exchangeInventoryItems,
multiConsumeInventoryItems,
purchaseExternalInventoryItem,
recycleClassicItems,
type ExchangeItemDelta,
} from '../../inventory/inventory-rules.ts';
import { deltaToInventoryJson, parseExchangeItemsRequest } from '../../inventory/inventory-wire.ts';
import type { InventoryCatalogue } from '../../inventory/itemdef-catalogue.ts';
import { buyTrophy, type TrophyCatalogue } from '../../inventory/trophy-catalogue.ts';
import type { ItemCatalogue } from '../../items/item-catalogue.ts';
import { clientProfile } from '../../profile/client-profile.ts';
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
import { serverTimeNow } from '../../profile/server-time.ts';
import type { RuleOutcome } from '../../research/rule-outcome.ts';
import type { CharActionHandler } from '../char-action.ts';
import { withAccount } from './account-context.ts';
import { intParam, stringParam } from './payload-params.ts';
import { ruleAction } from './rule-answer.ts';
function profileRuleWithNotify(
profiles: PlayerProfiles,
accounts: AccountStore,
notifyInventoryChanged: () => void,
fromPayload: (payload: BlkBlock) => ((profile: BlkBlock) => RuleOutcome) | undefined,
): CharActionHandler {
return (context) => withAccount(context, accounts, (account) => {
const rule = context.payload && fromPayload(context.payload);
if (!rule) return { kind: 'error', code: 'BAD_PARAMS' };
let outcome: RuleOutcome = { ok: false, refusal: 'BAD_PARAMS' };
const saved = profiles.updateWhen(account.userId, (profile) => {
outcome = rule(profile);
return outcome.ok;
});
if (!saved) return { kind: 'error', code: outcome.ok ? 'BAD_PARAMS' : outcome.refusal };
notifyInventoryChanged();
return { kind: 'data', blk: clientProfile(saved, account) };
});
}
export function consumeInventoryItemAction(
profiles: PlayerProfiles,
accounts: AccountStore,
inventory: InventoryCatalogue,
items: ItemCatalogue,
notifyInventoryChanged: () => void,
): CharActionHandler {
return profileRuleWithNotify(profiles, accounts, notifyInventoryChanged, (payload) => {
const itemId = intParam(payload, 'itemId');
const quantity = intParam(payload, 'quantity') ?? 1;
if (itemId === undefined) return undefined;
return (profile) => consumeInventoryCoupon(profile, inventory, items, String(itemId), quantity, serverTimeNow());
});
}
export function purchaseInventoryItemAction(
profiles: PlayerProfiles,
accounts: AccountStore,
inventory: InventoryCatalogue,
notifyInventoryChanged: () => void,
): CharActionHandler {
return profileRuleWithNotify(profiles, accounts, notifyInventoryChanged, (payload) => {
const itemDefId = intParam(payload, 'itemDefId');
if (itemDefId === undefined) return undefined;
const amount = intParam(payload, 'amount') ?? 1;
const wpCost = intParam(payload, 'wpCost') ?? 0;
const goldCost = intParam(payload, 'goldCost') ?? 0;
return (profile) => purchaseExternalInventoryItem(profile, inventory, itemDefId, amount, wpCost, goldCost);
});
}
export function recycleItemsAction(
profiles: PlayerProfiles,
accounts: AccountStore,
items: ItemCatalogue,
notifyInventoryChanged: () => void,
): CharActionHandler {
return profileRuleWithNotify(profiles, accounts, notifyInventoryChanged, (payload) => {
const itemsBlock = payload.blocks.find((b) => b.name === 'items');
if (!itemsBlock) return undefined;
const requests = itemsBlock.blocks
.filter((b) => b.name === 'item')
.map((b) => ({
uid: stringParam(b, 'itemId') ?? '',
count: intParam(b, 'count') ?? 1,
}));
if (requests.length === 0) return undefined;
return (profile) => recycleClassicItems(profile, items, requests);
});
}
export function multiConsumeInventoryItemsAction(
profiles: PlayerProfiles,
accounts: AccountStore,
inventory: InventoryCatalogue,
items: ItemCatalogue,
notifyInventoryChanged: () => void,
): CharActionHandler {
return (context) => withAccount(context, accounts, (account) => {
const requests = parseMultiConsumeItems(context.payload, context.rawText);
if (requests.length === 0) return { kind: 'json', data: { revertedItems: [] } };
let revertedItems: number[] = [];
profiles.update(account.userId, (saved) => {
const res = multiConsumeInventoryItems(saved, inventory, items, requests, serverTimeNow());
revertedItems = res.revertedItems;
});
notifyInventoryChanged();
return { kind: 'json', data: { revertedItems } };
});
}
export function inventoryExchangeAction(
profiles: PlayerProfiles,
accounts: AccountStore,
inventory: InventoryCatalogue,
): CharActionHandler {
return (context) => withAccount(context, accounts, (account) => {
const parsed = parseExchangeItemsRequest(context.rawText);
if (!parsed) return { kind: 'error', code: 'BAD_JSON' };
let delta: ExchangeItemDelta[] | undefined;
let errorCode = 'EXCHANGE_FAILED';
profiles.updateWhen(account.userId, (saved) => {
const res = exchangeInventoryItems(
saved,
inventory,
parsed.outputItemDefId,
parsed.quantity,
parsed.materials,
);
if (!res.ok) {
errorCode = res.code;
return false;
}
delta = res.delta;
return true;
});
if (!delta) return { kind: 'error', code: errorCode };
return { kind: 'json', data: { response: { item_json: deltaToInventoryJson(delta, account.userId) } } };
});
}
export function buyTrophyAction(
profiles: PlayerProfiles,
accounts: AccountStore,
trophies: TrophyCatalogue,
items: ItemCatalogue,
): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => {
const name = stringParam(payload, 'name');
if (!name) return undefined;
const cost = intParam(payload, 'cost') ?? 0;
const costGold = intParam(payload, 'costGold') ?? 0;
return (profile) => buyTrophy(profile, trophies, items, name, cost, costGold, serverTimeNow());
});
}
function parseMultiConsumeItems(
blk: BlkBlock | undefined,
rawText: string,
): Array<{ readonly itemId: number; readonly quantity: number }> {
const fromBlk = blk?.blocks.find((b) => b.name === 'items');
if (fromBlk) {
return fromBlk.blocks
.filter((b) => b.name === 'item')
.flatMap((b) => {
const itemId = intParam(b, 'itemId');
const quantity = intParam(b, 'quantity') ?? 1;
return itemId !== undefined && quantity > 0 ? [{ itemId, quantity }] : [];
});
}
// `DataBlock.formatAsString()` emits `item{\n itemId:i=1\n quantity:i=1\n}` text blocks.
const results: Array<{ readonly itemId: number; readonly quantity: number }> = [];
const blockRegex = /item\s*\{([^}]*)\}/g;
let match: RegExpExecArray | null;
while ((match = blockRegex.exec(rawText)) !== null) {
const body = match[1] ?? '';
const idMatch = /itemId:i\s*=\s*(\d+)/.exec(body);
const qtyMatch = /quantity:i\s*=\s*(\d+)/.exec(body);
if (idMatch) {
const itemId = Number(idMatch[1]);
const quantity = qtyMatch ? Number(qtyMatch[1]) : 1;
if (Number.isSafeInteger(itemId) && quantity > 0) results.push({ itemId, quantity });
}
}
return results;
}
@@ -0,0 +1,66 @@
/**
* Classic item actions. All are sent with char_send_blk (job type
* 13), so each answers the whole profile.
*
* cln_buy_item name:t count:i cost:i costGold:i
* cln_set_current_booster name:t (uid)
* cln_set_current_personal_discount name:t (uid)
* cln_set_current_wager name:t (uid) wager:i
* cln_apply_spare_item uid:t unit:t useItemsCount:i
*/
import type { AccountStore } from '../../accounts/account-store.ts';
import { activateBooster, activateDiscount, startWager } from '../../items/item-activation.ts';
import type { ItemCatalogue } from '../../items/item-catalogue.ts';
import { buyItem } from '../../items/item-purchase.ts';
import { applyUniversalSpares } from '../../items/universal-spares.ts';
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
import { serverTimeNow } from '../../profile/server-time.ts';
import type { TechTree } from '../../research/tech-tree.ts';
import type { CharActionHandler } from '../char-action.ts';
import { intParam, stringParam } from './payload-params.ts';
import { ruleAction } from './rule-answer.ts';
export function buyItemAction(profiles: PlayerProfiles, accounts: AccountStore, items: ItemCatalogue): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => {
const name = stringParam(payload, 'name');
const pieces = intParam(payload, 'count');
if (name === undefined || pieces === undefined) return undefined;
const offered = { silverLions: intParam(payload, 'cost') ?? 0, goldenEagles: intParam(payload, 'costGold') ?? 0 };
return (profile) => buyItem(profile, items, name, pieces, offered, serverTimeNow());
});
}
export function activateBoosterAction(profiles: PlayerProfiles, accounts: AccountStore): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => {
const uid = stringParam(payload, 'name');
if (uid === undefined) return undefined;
return (profile) => activateBooster(profile, uid);
});
}
export function activateDiscountAction(profiles: PlayerProfiles, accounts: AccountStore, items: ItemCatalogue): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => {
const uid = stringParam(payload, 'name');
if (uid === undefined) return undefined;
return (profile) => activateDiscount(profile, items, uid, serverTimeNow());
});
}
export function startWagerAction(profiles: PlayerProfiles, accounts: AccountStore, items: ItemCatalogue): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => {
const uid = stringParam(payload, 'name');
const stake = intParam(payload, 'wager');
if (uid === undefined || stake === undefined) return undefined;
return (profile) => startWager(profile, items, uid, stake);
});
}
export function applySpareItemAction(profiles: PlayerProfiles, accounts: AccountStore, items: ItemCatalogue, techTree: TechTree): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => {
const uid = stringParam(payload, 'uid');
const vehicle = stringParam(payload, 'unit');
const pieces = intParam(payload, 'useItemsCount');
if (uid === undefined || vehicle === undefined || pieces === undefined) return undefined;
return (profile) => applyUniversalSpares(profile, items, techTree, uid, vehicle, pieces);
});
}
@@ -0,0 +1,86 @@
/**
* Modification, ammunition, weapon preset and spare actions. The
* purchases are sent with char_send_blk (job type 13); cln_enable_modifications by a native function with job type
* 0x17 (aces.exe 0x29aa21). Both types are profile updates, so each answers the whole profile.
*
* cln_buy_modification (scripts weaponry/weaponsPurchase.nut):
* aircraft:t modification:t open:b count:i cost:i costGold:i
* cln_buy_all_modification: unit:t forceOpen:b cost:i costGold:i
* cln_buy_spare_aircrafts: aircraft:t count:i cost:i costGold:i
* cln_buy_weapon: aircraft:t weapon:t count:i cost:i costGold:i
* cln_enable_modifications (shop_enable_modifications, 0x17a5020 -> 0x29a890; lab round 18):
* <vehicle>{ <modification>:b=yes ... } ...
*/
import type { BlkBlock } from '@wto/blk';
import type { AccountStore } from '../../accounts/account-store.ts';
import type { EquipmentCatalogue } from '../../modifications/equipment-catalogue.ts';
import { buyAllModifications, buyModification, enableModifications } from '../../modifications/modification-purchase.ts';
import { buySpares } from '../../modifications/spare-purchase.ts';
import { saveWeaponPresets } from '../../modifications/weapon-presets.ts';
import { buyWeapons } from '../../modifications/weapon-purchase.ts';
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
import type { CharActionHandler } from '../char-action.ts';
import { boolParam, intParam, stringParam } from './payload-params.ts';
import { ruleAction } from './rule-answer.ts';
export function buyModificationAction(profiles: PlayerProfiles, accounts: AccountStore, equipment: EquipmentCatalogue): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => {
const vehicle = stringParam(payload, 'aircraft');
const modification = stringParam(payload, 'modification');
if (vehicle === undefined || modification === undefined) return undefined;
const order = {
vehicle,
modification,
outright: boolParam(payload, 'open') ?? false,
amount: intParam(payload, 'count') ?? 1,
offered: offeredPrice(payload),
};
return (profile) => buyModification(profile, equipment, order);
});
}
export function buyAllModificationsAction(profiles: PlayerProfiles, accounts: AccountStore, equipment: EquipmentCatalogue): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => {
const vehicle = stringParam(payload, 'unit');
if (vehicle === undefined) return undefined;
const outright = boolParam(payload, 'forceOpen') ?? false;
const offered = offeredPrice(payload);
return (profile) => buyAllModifications(profile, equipment, vehicle, outright, offered);
});
}
export function buySparesAction(profiles: PlayerProfiles, accounts: AccountStore, equipment: EquipmentCatalogue): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => {
const vehicle = stringParam(payload, 'aircraft');
if (vehicle === undefined) return undefined;
const amount = intParam(payload, 'count') ?? 1;
const offered = offeredPrice(payload);
return (profile) => buySpares(profile, equipment, vehicle, amount, offered);
});
}
export function buyWeaponsAction(profiles: PlayerProfiles, accounts: AccountStore, equipment: EquipmentCatalogue): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => {
const vehicle = stringParam(payload, 'aircraft');
const weapon = stringParam(payload, 'weapon');
if (vehicle === undefined || weapon === undefined) return undefined;
const order = { vehicle, weapon, amount: intParam(payload, 'count') ?? 1, offered: offeredPrice(payload) };
return (profile) => buyWeapons(profile, equipment, order);
});
}
export function enableModificationsAction(profiles: PlayerProfiles, accounts: AccountStore, equipment: EquipmentCatalogue): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => {
const switches = payload.blocks.flatMap((vehicle) => vehicle.params.flatMap((param) =>
param.value.type === 'bool' ? [{ vehicle: vehicle.name, modification: param.name, enabled: param.value.value }] : []));
return (profile) => enableModifications(profile, equipment, switches);
});
}
export function saveWeaponPresetsAction(profiles: PlayerProfiles, accounts: AccountStore, equipment: EquipmentCatalogue): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => (profile) => saveWeaponPresets(profile, equipment, payload));
}
function offeredPrice(payload: BlkBlock) {
return { silverLions: intParam(payload, 'cost') ?? 0, goldenEagles: intParam(payload, 'costGold') ?? 0 };
}
@@ -0,0 +1,57 @@
/**
* Char actions of the online initialisation after sign-in, up to the profile
*.
*/
import { emptyBlock, setParam } from '@wto/blk';
import type { AccountStore } from '../../accounts/account-store.ts';
import type { CloudSettingsStore } from '../../cloud-settings/cloud-settings-store.ts';
import { clientProfile } from '../../profile/client-profile.ts';
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
import type { CharActionHandler } from '../char-action.ts';
import { withAccount } from './account-context.ts';
/**
* cln_get_initial_meta: server-side metadata the client reads in GameSaveData's initial-meta
* handling (aces.exe 0xeb5f60). binaryDataMetainfo lists server-side binary files the client
* must fetch and compare by hash; the local server has none, so the list is empty and no
* downloads follow. generalBlkMeta carries the cloud-settings schema and saved versions/hashes
*.
*/
export function initialMeta(accounts?: AccountStore, cloudSettings?: CloudSettingsStore): CharActionHandler {
return (context) => {
const meta = emptyBlock();
setParam(meta, 'machineId', { type: 'string', value: 'wto_local_machine' });
setParam(meta, 'bestCompression', { type: 'string', value: 'zstd' });
const account = context.userId !== undefined ? accounts?.byUserId(context.userId) : undefined;
const generalBlkMeta = cloudSettings
? cloudSettings.buildMetaBlk(account?.userId, 'generalBlkMeta')
: emptyBlock('generalBlkMeta');
meta.blocks.push(emptyBlock('binaryDataMetainfo'), generalBlkMeta);
return { kind: 'data', blk: meta };
};
}
/**
* cln_upd_entitlements_full: the profile request of the online initialisation stage
* CHAR_PROFILE_RECEIVED (sent at aces.exe 0x29f920 with headers onLogin and resetToken; the
* request body is the client's machine description). The answer is the whole profile: the
* job (EconomicSerializeJob, type 4) loads it as a BLK, and EconomicSerializeAction::
* performAction (0x295ef0) reads it into the client's profile with the profile serializer
* (0x917740) when it is not empty.
*/
export function entitlementsFull(profiles: PlayerProfiles, accounts: AccountStore): CharActionHandler {
return profileAnswer(profiles, accounts);
}
/** cln_legacy_get_userdata: the whole profile (ClientEconomicState::loadOnline, aces.exe 0x2a23b0). */
export function legacyUserData(profiles: PlayerProfiles, accounts: AccountStore): CharActionHandler {
return profileAnswer(profiles, accounts);
}
function profileAnswer(profiles: PlayerProfiles, accounts: AccountStore): CharActionHandler {
return (context) => withAccount(context, accounts, (account) => ({
kind: 'data',
blk: clientProfile(profiles.profileOf(account.userId), account),
}));
}
@@ -0,0 +1,71 @@
/** Read typed parameters from a char action's BLK payload or HTTP request headers. */
import { findParam, type BlkBlock } from '@wto/blk';
import type { CharActionContext } from '../char-action.ts';
export function stringParam(payload: BlkBlock, name: string): string | undefined {
const param = findParam(payload, name)?.value;
return param?.type === 'string' ? param.value : undefined;
}
export function intParam(payload: BlkBlock, name: string): number | undefined {
const param = findParam(payload, name)?.value;
return param?.type === 'int' ? param.value : undefined;
}
export function realParam(payload: BlkBlock, name: string): number | undefined {
const param = findParam(payload, name)?.value;
if (param?.type === 'real' || param?.type === 'int') {
return Number.isFinite(param.value) ? param.value : undefined;
}
return undefined;
}
export function boolParam(payload: BlkBlock, name: string): boolean | undefined {
const param = findParam(payload, name)?.value;
return param?.type === 'bool' ? param.value : undefined;
}
export function headerOrPayloadString(context: CharActionContext, name: string): string | undefined {
const fromPayload = context.payload ? stringParam(context.payload, name) : undefined;
return fromPayload ?? context.headerParam(name);
}
export function headerOrPayloadInt(context: CharActionContext, name: string): number | undefined {
if (context.payload) {
const fromPayload = intParam(context.payload, name);
if (fromPayload !== undefined) return fromPayload;
}
const hdr = context.headerParam(name)?.trim();
if (hdr !== undefined && /^-?\d+$/.test(hdr)) {
const parsed = Number(hdr);
if (Number.isSafeInteger(parsed)) return parsed;
}
return undefined;
}
export function headerOrPayloadBool(context: CharActionContext, name: string): boolean | undefined {
if (context.payload) {
const fromBool = boolParam(context.payload, name);
if (fromBool !== undefined) return fromBool;
const fromStr = stringParam(context.payload, name);
if (fromStr !== undefined) return parseTruthyFlag(fromStr);
}
const hdr = context.headerParam(name);
return hdr !== undefined ? parseTruthyFlag(hdr) : undefined;
}
export function headerOrPayloadId(context: CharActionContext, name: string): string | undefined {
if (context.payload) {
const param = findParam(context.payload, name)?.value;
if (param?.type === 'string' && param.value !== '') return param.value;
if (param?.type === 'int64') return param.value.toString();
if (param?.type === 'int') return String(param.value);
}
const hdr = context.headerParam(name);
return hdr && hdr !== '' ? hdr : undefined;
}
function parseTruthyFlag(raw: string): boolean {
const lower = raw.trim().toLowerCase();
return lower === 'yes' || lower === 'true' || lower === 'on' || lower === '1';
}
@@ -0,0 +1,112 @@
/**
* Player card actions. cln_select_title and cln_save_pilot_appearance
* are sent with char_send_blk (job type 13) and answer the whole profile; cln_get_users_terse_info
* (scripts user/usersInfoManager.nut, charRequestBlk) answers one block per requested user:
* request usersList="<uid>;<uid>", sent as a request header (char-action.ts headerParam)
* answer <uid>{ nick:t pilotIcon:t pilotId:t title:t clanTag:t clanName:t background:t frame:t
* shcType:t showcase{...} }
* or <uid>{ failed:b=yes } for unknown users
* cln_save_profile_showcase (scripts user/profileShowcase.nut saveShowcase, charSendBlk): one
* showcase type and its choices, answered with the whole profile; cln_get_showcases (scripts
* user/profileShowcasesData.nut, charRequestBlk): every saved showcase (showcase-rules.ts).
*/
import type { BlkBlock, BlkParam } from '@wto/blk';
import type { Account, AccountStore } from '../../accounts/account-store.ts';
import type { ClanStore } from '../../clans/clan-store.ts';
import type { ClanMemberRecord, ClanRecord } from '../../clans/clan-types.ts';
import { chooseTitle, saveAppearance } from '../../player-card/player-card-rules.ts';
import { currentShowcaseView, saveShowcase, showcasesAnswer } from '../../player-card/showcase-rules.ts';
import { appearance, chosenTitle } from '../../profile/profile-appearance.ts';
import { clanMembershipOf } from '../../profile/profile-clan.ts';
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
import type { TechTree } from '../../research/tech-tree.ts';
import type { CharActionHandler } from '../char-action.ts';
import { withAccount } from './account-context.ts';
import { stringParam } from './payload-params.ts';
import { ruleAction } from './rule-answer.ts';
export function selectTitleAction(profiles: PlayerProfiles, accounts: AccountStore): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => {
const title = stringParam(payload, 'name');
if (title === undefined) return undefined;
return (profile) => chooseTitle(profile, title);
});
}
export function savePilotAppearanceAction(profiles: PlayerProfiles, accounts: AccountStore): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => {
const choices = payload.params.flatMap((param) => param.value.type === 'string' ? [{ field: param.name, image: param.value.value }] : []);
return (profile) => saveAppearance(profile, choices);
});
}
export function saveShowcaseAction(profiles: PlayerProfiles, accounts: AccountStore): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => (profile) => saveShowcase(profile, payload));
}
export function showcasesAction(profiles: PlayerProfiles, accounts: AccountStore, techTree: TechTree): CharActionHandler {
return (context) => withAccount(context, accounts, (account) =>
({ kind: 'data', blk: showcasesAnswer(profiles.profileOf(account.userId), techTree) }));
}
export function usersTerseInfoAction(profiles: PlayerProfiles, accounts: AccountStore, techTree: TechTree, clans?: ClanStore): CharActionHandler {
return (context) => withAccount(context, accounts, () => {
const list = (context.payload ? stringParam(context.payload, 'usersList') : undefined) ?? context.headerParam('usersList');
if (list === undefined) return { kind: 'error', code: 'BAD_PARAMS' };
const blocks = list.split(';').filter((uid) => uid !== '').map((uid): BlkBlock => {
const account = accounts.byUserId(uid);
if (account) return accountTerseInfoBlk(uid, account, profiles, techTree, clans);
const npc = clans?.npcMemberByUid(uid);
if (npc) return npcTerseInfoBlk(uid, npc.clan, npc.member);
return { name: uid, params: [{ name: 'failed', value: { type: 'bool', value: true } }], blocks: [] };
});
return { kind: 'data', blk: { name: '', params: [], blocks } };
});
}
function accountTerseInfoBlk(
uid: string,
account: Account,
profiles: PlayerProfiles,
techTree: TechTree,
clans?: ClanStore,
): BlkBlock {
const profile = profiles.profileOf(account.userId);
clans?.syncProfile(profile, account);
const clanInfo = clanMembershipOf(profile);
const inClan = clanInfo.clanId !== '-1';
const looks = appearance(profile);
const { type, showcase } = currentShowcaseView(profile, techTree);
const fields: ReadonlyArray<readonly [string, string]> = [
['nick', account.nick],
['pilotIcon', looks.pilotIcon ?? ''],
['title', chosenTitle(profile)],
['clanTag', inClan ? clanInfo.clanTag : ''],
['clanName', inClan ? clanInfo.clanName : ''],
['background', looks.background ?? ''],
['frame', looks.frame ?? ''],
['shcType', type],
];
return { name: uid, params: toStringParams(fields), blocks: [showcase] };
}
function npcTerseInfoBlk(uid: string, clan: ClanRecord, member: ClanMemberRecord): BlkBlock {
const fields: ReadonlyArray<readonly [string, string]> = [
['nick', member.nick],
['pilotIcon', member.npcPilotIcon ?? 'cardicon_default'],
['title', member.npcTitle ?? ''],
['clanTag', clan.tag],
['clanName', clan.name],
['background', ''],
['frame', member.npcFrame ?? ''],
['shcType', member.npcShowcaseUnit ? 'favorite_unit' : 'none'],
];
const showcase: BlkBlock = member.npcShowcaseUnit
? { name: 'showcase', params: [{ name: 'unit', value: { type: 'string', value: member.npcShowcaseUnit } }], blocks: [] }
: { name: 'showcase', params: [], blocks: [] };
return { name: uid, params: toStringParams(fields), blocks: [showcase] };
}
function toStringParams(fields: ReadonlyArray<readonly [string, string]>): BlkParam[] {
return fields.map(([name, value]) => ({ name, value: { type: 'string', value } }));
}
@@ -0,0 +1,13 @@
/**
* cln_get_price_ex: the price table (implementation notes; char/actions/price-table.ts).
* Sent at sign-in with an empty body and again by the stock scripts when a purchase fails
* (scripts/unit/unitActions.nut impl_buyUnit: PRICE.update). The table only depends on the
* game files and tuning, so it is built once.
*/
import type { CharActionHandler } from '../char-action.ts';
import { priceTable, type PriceTableSources } from './price-table.ts';
export function priceEx(sources: PriceTableSources): CharActionHandler {
const table = priceTable(sources);
return () => ({ kind: 'data', blk: table });
}
+209
View File
@@ -0,0 +1,209 @@
/**
* The price table the char server sends for cln_get_price_ex (implementation notes,
* implementation notes).
*
* The client keeps the answer whole as its price table (aces.exe 2.61.0.37 0xeb7a88, job type
* 0x21; stored in the save-data object at +0x3f5c0, which warpoints::init makes the price
* source, 0x105bb4d..0x105bb67). Every price reader goes through one lookup (0x908a20 ->
* 0x908d10): it first takes a top-level block named after a client-side string (default
* "English"), else the top-level block "Common", else finds nothing; the path is looked up
* inside that block. So the whole table sits in Common:
*
* Common{
* aircrafts{
* <vehicle>{
* cost:i costGold:i the vehicle
* mods{ <modification>{ cost:i costGold:i openCostGold:i } }
* weapons{ <preset>{ cost:i costGold:i } }
* spare{ cost:i costGold:i }
* repair{ arcade{ cost:i } historical{ cost:i } simulation{ cost:i } } full repair cost per
* mode before modifications (0x10517b0, 0x90e0b0)
* specialization{ spec_expert{ cost:i } spec_ace{ costGold:i } }
* }
* }
* skins{ "<vehicle>/<skin>"{ cost:i costGold:i } } decorations (get_skin_cost_*, 0x17a8910...)
* decals{ <decal>{ ... } }
* attachable{ <attachable>{ ... } }
* skills{ <pack>{ costGold:i } } skill point packs (0x916380)
* unlocks{ <unlock>{ cost:i costGold:i } } unlocks for sale (0x9170c0)
* items{ <item>{ cost:i costGold:i } } classic items for sale, price per piece
* (wp_get_item_cost, 0x10531e0; implementation notes)
* trophy{ <id>{ cost:i costGold:i } } classic trophy prices
* }
* trophy{ <id>{ ... } } classic trophy definitions & drop weights
*
* Every entry is read as cost:i (silver lions), costGold:i (golden eagles), discount:i (percent
* off, not sent: no discounts), each 0 when missing (so zero prices are left out); openCostGold
* is the outright price of a modification before research progress (0xec0910). Anything the
* lookup does not find costs 0 for the client, which then offers it at 0 (lab round 20). The
* prices are config/wpcost.blk value and costGold (decorations: config/skins.blk, decals.blk,
* attachable.blk; unlocks: config/unlocks.blk), the same the purchase rules charge.
*/
import type { BlkBlock, BlkParam } from '@wto/blk';
import type { CrewSkillCatalogue } from '../../crew/crew-skill-rules.ts';
import type { DecorShop } from '../../decor/decor-purchase.ts';
import type { TrophyCatalogue, TrophyDefinition, TrophyPrize } from '../../inventory/trophy-catalogue.ts';
import type { ItemCatalogue } from '../../items/item-catalogue.ts';
import type { EquipmentCatalogue } from '../../modifications/equipment-catalogue.ts';
import { REPAIR_MODES } from '../../game-data/datasets/vehicle-repair.ts';
import type { RepairRules } from '../../repair/repair-rules.ts';
import type { TechTree } from '../../research/tech-tree.ts';
import type { UnlockShop } from '../../unlocks/unlock-purchase.ts';
/** The top-level block every client lookup falls back to (0x908e28). */
const COMMON_SECTION = 'Common';
export interface PriceTableSources {
readonly techTree: TechTree;
readonly equipment: EquipmentCatalogue;
readonly decor: DecorShop;
readonly crew: CrewSkillCatalogue;
readonly unlocks: UnlockShop;
readonly items: ItemCatalogue;
readonly trophies: TrophyCatalogue;
readonly repair: RepairRules;
}
export function priceTable(sources: PriceTableSources): BlkBlock {
return {
name: '',
params: [],
blocks: [
{
name: COMMON_SECTION,
params: [],
blocks: [
vehicleSection(sources.techTree, sources.equipment, sources.crew, sources.repair),
...decorSections(sources.decor),
skillPackSection(sources.crew),
unlockSection(sources.unlocks),
itemSection(sources.items),
trophyPriceSection(sources.trophies),
],
},
trophyDefinitionsSection(sources.trophies),
],
};
}
function vehicleSection(techTree: TechTree, equipment: EquipmentCatalogue, crew: CrewSkillCatalogue, repair: RepairRules): BlkBlock {
const vehicles: BlkBlock[] = [];
for (const vehicle of techTree.all()) {
const entry: BlkBlock = { name: vehicle.name, params: priceParams(vehicle.silverLions, vehicle.goldenEagles), blocks: [] };
const fitted = equipment.vehicle(vehicle.name);
if (fitted) {
const mods = fitted.modifications.filter((mod) => mod.silverLions > 0 || mod.goldenEagles > 0 || mod.openGoldenEagles > 0).map((mod) => ({
name: mod.name,
params: [...priceParams(mod.silverLions, mod.goldenEagles), ...(mod.openGoldenEagles > 0 ? [intParam('openCostGold', mod.openGoldenEagles)] : [])],
blocks: [],
}));
const weapons = fitted.weapons.filter((weapon) => weapon.silverLions > 0 || weapon.goldenEagles > 0)
.map((weapon) => ({ name: weapon.name, params: priceParams(weapon.silverLions, weapon.goldenEagles), blocks: [] }));
if (mods.length) entry.blocks.push({ name: 'mods', params: [], blocks: mods });
if (weapons.length) entry.blocks.push({ name: 'weapons', params: [], blocks: weapons });
if (fitted.spare) entry.blocks.push({ name: 'spare', params: priceParams(fitted.spare.silverLions, fitted.spare.goldenEagles), blocks: [] });
}
const repairCost = repair.vehicle(vehicle.name)?.cost;
if (repairCost) {
const modes = REPAIR_MODES.filter((mode) => repairCost[mode] > 0)
.map((mode) => ({ name: mode.toLowerCase(), params: priceParams(repairCost[mode], 0), blocks: [] }));
if (modes.length) entry.blocks.push({ name: 'repair', params: [], blocks: modes });
}
const training = crew.training(vehicle.name);
if (training && (training.expert > 0 || training.aceGoldenEagles > 0)) {
const specBlocks: BlkBlock[] = [];
if (training.expert > 0) specBlocks.push({ name: 'spec_expert', params: priceParams(training.expert, 0), blocks: [] });
if (training.aceGoldenEagles > 0) specBlocks.push({ name: 'spec_ace', params: priceParams(0, training.aceGoldenEagles), blocks: [] });
entry.blocks.push({ name: 'specialization', params: [], blocks: specBlocks });
}
if (entry.blocks.length || vehicle.silverLions > 0 || vehicle.goldenEagles > 0) vehicles.push(entry);
}
return { name: 'aircrafts', params: [], blocks: vehicles };
}
/** Zero prices are left out: the client reads a missing value as 0, and the table stays small. */
function priceParams(silverLions: number, goldenEagles: number): BlkParam[] {
return [
...(silverLions ? [intParam('cost', silverLions)] : []),
...(goldenEagles ? [intParam('costGold', goldenEagles)] : []),
];
}
function intParam(name: string, value: number): BlkParam {
return { name, value: { type: 'int', value } };
}
/** The price-table section each decoration kind is looked up in. */
const DECOR_SECTIONS = { skin: 'skins', decal: 'decals', attachable: 'attachable' } as const;
function decorSections(decor: DecorShop): BlkBlock[] {
const sections = new Map<string, BlkBlock>();
for (const price of decor.all()) {
const name = DECOR_SECTIONS[price.kind];
let section = sections.get(name);
if (!section) sections.set(name, section = { name, params: [], blocks: [] });
section.blocks.push({ name: price.key, params: priceParams(price.silverLions, price.goldenEagles), blocks: [] });
}
return [...sections.values()];
}
function skillPackSection(crew: CrewSkillCatalogue): BlkBlock {
return { name: 'skills', params: [], blocks: [...crew.packs()].map((pack) => ({ name: pack.name, params: priceParams(0, pack.goldenEagles), blocks: [] })) };
}
function unlockSection(unlocks: UnlockShop): BlkBlock {
return { name: 'unlocks', params: [], blocks: [...unlocks.all()].map((price) => ({ name: price.id, params: priceParams(price.silverLions, price.goldenEagles), blocks: [] })) };
}
function itemSection(items: ItemCatalogue): BlkBlock {
return { name: 'items', params: [], blocks: items.forSale().map((item) => ({ name: item.name, params: priceParams(item.silverLions, item.goldenEagles), blocks: [] })) };
}
function trophyPriceSection(trophies: TrophyCatalogue): BlkBlock {
return {
name: 'trophy',
params: [],
blocks: trophies.all().map((trophy) => ({ name: trophy.id, params: priceParams(trophy.silverLions, trophy.goldenEagles), blocks: [] })),
};
}
function trophyDefinitionsSection(trophies: TrophyCatalogue): BlkBlock {
return {
name: 'trophy',
params: [],
blocks: trophies.all().map(toTrophyDefinitionBlk),
};
}
function toTrophyDefinitionBlk(trophy: TrophyDefinition): BlkBlock {
const params: BlkParam[] = [
{ name: 'iconStyle', value: { type: 'string', value: trophy.iconStyle } },
{ name: 'showChances', value: { type: 'bool', value: trophy.showChances } },
{ name: 'repeatable', value: { type: 'bool', value: trophy.repeatable } },
{ name: 'instantOpening', value: { type: 'bool', value: trophy.instantOpening } },
];
if (trophy.numTotal > 0) params.push(intParam('numTotal', trophy.numTotal));
if (trophy.countryFlag) params.push({ name: 'showCountryFlag', value: { type: 'string', value: trophy.countryFlag } });
if (trophy.prizes.length === 1 && trophy.prizes[0]!.kind === 'unit') {
params.push({ name: 'showTypeInName', value: { type: 'bool', value: true } });
}
return {
name: trophy.id,
params,
blocks: [{ name: 'prizes', params: [], blocks: trophy.prizes.map(prizeToBlk) }],
};
}
function prizeToBlk(prize: TrophyPrize): BlkBlock {
// calculate_drop_chances (aces.exe 0x95a510 -> 0x95c27c..0x95c28f) checks paramType == TYPE_REAL (3)
// on `weight` (defaulting to 1.0f when non-real) and writes normalized `percent:i` (0..10000).
const params: BlkParam[] = [{ name: 'weight', value: { type: 'real', value: prize.weight } }];
if (prize.kind === 'warpoints') params.push(intParam('warpoints', prize.amount));
else if (prize.kind === 'gold') params.push(intParam('gold', prize.amount));
else if (prize.kind === 'item') {
params.push({ name: 'item', value: { type: 'string', value: prize.itemName } }, intParam('count', prize.count));
} else {
params.push({ name: 'unit', value: { type: 'string', value: prize.unitName } });
}
return { name: 'i', params, blocks: [] };
}
@@ -0,0 +1,38 @@
/**
* Purchase actions; the client applies each answer as a profile
* update, so each answers the whole profile.
*
* cln_buy_aircraft (char_send_blk, job type 13; gui.vromfs.bin scripts/unit/unitActions.nut
* impl_buyUnit):
* name:t the vehicle
* cost:i the silver lion price the client showed
* costGold:i the golden eagle price the client showed
* cln_buy_slot (purchase_crew_slot, aces.exe 2.61.0.37 0x1555a90 -> 0x2998f0, job type 10):
* country:t the country that gets one more crew slot
*/
import type { AccountStore } from '../../accounts/account-store.ts';
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
import { buyCrewSlot } from '../../research/crew-slot-purchase.ts';
import type { ResearchRules } from '../../research/research-rules.ts';
import { buyVehicle } from '../../research/vehicle-purchase.ts';
import type { CharActionHandler } from '../char-action.ts';
import { intParam, stringParam } from './payload-params.ts';
import { ruleAction } from './rule-answer.ts';
export function buyAircraft(profiles: PlayerProfiles, accounts: AccountStore, rules: ResearchRules): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => {
const vehicle = stringParam(payload, 'name');
const silverLions = intParam(payload, 'cost') ?? 0;
const goldenEagles = intParam(payload, 'costGold') ?? 0;
if (vehicle === undefined) return undefined;
return (profile) => buyVehicle(profile, rules, vehicle, { silverLions, goldenEagles });
});
}
export function buySlot(profiles: PlayerProfiles, accounts: AccountStore, rules: ResearchRules): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => {
const country = stringParam(payload, 'country');
if (country === undefined) return undefined;
return (profile) => buyCrewSlot(profile, rules, country);
});
}
@@ -0,0 +1,87 @@
/**
* Research actions. All are sent with char_send_blk (job type 13),
* so the client applies each answer as a profile update and each answers the whole profile.
*
* cln_set_researchable (shop_set_researchable_unit, aces.exe 2.61.0.37 0x17a3e80):
* unit:t the vehicle to research
* type:i its vehicle type number
* or, for a modification (shop_set_researchable_unit_module, 0x17a3e00; implementation notes):
* unit:t the owned vehicle
* mod:t the modification to research
* cln_reset_researchable (shop_reset_researchable_unit, 0x17a3f00): the player closed the
* "research finished" prompt without choosing.
* country:t, type:i
* cln_convert_exp (shop_convert_free_exp_for_unit, 0x17a4ec0): free research points into a
* vehicle, paid with golden eagles.
* unit:t, amount:i research points
* cln_move_exp_to_unit (scripts/unit/unitActions.nut flushExcessExpToUnit): put the branch's
* banked excess research points (researchUnits/<country>/exp<Type>) into a vehicle.
* unit:t
* cln_move_exp_to_module (flushExcessExpToModule): put a vehicle's banked excess research
* points (hangar/<vehicle>/excessExp) into one of its modifications.
* unit:t, mod:t
*/
import type { AccountStore } from '../../accounts/account-store.ts';
import type { EquipmentCatalogue } from '../../modifications/equipment-catalogue.ts';
import { chooseModuleResearch, moveExcessExpToModule } from '../../modifications/module-research-target.ts';
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
import { chooseResearchTarget, convertFreeResearchPoints, dismissFinishedResearch, moveExcessExpToUnit } from '../../research/research-progress.ts';
import type { ResearchRules } from '../../research/research-rules.ts';
import type { CharActionHandler } from '../char-action.ts';
import { intParam, stringParam } from './payload-params.ts';
import { ruleAction } from './rule-answer.ts';
export function setResearchable(
profiles: PlayerProfiles,
accounts: AccountStore,
rules: ResearchRules,
equipment: EquipmentCatalogue,
): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => {
const vehicle = stringParam(payload, 'unit');
const modification = stringParam(payload, 'mod');
if (vehicle !== undefined && modification !== undefined) return (profile) => chooseModuleResearch(profile, equipment, vehicle, modification);
const type = intParam(payload, 'type');
if (vehicle === undefined || type === undefined) return undefined;
return (profile) => chooseResearchTarget(profile, rules, vehicle, type);
});
}
export function resetResearchable(profiles: PlayerProfiles, accounts: AccountStore, rules: ResearchRules): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => {
const country = stringParam(payload, 'country');
const type = intParam(payload, 'type');
if (country === undefined || type === undefined) return undefined;
return (profile) => dismissFinishedResearch(profile, rules, country, type);
});
}
export function convertExp(profiles: PlayerProfiles, accounts: AccountStore, rules: ResearchRules): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => {
const vehicle = stringParam(payload, 'unit');
const amount = intParam(payload, 'amount');
if (vehicle === undefined || amount === undefined) return undefined;
return (profile) => convertFreeResearchPoints(profile, rules, vehicle, amount);
});
}
export function moveExpToUnitAction(profiles: PlayerProfiles, accounts: AccountStore, rules: ResearchRules): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => {
const vehicle = stringParam(payload, 'unit');
if (vehicle === undefined) return undefined;
return (profile) => moveExcessExpToUnit(profile, rules, vehicle);
});
}
export function moveExpToModuleAction(
profiles: PlayerProfiles,
accounts: AccountStore,
equipment: EquipmentCatalogue,
): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => {
const vehicle = stringParam(payload, 'unit');
const modification = stringParam(payload, 'mod');
if (vehicle === undefined || modification === undefined) return undefined;
return (profile) => moveExcessExpToModule(profile, equipment, vehicle, modification);
});
}
@@ -0,0 +1,28 @@
/**
* Actions that run one rule on the player's profile and answer the whole updated profile
* (job types the client applies as profile updates, implementation notes). A refused
* rule changes nothing and answers "!ERROR:<refusal>".
*/
import type { BlkBlock } from '@wto/blk';
import type { AccountStore } from '../../accounts/account-store.ts';
import { clientProfile } from '../../profile/client-profile.ts';
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
import type { RuleOutcome } from '../../research/rule-outcome.ts';
import type { CharActionHandler } from '../char-action.ts';
import { withAccount } from './account-context.ts';
/** Read the request into a rule (undefined: malformed request), run it, answer the outcome. */
export function ruleAction(profiles: PlayerProfiles, accounts: AccountStore,
readRequest: (payload: BlkBlock) => ((profile: BlkBlock) => RuleOutcome) | undefined): CharActionHandler {
return (context) => withAccount(context, accounts, (account) => {
const rule = context.payload && readRequest(context.payload);
if (!rule) return { kind: 'error', code: 'BAD_PARAMS' };
let outcome: RuleOutcome = { ok: false, refusal: 'BAD_PARAMS' };
const profile = profiles.updateWhen(account.userId, (saved) => {
outcome = rule(saved);
return outcome.ok;
});
if (profile) return { kind: 'data', blk: clientProfile(profile, account) };
return { kind: 'error', code: outcome.ok ? 'BAD_PARAMS' : outcome.refusal };
});
}
@@ -0,0 +1,55 @@
/**
* Char action handlers for squadron (clan) vehicle research and Golden-Eagle buyout
* (`cln_set_research_clan_unit`, `cln_flush_clan_exp_to_unit`, `cln_buy_not_researched_clans_unit`;
* implementation notes).
*/
import type { AccountStore } from '../../accounts/account-store.ts';
import type { ClanStore } from '../../clans/clan-store.ts';
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
import type { ResearchRules } from '../../research/research-rules.ts';
import {
buyNotResearchedSquadronUnit,
chooseSquadronResearchTarget,
flushSquadronExpToUnit,
} from '../../research/squadron-research.ts';
import type { CharActionHandler } from '../char-action.ts';
import { clanProfileRuleAction, priceFromClanPayload } from './clan-actions.ts';
import { boolParam, stringParam } from './payload-params.ts';
export function setResearchClanUnitAction(
profiles: PlayerProfiles,
accounts: AccountStore,
clans: ClanStore,
rules: ResearchRules,
): CharActionHandler {
return clanProfileRuleAction(profiles, accounts, clans, (context, profile, account) => {
const unit = context.payload && stringParam(context.payload, 'unit');
if (!unit) return { ok: false, refusal: 'BAD_PARAMS' };
const auto = (context.payload && boolParam(context.payload, 'auto')) ?? false;
return chooseSquadronResearchTarget(profile, rules, unit, auto, clans.earnedSquadronExpOf(account.userId));
});
}
export function flushClanExpToUnitAction(
profiles: PlayerProfiles,
accounts: AccountStore,
clans: ClanStore,
rules: ResearchRules,
): CharActionHandler {
return clanProfileRuleAction(profiles, accounts, clans, (_context, profile, account) =>
flushSquadronExpToUnit(profile, rules, clans.earnedSquadronExpOf(account.userId)));
}
export function buyNotResearchedClanUnitAction(
profiles: PlayerProfiles,
accounts: AccountStore,
clans: ClanStore,
rules: ResearchRules,
): CharActionHandler {
return clanProfileRuleAction(profiles, accounts, clans, (context, profile) => {
const unit = context.payload && stringParam(context.payload, 'unit');
const offered = context.payload && priceFromClanPayload(context.payload);
if (!unit || !offered) return { ok: false, refusal: 'BAD_PARAMS' };
return buyNotResearchedSquadronUnit(profile, rules, unit, offered);
});
}
@@ -0,0 +1,54 @@
/**
* The new player's first choice (implementation notes, step 6).
*
* The stock "first choice" window (gui.vromfs.bin scripts/firstChoice/unitTypeChoiceHandler.nut,
* clnSetStartingInfo) sends cln_set_starting_info with:
* country:t the country picked
* unitType:i the vehicle type picked
* unlock:t repeated: every country, and "chosen_unit_type_<type>" for the type picked
* batchTrainCrew{ trainCrew{ crewId:i unitName:t } ... } the vehicle for every crew slot
* (crew-slots-payload.ts; "" leaves the slot empty)
* The login script waits until the vehicle type counts as chosen, which the client reads as
* the unlock "chosen_unit_type_<type>" being earned (scripts/unit/unitTypesList.nut
* isFirstChosen). The client applies the answer as a profile update
* (GameSaveData::onAsyncEconTransComplete -> onUpdateProfile, job type 13), so the answer is
* the whole updated profile.
*
* The country picked is also recorded as chosen ("chosen_country_<country>", defined in
* config/unlocks.blk). The stock scripts start the base tutorial by force for a player who
* has a chosen vehicle type but no chosen country (scripts/tutorials.nut checkTutorialOnStart:
* needAutoStartTutorial = !hasRunTutorialDialog(), which is false while
* scripts/user/newbieTutorialDisplay.nut reqFirstCountryChoice() holds). With the country
* chosen, they offer the tutorial. The build enables AllowedToSkipBaseTutorials so the
* player can skip it.
*/
import { findParam } from '@wto/blk';
import type { AccountStore } from '../../accounts/account-store.ts';
import { clientProfile } from '../../profile/client-profile.ts';
import { assignCrewSlots, canAssignCrewSlots } from '../../profile/crew-slots.ts';
import { addUnlock } from '../../profile/profile-unlocks.ts';
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
import type { CharActionHandler } from '../char-action.ts';
import { withAccount } from './account-context.ts';
import { readCrewSlots } from './crew-slots-payload.ts';
export function setStartingInfo(profiles: PlayerProfiles, accounts: AccountStore): CharActionHandler {
return (context) => withAccount(context, accounts, (account) => {
const payload = context.payload;
if (!payload) return { kind: 'error', code: 'BAD_PARAMS' };
const unlocks = payload.params.flatMap((param) => (param.name === 'unlock' && param.value.type === 'string' ? [param.value.value] : []));
const country = findParam(payload, 'country')?.value;
const assignments = readCrewSlots(payload);
if (unlocks.length === 0 || assignments === undefined || country?.type !== 'string' || !country.value.startsWith('country_')) {
return { kind: 'error', code: 'BAD_PARAMS' };
}
unlocks.push(`chosen_${country.value}`);
if (!canAssignCrewSlots(profiles.profileOf(account.userId), assignments)) return { kind: 'error', code: 'BAD_PARAMS' };
const profile = profiles.update(account.userId, (saved) => {
for (const unlock of unlocks) addUnlock(saved, unlock);
assignCrewSlots(saved, assignments);
});
return { kind: 'data', blk: clientProfile(profile, account) };
});
}
@@ -0,0 +1,85 @@
/**
* Store char actions:
* - cln_get_entitlements_price_ex: encodes the store catalogue into Gaijin's entitlements BLK;
* - cln_buy_entitlement: Golden-Eagle entitlement purchase (aces.exe 0x17a0f50 -> 0x2a1240
* sends `entitlement` and `costGold` in the HTTP headers, job type 5, answer applied as a
* full profile update). Note: `cln_buy_entitlement_and_get_reward_for_day` is not referenced
* anywhere in 2.61.0.37 GUI scripts and is intentionally not registered.
*/
import { appendParam, emptyBlock, setParam, type BlkBlock } from '@wto/blk';
import type { AccountStore } from '../../accounts/account-store.ts';
import { clientProfile } from '../../profile/client-profile.ts';
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
import { serverTimeNow } from '../../profile/server-time.ts';
import type { RuleOutcome } from '../../research/rule-outcome.ts';
import type { StoreCatalogue, StoreProduct } from '../../store/store-catalogue.ts';
import { buyGoldEntitlement } from '../../store/store-purchase.ts';
import type { CharActionHandler } from '../char-action.ts';
import { withAccount } from './account-context.ts';
import { headerOrPayloadInt, headerOrPayloadString } from './payload-params.ts';
export function entitlementsPriceEx(store: StoreCatalogue): CharActionHandler {
const table = buildEntitlementsPriceBlk(store.allProducts());
return () => ({ kind: 'data', blk: table });
}
export function buyEntitlementAction(profiles: PlayerProfiles, accounts: AccountStore, store: StoreCatalogue): CharActionHandler {
return (context) => withAccount(context, accounts, (account) => {
const entitlement = headerOrPayloadString(context, 'entitlement');
const offeredGold = headerOrPayloadInt(context, 'costGold');
if (!entitlement || offeredGold === undefined || offeredGold < 0) {
return { kind: 'error', code: 'BAD_PARAMS' };
}
let outcome: RuleOutcome = { ok: false, refusal: 'BAD_PARAMS' };
const now = serverTimeNow();
const updated = profiles.updateWhen(account.userId, (saved) => {
outcome = buyGoldEntitlement(saved, store, entitlement, offeredGold, now);
return outcome.ok;
});
if (updated) return { kind: 'data', blk: clientProfile(updated, account) };
return { kind: 'error', code: outcome.ok ? 'BAD_PARAMS' : outcome.refusal };
});
}
function buildEntitlementsPriceBlk(products: readonly StoreProduct[]): BlkBlock {
const root = emptyBlock();
for (const product of products) {
const block = emptyBlock(product.id);
setParam(block, 'chapter', { type: 'string', value: product.chapter });
if (product.kind === 'eagles') {
setParam(block, 'onlinePurchase', { type: 'bool', value: true });
setParam(block, 'group', { type: 'string', value: 'eagles100' });
setParam(block, 'useGroupAmount', { type: 'bool', value: true });
setParam(block, 'goldIncome', { type: 'int', value: product.goldIncome! });
} else if (product.kind === 'warpoints') {
setParam(block, 'group', { type: 'string', value: '1KWP' });
setParam(block, 'useGroupAmount', { type: 'bool', value: true });
setParam(block, 'wpIncome', { type: 'int', value: product.silverIncome! });
setParam(block, 'goldCost', { type: 'int', value: product.goldCost! });
} else if (product.kind === 'premium-gold') {
setParam(block, 'alias', { type: 'string', value: 'PremiumAccount' });
setParam(block, 'group', { type: 'string', value: 'PremiumAccount' });
setParam(block, 'ttl', { type: 'int', value: product.premiumDays! });
setParam(block, 'goldCost', { type: 'int', value: product.goldCost! });
} else if (product.kind === 'premium-gjn') {
setParam(block, 'onlinePurchase', { type: 'bool', value: true });
setParam(block, 'alias', { type: 'string', value: 'PremiumAccount' });
setParam(block, 'group', { type: 'string', value: 'PremiumAccount' });
setParam(block, 'ttl', { type: 'int', value: product.premiumDays! });
} else if (product.kind === 'vehicle-pack' && product.vehicles) {
setParam(block, 'onlinePurchase', { type: 'bool', value: true });
setParam(block, 'wtoTitleEn', { type: 'string', value: product.title.en });
setParam(block, 'wtoTitleZh', { type: 'string', value: product.title.zh });
for (const vehicle of product.vehicles) {
appendParam(block, 'aircraftGift', { type: 'string', value: vehicle.name });
}
if (product.goldIncome) setParam(block, 'goldIncome', { type: 'int', value: product.goldIncome });
if (product.silverIncome) setParam(block, 'wpIncome', { type: 'int', value: product.silverIncome });
}
root.blocks.push(block);
}
return root;
}
@@ -0,0 +1,25 @@
/**
* Buying unlocks. cln_buy_unlock is sent with charSendBlk (job type
* 13), so the answer is the whole profile.
*
* cln_buy_unlock (scripts unlocks/unlocksAction.nut buyUnlockImpl; ship flags from
* customization/decoratorAcquire.nut, icons from chooseImage.nut, awards, smokes...):
* name:t the unlock
* unitName:t the vehicle in the hangar (flags); not needed to buy
* wpCost:i goldCost:i
*/
import type { AccountStore } from '../../accounts/account-store.ts';
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
import { buyUnlock, type UnlockShop } from '../../unlocks/unlock-purchase.ts';
import type { CharActionHandler } from '../char-action.ts';
import { intParam, stringParam } from './payload-params.ts';
import { ruleAction } from './rule-answer.ts';
export function buyUnlockAction(profiles: PlayerProfiles, accounts: AccountStore, unlocks: UnlockShop): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => {
const name = stringParam(payload, 'name');
if (name === undefined) return undefined;
const offered = { silverLions: intParam(payload, 'wpCost') ?? 0, goldenEagles: intParam(payload, 'goldCost') ?? 0 };
return (profile) => buyUnlock(profile, unlocks, name, offered);
});
}
+23
View File
@@ -0,0 +1,23 @@
/** What a char action handler gets and returns. Handlers belong to the rules layer's domains. */
import type { BlkBlock } from '@wto/blk';
import type { CharAnswer } from './char-answers.ts';
export interface CharActionContext {
/** From the request's uidhint header; undefined when the client sent none. */
readonly userId: string | undefined;
/** The request's BLK parameters, when the body carried a BLK. */
readonly payload: BlkBlock | undefined;
/** Raw UTF-8 request body text, for EATT_JSON_REQUEST custom actions. */
readonly rawText: string;
/** Raw request body bytes, for compressed or PBBD-framed cloud-settings uploads. */
readonly rawBody?: Uint8Array;
/**
* A request parameter sent as an HTTP header: char_request_blk_from_server (scripts
* charRequestBlk) sends the top-level parameters of its BLK that way and no body (lab round
* 22: cln_get_users_terse_info with a "usersList" header). Header names arrive lower-cased,
* so the lookup ignores case.
*/
readonly headerParam: (name: string) => string | undefined;
}
export type CharActionHandler = (context: CharActionContext) => CharAnswer;
+41
View File
@@ -0,0 +1,41 @@
/**
* The char service's answer shapes (implementation notes; aces.exe 2.61.0.37,
* CharServerClient::handleReqResult at 0x336d590):
* - data: HTTP 200, a compression marker ('i') and a binary BLK (`loadBlkFromAnswer`, 0x336fd60);
* - raw-blk: HTTP 200, a bare binary BLK with no compression marker, for `online_storage`
* endpoints (`GetMetaHandler` 0x46659c0 and `LoadingHandler` 0x4667930 -> `0x3280a50`);
* - json: HTTP 200, UTF-8 JSON for custom JSON actions;
* - done: HTTP 200 with a body starting "!OK", for requests that expect no data;
* - error: a body starting "!ERROR:" followed by an error code.
*/
import { encodeBlk, formatBlkText, type BlkBlock } from '@wto/blk';
import type { ServiceResponse } from '../transport/exchange.ts';
import { encodeDataAnswer } from './char-payload.ts';
export type CharAnswer =
| { readonly kind: 'data'; readonly blk: BlkBlock }
| { readonly kind: 'raw-blk'; readonly blk: BlkBlock }
| { readonly kind: 'json'; readonly data: unknown }
| { readonly kind: 'done' }
| { readonly kind: 'error'; readonly code: string };
export function toResponse(answer: CharAnswer): ServiceResponse {
switch (answer.kind) {
case 'data':
return { status: 200, headers: BINARY, body: encodeDataAnswer(answer.blk), logNotes: { responseText: formatBlkText(answer.blk) } };
case 'raw-blk':
return { status: 200, headers: BINARY, body: encodeBlk(answer.blk), logNotes: { responseText: formatBlkText(answer.blk) } };
case 'json': {
const body = JSON.stringify(answer.data);
return { status: 200, headers: JSON_HEADERS, body, logNotes: { responseText: body } };
}
case 'done':
return { status: 200, headers: TEXT, body: '!OK' };
case 'error':
return { status: 200, headers: TEXT, body: `!ERROR:${answer.code}` };
}
}
const BINARY = { 'content-type': 'application/octet-stream' };
const JSON_HEADERS = { 'content-type': 'application/json; charset=utf-8' };
const TEXT = { 'content-type': 'text/plain' };
+50
View File
@@ -0,0 +1,50 @@
/**
* Bodies exchanged with the char service.
*
* Answers carrying data are a compression marker followed by a binary BLK; the client loads
* them with loadBlkFromAnswer (aces.exe 0x336fd60). We always send them uncompressed.
*
* What the client sends in request bodies is not established yet, so
* decoding is attempted in the forms that are plausible (marked or bare binary BLK, form
* text) and the traffic log records which form it was.
*/
import { decodeBlk, encodeBlk, formatBlkText, type BlkBlock } from '@wto/blk';
import { markUncompressed, unpackMarked } from './compression-marker.ts';
import { describePbbdForLog, isPbbdStream } from './pbbd-stream.ts';
export function encodeDataAnswer(blk: BlkBlock): Uint8Array {
return markUncompressed(encodeBlk(blk));
}
export interface DecodedPayload {
/** How the body was laid out, for the traffic log. */
readonly form: string;
readonly blk?: BlkBlock;
/** Readable rendering for the traffic log. */
readonly text: string;
}
const BINARY_BLK_LABELS = new Set([1, 2, 3, 6]);
export function decodeRequestPayload(body: Uint8Array): DecodedPayload {
if (body.length === 0) return { form: 'empty', text: '' };
try {
if (isPbbdStream(body)) {
return { form: 'PBBD stream', text: describePbbdForLog(body) };
}
const marked = unpackMarked(body);
if (marked) {
if (!marked.data) return { form: `marked ${marked.method}, not unpacked`, text: '' };
return describeBlk(`marked ${marked.method}`, marked.data);
}
if (BINARY_BLK_LABELS.has(body[0]!)) return describeBlk('bare binary BLK', body);
} catch (error) {
return { form: `undecodable (${(error as Error).message})`, text: '' };
}
return { form: 'text', text: Buffer.from(body).toString('utf8') };
}
function describeBlk(form: string, bytes: Uint8Array): DecodedPayload {
const blk = decodeBlk(bytes);
return { form, blk, text: formatBlkText(blk) };
}
+65
View File
@@ -0,0 +1,65 @@
/**
* char service: profiles and player actions.
*
* The client names the action in the request header "action" (request headers assembled at
* aces.exe 0x336c590). Requests carry no "userid" header; the player is identified by
* "uidhint", the user id from the sign-in answer (implementation notes; added by
* EconomicSerializeJob::doJob, 0x2968a5). The local server trusts uidhint as it is: there
* is nothing to protect on a single-player machine.
*
* An action with no handler yet gets a data answer holding an empty BLK and is marked
* unhandled in the traffic log. handleReqResult treats any 200 answer that is not "!ERROR:"
* or "!RETRY" as success for both data requests and requests that expect "!OK", so this
* default lets the client continue and reveal what it asks for next.
*/
import { emptyBlock } from '@wto/blk';
import type { Service, ServiceRequest, ServiceResponse } from '../transport/exchange.ts';
import type { CharActionHandler } from './char-action.ts';
import { toResponse, type CharAnswer } from './char-answers.ts';
import { decodeRequestPayload } from './char-payload.ts';
const CHAR_HOST = /^char-[a-z0-9-]+\.warthunder\.com$/;
export class CharService implements Service {
readonly name = 'char';
readonly #actions: ReadonlyMap<string, CharActionHandler>;
constructor(actions: ReadonlyMap<string, CharActionHandler>) {
this.#actions = actions;
}
accepts(request: ServiceRequest): boolean {
return request.originalHost !== undefined && CHAR_HOST.test(request.originalHost);
}
handle(request: ServiceRequest): ServiceResponse {
const action = header(request, 'action') ?? '(no action header)';
const payload = decodeRequestPayload(request.body);
const handler = this.#actions.get(action);
const answer: CharAnswer = handler
? handler({
userId: header(request, 'uidhint'),
payload: payload.blk,
rawText: payload.text,
rawBody: request.body,
headerParam: (name) => header(request, name.toLowerCase()),
})
: { kind: 'data', blk: emptyBlock() };
const response = toResponse(answer);
return {
...response,
logNotes: {
...response.logNotes,
summary: `${action} [request body: ${payload.form}] -> ${answer.kind}${answer.kind === 'error' ? ` ${answer.code}` : ''}`,
unhandled: !handler,
requestText: payload.text,
},
};
}
}
function header(request: ServiceRequest, name: string): string | undefined {
const value = request.headers[name];
const text = Array.isArray(value) ? value[0] : value;
return text ? text : undefined;
}
@@ -0,0 +1,45 @@
/**
* Data answers of the char service start with one byte naming how the rest is compressed.
*
* Source: aces.exe 2.61.0.37. The client's table of compression methods is filled at
* 0x3373cd0 (name, implementation, marker byte); the answer is unpacked by
* processPotentiallyCompressedAnswer (0x3372190), which takes the bytes after an 'i' marker
* as they are. Only the methods Node can unpack are decoded here.
*/
import { gunzipSync, inflateSync, zstdDecompressSync } from 'node:zlib';
export const MARKER_NONE = 0x69; // 'i'
const DECODERS: ReadonlyMap<number, { readonly name: string; readonly unpack?: (data: Uint8Array) => Uint8Array }> = new Map([
[MARKER_NONE, { name: 'none', unpack: (data: Uint8Array) => data }],
[0x5a, { name: 'zstd', unpack: (data: Uint8Array) => zstdDecompressSync(data) }], // 'Z'
[0x7a, { name: 'zlib', unpack: (data: Uint8Array) => inflateSync(data) }], // 'z'
[0x1f, { name: 'gzip', unpack: (data: Uint8Array) => gunzipSync(data) }],
[0x4c, { name: 'lz4hc' }], // 'L'
[0x6c, { name: 'lz4' }], // 'l'
[0x73, { name: 'snappy' }], // 's'
[0x62, { name: 'bzip2' }], // 'b'
[0x56, { name: 'vromfs' }], // 'V'
]);
export interface UnpackResult {
readonly method: string;
/** Undefined when the method is known but cannot be unpacked here. */
readonly data: Uint8Array | undefined;
}
/** Undefined when the first byte is not a compression marker. */
export function unpackMarked(bytes: Uint8Array): UnpackResult | undefined {
const decoder = DECODERS.get(bytes[0] ?? -1);
if (!decoder) return undefined;
// gzip's marker is the first byte of the gzip stream itself.
const rest = decoder.name === 'gzip' ? bytes : bytes.subarray(1);
return { method: decoder.name, data: decoder.unpack ? decoder.unpack(rest) : undefined };
}
export function markUncompressed(data: Uint8Array): Uint8Array {
const marked = new Uint8Array(data.length + 1);
marked[0] = MARKER_NONE;
marked.set(data, 1);
return marked;
}
+136
View File
@@ -0,0 +1,136 @@
/**
* Protocol-layer wire codecs for `online_storage` (`cln_set_general_blk` and `PBBD` batch
* streams on `cln_bulk_set_gblk`; implementation notes; aces.exe 0x4662a70..0x466b2ec,
* 0x41537d0..0x4154020).
*/
import { createHash } from 'node:crypto';
import { gunzipSync, inflateSync, zstdDecompressSync } from 'node:zlib';
import { decodeBlk, emptyBlock, encodeBlk, findBlock, setParam, type BlkBlock } from '@wto/blk';
import type { ParsedGblkUpload } from '../cloud-settings/cloud-settings-store.ts';
import { intField, stringField } from '../profile/blk-fields.ts';
import { unpackMarked } from './compression-marker.ts';
export const PBBD_MAGIC = 0x44424250; // "PBBD" little-endian (0x4663427: 0x144424250)
export function isPbbdStream(bytes: Uint8Array): boolean {
if (bytes.byteLength < 8) return false;
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
return view.getUint32(0, true) === PBBD_MAGIC && view.getUint16(4, true) === 1;
}
export function unpackCloudBlk(bytes: Uint8Array, comprHeader: string | undefined): BlkBlock | undefined {
if (bytes.byteLength === 0) return undefined;
const raw = decompressCloudBytes(bytes, comprHeader);
if (!raw || raw.byteLength === 0) return undefined;
try {
return decodeBlk(raw);
} catch {
return undefined;
}
}
export function parsePbbdBulkUploads(bytes: Uint8Array): ReadonlyArray<ParsedGblkUpload> {
if (!isPbbdStream(bytes)) return [];
const chunks = readPbbdChunks(bytes);
const uploads: ParsedGblkUpload[] = [];
for (let i = 0; i < chunks.length; i++) {
const meta = chunks[i];
if (!meta) continue;
const desc = stringField(meta, 'desc');
if (desc === 'store_gblk') {
const containerCandidate = chunks[i + 1];
i += 1;
const blkType = stringField(meta, 'blkType');
if (!blkType || !containerCandidate) continue;
const fallbackVersion = intField(meta, 'version', 1) || 1;
const extracted = normalizeContainerBlk(containerCandidate, fallbackVersion);
const contentHash = stringField(meta, 'contentHash') || computeContentHash(extracted.content);
uploads.push({ blkType, version: extracted.version, contentHash, container: extracted.container });
} else if (desc === 'bigquery' || desc === 'logout') {
i += 1;
}
}
return uploads;
}
export function normalizeContainerBlk(
incoming: BlkBlock,
fallbackVersion: number,
): { readonly version: number; readonly content: BlkBlock; readonly container: BlkBlock } {
const existingContent = findBlock(incoming, 'content');
const rawVersion = intField(incoming, 'version', fallbackVersion);
const version = rawVersion > 0 ? rawVersion : Math.max(1, fallbackVersion);
const content = cloneAsContent(existingContent ?? incoming);
return { version, content, container: buildContainerBlk(version, content) };
}
export function buildContainerBlk(version: number, content: BlkBlock): BlkBlock {
const container = emptyBlock();
setParam(container, 'version', { type: 'int', value: Math.max(1, Math.trunc(version)) });
container.blocks.push(cloneAsContent(content));
return container;
}
export function computeContentHash(content: BlkBlock): string {
const rootCopy = emptyBlock();
rootCopy.params.push(...content.params);
rootCopy.blocks.push(...content.blocks);
return createHash('md5').update(encodeBlk(rootCopy)).digest('hex');
}
export function describePbbdForLog(bytes: Uint8Array): string {
const uploads = parsePbbdBulkUploads(bytes);
if (uploads.length === 0) return 'PBBD stream (0 store_gblk items)';
return uploads.map((u) => `${u.blkType} v${u.version} (${u.contentHash})`).join(', ');
}
function readPbbdChunks(bytes: Uint8Array): Array<BlkBlock | undefined> {
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
const chunkCount = view.getUint16(6, true);
const chunks: Array<BlkBlock | undefined> = [];
let offset = 8;
for (let i = 0; i < chunkCount; i++) {
if (offset + 5 > bytes.byteLength) break;
const payloadLen = view.getUint32(offset, true);
const marker = bytes[offset + 4]!;
offset += 5;
if (offset + payloadLen > bytes.byteLength) break;
const slice = bytes.subarray(offset, offset + payloadLen);
offset += payloadLen;
chunks.push(decodeMarkedChunk(marker, slice));
}
return chunks;
}
function cloneAsContent(source: BlkBlock): BlkBlock {
return { name: 'content', params: [...source.params], blocks: [...source.blocks] };
}
function decompressCloudBytes(bytes: Uint8Array, comprHeader: string | undefined): Uint8Array | undefined {
const method = comprHeader?.trim().toLowerCase();
try {
if (method === 'zstd') return zstdDecompressSync(bytes);
if (method === 'zlib') return bytes.byteLength > 4 ? inflateSync(bytes.subarray(4)) : undefined;
if (method === 'gzip') return gunzipSync(bytes);
if (!method || method === 'none') return unpackMarked(bytes)?.data ?? bytes;
return unpackMarked(bytes)?.data;
} catch {
return unpackMarked(bytes)?.data;
}
}
function decodeMarkedChunk(marker: number, payload: Uint8Array): BlkBlock | undefined {
if (payload.byteLength === 0) return emptyBlock();
try {
let raw: Uint8Array | undefined;
if (marker === 0x69) raw = payload;
else if (marker === 0x5a) raw = zstdDecompressSync(payload);
else if (marker === 0x7a) raw = payload.byteLength > 4 ? inflateSync(payload.subarray(4)) : undefined;
else if (marker === 0x1f) raw = gunzipSync(payload);
return raw ? decodeBlk(raw) : undefined;
} catch {
return undefined;
}
}
+88
View File
@@ -0,0 +1,88 @@
/**
* RFC 1459 + Gaijin IRC wire parser and line formatters used by the local chat server.
*/
export const IRC_SERVER_HOST = 'wt.local';
export interface IrcCommand {
readonly verb: string;
readonly params: readonly string[];
}
const HANDSHAKE_PREFIX = /^(?:PASS |NICK |USER |CAP |PING |QUIT(?: |\r|\n|$))/i;
export function startsIrcHandshake(firstChunk: Buffer): boolean {
if (firstChunk.length < 4) return false;
const head = firstChunk.subarray(0, Math.min(firstChunk.length, 16)).toString('latin1');
return HANDSHAKE_PREFIX.test(head);
}
export function parseIrcLine(rawLine: string): IrcCommand | undefined {
let rest = rawLine.replace(/[\r\n]+$/, '');
if (rest.length === 0) return undefined;
if (rest.startsWith(':')) {
const space = rest.indexOf(' ');
if (space < 0) return undefined;
rest = rest.slice(space + 1).trimStart();
}
if (rest.length === 0) return undefined;
const verbEnd = rest.indexOf(' ');
if (verbEnd < 0) {
return { verb: rest.toUpperCase(), params: [] };
}
const verb = rest.slice(0, verbEnd).toUpperCase();
let cursor = rest.slice(verbEnd + 1);
const params: string[] = [];
while (cursor.length > 0) {
while (cursor.startsWith(' ')) cursor = cursor.slice(1);
if (cursor.length === 0) break;
if (cursor.startsWith(':')) {
params.push(cursor.slice(1));
break;
}
const nextSpace = cursor.indexOf(' ');
if (nextSpace < 0) {
params.push(cursor);
break;
}
params.push(cursor.slice(0, nextSpace));
cursor = cursor.slice(nextSpace + 1);
}
return { verb, params };
}
export function formatServerNumeric(code: string, nick: string, params: readonly string[], trailing?: string): string {
const target = sanitizeToken(nick || '*');
const middle = params.length > 0 ? ` ${params.map(sanitizeToken).join(' ')}` : '';
const suffix = trailing !== undefined ? ` :${sanitizeTrailing(trailing)}` : '';
return `:${IRC_SERVER_HOST} ${code} ${target}${middle}${suffix}\r\n`;
}
export function formatServerCommand(verb: string, params: readonly string[], trailing?: string): string {
const middle = params.length > 0 ? ` ${params.map(sanitizeToken).join(' ')}` : '';
const suffix = trailing !== undefined ? ` :${sanitizeTrailing(trailing)}` : '';
return `:${IRC_SERVER_HOST} ${verb}${middle}${suffix}\r\n`;
}
export function formatUserEvent(nick: string, user: string, verb: string, params: readonly string[], trailing?: string): string {
const safeNick = sanitizeToken(nick || 'Player');
const safeUser = sanitizeToken(user || '0');
const middle = params.length > 0 ? ` ${params.map(sanitizeToken).join(' ')}` : '';
const suffix = trailing !== undefined ? ` :${sanitizeTrailing(trailing)}` : '';
return `:${safeNick}!${safeUser}@127.0.0.1 ${verb}${middle}${suffix}\r\n`;
}
export function sanitizeChannelName(raw: string): string {
const trimmed = sanitizeToken(raw);
if (trimmed.length === 0) return '#general';
return trimmed.startsWith('#') || trimmed.startsWith('&') ? trimmed : `#${trimmed}`;
}
function sanitizeToken(text: string): string {
return text.replace(/[\r\n\0 ]+/g, '');
}
function sanitizeTrailing(text: string): string {
return text.replace(/[\r\n\0]+/g, ' ');
}
+284
View File
@@ -0,0 +1,284 @@
/**
* In-process RFC 1459 + Gaijin IRC chat server (`IRCClient` in `aces.exe` 0x133c5e0).
*
* Serves hangar general rooms, custom player rooms, discussion threads (`XTJOIN` / `XTMETA`),
* private messages, and session presence so `gchat_is_connected()` and `gchat_is_enabled()`
* evaluate `true` natively in both hangar and battle.
*/
import type { Duplex } from 'node:stream';
import {
formatServerCommand,
formatServerNumeric,
formatUserEvent,
IRC_SERVER_HOST,
parseIrcLine,
sanitizeChannelName,
type IrcCommand,
} from './irc-protocol.ts';
interface IrcSession {
readonly socket: Duplex;
nick: string;
user: string;
realName: string;
registered: boolean;
buffer: string;
readonly channels: Set<string>;
}
interface IrcChannel {
readonly name: string;
topic: string;
readonly members: Set<IrcSession>;
}
const MAX_BUFFER_CHARS = 65_536;
export class IrcServer {
readonly #sessions = new Set<IrcSession>();
readonly #channels = new Map<string, IrcChannel>();
#nextThreadId = 1;
accept(socket: Duplex): void {
const session: IrcSession = {
socket, nick: '', user: '', realName: '', registered: false, buffer: '', channels: new Set(),
};
this.#sessions.add(session);
socket.on('data', (chunk: Buffer | string) => {
session.buffer += typeof chunk === 'string' ? chunk : chunk.toString('utf8');
if (session.buffer.length > MAX_BUFFER_CHARS) {
socket.destroy();
return;
}
let nl = session.buffer.indexOf('\n');
while (nl >= 0) {
const rawLine = session.buffer.slice(0, nl);
session.buffer = session.buffer.slice(nl + 1);
const cmd = parseIrcLine(rawLine);
if (cmd) this.#handleCommand(session, cmd);
nl = session.buffer.indexOf('\n');
}
});
socket.once('close', () => this.#removeSession(session, 'Client disconnected'));
socket.once('error', () => socket.destroy());
}
#handleCommand(session: IrcSession, cmd: IrcCommand): void {
const [p0 = '', p1 = ''] = cmd.params;
switch (cmd.verb) {
case 'CAP': if (p0.toUpperCase() === 'LS') this.#send(session, formatServerCommand('CAP', ['*', 'LS'], '')); return;
case 'PASS':
case 'PONG': return;
case 'NICK': this.#handleNick(session, p0); return;
case 'USER':
session.user = p0 || '0';
session.realName = cmd.params[3] ?? session.user;
this.#tryCompleteRegistration(session);
return;
case 'PING': this.#send(session, formatServerCommand('PONG', [IRC_SERVER_HOST], p0 || IRC_SERVER_HOST)); return;
case 'JOIN': this.#handleJoin(session, p0); return;
case 'PART': this.#handlePart(session, p0, p1); return;
case 'PRIVMSG':
case 'NOTICE': this.#handleMessage(session, cmd.verb, p0, p1); return;
case 'NAMES': this.#sendNames(session, sanitizeChannelName(p0 || '#general')); return;
case 'LIST': this.#handleList(session); return;
case 'TOPIC': this.#handleTopic(session, cmd.params); return;
case 'MODE': this.#handleMode(session, p0); return;
case 'WHO': this.#handleWho(session, p0); return;
case 'WHOIS': this.#handleWhois(session, p0); return;
case 'XTJOIN': this.#handleXtJoin(session, cmd.params); return;
case 'XTMETA': this.#handleXtMeta(session, cmd.params); return;
case 'QUIT':
this.#removeSession(session, p0 || 'Quit');
session.socket.end();
return;
default: return;
}
}
#handleNick(session: IrcSession, rawNick: string): void {
const nextNick = rawNick.trim() || `Player${this.#sessions.size}`;
const prevNick = session.nick;
session.nick = nextNick;
if (session.registered && prevNick && prevNick !== nextNick) {
this.#send(session, formatUserEvent(prevNick, session.user, 'NICK', [], nextNick));
return;
}
this.#tryCompleteRegistration(session);
}
#tryCompleteRegistration(session: IrcSession): void {
if (session.registered || !session.nick || !session.user) return;
session.registered = true;
const { nick, user } = session;
this.#send(session, formatServerNumeric('001', nick, [], `Welcome to the War Thunder Local Chat Network ${nick}!${user}@127.0.0.1`));
this.#send(session, formatServerNumeric('002', nick, [], `Your host is ${IRC_SERVER_HOST}, running version 1.0`));
this.#send(session, formatServerNumeric('003', nick, [], 'This server was created locally'));
this.#send(session, formatServerNumeric('004', nick, [IRC_SERVER_HOST, '1.0', 'iow', 'ntov']));
this.#send(session, formatServerNumeric('375', nick, [], `- ${IRC_SERVER_HOST} Message of the Day -`));
this.#send(session, formatServerNumeric('372', nick, [], '- Local offline chat service active'));
this.#send(session, formatServerNumeric('376', nick, [], 'End of /MOTD command.'));
}
#handleJoin(session: IrcSession, rawTargets: string): void {
if (!rawTargets) return;
if (rawTargets === '0') {
for (const chan of [...session.channels]) this.#partOne(session, chan, '');
return;
}
for (const raw of rawTargets.split(',')) {
if (!raw.trim()) continue;
this.#joinChannel(session, sanitizeChannelName(raw), '');
}
}
#joinChannel(session: IrcSession, channelName: string, initialTopic: string): void {
let channel = this.#channels.get(channelName);
if (!channel) {
channel = { name: channelName, topic: initialTopic, members: new Set() };
this.#channels.set(channelName, channel);
} else if (initialTopic && !channel.topic) {
channel.topic = initialTopic;
}
channel.members.add(session);
session.channels.add(channelName);
const joinLine = formatUserEvent(session.nick, session.user, 'JOIN', [], channelName);
for (const member of channel.members) this.#send(member, joinLine);
if (channel.topic) {
this.#send(session, formatServerNumeric('332', session.nick, [channelName], channel.topic));
} else {
this.#send(session, formatServerNumeric('331', session.nick, [channelName], 'No topic is set'));
}
this.#sendNames(session, channelName);
}
#handlePart(session: IrcSession, rawTargets: string, reason: string): void {
for (const raw of rawTargets.split(',')) {
if (!raw.trim()) continue;
this.#partOne(session, sanitizeChannelName(raw), reason);
}
}
#partOne(session: IrcSession, channelName: string, reason: string): void {
const channel = this.#channels.get(channelName);
if (!channel || !channel.members.has(session)) return;
const partLine = formatUserEvent(session.nick, session.user, 'PART', [channelName], reason || undefined);
for (const member of channel.members) this.#send(member, partLine);
channel.members.delete(session);
session.channels.delete(channelName);
if (channel.members.size === 0) this.#channels.delete(channelName);
}
#handleMessage(session: IrcSession, verb: 'PRIVMSG' | 'NOTICE', target: string, text: string): void {
if (!target) return;
if (target.startsWith('#') || target.startsWith('&')) {
const channel = this.#channels.get(sanitizeChannelName(target));
if (!channel) {
if (verb === 'PRIVMSG') this.#send(session, formatServerNumeric('403', session.nick, [target], 'No such channel'));
return;
}
const line = formatUserEvent(session.nick, session.user, verb, [channel.name], text);
for (const member of channel.members) {
if (member !== session) this.#send(member, line);
}
return;
}
const recipient = [...this.#sessions].find((peer) => peer.registered && peer.nick === target);
if (!recipient) {
if (verb === 'PRIVMSG') this.#send(session, formatServerNumeric('401', session.nick, [target], 'No such nick/channel'));
return;
}
this.#send(recipient, formatUserEvent(session.nick, session.user, verb, [recipient.nick], text));
}
#sendNames(session: IrcSession, channelName: string): void {
const channel = this.#channels.get(channelName);
const nicks = channel ? [...channel.members].map((m) => m.nick).filter(Boolean).join(' ') : session.nick;
this.#send(session, formatServerNumeric('353', session.nick, ['=', channelName], nicks));
this.#send(session, formatServerNumeric('366', session.nick, [channelName], 'End of /NAMES list.'));
}
#handleList(session: IrcSession): void {
this.#send(session, formatServerNumeric('321', session.nick, ['Channel'], 'Users Name'));
for (const channel of this.#channels.values()) {
if (channel.name === '#___empty___') continue;
this.#send(session, formatServerNumeric('322', session.nick, [channel.name, String(channel.members.size)], channel.topic));
}
this.#send(session, formatServerNumeric('323', session.nick, [], 'End of /LIST'));
}
#handleTopic(session: IrcSession, params: readonly string[]): void {
const channelName = sanitizeChannelName(params[0] ?? '');
const channel = this.#channels.get(channelName);
if (!channel) {
this.#send(session, formatServerNumeric('403', session.nick, [channelName], 'No such channel'));
return;
}
if (params.length >= 2) {
channel.topic = params[1] ?? '';
const line = formatUserEvent(session.nick, session.user, 'TOPIC', [channelName], channel.topic);
for (const member of channel.members) this.#send(member, line);
return;
}
if (channel.topic) this.#send(session, formatServerNumeric('332', session.nick, [channelName], channel.topic));
else this.#send(session, formatServerNumeric('331', session.nick, [channelName], 'No topic is set'));
}
#handleMode(session: IrcSession, target: string): void {
if (target.startsWith('#') || target.startsWith('&')) {
this.#send(session, formatServerNumeric('324', session.nick, [sanitizeChannelName(target), '+nt']));
} else this.#send(session, formatServerNumeric('221', session.nick, ['+i']));
}
#handleWho(session: IrcSession, target: string): void {
const channel = target.startsWith('#') ? this.#channels.get(sanitizeChannelName(target)) : undefined;
for (const m of channel?.members ?? []) {
this.#send(session, formatServerNumeric('352', session.nick, [channel!.name, m.user, '127.0.0.1', IRC_SERVER_HOST, m.nick, 'H'], `0 ${m.realName}`));
}
this.#send(session, formatServerNumeric('315', session.nick, [target || '*'], 'End of /WHO list.'));
}
#handleWhois(session: IrcSession, targetNick: string): void {
const found = [...this.#sessions].find((peer) => peer.nick === targetNick);
if (found) this.#send(session, formatServerNumeric('311', session.nick, [found.nick, found.user, '127.0.0.1', '*'], found.realName));
this.#send(session, formatServerNumeric('318', session.nick, [targetNick || '*'], 'End of /WHOIS list.'));
}
#handleXtJoin(session: IrcSession, params: readonly string[]): void {
this.#joinChannel(session, `#___xthread_${this.#nextThreadId++}`, params[1] ?? params[0] ?? 'Discussion');
}
#handleXtMeta(session: IrcSession, params: readonly string[]): void {
const channelName = sanitizeChannelName(params[0] ?? '');
const channel = this.#channels.get(channelName);
if (!channel || params[1]?.toLowerCase() !== 'topic') return;
channel.topic = params[2] ?? '';
const line = formatUserEvent(session.nick, session.user, 'TOPIC', [channelName], channel.topic);
for (const member of channel.members) this.#send(member, line);
}
#removeSession(session: IrcSession, reason: string): void {
if (!this.#sessions.delete(session)) return;
const quitLine = session.registered ? formatUserEvent(session.nick, session.user, 'QUIT', [], reason) : '';
const notified = new Set<IrcSession>();
for (const channelName of session.channels) {
const channel = this.#channels.get(channelName);
if (!channel) continue;
channel.members.delete(session);
for (const peer of quitLine ? channel.members : []) {
if (!notified.has(peer)) {
notified.add(peer);
this.#send(peer, quitLine);
}
}
if (channel.members.size === 0) this.#channels.delete(channelName);
}
session.channels.clear();
}
#send(session: IrcSession, line: string): void {
if (!session.socket.destroyed && session.socket.writable) session.socket.write(line);
}
}
+253
View File
@@ -0,0 +1,253 @@
/**
* DataBlock serializers for squadron (clan) char actions:
* - `cln_clan_get` full clan info (`clanInfoTable.nut` + `0xeb9f60`)
* - `cln_clan_get_leaderboard` /
* `cln_clan_find_by_prefix` leaderboard / search rows (`clansModalHandler.nut`)
* - `cln_clans_list_get_short_info` short info blocks (`clanInfo.nut`)
* - `cln_clan_get_log` paginated clan event log (`clanRequests.nut`)
*/
import type { BlkBlock, BlkParam } from '@wto/blk';
import type { ClanTuning } from './clan-tuning.ts';
import {
totalPeriodActivityOf,
type ClanLogEntry,
type ClanMemberRecord,
type ClanRecord,
type ClanStats,
} from './clan-types.ts';
const CLAN_STAT_KEYS: ReadonlyArray<keyof ClanStats> = [
'dr_era5_arc', 'dr_era5_hist', 'dr_era5_sim',
'akills_arc', 'akills_hist', 'akills_sim',
'gkills_arc', 'gkills_hist', 'gkills_sim',
'deaths_arc', 'deaths_hist', 'deaths_sim',
'ftime_arc', 'ftime_hist', 'ftime_sim',
];
const OPTIONAL_LOG_STRING_KEYS: ReadonlyArray<keyof Omit<ClanLogEntry, 'id' | 'ev' | 'timeSec' | 'uId' | 'uN'>> = [
'uid', 'nick', 'role', 'old', 'new', 'name', 'type', 'tag', 'desc', 'slogan', 'region', 'announcement', 'status', 'comments',
];
export function toClanInfoBlk(clan: ClanRecord, tuning: ClanTuning, nowSec = Math.floor(Date.now() / 1000)): BlkBlock {
const todayDay = Math.floor(nowSec / 86400);
const { maxPerPeriod, squadronRpPerFullPeriod, rewardPeriodDays, historyDepthDays } = tuning.activity;
return {
name: '',
params: [
str('_id', clan.id),
str('name', clan.name),
str('tag', clan.tag),
str('lastPaidTag', clan.lastPaidTag),
str('slogan', clan.slogan),
str('desc', clan.desc),
str('region', clan.region),
str('announcement', clan.announcement),
int('cdate', clan.cdateSec),
str('status', clan.status),
int('mlimit', clan.mlimit),
str('changed_by_nick', clan.changedByNick),
str('changed_by_uid', clan.changedByUid),
int('changed_time', clan.changedTimeSec),
int('mspent', clan.mspent),
int('region_last_updated', clan.regionLastUpdatedSec),
str('type', clan.type),
bool('autoaccept', clan.autoaccept),
int('maxActivityPerPeriod', maxPerPeriod),
int('maxClanActivity', squadronRpPerFullPeriod),
int('rewardPeriodDays', rewardPeriodDays),
bool('expRewardEnabled', true),
int('historyDepth', historyDepthDays),
int('nextRewardDayId', todayDay + rewardPeriodDays),
],
blocks: [
buildAstatBlock(clan, tuning),
buildMembershipReqBlock(clan),
...clan.members.map(memberToBlk),
buildMemberRatingsBlock(clan),
{ name: 'activity', params: [], blocks: clan.members.map((m) => buildMemberActivityBlock(m, todayDay)) },
...clan.candidates.map((c) => ({
name: 'candidates',
params: [str('uid', c.uid), str('nick', c.nick), str('comment', c.comment), int('date', c.dateSec)],
blocks: [],
})),
...clan.blacklist.map((b) => ({
name: 'blacklist',
params: [
str('uid', b.uid), str('nick', b.nick),
str('initiator_uid', b.initiatorUid), str('initiator_nick', b.initiatorNick),
str('comments', b.comments), int('date', b.dateSec),
],
blocks: [],
})),
...clan.bestRewards.map((r) => ({
name: 'clanBestRewards',
params: [str('seasonName', r.seasonName), str('title', r.title)],
blocks: [],
})),
],
};
}
export function toClanLeaderboardRowBlk(clan: ClanRecord, pos: number, tuning: ClanTuning): BlkBlock {
const periodAct = totalPeriodActivityOf(clan, tuning);
return {
name: 'clan',
params: [
str('_id', clan.id),
str('name', clan.name),
str('tag', clan.tag),
str('slogan', clan.slogan),
str('desc', clan.desc),
str('region', clan.region),
str('type', clan.type),
str('status', clan.status),
bool('autoaccept', clan.autoaccept),
int('mlimit', clan.mlimit),
int('members_cnt', clan.members.length),
int('pos', pos),
int('activity', periodAct),
int('clan_activity_by_periods', periodAct),
...statParams(clan.stats),
],
blocks: [buildAstatBlock(clan, tuning), buildMembershipReqBlock(clan)],
};
}
export function toClanShortInfoBlk(clan: ClanRecord, tuning: ClanTuning): BlkBlock {
return {
name: clan.id,
params: [
str('_id', clan.id),
str('name', clan.name),
str('tag', clan.tag),
str('type', clan.type),
str('slogan', clan.slogan),
str('region', clan.region),
str('status', clan.status),
int('mlimit', clan.mlimit),
int('members_cnt', clan.members.length),
],
blocks: [buildAstatBlock(clan, tuning)],
};
}
export function toClanLogBlk(
clan: ClanRecord,
count: number,
eventsFilter?: string,
lastMark?: string,
): BlkBlock {
const allowedEvents = eventsFilter
? new Set(eventsFilter.split(';').map((s) => s.trim()).filter(Boolean))
: undefined;
const maxId = lastMark && /^\d+$/.test(lastMark) ? Number(lastMark) : Number.MAX_SAFE_INTEGER;
const sorted = [...clan.logs]
.filter((entry) => entry.id < maxId && (!allowedEvents || allowedEvents.has(entry.ev)))
.sort((a, b) => b.id - a.id);
const page = sorted.slice(0, Math.max(1, count));
const nextMark = sorted.length > page.length ? String(page[page.length - 1]!.id) : '';
return {
name: '',
params: nextMark ? [str('lastMark', nextMark)] : [],
blocks: page.map(logEntryToBlk),
};
}
function memberToBlk(m: ClanMemberRecord): BlkBlock {
return {
name: 'members',
params: [str('uid', m.uid), str('nick', m.nick), int('role', m.role), int('date', m.joinDateSec)],
blocks: [],
};
}
function buildMemberRatingsBlock(clan: ClanRecord): BlkBlock {
return {
name: 'member_ratings',
params: [],
blocks: clan.members.map((m) => ({
name: m.uid,
params: [int('dr_era5_arc', m.ratingArc), int('dr_era5_hist', m.ratingHist), int('dr_era5_sim', m.ratingSim)],
blocks: [],
})),
};
}
function buildMembershipReqBlock(clan: ClanRecord): BlkBlock {
return clan.membershipReqBlk
? { ...structuredClone(clan.membershipReqBlk), name: 'membership_req' }
: { name: 'membership_req', params: [], blocks: [] };
}
function logEntryToBlk(entry: ClanLogEntry): BlkBlock {
const params: BlkParam[] = [
str('ev', entry.ev),
int('time', entry.timeSec),
str('uId', entry.uId),
str('uN', entry.uN),
];
for (const key of OPTIONAL_LOG_STRING_KEYS) {
const val = entry[key];
if (val !== undefined) params.push(str(key, val));
}
return { name: 'log', params, blocks: [] };
}
function buildAstatBlock(clan: ClanRecord, tuning: ClanTuning): BlkBlock {
const periodAct = totalPeriodActivityOf(clan, tuning);
return {
name: 'astat',
params: [
int('activity', periodAct),
int('clan_activity_by_periods', periodAct),
...statParams(clan.stats),
],
blocks: [],
};
}
function statParams(stats: ClanStats): BlkParam[] {
return CLAN_STAT_KEYS.map((key) => int(key, stats[key]));
}
function buildMemberActivityBlock(member: ClanMemberRecord, todayDay: number): BlkBlock {
const periods = member.periods.length > 0
? member.periods
: [{ day: todayDay, activity: member.curActivity, exp: 20000 }];
return {
name: member.uid,
params: [
int('cur', member.curActivity),
int('total', member.totalActivity),
int('activity', member.curActivity),
int('exp', member.earnedSquadronExp),
],
blocks: [
{ name: 'history', params: periods.map((p) => int(String(p.day), p.activity)), blocks: [] },
{
name: 'expActivity',
params: [],
blocks: periods.map((p) => ({
name: String(p.day),
params: [int('activity', p.activity), int('exp', p.exp), int('expRewardBase', p.exp), int('expBoost', 0)],
blocks: [],
})),
},
],
};
}
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: Math.trunc(value) } };
}
function bool(name: string, value: boolean): BlkParam {
return { name, value: { type: 'bool', value } };
}
+296
View File
@@ -0,0 +1,296 @@
/**
* Squadron lifecycle rules: creation, info editing, upgrading from training battalion to
* full squadron, member-limit expansion, requirements, and disbanding.
*/
import type { BlkBlock } from '@wto/blk';
import type { Account } from '../accounts/account-store.ts';
import type { ClanEconomy } from '../game-data/datasets/clan-economy.ts';
import type { ClanKind } from '../profile/profile-clan.ts';
import { canAfford, pay, type Price } from '../profile/profile-currency.ts';
import { ACCEPTED, refused, type RuleOutcome } from '../research/rule-outcome.ts';
import { appendClanLog, clearCandidateEverywhere, hasClanManageRight } from './clan-membership.ts';
import { buildDefaultPeriods } from './clan-seeds.ts';
import type { ClanTuning } from './clan-tuning.ts';
import {
ClanRole,
type ClanMemberRecord,
type ClanRecord,
} from './clan-types.ts';
export interface StoredClansState {
nextClanId: number;
clans: ClanRecord[];
}
export interface CreateClanInput {
readonly name: string;
readonly tag: string;
readonly slogan: string;
readonly region: string;
readonly desc: string;
readonly announcement: string;
readonly type: ClanKind;
readonly offered: Price;
}
export interface ClanInfoChanges {
readonly name?: string | undefined;
readonly tag?: string | undefined;
readonly desc?: string | undefined;
readonly slogan?: string | undefined;
readonly announcement?: string | undefined;
readonly region?: string | undefined;
readonly status?: 'open' | 'closed' | undefined;
}
export function stripClanDecorators(tag: string): string {
return tag.replace(/^[^\p{L}\p{N}_]+|[^\p{L}\p{N}_]+$/gu, '');
}
export function createClanInState(
state: StoredClansState,
profile: BlkBlock,
account: Account,
economy: ClanEconomy,
tuning: ClanTuning,
input: CreateClanInput,
nowSec: number,
): RuleOutcome {
if (state.clans.some((c) => c.members.some((m) => m.uid === account.userId))) return refused('NOT_AVAILABLE');
const name = input.name.trim();
const tag = input.tag.trim();
if (!name || !tag || !stripClanDecorators(tag)) return refused('BAD_PARAMS');
if (hasConflictingClan(state.clans, undefined, name, tag)) return refused('NOT_AVAILABLE');
const expectedPrice: Price = input.type === 'battalion'
? { silverLions: economy.battalionCreateSilver, goldenEagles: economy.battalionCreateGold }
: { silverLions: economy.normalCreateSilver, goldenEagles: economy.normalCreateGold };
if (input.offered.silverLions !== expectedPrice.silverLions || input.offered.goldenEagles !== expectedPrice.goldenEagles) {
return refused('PRICE_CHANGED');
}
if (!canAfford(profile, expectedPrice)) return refused('NOT_ENOUGH_MONEY');
clearCandidateEverywhere(state.clans, account.userId);
pay(profile, expectedPrice);
state.clans.unshift(buildCreatedClanRecord(String(state.nextClanId++), account, name, tag, input, nowSec, tuning));
return ACCEPTED;
}
export function editClanInfoInState(
clans: readonly ClanRecord[],
clan: ClanRecord | undefined,
profile: BlkBlock,
account: Account,
economy: ClanEconomy,
changes: ClanInfoChanges,
nowSec: number,
): RuleOutcome {
if (!clan || !hasClanManageRight(clan, account.userId)) return refused('NOT_AVAILABLE');
const nextName = changes.name !== undefined && changes.name.trim() ? changes.name.trim() : clan.name;
const nextTag = changes.tag !== undefined && changes.tag.trim() ? changes.tag.trim() : clan.tag;
if (!stripClanDecorators(nextTag)) return refused('BAD_PARAMS');
if (hasConflictingClan(clans, clan.id, nextName, nextTag)) return refused('NOT_AVAILABLE');
const editPrice = computeInfoEditPrice(clan, economy, nextName, nextTag, changes);
if (!canAfford(profile, editPrice)) return refused('NOT_ENOUGH_MONEY');
pay(profile, editPrice);
applyInfoFieldUpdates(clan, account, nextName, nextTag, changes, nowSec);
return ACCEPTED;
}
export function upgradeClanToNormalInState(
clans: readonly ClanRecord[],
clan: ClanRecord | undefined,
profile: BlkBlock,
account: Account,
economy: ClanEconomy,
tuning: ClanTuning,
input: { readonly tag: string; readonly desc: string; readonly announcement: string },
nowSec: number,
): RuleOutcome {
if (!clan || clan.type !== 'battalion' || !hasClanManageRight(clan, account.userId)) return refused('NOT_AVAILABLE');
const nextTag = input.tag.trim() || clan.tag;
if (!stripClanDecorators(nextTag) || hasConflictingClan(clans, clan.id, clan.name, nextTag)) {
return refused('NOT_AVAILABLE');
}
const goldCost = Math.max(0, economy.upgradeBattalionToNormalGold - clan.mspent);
const price: Price = { silverLions: economy.upgradeBattalionToNormalSilver, goldenEagles: goldCost };
if (!canAfford(profile, price)) return refused('NOT_ENOUGH_MONEY');
pay(profile, price);
clan.type = 'normal';
clan.mlimit = tuning.memberLimits.normal;
clan.tag = nextTag;
clan.lastPaidTag = nextTag;
clan.desc = input.desc;
clan.announcement = input.announcement;
clan.changedByUid = account.userId;
clan.changedByNick = account.nick;
clan.changedTimeSec = nowSec;
appendClanLog(clan, {
ev: 'upgrade', timeSec: nowSec, uId: account.userId, uN: account.nick,
type: 'normal', tag: clan.tag, desc: clan.desc,
});
return ACCEPTED;
}
export function upgradeMembersLimitInState(
clan: ClanRecord | undefined,
profile: BlkBlock,
account: Account,
economy: ClanEconomy,
nowSec: number,
): RuleOutcome {
if (!clan || clan.type !== 'battalion' || !hasClanManageRight(clan, account.userId)) return refused('NOT_AVAILABLE');
if (clan.mlimit >= economy.battalionMembersUpgradeLimit) return refused('NOT_AVAILABLE');
const price: Price = { silverLions: 0, goldenEagles: economy.battalionMembersUpgradeGold };
if (!canAfford(profile, price)) return refused('NOT_ENOUGH_MONEY');
const oldLimit = clan.mlimit;
pay(profile, price);
clan.mlimit = Math.min(economy.battalionMembersUpgradeLimit, clan.mlimit + economy.battalionMembersUpgradeStep);
clan.mspent += economy.battalionMembersUpgradeGold;
appendClanLog(clan, {
ev: 'upgrade_members', timeSec: nowSec, uId: account.userId, uN: account.nick,
old: String(oldLimit), new: String(clan.mlimit),
});
return ACCEPTED;
}
export function disbandClanInState(state: StoredClansState, clan: ClanRecord | undefined, account: Account): RuleOutcome {
const role = clan?.members.find((m) => m.uid === account.userId)?.role;
if (!clan || (role !== ClanRole.LEADER && role !== ClanRole.CLANADMIN)) return refused('NOT_AVAILABLE');
state.clans = state.clans.filter((c) => c.id !== clan.id);
return ACCEPTED;
}
function hasConflictingClan(clans: readonly ClanRecord[], excludeId: string | undefined, name: string, tag: string): boolean {
const lowerName = name.toLowerCase();
const coreTag = stripClanDecorators(tag).toLowerCase();
return clans.some((c) => c.id !== excludeId && (c.name.toLowerCase() === lowerName || stripClanDecorators(c.tag).toLowerCase() === coreTag));
}
function computeInfoEditPrice(
clan: ClanRecord,
economy: ClanEconomy,
nextName: string,
nextTag: string,
changes: ClanInfoChanges,
): Price {
const nameChanged = nextName !== clan.name;
const coreTagChanged = stripClanDecorators(nextTag) !== stripClanDecorators(clan.tag);
const paidDecorChanged = nextTag !== clan.tag && nextTag !== clan.lastPaidTag && !isFreeDecorator(clan.type, nextTag, economy);
const primaryChanged = nameChanged || coreTagChanged || paidDecorChanged;
const secondaryChanged = (changes.desc !== undefined && changes.desc !== clan.desc)
|| (changes.slogan !== undefined && changes.slogan !== clan.slogan)
|| (changes.announcement !== undefined && changes.announcement !== clan.announcement)
|| (changes.region !== undefined && changes.region !== clan.region);
const primaryGold = clan.type === 'battalion' ? economy.battalionPrimaryEditGold : economy.normalPrimaryEditGold;
const primarySilver = clan.type === 'battalion' ? economy.battalionPrimaryEditSilver : economy.normalPrimaryEditSilver;
const secondaryGold = clan.type === 'battalion' ? economy.battalionSecondaryEditGold : economy.normalSecondaryEditGold;
const secondarySilver = clan.type === 'battalion' ? economy.battalionSecondaryEditSilver : economy.normalSecondaryEditSilver;
return {
silverLions: (primaryChanged ? primarySilver : 0) + (!primaryChanged && secondaryChanged ? secondarySilver : 0),
goldenEagles: (primaryChanged ? primaryGold : 0) + (!primaryChanged && secondaryChanged ? secondaryGold : 0),
};
}
function isFreeDecorator(clanType: ClanKind, tag: string, economy: ClanEconomy): boolean {
const freeList = clanType === 'battalion' ? economy.battalionFreeDecorators : economy.normalFreeDecorators;
return freeList.some((decor) => {
const half = Math.floor(decor.length / 2);
const start = decor.slice(0, half);
const end = decor.slice(half);
return tag.startsWith(start) && tag.endsWith(end);
});
}
function applyInfoFieldUpdates(
clan: ClanRecord,
account: Account,
nextName: string,
nextTag: string,
changes: ClanInfoChanges,
nowSec: number,
): void {
clan.name = nextName;
if (nextTag !== clan.tag) {
clan.tag = nextTag;
clan.lastPaidTag = nextTag;
}
if (changes.desc !== undefined) clan.desc = changes.desc;
if (changes.slogan !== undefined) clan.slogan = changes.slogan;
if (changes.announcement !== undefined) clan.announcement = changes.announcement;
if (changes.region !== undefined && changes.region !== clan.region) {
clan.region = changes.region;
clan.regionLastUpdatedSec = nowSec;
}
if (changes.status !== undefined) clan.status = changes.status;
clan.changedByUid = account.userId;
clan.changedByNick = account.nick;
clan.changedTimeSec = nowSec;
appendClanLog(clan, {
ev: 'info', timeSec: nowSec, uId: account.userId, uN: account.nick,
name: clan.name, tag: clan.tag, desc: clan.desc, slogan: clan.slogan,
region: clan.region, announcement: clan.announcement, status: clan.status,
});
}
function buildCreatedClanRecord(
id: string,
account: Account,
name: string,
tag: string,
input: CreateClanInput,
nowSec: number,
tuning: ClanTuning,
): ClanRecord {
const periods = buildDefaultPeriods(Math.floor(nowSec / 86400), tuning);
const leader: ClanMemberRecord = {
uid: account.userId,
nick: account.nick,
role: ClanRole.LEADER,
joinDateSec: nowSec,
curActivity: tuning.activity.maxPerPeriod,
totalActivity: periods.reduce((s, p) => s + p.activity, 0),
earnedSquadronExp: periods.reduce((s, p) => s + p.exp, 0),
ratingArc: tuning.playerRating.founder.arc,
ratingHist: tuning.playerRating.founder.hist,
ratingSim: tuning.playerRating.founder.sim,
periods,
};
const desc = input.type === 'normal' ? input.desc : '';
return {
id, name, tag, lastPaidTag: tag, type: input.type,
slogan: input.slogan, desc, announcement: input.announcement, region: input.region,
status: 'open', autoaccept: true,
mlimit: input.type === 'battalion' ? tuning.memberLimits.battalionInitial : tuning.memberLimits.normal,
mspent: 0, cdateSec: nowSec,
changedByUid: account.userId, changedByNick: account.nick, changedTimeSec: nowSec,
regionLastUpdatedSec: input.region ? nowSec : 0,
stats: {
dr_era5_arc: 1500, dr_era5_hist: 1500, dr_era5_sim: 1500,
akills_arc: 0, akills_hist: 0, akills_sim: 0,
gkills_arc: 0, gkills_hist: 0, gkills_sim: 0,
deaths_arc: 0, deaths_hist: 0, deaths_sim: 0,
ftime_arc: 0, ftime_hist: 0, ftime_sim: 0,
},
members: [leader],
candidates: [],
blacklist: [],
logs: [{
id: 1, ev: 'create', timeSec: nowSec, uId: account.userId, uN: account.nick,
name, type: input.type, tag, desc, slogan: input.slogan, region: input.region, announcement: input.announcement,
}],
bestRewards: [],
};
}
+292
View File
@@ -0,0 +1,292 @@
/**
* Squadron membership, candidate moderation, role changes, blacklist, and event-log helpers
*.
*/
import type { ClanTuning } from './clan-tuning.ts';
import type { Account } from '../accounts/account-store.ts';
import { ACCEPTED, refused, type RuleOutcome } from '../research/rule-outcome.ts';
import { buildDefaultPeriods } from './clan-seeds.ts';
import {
ClanRole,
isAssignableClanRole,
roleNameOf,
type ClanLogEntry,
type ClanRecord,
} from './clan-types.ts';
export interface MembershipRequestQuery {
readonly clanId?: string | undefined;
readonly clanName?: string | undefined;
readonly clanTag?: string | undefined;
readonly cancel?: boolean | undefined;
readonly comment?: string | undefined;
}
export function hasClanManageRight(clan: ClanRecord, userId: string): boolean {
const role = clan.members.find((m) => m.uid === userId)?.role;
return role === ClanRole.LEADER || role === ClanRole.DEPUTY || role === ClanRole.CLANADMIN;
}
export function hasClanOfficerRight(clan: ClanRecord, userId: string): boolean {
const role = clan.members.find((m) => m.uid === userId)?.role;
return role === ClanRole.LEADER || role === ClanRole.DEPUTY || role === ClanRole.OFFICER || role === ClanRole.CLANADMIN;
}
export function appendClanLog(clan: ClanRecord, entry: Omit<ClanLogEntry, 'id'>): void {
const nextId = clan.logs.reduce((max, item) => Math.max(max, item.id), 0) + 1;
clan.logs.push({ id: nextId, ...entry });
}
export function clearCandidateEverywhere(clans: readonly ClanRecord[], userId: string): void {
for (const clan of clans) {
clan.candidates = clan.candidates.filter((c) => c.uid !== userId);
}
}
export function addMemberToClan(
clan: ClanRecord,
uid: string,
nick: string,
role: number,
initiatorUid: string,
initiatorNick: string,
nowSec: number,
tuning: ClanTuning,
): void {
if (clan.members.some((m) => m.uid === uid)) return;
const periods = buildDefaultPeriods(Math.floor(nowSec / 86400), tuning);
clan.members.push({
uid,
nick,
role,
joinDateSec: nowSec,
curActivity: tuning.activity.maxPerPeriod,
totalActivity: periods.reduce((s, p) => s + p.activity, 0),
earnedSquadronExp: periods.reduce((s, p) => s + p.exp, 0),
ratingArc: tuning.playerRating.joiner.arc,
ratingHist: tuning.playerRating.joiner.hist,
ratingSim: tuning.playerRating.joiner.sim,
periods,
});
appendClanLog(clan, {
ev: 'add',
timeSec: nowSec,
uId: initiatorUid,
uN: initiatorNick,
uid,
nick,
role: roleNameOf(role),
});
}
export function requestOrCancelMembershipInState(
clans: readonly ClanRecord[],
targetClan: ClanRecord | undefined,
alreadyInClan: boolean,
account: Account,
query: MembershipRequestQuery,
nowSec: number,
tuning: ClanTuning,
): { readonly outcome: RuleOutcome; readonly mutated: boolean } {
if (query.cancel || (!query.clanId && !query.clanName && !query.clanTag) || query.clanId === '-1') {
clearCandidateEverywhere(clans, account.userId);
return { outcome: ACCEPTED, mutated: true };
}
if (alreadyInClan) return { outcome: refused('NOT_AVAILABLE'), mutated: false };
if (!targetClan || targetClan.status === 'closed' || targetClan.members.length >= targetClan.mlimit) {
return { outcome: refused('NOT_AVAILABLE'), mutated: false };
}
if (targetClan.blacklist.some((b) => b.uid === account.userId)) {
return { outcome: refused('NOT_AVAILABLE'), mutated: false };
}
clearCandidateEverywhere(clans, account.userId);
if (targetClan.autoaccept) {
addMemberToClan(targetClan, account.userId, account.nick, ClanRole.REGULAR, account.userId, account.nick, nowSec, tuning);
} else {
targetClan.candidates.push({
uid: account.userId,
nick: account.nick,
comment: query.comment ?? '',
dateSec: nowSec,
});
}
return { outcome: ACCEPTED, mutated: true };
}
export function leaveClanInState(
clans: ClanRecord[],
clan: ClanRecord | undefined,
account: Account,
nowSec: number,
): { readonly outcome: RuleOutcome; readonly nextClans: ClanRecord[] } {
if (!clan) return { outcome: refused('NOT_AVAILABLE'), nextClans: clans };
clan.members = clan.members.filter((m) => m.uid !== account.userId);
if (clan.members.length === 0) {
return { outcome: ACCEPTED, nextClans: clans.filter((c) => c.id !== clan.id) };
}
if (!clan.members.some((m) => m.role === ClanRole.LEADER)) {
clan.members[0] = { ...clan.members[0]!, role: ClanRole.LEADER };
}
appendClanLog(clan, {
ev: 'rem',
timeSec: nowSec,
uId: account.userId,
uN: account.nick,
uid: account.userId,
nick: account.nick,
});
return { outcome: ACCEPTED, nextClans: clans };
}
export function acceptCandidateOnClan(
allClans: readonly ClanRecord[],
clan: ClanRecord | undefined,
initiator: Account,
targetUid: string,
targetNick: string,
role: number,
nowSec: number,
tuning: ClanTuning,
): boolean {
if (!clan || !hasClanOfficerRight(clan, initiator.userId) || clan.members.length >= clan.mlimit) return false;
const cand = clan.candidates.find((c) => c.uid === targetUid);
if (!cand) return false;
if (allClans.some((c) => c.members.some((m) => m.uid === targetUid))) return false;
const assignedRole = isAssignableClanRole(clan.type, role) ? role : ClanRole.REGULAR;
clearCandidateEverywhere(allClans, targetUid);
addMemberToClan(clan, targetUid, cand.nick || targetNick, assignedRole, initiator.userId, initiator.nick, nowSec, tuning);
return true;
}
export function rejectCandidateOnClan(
clan: ClanRecord | undefined,
initiator: Account,
targetUid: string,
comments: string,
nowSec: number,
): boolean {
if (!clan || !hasClanOfficerRight(clan, initiator.userId)) return false;
const cand = clan.candidates.find((c) => c.uid === targetUid);
if (!cand) return false;
clan.candidates = clan.candidates.filter((c) => c.uid !== targetUid);
appendClanLog(clan, {
ev: 'reject_candidate',
timeSec: nowSec,
uId: initiator.userId,
uN: initiator.nick,
uid: cand.uid,
nick: cand.nick,
comments,
});
return true;
}
export function dismissMemberOnClan(
clan: ClanRecord | undefined,
initiator: Account,
targetUid: string,
comments: string,
nowSec: number,
): boolean {
if (!clan || !hasClanOfficerRight(clan, initiator.userId) || targetUid === initiator.userId) return false;
const member = clan.members.find((m) => m.uid === targetUid);
if (!member || member.role === ClanRole.LEADER) return false;
clan.members = clan.members.filter((m) => m.uid !== targetUid);
appendClanLog(clan, {
ev: 'rem',
timeSec: nowSec,
uId: initiator.userId,
uN: initiator.nick,
uid: member.uid,
nick: member.nick,
comments,
});
return true;
}
export function changeMemberRoleOnClan(
clan: ClanRecord | undefined,
initiator: Account,
targetUid: string,
newRole: number,
nowSec: number,
): boolean {
if (!clan || !hasClanManageRight(clan, initiator.userId) || targetUid === initiator.userId) return false;
const initiatorIdx = clan.members.findIndex((m) => m.uid === initiator.userId);
const targetIdx = clan.members.findIndex((m) => m.uid === targetUid);
if (initiatorIdx < 0 || targetIdx < 0) return false;
const initiatorMember = clan.members[initiatorIdx]!;
const prev = clan.members[targetIdx]!;
if (newRole === ClanRole.LEADER) {
if (initiatorMember.role !== ClanRole.LEADER) return false;
const demotedRole = clan.type === 'battalion' ? ClanRole.OFFICER : ClanRole.DEPUTY;
clan.members[initiatorIdx] = { ...initiatorMember, role: demotedRole };
clan.members[targetIdx] = { ...prev, role: ClanRole.LEADER };
} else {
if (prev.role === ClanRole.LEADER || !isAssignableClanRole(clan.type, newRole)) return false;
clan.members[targetIdx] = { ...prev, role: newRole };
}
appendClanLog(clan, {
ev: 'role',
timeSec: nowSec,
uId: initiator.userId,
uN: initiator.nick,
uid: prev.uid,
nick: prev.nick,
old: roleNameOf(prev.role),
new: roleNameOf(newRole),
});
return true;
}
export function editBlacklistOnClan(
clan: ClanRecord | undefined,
initiator: Account,
targetUid: string,
targetNick: string,
add: boolean,
comments: string,
nowSec: number,
): boolean {
if (!clan || !hasClanOfficerRight(clan, initiator.userId)) return false;
if (add) {
clan.candidates = clan.candidates.filter((c) => c.uid !== targetUid);
const resolvedNick = targetNick || `Pilot_${targetUid}`;
if (!clan.blacklist.some((b) => b.uid === targetUid)) {
clan.blacklist.push({
uid: targetUid,
nick: resolvedNick,
initiatorUid: initiator.userId,
initiatorNick: initiator.nick,
comments,
dateSec: nowSec,
});
}
appendClanLog(clan, {
ev: 'add_to_blacklist',
timeSec: nowSec,
uId: initiator.userId,
uN: initiator.nick,
uid: targetUid,
nick: resolvedNick,
comments,
});
} else {
const existing = clan.blacklist.find((b) => b.uid === targetUid);
clan.blacklist = clan.blacklist.filter((b) => b.uid !== targetUid);
appendClanLog(clan, {
ev: 'remove_from_blacklist',
timeSec: nowSec,
uId: initiator.userId,
uN: initiator.nick,
uid: targetUid,
nick: existing?.nick ?? targetNick,
comments,
});
}
return true;
}
+83
View File
@@ -0,0 +1,83 @@
/**
* Read-only search and leaderboard queries over the local squadron directory
*.
*/
import type { ClanTuning } from './clan-tuning.ts';
import { stripClanDecorators } from './clan-lifecycle.ts';
import { totalPeriodActivityOf, type ClanRecord } from './clan-types.ts';
export interface LeaderboardQuery {
readonly start: number;
readonly count: number;
readonly sortField: string;
readonly clanId?: string | undefined;
readonly prefix?: string | undefined;
readonly filterOpen?: boolean | undefined;
readonly filterNotFull?: boolean | undefined;
readonly filterAutoAccept?: boolean | undefined;
}
export function findClanInList(
clans: readonly ClanRecord[],
query: { readonly clanId?: string | undefined; readonly clanName?: string | undefined; readonly clanTag?: string | undefined },
): ClanRecord | undefined {
if (query.clanId && query.clanId !== '-1') {
const byId = clans.find((c) => c.id === query.clanId);
if (byId) return byId;
}
if (query.clanName) {
const lower = query.clanName.toLowerCase();
const byName = clans.find((c) => c.name.toLowerCase() === lower);
if (byName) return byName;
}
if (query.clanTag) {
const lower = query.clanTag.toLowerCase();
const byTag = clans.find((c) => c.tag.toLowerCase() === lower);
if (byTag) return byTag;
}
return undefined;
}
export function queryClanLeaderboard(
clans: readonly ClanRecord[],
query: LeaderboardQuery,
tuning: ClanTuning,
): ReadonlyArray<{ readonly clan: ClanRecord; readonly pos: number }> {
const sorted = [...clans].sort((a, b) => metricOf(b, query.sortField, tuning) - metricOf(a, query.sortField, tuning));
const withPos = sorted.map((clan, index) => ({ clan, pos: index }));
if (query.clanId && query.clanId !== '-1') return withPos.filter((entry) => entry.clan.id === query.clanId);
const prefix = query.prefix?.trim().toLowerCase() ?? '';
const filtered = withPos.filter(({ clan }) => {
if (query.filterOpen && clan.status === 'closed') return false;
if (query.filterNotFull && clan.members.length >= clan.mlimit) return false;
if (query.filterAutoAccept && !clan.autoaccept) return false;
if (prefix) {
const strippedTag = stripClanDecorators(clan.tag).toLowerCase();
if (!clan.name.toLowerCase().includes(prefix) && !clan.tag.toLowerCase().includes(prefix) && !strippedTag.includes(prefix)) {
return false;
}
}
return true;
});
const start = Math.max(0, query.start);
const count = query.count > 0 ? query.count : 20;
return filtered.slice(start, start + count);
}
function metricOf(clan: ClanRecord, sortField: string, tuning: ClanTuning): number {
switch (sortField) {
case 'activity':
case 'clan_activity_by_periods':
return totalPeriodActivityOf(clan, tuning);
case 'members_cnt':
return clan.members.length;
case 'dr_era5_arc':
return clan.stats.dr_era5_arc;
case 'dr_era5_sim':
return clan.stats.dr_era5_sim;
case 'dr_era5_hist':
default:
return clan.stats.dr_era5_hist;
}
}
+80
View File
@@ -0,0 +1,80 @@
/**
* The preset squadron directory written on first creation of `<data>/clans.json`
* (implementation notes section I; implementation notes), and the activity periods a member
* starts with. Both are tuning (tuning/clans.jsonc).
*/
import type { ClanTuning, PresetClan, PresetMember } from './clan-tuning.ts';
import type { ClanActivityPeriodEntry, ClanMemberRecord, ClanRecord } from './clan-types.ts';
const SECONDS_PER_DAY = 86400;
export function createDefaultClans(tuning: ClanTuning, nowSec = Math.floor(Date.now() / 1000)): ClanRecord[] {
const todayDay = Math.floor(nowSec / SECONDS_PER_DAY);
const createdBase = nowSec - tuning.presetClans.createdDaysAgo * SECONDS_PER_DAY;
return tuning.presetClans.clans.map((spec) => buildSeededClan(spec, createdBase + spec.createdAfterDays * SECONDS_PER_DAY, todayDay, tuning));
}
/** The activity periods a member starts with: startingPeriods periods, each with the given activity and the squadron RP it earns. */
export function buildDefaultPeriods(todayDay: number, tuning: ClanTuning, periodActivity = tuning.activity.maxPerPeriod): ClanActivityPeriodEntry[] {
const { maxPerPeriod, squadronRpPerFullPeriod, rewardPeriodDays, startingPeriods } = tuning.activity;
const exp = Math.round((periodActivity / maxPerPeriod) * squadronRpPerFullPeriod);
return Array.from({ length: startingPeriods }, (_, idx) => ({ day: todayDay - idx * rewardPeriodDays, activity: periodActivity, exp }));
}
function buildSeededClan(spec: PresetClan, cdateSec: number, todayDay: number, tuning: ClanTuning): ClanRecord {
const members = spec.members.map((npc, idx) => buildSeededMember(spec, npc, idx, cdateSec, todayDay, tuning));
const leader = spec.members[0]!;
return {
id: spec.id,
name: spec.name,
tag: spec.tag,
lastPaidTag: spec.tag,
type: spec.type,
slogan: spec.slogan,
desc: spec.desc,
announcement: spec.announcement,
region: spec.region,
status: 'open',
autoaccept: spec.autoAccept,
mlimit: spec.type === 'battalion' ? tuning.memberLimits.battalionInitial : tuning.memberLimits.normal,
mspent: 0,
cdateSec,
changedByUid: leader.uid,
changedByNick: leader.nick,
changedTimeSec: cdateSec,
regionLastUpdatedSec: 0,
stats: { dr_era5_arc: spec.rating.arc, dr_era5_hist: spec.rating.hist, dr_era5_sim: spec.rating.sim, ...tuning.presetClans.stats },
members,
candidates: [],
blacklist: [],
logs: [{
id: 1, ev: 'create', timeSec: cdateSec, uId: leader.uid, uN: leader.nick,
name: spec.name, type: spec.type, tag: spec.tag, desc: spec.desc,
slogan: spec.slogan, region: spec.region, announcement: spec.announcement,
}],
bestRewards: [],
};
}
function buildSeededMember(spec: PresetClan, npc: PresetMember, idx: number, cdateSec: number, todayDay: number, tuning: ClanTuning): ClanMemberRecord {
const periods = buildDefaultPeriods(todayDay, tuning, npc.activity);
const { step, floor } = tuning.presetClans.memberRating;
return {
uid: npc.uid,
nick: npc.nick,
role: npc.role,
joinDateSec: cdateSec + idx * tuning.presetClans.memberJoinSpacingMinutes * 60,
isNpc: true,
npcTitle: npc.title,
npcPilotIcon: npc.icon,
npcFrame: '',
npcShowcaseUnit: npc.unit,
curActivity: npc.activity,
totalActivity: periods.reduce((sum, p) => sum + p.activity, 0),
earnedSquadronExp: periods.reduce((sum, p) => sum + p.exp, 0),
ratingArc: Math.max(floor.arc, spec.rating.arc - idx * step.arc),
ratingHist: Math.max(floor.hist, spec.rating.hist - idx * step.hist),
ratingSim: Math.max(floor.sim, spec.rating.sim - idx * step.sim),
periods,
};
}
+260
View File
@@ -0,0 +1,260 @@
/**
* Persistent local squadron (clan) directory & state store (`<data>/clans.json`),
* delegating queries, lifecycle, and membership rules to `clan-queries.ts`,
* `clan-lifecycle.ts`, and `clan-membership.ts` (implementation notes; implementation notes I).
*/
import { existsSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import type { BlkBlock } from '@wto/blk';
import type { Account } from '../accounts/account-store.ts';
import type { ClanEconomy } from '../game-data/datasets/clan-economy.ts';
import {
clanMembershipOf,
clearClanMembership,
setClanMembership,
setPendingClanRequest,
syncStoredClanEarnedExp,
} from '../profile/profile-clan.ts';
import type { RuleOutcome } from '../research/rule-outcome.ts';
import { writeFileAtomic } from '../storage/atomic-file.ts';
import {
createClanInState,
disbandClanInState,
editClanInfoInState,
upgradeClanToNormalInState,
upgradeMembersLimitInState,
type ClanInfoChanges,
type CreateClanInput,
type StoredClansState,
} from './clan-lifecycle.ts';
import {
acceptCandidateOnClan,
changeMemberRoleOnClan,
dismissMemberOnClan,
editBlacklistOnClan,
hasClanManageRight,
leaveClanInState,
rejectCandidateOnClan,
requestOrCancelMembershipInState,
type MembershipRequestQuery,
} from './clan-membership.ts';
import { findClanInList, queryClanLeaderboard, type LeaderboardQuery } from './clan-queries.ts';
import { createDefaultClans } from './clan-seeds.ts';
import type { ClanTuning } from './clan-tuning.ts';
import type { ClanBestReward, ClanMemberRecord, ClanRecord } from './clan-types.ts';
export type { LeaderboardQuery };
export class ClanStore {
readonly #filePath: string;
/** tuning/clans.jsonc; the clan actions serialize clan info with it too. */
readonly tuning: ClanTuning;
#state: StoredClansState;
constructor(dataFolder: string, tuning: ClanTuning) {
this.#filePath = join(dataFolder, 'clans.json');
this.tuning = tuning;
this.#state = this.#loadOrSeed();
}
#loadOrSeed(): StoredClansState {
if (existsSync(this.#filePath)) {
const parsed = JSON.parse(readFileSync(this.#filePath, 'utf8')) as StoredClansState;
if (Array.isArray(parsed.clans) && typeof parsed.nextClanId === 'number') return parsed;
}
const seeded: StoredClansState = { nextClanId: this.tuning.firstNewClanId, clans: createDefaultClans(this.tuning) };
this.#save(seeded);
return seeded;
}
#save(state: StoredClansState = this.#state): void {
writeFileAtomic(this.#filePath, JSON.stringify(state, null, 2));
}
#resolveClan(clanId: string | undefined, userId: string): ClanRecord | undefined {
return clanId && clanId !== '-1' ? this.byId(clanId) : this.clanOfUser(userId)?.clan;
}
byId(clanId: string): ClanRecord | undefined {
return this.#state.clans.find((c) => c.id === clanId);
}
findClan(query: { readonly clanId?: string | undefined; readonly clanName?: string | undefined; readonly clanTag?: string | undefined }): ClanRecord | undefined {
return findClanInList(this.#state.clans, query);
}
clanOfUser(userId: string): { readonly clan: ClanRecord; readonly member: ClanMemberRecord } | undefined {
for (const clan of this.#state.clans) {
const member = clan.members.find((m) => m.uid === userId);
if (member) return { clan, member };
}
return undefined;
}
pendingRequestOfUser(userId: string): ClanRecord | undefined {
return this.#state.clans.find((c) => c.candidates.some((cand) => cand.uid === userId));
}
earnedSquadronExpOf(userId: string): number {
return this.clanOfUser(userId)?.member.earnedSquadronExp ?? 0;
}
npcMemberByUid(uid: string): { readonly clan: ClanRecord; readonly member: ClanMemberRecord } | undefined {
for (const clan of this.#state.clans) {
const member = clan.members.find((m) => m.uid === uid && m.isNpc);
if (member) return { clan, member };
}
return undefined;
}
syncProfile(profile: BlkBlock, account: Account): void {
const found = this.clanOfUser(account.userId);
if (found) {
const { clan, member } = found;
if (member.nick !== account.nick) {
const idx = clan.members.findIndex((m) => m.uid === account.userId);
if (idx >= 0) {
clan.members[idx] = { ...member, nick: account.nick };
this.#save();
}
}
setClanMembership(profile, { clanId: clan.id, clanTag: clan.tag, clanName: clan.name, clanType: clan.type, role: member.role });
syncStoredClanEarnedExp(profile, member.earnedSquadronExp);
return;
}
const pending = this.pendingRequestOfUser(account.userId);
if (pending) {
setPendingClanRequest(profile, { clanId: pending.id, clanTag: pending.tag, clanName: pending.name });
} else if (clanMembershipOf(profile).clanId !== '-1' || clanMembershipOf(profile).requestedClanId !== '-1') {
clearClanMembership(profile);
}
}
queryLeaderboard(query: LeaderboardQuery): ReadonlyArray<{ readonly clan: ClanRecord; readonly pos: number }> {
return queryClanLeaderboard(this.#state.clans, query, this.tuning);
}
createClan(profile: BlkBlock, account: Account, economy: ClanEconomy, input: CreateClanInput, nowSec = nowSeconds()): RuleOutcome {
const outcome = createClanInState(this.#state, profile, account, economy, this.tuning, input, nowSec);
if (outcome.ok) {
this.#save();
this.syncProfile(profile, account);
}
return outcome;
}
editClanInfo(profile: BlkBlock, account: Account, economy: ClanEconomy, clanId: string, changes: ClanInfoChanges, nowSec = nowSeconds()): RuleOutcome {
const outcome = editClanInfoInState(this.#state.clans, this.#resolveClan(clanId, account.userId), profile, account, economy, changes, nowSec);
if (outcome.ok) {
this.#save();
this.syncProfile(profile, account);
}
return outcome;
}
upgradeClanToNormal(
profile: BlkBlock,
account: Account,
economy: ClanEconomy,
clanId: string,
input: { readonly tag: string; readonly desc: string; readonly announcement: string },
nowSec = nowSeconds(),
): RuleOutcome {
const outcome = upgradeClanToNormalInState(this.#state.clans, this.#resolveClan(clanId, account.userId), profile, account, economy, this.tuning, input, nowSec);
if (outcome.ok) {
this.#save();
this.syncProfile(profile, account);
}
return outcome;
}
upgradeMembersLimit(profile: BlkBlock, account: Account, economy: ClanEconomy, clanId: string, nowSec = nowSeconds()): RuleOutcome {
const outcome = upgradeMembersLimitInState(this.#resolveClan(clanId, account.userId), profile, account, economy, nowSec);
if (outcome.ok) {
this.#save();
this.syncProfile(profile, account);
}
return outcome;
}
setMembershipRequirements(clanId: string, account: Account, reqBlk: BlkBlock | undefined, autoaccept: boolean): boolean {
const clan = this.#resolveClan(clanId, account.userId);
if (!clan || !hasClanManageRight(clan, account.userId)) return false;
clan.autoaccept = autoaccept;
if (reqBlk) clan.membershipReqBlk = structuredClone(reqBlk);
else delete clan.membershipReqBlk;
this.#save();
return true;
}
requestOrCancelMembership(profile: BlkBlock, account: Account, query: MembershipRequestQuery, nowSec = nowSeconds()): RuleOutcome {
const res = requestOrCancelMembershipInState(this.#state.clans, this.findClan(query), Boolean(this.clanOfUser(account.userId)), account, query, nowSec, this.tuning);
if (res.mutated) {
this.#save();
this.syncProfile(profile, account);
}
return res.outcome;
}
leaveClan(profile: BlkBlock, account: Account, nowSec = nowSeconds()): RuleOutcome {
const res = leaveClanInState(this.#state.clans, this.clanOfUser(account.userId)?.clan, account, nowSec);
if (res.outcome.ok) {
this.#state.clans = res.nextClans;
this.#save();
clearClanMembership(profile);
}
return res.outcome;
}
disbandClan(profile: BlkBlock, account: Account, clanId?: string): RuleOutcome {
const outcome = disbandClanInState(this.#state, this.#resolveClan(clanId, account.userId), account);
if (outcome.ok) {
this.#save();
this.syncProfile(profile, account);
}
return outcome;
}
acceptCandidate(initiator: Account, clanId: string | undefined, targetUid: string, targetNick: string, role: number, nowSec = nowSeconds()): boolean {
if (!acceptCandidateOnClan(this.#state.clans, this.#resolveClan(clanId, initiator.userId), initiator, targetUid, targetNick, role, nowSec, this.tuning)) return false;
this.#save();
return true;
}
rejectCandidate(initiator: Account, clanId: string | undefined, targetUid: string, comments: string, nowSec = nowSeconds()): boolean {
if (!rejectCandidateOnClan(this.#resolveClan(clanId, initiator.userId), initiator, targetUid, comments, nowSec)) return false;
this.#save();
return true;
}
dismissMember(initiator: Account, targetUid: string, comments: string, nowSec = nowSeconds()): boolean {
if (!dismissMemberOnClan(this.clanOfUser(initiator.userId)?.clan, initiator, targetUid, comments, nowSec)) return false;
this.#save();
return true;
}
changeMemberRole(initiator: Account, targetUid: string, newRole: number, nowSec = nowSeconds()): boolean {
if (!changeMemberRoleOnClan(this.clanOfUser(initiator.userId)?.clan, initiator, targetUid, newRole, nowSec)) return false;
this.#save();
return true;
}
editBlacklist(initiator: Account, clanId: string | undefined, targetUid: string, targetNick: string, add: boolean, comments: string, nowSec = nowSeconds()): boolean {
if (!editBlacklistOnClan(this.#resolveClan(clanId, initiator.userId), initiator, targetUid, targetNick, add, comments, nowSec)) return false;
this.#save();
return true;
}
setBestRewards(clanId: string, initiatorUserId: string, rewards: readonly ClanBestReward[]): boolean {
const clan = this.byId(clanId);
if (!clan || !hasClanManageRight(clan, initiatorUserId)) return false;
clan.bestRewards = [...rewards];
this.#save();
return true;
}
}
function nowSeconds(): number {
return Math.floor(Date.now() / 1000);
}
+132
View File
@@ -0,0 +1,132 @@
/** Typed content of tuning/clans.jsonc. */
import { TuningError, type TuningReader } from '../tuning/tuning-reader.ts';
import { roleCodeFromString, type ClanStats } from './clan-types.ts';
/** The clan statistics a preset clan starts with; the per-mode ratings (dr_era5_*) come from each clan's rating. */
export type PresetClanStats = Omit<ClanStats, 'dr_era5_arc' | 'dr_era5_hist' | 'dr_era5_sim'>;
const STAT_KEYS: readonly (keyof PresetClanStats)[] = [
'akills_arc', 'akills_hist', 'akills_sim', 'gkills_arc', 'gkills_hist', 'gkills_sim',
'deaths_arc', 'deaths_hist', 'deaths_sim', 'ftime_arc', 'ftime_hist', 'ftime_sim',
];
export interface ModeTriple {
readonly arc: number;
readonly hist: number;
readonly sim: number;
}
export interface PresetMember {
readonly uid: string;
readonly nick: string;
readonly role: number;
readonly title: string;
readonly icon: string;
readonly unit: string;
readonly activity: number;
}
export interface PresetClan {
readonly id: string;
readonly tag: string;
readonly name: string;
readonly type: 'normal' | 'battalion';
readonly slogan: string;
readonly desc: string;
readonly announcement: string;
readonly region: string;
readonly autoAccept: boolean;
readonly createdAfterDays: number;
readonly rating: ModeTriple;
readonly members: readonly PresetMember[];
}
export interface ClanTuning {
readonly activity: {
readonly maxPerPeriod: number;
readonly squadronRpPerFullPeriod: number;
readonly rewardPeriodDays: number;
readonly historyDepthDays: number;
readonly startingPeriods: number;
};
readonly memberLimits: { readonly normal: number; readonly battalionInitial: number };
readonly leaderboard: { readonly activityMultiplier: number; readonly maxActivity: number };
readonly firstNewClanId: number;
readonly playerRating: { readonly founder: ModeTriple; readonly joiner: ModeTriple };
readonly presetClans: {
readonly createdDaysAgo: number;
readonly memberJoinSpacingMinutes: number;
readonly stats: PresetClanStats;
readonly memberRating: { readonly step: ModeTriple; readonly floor: ModeTriple };
readonly clans: readonly PresetClan[];
};
}
export function readClanTuning(file: TuningReader): ClanTuning {
const activity = file.object('activity');
const limits = file.object('memberLimits');
const leaderboard = file.object('leaderboard');
const preset = file.object('presetClans');
const stats = preset.object('stats');
const rating = preset.object('memberRating');
return {
activity: {
maxPerPeriod: activity.int('maxPerPeriod', { min: 1 }),
squadronRpPerFullPeriod: activity.int('squadronRpPerFullPeriod', { min: 0 }),
rewardPeriodDays: activity.int('rewardPeriodDays', { min: 1 }),
historyDepthDays: activity.int('historyDepthDays', { min: 1 }),
startingPeriods: activity.int('startingPeriods', { min: 0 }),
},
memberLimits: { normal: limits.int('normal', { min: 1 }), battalionInitial: limits.int('battalionInitial', { min: 1 }) },
leaderboard: { activityMultiplier: leaderboard.number('activityMultiplier', { min: 0 }), maxActivity: leaderboard.int('maxActivity', { min: 0 }) },
firstNewClanId: file.int('firstNewClanId', { min: 1 }),
playerRating: { founder: triple(file.object('playerRating').object('founder')), joiner: triple(file.object('playerRating').object('joiner')) },
presetClans: {
createdDaysAgo: preset.int('createdDaysAgo', { min: 0 }),
memberJoinSpacingMinutes: preset.int('memberJoinSpacingMinutes', { min: 0 }),
stats: Object.fromEntries(STAT_KEYS.map((key) => [key, stats.int(key, { min: 0 })])) as unknown as PresetClanStats,
memberRating: { step: triple(rating.object('step')), floor: triple(rating.object('floor')) },
clans: preset.list('clans', readPresetClan),
},
};
}
function readPresetClan(entry: TuningReader): PresetClan {
const type = entry.string('type');
if (type !== 'normal' && type !== 'battalion') throw new TuningError(`tuning file clans.jsonc: clan type must be normal or battalion (found "${type}")`);
const members = entry.list('members', readPresetMember);
if (members.length === 0) throw new TuningError(`tuning file clans.jsonc: preset clan ${entry.string('id')} needs at least one member (the first is its leader)`);
return {
id: entry.string('id'),
tag: entry.string('tag'),
name: entry.string('name'),
type,
slogan: entry.string('slogan'),
desc: entry.string('desc'),
announcement: entry.string('announcement'),
region: entry.string('region'),
autoAccept: entry.bool('autoAccept'),
createdAfterDays: entry.int('createdAfterDays', { min: 0 }),
rating: triple(entry.object('rating')),
members,
};
}
function readPresetMember(member: TuningReader): PresetMember {
const roleName = member.string('role');
const role = roleCodeFromString(roleName);
if (role === undefined) throw new TuningError(`tuning file clans.jsonc: unknown member role "${roleName}"`);
return {
uid: member.string('uid'),
nick: member.string('nick'),
role,
title: member.string('title'),
icon: member.string('icon'),
unit: member.string('unit'),
activity: member.int('activity', { min: 0 }),
};
}
function triple(entry: TuningReader): ModeTriple {
return { arc: entry.int('arc'), hist: entry.int('hist'), sim: entry.int('sim') };
}
+182
View File
@@ -0,0 +1,182 @@
/**
* Types, binary enum constants, and shared squadron domain constants
*.
*/
import type { ClanTuning } from './clan-tuning.ts';
import type { BlkBlock } from '@wto/blk';
import type { ClanKind } from '../profile/profile-clan.ts';
/** Exact `ECMR_*` role codes registered at aces.exe 0x2986a0..0x298802 (table 0x7ba87e8). */
export const ClanRole = {
LEADER: 1,
OFFICER: 2,
REGULAR: 3,
CLANADMIN: 4,
DEPUTY: 5,
SERGEANT: 6,
} as const;
export type ClanRoleCode = (typeof ClanRole)[keyof typeof ClanRole];
export function roleNameOf(role: number): string {
switch (role) {
case ClanRole.LEADER:
return 'LEADER';
case ClanRole.DEPUTY:
return 'DEPUTY';
case ClanRole.OFFICER:
return 'OFFICER';
case ClanRole.SERGEANT:
return 'SERGEANT';
default:
return 'REGULAR';
}
}
export function roleCodeFromString(name: string): number | undefined {
switch (name.trim().toUpperCase()) {
case 'LEADER':
return ClanRole.LEADER;
case 'DEPUTY':
return ClanRole.DEPUTY;
case 'OFFICER':
return ClanRole.OFFICER;
case 'SERGEANT':
return ClanRole.SERGEANT;
case 'REGULAR':
return ClanRole.REGULAR;
default:
return undefined;
}
}
/** Whether a non-leader member role is valid for the given squadron type (0x2986a0 table). */
export function isAssignableClanRole(clanType: ClanKind, role: number): boolean {
if (clanType === 'battalion') {
return role === ClanRole.OFFICER || role === ClanRole.REGULAR;
}
return role === ClanRole.DEPUTY
|| role === ClanRole.OFFICER
|| role === ClanRole.SERGEANT
|| role === ClanRole.REGULAR;
}
/** The period activity shown on the leaderboard (tuning/clans.jsonc leaderboard). */
export function totalPeriodActivityOf(clan: ClanRecord, tuning: ClanTuning): number {
const sum = clan.members.reduce((acc, m) => acc + m.curActivity, 0);
return Math.min(tuning.leaderboard.maxActivity, Math.round(sum * tuning.leaderboard.activityMultiplier));
}
export interface ClanStats {
readonly dr_era5_arc: number;
readonly dr_era5_hist: number;
readonly dr_era5_sim: number;
readonly akills_arc: number;
readonly akills_hist: number;
readonly akills_sim: number;
readonly gkills_arc: number;
readonly gkills_hist: number;
readonly gkills_sim: number;
readonly deaths_arc: number;
readonly deaths_hist: number;
readonly deaths_sim: number;
readonly ftime_arc: number;
readonly ftime_hist: number;
readonly ftime_sim: number;
}
export interface ClanActivityPeriodEntry {
readonly day: number;
readonly activity: number;
readonly exp: number;
}
export interface ClanMemberRecord {
readonly uid: string;
readonly nick: string;
readonly role: number;
readonly joinDateSec: number;
readonly isNpc?: boolean;
readonly npcTitle?: string;
readonly npcPilotIcon?: string;
readonly npcFrame?: string;
readonly npcShowcaseUnit?: string;
readonly curActivity: number;
readonly totalActivity: number;
readonly earnedSquadronExp: number;
readonly ratingArc: number;
readonly ratingHist: number;
readonly ratingSim: number;
readonly periods: readonly ClanActivityPeriodEntry[];
}
export interface ClanCandidateRecord {
readonly uid: string;
readonly nick: string;
readonly comment: string;
readonly dateSec: number;
}
export interface ClanBlacklistEntry {
readonly uid: string;
readonly nick: string;
readonly initiatorUid: string;
readonly initiatorNick: string;
readonly comments: string;
readonly dateSec: number;
}
export interface ClanLogEntry {
readonly id: number;
readonly ev: 'create' | 'info' | 'upgrade' | 'add' | 'rem' | 'role' | 'upgrade_members' | 'reject_candidate' | 'add_to_blacklist' | 'remove_from_blacklist';
readonly timeSec: number;
readonly uId: string;
readonly uN: string;
readonly uid?: string;
readonly nick?: string;
readonly role?: string;
readonly old?: string;
readonly new?: string;
readonly name?: string;
readonly type?: string;
readonly tag?: string;
readonly desc?: string;
readonly slogan?: string;
readonly region?: string;
readonly announcement?: string;
readonly status?: string;
readonly comments?: string;
}
export interface ClanBestReward {
readonly seasonName: string;
readonly title: string;
}
export interface ClanRecord {
id: string;
name: string;
tag: string;
lastPaidTag: string;
type: ClanKind;
slogan: string;
desc: string;
announcement: string;
region: string;
status: 'open' | 'closed';
autoaccept: boolean;
mlimit: number;
mspent: number;
cdateSec: number;
changedByUid: string;
changedByNick: string;
changedTimeSec: number;
regionLastUpdatedSec: number;
stats: ClanStats;
members: ClanMemberRecord[];
candidates: ClanCandidateRecord[];
blacklist: ClanBlacklistEntry[];
logs: ClanLogEntry[];
bestRewards: ClanBestReward[];
membershipReqBlk?: BlkBlock;
}
+41
View File
@@ -0,0 +1,41 @@
/**
* Development entry point of the local server.
*
* node apps/server/src/cli.ts --game <game folder> --data <data folder> --port <n>
*
* The port must match the one the game copy was built with (packages/patcher). The launcher
* will start the service the same way. Stops on Ctrl+C.
*/
import { parseArgs } from 'node:util';
import { LOOPBACK, startServer } from './server.ts';
async function main(): Promise<number> {
const { values } = parseArgs({
options: {
game: { type: 'string' },
data: { type: 'string' },
port: { type: 'string' },
},
});
const port = Number(values.port);
if (!values.game || !values.data || !Number.isInteger(port) || port < 1 || port > 65535) {
console.error('usage: cli.ts --game <game folder> --data <data folder> --port <n>');
return 2;
}
let service;
try {
service = await startServer({ gameFolder: values.game, dataFolder: values.data, port, report: (line) => console.log(line) });
} catch (error) {
const code = (error as NodeJS.ErrnoException).code;
console.error(code === 'EADDRINUSE' ? `port ${port} is already in use; choose another port` : String(error));
return 1;
}
console.log(`local server listening on ${LOOPBACK}:${port}`);
console.log(`traffic log: ${service.logFolder}`);
const running = service;
await new Promise<void>((resolve) => process.once('SIGINT', resolve));
await running.close();
return 0;
}
process.exitCode = await main();
@@ -0,0 +1,186 @@
/**
* Per-player cloud settings persistence inside `<data>/saves/<userId>/cloud-settings/`
*. Keeping cloud settings inside each player's save directory means copying `saves/<userId>/`
* to another machine or fresh client folder carries all game options, keybinds, HUD settings,
* presets, and map preferences along automatically.
*
* When an account has no saved `GBT_GENERAL_SETTINGS.blk` yet, version 1 is seeded once with
* `hudShowFuel = 2` and `hudShowAmmo = 2` ("Always", `aces.exe` 0xf4cc1f..0xf4cc55) so the
* top-left ground/air weapon and fuel HUD indicators are visible out of the box without
* overriding any subsequent change the player makes in the in-game Options menu.
*/
import { createHash } from 'node:crypto';
import { existsSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { decodeBlk, emptyBlock, encodeBlk, ensureBlock, setParam, type BlkBlock } from '@wto/blk';
import { writeFileAtomic } from '../storage/atomic-file.ts';
/**
* The three GeneralBlk types accepted by `PlayerProfile::applyGeneralBlk` (0xf5afb0) and
* `PlayerProfile::storeGeneralBlk` (0xf5b080).
*/
export const GENERAL_BLK_TYPES = [
'GBT_GENERAL_STORAGE',
'GBT_GENERAL_SETTINGS',
'GBT_GENERAL_MACHINE_SETTINGS',
] as const;
/**
* Compression methods advertised in `cln_get_meta_blk`'s `compressionSupported`. Put `zstd`
* first so `online_storage::Context::selectCompression` (0x4665de1) selects pure Zstandard
* frames (0x3372ca0), which Node's built-in `node:zlib` unpacks directly.
*/
export const SUPPORTED_CLOUD_COMPRESSIONS = 'zstd;zlib;gzip';
const SUPPORTED_BLK_TYPE_SET: ReadonlySet<string> = new Set(GENERAL_BLK_TYPES);
const HUD_SHOW_ALWAYS = 2;
export interface ParsedGblkUpload {
readonly blkType: string;
readonly version: number;
readonly contentHash: string;
readonly container: BlkBlock;
}
interface StoredBlockMeta {
version: number;
contentHash: string;
updatedAt: string;
}
interface CloudSettingsMetaFile {
formatVersion: 1;
blocks: Record<string, StoredBlockMeta>;
}
export class CloudSettingsStore {
readonly #savesRoot: string;
constructor(dataFolder: string) {
this.#savesRoot = join(dataFolder, 'saves');
}
buildMetaBlk(userId?: string, blockName?: string): BlkBlock {
if (userId && isValidUserId(userId)) this.#ensureDefaultGeneralSettings(userId);
const meta = blockName ? emptyBlock(blockName) : emptyBlock();
setParam(meta, 'machineHash', { type: 'string', value: `hhh${userId ?? '0'}` });
setParam(meta, 'compressionSupported', { type: 'string', value: SUPPORTED_CLOUD_COMPRESSIONS });
const schema = ensureBlock(meta, '__schema');
const saved = userId && isValidUserId(userId) ? this.#loadMeta(userId).blocks : {};
const allTypes = new Set<string>([...GENERAL_BLK_TYPES, ...Object.keys(saved).filter(isSupportedGeneralBlkType)]);
for (const blkType of allTypes) {
const schemaEntry = ensureBlock(schema, blkType);
setParam(schemaEntry, 'perMachine', { type: 'bool', value: false });
const entry = saved[blkType];
if (entry && entry.version > 0) {
const typeBlock = ensureBlock(meta, blkType);
setParam(typeBlock, 'version', { type: 'int', value: entry.version });
setParam(typeBlock, 'contentHash', { type: 'string', value: entry.contentHash });
}
}
return meta;
}
loadContainer(userId: string, blkType: string): BlkBlock | undefined {
if (!isValidUserId(userId) || !isSupportedGeneralBlkType(blkType)) return undefined;
if (blkType === 'GBT_GENERAL_SETTINGS') this.#ensureDefaultGeneralSettings(userId);
const blkPath = this.#blkPath(userId, blkType);
if (!existsSync(blkPath)) return undefined;
try {
return decodeBlk(readFileSync(blkPath));
} catch {
return undefined;
}
}
saveUpload(userId: string, upload: ParsedGblkUpload): boolean {
if (!isValidUserId(userId) || !isSupportedGeneralBlkType(upload.blkType)) return false;
const meta = this.#loadMeta(userId);
const nextVersion = Math.max(1, Math.trunc(upload.version));
setParam(upload.container, 'version', { type: 'int', value: nextVersion });
writeFileAtomic(this.#blkPath(userId, upload.blkType), encodeBlk(upload.container));
meta.blocks[upload.blkType] = {
version: nextVersion,
contentHash: upload.contentHash,
updatedAt: new Date().toISOString(),
};
writeFileAtomic(this.#metaPath(userId), JSON.stringify(meta, null, 2));
return true;
}
saveBulkUploads(userId: string, uploads: ReadonlyArray<ParsedGblkUpload>): number {
let savedCount = 0;
for (const upload of uploads) {
if (this.saveUpload(userId, upload)) savedCount += 1;
}
return savedCount;
}
#ensureDefaultGeneralSettings(userId: string): void {
const blkPath = this.#blkPath(userId, 'GBT_GENERAL_SETTINGS');
if (existsSync(blkPath)) return;
const { container, contentHash } = buildDefaultGeneralSettings();
this.saveUpload(userId, {
blkType: 'GBT_GENERAL_SETTINGS',
version: 1,
contentHash,
container,
});
}
#loadMeta(userId: string): CloudSettingsMetaFile {
const metaPath = this.#metaPath(userId);
if (!existsSync(metaPath)) return { formatVersion: 1, blocks: {} };
try {
const parsed = JSON.parse(readFileSync(metaPath, 'utf8')) as Partial<CloudSettingsMetaFile>;
return {
formatVersion: 1,
blocks: parsed.blocks && typeof parsed.blocks === 'object' ? { ...parsed.blocks } : {},
};
} catch {
return { formatVersion: 1, blocks: {} };
}
}
#folderOf(userId: string): string {
return join(this.#savesRoot, userId, 'cloud-settings');
}
#metaPath(userId: string): string {
return join(this.#folderOf(userId), 'meta.json');
}
#blkPath(userId: string, blkType: string): string {
return join(this.#folderOf(userId), `${blkType}.blk`);
}
}
function buildDefaultGeneralSettings(): { readonly container: BlkBlock; readonly contentHash: string } {
const content = emptyBlock('content');
const profile = ensureBlock(content, 'profile');
const settings = ensureBlock(profile, 'settings');
setParam(settings, 'hudShowFuel', { type: 'int', value: HUD_SHOW_ALWAYS });
setParam(settings, 'hudShowAmmo', { type: 'int', value: HUD_SHOW_ALWAYS });
const hashRoot = emptyBlock();
hashRoot.params.push(...content.params);
hashRoot.blocks.push(...content.blocks);
const contentHash = createHash('md5').update(encodeBlk(hashRoot)).digest('hex');
const container = emptyBlock();
setParam(container, 'version', { type: 'int', value: 1 });
container.blocks.push(content);
return { container, contentHash };
}
function isValidUserId(userId: string): boolean {
return /^\d+$/.test(userId);
}
export function isSupportedGeneralBlkType(blkType: string): boolean {
return SUPPORTED_BLK_TYPE_SET.has(blkType);
}
+130
View File
@@ -0,0 +1,130 @@
/**
* Crew skill upgrades, skill point packs and specializations:
*
* cln_upgrade_crew raise skills: <page>{ <skill>:i=levels to add } id:i
* cost = sum of the per-level costs of the new levels
* (crew_skills.blk skill_level_exp), paid in skill points
* cln_purchase_skill_points id:i pack:t: warpoints.blk crewSkillPointsCost, golden eagles
* cln_specialize_crew id:i aircraft:t: one step up for a trained vehicle,
* expert (wpcost.blk train2Cost, silver lions) then
* ace (train3Cost_gold discounted by expert_to_ace_cost_reduce)
*/
import type { BlkBlock } from '@wto/blk';
import type { AceDiscountStage, CrewSkillData, CrewTrainingPrices, SkillFacts, SkillPointPack } from '../game-data/datasets/crew-skills.ts';
import { canAfford, pay, type Price } from '../profile/profile-currency.ts';
import {
addSkillPoints,
expertToAceRp,
isTrainedFor,
setSkillLevel,
setSpecialization,
skillLevel,
skillPoints,
specializationOf,
} from '../profile/profile-crew-skills.ts';
import { crewOf } from '../profile/profile-crews.ts';
import { ACCEPTED, refused, type RuleOutcome } from '../research/rule-outcome.ts';
const ACE = 2;
export class CrewSkillCatalogue {
readonly #skills = new Map<string, SkillFacts>();
readonly #packs: ReadonlyMap<string, SkillPointPack>;
readonly #training: ReadonlyMap<string, CrewTrainingPrices>;
readonly #aceDiscountStages: readonly AceDiscountStage[];
constructor(data: CrewSkillData) {
for (const page of data.pages) for (const skill of page.skills) this.#skills.set(`${page.name}/${skill.name}`, skill);
this.#packs = new Map(data.packs.map((pack) => [pack.name, pack]));
this.#training = new Map(data.training.map((prices) => [prices.vehicle, prices]));
this.#aceDiscountStages = data.aceDiscountStages;
}
skill(page: string, skill: string): SkillFacts | undefined {
return this.#skills.get(`${page}/${skill}`);
}
pack(name: string): SkillPointPack | undefined {
return this.#packs.get(name);
}
packs(): Iterable<SkillPointPack> {
return this.#packs.values();
}
training(vehicle: string): CrewTrainingPrices | undefined {
return this.#training.get(vehicle);
}
/**
* The price the client shows (wp_get_specialization_cost_gold -> aces.exe 2.61.0.37 0x9165f0):
* train3Cost_gold less the discount of the last expert_to_ace_cost_reduce stage whose percent
* the crew's RP with the vehicle has reached. A crew that reaches train3Cost_exp becomes ace
* without buying (battle/battle-rp-investment.ts).
*/
aceGoldenEaglesPrice(vehicle: string, earnedAceRp: number): number {
const prices = this.#training.get(vehicle);
if (!prices) return 0;
const baseGold = Math.max(0, prices.aceGoldenEagles);
const targetRp = prices.aceResearchPoints;
if (baseGold === 0 || targetRp <= 0 || earnedAceRp <= 0) return baseGold;
const progressPercent = Math.floor((earnedAceRp * 100) / targetRp);
let discount = 0;
for (const stage of this.#aceDiscountStages) {
if (progressPercent >= stage.percent && stage.discount > discount) discount = stage.discount;
}
return Math.max(0, baseGold - Math.floor((baseGold * discount) / 100));
}
}
export interface SkillRaise {
readonly page: string;
readonly skill: string;
readonly levels: number;
}
export function upgradeCrewSkills(profile: BlkBlock, catalogue: CrewSkillCatalogue, crewId: number, raises: readonly SkillRaise[]): RuleOutcome {
const crew = crewOf(profile, crewId);
if (!crew || raises.length === 0) return refused('BAD_PARAMS');
let cost = 0;
const changes: { raise: SkillRaise; level: number }[] = [];
for (const raise of raises) {
const facts = catalogue.skill(raise.page, raise.skill);
if (!facts || raise.levels < 1) return refused('BAD_PARAMS');
const current = skillLevel(crew, raise.page, raise.skill);
const level = current + raise.levels;
if (level > facts.levelCosts.length) return refused('NOT_AVAILABLE');
for (let next = current + 1; next <= level; next++) cost += facts.levelCosts[next - 1] ?? 0;
changes.push({ raise, level });
}
if (cost > skillPoints(crew)) return refused('NOT_ENOUGH_SKILL_POINTS');
for (const { raise, level } of changes) setSkillLevel(crew, raise.page, raise.skill, level);
addSkillPoints(crew, -cost);
return ACCEPTED;
}
export function buySkillPoints(profile: BlkBlock, catalogue: CrewSkillCatalogue, crewId: number, packName: string): RuleOutcome {
const crew = crewOf(profile, crewId);
const pack = catalogue.pack(packName);
if (!crew || !pack) return refused('BAD_PARAMS');
const price: Price = { silverLions: 0, goldenEagles: pack.goldenEagles };
if (!canAfford(profile, price)) return refused('NOT_ENOUGH_MONEY');
pay(profile, price);
addSkillPoints(crew, pack.points);
return ACCEPTED;
}
export function specializeCrew(profile: BlkBlock, catalogue: CrewSkillCatalogue, crewId: number, vehicle: string): RuleOutcome {
const crew = crewOf(profile, crewId);
const prices = catalogue.training(vehicle);
if (!crew || !prices || !isTrainedFor(crew, vehicle)) return refused('BAD_PARAMS');
const spec = specializationOf(crew, vehicle);
if (spec >= ACE) return refused('NOT_AVAILABLE');
const price: Price = spec === 0
? { silverLions: prices.expert, goldenEagles: 0 }
: { silverLions: 0, goldenEagles: catalogue.aceGoldenEaglesPrice(vehicle, expertToAceRp(crew, vehicle)) };
if (!canAfford(profile, price)) return refused('NOT_ENOUGH_MONEY');
pay(profile, price);
setSpecialization(crew, vehicle, spec + 1);
return ACCEPTED;
}
+25
View File
@@ -0,0 +1,25 @@
/**
* Crew training fee: putting a vehicle into a crew that is not trained
* for it yet costs the vehicle's wpcost.blk trainCost in silver lions (scripts crew/crew.nut
* getCrewTrainCost; reserve vehicles cost 0). Charged by cln_train_aircraft and
* cln_bulk_train_aircraft for every new crew/vehicle pair.
*/
import type { BlkBlock } from '@wto/blk';
import type { Price } from '../profile/profile-currency.ts';
import { isTrainedFor } from '../profile/profile-crew-skills.ts';
import { crewOf } from '../profile/profile-crews.ts';
import type { CrewSlotAssignment } from '../profile/crew-slots.ts';
import type { CrewSkillCatalogue } from './crew-skill-rules.ts';
export function trainingFee(profile: BlkBlock, catalogue: CrewSkillCatalogue, assignments: readonly CrewSlotAssignment[]): Price {
const counted = new Set<string>();
let silverLions = 0;
for (const { crewId, vehicle } of assignments) {
const crew = crewOf(profile, crewId);
const key = `${crewId}/${vehicle}`;
if (vehicle === '' || !crew || isTrainedFor(crew, vehicle) || counted.has(key)) continue;
counted.add(key);
silverLions += catalogue.training(vehicle)?.training ?? 0;
}
return { silverLions, goldenEagles: 0 };
}
+48
View File
@@ -0,0 +1,48 @@
/**
* Buying decorations: cln_buy_resource with name:t, type:t (skin, decal,
* attachable), unitName:t, cost:i, costGold:i (scripts customization/decoratorAcquire.nut).
* A skin's key is "<unitName>/<name>". The decoration must be for sale (a positive price in
* config/skins.blk, decals.blk or attachable.blk), not owned yet, the offered price must match;
* it then goes into resourcesInfo.
*/
import type { BlkBlock } from '@wto/blk';
import type { DecorKind, DecorPrice } from '../game-data/datasets/decor-catalogue.ts';
import { canAfford, pay, type Price } from '../profile/profile-currency.ts';
import { addResource, ownsResource } from '../profile/profile-resources.ts';
import { ACCEPTED, refused, type RuleOutcome } from '../research/rule-outcome.ts';
export class DecorShop {
readonly #prices: ReadonlyMap<string, DecorPrice>;
constructor(prices: readonly DecorPrice[]) {
this.#prices = new Map(prices.map((price) => [`${price.kind}:${price.key}`, price]));
}
all(): Iterable<DecorPrice> {
return this.#prices.values();
}
price(kind: DecorKind, key: string): DecorPrice | undefined {
return this.#prices.get(`${kind}:${key}`);
}
}
export function decorKey(kind: DecorKind, name: string, vehicle: string): string {
return kind === 'skin' ? `${vehicle}/${name}` : name;
}
export function isDecorKind(type: string): type is DecorKind {
return type === 'skin' || type === 'decal' || type === 'attachable';
}
export function buyDecoration(profile: BlkBlock, shop: DecorShop, kind: DecorKind, key: string, offered: Price): RuleOutcome {
const forSale = shop.price(kind, key);
if (!forSale) return refused('NOT_AVAILABLE');
if (ownsResource(profile, key)) return refused('NOT_AVAILABLE');
const price: Price = { silverLions: forSale.silverLions, goldenEagles: forSale.goldenEagles };
if (price.silverLions !== offered.silverLions || price.goldenEagles !== offered.goldenEagles) return refused('PRICE_CHANGED');
if (!canAfford(profile, price)) return refused('NOT_ENOUGH_MONEY');
pay(profile, price);
addResource(profile, key, price);
return ACCEPTED;
}
@@ -0,0 +1,38 @@
/**
* Downloadable content (dldata): there is no CDN offline, so the index list and every file on
* the dldata hosts are answered with 404, each with a note in the traffic log.
*
* Where the client gets its decals instead (aces.exe 2.61.0.37; packages/patcher/src/decals/):
* - No player decal source: char.vromfs.bin holds dldata/downloadable_skins.blk and
* dldata/downloadable_decals.blk, the client loads them at init (0xd3bc40 -> 0xd3cc60) and
* never asks for dldata_s.info.
* - Player decal source: the player's web cache folder is copied to <game>/cache/content; the
* client asks for dldata_s.info (webdlcontent::init 0xd3eb40, "%s/dldata_s.info"), and on
* failure reads its cached copy ("will fallback local copy"), whose indexes are then in the
* folder. Decal textures the cache lacks would be fetched from the dldata hosts
* (network.blk skinsDecalsCDN) and are not available.
* The client does not download the indexes themselves (0xd3e710 only looks in the cache
* folder), so serving them here would have no effect.
*/
import type { Service, ServiceRequest, ServiceResponse } from '../transport/exchange.ts';
const INFO_HOST = /^public-configs[a-z0-9-]*\.(warthunder\.com|cdn\.gaijin\.net)$/;
const INFO_PATH = /^\/[a-z0-9_-]+\/dldata_s\.info$/;
const CONTENT_HOST = /^dldata[a-z0-9-]*\.(warthunder\.com|cdn\.gaijin\.net)$/;
export class DownloadableContentService implements Service {
readonly name = 'dldata';
accepts(request: ServiceRequest): boolean {
const host = request.originalHost;
if (host === undefined || request.method !== 'GET') return false;
return (INFO_HOST.test(host) && INFO_PATH.test(request.path)) || CONTENT_HOST.test(host);
}
handle(request: ServiceRequest): ServiceResponse {
const summary = INFO_PATH.test(request.path)
? 'dldata_s.info: no CDN offline, the client falls back to its cached copy'
: `${request.path}: no CDN offline`;
return { status: 404, body: 'not available offline', logNotes: { summary } };
}
}
@@ -0,0 +1,138 @@
/**
* Dataset: the battle reward factors the game files carry (implementation notes "3d").
*
* char.vromfs.bin config/wpcost.blk, per vehicle:
* unitClass, expMul, rewardMul<Arcade|Historical|Simulation>, battleTimeAward<...>, timedAward<...>
* char.vromfs.bin config/warpoints.blk:
* aKill (Silver Lions of a reference kill), aiKillK, winK, defeatK, wpMultiplier (premium account),
* units{} (Silver Lions factor by the destroyed unit's expClass)
* char.vromfs.bin config/rank.blk:
* xpMultiplier (premium account), goldPlaneExpMul (premium vehicle / talisman),
* expForVictoryVersusPerSec, expForPlayingVersusPerSec, crew_exp_mul_<difficulty>, denominateFreeExp,
* units{} (Research Points factor by the destroyed unit's expClass),
* ExpSkillBonus{<economic name>{BonusLevel<N>{bonusPercent, kills|damage}}}
*
* The stock client shows the same factors on the vehicle card (gui.vromfs.bin scripts/airinfo.nut,
* reward formula: expMul x (1 + premium + talisman), rewardMul x (1 + premium)).
*/
import type { BlkBlock } from '@wto/blk';
import { blockAt, numberField, stringField } from './blk-fields.ts';
import type { Dataset } from './dataset.ts';
export type EconomyDifficulty = 'arcade' | 'historical' | 'simulation';
const DIFFICULTY_SUFFIX: Readonly<Record<EconomyDifficulty, string>> = {
arcade: 'Arcade',
historical: 'Historical',
simulation: 'Simulation',
};
export interface VehicleEconomy {
readonly unitClass: string;
readonly expMul: number;
readonly rewardMul: Readonly<Record<EconomyDifficulty, number>>;
readonly battleTimeAward: Readonly<Record<EconomyDifficulty, number>>;
readonly timedAward: Readonly<Record<EconomyDifficulty, number>>;
}
export interface SkillBonusLevel {
readonly level: number;
readonly bonusPercent: number;
/** Kills needed, or naval damage needed when `metric` is "damage". */
readonly threshold: number;
readonly metric: 'kills' | 'damage';
}
export interface BattleEconomyData {
readonly vehicles: Readonly<Record<string, VehicleEconomy>>;
readonly killSilverLions: number;
readonly aiKillK: number;
readonly winK: number;
readonly defeatK: number;
readonly premiumSilverLionsMul: number;
readonly premiumResearchMul: number;
readonly talismanResearchMul: number;
readonly silverLionsClassFactors: Readonly<Record<string, number>>;
readonly researchClassFactors: Readonly<Record<string, number>>;
readonly researchPerSecondWin: number;
readonly researchPerSecondPlaying: number;
readonly crewExpMul: Readonly<Record<EconomyDifficulty, number>>;
readonly freeResearchDivisor: number;
readonly skillBonus: Readonly<Record<string, readonly SkillBonusLevel[]>>;
}
export const battleEconomy: Dataset<BattleEconomyData> = {
id: 'battle-economy',
version: 1,
extract: (source) => {
const wpcost = source.readBlk('char.vromfs.bin', 'config/wpcost.blk');
const warpoints = source.readBlk('char.vromfs.bin', 'config/warpoints.blk');
const rank = source.readBlk('char.vromfs.bin', 'config/rank.blk');
const required = (block: BlkBlock, file: string, name: string): number => {
const value = numberField(block, name);
if (value === undefined) throw new Error(`${file}: ${name} is missing`);
return value;
};
return {
vehicles: Object.fromEntries(wpcost.blocks.map((vehicle) => [vehicle.name, vehicleEconomy(vehicle)])),
killSilverLions: required(warpoints, 'warpoints.blk', 'aKill'),
aiKillK: required(warpoints, 'warpoints.blk', 'aiKillK'),
winK: required(warpoints, 'warpoints.blk', 'winK'),
defeatK: required(warpoints, 'warpoints.blk', 'defeatK'),
premiumSilverLionsMul: required(warpoints, 'warpoints.blk', 'wpMultiplier'),
premiumResearchMul: required(rank, 'rank.blk', 'xpMultiplier'),
talismanResearchMul: required(rank, 'rank.blk', 'goldPlaneExpMul'),
silverLionsClassFactors: numberMap(blockAt(warpoints, 'units')),
researchClassFactors: numberMap(blockAt(rank, 'units')),
researchPerSecondWin: required(rank, 'rank.blk', 'expForVictoryVersusPerSec'),
researchPerSecondPlaying: required(rank, 'rank.blk', 'expForPlayingVersusPerSec'),
crewExpMul: {
arcade: required(rank, 'rank.blk', 'crew_exp_mul_arcade'),
historical: required(rank, 'rank.blk', 'crew_exp_mul_historical'),
simulation: required(rank, 'rank.blk', 'crew_exp_mul_simulation'),
},
freeResearchDivisor: required(rank, 'rank.blk', 'denominateFreeExp'),
skillBonus: skillBonusTable(blockAt(rank, 'ExpSkillBonus')),
};
},
};
function vehicleEconomy(vehicle: BlkBlock): VehicleEconomy {
const perDifficulty = (prefix: string, fallback: number): Record<EconomyDifficulty, number> => ({
arcade: numberField(vehicle, `${prefix}${DIFFICULTY_SUFFIX.arcade}`) ?? fallback,
historical: numberField(vehicle, `${prefix}${DIFFICULTY_SUFFIX.historical}`) ?? fallback,
simulation: numberField(vehicle, `${prefix}${DIFFICULTY_SUFFIX.simulation}`) ?? fallback,
});
return {
unitClass: stringField(vehicle, 'unitClass') ?? '',
expMul: numberField(vehicle, 'expMul') ?? 1,
// The client reads a missing rewardMul as 1.0 (scripts/unit/unit.nut getWpRewardMulList).
rewardMul: perDifficulty('rewardMul', 1),
battleTimeAward: perDifficulty('battleTimeAward', 0),
timedAward: perDifficulty('timedAward', 0),
};
}
function numberMap(block: BlkBlock | undefined): Record<string, number> {
return Object.fromEntries((block?.params ?? []).flatMap((param) =>
param.value.type === 'real' || param.value.type === 'int' ? [[param.name, param.value.value]] : []));
}
function skillBonusTable(block: BlkBlock | undefined): Record<string, SkillBonusLevel[]> {
return Object.fromEntries((block?.blocks ?? []).map((event) => [
event.name,
event.blocks.flatMap((level): SkillBonusLevel[] => {
const index = /^BonusLevel(\d+)$/.exec(level.name)?.[1];
const bonusPercent = numberField(level, 'bonusPercent');
const kills = numberField(level, 'kills');
const damage = numberField(level, 'damage');
if (index === undefined || bonusPercent === undefined || (kills === undefined && damage === undefined)) return [];
return [{
level: Number(index),
bonusPercent,
threshold: kills ?? damage ?? 0,
metric: kills !== undefined ? 'kills' : 'damage',
}];
}).sort((a, b) => a.level - b.level),
]));
}
@@ -0,0 +1,195 @@
/**
* Dataset: the extra vehicles a battle adds to a player's lineup, as the game files list them.
*
* aces.vromfs.bin config/gameplay.blk
* missionSupportPlane{ <event name>{ UnitPreset{ killStreakTagName:t rankRange:ip2 spawnScoreToShow:i
* spawnScoreToUse:i <country>{ unitName:t weapon:t } } } }
* Killstreak aircraft (the nuclear carrier) per session rank bracket, one per country.
* RandomSpawnUnits{ <event economic name>{ <country>{ <group>{ minPlayerMRank:i
* maxDiffBetweenTopUnitAndSessionRank:i mRanksCount:i <unit>{ addModification:t addWeapon:t
* forceWeapon:t } } } } }
* The random vehicle groups (dice slots: random tank and SPAA in ground battles, random fighter
* and bomber in naval battles). The stock client reads the same block for forced weapons
* (scripts/unit/randomunitsforceweapon.nut).
* char.vromfs.bin config/wpcost.blk
* ucav_*_killstreak{ country:t ... }
* The strike UCAVs, one per country.
* char.vromfs.bin config/warpoints.blk respawn_points / TankHistorical
* Starting points and unit cost parameters for Ground Realistic Battles.
*/
import type { BlkBlock } from '@wto/blk';
import { findParam } from '@wto/blk';
import { blockAt, numberField, stringField, stringList } from './blk-fields.ts';
import type { Dataset } from './dataset.ts';
export interface SupportPlaneUnit {
readonly unitName: string;
readonly weapon: string;
}
export interface SupportPlanePreset {
readonly killStreakTag: string;
/** Session rank bracket (`rankRange`, inclusive). */
readonly minMrank: number;
readonly maxMrank: number;
readonly spawnScoreToShow: number;
readonly spawnScoreToUse: number;
/** By country. */
readonly units: Readonly<Record<string, SupportPlaneUnit>>;
}
export interface StrikeUcav {
readonly country: string;
readonly unitName: string;
}
export interface RandomSpawnUnit {
readonly unitName: string;
readonly addModifications: readonly string[];
readonly forceWeapon?: string;
}
export interface RandomSpawnGroup {
/** `tank`, `spaa`, `fighter`, `bomber`: the key of `random_units` and of gui.blk `randomSpawnUnitPresets`. */
readonly name: string;
readonly minPlayerMrank: number;
readonly maxDiffBetweenTopUnitAndSessionRank: number;
readonly mranksCount: number;
readonly units: readonly RandomSpawnUnit[];
}
interface SpawnScoreParameterSet {
readonly parameters: Readonly<Record<string, number>>;
readonly classCosts: Readonly<Record<string, number>>;
}
export interface SpawnScoreRules {
readonly common: Readonly<Record<string, number>>;
readonly tankHistorical: SpawnScoreParameterSet;
readonly overrides: ReadonlyArray<SpawnScoreParameterSet & {
readonly minMrank: number;
readonly maxMrank: number;
}>;
}
export interface BattleSpawnRulesData {
/** By event name (`missionSupportPlane` keys are game mode names). */
readonly supportPlanes: Readonly<Record<string, readonly SupportPlanePreset[]>>;
readonly strikeUcavs: readonly StrikeUcav[];
readonly spawnScore: SpawnScoreRules;
/** By event economic name, then country. */
readonly randomSpawnUnits: Readonly<Record<string, Readonly<Record<string, readonly RandomSpawnGroup[]>>>>;
}
const STRIKE_UCAV_PATTERN = /^ucav_.*_killstreak$/;
export const battleSpawnRules: Dataset<BattleSpawnRulesData> = {
id: 'battle-spawn-rules',
version: 3,
extract: (source) => {
const gameplay = source.readBlk('aces.vromfs.bin', 'config/gameplay.blk');
const wpcost = source.readBlk('char.vromfs.bin', 'config/wpcost.blk');
return {
supportPlanes: extractSupportPlanes(blockAt(gameplay, 'missionSupportPlane')),
strikeUcavs: extractStrikeUcavs(wpcost.blocks),
spawnScore: extractSpawnScore(blockAt(source.readBlk('char.vromfs.bin', 'config/warpoints.blk'), 'respawn_points')),
randomSpawnUnits: extractRandomSpawnUnits(blockAt(gameplay, 'RandomSpawnUnits')),
};
},
};
function extractSpawnScore(root: BlkBlock | undefined): SpawnScoreRules {
const tankHistorical = blockAt(root, 'TankHistorical');
return {
common: numericParams(root),
tankHistorical: spawnScoreParams(tankHistorical),
overrides: (blockAt(tankHistorical, 'override_params_by_session_rank')?.blocks ?? []).map((block) => ({
...spawnScoreParams(block),
minMrank: numberField(block, 'minMRank') ?? -1,
maxMrank: numberField(block, 'maxMRank') ?? -1,
})),
};
}
function spawnScoreParams(block: BlkBlock | undefined): SpawnScoreParameterSet {
return {
parameters: numericParams(block),
classCosts: numericParams(blockAt(block, 'respawn_cost_mul_by_exp_class')),
};
}
function numericParams(block: BlkBlock | undefined): Record<string, number> {
const params = block?.params ?? [];
return Object.fromEntries(params.flatMap(({ name, value }) =>
value.type === 'int' || value.type === 'real' ? [[name, value.value]] : []));
}
function extractSupportPlanes(root: BlkBlock | undefined): Record<string, SupportPlanePreset[]> {
const byEvent: Record<string, SupportPlanePreset[]> = {};
for (const eventBlk of root?.blocks ?? []) {
const presets: SupportPlanePreset[] = [];
for (const preset of eventBlk.blocks) {
if (preset.name !== 'UnitPreset') continue;
const range = findParam(preset, 'rankRange')?.value;
const spawnScoreToUse = numberField(preset, 'spawnScoreToUse');
if (range?.type !== 'ipoint2' || spawnScoreToUse === undefined) continue;
const units: Record<string, SupportPlaneUnit> = {};
for (const countryBlk of preset.blocks) {
const unitName = stringField(countryBlk, 'unitName');
const weapon = stringField(countryBlk, 'weapon');
if (countryBlk.name.startsWith('country_') && unitName && weapon) units[countryBlk.name] = { unitName, weapon };
}
presets.push({
killStreakTag: stringField(preset, 'killStreakTagName') ?? '',
minMrank: range.value[0],
maxMrank: range.value[1],
spawnScoreToShow: numberField(preset, 'spawnScoreToShow') ?? spawnScoreToUse,
spawnScoreToUse,
units,
});
}
if (presets.length > 0) byEvent[eventBlk.name] = presets;
}
return byEvent;
}
function extractStrikeUcavs(wpcostBlocks: readonly BlkBlock[]): StrikeUcav[] {
return wpcostBlocks.flatMap((unitBlk) => {
const country = stringField(unitBlk, 'country') ?? '';
return STRIKE_UCAV_PATTERN.test(unitBlk.name) && country.startsWith('country_')
? [{ country, unitName: unitBlk.name }]
: [];
});
}
function extractRandomSpawnUnits(
root: BlkBlock | undefined,
): Record<string, Record<string, RandomSpawnGroup[]>> {
const byEvent: Record<string, Record<string, RandomSpawnGroup[]>> = {};
for (const eventBlk of root?.blocks ?? []) {
const byCountry: Record<string, RandomSpawnGroup[]> = {};
for (const countryBlk of eventBlk.blocks) {
if (!countryBlk.name.startsWith('country_')) continue;
const groups = countryBlk.blocks.flatMap((groupBlk): RandomSpawnGroup[] => {
const units = groupBlk.blocks.map((unitBlk): RandomSpawnUnit => {
const forceWeapon = stringField(unitBlk, 'forceWeapon');
return {
unitName: unitBlk.name,
addModifications: stringList(unitBlk, 'addModification'),
...(forceWeapon ? { forceWeapon } : {}),
};
});
return units.length === 0 ? [] : [{
name: groupBlk.name,
minPlayerMrank: numberField(groupBlk, 'minPlayerMRank') ?? 0,
maxDiffBetweenTopUnitAndSessionRank: numberField(groupBlk, 'maxDiffBetweenTopUnitAndSessionRank') ?? 0,
mranksCount: numberField(groupBlk, 'mRanksCount') ?? 0,
units,
}];
});
if (groups.length > 0) byCountry[countryBlk.name] = groups;
}
byEvent[eventBlk.name] = byCountry;
}
return byEvent;
}
@@ -0,0 +1,124 @@
/**
* Dataset: the battle awards ("streaks") of char.vromfs.bin config/unlocks.blk (implementation notes "3e").
*
* unlockable{ id:t type:t="streak" hidden:b isAfterFlight:b isMultiStage:b
* amount_warpoints:i|ip3 amount_exp:i|ip3 reward of a single-stage award
* wpA:p3 wpB:p3 expA:p3 expB:p3 reward terms of a multi-stage award
* stage{ param:i amount_warpoints amount_exp } first stage of a multi-stage award
* mode{ type:t <mode parameters> condition{ type:t <condition parameters> } ... }
* }
*
* Three-value parameters (p3 / ip3) are per difficulty: arcade, realistic, simulator. Hidden
* awards are kept and flagged: the stock client does not show them (scripts/unlocks
* isUnlockVisible), but wagers name some of them as win conditions (hidden_win_streak ...).
* Online the battle server evaluates these definitions; battle/battle-streaks.ts does it offline.
*/
import type { BlkBlock, BlkValue } from '@wto/blk';
import type { Dataset } from './dataset.ts';
export type StreakValue = string | number | boolean;
/** Every parameter of a block by name, repeated names in order; three-value parameters spread. */
export type StreakParams = Readonly<Record<string, readonly StreakValue[]>>;
export interface StreakCondition {
readonly type: string;
readonly params: StreakParams;
}
export interface StreakMode {
readonly type: string;
readonly params: StreakParams;
readonly conditions: readonly StreakCondition[];
}
export type PerDifficulty = readonly [number, number, number];
export interface StreakDefinition {
readonly id: string;
readonly hidden: boolean;
readonly afterFlight: boolean;
readonly multiStage: boolean;
readonly wp: PerDifficulty;
readonly exp: PerDifficulty;
readonly stage?: { readonly param: number; readonly wp: PerDifficulty; readonly exp: PerDifficulty };
readonly wpA: PerDifficulty;
readonly wpB: PerDifficulty;
readonly expA: PerDifficulty;
readonly expB: PerDifficulty;
readonly mode?: StreakMode;
}
export const battleStreaks: Dataset<readonly StreakDefinition[]> = {
id: 'battle-streaks',
version: 2,
extract: (source) => source.readBlk('char.vromfs.bin', 'config/unlocks.blk').blocks
.filter((block) => block.name === 'unlockable')
.flatMap((block): StreakDefinition[] => {
const params = paramsOf(block);
const id = params.id?.[0];
if (params.type?.[0] !== 'streak' || typeof id !== 'string') return [];
const stage = block.blocks.find((child) => child.name === 'stage');
const stageParams = stage && paramsOf(stage);
const stageParam = stageParams?.param?.[0];
const mode = block.blocks.find((child) => child.name === 'mode');
return [{
id,
hidden: params.hidden?.[0] === true,
afterFlight: params.isAfterFlight?.[0] === true,
multiStage: params.isMultiStage?.[0] === true,
wp: perDifficulty(params.amount_warpoints),
exp: perDifficulty(params.amount_exp),
...(stageParams && typeof stageParam === 'number'
? { stage: { param: stageParam, wp: perDifficulty(stageParams.amount_warpoints), exp: perDifficulty(stageParams.amount_exp) } }
: {}),
wpA: perDifficulty(params.wpA),
wpB: perDifficulty(params.wpB),
expA: perDifficulty(params.expA),
expB: perDifficulty(params.expB),
...(mode ? { mode: unlockModeOf(mode) } : {}),
}];
}),
};
/** An unlock mode block: its type, parameters and condition{} children (also used by wagers). */
export function unlockModeOf(block: BlkBlock): StreakMode {
const params = paramsOf(block);
return {
type: String(params.type?.[0] ?? ''),
params,
conditions: block.blocks.filter((child) => child.name === 'condition').map((condition) => {
const conditionParams = paramsOf(condition);
return { type: String(conditionParams.type?.[0] ?? ''), params: conditionParams };
}),
};
}
function paramsOf(block: BlkBlock): Record<string, StreakValue[]> {
const out: Record<string, StreakValue[]> = {};
for (const param of block.params) (out[param.name] ??= []).push(...valuesOf(param.value));
return out;
}
function valuesOf(value: BlkValue): StreakValue[] {
switch (value.type) {
case 'string':
case 'int':
case 'real':
case 'bool':
return [value.value];
case 'point3':
case 'ipoint3':
return [...value.value];
default:
return [];
}
}
/** An int applies to every difficulty; a three-value parameter is per difficulty; missing is 0. */
function perDifficulty(values: readonly StreakValue[] | undefined): PerDifficulty {
const numbers = (values ?? []).filter((value): value is number => typeof value === 'number');
if (numbers.length >= 3) return [numbers[0]!, numbers[1]!, numbers[2]!];
const single = numbers[0] ?? 0;
return [single, single, single];
}
@@ -0,0 +1,36 @@
/** Typed reads of BLK parameters for dataset extraction; a missing or differently typed parameter reads as undefined. */
import { findBlock, findParam, type BlkBlock } from '@wto/blk';
export function stringField(block: BlkBlock | undefined, name: string): string | undefined {
const value = block && findParam(block, name)?.value;
return value?.type === 'string' ? value.value : undefined;
}
export function numberField(block: BlkBlock | undefined, name: string): number | undefined {
const value = block && findParam(block, name)?.value;
return value?.type === 'int' || value?.type === 'real' ? value.value : undefined;
}
export function boolField(block: BlkBlock | undefined, name: string): boolean | undefined {
const value = block && findParam(block, name)?.value;
return value?.type === 'bool' ? value.value : undefined;
}
/** Every string value of a repeated parameter, in order. */
export function stringList(block: BlkBlock | undefined, name: string): string[] {
if (!block) return [];
return block.params.flatMap((param) => param.name === name && param.value.type === 'string' ? [param.value.value] : []);
}
/** Every bool parameter of a block, by name. */
export function boolFields(block: BlkBlock | undefined): Record<string, boolean> {
if (!block) return {};
return Object.fromEntries(block.params.flatMap((param) => param.value.type === 'bool' ? [[param.name, param.value.value]] : []));
}
/** Follow a path of first-found sub-blocks. */
export function blockAt(block: BlkBlock | undefined, ...names: string[]): BlkBlock | undefined {
let current = block;
for (const name of names) current = current && findBlock(current, name);
return current;
}
@@ -0,0 +1,75 @@
/**
* Dataset: squadron creation, edit, member-limit upgrade, battalion-to-normal upgrade prices,
* and free tag decorators from char.vromfs.bin config/warpoints.blk (implementation notes;
* aces.exe 0x906fe0..0x907070; scripts/clans/clanType.nut).
*/
import { findBlock, type BlkBlock } from '@wto/blk';
import { numberField } from './blk-fields.ts';
import type { Dataset } from './dataset.ts';
const WARPOINTS = 'config/warpoints.blk';
export interface ClanEconomy {
readonly normalCreateGold: number;
readonly normalCreateSilver: number;
readonly normalPrimaryEditGold: number;
readonly normalPrimaryEditSilver: number;
readonly normalSecondaryEditGold: number;
readonly normalSecondaryEditSilver: number;
readonly battalionCreateGold: number;
readonly battalionCreateSilver: number;
readonly battalionPrimaryEditGold: number;
readonly battalionPrimaryEditSilver: number;
readonly battalionSecondaryEditGold: number;
readonly battalionSecondaryEditSilver: number;
readonly battalionMembersUpgradeGold: number;
readonly battalionMembersUpgradeStep: number;
readonly battalionMembersUpgradeLimit: number;
readonly upgradeBattalionToNormalGold: number;
readonly upgradeBattalionToNormalSilver: number;
readonly normalFreeDecorators: readonly string[];
readonly battalionFreeDecorators: readonly string[];
}
export const clanEconomy: Dataset<ClanEconomy> = {
id: 'clan-economy',
version: 3,
extract: (source) => {
const wp = source.readBlk('char.vromfs.bin', WARPOINTS);
const required = (key: string): number => {
const value = numberField(wp, key);
if (value === undefined) throw new Error(`${WARPOINTS} has no ${key}; this game build differs from the verified ones`);
return value;
};
// scripts/clans/clanType.nut reads these costs as `blk?[name] ?? 0`; 2.61.0.37 has no
// clanCreateWPCost, costWPPrimaryInfo or costWPSecondaryInfo, so they are 0 there too.
const clientDefaultZero = (key: string): number => numberField(wp, key) ?? 0;
return {
normalCreateGold: required('clanCreateGoldCost'),
normalCreateSilver: clientDefaultZero('clanCreateWPCost'),
normalPrimaryEditGold: clientDefaultZero('costGoldPrimaryInfo'),
normalPrimaryEditSilver: clientDefaultZero('costWPPrimaryInfo'),
normalSecondaryEditGold: required('costGoldSecondaryInfo'),
normalSecondaryEditSilver: clientDefaultZero('costWPSecondaryInfo'),
battalionCreateGold: required('battalionCreateGoldCost'),
battalionCreateSilver: clientDefaultZero('battalionCreateWPCost'),
battalionPrimaryEditGold: clientDefaultZero('battalionCostGoldPrimaryInfo'),
battalionPrimaryEditSilver: required('battalionCostWPPrimaryInfo'),
battalionSecondaryEditGold: required('battalionCostGoldSecondaryInfo'),
battalionSecondaryEditSilver: required('battalionCostWPSecondaryInfo'),
battalionMembersUpgradeGold: required('battalionMembersUpgradeCost'),
battalionMembersUpgradeStep: required('battalionMembersUpgradeStep'),
battalionMembersUpgradeLimit: required('battalionMembersUpgradeLimit'),
upgradeBattalionToNormalGold: required('clanUpgradeCostGoldBattalionToNormal'),
upgradeBattalionToNormalSilver: clientDefaultZero('clanUpgradeCostWPBattalionToNormal'),
normalFreeDecorators: readDecorList(wp, 'clanTagDecorators'),
battalionFreeDecorators: readDecorList(wp, 'battalionTagDecorators'),
};
},
};
function readDecorList(wp: BlkBlock, blockName: string): readonly string[] {
const block = findBlock(wp, blockName);
if (!block) throw new Error(`${WARPOINTS} has no ${blockName}; this game build differs from the verified ones`);
return block.params.flatMap((p) => (p.name === 'decor' && p.value.type === 'string' ? [p.value.value] : []));
}
@@ -0,0 +1,96 @@
/**
* Dataset: crew skills, skill point packs, per-vehicle crew training prices, and
* Expert-to-Ace Golden Eagles discount stages.
*
* char.vromfs.bin config/crew_skills.blk
* crew_skills{ <page>{ type:t <skill>{ skill_level_exp{ level1:i ... levelN:i } } } }
* levelN is the skill point cost of level N (the scripts add them up into costTbl).
* char.vromfs.bin config/warpoints.blk
* crewSkillPointsCost{ <pack>{ costGold:i crewExp:i } }
* expert_to_ace_cost_reduce{ stage{ percent:i discount:i } }
* char.vromfs.bin config/wpcost.blk, per vehicle
* trainCost:i (training a crew, silver lions), train2Cost:i (expert, silver lions),
* train3Cost_gold:i (ace, golden eagles), train3Cost_exp:i (free ace RP threshold)
*/
import type { BlkBlock } from '@wto/blk';
import { findBlock } from '@wto/blk';
import { numberField, stringField } from './blk-fields.ts';
import type { Dataset } from './dataset.ts';
export interface SkillFacts {
readonly name: string;
/** Cost of each level, index 0 = level 1; the length is the maximum level. */
readonly levelCosts: readonly number[];
}
export interface SkillPage {
readonly name: string;
readonly type: string;
readonly skills: readonly SkillFacts[];
}
export interface SkillPointPack {
readonly name: string;
readonly goldenEagles: number;
readonly points: number;
}
export interface AceDiscountStage {
readonly percent: number;
readonly discount: number;
}
export interface CrewTrainingPrices {
readonly vehicle: string;
readonly training: number;
readonly expert: number;
readonly aceGoldenEagles: number;
readonly aceResearchPoints: number;
}
export interface CrewSkillData {
readonly pages: readonly SkillPage[];
readonly packs: readonly SkillPointPack[];
readonly aceDiscountStages: readonly AceDiscountStage[];
readonly training: readonly CrewTrainingPrices[];
}
export const crewSkillData: Dataset<CrewSkillData> = {
id: 'crew-skills',
version: 2,
extract: (source) => {
const skills = findBlock(source.readBlk('char.vromfs.bin', 'config/crew_skills.blk'), 'crew_skills');
const warpoints = source.readBlk('char.vromfs.bin', 'config/warpoints.blk');
const packs = findBlock(warpoints, 'crewSkillPointsCost');
const aceReduce = findBlock(warpoints, 'expert_to_ace_cost_reduce');
return {
pages: (skills?.blocks ?? []).map(pageOf),
packs: (packs?.blocks ?? []).map((pack) => ({ name: pack.name, goldenEagles: numberField(pack, 'costGold') ?? 0, points: numberField(pack, 'crewExp') ?? 0 })),
aceDiscountStages: (aceReduce?.blocks ?? [])
.filter((stage) => stage.name === 'stage')
.map((stage) => ({ percent: numberField(stage, 'percent') ?? 0, discount: numberField(stage, 'discount') ?? 0 }))
.filter((stage) => stage.percent > 0 && stage.discount > 0)
.sort((a, b) => a.percent - b.percent),
training: source.readBlk('char.vromfs.bin', 'config/wpcost.blk').blocks.map((vehicle) => ({
vehicle: vehicle.name,
training: numberField(vehicle, 'trainCost') ?? 0,
expert: numberField(vehicle, 'train2Cost') ?? 0,
aceGoldenEagles: numberField(vehicle, 'train3Cost_gold') ?? 0,
aceResearchPoints: numberField(vehicle, 'train3Cost_exp') ?? 0,
})),
};
},
};
function pageOf(page: BlkBlock): SkillPage {
return {
name: page.name,
type: stringField(page, 'type') ?? '',
skills: page.blocks.map((skill) => {
const levels = findBlock(skill, 'skill_level_exp');
const levelCosts: number[] = [];
for (let level = 1; levels && numberField(levels, `level${level}`) !== undefined; level++) levelCosts.push(numberField(levels, `level${level}`)!);
return { name: skill.name, levelCosts };
}),
};
}
@@ -0,0 +1,163 @@
/**
* Extract datasets once and reuse the result while the game files stay the same
*:
*
* 1. every pack the dataset read has the same size and modification time as when it was
* extracted: use the cached result;
* 2. otherwise compare the SHA-1 of the files the dataset actually read (and of the file
* listings it used): all equal, the result still holds, so only the pack stamps are
* updated (the build rewrites char.vromfs.bin on every launch without touching what
* the datasets read);
* 3. otherwise extract again.
*
* Cache entries live in <data folder>/cache/datasets/<dataset id>.json.
*/
import { createHash } from 'node:crypto';
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import type { BlkBlock } from '@wto/blk';
import { writeFileAtomic } from '../../storage/atomic-file.ts';
import type { GameFiles, GamePackName, PackStamp } from '../game-files.ts';
import type { Dataset, DatasetSource } from './dataset.ts';
interface FileInput {
readonly pack: GamePackName;
readonly path: string;
readonly sha1: string;
}
interface ListingInput {
readonly pack: GamePackName;
readonly sha1: string;
}
interface CacheEntry {
readonly id: string;
readonly version: number;
readonly packs: Partial<Record<GamePackName, PackStamp>>;
readonly files: readonly FileInput[];
readonly listings: readonly ListingInput[];
readonly data: unknown;
}
export type DatasetOrigin = 'cache' | 'cache, verified by content' | 'extracted';
export class DatasetCache {
readonly #folder: string;
readonly #gameFiles: GameFiles;
readonly #report: (line: string) => void;
constructor(dataFolder: string, gameFiles: GameFiles, report: (line: string) => void) {
this.#folder = join(dataFolder, 'cache', 'datasets');
this.#gameFiles = gameFiles;
this.#report = report;
}
load<T>(dataset: Dataset<T>): T {
const entryPath = join(this.#folder, `${dataset.id}.json`);
const cached = readEntry(entryPath);
if (cached && cached.id === dataset.id && cached.version === dataset.version) {
if (this.#stampsMatch(cached)) return this.#use(dataset, cached, 'cache');
if (this.#contentMatches(cached)) {
writeEntry(entryPath, { ...cached, packs: this.#stamps(Object.keys(cached.packs) as GamePackName[]) });
return this.#use(dataset, cached, 'cache, verified by content');
}
}
const started = Date.now();
const tracked = new TrackedSource(this.#gameFiles);
const data = dataset.extract(tracked);
const entry: CacheEntry = {
id: dataset.id,
version: dataset.version,
packs: this.#stamps(tracked.packs()),
files: tracked.files(),
listings: tracked.listings(),
data,
};
writeEntry(entryPath, entry);
this.#report(`dataset ${dataset.id}: extracted in ${Date.now() - started} ms (${entry.files.length} files)`);
return data;
}
#use<T>(dataset: Dataset<T>, entry: CacheEntry, origin: DatasetOrigin): T {
this.#report(`dataset ${dataset.id}: ${origin}`);
return entry.data as T;
}
#stamps(packs: readonly GamePackName[]): Partial<Record<GamePackName, PackStamp>> {
return Object.fromEntries(packs.map((pack) => [pack, this.#gameFiles.packStamp(pack)]));
}
#stampsMatch(entry: CacheEntry): boolean {
return Object.entries(entry.packs).every(([pack, stamp]) => {
const current = this.#gameFiles.packStamp(pack as GamePackName);
return stamp !== undefined && current.size === stamp.size && current.mtimeMs === stamp.mtimeMs;
});
}
#contentMatches(entry: CacheEntry): boolean {
return entry.files.every(({ pack, path, sha1 }) => this.#gameFiles.pack(pack).fileDigest(path) === sha1)
&& entry.listings.every(({ pack, sha1 }) => listingDigest(this.#gameFiles.pack(pack).paths()) === sha1);
}
}
/** Reads through to the game files and remembers every input. */
class TrackedSource implements DatasetSource {
readonly #gameFiles: GameFiles;
readonly #files = new Map<string, FileInput>();
readonly #listings = new Map<GamePackName, ListingInput>();
constructor(gameFiles: GameFiles) {
this.#gameFiles = gameFiles;
}
readBlk(pack: GamePackName, path: string): BlkBlock {
const gamePack = this.#gameFiles.pack(pack);
const sha1 = gamePack.fileDigest(path);
if (sha1 === undefined) throw new Error(`${pack} has no file ${path}`);
this.#files.set(`${pack}/${path}`, { pack, path, sha1 });
return gamePack.readBlk(path);
}
readText(pack: GamePackName, path: string): string {
const gamePack = this.#gameFiles.pack(pack);
const sha1 = gamePack.fileDigest(path);
if (sha1 === undefined) throw new Error(`${pack} has no file ${path}`);
this.#files.set(`${pack}/${path}`, { pack, path, sha1 });
return gamePack.readText(path);
}
listFiles(pack: GamePackName): readonly string[] {
const paths = this.#gameFiles.pack(pack).paths();
this.#listings.set(pack, { pack, sha1: listingDigest(paths) });
return paths;
}
packs(): GamePackName[] {
return [...new Set([...this.#files.values(), ...this.#listings.values()].map((input) => input.pack))];
}
files(): FileInput[] {
return [...this.#files.values()];
}
listings(): ListingInput[] {
return [...this.#listings.values()];
}
}
function listingDigest(paths: readonly string[]): string {
return createHash('sha1').update(paths.join('\n')).digest('hex');
}
function readEntry(path: string): CacheEntry | undefined {
try {
return JSON.parse(readFileSync(path, 'utf8')) as CacheEntry;
} catch {
return undefined;
}
}
function writeEntry(path: string, entry: CacheEntry): void {
writeFileAtomic(path, JSON.stringify(entry));
}
@@ -0,0 +1,26 @@
/**
* A dataset: a set of static facts extracted from the player's game files (implementation notes
* 3.4). Each dataset declares what it produces and reads its inputs only through the source
* it is given, so the cache knows exactly which files the result depends on.
*
* A dataset only records what the game files say; deciding what the facts mean for a game
* rule belongs to the rules layer.
*/
import type { BlkBlock } from '@wto/blk';
import type { GamePackName } from '../game-files.ts';
export interface DatasetSource {
readBlk(pack: GamePackName, path: string): BlkBlock;
readText(pack: GamePackName, path: string): string;
/** Every file path in a pack, sorted. */
listFiles(pack: GamePackName): readonly string[];
}
export interface Dataset<T> {
/** File name of the cache entry; unique among datasets. */
readonly id: string;
/** Raise when the extraction code or the shape of the result changes: old cache entries are then ignored. */
readonly version: number;
/** The result must survive JSON.stringify / JSON.parse unchanged. */
extract(source: DatasetSource): T;
}
@@ -0,0 +1,44 @@
/**
* Dataset: the decorations that can be bought.
*
* char.vromfs.bin config/skins.blk, config/decals.blk, config/attachable.blk: one block per
* decoration, named like the client keys it (skins "<vehicle>/<skin>", decals and attachables by
* name), with
* cost:i silver lions (missing = -1)
* costGold:i golden eagles (missing = -1; -1 means not for sale)
* unlock:t an unlock that also gives it
* Only decorations with a positive price are recorded: the others are either free (the client
* counts them as owned, aces.exe 0x95e1c5) or not for sale.
*/
import type { BlkBlock } from '@wto/blk';
import { numberField } from './blk-fields.ts';
import type { Dataset } from './dataset.ts';
export type DecorKind = 'skin' | 'decal' | 'attachable';
export interface DecorPrice {
readonly kind: DecorKind;
/** The client's key: "<vehicle>/<skin>" for skins, the name otherwise. */
readonly key: string;
readonly silverLions: number;
readonly goldenEagles: number;
}
const SOURCES: readonly { kind: DecorKind; path: string }[] = [
{ kind: 'skin', path: 'config/skins.blk' },
{ kind: 'decal', path: 'config/decals.blk' },
{ kind: 'attachable', path: 'config/attachable.blk' },
];
export const decorCatalogue: Dataset<readonly DecorPrice[]> = {
id: 'decor-catalogue',
version: 1,
extract: (source) => SOURCES.flatMap(({ kind, path }) =>
source.readBlk('char.vromfs.bin', path).blocks.flatMap((entry) => priceOf(kind, entry))),
};
function priceOf(kind: DecorKind, entry: BlkBlock): DecorPrice[] {
const silverLions = Math.max(0, numberField(entry, 'cost') ?? 0);
const goldenEagles = Math.max(0, numberField(entry, 'costGold') ?? 0);
return silverLions > 0 || goldenEagles > 0 ? [{ kind, key: entry.name, silverLions, goldenEagles }] : [];
}
@@ -0,0 +1,108 @@
/**
* Dataset: stock game references to external inventory itemdef IDs outside shop.blk vehicles
*:
* - Decorator marketplace coupons in char.vromfs.bin config/{skins,decals,attachable}.blk;
* - Unlock/pilot-icon marketplace coupons in char.vromfs.bin config/unlocks.blk;
* - Workshop referenced itemdef IDs in aces.vromfs.bin config/workshop.blk.
*/
import type { BlkBlock } from '@wto/blk';
import { numberField, stringField } from './blk-fields.ts';
import type { Dataset, DatasetSource } from './dataset.ts';
import type { DecorKind } from './decor-catalogue.ts';
import { parseLocalizedCsvMap } from './lang-csv.ts';
import type { LocalizedText } from './unit-names.ts';
export interface MarketplaceDecorCoupon {
readonly itemdefId: number;
readonly kind: DecorKind;
readonly resourceKey: string;
readonly rarityColor?: string;
readonly name: LocalizedText;
}
export interface MarketplaceUnlockCoupon {
readonly itemdefId: number;
readonly unlockId: string;
readonly unlockType: string;
readonly name: LocalizedText;
}
export interface ExternalItemSources {
readonly decorCoupons: readonly MarketplaceDecorCoupon[];
readonly unlockCoupons: readonly MarketplaceUnlockCoupon[];
readonly workshopItemdefIds: readonly number[];
}
const DECOR_FILES: readonly { kind: DecorKind; blkPath: string; csvPath: string }[] = [
{ kind: 'skin', blkPath: 'config/skins.blk', csvPath: 'lang/unlocks_skins.csv' },
{ kind: 'decal', blkPath: 'config/decals.blk', csvPath: 'lang/unlocks_decals.csv' },
{ kind: 'attachable', blkPath: 'config/attachable.blk', csvPath: 'lang/unlocks_attachables.csv' },
];
export const externalItemSources: Dataset<ExternalItemSources> = {
id: 'external-item-sources',
version: 1,
extract: (source) => ({
decorCoupons: DECOR_FILES.flatMap(({ kind, blkPath, csvPath }) => extractDecorCoupons(source, kind, blkPath, csvPath)),
unlockCoupons: extractUnlockCoupons(source),
workshopItemdefIds: [...collectWorkshopIds(source.readBlk('aces.vromfs.bin', 'config/workshop.blk'))].sort((a, b) => a - b),
}),
};
function extractDecorCoupons(
source: DatasetSource,
kind: DecorKind,
blkPath: string,
csvPath: string,
): MarketplaceDecorCoupon[] {
const locMap = parseLocalizedCsvMap(source.readText('lang.vromfs.bin', csvPath));
const root = source.readBlk('char.vromfs.bin', blkPath);
const out: MarketplaceDecorCoupon[] = [];
for (const entry of root.blocks) {
const itemdefId = numberField(entry, 'marketplaceItemdefId');
if (!itemdefId || itemdefId <= 0) continue;
const key = entry.name;
const localized = locMap.get(key)
?? locMap.get(`decals/${key}`)
?? locMap.get(`attachables/${key}`)
?? { en: humanizeKey(key), zh: humanizeKey(key) };
const rarityColor = stringField(entry, 'userlogColoredText') ?? undefined;
out.push({ itemdefId, kind, resourceKey: key, ...(rarityColor ? { rarityColor } : {}), name: localized });
}
return out;
}
function extractUnlockCoupons(source: DatasetSource): MarketplaceUnlockCoupon[] {
const menuLoc = parseLocalizedCsvMap(source.readText('lang.vromfs.bin', 'lang/menu.csv'));
const achieveLoc = parseLocalizedCsvMap(source.readText('lang.vromfs.bin', 'lang/unlocks_achievements.csv'));
const root = source.readBlk('char.vromfs.bin', 'config/unlocks.blk');
const out: MarketplaceUnlockCoupon[] = [];
for (const entry of root.blocks) {
const itemdefId = numberField(entry, 'marketplaceItemdefId');
const unlockId = stringField(entry, 'id');
if (!itemdefId || itemdefId <= 0 || !unlockId) continue;
const unlockType = stringField(entry, 'type') ?? 'unlock';
const localized = achieveLoc.get(`${unlockId}/name`)
?? menuLoc.get(`${unlockId}/name`)
?? achieveLoc.get(unlockId)
?? menuLoc.get(unlockId)
?? { en: humanizeKey(unlockId), zh: humanizeKey(unlockId) };
out.push({ itemdefId, unlockId, unlockType, name: localized });
}
return out;
}
function collectWorkshopIds(block: BlkBlock, out = new Set<number>()): Set<number> {
for (const param of block.params) {
if (param.value.type === 'int' && param.value.value >= 1000) out.add(param.value.value);
else if (param.value.type === 'string' && /^\d{4,}$/.test(param.value.value)) out.add(Number(param.value.value));
}
if (/^\d{4,}$/.test(block.name)) out.add(Number(block.name));
for (const child of block.blocks) collectWorkshopIds(child, out);
return out;
}
function humanizeKey(key: string): string {
const leaf = key.includes('/') ? key.slice(key.indexOf('/') + 1) : key;
return leaf.replace(/[_-]+/g, ' ').replace(/\b[a-z]/g, (ch) => ch.toUpperCase());
}
@@ -0,0 +1,235 @@
/**
* Dataset: the classic items, char.vromfs.bin config/items.blk.
* One block per item, named after the item:
*
* <item>{
* type:t rateBooster, personalDiscounts, wager, missionOrder, universalSpare
* cost:i costGold:i price of one piece; most items have none (prizes only)
* sell_count_step:i pieces per purchase
* purchase_feature:t sold only to players with that feature ("devItemShop")
* expiredTimeH:r lifetime in hours from when the player gets it
* expiredTimeHAfterActivation:r lifetime in hours from activation
* expiredAt:t absolute end, "YYYY-MM-DD hh:mm:ss" UTC
* canPacked:b the pieces stack under one uid
* universalSpareParams{ numSpares:i country:t... unitType:t... minRank:i maxRank:i }
* rateBoosterParams{ wpRate:i xpRate:i percent added to the battle's Silver Lions / Research Points
* personal:b no: "(all allies)" booster; missing = personal
* spentInSessionTimeMin:i each such span of one battle counts as one more battle
* event{ type:t condition{...} } only rewards of this event (kill, kill_ground, assist)
* stop{ type:t num:i } ends after num sessionsStarted / killedPlayers / killedGround
* }
* wagerParams{ minWager:i maxWager:i wagerStep:i goldWager:b maxWins:i maxFails:i
* win{ <unlock mode> } what one battle must achieve to complete a stage
* active{ <unlock mode> condition{...} } which battles count at all
* winParams{ reward{ param:i <type>RewardParams:p3 } ... } wpRewardParams, goldRewardParams,
* rpRewardParams, freeRpRewardParams: (a, b, c)
* }
* personalDiscountsParams{ purchasesMaxCount:i discountsDesc{ <category>{ <key>:i aircrafts{ <vehicle>:i } } } }
* }
*/
import { findParam, type BlkBlock } from '@wto/blk';
import { unlockModeOf, type StreakMode } from './battle-streaks.ts';
import { blockAt, boolField, numberField, stringField, stringList } from './blk-fields.ts';
import type { Dataset } from './dataset.ts';
const ITEMS = 'config/items.blk';
export interface SpareConditions {
readonly spares: number;
/** Empty: any country. */
readonly countries: readonly string[];
/** The client's lower-case unit type names (aircraft, tank, ship, helicopter, boat); empty: any. */
readonly unitTypes: readonly string[];
readonly minRank?: number;
readonly maxRank?: number;
}
export interface BoosterDefinition {
readonly wpPercent: number;
readonly rpPercent: number;
/** False for the "(all allies)" boosters. */
readonly personal: boolean;
/** spentInSessionTimeMin; 0 when a battle counts once however long it lasts. */
readonly minutesPerBattle: number;
/** rateBoosterParams/event: the booster only adds to the rewards of this event. */
readonly event?: StreakMode;
readonly stop: { readonly type: string; readonly count: number };
}
export type WagerRewardKind = 'rp' | 'freeRp' | 'wp' | 'gold';
export type WagerRewardTerms = readonly [a: number, b: number, c: number];
export interface WagerReward {
/** The stage (number of won battles) from which this reward applies. */
readonly stage: number;
readonly terms: Readonly<Partial<Record<WagerRewardKind, WagerRewardTerms>>>;
}
export interface WagerDefinition {
readonly minStake: number;
readonly maxStake: number;
readonly stakeStep: number;
readonly goldenEagles: boolean;
readonly maxWins: number;
readonly maxFails: number;
readonly win?: StreakMode;
readonly active?: StreakMode;
/** Sorted by stage. */
readonly rewards: readonly WagerReward[];
}
/** One category of a discount description: percentages by key, and by vehicle under "aircrafts". */
export interface DiscountCategory {
readonly name: string;
readonly keys: Readonly<Record<string, number>>;
readonly vehicles: Readonly<Record<string, number>>;
}
export interface DiscountDefinition {
readonly maxPurchases: number;
readonly categories: readonly DiscountCategory[];
}
export interface ItemDefinition {
readonly name: string;
readonly type: string;
readonly silverLions: number;
readonly goldenEagles: number;
readonly piecesPerPurchase: number;
readonly purchaseFeature?: string;
readonly lifetimeHours?: number;
readonly lifetimeHoursAfterActivation?: number;
/** Unix milliseconds. */
readonly expiresAt?: number;
readonly stacks: boolean;
readonly spare?: SpareConditions;
readonly booster?: BoosterDefinition;
readonly wager?: WagerDefinition;
readonly discount?: DiscountDefinition;
/** External inventory craft-part itemdef id granted on recycling (299000..299004; implementation notes). */
readonly recycleItemResult?: number;
}
export const itemCatalogue: Dataset<readonly ItemDefinition[]> = {
id: 'item-catalogue',
version: 3,
extract: (source) => source.readBlk('char.vromfs.bin', ITEMS).blocks.flatMap(itemOf),
};
function itemOf(entry: BlkBlock): ItemDefinition[] {
const type = stringField(entry, 'type');
if (type === undefined) return [];
const lifetimeHours = positive(numberField(entry, 'expiredTimeH'));
const lifetimeHoursAfterActivation = positive(numberField(entry, 'expiredTimeHAfterActivation'));
const expiresAt = utcTime(stringField(entry, 'expiredAt'));
const purchaseFeature = stringField(entry, 'purchase_feature');
const recycleItemResult = positive(numberField(entry, 'recycleItemResult'));
const spare = spareOf(blockAt(entry, 'universalSpareParams'));
const booster = boosterOf(blockAt(entry, 'rateBoosterParams'));
const wager = wagerOf(blockAt(entry, 'wagerParams'));
const discount = discountOf(blockAt(entry, 'personalDiscountsParams'));
return [{
name: entry.name,
type,
silverLions: Math.max(0, numberField(entry, 'cost') ?? 0),
goldenEagles: Math.max(0, numberField(entry, 'costGold') ?? 0),
piecesPerPurchase: Math.max(1, numberField(entry, 'sell_count_step') ?? 1),
stacks: boolField(entry, 'canPacked') ?? false,
...(purchaseFeature ? { purchaseFeature } : {}),
...(lifetimeHours !== undefined ? { lifetimeHours } : {}),
...(lifetimeHoursAfterActivation !== undefined ? { lifetimeHoursAfterActivation } : {}),
...(expiresAt !== undefined ? { expiresAt } : {}),
...(recycleItemResult !== undefined ? { recycleItemResult } : {}),
...(spare ? { spare } : {}),
...(booster ? { booster } : {}),
...(wager ? { wager } : {}),
...(discount ? { discount } : {}),
}];
}
function spareOf(params: BlkBlock | undefined): SpareConditions | undefined {
if (!params) return undefined;
const minRank = numberField(params, 'minRank');
const maxRank = numberField(params, 'maxRank');
return {
spares: Math.max(1, numberField(params, 'numSpares') ?? 1),
countries: stringList(params, 'country'),
unitTypes: stringList(params, 'unitType'),
...(minRank !== undefined ? { minRank } : {}),
...(maxRank !== undefined ? { maxRank } : {}),
};
}
function boosterOf(params: BlkBlock | undefined): BoosterDefinition | undefined {
if (!params) return undefined;
const event = blockAt(params, 'event');
const stop = blockAt(params, 'stop');
return {
wpPercent: Math.max(0, numberField(params, 'wpRate') ?? 0),
rpPercent: Math.max(0, numberField(params, 'xpRate') ?? 0),
personal: boolField(params, 'personal') ?? true,
minutesPerBattle: Math.max(0, numberField(params, 'spentInSessionTimeMin') ?? 0),
...(event ? { event: unlockModeOf(event) } : {}),
stop: { type: stringField(stop, 'type') ?? 'sessionsStarted', count: Math.max(1, numberField(stop, 'num') ?? 1) },
};
}
const REWARD_KINDS: Readonly<Record<string, WagerRewardKind>> = {
rpRewardParams: 'rp', freeRpRewardParams: 'freeRp', wpRewardParams: 'wp', goldRewardParams: 'gold',
};
function wagerOf(params: BlkBlock | undefined): WagerDefinition | undefined {
if (!params) return undefined;
const win = blockAt(params, 'win');
const active = blockAt(params, 'active');
const rewards = (blockAt(params, 'winParams')?.blocks ?? []).filter((block) => block.name === 'reward').flatMap((reward): WagerReward[] => {
const stage = numberField(reward, 'param') ?? 0;
const terms: Partial<Record<WagerRewardKind, WagerRewardTerms>> = {};
for (const [name, kind] of Object.entries(REWARD_KINDS)) {
const value = findParam(reward, name)?.value;
if (value?.type === 'point3' && value.value.some((part) => part !== 0)) terms[kind] = [value.value[0], value.value[1], value.value[2]];
}
return stage > 0 && Object.keys(terms).length > 0 ? [{ stage, terms }] : [];
}).sort((a, b) => a.stage - b.stage);
return {
minStake: Math.max(0, numberField(params, 'minWager') ?? 0),
maxStake: Math.max(0, numberField(params, 'maxWager') ?? 0),
stakeStep: Math.max(1, numberField(params, 'wagerStep') ?? 1),
goldenEagles: boolField(params, 'goldWager') ?? false,
maxWins: Math.max(0, numberField(params, 'maxWins') ?? 0),
maxFails: Math.max(0, numberField(params, 'maxFails') ?? 0),
...(win ? { win: unlockModeOf(win) } : {}),
...(active ? { active: unlockModeOf(active) } : {}),
rewards,
};
}
function discountOf(params: BlkBlock | undefined): DiscountDefinition | undefined {
if (!params) return undefined;
const description = blockAt(params, 'discountsDesc');
return {
maxPurchases: numberField(params, 'purchasesMaxCount') ?? 0,
categories: (description?.blocks ?? []).map((category) => ({
name: category.name,
keys: intsOf(category),
vehicles: intsOf(blockAt(category, 'aircrafts')),
})),
};
}
function intsOf(block: BlkBlock | undefined): Record<string, number> {
if (!block) return {};
return Object.fromEntries(block.params.flatMap((param) => param.value.type === 'int' ? [[param.name, param.value.value]] : []));
}
function positive(value: number | undefined): number | undefined {
return value !== undefined && value > 0 ? value : undefined;
}
/** "YYYY-MM-DD hh:mm:ss" in UTC, as the scripts read it (getTimestampFromStringUtc). */
function utcTime(text: string | undefined): number | undefined {
const match = text && /^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2}):(\d{2})$/.exec(text.trim());
if (!match) return undefined;
const [, year, month, day, hour, minute, second] = match.map(Number) as [number, number, number, number, number, number, number];
return Date.UTC(year, month - 1, day, hour, minute, second);
}
@@ -0,0 +1,57 @@
/**
* Shared semicolon-separated localization CSV parser for files in `lang.vromfs.bin`.
*/
export interface LocalizedCsvText {
readonly en: string;
readonly zh: string;
}
export function parseSemicolonCsvRow(line: string): string[] {
const fields: string[] = [];
let current = '';
let inQuotes = false;
for (let i = 0; i < line.length; i += 1) {
const ch = line[i]!;
if (ch === '"') {
if (inQuotes && line[i + 1] === '"') {
current += '"';
i += 1;
} else {
inQuotes = !inQuotes;
}
} else if (ch === ';' && !inQuotes) {
fields.push(current);
current = '';
} else {
current += ch;
}
}
fields.push(current);
return fields;
}
/** Strip zero-width word-break spaces Gaijin inserts into CJK localization strings. */
export function cleanLangText(raw: string): string {
return raw.replace(/\u200b/g, '').trim();
}
export function parseLocalizedCsvMap(csvText: string): Map<string, LocalizedCsvText> {
const lines = csvText.split(/\r?\n/);
const header = parseSemicolonCsvRow(lines[0] ?? '');
const enIdx = Math.max(1, header.findIndex((col) => col.includes('<English>')));
const zhIdx = header.findIndex((col) => col.includes('<Chinese>'));
const hzhIdx = header.findIndex((col) => col.includes('<HChinese>'));
const map = new Map<string, LocalizedCsvText>();
for (let i = 1; i < lines.length; i += 1) {
const line = lines[i];
if (!line) continue;
const cols = parseSemicolonCsvRow(line);
const id = cols[0];
if (!id) continue;
const en = cleanLangText(cols[enIdx] ?? '') || id;
const zh = cleanLangText((zhIdx >= 0 ? cols[zhIdx] : '') || (hzhIdx >= 0 ? cols[hzhIdx] : '') || '') || en;
map.set(id, { en, zh });
}
return map;
}
@@ -0,0 +1,137 @@
/**
* Dataset: the game's multiplayer missions, as the game lists and describes them.
*
* - The list: char.vromfs.bin config/mislist.blk, block "skirmish". One sub-block per
* category (e.g. air_ground_Dom, air_dom, air_naval_Dom, pve), holding the category's
* flags (isDebug, isForceHidden, …) and its mission names (repeated "m").
* - Each mission: mis.vromfs.bin gamedata/missions/…/<name lower-cased>.blk. Its
* mission_settings block names the map, the kind of game, the two sides' countries, the
* vehicle types allowed, per-difficulty overrides, and the players' spawn slots
* ("wing" entries of player / player_teamB). Its scalar parameters (and those of each
* per-difficulty "mission" sub-block) are also kept as written, with their BLK types, for
* the mission settings the local server sends when a battle starts.
*
* 2.61.0.37: 1315 missions, each name matching exactly one mission file (docs/implementation notes).
*/
import type { BlkBlock, BlkParam } from '@wto/blk';
import type { Dataset, DatasetSource } from './dataset.ts';
import { blockAt, boolFields, numberField, stringField, stringList } from './blk-fields.ts';
const MISSION_LIST = 'config/mislist.blk';
const MULTIPLAYER_SECTION = 'skirmish';
const MISSION_FOLDER = 'gamedata/missions/';
export interface MissionCategory {
readonly name: string;
readonly flags: Readonly<Record<string, boolean>>;
readonly missions: readonly string[];
}
export interface MissionHeader {
readonly name: string;
readonly path: string;
readonly level?: string;
readonly type?: string;
readonly environment?: string;
readonly weather?: string;
readonly locName?: string;
readonly postfix?: string;
readonly countryAxis?: string;
readonly countryAllies?: string;
readonly timeLimit?: number;
/** As written in the mission (isAirplanesAllowed, isTanksAllowed, …); empty when the mission does not say. */
readonly allowedUnitTypes: Readonly<Record<string, boolean>>;
/** Difficulties the mission has its own settings for. */
readonly difficultyOverrides: readonly string[];
/** Spawn slots per side. */
readonly playerSlots: { readonly teamA: number; readonly teamB: number };
/** String, int, real and bool parameters of mission_settings.mission, in file order. */
readonly missionParams: readonly BlkParam[];
/** The same for each per-difficulty "mission" sub-block, keyed by its `difficulty`. */
readonly difficultyParams: Readonly<Record<string, readonly BlkParam[]>>;
}
export interface MultiplayerMissions {
readonly categories: readonly MissionCategory[];
readonly missions: Readonly<Record<string, MissionHeader>>;
}
export const multiplayerMissions: Dataset<MultiplayerMissions> = {
id: 'multiplayer-missions',
version: 3,
extract(source: DatasetSource): MultiplayerMissions {
const section = blockAt(source.readBlk('char.vromfs.bin', MISSION_LIST), MULTIPLAYER_SECTION);
if (!section) throw new Error(`${MISSION_LIST} has no "${MULTIPLAYER_SECTION}" block`);
const categories = section.blocks.map((block): MissionCategory => ({
name: block.name,
flags: boolFields(block),
missions: stringList(block, 'm'),
}));
const pathByName = missionPathsByLowerName(source.listFiles('mis.vromfs.bin'));
const missions: Record<string, MissionHeader> = {};
for (const name of categories.flatMap((category) => category.missions)) {
if (name in missions) continue;
const path = pathByName.get(name.toLowerCase());
if (!path) throw new Error(`mission ${name} (${MISSION_LIST}) has no file in mis.vromfs.bin`);
missions[name] = readHeader(name, path, source.readBlk('mis.vromfs.bin', path));
}
return { categories, missions };
},
};
function missionPathsByLowerName(paths: readonly string[]): Map<string, string> {
const byName = new Map<string, string>();
const repeated = new Set<string>();
for (const path of paths) {
if (!path.startsWith(MISSION_FOLDER) || !path.endsWith('.blk')) continue;
const name = path.slice(path.lastIndexOf('/') + 1, -'.blk'.length);
if (byName.has(name)) repeated.add(name);
byName.set(name, path);
}
for (const name of repeated) byName.delete(name);
return byName;
}
function readHeader(name: string, path: string, document: BlkBlock): MissionHeader {
const settings = blockAt(document, 'mission_settings');
const mission = blockAt(settings, 'mission');
const optional = {
level: stringField(mission, 'level'),
type: stringField(mission, 'type'),
environment: stringField(mission, 'environment'),
weather: stringField(mission, 'weather'),
locName: stringField(mission, 'locName'),
postfix: stringField(mission, 'postfix'),
countryAxis: stringField(mission, 'country_axis'),
countryAllies: stringField(mission, 'country_allies'),
timeLimit: numberField(mission, 'timeLimit'),
};
return {
name,
path,
...Object.fromEntries(Object.entries(optional).filter(([, value]) => value !== undefined)),
allowedUnitTypes: boolFields(blockAt(mission, 'allowedUnitTypes')),
difficultyOverrides: (mission?.blocks ?? [])
.filter((block) => block.name === 'mission')
.flatMap((block) => stringField(block, 'difficulty') ?? []),
playerSlots: {
teamA: stringList(blockAt(settings, 'player'), 'wing').length,
teamB: stringList(blockAt(settings, 'player_teamB'), 'wing').length,
},
missionParams: scalarParams(mission),
difficultyParams: Object.fromEntries((mission?.blocks ?? [])
.filter((block) => block.name === 'mission')
.flatMap((block) => {
const difficulty = stringField(block, 'difficulty');
return difficulty ? [[difficulty, scalarParams(block)]] : [];
})),
};
}
const SCALAR_TYPES = new Set(['string', 'int', 'real', 'bool']);
/** The parameters whose values survive the dataset cache's JSON unchanged. */
function scalarParams(block: BlkBlock | undefined): BlkParam[] {
return (block?.params ?? []).filter((param) => SCALAR_TYPES.has(param.value.type));
}
@@ -0,0 +1,55 @@
/**
* Datasets from char.vromfs.bin config/rank.blk.
*
* needBuyToOpenNextInEra{ <country>{ needBuyToOpenNextInEra<type><rank>:i=N } }
* how many vehicles of a rank a country's branch must own before the next rank opens; the
* stock scripts also look up the name without the type (gui.vromfs.bin
* scripts/unit/unitInfo.nut getUnitsNeedBuyToOpenNextInEra).
*
* crew_slots{ slot<N>{ cost:i costGold:i } }
* the price of a country's next crew slot when it has N crews (aces.exe 2.61.0.37
* get_crew_slot_cost, 0x90eaa0).
*/
import { numberField } from './blk-fields.ts';
import type { Dataset } from './dataset.ts';
const RANK = 'config/rank.blk';
const SLOT = /^slot(\d+)$/;
/** country -> parameter name -> vehicles needed, as written. */
export type EraRequirements = Readonly<Record<string, Readonly<Record<string, number>>>>;
export const eraRequirements: Dataset<EraRequirements> = {
id: 'era-requirements',
version: 1,
extract: (source) => {
const block = source.readBlk('char.vromfs.bin', RANK).blocks.find((child) => child.name === 'needBuyToOpenNextInEra');
return Object.fromEntries((block?.blocks ?? []).map((country) => [
country.name,
Object.fromEntries(country.params.flatMap((param) => (param.value.type === 'int' ? [[param.name, param.value.value]] : []))),
]));
},
};
export interface CrewSlotPrice {
readonly silverLions: number;
readonly goldenEagles: number;
}
/** Indexed by the number of crews the country has; a missing index has no price (cannot be bought). */
export type CrewSlotPrices = readonly (CrewSlotPrice | null)[];
export const crewSlotPrices: Dataset<CrewSlotPrices> = {
id: 'crew-slot-prices',
version: 1,
extract: (source) => {
const block = source.readBlk('char.vromfs.bin', RANK).blocks.find((child) => child.name === 'crew_slots');
const prices: (CrewSlotPrice | null)[] = [];
for (const slot of block?.blocks ?? []) {
const index = SLOT.exec(slot.name)?.[1];
if (index === undefined) continue;
prices[Number(index)] = { silverLions: numberField(slot, 'cost') ?? 0, goldenEagles: numberField(slot, 'costGold') ?? 0 };
}
return Array.from(prices, (price) => price ?? null);
},
};
@@ -0,0 +1,82 @@
/**
* Dataset: how a battle's Research Points reach the researched vehicle (implementation notes "3e").
*
* char.vromfs.bin config/rank.blk:
* expBonusPercentForChildForMode<N> bonus when the vehicle played precedes the researched one;
* the client reads N = the difficulty's diffCode
* (gui.vromfs.bin scripts/airinfo.nut)
* expPenaltyPercentForHigherRank<N> penalty when the researched vehicle is N ranks above the one played
* expPenaltyPercentForLowerRank<N> penalty when it is N ranks below
* ExpNewNationBonus{<type>{rank<N>}} "Vehicle Research Bonus" percent by the researched vehicle's rank
* expNewNationBonusDailyBattleCount battles per nation and branch per day that get it
* char.vromfs.bin config/shop.blk:
* country{ branch{ range{ vehicle | group{ vehicle... } } } }: the last entry of each range ends a
* research line; when it is a group, its first vehicle counts (official wiki "Research Points",
* "top" vehicle definition).
*/
import type { BlkBlock } from '@wto/blk';
import { numberField } from './blk-fields.ts';
import type { Dataset } from './dataset.ts';
import { SHOP } from './shop-tree.ts';
export interface ResearchEfficiencyData {
/** Indexed by mode number N of expBonusPercentForChildForMode<N>. */
readonly childBonusPercent: readonly number[];
/** Indexed by the rank difference. */
readonly higherRankPenaltyPercent: readonly number[];
readonly lowerRankPenaltyPercent: readonly number[];
/** Vehicle type (rank.blk spelling: Tank, Aircraft, Helicopter, Ship, Boat) -> rank -> percent. */
readonly nationBonusPercent: Readonly<Record<string, Readonly<Record<number, number>>>>;
readonly nationBonusDailyBattles: number;
/** The vehicle that ends each research line of shop.blk. */
readonly lineEnds: readonly string[];
}
const RANK = 'config/rank.blk';
export const researchEfficiency: Dataset<ResearchEfficiencyData> = {
id: 'research-efficiency',
version: 1,
extract: (source) => {
const rank = source.readBlk('char.vromfs.bin', RANK);
const nationBonus = rank.blocks.find((block) => block.name === 'ExpNewNationBonus');
const dailyBattles = numberField(rank, 'expNewNationBonusDailyBattleCount');
if (dailyBattles === undefined) throw new Error('rank.blk: expNewNationBonusDailyBattleCount is missing');
return {
childBonusPercent: indexedSeries(rank, 'expBonusPercentForChildForMode'),
higherRankPenaltyPercent: indexedSeries(rank, 'expPenaltyPercentForHigherRank'),
lowerRankPenaltyPercent: indexedSeries(rank, 'expPenaltyPercentForLowerRank'),
nationBonusPercent: Object.fromEntries((nationBonus?.blocks ?? []).map((type) => [
type.name,
Object.fromEntries(type.params.flatMap((param) => {
const rankNumber = /^rank(\d+)$/.exec(param.name)?.[1];
return rankNumber !== undefined && param.value.type === 'int' ? [[Number(rankNumber), param.value.value]] : [];
})),
])),
nationBonusDailyBattles: dailyBattles,
lineEnds: source.readBlk('char.vromfs.bin', SHOP).blocks.flatMap((country) =>
country.blocks.flatMap((branch) => branch.blocks.filter((range) => range.name === 'range').flatMap(lineEnd))),
};
},
};
/** <prefix>0, <prefix>1, ... up to the first missing index. */
function indexedSeries(block: BlkBlock, prefix: string): number[] {
const values: number[] = [];
for (let index = 0; ; index++) {
const value = numberField(block, `${prefix}${index}`);
if (value === undefined) break;
values.push(value);
}
if (values.length === 0) throw new Error(`rank.blk: ${prefix}0 is missing`);
return values;
}
/** A vehicle entry has no child blocks; a group holds its vehicles as child blocks. */
function lineEnd(range: BlkBlock): string[] {
const last = range.blocks.at(-1);
if (!last) return [];
if (last.blocks.length === 0) return [last.name];
const first = last.blocks[0];
return first ? [first.name] : [];
}
@@ -0,0 +1,17 @@
/**
* Dataset: how many free research points one golden eagle converts into a vehicle's research
* points (implementation notes, cln_convert_exp).
*
* char.vromfs.bin config/warpoints.blk playerExpToCountryFor1Gold:i (2.61.0.37: 45). The
* client reads it in wp_get_exp_convert_exp_for_gold_rate (aces.exe 0x1052af0 -> 0x916eb0),
* defaulting to 1; the price table can override it per country (exp_to_gold_rate), which the
* local server does not send.
*/
import { numberField } from './blk-fields.ts';
import type { Dataset } from './dataset.ts';
export const researchPointsPerGoldenEagle: Dataset<number> = {
id: 'research-point-rate',
version: 1,
extract: (source) => numberField(source.readBlk('char.vromfs.bin', 'config/warpoints.blk'), 'playerExpToCountryFor1Gold') ?? 1,
};
@@ -0,0 +1,64 @@
/**
* Dataset: the reserve vehicles, the free rank-I vehicles of each country and branch.
*
* The client decides what counts as a reserve vehicle with the native script function
* is_default_aircraft (aces.exe 2.61.0.37 0x17a5d50 -> 0x9640c0). It looks the vehicle up in
* char.vromfs.bin config/wpcost.blk and reads repairCostArcade, repairCostHistorical and
* repairCostSimulation: a vehicle is a reserve vehicle unless one of them is above 0 (a
* missing value counts as 0). The stock UI then only offers reserve vehicles that are also in
* the tech tree (scripts/slotbar/slotbarStateData.nut checkReserveUnit: isVisibleInShop), so
* only vehicles listed in config/shop.blk are taken; the shop also gives each one's country.
*
* 2.61.0.37: 56 vehicles; every country except Israel has reserve aircraft and ground
* vehicles, and all but China and Sweden have reserve boats and ships. No helicopter is a
* reserve vehicle.
*/
import type { BlkBlock } from '@wto/blk';
import type { Dataset } from './dataset.ts';
import { numberField } from './blk-fields.ts';
const VEHICLE_ECONOMY = 'config/wpcost.blk';
const SHOP = 'config/shop.blk';
const REPAIR_COSTS = ['repairCostArcade', 'repairCostHistorical', 'repairCostSimulation'] as const;
export interface ReserveVehicle {
readonly name: string;
readonly country: string;
}
export const reserveVehicles: Dataset<readonly ReserveVehicle[]> = {
id: 'reserve-vehicles',
version: 1,
extract: (source) => {
const economy = new Map(source.readBlk('char.vromfs.bin', VEHICLE_ECONOMY).blocks.map((vehicle) => [vehicle.name, vehicle]));
const result: ReserveVehicle[] = [];
for (const country of source.readBlk('char.vromfs.bin', SHOP).blocks) {
for (const name of vehiclesInTree(country)) {
const vehicle = economy.get(name);
if (vehicle && isReserve(vehicle) && !result.some((known) => known.name === name)) result.push({ name, country: country.name });
}
}
return result;
},
};
function isReserve(vehicle: BlkBlock): boolean {
return REPAIR_COSTS.every((cost) => (numberField(vehicle, cost) ?? 0) <= 0);
}
/**
* Every block name below a country's tech tree: country -> branch -> column -> vehicle, with
* grouped vehicles one level deeper. Names that are not vehicles (columns, groups) are
* dropped by the caller, which only keeps names that have an economy entry.
*/
function vehiclesInTree(country: BlkBlock): string[] {
const names: string[] = [];
const walk = (block: BlkBlock): void => {
for (const child of block.blocks) {
names.push(child.name);
walk(child);
}
};
for (const branch of country.blocks) walk(branch);
return names;
}
@@ -0,0 +1,18 @@
/**
* Dataset: the tech-tree branches of each country.
*
* char.vromfs.bin config/shop.blk has one top-level block per country, and under it one block
* per branch: army, helicopters, aviation, ships, boats (2.61.0.37: China, Sweden and Israel
* have no naval branches).
*/
import type { Dataset } from './dataset.ts';
const SHOP = 'config/shop.blk';
export type ShopBranches = Readonly<Record<string, readonly string[]>>;
export const shopBranches: Dataset<ShopBranches> = {
id: 'shop-branches',
version: 1,
extract: (source) => Object.fromEntries(source.readBlk('char.vromfs.bin', SHOP).blocks.map((country) => [country.name, country.blocks.map((branch) => branch.name)])),
};
@@ -0,0 +1,15 @@
/**
* Dataset: the countries of the game, in tech-tree order.
*
* char.vromfs.bin config/shop.blk has one top-level block per country (country_usa, …).
* The stock UI builds its own country list the same way (gui.vromfs.bin
* scripts/shop/shopCountriesList.nut, updateShopCountriesList).
*/
import type { Dataset } from './dataset.ts';
import { shopCountryNames } from './shop-tree.ts';
export const shopCountries: Dataset<readonly string[]> = {
id: 'shop-countries',
version: 1,
extract: shopCountryNames,
};
@@ -0,0 +1,27 @@
/**
* Walk char.vromfs.bin config/shop.blk: one top-level block per country, below it branches,
* columns, groups and vehicles. Shared by the datasets that need the
* per-vehicle shop entries.
*/
import type { BlkBlock } from '@wto/blk';
import type { DatasetSource } from './dataset.ts';
export const SHOP = 'config/shop.blk';
/** Every shop entry by name; the first entry wins when a name repeats. Non-vehicle entries are included and simply never looked up. */
export function shopEntriesByName(source: DatasetSource): Map<string, BlkBlock> {
const entries = new Map<string, BlkBlock>();
for (const country of source.readBlk('char.vromfs.bin', SHOP).blocks) {
for (const entry of entriesBelow(country)) if (!entries.has(entry.name)) entries.set(entry.name, entry);
}
return entries;
}
/** The countries in tech-tree order (the top-level block names). */
export function shopCountryNames(source: DatasetSource): string[] {
return source.readBlk('char.vromfs.bin', SHOP).blocks.map((block) => block.name);
}
function entriesBelow(block: BlkBlock): BlkBlock[] {
return block.blocks.flatMap((child) => [child, ...entriesBelow(child)]);
}
@@ -0,0 +1,27 @@
/**
* Dataset: entitlement-to-GUID mappings from aces.vromfs.bin config/gui.blk bundles/guid
* (gui.vromfs.bin scripts/onlineShop/onlineBundles.nut, implementation notes).
*/
import { findBlock } from '@wto/blk';
import type { Dataset } from './dataset.ts';
const GUI_CONFIG = 'config/gui.blk';
/** Entitlement name -> store item GUID (upper-case UUID string). */
export type StoreBundleGuids = Readonly<Record<string, string>>;
export const storeBundles: Dataset<StoreBundleGuids> = {
id: 'store-bundles',
version: 1,
extract: (source) => {
const gui = source.readBlk('aces.vromfs.bin', GUI_CONFIG);
const guidBlock = findBlock(findBlock(gui, 'bundles') ?? { name: '', params: [], blocks: [] }, 'guid');
const result: Record<string, string> = {};
for (const param of guidBlock?.params ?? []) {
if (param.value.type === 'string' && param.value.value) {
result[param.name] = param.value.value;
}
}
return result;
},
};
@@ -0,0 +1,27 @@
/**
* Dataset: the game's own names for countries and vehicle types, from lang.vromfs.bin
*:
* lang/_common_languages.csv: country_usa, country_germany, ... country names
* lang/menu.csv: mainmenu/type_aircraft, type_tank, ... vehicle type names
*/
import type { Dataset } from './dataset.ts';
import { parseLocalizedCsvMap, type LocalizedCsvText } from './lang-csv.ts';
const LABEL_FILES = ['lang/_common_languages.csv', 'lang/menu.csv'] as const;
const KEY_PREFIXES = ['country_', 'mainmenu/type_'];
export type UiLabels = Readonly<Record<string, LocalizedCsvText>>;
export const uiLabels: Dataset<UiLabels> = {
id: 'ui-labels',
version: 2,
extract: (source) => {
const labels: Record<string, LocalizedCsvText> = {};
for (const file of LABEL_FILES) {
for (const [key, text] of parseLocalizedCsvMap(source.readText('lang.vromfs.bin', file))) {
if (KEY_PREFIXES.some((prefix) => key.startsWith(prefix))) labels[key] = text;
}
}
return labels;
},
};
Loaded 100 of 476 files, more files were not shown because too many files have changed in this diff. Show more