diff --git a/apps/server/src/battle/battle-matchmaker.ts b/apps/server/src/battle/battle-matchmaker.ts index e93b68c..823582a 100644 --- a/apps/server/src/battle/battle-matchmaker.ts +++ b/apps/server/src/battle/battle-matchmaker.ts @@ -10,7 +10,7 @@ import type { BattleSpawnRulesData } from '../game-data/datasets/battle-spawn-ru 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, SINGLE_SPAWN, modeMaxRespawns } from '../game-modes/mode-definition.ts'; +import { MISSION_DIFFICULTY, SINGLE_SPAWN, UNLIMITED_RESPAWNS, modeMaxRespawns } 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'; @@ -73,6 +73,7 @@ export interface BattleLaunchPlan { readonly maxPlayers: number; readonly maxBots: number; readonly maxRespawns?: number; + readonly allowSpares: boolean; readonly tankBotRespawns: number; readonly airBotRespawns: number; readonly useTankBots: boolean; @@ -281,6 +282,7 @@ export class BattleMatchmaker { maxMrank, maxPlayers, maxBots, + allowSpares: declaration.multiSlot !== false && maxRespawns !== SINGLE_SPAWN && maxRespawns !== UNLIMITED_RESPAWNS, ...(maxRespawns === undefined ? {} : { maxRespawns }), tankBotRespawns: this.#tuning.tankBotRespawns, airBotRespawns: declaration.multiSlot === false ? SINGLE_SPAWN : this.#tuning.airBotRespawns, diff --git a/apps/server/src/battle/battle-mission-settings.ts b/apps/server/src/battle/battle-mission-settings.ts index bc4571d..a62b74a 100644 --- a/apps/server/src/battle/battle-mission-settings.ts +++ b/apps/server/src/battle/battle-mission-settings.ts @@ -72,7 +72,7 @@ export function battleMissionSettings(plan: BattleLaunchPlan, scores: Readonly:i ... } backup vehicles used + * spares{ spawn{ slot:i unit:t backup:t } ... } confirmed backup spawns */ import { findBlock, type BlkBlock } from '@wto/blk'; import type { CombatEventFact } from './battle-economy.ts'; +import type { BackupSpawn } from './battle-spares.ts'; export type BattleOutcomeKind = 'win' | 'lose' | 'running'; @@ -83,7 +84,7 @@ export interface BattleReport { readonly players: readonly ScoreboardPlayer[]; /** Mission times at which the local player's nuclear bombs exploded. */ readonly nuclearStrikes: readonly number[]; - readonly usedSpares: Readonly>; + readonly spareSpawns: readonly BackupSpawn[]; } /** Undefined when the report is malformed; lives and events that make no sense are dropped. */ @@ -139,19 +140,15 @@ export function parseBattleReport(payload: BlkBlock): BattleReport | undefined { ...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')), + spareSpawns: (findBlock(payload, 'spares')?.blocks ?? []).flatMap((block): BackupSpawn[] => { + const slot = intOf(block, 'slot', -1); + const unit = strOf(block, 'unit'); + const backup = strOf(block, 'backup'); + return slot >= 0 && unit && backup ? [{ slot, unit, backup }] : []; + }), }; } -function parseSpareMap(sparesBlk: BlkBlock | undefined): Record { - const out: Record = {}; - 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; diff --git a/apps/server/src/battle/battle-result-log.ts b/apps/server/src/battle/battle-result-log.ts index 588f684..d83e415 100644 --- a/apps/server/src/battle/battle-result-log.ts +++ b/apps/server/src/battle/battle-result-log.ts @@ -9,7 +9,8 @@ * container.aircraftsRepaired{ aname:t cost:i } and container.wpExpensesCompensation:i * (userlogviewdata.nut "damaged vehicles", "automatic repair", "expenses compensation"). */ -import { emptyBlock, setParam, type BlkBlock, type BlkParam } from '@wto/blk'; +import { emptyBlock, findBlock, setParam, type BlkBlock, type BlkParam } from '@wto/blk'; +import { intField, int64Field } from '../profile/blk-fields.ts'; 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'; @@ -18,6 +19,11 @@ 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 function hasBattleResultLog(profile: BlkBlock, roomId: bigint): boolean { + return findBlock(profile, 'userlogs')?.blocks.some((log) => + intField(log, 'type') === EULT_SESSION_RESULT && int64Field(log, 'roomId') === roomId) ?? false; +} + export interface EarnedRpItem { readonly unit: string; readonly modification?: string; diff --git a/apps/server/src/battle/battle-session-store.ts b/apps/server/src/battle/battle-session-store.ts index e7da90f..24bda5d 100644 --- a/apps/server/src/battle/battle-session-store.ts +++ b/apps/server/src/battle/battle-session-store.ts @@ -24,6 +24,8 @@ export interface BattleSession { readonly missionLocName?: string; readonly country: string; readonly startedAtSec: number; + /** Owned lineup slots that may use a backup in this session. Filled when launch is sent. */ + spareSlots?: ReadonlyMap; settled: boolean; } diff --git a/apps/server/src/battle/battle-settlement.ts b/apps/server/src/battle/battle-settlement.ts index 1326d3c..dd99412 100644 --- a/apps/server/src/battle/battle-settlement.ts +++ b/apps/server/src/battle/battle-settlement.ts @@ -35,6 +35,7 @@ import { autoRepairVehicles, damageBattleVehicles, expensesCompensation } from ' 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 { consumeBattleSpares } from './battle-spares.ts'; import { appendStreakLogs } from './battle-streak-log.ts'; import type { BattleStreaks } from './battle-streaks.ts'; import type { BattleSession } from './battle-session-store.ts'; @@ -121,13 +122,14 @@ export function settleBattle(profile: BlkBlock, report: BattleReport, session: B if (compensation > 0) addSilverLions(profile, compensation); const debriefing = debriefingTable('wtoDebriefing', rewards, research, unlocks, compensation); + const usedSpares = consumeBattleSpares(profile, session, report.spareSpawns, deps.items, deps.research.techTree); 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, + usedSpares, rpItems: mergeEarnedRpItems(research.rpItems), researchUnits: research.units, affectedBoosters: boosters.applied.map((booster) => booster.id), diff --git a/apps/server/src/battle/battle-spares.ts b/apps/server/src/battle/battle-spares.ts new file mode 100644 index 0000000..ae326b9 --- /dev/null +++ b/apps/server/src/battle/battle-spares.ts @@ -0,0 +1,51 @@ +import type { BlkBlock } from '@wto/blk'; +import type { ItemCatalogue } from '../items/item-catalogue.ts'; +import { applyUniversalSpares } from '../items/universal-spares.ts'; +import { dailySparesLeft, recordDailySpare, usedDailySpare } from '../profile/profile-daily-spares.ts'; +import { setSpareCount, spareCount } from '../profile/profile-vehicle-state.ts'; +import type { TechTree } from '../research/tech-tree.ts'; +import type { BattleSession } from './battle-session-store.ts'; + +/** LocalMP uses a source token for an attached backup and the stock UID for an inventory item. */ +const VEHICLE_BACKUP = 'vehicle'; +export const DAILY_BACKUP = 'daily_free_spare'; + +export interface BackupSpawn { + readonly slot: number; + readonly unit: string; + readonly backup: string; +} + +function receiptKey(session: BattleSession, slot: number): string { + return `${session.sessionId}_${slot}`; +} + +export function recordDailyBackupSpawn(profile: BlkBlock, session: BattleSession, spawn: BackupSpawn): boolean { + return spawn.backup === DAILY_BACKUP && session.spareSlots?.get(spawn.slot) === spawn.unit + && recordDailySpare(profile, session.startedAtSec, receiptKey(session, spawn.slot)); +} + +/** Debit confirmed backup spawns from the lineup that the server sent at launch. */ +export function consumeBattleSpares( + profile: BlkBlock, session: BattleSession, spawns: readonly BackupSpawn[], items: ItemCatalogue, techTree: TechTree, +): Readonly> { + const seenSlots = new Set(); + const consumed = new Map(); + for (const spawn of spawns) { + const { slot, unit, backup } = spawn; + if (session.spareSlots?.get(slot) !== unit || seenSlots.has(slot)) continue; + seenSlots.add(slot); + if (backup === DAILY_BACKUP) { + recordDailyBackupSpawn(profile, session, spawn); + continue; + } + if (dailySparesLeft(profile, session.startedAtSec) > 0 + || usedDailySpare(profile, session.startedAtSec, receiptKey(session, slot))) continue; + if (backup !== VEHICLE_BACKUP && !applyUniversalSpares(profile, items, techTree, backup, unit, 1).ok) continue; + const owned = spareCount(profile, unit); + if (owned < 1) continue; + setSpareCount(profile, unit, owned - 1); + consumed.set(unit, (consumed.get(unit) ?? 0) + 1); + } + return Object.fromEntries(consumed); +} diff --git a/apps/server/src/char/actions/battle-actions.ts b/apps/server/src/char/actions/battle-actions.ts index 47f8499..c99ab72 100644 --- a/apps/server/src/char/actions/battle-actions.ts +++ b/apps/server/src/char/actions/battle-actions.ts @@ -6,6 +6,7 @@ import type { BattleSettlementContext } from '@wto/mods'; import type { AccountStore } from '../../accounts/account-store.ts'; import { parseBattleReport } from '../../battle/battle-report.ts'; +import { hasBattleResultLog } from '../../battle/battle-result-log.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'; @@ -62,15 +63,19 @@ export function finishBattleAction(ctx: FinishBattleContext, battle: BattleActio if (session.settled) { return { kind: 'data', blk: clientProfile(ctx.profiles.profileOf(account.userId), account) }; } - const updated = ctx.profiles.update(account.userId, (profile) => { + const updated = ctx.profiles.updateWhen(account.userId, (profile) => { + // The result log and expenses are written together. A retry can arrive after the profile + // was saved but before the session was marked settled. + if (hasBattleResultLog(profile, session.roomId)) return false; settleBattle(profile, report, session, settlementDeps); battle.onAfterSettle?.({ userId: account.userId, roomId: session.sessionId, summary: { profile, report, session }, }); + return true; }); battle.sessions.markSettled(session.sessionId); - return { kind: 'data', blk: clientProfile(updated, account) }; + return { kind: 'data', blk: clientProfile(updated ?? ctx.profiles.profileOf(account.userId), account) }; }); } diff --git a/apps/server/src/matching/battle-launch-notify.ts b/apps/server/src/matching/battle-launch-notify.ts index ba56f96..932b74c 100644 --- a/apps/server/src/matching/battle-launch-notify.ts +++ b/apps/server/src/matching/battle-launch-notify.ts @@ -32,10 +32,16 @@ export interface BattleLaunchNotify extends Record { readonly battle: Readonly>; } +export interface BattleBackupAllowance { + readonly daily: number; + readonly vehicles: Readonly>; +} + export function battleLaunchNotify( plan: BattleLaunchPlan, awards: BannerParams, scores: Readonly>, + backups?: BattleBackupAllowance, ): BattleLaunchNotify { return { from: 'wto_battle', @@ -64,6 +70,7 @@ export function battleLaunchNotify( ...(plan.selectedSlot ? { selectedSlot: plan.selectedSlot } : {}), extraBattleSlots: plan.extraBattleSlots, ...(plan.spawnScore ? { spawnScore: plan.spawnScore } : {}), + ...(backups ? { backups } : {}), awards, }, }; diff --git a/apps/server/src/matching/battle-queue-requests.ts b/apps/server/src/matching/battle-queue-requests.ts index 385251e..e1b49fa 100644 --- a/apps/server/src/matching/battle-queue-requests.ts +++ b/apps/server/src/matching/battle-queue-requests.ts @@ -5,17 +5,21 @@ * - `match.leave_queue` (scripts/queue/queuestate.nut:28) * - `match.check_reconnect` */ +import type { BlkBlock } from '@wto/blk'; import type { BattleMatchmakeContext } from '@wto/mods'; import { MAX_BATTLE_CREW_SLOTS } from '../battle/battle-extra-slots.ts'; import { economyDifficulty, type BattleEconomy } from '../battle/battle-economy.ts'; import type { BattleMatchmaker } from '../battle/battle-matchmaker.ts'; import { maxModeMrank, unitClassOfExpClass, unitClassOfTypeCode, type CraftRankEntry } from '../battle/battle-ranks.ts'; -import type { BattleSessionStore } from '../battle/battle-session-store.ts'; +import type { BattleSession, BattleSessionStore } from '../battle/battle-session-store.ts'; +import { DAILY_BACKUP, recordDailyBackupSpawn } from '../battle/battle-spares.ts'; import type { GameModes, OfferedGameMode } from '../game-modes/game-modes.ts'; import { crewSlotVehicleOfCountry, crewVehiclesOfCountry } from '../profile/profile-crews.ts'; +import { dailySparesLeft } from '../profile/profile-daily-spares.ts'; import { vehicleMrankDelta } from '../profile/profile-hangar.ts'; +import { spareCount } from '../profile/profile-vehicle-state.ts'; import type { PlayerProfiles } from '../profile/player-profiles.ts'; -import { battleLaunchNotify, type BattleLaunchNotify } from './battle-launch-notify.ts'; +import { battleLaunchNotify, type BattleBackupAllowance, type BattleLaunchNotify } from './battle-launch-notify.ts'; import type { MatchingRequestHandler } from './matching-requests.ts'; export interface BattleQueueDependencies { @@ -38,6 +42,18 @@ export function battleQueueRequests(deps: BattleQueueDependencies): Array<[strin return {}; }], ['match.check_reconnect', () => ({})], + ['wto_battle.daily_spare', ({ params }, connection) => { + const userId = connection.authenticatedUserId(); + if (!userId) return { error: 'AUTH_REQ_ERROR' }; + const { sessionId, slot, unit } = params; + if (typeof sessionId !== 'string' || typeof slot !== 'number' || typeof unit !== 'string') { + return { error: 'BAD_PARAMS' }; + } + const battle = deps.sessions.findForUser(sessionId, userId); + if (!battle || battle.settled || battle.spareSlots?.get(slot) !== unit) return { error: 'BAD_PARAMS' }; + deps.profiles.updateWhen(userId, (profile) => recordDailyBackupSpawn(profile, battle, { slot, unit, backup: DAILY_BACKUP })); + return {}; + }], ]; } @@ -119,11 +135,25 @@ function handleEnqueue( const battle = deps.sessions.findForUser(launch.sessionId, userId); if (!battle) return; const awards = deps.economy.bannerParams(playerVehicles, economyDifficulty(battle.difficulty), battle.modeName); - deps.notifyLaunch(userId, battleLaunchNotify(launch, awards, deps.economy.missionScores(battle.modeName))); + const backups = launch.allowSpares ? configureBattleBackups(battle, profile) : undefined; + deps.notifyLaunch(userId, battleLaunchNotify(launch, awards, deps.economy.missionScores(battle.modeName), backups)); }); return {}; } +function configureBattleBackups(battle: BattleSession, profile: BlkBlock): BattleBackupAllowance { + const slots = new Map(); + for (let slot = 0; slot < MAX_BATTLE_CREW_SLOTS; slot++) { + const unit = crewSlotVehicleOfCountry(profile, battle.country, slot); + if (unit) slots.set(slot, unit); + } + battle.spareSlots = slots; + return { + daily: dailySparesLeft(profile, battle.startedAtSec), + vehicles: Object.fromEntries([...slots.values()].map((unit) => [unit, spareCount(profile, unit)])), + }; +} + function parsePlayerCrafts(rawCrafts: unknown): CraftRankEntry[] { if (!Array.isArray(rawCrafts)) return []; return rawCrafts.flatMap((craft): CraftRankEntry[] => { diff --git a/apps/server/src/profile/client-profile.ts b/apps/server/src/profile/client-profile.ts index fd05d8c..da812bc 100644 --- a/apps/server/src/profile/client-profile.ts +++ b/apps/server/src/profile/client-profile.ts @@ -11,15 +11,18 @@ import { setParam, type BlkBlock } from '@wto/blk'; import type { Account } from '../accounts/account-store.ts'; import { appearance, DEFAULT_PILOT_ICON } from './profile-appearance.ts'; +import { DAILY_SPARES_BLOCK } from './profile-daily-spares.ts'; import { clearStoreCart } from './profile-store-cart.ts'; +import { clientHangarSpares } from './profile-vehicle-state.ts'; import { serverTimeNow } from './server-time.ts'; export function clientProfile(saved: BlkBlock, account: Account): BlkBlock { - // Shallow-copy only the top-level lists; child blocks are never mutated here. + // Clone the hangar entries whose spare count has a different wire representation. const profile: BlkBlock = { name: saved.name, params: [...saved.params], - blocks: [...saved.blocks], + blocks: saved.blocks.filter((block) => block.name !== DAILY_SPARES_BLOCK) + .map((block) => block.name === 'hangar' ? clientHangarSpares(block) : block), }; clearStoreCart(profile); const pilotIcon = appearance(profile).pilotIcon || DEFAULT_PILOT_ICON; diff --git a/apps/server/src/profile/profile-daily-spares.ts b/apps/server/src/profile/profile-daily-spares.ts new file mode 100644 index 0000000..50db6a4 --- /dev/null +++ b/apps/server/src/profile/profile-daily-spares.ts @@ -0,0 +1,33 @@ +import { ensureBlock, findBlock, findParam, setParam, type BlkBlock } from '@wto/blk'; + +export const DAILY_SPARES_BLOCK = 'wtoDailySpares'; + +// Stock quota from the Spearhead release notes and aces.exe 2.61.0.58 at 0x967a8d. +const FREE_SPARES_PER_DAY = 5; +const DAY_SECONDS = 24 * 60 * 60; + +function utcDay(seconds: number): string { + return String(Math.floor(seconds / DAY_SECONDS)); +} + +function dayOf(profile: BlkBlock, startedAtSec: number): BlkBlock | undefined { + const ledger = findBlock(profile, DAILY_SPARES_BLOCK); + return ledger && findBlock(ledger, utcDay(startedAtSec)); +} + +export function dailySparesLeft(profile: BlkBlock, startedAtSec: number): number { + return Math.max(0, FREE_SPARES_PER_DAY - (dayOf(profile, startedAtSec)?.params.length ?? 0)); +} + +export function usedDailySpare(profile: BlkBlock, startedAtSec: number, key: string): boolean { + const day = dayOf(profile, startedAtSec); + return day !== undefined && findParam(day, key) !== undefined; +} + +/** One receipt per room and crew slot, shared by the live and settlement writes. */ +export function recordDailySpare(profile: BlkBlock, startedAtSec: number, key: string): boolean { + if (usedDailySpare(profile, startedAtSec, key) || dailySparesLeft(profile, startedAtSec) === 0) return false; + const day = ensureBlock(ensureBlock(profile, DAILY_SPARES_BLOCK), utcDay(startedAtSec)); + setParam(day, key, { type: 'bool', value: true }); + return true; +} diff --git a/apps/server/src/profile/profile-vehicle-state.ts b/apps/server/src/profile/profile-vehicle-state.ts index c70dbeb..ae0f9f8 100644 --- a/apps/server/src/profile/profile-vehicle-state.ts +++ b/apps/server/src/profile/profile-vehicle-state.ts @@ -5,7 +5,7 @@ * investMode:t the modification being researched, empty = none (AircraftInfo+0x100) * investModePrev:t the modification whose research just finished (+0x108) * tierNumber:i the highest open modification tier (script is_tier_available) - * spareAircraftsCount:i spares the player has for this vehicle + * spareAircraftsCount:i owned spares in the saved profile, encoded as a negative i64 on the wire * excessExp:i64 banked modification research points (+0x70) * freeRepairs:i64 free repairs used (0x941cef; shop_get_free_repairs_used at 0x17a4b80) */ @@ -55,6 +55,19 @@ export function setSpareCount(profile: BlkBlock, vehicle: string, count: number) if (entry) setParam(entry, SPARES, { type: 'int', value: count }); } +/** SpareAircraftStat reads i64 and clears positive values. The getter negates the stat + * (aces.exe 2.61.0.58 0x9447bb, 0x94f7ab, 0x17abe70). */ +export function clientHangarSpares(hangar: BlkBlock): BlkBlock { + const blocks = hangar.blocks.map((vehicle) => { + const count = findParam(vehicle, SPARES)?.value; + if (count?.type !== 'int') return vehicle; + const clientVehicle = { ...vehicle, params: [...vehicle.params] }; + setParam(clientVehicle, SPARES, { type: 'int64', value: -BigInt(count.value) }); + return clientVehicle; + }); + return { ...hangar, blocks }; +} + /** Uses one free repair on an owned vehicle if it still has an allowance. */ export function consumeFreeRepair(profile: BlkBlock, vehicle: string, allowance: number): boolean { const entry = vehicleEntry(profile, vehicle); diff --git a/native/wto-net/src/local_mp_awards.c b/native/wto-net/src/local_mp_awards.c index 5645fc2..a82c1cc 100644 --- a/native/wto-net/src/local_mp_awards.c +++ b/native/wto-net/src/local_mp_awards.c @@ -110,6 +110,22 @@ void local_mp_report_airfield_spawn(const char *unit_name, int32_t base_id) fn_blk_dtor(blk); } +void local_mp_report_backup_spawn(const char *unit_name, int32_t slot_id, const char *backup) +{ + __declspec(align(16)) uint8_t blk[LMP_BLK_SIZE]; + uint8_t *gsd = g_game_save_data ? *g_game_save_data : NULL; + + if (gsd == NULL || fn_hud_notify_script == NULL || unit_name == NULL) + return; + memset(blk, 0, sizeof(blk)); + fn_blk_ctor(blk); + fn_blk_set_str(blk, "unit", unit_name); + fn_blk_set_str(blk, "backup", backup); + blk_set_int(blk, "slot", slot_id); + fn_hud_notify_script(gsd + LMP_GSD_OFF_HUD_QUEUE, "wtoLocalMpBackupSpawn", blk); + fn_blk_dtor(blk); +} + int install_local_mp_award_hooks(void) { g_game_save_data = (uint8_t **)g_lmp.game_save_data; diff --git a/native/wto-net/src/local_mp_internal.h b/native/wto-net/src/local_mp_internal.h index f5f3fad..a0c84b6 100644 --- a/native/wto-net/src/local_mp_internal.h +++ b/native/wto-net/src/local_mp_internal.h @@ -58,12 +58,13 @@ char *local_mp_strdup(const char *s); const char *local_mp_unit_name(const uint8_t *unit); /* Player state & slot tracking notifications shared with loadout module. */ -void local_mp_players_queue_spawn(int32_t slot_id, int32_t spare_type, int32_t base_id, int is_silent); +void local_mp_players_queue_spawn(int32_t slot_id, int32_t spare_type, int32_t base_id, const char *backup, int is_silent); /* Local player events sent to the GUI scripts (local_mp_awards.c). */ void local_mp_report_award_event(const LocalMpAwardEvent *ev); void local_mp_report_nuclear_strike(void); void local_mp_report_airfield_spawn(const char *unit_name, int32_t base_id); +void local_mp_report_backup_spawn(const char *unit_name, int32_t slot_id, const char *backup); /* A destroyed unit that is some player's mission support unit: its reference is freed once the * player has been given back control (local_mp_support.c). */ diff --git a/native/wto-net/src/local_mp_loadout.c b/native/wto-net/src/local_mp_loadout.c index 3c4e1ad..908b426 100644 --- a/native/wto-net/src/local_mp_loadout.c +++ b/native/wto-net/src/local_mp_loadout.c @@ -287,7 +287,9 @@ static void __fastcall hook_sem_change_aircraft_send( mplayer[LMP_MP_OFF_GUI_STATE] != LMP_GUI_STATE_CA_READY) g_lmp_set_player_gui_state((int32_t)mplayer[LMP_MP_OFF_PID], LMP_GUI_STATE_CA_READY); - local_mp_players_queue_spawn(req_slot_id, req_spare_type, req_base_id, is_silent); + const char *backup = !is_silent && modifications_blk != NULL + ? g_lmp_datablock_get_str(modifications_blk, "wtoBackup", "") : NULL; + local_mp_players_queue_spawn(req_slot_id, req_spare_type, req_base_id, backup, is_silent); log_line("local_mp: configured unit='%s' weapon='%s' slot=%d silent=%d", unit_name ? unit_name : "", weapon_name ? weapon_name : "", (int)req_slot_id, is_silent); } diff --git a/native/wto-net/src/local_mp_players.c b/native/wto-net/src/local_mp_players.c index 55e1316..fc82a55 100644 --- a/native/wto-net/src/local_mp_players.c +++ b/native/wto-net/src/local_mp_players.c @@ -26,13 +26,30 @@ static int g_respawn_dispatched = 0; static int32_t g_pending_slot_id = -1; static int32_t g_pending_spare_type = -1; static int32_t g_pending_base_id = -1; +/* Holds the source token or a classic inventory UID (item_%016llx_%x). */ +static char g_pending_backup[64]; -void local_mp_players_queue_spawn(int32_t slot_id, int32_t spare_type, int32_t base_id, int is_silent) +static void clear_pending_spawn(void) +{ + g_respawn_dispatched = 0; + g_pending_slot_id = -1; + g_pending_spare_type = -1; + g_pending_base_id = -1; + g_pending_backup[0] = '\0'; +} + +void local_mp_players_queue_spawn(int32_t slot_id, int32_t spare_type, int32_t base_id, const char *backup, int is_silent) { if (!is_silent || g_pending_slot_id < 0) { + size_t length = backup ? strlen(backup) : 0; g_pending_slot_id = slot_id; g_pending_spare_type = spare_type; g_pending_base_id = base_id; + g_pending_backup[0] = '\0'; + if (length > 0 && length < sizeof(g_pending_backup)) + memcpy(g_pending_backup, backup, length + 1); + } else if (slot_id != g_pending_slot_id) { + g_pending_backup[0] = '\0'; } if (!is_silent) g_respawn_dispatched = 0; @@ -112,6 +129,8 @@ static void __fastcall hook_mplayer_init_from_matching(uint8_t *mplayer, uint8_t *(int32_t *)(info + LMP_MATCH_INFO_OFF_SQUAD_ID) = 1; local_mp_events_reset(); local_mp_zones_reset(); + g_accept_pending = 0; + clear_pending_spawn(); log_line("local_mp: initialized local player team=%d squad=%d", (int)(*(int32_t *)(info + LMP_MATCH_INFO_OFF_TEAM)), (int)(*(int32_t *)(info + LMP_MATCH_INFO_OFF_SQUAD_ID))); @@ -136,20 +155,22 @@ static void finish_pending_spawn(uint8_t *mplayer) if (!g_respawn_dispatched || mplayer == NULL) return; if (mplayer[LMP_MP_OFF_GUI_STATE] == LMP_GUI_STATE_CA_SELECT) { - g_respawn_dispatched = 0; + clear_pending_spawn(); return; } if (mplayer[LMP_MP_OFF_GUI_STATE] != LMP_GUI_STATE_PILOT_CONTROL) return; - g_respawn_dispatched = 0; hero_name = g_local_mp_hero ? local_mp_unit_name(*g_local_mp_hero) : NULL; if (g_pending_slot_id >= 0 && g_pending_slot_id < 32) { uint32_t bit = 1u << (uint32_t)g_pending_slot_id; if (has_unlimited_respawns()) local_mp_report_airfield_spawn(hero_name, g_pending_base_id); - else if (g_pending_spare_type < 0) + else if (g_pending_backup[0] != '\0') { + *(uint32_t *)(mplayer + LMP_MP_OFF_USED_SPARES_MASK) |= bit; + local_mp_report_backup_spawn(hero_name, g_pending_slot_id, g_pending_backup); + } else if (g_pending_spare_type < 0) *(uint32_t *)(mplayer + LMP_MP_OFF_BROKEN_SLOTS_MASK) |= bit; else *(uint32_t *)(mplayer + LMP_MP_OFF_USED_SPARES_MASK) |= bit; @@ -157,9 +178,8 @@ static void finish_pending_spawn(uint8_t *mplayer) hero_name ? hero_name : "", (int)g_pending_slot_id, (int)g_pending_spare_type, *(uint32_t *)(mplayer + LMP_MP_OFF_BROKEN_SLOTS_MASK), *(uint32_t *)(mplayer + LMP_MP_OFF_USED_SPARES_MASK)); - g_pending_slot_id = -1; - g_pending_base_id = -1; } + clear_pending_spawn(); } static void __fastcall hook_gui_state_update(uint8_t *gui_state_obj, float dt) @@ -171,9 +191,7 @@ static void __fastcall hook_gui_state_update(uint8_t *gui_state_obj, float dt) if (!local_mp_is_host()) { g_accept_pending = 0; - g_respawn_dispatched = 0; - g_pending_slot_id = -1; - g_pending_base_id = -1; + clear_pending_spawn(); return; } @@ -206,6 +224,8 @@ static int64_t __fastcall hook_do_respawn_player(void *app) g_respawn_dispatched = 1; result = orig_do_respawn(app); + if (!result) + g_respawn_dispatched = 0; finish_pending_spawn(mplayer); bind_ai_mplayer_units(); return result; diff --git a/patches/gui/battle/available-local-backups/find-availability.nut b/patches/gui/battle/available-local-backups/find-availability.nut new file mode 100644 index 0000000..92bc54a --- /dev/null +++ b/patches/gui/battle/available-local-backups/find-availability.nut @@ -0,0 +1,2 @@ +function canRespawnWithUniversalSpares(crew, unit) { + if (!hasFeature("ActivateUniversalSpareInBattle")) diff --git a/patches/gui/battle/available-local-backups/find-export.nut b/patches/gui/battle/available-local-backups/find-export.nut new file mode 100644 index 0000000..3fffb4f --- /dev/null +++ b/patches/gui/battle/available-local-backups/find-export.nut @@ -0,0 +1,2 @@ + getDailyFreeSparesLeftCount + canUseOnlyDailyFreeSpares diff --git a/patches/gui/battle/available-local-backups/find-quota.nut b/patches/gui/battle/available-local-backups/find-quota.nut new file mode 100644 index 0000000..4386509 --- /dev/null +++ b/patches/gui/battle/available-local-backups/find-quota.nut @@ -0,0 +1 @@ +let getDailyFreeSparesLeftCount = @() getNumFreeSparesPerDay() - getNumFreeSparesUsed() diff --git a/patches/gui/battle/available-local-backups/patch.jsonc b/patches/gui/battle/available-local-backups/patch.jsonc new file mode 100644 index 0000000..9be7ff1 --- /dev/null +++ b/patches/gui/battle/available-local-backups/patch.jsonc @@ -0,0 +1,17 @@ +// Offer backups on a consumed LocalMP lineup slot when a daily, attached or universal spare is available. +// The game reads slot masks in process. The local service sends the account's quota and balances at launch. +// Without this bridge, a consumed slot with only attached backups can be unavailable. +{ + "id": "battle/available-local-backups", + "title": "Use the local account's backup availability in battle", + "features": ["K-Spawn score and respawns"], + "variants": [{ + "written_for": "2.61.0.37", + "file": "scripts/respawn/respawnstate.nut", + "edits": [ + { "find": "find-quota.nut", "replace": "replace-quota.nut" }, + { "find": "find-availability.nut", "replace": "replace-availability.nut" }, + { "find": "find-export.nut", "replace": "replace-export.nut" } + ] + }] +} diff --git a/patches/gui/battle/available-local-backups/replace-availability.nut b/patches/gui/battle/available-local-backups/replace-availability.nut new file mode 100644 index 0000000..490af14 --- /dev/null +++ b/patches/gui/battle/available-local-backups/replace-availability.nut @@ -0,0 +1,19 @@ +// null means stock slot handling. An empty string means the local slot cannot use a backup. +function getWtoBackupSource(slot, unit) { + let vehicles = require("nestdb").ndbTryRead(["wto", "activeBattle"])?.backups?.vehicles + if (vehicles == null || unit == null || !(unit.name in vehicles) || !is_bit_set(getBrokenSlotsMask(), slot)) + return null + if (isSpareAircraftInSlot(slot) || is_bit_set(getDisabledByMatchingSlotsMask(), slot)) + return "" + if (hasDailyFreeSpares()) + return "daily" + if (vehicles[unit.name] > 0) + return "vehicle" + return getUniversalSparesForUnit(unit).len() > 0 ? "item" : "" +} + +function canRespawnWithUniversalSpares(crew, unit) { + let wtoSource = getWtoBackupSource(crew.idInCountry, unit) + if (wtoSource != null) + return wtoSource != "" + if (!hasFeature("ActivateUniversalSpareInBattle")) diff --git a/patches/gui/battle/available-local-backups/replace-export.nut b/patches/gui/battle/available-local-backups/replace-export.nut new file mode 100644 index 0000000..15f2515 --- /dev/null +++ b/patches/gui/battle/available-local-backups/replace-export.nut @@ -0,0 +1,3 @@ + getDailyFreeSparesLeftCount + canUseOnlyDailyFreeSpares + getWtoBackupSource diff --git a/patches/gui/battle/available-local-backups/replace-quota.nut b/patches/gui/battle/available-local-backups/replace-quota.nut new file mode 100644 index 0000000..82e4caa --- /dev/null +++ b/patches/gui/battle/available-local-backups/replace-quota.nut @@ -0,0 +1,8 @@ +function getDailyFreeSparesLeftCount() { + let { ndbTryRead } = require("nestdb") + let daily = ndbTryRead(["wto", "activeBattle"])?.backups?.daily + if (daily == null) + return getNumFreeSparesPerDay() - getNumFreeSparesUsed() + let used = ndbTryRead(["wto", "battleLog", "dailyBackupsUsed"]) ?? 0 + return max(0, daily - used) +} diff --git a/patches/gui/battle/pass-spawn-modifications-blk/find-backup-choice.nut b/patches/gui/battle/pass-spawn-modifications-blk/find-backup-choice.nut new file mode 100644 index 0000000..49f8a15 --- /dev/null +++ b/patches/gui/battle/pass-spawn-modifications-blk/find-backup-choice.nut @@ -0,0 +1,12 @@ + function openRespawnSpareWndIfNeeded(requestData) { + if (requestData.spareUid != "") + return false + + let crew = this.getCurCrew() + if (crew == null) + return false + + let unit = getAircraftByName(requestData.name) + let canUseOnlyDailySpares = canUseOnlyDailyFreeSpares(crew.idInCountry) + if (!canUseOnlyDailySpares && !isRespawnWithUniversalSpare(crew, unit)) + return false diff --git a/patches/gui/battle/pass-spawn-modifications-blk/find-confirm-spawn.nut b/patches/gui/battle/pass-spawn-modifications-blk/find-confirm-spawn.nut new file mode 100644 index 0000000..c54fc3f --- /dev/null +++ b/patches/gui/battle/pass-spawn-modifications-blk/find-confirm-spawn.nut @@ -0,0 +1,2 @@ + function doRespawn() { + log("doRespawnPlayer called") diff --git a/patches/gui/battle/pass-spawn-modifications-blk/find-used-item.nut b/patches/gui/battle/pass-spawn-modifications-blk/find-used-item.nut new file mode 100644 index 0000000..1d4b3e9 --- /dev/null +++ b/patches/gui/battle/pass-spawn-modifications-blk/find-used-item.nut @@ -0,0 +1,2 @@ + markUsedItemCount(itemType.UNIVERSAL_SPARE, this.lastRequestData.spareUid) + this.universalSpareUidForRespawn = "" diff --git a/patches/gui/battle/pass-spawn-modifications-blk/patch.jsonc b/patches/gui/battle/pass-spawn-modifications-blk/patch.jsonc index bcc8ed9..8087edc 100644 --- a/patches/gui/battle/pass-spawn-modifications-blk/patch.jsonc +++ b/patches/gui/battle/pass-spawn-modifications-blk/patch.jsonc @@ -1,5 +1,4 @@ -// Send the vehicle's enabled and disabled modifications with every LocalMP spawn request, and count -// backup vehicles used for the settlement. +// Send the vehicle's modifications and chosen backup source with each LocalMP spawn request. // Why the client: the battle server would read the modifications from the profile; on a LocalMP host // the native spawn receiver (wto_ws.dll local_mp_loadout.c) only gets what this request carries. // Without it: every spawned vehicle is stock (no fire extinguisher, smoke, repair kit, upgrades). @@ -17,7 +16,10 @@ { "find": "find.nut", "replace": "replace.nut" - } + }, + { "find": "find-backup-choice.nut", "replace": "replace-backup-choice.nut" }, + { "find": "find-confirm-spawn.nut", "replace": "replace-confirm-spawn.nut" }, + { "find": "find-used-item.nut", "replace": "replace-used-item.nut" } ] } ] diff --git a/patches/gui/battle/pass-spawn-modifications-blk/replace-backup-choice.nut b/patches/gui/battle/pass-spawn-modifications-blk/replace-backup-choice.nut new file mode 100644 index 0000000..5ce6b71 --- /dev/null +++ b/patches/gui/battle/pass-spawn-modifications-blk/replace-backup-choice.nut @@ -0,0 +1,44 @@ + function getWtoBackupSourceForRequest(requestData) { + let getSource = require("%scripts/respawn/respawnState.nut")?.getWtoBackupSource + return getSource == null ? null : getSource(requestData.idInCountry, getAircraftByName(requestData.name)) + } + + function getWtoBackupToken(requestData, source) { + if (source == null) + return "" + if (source == "vehicle") + return "vehicle" + let uid = requestData.spareUid + if (source == "daily") + return uid == DAILY_FREE_SPARE_UID ? uid : null + if (source == "item" && uid != "" && uid != DAILY_FREE_SPARE_UID) { + let unit = getAircraftByName(requestData.name) + if (getUniversalSparesForUnit(unit).findvalue(@(item) item.uids.contains(uid)) != null) + return uid + } + return null + } + + function openRespawnSpareWndIfNeeded(requestData) { + let wtoSource = this.getWtoBackupSourceForRequest(requestData) + if (wtoSource == "") { + showInfoMsgBox(loc("crew_not_available"), "crew_not_available") + return true + } + if (wtoSource == "vehicle") { + this.universalSpareUidForRespawn = "" + requestData.spareUid = "" + return false + } + if ((wtoSource == null && requestData.spareUid != "") + || (wtoSource != null && this.getWtoBackupToken(requestData, wtoSource) != null)) + return false + + let crew = this.getCurCrew() + if (crew == null) + return false + + let unit = getAircraftByName(requestData.name) + let canUseOnlyDailySpares = wtoSource == "daily" || (wtoSource == null && canUseOnlyDailyFreeSpares(crew.idInCountry)) + if (wtoSource == null && !canUseOnlyDailySpares && !isRespawnWithUniversalSpare(crew, unit)) + return false diff --git a/patches/gui/battle/pass-spawn-modifications-blk/replace-confirm-spawn.nut b/patches/gui/battle/pass-spawn-modifications-blk/replace-confirm-spawn.nut new file mode 100644 index 0000000..122aeed --- /dev/null +++ b/patches/gui/battle/pass-spawn-modifications-blk/replace-confirm-spawn.nut @@ -0,0 +1,14 @@ + function doRespawn() { + let request = this.lastRequestData + let source = request == null ? null : this.getWtoBackupSourceForRequest(request) + if (source != null) { + let backup = this.getWtoBackupToken(request, source) + if (backup == null || request?.wtoBackup != backup) { + this.lastRequestData = null + this.isApplyPressed = false + this.checkReady() + this.doSelectAircraft() + return + } + } + log("doRespawnPlayer called") diff --git a/patches/gui/battle/pass-spawn-modifications-blk/replace-used-item.nut b/patches/gui/battle/pass-spawn-modifications-blk/replace-used-item.nut new file mode 100644 index 0000000..a34da6f --- /dev/null +++ b/patches/gui/battle/pass-spawn-modifications-blk/replace-used-item.nut @@ -0,0 +1,3 @@ + if (this.lastRequestData?.wtoBackup == null) + markUsedItemCount(itemType.UNIVERSAL_SPARE, this.lastRequestData.spareUid) + this.universalSpareUidForRespawn = "" diff --git a/patches/gui/battle/pass-spawn-modifications-blk/replace.nut b/patches/gui/battle/pass-spawn-modifications-blk/replace.nut index d5112e2..1fd7089 100644 --- a/patches/gui/battle/pass-spawn-modifications-blk/replace.nut +++ b/patches/gui/battle/pass-spawn-modifications-blk/replace.nut @@ -86,11 +86,17 @@ wtoBlk.enabledMods = ";".join(wtoEnabledMods) wtoBlk.disabledMods = ";".join(wtoDisabledMods) wtoBlk.isSilentPreview = isSilent ? "1" : "0" - if (!isSilent && (requestData?.spareUid ?? "") != "" && wtoUnitName != "") { - let prevSpares = wtoBattle?.usedSpares ?? {} - prevSpares[wtoUnitName] <- (prevSpares?[wtoUnitName] ?? 0) + 1 - wtoBattle.usedSpares <- prevSpares - wtoNdb.ndbWrite(["wto", "activeBattle"], wtoBattle) + if (!isSilent) { + let source = this.getWtoBackupSourceForRequest(requestData) + let backup = this.getWtoBackupToken(requestData, source) + if (backup == null) + return -1 + if (backup != "") { + requestData.wtoBackup <- backup + wtoBlk.wtoBackup = backup + } + if (source == "vehicle") + requestData.spareUid = "" } return wtoGuiRespawn.requestAircraftAndWeaponWithSlots(requestData, requestData.idInCountry, requestData.respBaseId, requestData.spareUid, wtoBlk, DataBlock()) diff --git a/patches/gui/battle/record-local-battle-awards/replace.nut b/patches/gui/battle/record-local-battle-awards/replace.nut index 1625d4a..bc844b0 100644 --- a/patches/gui/battle/record-local-battle-awards/replace.nut +++ b/patches/gui/battle/record-local-battle-awards/replace.nut @@ -169,6 +169,31 @@ function wtoOnLocalMpNuclearStrike(_ev) { wtoSendLiveFact("strike", strike) } +function wtoOnLocalMpBackupSpawn(ev) { + let { ndbTryRead, ndbWrite } = require("nestdb") + let battle = ndbTryRead(["wto", "activeBattle"]) + if (battle?.backups == null || (ev?.unit ?? "") == "" || (ev?.backup ?? "") == "") + return + let slot = ev?.slot ?? -1 + let spawns = ndbTryRead(["wto", "battleLog", "spares"]) ?? [] + if (slot < 0 || spawns.findvalue(@(spawn) spawn.slot == slot) != null) + return + wtoAppendBattleLog("spares", { slot, unit = ev.unit, backup = ev.backup }) + + let { DAILY_FREE_SPARE_UID } = require("%scripts/respawn/respawnDailyFreeSpare.nut") + if (ev.backup == DAILY_FREE_SPARE_UID) { + let path = ["wto", "battleLog", "dailyBackupsUsed"] + ndbWrite(path, (ndbTryRead(path) ?? 0) + 1) + let { matchingApiFunc } = require("%scripts/matching/api.nut") + matchingApiFunc("wto_battle.daily_spare", @(_response) null, { sessionId = battle.sessionId, slot, unit = ev.unit }) + } + else if (ev.backup != "vehicle") { + let { markUsedItemCount } = require("%scripts/items/usedItemsInBattle.nut") + let { itemType } = require("%scripts/items/itemsConsts.nut") + markUsedItemCount(itemType.UNIVERSAL_SPARE, ev.backup) + } +} + function wtoSubscribeBattleAwards() { let { g_hud_event_manager } = require("%scripts/hud/hudEventManager.nut") g_hud_event_manager.subscribe("wtoLocalMpExpEvent", wtoOnLocalMpExpEvent) @@ -176,6 +201,7 @@ function wtoSubscribeBattleAwards() { g_hud_event_manager.subscribe("LocalPlayerDead", wtoOnLocalPlayerDead) g_hud_event_manager.subscribe("HudMessage", wtoOnHudMessage) g_hud_event_manager.subscribe("wtoLocalMpNuclearStrike", wtoOnLocalMpNuclearStrike) + g_hud_event_manager.subscribe("wtoLocalMpBackupSpawn", wtoOnLocalMpBackupSpawn) } // The local player leaves the battle, after its end (the fade to the debriefing) or from the menu diff --git a/patches/gui/battle/report-local-battle-settlement/replace.nut b/patches/gui/battle/report-local-battle-settlement/replace.nut index 444f072..59d597f 100644 --- a/patches/gui/battle/report-local-battle-settlement/replace.nut +++ b/patches/gui/battle/report-local-battle-settlement/replace.nut @@ -61,9 +61,12 @@ function buildWtoBattleReport(wtoBattle, res) { strikeBlk.time = strike.time.tofloat() } let sparesBlk = blk.addNewBlock("spares") - foreach (spUnit, spCnt in (wtoBattle?.usedSpares ?? {})) - if (spUnit != "" && spCnt > 0) - sparesBlk[spUnit] = spCnt.tointeger() + foreach (use in (battleLog?.spares ?? [])) { + let useBlk = sparesBlk.addNewBlock("spawn") + useBlk.slot = use.slot.tointeger() + useBlk.unit = use.unit + useBlk.backup = use.backup + } return blk }