fix(battle): assign combat presets to AI aircraft

Read stock weapon triggers and prerequisite modifications. Supply a suitable native preset for aircraft whose default lacks the relevant armament and preserve repeated modification names in the launch block.
This commit is contained in:
N0VAN0M4LY committed 2026-12-01 13:50:04 +08:00
1 parent 44e64fa414
commit 70c4ee4880
8 files changed
+190 -9

No files matched your search

+5 -1
View File
@@ -23,6 +23,7 @@ import {
} 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 {
@@ -88,6 +89,7 @@ export class BattleMatchmaker {
readonly #sessions: BattleSessionStore;
readonly #tuning: BattleTuning;
readonly #spawnRules: BattleSpawnRulesData;
readonly #aircraftLoadouts: ReadonlyMap<string, BotAircraftLoadout>;
constructor(
gameModes: GameModes,
@@ -95,6 +97,7 @@ export class BattleMatchmaker {
sessions: BattleSessionStore,
tuning: BattleTuning,
spawnRules: BattleSpawnRulesData,
aircraftLoadouts: ReadonlyMap<string, BotAircraftLoadout>,
) {
this.#gameModes = gameModes;
this.#vehicles = vehicles;
@@ -102,6 +105,7 @@ export class BattleMatchmaker {
this.#sessions = sessions;
this.#tuning = tuning;
this.#spawnRules = spawnRules;
this.#aircraftLoadouts = aircraftLoadouts;
}
enqueue(input: EnqueueBattleInput): MatchmakeOutcome {
@@ -147,7 +151,7 @@ export class BattleMatchmaker {
minMrank,
maxMrank,
limitPerType: this.#tuning.botPoolLimitPerType,
});
}, this.#aircraftLoadouts);
return {
ok: true,
launch: this.#buildLaunchPlan(input, chosenMode, mission, coalitions, playerMrank, minMrank, maxMrank, customBots),
@@ -134,6 +134,11 @@ function poolBlock(name: string, entryName: string, entries: CustomBotsPool['tan
appendParam(block, 'name', text(entry.name));
appendParam(block, 'weight', { type: 'real', value: entry.weight });
appendParam(block, 'country', text(entry.country));
const loadout = entry.aircraftLoadout;
if (loadout !== undefined) {
setParam(ensureBlock(block, 'preset'), 'name', text(loadout.preset));
for (const modification of loadout.modifications) appendParam(block, 'addModification', text(modification));
}
pool.blocks.push(block);
}
return pool;
+10 -2
View File
@@ -9,6 +9,7 @@
import type { CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.ts';
import type { GameModeDeclaration, ModeDifficulty, UnitClass } from '../game-modes/catalogue/game-mode-declaration.ts';
import { vehicleTypeById, vehicleTypeOfClass, type VehicleType } from '../research/vehicle-types.ts';
import type { BotAircraftLoadout } from './bot-aircraft-loadouts.ts';
const COUNTRY_PREFIX = 'country_';
@@ -21,6 +22,7 @@ export interface BotPoolEntry {
readonly name: string;
readonly country: string;
readonly weight: number;
readonly aircraftLoadout?: BotAircraftLoadout;
}
export interface CustomBotsPool {
@@ -105,12 +107,18 @@ export function lineupMrank(
return maxModeMrank(crafts, requiredClass, allowedClasses);
}
export function selectCustomBots(vehicles: readonly CatalogueVehicle[], query: BotPoolQuery): CustomBotsPool {
export function selectCustomBots(
vehicles: readonly CatalogueVehicle[], query: BotPoolQuery, aircraftLoadouts: ReadonlyMap<string, BotAircraftLoadout>,
): CustomBotsPool {
const allowed = new Set(query.allowedClasses);
const orderedCountries = [...new Set(query.countries.map((c) => (c.startsWith(COUNTRY_PREFIX) ? c : `${COUNTRY_PREFIX}${c}`)))];
const aircrafts = allowed.has('aircraft') ? pickCategoryPool(vehicles, orderedCountries, 'aircraft', query) : [];
return {
tanks: allowed.has('tank') ? pickCategoryPool(vehicles, orderedCountries, 'tank', query) : [],
aircrafts: allowed.has('aircraft') ? pickCategoryPool(vehicles, orderedCountries, 'aircraft', query) : [],
aircrafts: query.requiredClass === 'aircraft' ? aircrafts.map((entry) => {
const aircraftLoadout = aircraftLoadouts.get(entry.name);
return aircraftLoadout === undefined ? entry : { ...entry, aircraftLoadout };
}) : aircrafts,
ships: allowed.has('ship') ? pickCategoryPool(vehicles, orderedCountries, 'ship', query) : [],
};
}
@@ -0,0 +1,62 @@
/** Choose a stock combat preset when the native default carries no suitable armament. */
import type { FlightModelPreset, FlightModelPresets } from '../game-data/datasets/flight-model-presets.ts';
import type { CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.ts';
import type { EquipmentCatalogue } from '../modifications/equipment-catalogue.ts';
import { vehicleTypeOfClass } from '../research/vehicle-types.ts';
const AIR_WEAPONS = new Set(['aam', 'additional gun', 'cannon', 'machine gun']);
const STRIKE_WEAPONS = new Set(['bombs', 'guided bombs', 'rockets', 'atgm', 'torpedoes']);
export interface BotAircraftLoadout {
readonly preset: string;
readonly modifications: readonly string[];
}
export function selectBotAircraftLoadouts(
vehicles: readonly CatalogueVehicle[], models: FlightModelPresets, equipment: EquipmentCatalogue,
): ReadonlyMap<string, BotAircraftLoadout> {
const result = new Map<string, BotAircraftLoadout>();
for (const vehicle of vehicles) {
if (vehicleTypeOfClass(vehicle.unitClass) !== 'Aircraft') continue;
const presets = models[vehicle.name.toLowerCase()]?.filter((preset) => !preset.auxiliary);
if (!presets?.length) continue;
const loadout = chooseLoadout(vehicle, presets, equipment);
if (loadout !== undefined) result.set(vehicle.name, loadout);
}
return result;
}
function chooseLoadout(
vehicle: CatalogueVehicle, presets: readonly FlightModelPreset[], equipment: EquipmentCatalogue,
): BotAircraftLoadout | undefined {
const priorities = vehicle.unitClass === 'exp_fighter' ? [AIR_WEAPONS] : [STRIKE_WEAPONS, AIR_WEAPONS];
const stockDefault = presets[0];
if (!stockDefault || priorities.some((group) => carriesWeapons(stockDefault, group))) return undefined;
for (const group of priorities) {
const candidates = presets.filter((preset) => carriesWeapons(preset, group)).map((preset) => ({
preset: preset.name,
modifications: requiredModifications(vehicle.name, preset, equipment),
}));
if (candidates.length > 0) {
return candidates.find((candidate) => candidate.modifications.length === 0) ?? candidates[0];
}
}
return undefined;
}
function carriesWeapons(preset: FlightModelPreset, group: ReadonlySet<string>): boolean {
return preset.triggers.some((trigger) => group.has(trigger));
}
function requiredModifications(
vehicle: string, preset: FlightModelPreset, equipment: EquipmentCatalogue,
): string[] {
const requirements = new Set([...preset.requires, ...(equipment.weapon(vehicle, preset.name)?.requires ?? [])]);
for (const name of requirements) {
for (const prerequisite of equipment.modification(vehicle, name)?.requires ?? []) {
requirements.add(prerequisite);
}
}
return [...requirements];
}
@@ -0,0 +1,95 @@
/** Stock flight-model presets and the weapon triggers and modifications of their payloads. */
import type { BlkBlock } from '@wto/blk';
import { blockAt, boolField, numberField, stringField, stringList } from './blk-fields.ts';
import type { Dataset } from './dataset.ts';
const PACK = 'aces.vromfs.bin';
const MODEL_FILE = /^gamedata\/flightmodels\/([^/]+)\.blk$/;
export interface FlightModelPreset {
readonly name: string;
readonly auxiliary: boolean;
readonly triggers: readonly string[];
readonly requires: readonly string[];
}
export type FlightModelPresets = Readonly<Record<string, readonly FlightModelPreset[]>>;
type MountsBySlot = ReadonlyMap<number, ReadonlyMap<string, BlkBlock>>;
export const flightModelPresets: Dataset<FlightModelPresets> = {
id: 'flight-model-presets',
version: 1,
extract(source) {
const files = new Set(source.listFiles(PACK));
const payloads = new Map<string, BlkBlock>();
const entries: [string, FlightModelPreset[]][] = [];
for (const file of files) {
const unit = MODEL_FILE.exec(file)?.[1];
if (unit === undefined) continue;
const model = source.readBlk(PACK, file);
const presets = blockAt(model, 'weapon_presets');
if (!presets?.blocks.length) continue;
const mounts = readMounts(model);
entries.push([unit, presets.blocks.flatMap((preset) => {
const name = stringField(preset, 'name');
if (!name) return [];
const path = stringField(preset, 'blk')?.toLowerCase();
let payload = path === undefined ? undefined : payloads.get(path);
if (path !== undefined && payload === undefined && files.has(path)) {
payload = source.readBlk(PACK, path);
payloads.set(path, payload);
}
// Some stock presets point to absent files. Keep their place in the list without
// treating their unverified payload as a candidate.
return [readPreset(name, preset, payload, mounts)];
})]);
}
return Object.fromEntries(entries);
},
};
function readMounts(model: BlkBlock): MountsBySlot {
const slots = new Map<number, Map<string, BlkBlock>>();
for (const slot of blockAt(model, 'WeaponSlots')?.blocks ?? []) {
const index = numberField(slot, 'index');
if (slot.name !== 'WeaponSlot' || index === undefined) continue;
const choices = new Map<string, BlkBlock>();
for (const mount of slot.blocks) {
const name = stringField(mount, 'name');
if (name !== undefined) choices.set(name, mount);
}
slots.set(index, choices);
}
return slots;
}
function readPreset(name: string, definition: BlkBlock, payload: BlkBlock | undefined, mounts: MountsBySlot): FlightModelPreset {
const requires = new Set(stringList(definition, 'reqModification'));
const triggers = new Set<string>();
const visitedMounts = new Set<BlkBlock>();
function readWeapons(block: BlkBlock): void {
for (const weapon of block.blocks) {
if (weapon.name !== 'Weapon' && weapon.name !== 'DependentWeaponPreset') continue;
const trigger = stringField(weapon, 'trigger');
if (trigger !== undefined) triggers.add(trigger);
const slot = numberField(weapon, 'slot');
const preset = stringField(weapon, 'preset');
if (slot === undefined || preset === undefined) continue;
const mount = mounts.get(slot)?.get(preset);
if (mount === undefined || visitedMounts.has(mount)) continue;
visitedMounts.add(mount);
for (const requirement of stringList(mount, 'reqModification')) requires.add(requirement);
readWeapons(mount);
}
}
if (payload !== undefined) readWeapons(payload);
return {
name,
auxiliary: boolField(blockAt(definition, 'tags'), 'aux') === true,
triggers: [...triggers],
requires: [...requires],
};
}
+4 -1
View File
@@ -8,6 +8,7 @@ import { RegistrationService } from './accounts/registration-service.ts';
import { BattleEconomy } from './battle/battle-economy.ts';
import { BattleMatchmaker } from './battle/battle-matchmaker.ts';
import { BattleSessionStore } from './battle/battle-session-store.ts';
import { selectBotAircraftLoadouts } from './battle/bot-aircraft-loadouts.ts';
import { actionTable } from './char/actions/action-table.ts';
import { CharService } from './char/char-service.ts';
import { ClanStore } from './clans/clan-store.ts';
@@ -28,6 +29,7 @@ import { crewSkillData } from './game-data/datasets/crew-skills.ts';
import { DatasetCache } from './game-data/datasets/dataset-cache.ts';
import { decorCatalogue } from './game-data/datasets/decor-catalogue.ts';
import { externalItemSources } from './game-data/datasets/external-item-sources.ts';
import { flightModelPresets } from './game-data/datasets/flight-model-presets.ts';
import { itemCatalogue } from './game-data/datasets/item-catalogue.ts';
import { multiplayerMissions } from './game-data/datasets/multiplayer-missions.ts';
import { shopCountries } from './game-data/datasets/shop-countries.ts';
@@ -103,12 +105,13 @@ export async function startServer(options: ServerOptions): Promise<RunningServer
listings: catalogues.inventory.marketplaceListings(),
}, report);
const webUi = new WebUiService(datasets.load(webIcons), labels, options.dataFolder, artwork);
const botAircraftLoadouts = selectBotAircraftLoadouts(vehicles, datasets.load(flightModelPresets), equipment);
gameFiles.releasePacks();
let matching: MatchingService | undefined;
const notifyInventoryChanged = () => matching?.broadcastNotify('mrpc.generic_notify', { from: 'inventory', func: 'changed' });
const battleSessions = new BattleSessionStore(tuning.limits.battleSessionsKept);
const battleMatchmaker = new BattleMatchmaker(gameModes, vehicles, battleSessions, tuning.battle, spawnRules);
const battleMatchmaker = new BattleMatchmaker(gameModes, vehicles, battleSessions, tuning.battle, spawnRules, botAircraftLoadouts);
const economy = new BattleEconomy(
economyData,
tuning.battleEconomy,
@@ -1,5 +1,6 @@
// Start a local battle pushed by the local server: rebuild the mission settings it sends and host
// the battle as an in-process LocalMP session (select_training_mission + guiStartFlight).
// the battle as an in-process LocalMP session (select_training_mission + guiStartFlight). It preserves
// repeated text fields such as the modifications required by an AI aircraft's selected preset.
// Why the client: the stock queue only ever joins a remote room (connect_to_host_list, peer mode);
// nothing in it enters LocalMP, so no answer from the service can start a hosted battle.
// Without it: "To Battle!" queues forever.
@@ -6,10 +6,13 @@
function wtoBlkFromWire(blk, node) {
foreach (param in (node?.p ?? [])) {
let [name, kind, value] = param
blk[name] <- kind == "i" ? value.tointeger()
: kind == "r" ? value.tofloat()
: kind == "b" ? value == true
: value.tostring()
// Aircraft loadouts can send several native addModification entries in one block.
if (kind == "t")
blk.addStr(name, value.tostring())
else
blk[name] <- kind == "i" ? value.tointeger()
: kind == "r" ? value.tofloat()
: value == true
}
foreach (child in (node?.b ?? []))
wtoBlkFromWire(blk.addNewBlock(child[0]), child[1])