Files
WT-Offline/apps/server/src/battle/battle-matchmaker.ts
T
N0VAN0M4LY 899fb5d91b fix(server): persist selectable battle ratings
Validate the selected rank against owned modifications and return the saved profile.

Use the saved rank delta for mode eligibility and room matchmaking.

Verified with typecheck and a local 2.61.0.58 server run using temporary data. In-game acceptance is pending.
2026-12-02 19:55:41 +08:00

289 lines
12 KiB
TypeScript

/**
* Pure local-battle matchmaking rules (`match.enqueue`):
* validates the chosen PvP mode and country, computes the player's lineup BR, selects a
* two-sided multiplayer mission honoring banned/disliked map preferences, pairs AB/RB/SB
* nation coalitions, builds the `customBots` pool and extra battle slots, and records a
* `BattleSession`.
*/
import { randomInt } from 'node:crypto';
import type { BattleSpawnRulesData } from '../game-data/datasets/battle-spawn-rules.ts';
import type { MissionHeader } from '../game-data/datasets/multiplayer-missions.ts';
import type { CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.ts';
import type { GameModes, OfferedGameMode } from '../game-modes/game-modes.ts';
import { MISSION_DIFFICULTY, SINGLE_SPAWN } from '../game-modes/mode-definition.ts';
import { serverTimeNow, serverTimeToUnixSeconds } from '../profile/server-time.ts';
import { selectBattleCoalitions, type CoalitionPairing } from './battle-coalitions.ts';
import { selectExtraBattleSlots, type ExtraBattleSlot } from './battle-extra-slots.ts';
import {
activeVehiclesForMode,
isModeEligibleForLineup,
lineupMrank,
selectCustomBots,
type CustomBotsPool,
} from './battle-ranks.ts';
import type { BattleSessionStore } from './battle-session-store.ts';
import { battleSpawnScore, type BattleSpawnScore } from './battle-spawn-score.ts';
import type { BotAircraftLoadout } from './bot-aircraft-loadouts.ts';
import type { BattleTuning } from './battle-tuning.ts';
export interface BattleCrewSlot {
readonly idInCountry: number;
readonly unitName: string;
}
export interface EnqueueBattleInput {
readonly userId: string;
readonly mode: OfferedGameMode;
readonly modes?: readonly OfferedGameMode[];
readonly country: string;
readonly slotVehicles: readonly string[];
readonly mrankDeltas: ReadonlyMap<string, number>;
readonly selectedSlot?: BattleCrewSlot;
readonly bannedMissions: ReadonlySet<string>;
readonly dislikedMissions: ReadonlySet<string>;
}
export interface BattleLaunchPlan {
readonly sessionId: string;
readonly modeId: number;
readonly modeName: string;
readonly economicName: string;
readonly missionName: string;
/** The mission as the game describes it, including the parameters copied into the mission settings. */
readonly mission: MissionHeader;
readonly missionFile: string;
readonly missionType: string;
readonly level?: string;
readonly environment?: string;
readonly weather?: string;
readonly difficulty: string;
readonly country: string;
readonly playerTeam: 1 | 2;
readonly countryAllies: string;
readonly countryAxis: string;
readonly countriesAllies: readonly string[];
readonly countriesAxis: readonly string[];
readonly symmetricTeams: boolean;
readonly minMrank: number;
readonly maxMrank: number;
readonly maxPlayers: number;
readonly maxBots: number;
readonly tankBotRespawns: number;
readonly airBotRespawns: number;
readonly useTankBots: boolean;
readonly useShipBots: boolean;
readonly useSpawnScore: boolean;
readonly spawnScore?: BattleSpawnScore;
readonly customBots: CustomBotsPool;
readonly selectedSlot?: BattleCrewSlot;
readonly extraBattleSlots: readonly ExtraBattleSlot[];
}
export type MatchmakeOutcome =
| { readonly ok: true; readonly launch: BattleLaunchPlan }
| { readonly ok: false; readonly error: string };
export class BattleMatchmaker {
readonly #gameModes: GameModes;
readonly #vehicles: readonly CatalogueVehicle[];
readonly #vehiclesByName: ReadonlyMap<string, CatalogueVehicle>;
readonly #sessions: BattleSessionStore;
readonly #tuning: BattleTuning;
readonly #spawnRules: BattleSpawnRulesData;
readonly #aircraftLoadouts: ReadonlyMap<string, BotAircraftLoadout>;
constructor(
gameModes: GameModes,
vehicles: readonly CatalogueVehicle[],
sessions: BattleSessionStore,
tuning: BattleTuning,
spawnRules: BattleSpawnRulesData,
aircraftLoadouts: ReadonlyMap<string, BotAircraftLoadout>,
) {
this.#gameModes = gameModes;
this.#vehicles = vehicles;
this.#vehiclesByName = new Map(vehicles.map((vehicle) => [vehicle.name, vehicle]));
this.#sessions = sessions;
this.#tuning = tuning;
this.#spawnRules = spawnRules;
this.#aircraftLoadouts = aircraftLoadouts;
}
enqueue(input: EnqueueBattleInput): MatchmakeOutcome {
const knownCountries = this.#gameModes.countries();
if (!knownCountries.includes(input.country)) return { ok: false, error: 'BAD_PARAMS' };
const candidates = input.modes && input.modes.length > 0 ? input.modes : [input.mode];
const pvpModes = candidates.filter(
(mode) => mode.declaration.displayType !== 'pve_battle' && twoSidedMissionsOf(mode).length > 0,
);
if (pvpModes.length === 0) return { ok: false, error: 'PVE_NOT_SUPPORTED' };
const chosenMode = this.#pickQueuedMode(pvpModes, input);
if (!chosenMode) return { ok: false, error: 'BAD_PARAMS' };
const { declaration } = chosenMode;
const activeVehicles = activeVehiclesForMode(declaration, input.slotVehicles, input.selectedSlot?.unitName, this.#vehiclesByName);
const playerMrank = lineupMrank(
activeVehicles, this.#vehiclesByName, declaration.difficulty, declaration.requiredClass, declaration.allowedClasses,
input.mrankDeltas,
);
const minMrank = Math.max(declaration.minQueueMrank ?? 0, playerMrank - this.#tuning.brSpreadMrank);
const roomCeiling = chosenMode.missionRanks?.maxMrank ?? Infinity;
const maxMrank = Math.max(minMrank, playerMrank, Math.min(roomCeiling, playerMrank + this.#tuning.brSpreadMrank));
const missions = twoSidedMissionsOf(chosenMode, maxMrank);
if (missions.length === 0) return { ok: false, error: 'NO_MISSION_FOR_BR' };
const mission = pickMission(missions, input.bannedMissions, input.dislikedMissions);
const coalitions = selectBattleCoalitions({
vehicles: this.#vehicles,
knownCountries,
playerCountry: input.country,
difficulty: declaration.difficulty,
requiredClass: declaration.requiredClass,
playerMrank,
minMrank,
maxMrank,
tuning: this.#tuning,
});
const customBots = selectCustomBots(this.#vehicles, {
difficulty: declaration.difficulty,
requiredClass: declaration.requiredClass,
allowedClasses: declaration.allowedClasses,
countries: [...coalitions.countriesAllies, ...coalitions.countriesAxis],
centerMrank: playerMrank,
minMrank,
maxMrank,
limitPerType: this.#tuning.botPoolLimitPerType,
}, declaration.allowBotAircraftLoadouts === false ? undefined : this.#aircraftLoadouts);
return {
ok: true,
launch: this.#buildLaunchPlan(input, chosenMode, mission, coalitions, playerMrank, minMrank, maxMrank, customBots),
};
}
#pickQueuedMode(candidates: readonly OfferedGameMode[], input: EnqueueBattleInput): OfferedGameMode | undefined {
const pool = candidates.filter((mode) => isModeEligibleForLineup(
mode.declaration, input.slotVehicles, input.selectedSlot?.unitName, this.#vehiclesByName, input.mrankDeltas,
));
if (pool.length === 0) return candidates.find((mode) => mode.declaration.multiSlot !== false);
const classics = pool.filter((mode) => !mode.declaration.tag);
const subModes = pool.filter((mode) => Boolean(mode.declaration.tag));
if (subModes.length > 0 && classics.length > 0) {
const useSubMode = randomInt(1_000_000) < Math.round(this.#tuning.subModeChance * 1_000_000);
const bucket = useSubMode ? subModes : classics;
return bucket[randomInt(bucket.length)];
}
return pool[randomInt(pool.length)];
}
#buildLaunchPlan(
input: EnqueueBattleInput,
chosenMode: OfferedGameMode,
mission: MissionHeader,
coalitions: CoalitionPairing,
playerMrank: number,
minMrank: number,
maxMrank: number,
customBots: CustomBotsPool,
): BattleLaunchPlan {
const { declaration } = chosenMode;
const desiredPlayers = declaration.isSmallTeams ? this.#tuning.smallTeamsMaxPlayers : this.#tuning.maxPlayers;
const maxPlayers = Math.min(desiredPlayers, maxSlotsForMission(mission, desiredPlayers));
const maxBots = Math.min(this.#tuning.maxBots, Math.max(1, maxPlayers - 1));
const missionLocName = resolveMissionLocName(mission);
const environment = declaration.environmentOverride ?? mission.environment;
const session = this.#sessions.create({
userId: input.userId,
modeId: declaration.gameModeId,
modeName: declaration.name,
economicName: declaration.economicName,
difficulty: declaration.difficulty,
requiredClass: declaration.requiredClass,
randomBattle: declaration.displayType === 'random_battle',
missionName: mission.name,
missionPath: mission.path,
...(missionLocName !== undefined ? { missionLocName } : {}),
country: input.country,
startedAtSec: serverTimeToUnixSeconds(serverTimeNow()),
});
const allowedSet = new Set(declaration.allowedClasses);
const extraBattleSlots = selectExtraBattleSlots({
country: input.country,
slotVehicles: input.slotVehicles,
declaration,
playerMrank,
sessionMaxMrank: maxMrank,
vehiclesByName: this.#vehiclesByName,
rules: this.#spawnRules,
tuning: this.#tuning,
});
const useSpawnScore = declaration.requiredClass === 'tank' && declaration.difficulty === 'realistic';
return {
sessionId: session.sessionId,
modeId: declaration.gameModeId,
modeName: declaration.name,
economicName: declaration.economicName,
missionName: mission.name,
mission,
missionFile: mission.path,
missionType: mission.type ?? 'domination',
...(mission.level !== undefined ? { level: mission.level } : {}),
...(environment !== undefined ? { environment } : {}),
...(mission.weather !== undefined ? { weather: mission.weather } : {}),
difficulty: MISSION_DIFFICULTY[declaration.difficulty],
country: input.country,
playerTeam: coalitions.playerTeam,
countryAllies: coalitions.countryAllies,
countryAxis: coalitions.countryAxis,
countriesAllies: coalitions.countriesAllies,
countriesAxis: coalitions.countriesAxis,
symmetricTeams: coalitions.symmetricTeams,
minMrank,
maxMrank,
maxPlayers,
maxBots,
tankBotRespawns: this.#tuning.tankBotRespawns,
airBotRespawns: declaration.multiSlot === false ? SINGLE_SPAWN : this.#tuning.airBotRespawns,
useTankBots: allowedSet.has('tank'),
useShipBots: allowedSet.has('ship'),
useSpawnScore,
...(useSpawnScore ? {
spawnScore: battleSpawnScore(input.slotVehicles, extraBattleSlots, maxMrank, this.#vehiclesByName, this.#spawnRules.spawnScore),
} : {}),
customBots,
...(declaration.multiSlot === false && input.selectedSlot ? { selectedSlot: input.selectedSlot } : {}),
extraBattleSlots,
};
}
}
function twoSidedMissionsOf(mode: OfferedGameMode, roomMrank?: number): MissionHeader[] {
return mode.missions.filter((mission) => {
if (mission.playerSlots.teamA === 0 || mission.playerSlots.teamB === 0) return false;
if (!mode.missionRanks || roomMrank === undefined) return true;
return mode.missionRanks.byMission.get(mission.name)?.some(({ minMRank, maxMRank }) =>
roomMrank >= minMRank && roomMrank <= maxMRank);
});
}
function pickMission(missions: readonly MissionHeader[], banned: ReadonlySet<string>, disliked: ReadonlySet<string>): MissionHeader {
const unbanned = missions.filter((mission) => !banned.has(mission.name));
const poolAfterBan = unbanned.length > 0 ? unbanned : missions;
const preferred = poolAfterBan.filter((mission) => !disliked.has(mission.name));
const pool = preferred.length > 0 ? preferred : poolAfterBan;
return pool[randomInt(pool.length)]!;
}
function maxSlotsForMission(mission: MissionHeader, desiredMaxPlayers: number): number {
const { teamA, teamB } = mission.playerSlots;
return Math.max(2, Math.min(desiredMaxPlayers, Math.min(teamA, teamB) * 2));
}
function resolveMissionLocName(mission: MissionHeader): string | undefined {
if (mission.locName && mission.locName.length > 0) return mission.locName;
if (mission.postfix && mission.postfix.length > 0 && mission.name.endsWith(mission.postfix)) {
const baseName = mission.name.slice(0, -mission.postfix.length);
if (baseName.length > 0) return `missions/${mission.postfix};missions/${baseName}`;
}
return undefined;
}