diff --git a/gui-patches/battle/record-local-battle-awards/patch.jsonc b/gui-patches/battle/record-local-battle-awards/patch.jsonc index d75b625..463c669 100644 --- a/gui-patches/battle/record-local-battle-awards/patch.jsonc +++ b/gui-patches/battle/record-local-battle-awards/patch.jsonc @@ -1,14 +1,18 @@ -// Record the local player's lives and combat events in a LocalMP battle and show their reward banner. -// Why the client: online the battle server prices each event and sends the banner (packet 0xb03d); -// a LocalMP host has no battle server, so the native bridge reports the facts as the HUD event -// "wtoLocalMpExpEvent" and only the client sees when the player spawns and dies. -// Without it: no reward banners in battle and nothing to settle after it. +// Record the local player's lives, combat events and the battle's kill log in a LocalMP battle, +// show the reward banner, and pass each fact to the local service live to show the battle awards +// (streaks) it completes. +// Why the client: online the battle server prices each event, judges the awards and sends both +// banners (packet 0xb03d, streak messages); a LocalMP host has no battle server, so the native +// bridge reports the facts as the HUD event "wtoLocalMpExpEvent" and only the client sees spawns, +// deaths and the kill log. +// Without it: no reward or award banners in battle and nothing to settle after it. { "id": "battle/record-local-battle-awards", - "title": "Record LocalMP combat events and lives, and show their reward banner", + "title": "Record LocalMP battle facts and show their reward and award banners", "file": "scripts/hud/hudrewardmessage.nut", "features": [ - "K-击杀、助攻、占点计分" + "K-击杀、助攻、占点计分", + "L-战斗奖章" ], "verified_on": [ "2.61.0.37" diff --git a/gui-patches/battle/record-local-battle-awards/replace.nut b/gui-patches/battle/record-local-battle-awards/replace.nut index 1617600..4a9fb01 100644 --- a/gui-patches/battle/record-local-battle-awards/replace.nut +++ b/gui-patches/battle/record-local-battle-awards/replace.nut @@ -3,6 +3,43 @@ // HUD event "wtoLocalMpExpEvent" with the facts, the banner amount comes from the parameters the // local service sent at launch (nestdb wto.activeBattle.awards, battle-economy.ts BannerParams), and // the record (nestdb wto.battleLog) is settled by the local service after the battle. +// Each fact is also sent to the local service as it happens (matching request wto_battle.fact); +// the battle awards (streaks) it completed come back and are shown with the stock award banner, +// as the battle server's award messages are online. +function wtoShowLiveStreaks(resp) { + let streaks = resp?.streaks ?? [] + if (streaks.len() == 0) + return + let { add_streak_message, getLocForStreak } = require("%scripts/streaks.nut") + let { SNT_MY_STREAK_HEADER } = require("%globalScripts/battleMetaConsts.nut") + let { HUD_MSG_STREAK } = require("hudMessages") + let { g_hud_event_manager } = require("%scripts/hud/hudEventManager.nut") + let localId = require("mission").get_local_mplayer()?.id ?? -1 + foreach (streak in streaks) { + let stageParam = streak?.stageParam ?? 0 + add_streak_message({ + header = getLocForStreak(SNT_MY_STREAK_HEADER, streak.id, stageParam) + wp = streak?.wp ?? 0 + exp = streak?.exp ?? 0 + id = streak.id + }) + g_hud_event_manager.onHudEvent("HudMessage", { type = HUD_MSG_STREAK, unlockId = streak.id, stage = stageParam, playerId = localId }) + } +} + +function wtoSendLiveFact(kind, fact) { + let battle = require("nestdb").ndbTryRead(["wto", "activeBattle"]) + if (battle == null) + return + let { matchingApiFunc } = require("%scripts/matching/api.nut") + matchingApiFunc("wto_battle.fact", wtoShowLiveStreaks, fact.__merge({ + sessionId = battle.sessionId + kind + localPlayerId = require("mission").get_local_mplayer()?.id ?? -1 + localTeam = require("mission").get_mp_local_team() + })) +} + function wtoAppendBattleLog(key, entry) { let { ndbTryRead, ndbWrite } = require("nestdb") let list = (ndbTryRead(["wto", "battleLog", key]) ?? []).map(@(v) v) @@ -37,7 +74,7 @@ function wtoOnLocalMpExpEvent(ev) { return let wtoMission = require("mission") let unit = ndbTryRead(["wto", "battleLog", "openLife"])?.unit ?? require("unit").get_player_unit_name() - wtoAppendBattleLog("events", { + let entry = { time = wtoMission.get_mission_time() unit code = ev?.messageCode ?? -1 @@ -47,7 +84,9 @@ function wtoOnLocalMpExpEvent(ev) { friendly = (ev?.friendly ?? 0) != 0 modifier = ev?.messageModifier ?? "" damage = ev?.damage ?? 0 - }) + } + wtoAppendBattleLog("events", entry) + wtoSendLiveFact("event", entry) let reward = wtoBannerReward(battle?.awards, unit, ev) if (reward == null) return @@ -62,20 +101,22 @@ function wtoOnLocalMpExpEvent(ev) { }) } -function wtoCloseBattleLife() { +function wtoCloseBattleLife(died) { let { ndbTryRead, ndbDelete } = require("nestdb") let life = ndbTryRead(["wto", "battleLog", "openLife"]) if (life == null) return ndbDelete(["wto", "battleLog", "openLife"]) - wtoAppendBattleLog("lives", life.__merge({ end = require("mission").get_mission_time() })) + let closed = life.__merge({ end = require("mission").get_mission_time(), died }) + wtoAppendBattleLog("lives", closed) + wtoSendLiveFact("life", closed) } function wtoOnLocalPlayerAlive(_ev) { let { ndbExists, ndbWrite } = require("nestdb") if (!ndbExists(["wto", "activeBattle"])) return - wtoCloseBattleLife() + wtoCloseBattleLife(false) let unit = require("unit").get_player_unit_name() if ((unit ?? "") != "") ndbWrite(["wto", "battleLog", "openLife"], { unit, start = require("mission").get_mission_time() }) @@ -83,7 +124,31 @@ function wtoOnLocalPlayerAlive(_ev) { function wtoOnLocalPlayerDead(_ev) { if (require("nestdb").ndbExists(["wto", "activeBattle"])) - wtoCloseBattleLife() + wtoCloseBattleLife(true) +} + +// Every kill of the HUD kill log, for the awards that depend on who killed whom (first kill, +// avenging). A message without player ids is about the local player (scripts/hud/hudBattleLog.nut). +function wtoOnHudMessage(msg) { + let { HUD_MSG_MULTIPLAYER_DMG } = require("hudMessages") + if (msg?.type != HUD_MSG_MULTIPLAYER_DMG || !(msg?.isKill ?? true)) + return + if (!require("nestdb").ndbExists(["wto", "activeBattle"])) + return + let wtoMission = require("mission") + let localId = wtoMission.get_local_mplayer()?.id ?? -1 + let localTeam = wtoMission.get_mp_local_team() + let killer = msg?.playerId ?? localId + let victim = msg?.victimPlayerId ?? localId + let kill = { + time = wtoMission.get_mission_time() + killer + killerTeam = msg?.team ?? (killer == localId ? localTeam : 0) + victim + victimTeam = msg?.victimTeam ?? (victim == localId ? localTeam : 0) + } + wtoAppendBattleLog("feed", kill) + wtoSendLiveFact("kill", kill) } function wtoSubscribeBattleAwards() { @@ -91,6 +156,7 @@ function wtoSubscribeBattleAwards() { g_hud_event_manager.subscribe("wtoLocalMpExpEvent", wtoOnLocalMpExpEvent) g_hud_event_manager.subscribe("LocalPlayerAlive", wtoOnLocalPlayerAlive) g_hud_event_manager.subscribe("LocalPlayerDead", wtoOnLocalPlayerDead) + g_hud_event_manager.subscribe("HudMessage", wtoOnHudMessage) } // The battle ends for the local player here: close the open life and keep the end time, which the @@ -99,7 +165,7 @@ function wtoOnQuitToDebriefing(_p) { let { ndbExists, ndbWrite } = require("nestdb") if (!ndbExists(["wto", "activeBattle"])) return - wtoCloseBattleLife() + wtoCloseBattleLife(false) ndbWrite(["wto", "battleLog", "sessionEnd"], require("mission").get_mission_time()) } diff --git a/gui-patches/battle/report-local-battle-settlement/patch.jsonc b/gui-patches/battle/report-local-battle-settlement/patch.jsonc index 89a0a77..dfd6efa 100644 --- a/gui-patches/battle/report-local-battle-settlement/patch.jsonc +++ b/gui-patches/battle/report-local-battle-settlement/patch.jsonc @@ -8,7 +8,8 @@ "title": "Report LocalMP battle facts to local-service and show the settled debriefing", "file": "scripts/debriefing/debriefingmodal.nut", "features": [ - "L-结算页" + "L-结算页", + "L-战斗奖章" ], "verified_on": [ "2.61.0.37" diff --git a/gui-patches/battle/report-local-battle-settlement/replace.nut b/gui-patches/battle/report-local-battle-settlement/replace.nut index 98495c9..54cf023 100644 --- a/gui-patches/battle/report-local-battle-settlement/replace.nut +++ b/gui-patches/battle/report-local-battle-settlement/replace.nut @@ -19,12 +19,31 @@ function buildWtoBattleReport(wtoBattle, res) { let sessionEnd = battleLog?.sessionEnd ?? lives.reduce(@(acc, life) life.end > acc ? life.end : acc, 0.0) blk.sessionStart = 0.0 blk.sessionEnd = sessionEnd.tofloat() + blk.localPlayerId = (require("mission").get_local_mplayer()?.id ?? -1).tointeger() let livesBlk = blk.addNewBlock("lives") foreach (life in lives) { let lifeBlk = livesBlk.addNewBlock("life") lifeBlk.unit = life.unit lifeBlk.start = life.start.tofloat() lifeBlk.end = life.end.tofloat() + lifeBlk.died = life?.died ?? false + } + let feedBlk = blk.addNewBlock("feed") + foreach (kill in (battleLog?.feed ?? [])) { + let killBlk = feedBlk.addNewBlock("k") + killBlk.time = kill.time.tofloat() + foreach (key in ["killer", "killerTeam", "victim", "victimTeam"]) + killBlk[key] = kill[key].tointeger() + } + // The final scoreboard, for the awards given to the best player of the battle. + let playersBlk = blk.addNewBlock("players") + foreach (player in (res?.mplayers_list ?? [])) { + let playerBlk = playersBlk.addNewBlock("p") + playerBlk.id = (player?.id ?? -1).tointeger() + playerBlk.team = (player?.team ?? 0).tointeger() + foreach (key in ["score", "kills", "groundKills", "humanKills", "navalKills", "aiKills", "aiGroundKills", + "aiNavalKills", "assists", "deaths"]) + playerBlk[key] = (player?[key] ?? 0).tointeger() } let eventsBlk = blk.addNewBlock("events") foreach (ev in (battleLog?.events ?? [])) { diff --git a/packages/local-service/src/battle/battle-debriefing.ts b/packages/local-service/src/battle/battle-debriefing.ts index 3bb9237..4312659 100644 --- a/packages/local-service/src/battle/battle-debriefing.ts +++ b/packages/local-service/src/battle/battle-debriefing.ts @@ -22,7 +22,14 @@ import type { BattleRpResult } from './battle-rp-investment.ts'; const STATS_RESULT_SUCCESS = 1; const STATS_RESULT_FAIL = 2; -export function debriefingTable(name: string, rewards: BattleRewards, research: BattleRpResult): BlkBlock { +/** 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; +} + +export function debriefingTable(name: string, rewards: BattleRewards, research: BattleRpResult, unlocks: UnlockRewards): BlkBlock { const root = emptyBlock(name); const rootRows = new Map(); for (const vehicle of rewards.vehicles) { @@ -36,7 +43,10 @@ export function debriefingTable(name: string, rewards: BattleRewards, research: setParam(root, 'activity', { type: 'real', value: rewards.activity }); setParam(root, 'sessionTime', { type: 'real', value: rewards.sessionTime }); setParam(root, 'battleTime', { type: 'real', value: rewards.battleTime }); - writeRows(root, rootRows, rewards.wpTotal, rewards.expTotal); + if (unlocks.count > 0) { + rootRows.set('Unlocks', { count: unlocks.count, noBonusWp: unlocks.wp, noBonusExp: unlocks.exp, premAccWp: 0, premAccExp: 0, premModExp: 0 }); + } + writeRows(root, rootRows, rewards.wpTotal + unlocks.wp, 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 }); diff --git a/packages/local-service/src/battle/battle-live-log.ts b/packages/local-service/src/battle/battle-live-log.ts new file mode 100644 index 0000000..9917a0a --- /dev/null +++ b/packages/local-service/src/battle/battle-live-log.ts @@ -0,0 +1,35 @@ +/** + * 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[]; + /** Keys of the awards already announced (battle-streaks.ts AwardedStreak.key). */ + readonly announced: Set; +} + +export class BattleLiveLogs { + readonly #logs = new Map(); + 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: [], announced: new Set() }; + this.#logs.set(sessionId, log); + while (this.#logs.size > this.#maxRetained) this.#logs.delete(this.#logs.keys().next().value!); + } + return log; + } +} diff --git a/packages/local-service/src/battle/battle-report.ts b/packages/local-service/src/battle/battle-report.ts index acb43d0..ae780c0 100644 --- a/packages/local-service/src/battle/battle-report.ts +++ b/packages/local-service/src/battle/battle-report.ts @@ -5,9 +5,16 @@ * * sessionId:t outcome:t ("win" | "lose" | "running") localTeam:i * teamAScore:i teamBScore:i sessionStart:r sessionEnd:r (mission time, seconds) - * lives{ life{ unit:t start:r end:r } ... } one per spawn of the local player + * 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 * spares{ :i ... } backup vehicles used */ import { findBlock, type BlkBlock } from '@wto/blk'; @@ -19,8 +26,39 @@ 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; @@ -36,8 +74,11 @@ export interface BattleReport { 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[]; readonly usedSpares: Readonly>; } @@ -52,7 +93,7 @@ export function parseBattleReport(payload: BlkBlock): BattleReport | undefined { 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 }] : []; + 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[] => { @@ -78,8 +119,21 @@ export function parseBattleReport(payload: BlkBlock): BattleReport | undefined { 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>, + })), usedSpares: parseSpareMap(findBlock(payload, 'spares')), }; } diff --git a/packages/local-service/src/battle/battle-result-log.ts b/packages/local-service/src/battle/battle-result-log.ts index 46e49fe..9dae569 100644 --- a/packages/local-service/src/battle/battle-result-log.ts +++ b/packages/local-service/src/battle/battle-result-log.ts @@ -21,6 +21,8 @@ export interface EarnedRpItem { 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>; readonly rpItems: readonly EarnedRpItem[]; @@ -79,7 +81,7 @@ export function appendBattleResultLog(profile: BlkBlock, session: BattleSession, ...(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 } }, + { 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 } }, ...(friendlyFirePenalty !== 0 ? [{ name: 'friendlyFirePenalty', value: { type: 'int' as const, value: friendlyFirePenalty } }] : []), diff --git a/packages/local-service/src/battle/battle-rewards.ts b/packages/local-service/src/battle/battle-rewards.ts index 8248e20..3f05430 100644 --- a/packages/local-service/src/battle/battle-rewards.ts +++ b/packages/local-service/src/battle/battle-rewards.ts @@ -24,7 +24,7 @@ import type { EconomyDifficulty } from '../game-data/datasets/battle-economy.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'; +export type RewardRow = DebriefingRow | 'BattleTime' | 'TimedAward' | 'Mission' | 'Unlocks'; export interface RowRewards { count: number; diff --git a/packages/local-service/src/battle/battle-settlement.ts b/packages/local-service/src/battle/battle-settlement.ts index 3ca5bc0..8d75cce 100644 --- a/packages/local-service/src/battle/battle-settlement.ts +++ b/packages/local-service/src/battle/battle-settlement.ts @@ -25,6 +25,8 @@ import type { BattleReport } from './battle-report.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'; /** Talisman modification name (scripts/airinfo.nut shopIsModificationEnabled(unit, "premExpMul")). */ @@ -36,6 +38,7 @@ export interface BattleSettlementDeps { readonly equipment: EquipmentCatalogue; readonly crew: CrewSkillCatalogue; readonly economy: BattleEconomy; + readonly streaks: BattleStreaks; } export function settleBattle(profile: BlkBlock, report: BattleReport, session: BattleSession, deps: BattleSettlementDeps): void { @@ -48,7 +51,13 @@ export function settleBattle(profile: BlkBlock, report: BattleReport, session: B hasTalisman: (vehicle) => deps.economy.isPremiumVehicle(vehicle) || ownsModification(profile, vehicle, TALISMAN), }); - applyNetSilverLions(profile, rewards.wpTotal); + const streaks = deps.streaks.evaluate(report, session); + 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) { @@ -62,10 +71,12 @@ export function settleBattle(profile: BlkBlock, report: BattleReport, session: B difficulty, nowUnixSec: serverTimeToUnixSeconds(now), }, deps); - const debriefing = debriefingTable('wtoDebriefing', rewards, research); + const debriefing = debriefingTable('wtoDebriefing', rewards, research, unlocks); + 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), diff --git a/packages/local-service/src/battle/battle-streak-log.ts b/packages/local-service/src/battle/battle-streak-log.ts new file mode 100644 index 0000000..64d4920 --- /dev/null +++ b/packages/local-service/src/battle/battle-streak-log.ts @@ -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, 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 }); + } +} diff --git a/packages/local-service/src/battle/battle-streaks.ts b/packages/local-service/src/battle/battle-streaks.ts new file mode 100644 index 0000000..12704d3 --- /dev/null +++ b/packages/local-service/src/battle/battle-streaks.ts @@ -0,0 +1,454 @@ +/** + * 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//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 + * 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 all listed awards earned in the battle + * Not supported (the facts are not reported): finalBlow, lastManStanding, killWithoutHit, + * hitWithoutDeath, killWithoutMiss, landings, scout / repair / extinguish help, squad awards, + * 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, 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[]; + readonly localPlayerId: number; + readonly localTeam: number; + /** The final scoreboard; absent while the battle runs (after-battle awards are then skipped). */ + readonly players?: readonly ScoreboardPlayer[]; + 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; + /** 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> = { arcade: 0, historical: 1, simulation: 2 }; +const MUL_NAMES = ['mulArcade', 'mulRealistic', 'mulHardcore'] as const; +const KILL_CODES: ReadonlySet = 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> = { + 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> = { + 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(); + 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, ...(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 '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 needed = (def.mode?.params.unlock ?? []).map(String); + if (needed.length > 0 && needed.every((id) => occurrences.has(id))) 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> = { 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; + 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): 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; + }, + }); + } +} diff --git a/packages/local-service/src/char/actions/battle-actions.ts b/packages/local-service/src/char/actions/battle-actions.ts index dd14196..50185d5 100644 --- a/packages/local-service/src/char/actions/battle-actions.ts +++ b/packages/local-service/src/char/actions/battle-actions.ts @@ -8,6 +8,7 @@ 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 type { CrewSkillCatalogue } from '../../crew/crew-skill-rules.ts'; import type { EquipmentCatalogue } from '../../modifications/equipment-catalogue.ts'; import { clientProfile } from '../../profile/client-profile.ts'; @@ -21,6 +22,7 @@ export interface BattleActionDependencies { readonly sessions: BattleSessionStore; readonly economy: BattleEconomy; readonly efficiency: ResearchEfficiency; + readonly streaks: BattleStreaks; } export interface FinishBattleContext { @@ -38,6 +40,7 @@ export function finishBattleAction(ctx: FinishBattleContext, battle: BattleActio equipment: ctx.equipment, crew: ctx.crew, economy: battle.economy, + streaks: battle.streaks, }; return (context) => withAccount(context, ctx.accounts, (account) => { const report = context.payload && parseBattleReport(context.payload); diff --git a/packages/local-service/src/game-data/datasets/battle-streaks.ts b/packages/local-service/src/game-data/datasets/battle-streaks.ts new file mode 100644 index 0000000..e53cb59 --- /dev/null +++ b/packages/local-service/src/game-data/datasets/battle-streaks.ts @@ -0,0 +1,120 @@ +/** + * 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 condition{ type:t } ... } + * } + * + * Three-value parameters (p3 / ip3) are per difficulty: arcade, realistic, simulator. Hidden + * awards are left out: the stock client does not show them (scripts/unlocks isUnlockVisible). + * 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>; + +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 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 = { + id: 'battle-streaks', + version: 1, + 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' || params.hidden?.[0] === true) 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, + 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: modeOf(mode) } : {}), + }]; + }), +}; + +function modeOf(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 { + const out: Record = {}; + 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]; +} diff --git a/packages/local-service/src/local-service.ts b/packages/local-service/src/local-service.ts index c9a76ec..94afbf4 100644 --- a/packages/local-service/src/local-service.ts +++ b/packages/local-service/src/local-service.ts @@ -18,6 +18,9 @@ import { battleEconomy } from './game-data/datasets/battle-economy.ts'; import { battleSpawnRules } from './game-data/datasets/battle-spawn-rules.ts'; import { researchEfficiency } from './game-data/datasets/research-efficiency.ts'; import { ResearchEfficiency } from './research/research-efficiency.ts'; +import { battleStreaks } from './game-data/datasets/battle-streaks.ts'; +import { BattleStreaks } from './battle/battle-streaks.ts'; +import { BattleLiveLogs } from './battle/battle-live-log.ts'; import { clanEconomy } from './game-data/datasets/clan-economy.ts'; import { crewSkillData } from './game-data/datasets/crew-skills.ts'; import { DatasetCache } from './game-data/datasets/dataset-cache.ts'; @@ -86,6 +89,7 @@ export async function startLocalService(options: LocalServiceOptions): Promise vehicle.goldenEagles > 0 || vehicle.premiumPack).map((vehicle) => vehicle.name)), ); + const streaks = new BattleStreaks(streakDefinitions, vehicles, economy); + const router = new Router([ webUi, new StoreService(accounts, profiles, catalogues.store, tuning.redeemCodes, options.port), @@ -124,7 +130,7 @@ export async function startLocalService(options: LocalServiceOptions): Promise matching?.notifyUser(userId, 'mrpc.generic_notify', payload), }, + battleLive: { sessions: battleSessions, liveLogs: new BattleLiveLogs(tuning.limits.battleSessionsKept), streaks }, }), log, loadOrCreateCredentials(options.dataFolder), diff --git a/packages/local-service/src/matching/battle-live-requests.ts b/packages/local-service/src/matching/battle-live-requests.ts new file mode 100644 index 0000000..8d2a044 --- /dev/null +++ b/packages/local-service/src/matching/battle-live-requests.ts @@ -0,0 +1,80 @@ +/** + * Matching request `wto_battle.fact` (gui-patches/battle/record-local-battle-awards): one fact of a + * running LocalMP battle; the answer lists the battle awards it completed, which the client shows + * as the stock award banner (scripts/streaks.nut add_streak_message). Online the battle server + * sends those banners. + * + * params: sessionId:s localPlayerId:i localTeam:i kind:s, and by kind + * "event": time:f unit:s code:i expClass:s victim:s victimIsPlayer:b friendly:b modifier:s damage:i + * "life": unit:s start:f end:f died:b + * "kill": time:f killer:i killerTeam:i victim:i victimTeam:i + * answer: { streaks: [{ id:s stage:i (-1 = single-stage) stageParam:i wp:i exp:i }] } + */ +import type { BattleLiveLogs } from '../battle/battle-live-log.ts'; +import type { BattleSessionStore } from '../battle/battle-session-store.ts'; +import type { BattleStreaks } from '../battle/battle-streaks.ts'; +import type { MatchingRequestHandler } from './matching-requests.ts'; + +export interface BattleLiveDependencies { + readonly sessions: BattleSessionStore; + readonly liveLogs: BattleLiveLogs; + readonly streaks: BattleStreaks; +} + +export function battleLiveRequests(deps: BattleLiveDependencies): Array<[string, MatchingRequestHandler]> { + return [['wto_battle.fact', (request, connection) => { + const userId = connection.authenticatedUserId(); + const p = request.params; + const sessionId = typeof p.sessionId === 'string' ? p.sessionId.toLowerCase() : ''; + const session = userId ? deps.sessions.findForUser(sessionId, userId) : undefined; + if (!session || session.settled) return { streaks: [] }; + const log = deps.liveLogs.of(session.sessionId); + if (!recordFact(log, p)) return { streaks: [] }; + const awarded = deps.streaks.evaluate({ + events: log.events, + lives: log.lives, + feed: log.feed, + localPlayerId: int(p.localPlayerId, -1), + localTeam: int(p.localTeam, 0), + sessionEnd: Math.max(0, ...log.lives.map((life) => life.end), ...log.events.map((e) => e.time)), + }, session); + const fresh = awarded.filter((streak) => !log.announced.has(streak.key)); + for (const streak of fresh) log.announced.add(streak.key); + return { + streaks: fresh.map((streak) => ({ + id: streak.id, stage: streak.stage ?? -1, stageParam: streak.stageParam, wp: streak.wp, exp: streak.exp, + })), + }; + }]]; +} + +function recordFact(log: ReturnType, p: Readonly>): boolean { + switch (p.kind) { + case 'event': + log.events.push({ + time: num(p.time), unit: str(p.unit), code: int(p.code, -1), expClass: str(p.expClass), victim: str(p.victim), + victimIsPlayer: p.victimIsPlayer === true, friendly: p.friendly === true, modifier: str(p.modifier), damage: int(p.damage, 0), + }); + return true; + case 'life': + log.lives.push({ unit: str(p.unit), start: num(p.start), end: num(p.end), died: p.died === true }); + return true; + case 'kill': + log.feed.push({ time: num(p.time), killer: int(p.killer, -1), killerTeam: int(p.killerTeam, 0), victim: int(p.victim, -1), victimTeam: int(p.victimTeam, 0) }); + return true; + default: + return false; + } +} + +function str(value: unknown): string { + return typeof value === 'string' ? value : ''; +} + +function num(value: unknown): number { + return typeof value === 'number' && Number.isFinite(value) ? value : 0; +} + +function int(value: unknown, fallback: number): number { + return typeof value === 'number' && Number.isFinite(value) ? Math.trunc(value) : fallback; +} diff --git a/packages/local-service/src/matching/matching-requests.ts b/packages/local-service/src/matching/matching-requests.ts index f110fc7..5403bed 100644 --- a/packages/local-service/src/matching/matching-requests.ts +++ b/packages/local-service/src/matching/matching-requests.ts @@ -10,6 +10,7 @@ */ import type { AccountStore } from '../accounts/account-store.ts'; import type { GameModes } from '../game-modes/game-modes.ts'; +import { battleLiveRequests, type BattleLiveDependencies } from './battle-live-requests.ts'; import { battleQueueRequests, type BattleQueueDependencies } from './battle-queue-requests.ts'; import { fetchClustersList } from './cluster-list.ts'; import { gameModeRequests } from './game-modes-requests.ts'; @@ -37,9 +38,10 @@ export interface MatchingRules { readonly gameModes: GameModes; readonly accounts?: AccountStore; readonly battle?: BattleQueueDependencies; + readonly battleLive?: BattleLiveDependencies; } -export function matchingRequests({ gameModes, accounts, battle }: MatchingRules): MatchingRequestTable { +export function matchingRequests({ gameModes, accounts, battle, battleLive }: MatchingRules): MatchingRequestTable { return new Map([ ['mlogin.login', (request, session) => signIn(request, session, accounts)], ['wtmm_static.fetch_clusters_list', fetchClustersList], @@ -47,6 +49,7 @@ export function matchingRequests({ gameModes, accounts, battle }: MatchingRules) ['mrooms.leave_room', () => ({})], ...gameModeRequests(gameModes), ...(battle ? battleQueueRequests(battle) : []), + ...(battleLive ? battleLiveRequests(battleLive) : []), ]); }