Files
WT-Offline/packages/local-service/src/matching/battle-queue-requests.ts
T
N0VAN0M4LY d5df921d7f Show LocalMP extra lineup vehicles as plain vehicles
The live game draws one vehicle from each RandomSpawnUnits group at
launch and shows it as a plain lineup vehicle (a 12.7 US lineup gets an
M1A1 12.0 and an ADATS 12.0, no dice), so the random_units state and the
patch that filled it are gone. The strike UCAV costs 750 spawn points,
the live game's value, now in tuning/battle.jsonc.
2026-11-28 07:28:48 +08:00

184 lines
8.3 KiB
TypeScript

/**
* Matching-server RPC handlers for hangar battle-rating display and battle queueing
*:
* - `wtmm_static.calc_ranks` (scripts/battlerating.nut:179)
* - `match.enqueue` (scripts/matching/servicenotifications/match.nut:75)
* - `match.leave_queue` (scripts/queue/queuestate.nut:28)
* - `match.check_reconnect`
*/
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 { 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 BattleQueueDependencies {
readonly gameModes: GameModes;
readonly profiles: PlayerProfiles;
readonly matchmaker: BattleMatchmaker;
readonly sessions: BattleSessionStore;
readonly economy: BattleEconomy;
readonly notifyLaunch: (userId: string, payload: BattleLaunchNotify) => void;
}
export function battleQueueRequests(deps: BattleQueueDependencies): Array<[string, MatchingRequestHandler]> {
return [
['wtmm_static.calc_ranks', (request) => answerCalcRanks(request.params, deps.gameModes)],
['match.enqueue', (request, session) => handleEnqueue(request.params, session, deps)],
['match.leave_queue', (_request, session) => {
const userId = session.authenticatedUserId();
if (userId) deps.sessions.cancelPendingForUser(userId);
return {};
}],
['match.check_reconnect', () => ({})],
];
}
function answerCalcRanks(params: Readonly<Record<string, unknown>>, gameModes: GameModes): Record<string, unknown> {
const mode = typeof params.gameModeId === 'number' ? gameModes.byId(params.gameModeId) : undefined;
const players = Array.isArray(params.players) ? params.players : [];
const answer: Record<string, Array<{ mrank: number }>> = {};
for (const rawPlayer of players) {
if (!isRecord(rawPlayer) || typeof rawPlayer.name !== 'string' || !rawPlayer.name) continue;
const crafts = parsePlayerCrafts(rawPlayer.crafts);
const slot = typeof rawPlayer.slot === 'number' && Number.isInteger(rawPlayer.slot) ? rawPlayer.slot : -1;
const singleSlotCraft = mode?.declaration.multiSlot === false && slot >= 0 && slot < crafts.length
? crafts[slot]
: undefined;
const scopedCrafts = singleSlotCraft && singleSlotCraft.unitClass === mode?.declaration.requiredClass
? [singleSlotCraft]
: crafts;
const mrank = mode
? maxModeMrank(scopedCrafts, mode.declaration.requiredClass, mode.declaration.allowedClasses)
: scopedCrafts.reduce((max, craft) => Math.max(max, craft.mrank), 0);
answer[rawPlayer.name] = [{ mrank }];
}
return answer;
}
function handleEnqueue(
params: Readonly<Record<string, unknown>>,
session: { authenticatedUserId(): string | undefined; note(text: string): void },
deps: BattleQueueDependencies,
): Record<string, unknown> {
const userId = session.authenticatedUserId();
if (!userId) {
session.note('rejected: matching session is not authenticated');
return { error: 'AUTH_REQ_ERROR' };
}
const modes = resolveQueuedModes(params, deps.gameModes);
if (modes.length === 0) {
session.note('rejected: unknown game mode');
return { error: 'UNKNOWN_GAME_MODE' };
}
const playerEntry = extractPlayerEntry(params, userId);
if (!playerEntry) {
session.note('rejected: missing player country in match.enqueue');
return { error: 'BAD_PARAMS' };
}
const profile = deps.profiles.profileOf(userId);
const slotVehicles = crewVehiclesOfCountry(profile, playerEntry.country);
const selectedSlotVehicle = playerEntry.selectedSlot !== undefined
? crewSlotVehicleOfCountry(profile, playerEntry.country, playerEntry.selectedSlot)
: undefined;
const outcome = deps.matchmaker.enqueue({
userId,
mode: modes[0]!,
modes,
country: playerEntry.country,
slotVehicles,
...(selectedSlotVehicle !== undefined ? { selectedSlotVehicle } : {}),
bannedMissions: playerEntry.bannedMissions,
dislikedMissions: playerEntry.dislikedMissions,
});
if (!outcome.ok) {
session.note(`rejected: ${outcome.error}`);
return { error: outcome.error };
}
const { launch } = outcome;
session.note(`mode=${launch.modeName}, mission=${launch.missionName}, mrank=${launch.minMrank}..${launch.maxMrank}`);
const playerVehicles = new Set([
...slotVehicles,
...launch.extraBattleSlots.map((slot) => slot.unitName),
]);
const awards = deps.economy.bannerParams(playerVehicles, economyDifficulty(modes[0]!.declaration.difficulty));
setImmediate(() => {
if (!deps.sessions.isPending(userId, launch.sessionId)) return;
deps.sessions.clearPending(userId, launch.sessionId);
deps.notifyLaunch(userId, battleLaunchNotify(launch, awards, deps.economy.missionScores()));
});
return {};
}
function parsePlayerCrafts(rawCrafts: unknown): CraftRankEntry[] {
if (!Array.isArray(rawCrafts)) return [];
return rawCrafts.flatMap((craft): CraftRankEntry[] => {
if (!isRecord(craft) || typeof craft.mrank !== 'number' || !Number.isFinite(craft.mrank)) return [];
const fromExp = typeof craft.craftType === 'string' ? unitClassOfExpClass(craft.craftType) : undefined;
const fromCode = typeof craft.unitTypeCode === 'number' ? unitClassOfTypeCode(craft.unitTypeCode) : undefined;
return [{ unitClass: fromExp ?? fromCode, mrank: Math.max(0, Math.trunc(craft.mrank)) }];
});
}
/**
* Resolve every candidate `OfferedGameMode` allowed by `match.enqueue` (`scripts/queue/queue/queueevent.nut:191-207`):
* - `game_mode_id`: explicit single mode ID;
* - `game_modes_list`: filtered IDs after applying `onlyTags` / `excludedTags`;
* - `mode`: sent when `onlyTags` and `excludedTags` are both empty (classic mode plus every
* sub-mode of that `economicName` is enabled; server-side BR/craft guards still apply).
*/
function resolveQueuedModes(params: Readonly<Record<string, unknown>>, gameModes: GameModes): OfferedGameMode[] {
if (typeof params.game_mode_id === 'number') {
const found = gameModes.byId(params.game_mode_id);
return found ? [found] : [];
}
if (Array.isArray(params.game_modes_list)) {
return params.game_modes_list.flatMap((id) => (typeof id === 'number' ? gameModes.byId(id) ?? [] : []));
}
if (typeof params.mode === 'string' && params.mode) {
const primary = gameModes.byName(params.mode);
if (!primary) return [];
const family = gameModes.byEconomicName(primary.declaration.economicName);
return family.length > 0 ? [...family] : [primary];
}
return [];
}
function extractPlayerEntry(
params: Readonly<Record<string, unknown>>,
userId: string,
): {
readonly country: string;
readonly selectedSlot?: number;
readonly bannedMissions: Set<string>;
readonly dislikedMissions: Set<string>;
} | undefined {
const players = isRecord(params.players) ? params.players : undefined;
const entry = players && isRecord(players[userId]) ? players[userId] : undefined;
const rawCountry = typeof entry?.country === 'string' ? entry.country.trim() : '';
if (!rawCountry) return undefined;
const country = rawCountry.startsWith('country_') ? rawCountry : `country_${rawCountry}`;
const slots = isRecord(entry?.slots) ? entry.slots : undefined;
const rawSlot = slots?.[country] ?? slots?.[rawCountry];
const selectedSlot = typeof rawSlot === 'number' && Number.isInteger(rawSlot) && rawSlot >= 0 ? rawSlot : undefined;
return {
country,
...(selectedSlot !== undefined ? { selectedSlot } : {}),
bannedMissions: toStringSet(entry?.bannedMissions),
dislikedMissions: toStringSet(entry?.dislikedMissions),
};
}
function toStringSet(raw: unknown): Set<string> {
if (!Array.isArray(raw)) return new Set();
return new Set(raw.filter((item): item is string => typeof item === 'string' && item.length > 0));
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}