Build the local battle mission settings in the local service

The launch script patch used to assemble the whole MissionSettings block
on the client: reading the mission file for localization keys and ticket
rules, filling the AI vehicle pool, rank window and extra slot costs.
All of that is pre-battle data the local service already owns.

- multiplayer-missions dataset v3 keeps the scalar parameters of
  mission_settings.mission and of each per-difficulty sub-block, with
  their BLK types.
- battle-mission-settings.ts builds the complete MissionSettings block
  from the launch plan (same parameters as before).
- battle-launch-notify.ts sends it as a typed tree, so ints and reals
  keep the types the engine reads, plus the lobby settings and the
  per-battle record the in-battle patches read from nestdb.
- The launch patch shrinks from 208 to about 70 lines: rebuild the
  DataBlock, set _gameMode from the client's own native constant, enter
  the session lobby and start the LocalMP battle.

Behaviour is unchanged; coalitions, extra slots and economy are reworked
in later commits. Verified: npm run typecheck, check-gui (33 patches).
This commit is contained in:
N0VAN0M4LY committed 2026-11-28 03:39:53 +08:00
1 parent 16b5d3cab1
commit b1392c0512
7 files changed
+276 -181

No files matched your search

@@ -41,6 +41,8 @@ export interface BattleLaunchPlan {
readonly modeName: string;
readonly economicName: string;
readonly missionName: string;
/** The mission as the game describes it, including the parameters copied into the mission settings. */
readonly mission: MissionHeader;
readonly missionFile: string;
readonly missionType: string;
readonly level?: string;
@@ -205,6 +207,7 @@ export class BattleMatchmaker {
modeName: declaration.name,
economicName: declaration.economicName,
missionName: mission.name,
mission,
missionFile: mission.path,
missionType: mission.type ?? 'domination',
...(mission.level !== undefined ? { level: mission.level } : {}),
@@ -0,0 +1,128 @@
/**
* Mission settings for a local battle: the block the client hands to the native
* `select_training_mission` (guiMission) to host the battle as an in-process LocalMP session.
*
* The client loads the mission file itself, but does not copy the localization keys or the
* ticket and capture rules of `mission_settings.mission` into its MissionSettings; they are
* copied here from the mission file, base values first and then the sub-block for the battle's
* difficulty. `_gameMode` is left to the client, which takes it from its own native constants.
*/
import { emptyBlock, ensureBlock, setParam, appendParam, type BlkBlock, type BlkParam, type BlkValue } from '@wto/blk';
import type { ExtraBattleSlot } from './battle-extra-slots.ts';
import type { BattleLaunchPlan } from './battle-matchmaker.ts';
import type { CustomBotsPool } from './battle-ranks.ts';
/** Mission localization keys the client reads from MissionSettings (missionsText.nut). */
const LOCALIZATION_KEYS: readonly string[] = [
'locName', 'locDesc', 'locNameTeamA', 'locNameTeamB', 'locDescTeamA', 'locDescTeamB', 'loc_name', 'postfix', 'restoreType',
];
/** Ticket, capture and time rules of the mission. */
const RULE_KEYS: readonly string[] = [
'scoreLimit', 'timeLimit', 'killLimit', 'deathPenaltyMul',
'ctaCaptureZoneEqualPenaltyMul', 'ctaCaptureZonePenaltyMul', 'captureZonePenaltyMul', 'scorePerSec',
'ctaInstantDecreaseTicketsWhenNoRespawn', 'randomSpawnTeams', 'remapAiTankModels', 'useAlternativeMapCoord',
];
/** Game type switches of a versus battle with tickets, capture zones and session rewards. */
const VERSUS_SWITCHES: readonly string[] = [
'gt_versus', 'gt_mp_tickets', 'gt_mp_capture', 'gt_use_wp', 'gt_use_xp', 'gt_use_stats', 'gt_use_unlocks',
'allowSpare', 'isLimitedAmmo', 'allowUseArtillerySupport', 'isBotsAllowed', 'autoBalance',
];
export function battleMissionSettings(plan: BattleLaunchPlan): BlkBlock {
const settings = emptyBlock();
copyMissionParams(settings, plan);
if (plan.level !== undefined) setParam(settings, 'level', text(plan.level));
if (plan.environment !== undefined) setParam(settings, 'environment', text(plan.environment));
if (plan.weather !== undefined) setParam(settings, 'weather', text(plan.weather));
setParam(settings, 'localMP', flag(true));
setParam(settings, 'name', text(plan.missionName));
setParam(settings, 'economicName', text(plan.economicName));
setParam(settings, 'mis_file', text(plan.missionFile));
setParam(settings, 'chapter', text('skirmish'));
setParam(settings, 'type', text(plan.missionType));
setParam(settings, 'difficulty', text(plan.difficulty));
setParam(settings, 'country_allies', text(plan.countryAllies));
setParam(settings, 'country_axis', text(plan.countryAxis));
setParam(settings, 'arcadeCountry', flag(true));
setParam(settings, 'symmetricTeams', flag(plan.symmetricTeams));
setParam(settings, 'gt_mp_solo', flag(false));
for (const name of VERSUS_SWITCHES) setParam(settings, name, flag(true));
setParam(settings, 'useSpawnScore', flag(plan.useSpawnScore));
setParam(settings, 'useTankBots', flag(plan.useTankBots));
setParam(settings, 'useShipBots', flag(plan.useShipBots));
setParam(settings, 'maxPlayers', integer(plan.maxPlayers));
setParam(settings, 'maxBots', integer(plan.maxBots));
addPersistentSpawnCosts(settings, plan.extraBattleSlots);
for (const name of ['ranks', 'forcedRanks']) {
const ranks = ensureBlock(settings, name);
setParam(ranks, 'min', integer(plan.minMrank));
setParam(ranks, 'max', integer(plan.maxMrank));
}
settings.blocks.push(customBotsBlock(plan));
return settings;
}
function copyMissionParams(settings: BlkBlock, plan: BattleLaunchPlan): void {
const wanted = new Set([...LOCALIZATION_KEYS, ...RULE_KEYS]);
const copy = (params: readonly BlkParam[] | undefined, keys: ReadonlySet<string>): void => {
for (const param of params ?? []) {
if (keys.has(param.name)) setParam(settings, param.name, param.value);
}
};
copy(plan.mission.missionParams, wanted);
copy(plan.mission.difficultyParams[plan.difficulty], new Set(RULE_KEYS));
}
/** Fixed spawn costs of extra slots, read back by the spawn score respondents (customSpawnScore). */
function addPersistentSpawnCosts(settings: BlkBlock, slots: readonly ExtraBattleSlot[]): void {
const costed = slots.filter((slot) => slot.persistentCost > 0 && slot.unitName !== '');
if (costed.length === 0) return;
const costs = ensureBlock(ensureBlock(settings, 'customSpawnScore'), 'persistent_costs');
for (const slot of costed) setParam(costs, slot.unitName, integer(slot.persistentCost));
}
/** AI vehicle pool in the layout of config/bots.blk; repeated entries are separate blocks. */
function customBotsBlock(plan: BattleLaunchPlan): BlkBlock {
const bots = emptyBlock('customBots');
setParam(bots, 'wtoPlayerTeam', text(String(plan.playerTeam)));
setParam(bots, 'wtoTeamACountries', text(plan.countriesAllies.join(';')));
setParam(bots, 'wtoTeamBCountries', text(plan.countriesAxis.join(';')));
setParam(bots, 'numBotRespawnsInMultiSlot', integer(plan.airBotRespawns));
setParam(bots, 'numTankBotRespawnsInMultiSlot', integer(plan.tankBotRespawns));
setParam(bots, 'numBotRespawnsInVersus', integer(plan.airBotRespawns));
setParam(bots, 'numTankBotRespawnsInVersus', integer(plan.tankBotRespawns));
bots.blocks.push(
poolBlock('allowedTanks', 'tank', plan.customBots.tanks),
poolBlock('allowedAircrafts', 'aircraft', plan.customBots.aircrafts),
poolBlock('allowedShips', 'ship', plan.customBots.ships),
);
return bots;
}
function poolBlock(name: string, entryName: string, entries: CustomBotsPool['tanks']): BlkBlock {
const pool = emptyBlock(name);
for (const entry of entries) {
const block = emptyBlock(entryName);
appendParam(block, 'name', text(entry.name));
appendParam(block, 'weight', { type: 'real', value: entry.weight });
appendParam(block, 'country', text(entry.country));
pool.blocks.push(block);
}
return pool;
}
function text(value: string): BlkValue {
return { type: 'string', value };
}
function integer(value: number): BlkValue {
return { type: 'int', value: Math.trunc(value) };
}
function flag(value: boolean): BlkValue {
return { type: 'bool', value };
}
@@ -7,11 +7,13 @@
* - Each mission: mis.vromfs.bin gamedata/missions/…/<name lower-cased>.blk. Its
* mission_settings block names the map, the kind of game, the two sides' countries, the
* vehicle types allowed, per-difficulty overrides, and the players' spawn slots
* ("wing" entries of player / player_teamB).
* ("wing" entries of player / player_teamB). Its scalar parameters (and those of each
* per-difficulty "mission" sub-block) are also kept as written, with their BLK types, for
* the mission settings the local service sends when a battle starts.
*
* 2.61.0.37: 1315 missions, each name matching exactly one mission file (docs/implementation notes).
*/
import type { BlkBlock } from '@wto/blk';
import type { BlkBlock, BlkParam } from '@wto/blk';
import type { Dataset, DatasetSource } from './dataset.ts';
import { blockAt, boolFields, numberField, stringField, stringList } from './blk-fields.ts';
@@ -43,6 +45,10 @@ export interface MissionHeader {
readonly difficultyOverrides: readonly string[];
/** Spawn slots per side. */
readonly playerSlots: { readonly teamA: number; readonly teamB: number };
/** String, int, real and bool parameters of mission_settings.mission, in file order. */
readonly missionParams: readonly BlkParam[];
/** The same for each per-difficulty "mission" sub-block, keyed by its `difficulty`. */
readonly difficultyParams: Readonly<Record<string, readonly BlkParam[]>>;
}
export interface MultiplayerMissions {
@@ -52,7 +58,7 @@ export interface MultiplayerMissions {
export const multiplayerMissions: Dataset<MultiplayerMissions> = {
id: 'multiplayer-missions',
version: 2,
version: 3,
extract(source: DatasetSource): MultiplayerMissions {
const section = blockAt(source.readBlk('char.vromfs.bin', MISSION_LIST), MULTIPLAYER_SECTION);
if (!section) throw new Error(`${MISSION_LIST} has no "${MULTIPLAYER_SECTION}" block`);
@@ -113,5 +119,19 @@ function readHeader(name: string, path: string, document: BlkBlock): MissionHead
teamA: stringList(blockAt(settings, 'player'), 'wing').length,
teamB: stringList(blockAt(settings, 'player_teamB'), 'wing').length,
},
missionParams: scalarParams(mission),
difficultyParams: Object.fromEntries((mission?.blocks ?? [])
.filter((block) => block.name === 'mission')
.flatMap((block) => {
const difficulty = stringField(block, 'difficulty');
return difficulty ? [[difficulty, scalarParams(block)]] : [];
})),
};
}
const SCALAR_TYPES = new Set(['string', 'int', 'real', 'bool']);
/** The parameters whose values survive the dataset cache's JSON unchanged. */
function scalarParams(block: BlkBlock | undefined): BlkParam[] {
return (block?.params ?? []).filter((param) => SCALAR_TYPES.has(param.value.type));
}
@@ -0,0 +1,79 @@
/**
* The `mrpc.generic_notify` message that starts a local battle (`from: "wto_battle"`,
* `func: "launch"`), received by the client's launch script patch
* (gui-patches/battle/launch-local-battle-from-queue).
*
* - `mission`: the complete mission settings for `select_training_mission`, as a typed tree
* `{ p: [[name, type, value], ...], b: [[name, node], ...] }` with type "t", "i", "r" or "b".
* Matching notifications are JSON, which cannot tell 1 from 1.0; the engine reads ints and reals
* with typed getters, so the type travels with every value. Repeated blocks stay separate.
* - `lobby`: the session lobby settings the client's own room scripts read during the battle
* (game mode and both sides' countries).
* - `battle`: what the client keeps for this battle (session id for the settlement, extra slots).
*/
import type { BlkBlock, BlkValue } from '@wto/blk';
import type { BattleLaunchPlan } from '../battle/battle-matchmaker.ts';
import { battleMissionSettings } from '../battle/battle-mission-settings.ts';
type WireParam = readonly [name: string, type: 't' | 'i' | 'r' | 'b', value: string | number | boolean];
interface WireBlock {
readonly p: readonly WireParam[];
readonly b: ReadonlyArray<readonly [name: string, block: WireBlock]>;
}
export interface BattleLaunchNotify extends Record<string, unknown> {
readonly from: 'wto_battle';
readonly func: 'launch';
readonly mission: WireBlock;
readonly lobby: Readonly<Record<string, unknown>>;
readonly battle: Readonly<Record<string, unknown>>;
}
export function battleLaunchNotify(plan: BattleLaunchPlan): BattleLaunchNotify {
return {
from: 'wto_battle',
func: 'launch',
mission: toWire(battleMissionSettings(plan)),
lobby: {
game_mode_id: plan.modeId,
game_mode_name: plan.modeName,
economicName: plan.economicName,
symmetricTeams: plan.symmetricTeams,
country_allies: plan.countriesAllies.map(withCountryPrefix),
country_axis: plan.countriesAxis.map(withCountryPrefix),
mission: { name: plan.missionName, difficulty: plan.difficulty },
},
battle: {
sessionId: plan.sessionId,
modeName: plan.modeName,
economicName: plan.economicName,
country: plan.country,
missionName: plan.missionName,
extraBattleSlots: plan.extraBattleSlots,
randomUnits: plan.randomUnits,
randomUnitsEventName: plan.randomUnitsEventName ?? '',
},
};
}
function toWire(block: BlkBlock): WireBlock {
return {
p: block.params.map((param) => [param.name, ...wireValue(param.name, param.value)] as const),
b: block.blocks.map((child) => [child.name, toWire(child)] as const),
};
}
function wireValue(name: string, value: BlkValue): readonly ['t' | 'i' | 'r' | 'b', string | number | boolean] {
switch (value.type) {
case 'string': return ['t', value.value];
case 'int': return ['i', value.value];
case 'real': return ['r', value.value];
case 'bool': return ['b', value.value];
default: throw new Error(`mission settings parameter ${name} has type ${value.type}, which the launch message cannot carry`);
}
}
function withCountryPrefix(country: string): string {
return country.startsWith('country_') ? country : `country_${country}`;
}
@@ -6,25 +6,21 @@
* - `match.leave_queue` (scripts/queue/queuestate.nut:28)
* - `match.check_reconnect`
*/
import type { BattleLaunchPlan, BattleMatchmaker } from '../battle/battle-matchmaker.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 { GameModes, OfferedGameMode } from '../game-modes/game-modes.ts';
import { crewSlotVehicleOfCountry, crewVehiclesOfCountry } from '../profile/profile-crews.ts';
import type { PlayerProfiles } from '../profile/player-profiles.ts';
import { battleLaunchNotify, type BattleLaunchNotify } from './battle-launch-notify.ts';
import type { MatchingRequestHandler } from './matching-requests.ts';
export interface BattleLaunchNotifyPayload extends BattleLaunchPlan, Record<string, unknown> {
readonly from: 'wto_battle';
readonly func: 'launch';
}
export interface BattleQueueDependencies {
readonly gameModes: GameModes;
readonly profiles: PlayerProfiles;
readonly matchmaker: BattleMatchmaker;
readonly sessions: BattleSessionStore;
readonly notifyLaunch: (userId: string, payload: BattleLaunchNotifyPayload) => void;
readonly notifyLaunch: (userId: string, payload: BattleLaunchNotify) => void;
}
export function battleQueueRequests(deps: BattleQueueDependencies): Array<[string, MatchingRequestHandler]> {
@@ -106,7 +102,7 @@ function handleEnqueue(
setImmediate(() => {
if (!deps.sessions.isPending(userId, launch.sessionId)) return;
deps.sessions.clearPending(userId, launch.sessionId);
deps.notifyLaunch(userId, { from: 'wto_battle', func: 'launch', ...launch });
deps.notifyLaunch(userId, battleLaunchNotify(launch));
});
return {};
}