diff --git a/apps/launcher/src/main/services/resources/resource-paths.ts b/apps/launcher/src/main/services/resources/resource-paths.ts index 231994a..0ff8410 100644 --- a/apps/launcher/src/main/services/resources/resource-paths.ts +++ b/apps/launcher/src/main/services/resources/resource-paths.ts @@ -19,6 +19,8 @@ export interface ResourcePaths { readonly appIcon: string; /** Bundled example mod templates seeded into an empty mods folder on first use. */ readonly modTemplates: string; + /** Modular ground AI daScript sources injected into `game.vromfs.bin` when active. */ + readonly groundAiScripts: string; } export function resourcePaths(): ResourcePaths { @@ -35,6 +37,7 @@ export function bundledResourcePaths(): ResourcePaths { networkHookLibrary: join(process.resourcesPath, 'native', 'wto_ws.dll'), appIcon: join(process.resourcesPath, 'icon.ico'), modTemplates: join(process.resourcesPath, 'mod-templates'), + groundAiScripts: join(process.resourcesPath, 'game-ai', 'ground'), }; } // The app path is apps/launcher; the repository is two levels up. @@ -44,6 +47,7 @@ export function bundledResourcePaths(): ResourcePaths { networkHookLibrary: join(repository, 'build', 'native', 'wto_ws.dll'), appIcon: join(repository, 'apps', 'launcher', 'resources', 'icon.ico'), modTemplates: join(repository, 'mod-dev-docs', 'templates'), + groundAiScripts: join(repository, 'game-ai', 'ground'), }; } diff --git a/apps/launcher/src/main/workers/build-protocol.ts b/apps/launcher/src/main/workers/build-protocol.ts index 317e4e7..3b0a1a6 100644 --- a/apps/launcher/src/main/workers/build-protocol.ts +++ b/apps/launcher/src/main/workers/build-protocol.ts @@ -9,6 +9,7 @@ export interface BuildRequest { readonly port: number; readonly patches: string; readonly networkHookLibrary: string; + readonly groundAiScripts: string; readonly decalCache?: string; readonly hookLogging: boolean; readonly acceptedUnavailable: readonly string[]; diff --git a/apps/launcher/src/main/workers/build-worker.ts b/apps/launcher/src/main/workers/build-worker.ts index 311f22a..000a450 100644 --- a/apps/launcher/src/main/workers/build-worker.ts +++ b/apps/launcher/src/main/workers/build-worker.ts @@ -8,15 +8,18 @@ import { computeModsBuildFingerprint, copyPlayerDecalCache, CORE_BUILD_PACKS, + GAME_PACK_FILE, + isGroundAiActive, playerDecalCacheProblem, prepareOptionalStockPacks, readPlayerDecalIndexFiles, readStockGameFiles, syncExternalModFiles, writeGameCopy, + type GameCopyBuild, type GameCopyFile, } from '@wto/patcher'; -import { multiVehiclePackIds } from '@wto/server'; +import { loadGroundAiTuning, multiVehiclePackIds } from '@wto/server'; import type { BuildCommand, BuildReply, BuildRequest } from './build-protocol.ts'; let prepared: { @@ -61,13 +64,34 @@ function resolveOrderedMods(modsDir: string | undefined, enabledModIds: readonly return ordered; } +function logModBuildSummary(result: GameCopyBuild): void { + if (result.gamePack) { + console.info(`[build] injected ${result.gamePack.modules.length} ground AI module(s) into ${result.gamePack.archiveFolder}`); + } + if (result.mods.enabledModIds.length === 0) return; + console.info( + `[build] applied ${result.mods.enabledModIds.length} mod(s): ${result.mods.enabledModIds.join(', ')} ` + + `(pack overlays=${result.mods.packOverlays.length}, addons=${result.mods.addonMounts.length}, ` + + `gui=${result.mods.guiPatches.applied.length} ok/${result.mods.guiPatches.failures.length} failed, ` + + `exe=${result.mods.exePatches.applied.length} ok/${result.mods.exePatches.failures.length} failed)`, + ); + for (const failure of [...result.mods.guiPatches.failures, ...result.mods.exePatches.failures]) { + console.warn(`[build] mod "${failure.modId}" patch "${failure.patchId}" skipped: ${failure.reason}`); + } +} + function build(request: BuildRequest): void { checkBuildLocation(request); const decalCache = importedDecals(request.decalCache); const decalIndexFiles = decalCache ? readPlayerDecalIndexFiles(decalCache) : undefined; const enabledMods = resolveOrderedMods(request.modsDir, request.enabledModIds); - const touchedPacks = touchedClientPacks(enabledMods); - const optionalPacksInBuild = touchedPacks.filter((pack) => !CORE_BUILD_PACKS.has(pack)); + const groundAiConfig = loadGroundAiTuning(request.dataPath, console.info, enabledMods); + const groundAiActive = isGroundAiActive(groundAiConfig); + const touchedSet = new Set( + touchedClientPacks(enabledMods).filter((pack) => !CORE_BUILD_PACKS.has(pack)), + ); + if (groundAiActive) touchedSet.add(GAME_PACK_FILE); + const optionalPacksInBuild = [...touchedSet]; const extraStockPacks = optionalPacksInBuild.length > 0 ? prepareOptionalStockPacks(request.copyPath, request.stockPath, optionalPacksInBuild) : undefined; @@ -83,6 +107,7 @@ function build(request: BuildRequest): void { hookLogging: request.hookLogging, ...(enabledMods.length > 0 ? { mods: enabledMods } : {}), ...(extraStockPacks ? { extraStockPacks } : {}), + groundAi: { scriptsFolder: request.groundAiScripts, config: groundAiConfig }, }); const unavailable = [...result.exePatches.failures, ...result.guiPatches.failures, ...result.nativeModules.failures]; const accepted = new Set(request.acceptedUnavailable); @@ -91,18 +116,12 @@ function build(request: BuildRequest): void { send({ kind: 'failed', error: 'launch_build_unavailable' }); return; } - if (result.mods.enabledModIds.length > 0) { - console.info( - `[build] applied ${result.mods.enabledModIds.length} mod(s): ${result.mods.enabledModIds.join(', ')} ` + - `(pack overlays=${result.mods.packOverlays.length}, addons=${result.mods.addonMounts.length}, ` + - `gui=${result.mods.guiPatches.applied.length} ok/${result.mods.guiPatches.failures.length} failed, ` + - `exe=${result.mods.exePatches.applied.length} ok/${result.mods.exePatches.failures.length} failed)`, - ); - for (const failure of [...result.mods.guiPatches.failures, ...result.mods.exePatches.failures]) { - console.warn(`[build] mod "${failure.modId}" patch "${failure.patchId}" skipped: ${failure.reason}`); - } - } - const fingerprint = computeModsBuildFingerprint(enabledMods, request.port, request.patches); + logModBuildSummary(result); + const fingerprint = computeModsBuildFingerprint( + enabledMods, + request.port, + `${request.patches}|groundAi=${JSON.stringify(groundAiConfig)}`, + ); prepared = { request, files: result.files, decalCache, enabledMods, optionalPacksInBuild, fingerprint }; send({ kind: 'prepared', total: prepared.files.length }); } diff --git a/apps/server/src/battle/battle-matchmaker.ts b/apps/server/src/battle/battle-matchmaker.ts index bfcc421..e93b68c 100644 --- a/apps/server/src/battle/battle-matchmaker.ts +++ b/apps/server/src/battle/battle-matchmaker.ts @@ -19,11 +19,13 @@ import { isModeEligibleForLineup, lineupMrank, selectCustomBots, + type TankLineupWeights, 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 { BotTankLoadout } from './bot-tank-loadouts.ts'; import type { BattleTuning } from './battle-tuning.ts'; export interface BattleCrewSlot { @@ -104,6 +106,8 @@ export class BattleMatchmaker { readonly #tuning: BattleTuning; readonly #spawnRules: BattleSpawnRulesData; readonly #aircraftLoadouts: ReadonlyMap; + readonly #tankWeights: TankLineupWeights | undefined; + readonly #tankLoadouts: ReadonlyMap | undefined; readonly #filterMissions: MissionPoolFilter | undefined; constructor( @@ -113,6 +117,8 @@ export class BattleMatchmaker { tuning: BattleTuning, spawnRules: BattleSpawnRulesData, aircraftLoadouts: ReadonlyMap, + tankWeights: TankLineupWeights | undefined, + tankLoadouts?: ReadonlyMap, filterMissions?: MissionPoolFilter, ) { this.#gameModes = gameModes; @@ -122,6 +128,8 @@ export class BattleMatchmaker { this.#tuning = tuning; this.#spawnRules = spawnRules; this.#aircraftLoadouts = aircraftLoadouts; + this.#tankWeights = tankWeights; + this.#tankLoadouts = tankLoadouts; this.#filterMissions = filterMissions; } @@ -181,7 +189,7 @@ export class BattleMatchmaker { minMrank, maxMrank, limitPerType: this.#tuning.botPoolLimitPerType, - }, declaration.allowBotAircraftLoadouts === false ? undefined : this.#aircraftLoadouts); + }, declaration.allowBotAircraftLoadouts === false ? undefined : this.#aircraftLoadouts, this.#tankWeights, this.#tankLoadouts); return { ok: true, launch: this.#buildLaunchPlan(input, chosenMode, mission, coalitions, playerMrank, minMrank, maxMrank, customBots), diff --git a/apps/server/src/battle/battle-mission-settings.ts b/apps/server/src/battle/battle-mission-settings.ts index 1099625..bc4571d 100644 --- a/apps/server/src/battle/battle-mission-settings.ts +++ b/apps/server/src/battle/battle-mission-settings.ts @@ -130,6 +130,7 @@ function customBotsBlock(plan: BattleLaunchPlan): BlkBlock { setParam(bots, 'wtoPlayerTeam', text(String(plan.playerTeam))); setParam(bots, 'wtoTeamACountries', text(plan.countriesAllies.join(';'))); setParam(bots, 'wtoTeamBCountries', text(plan.countriesAxis.join(';'))); + if (plan.mission.groundMode !== undefined) setParam(bots, 'wtoGroundMode', text(plan.mission.groundMode)); if (plan.maxRespawns === UNLIMITED_RESPAWNS) setParam(bots, 'wtoUnlimitedRespawns', text('1')); setParam(bots, 'numBotRespawnsInMultiSlot', integer(plan.airBotRespawns)); setParam(bots, 'numTankBotRespawnsInMultiSlot', integer(plan.tankBotRespawns)); @@ -140,6 +141,7 @@ function customBotsBlock(plan: BattleLaunchPlan): BlkBlock { poolBlock('allowedAircrafts', 'aircraft', plan.customBots.aircrafts), poolBlock('allowedShips', 'ship', plan.customBots.ships), ); + addTankAmmoParams(bots, plan.customBots.tanks); return bots; } @@ -155,11 +157,26 @@ function poolBlock(name: string, entryName: string, entries: CustomBotsPool['tan setParam(ensureBlock(block, 'preset'), 'name', text(loadout.preset)); for (const modification of loadout.modifications) appendParam(block, 'addModification', text(modification)); } + if (entry.tankLoadout !== undefined) { + for (const modification of entry.tankLoadout.modifications) appendParam(block, 'addModification', text(modification)); + } pool.blocks.push(block); } return pool; } +/** Per-tank bot ammo strings (`weapon|mod0:count0|mod1:count1`) read by local_mp_loadout.c. */ +function addTankAmmoParams(bots: BlkBlock, entries: CustomBotsPool['tanks']): void { + const seen = new Set(); + for (const entry of entries) { + const loadout = entry.tankLoadout; + if (!loadout || loadout.bullets.length === 0 || seen.has(entry.name)) continue; + seen.add(entry.name); + const parts = [loadout.weaponName, ...loadout.bullets.slice(0, 2).map((s) => `${s.modName}:${s.count}`)]; + setParam(bots, `wtoAmmo_${entry.name}`, text(parts.join('|'))); + } +} + function text(value: string): BlkValue { return { type: 'string', value }; } diff --git a/apps/server/src/battle/battle-ranks.ts b/apps/server/src/battle/battle-ranks.ts index d05ae3c..a3b21a6 100644 --- a/apps/server/src/battle/battle-ranks.ts +++ b/apps/server/src/battle/battle-ranks.ts @@ -10,6 +10,7 @@ import type { CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.t 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'; +import type { BotTankLoadout } from './bot-tank-loadouts.ts'; const COUNTRY_PREFIX = 'country_'; @@ -23,6 +24,7 @@ export interface BotPoolEntry { readonly country: string; readonly weight: number; readonly aircraftLoadout?: BotAircraftLoadout; + readonly tankLoadout?: BotTankLoadout; } export interface CustomBotsPool { @@ -31,6 +33,16 @@ export interface CustomBotsPool { readonly ships: readonly BotPoolEntry[]; } +/** Offline tank pool weights by vehicle class (`tuning/ground-ai.jsonc` `lineupWeights`). */ +export interface TankLineupWeights { + readonly spaa: number; + readonly lightTank: number; + readonly tankDestroyer: number; + readonly heavyTank: number; + readonly mediumTank: number; + readonly other: number; +} + export interface BotPoolQuery { readonly difficulty: ModeDifficulty; readonly requiredClass: UnitClass; @@ -117,14 +129,25 @@ function lineupVehicleMrank( return vehicleMrank(vehicle, difficulty, requiredClass) + (mrankDeltas.get(vehicle.name) ?? 0); } +/** + * Without `tankWeights` every pool entry keeps the stock weight of 1. + */ export function selectCustomBots( - vehicles: readonly CatalogueVehicle[], query: BotPoolQuery, aircraftLoadouts?: ReadonlyMap, + vehicles: readonly CatalogueVehicle[], + query: BotPoolQuery, + aircraftLoadouts?: ReadonlyMap, + tankWeights?: TankLineupWeights, + tankLoadouts?: ReadonlyMap, ): 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) : []; + const rawTanks = allowed.has('tank') ? pickCategoryPool(vehicles, orderedCountries, 'tank', query, tankWeights) : []; return { - tanks: allowed.has('tank') ? pickCategoryPool(vehicles, orderedCountries, 'tank', query) : [], + tanks: tankLoadouts ? rawTanks.map((entry) => { + const tankLoadout = tankLoadouts.get(entry.name); + return tankLoadout === undefined ? entry : { ...entry, tankLoadout }; + }) : rawTanks, aircrafts: query.requiredClass === 'aircraft' && aircraftLoadouts ? aircrafts.map((entry) => { const aircraftLoadout = aircraftLoadouts.get(entry.name); return aircraftLoadout === undefined ? entry : { ...entry, aircraftLoadout }; @@ -138,6 +161,7 @@ function pickCategoryPool( orderedCountries: readonly string[], category: 'tank' | 'aircraft' | 'ship', query: BotPoolQuery, + tankWeights?: TankLineupWeights, ): BotPoolEntry[] { const countrySet = new Set(orderedCountries); const eligible = vehicles.filter((vehicle) => @@ -161,13 +185,14 @@ function pickCategoryPool( return mrank >= query.minMrank && mrank <= query.maxMrank; }); const source = inWindow.length > 0 ? inWindow : sortedByCloseness.slice(0, query.limitPerType); - return roundRobinByCountry(source, orderedCountries, query.limitPerType); + return roundRobinByCountry(source, orderedCountries, query.limitPerType, (vehicle) => tankPoolWeight(vehicle, tankWeights)); } function roundRobinByCountry( vehicles: readonly CatalogueVehicle[], orderedCountries: readonly string[], limit: number, + weightOf: (vehicle: CatalogueVehicle) => number, ): BotPoolEntry[] { const buckets = new Map(orderedCountries.map((country) => [country, []])); for (const vehicle of vehicles) buckets.get(vehicle.country)?.push(vehicle); @@ -177,7 +202,7 @@ function roundRobinByCountry( for (const country of orderedCountries) { const vehicle = buckets.get(country)?.[index]; if (!vehicle) continue; - out.push({ name: vehicle.name, country: stripCountryPrefix(country), weight: 1 }); + out.push({ name: vehicle.name, country: stripCountryPrefix(country), weight: weightOf(vehicle) }); added = true; if (out.length >= limit) break; } @@ -186,6 +211,16 @@ function roundRobinByCountry( return out; } +function tankPoolWeight(vehicle: CatalogueVehicle, weights: TankLineupWeights | undefined): number { + if (weights === undefined) return 1; + if (vehicle.unitClass === 'exp_SPAA') return weights.spaa; + if (vehicle.isLightTank) return weights.lightTank; + if (vehicle.unitClass === 'exp_tank_destroyer') return weights.tankDestroyer; + if (vehicle.unitClass === 'exp_heavy_tank') return weights.heavyTank; + if (vehicle.unitClass === 'exp_tank') return weights.mediumTank; + return weights.other; +} + function unitClassOfVehicleType(type: VehicleType | undefined): UnitClass | undefined { if (type === 'Tank') return 'tank'; if (type === 'Aircraft') return 'aircraft'; diff --git a/apps/server/src/battle/bot-tank-loadouts.ts b/apps/server/src/battle/bot-tank-loadouts.ts new file mode 100644 index 0000000..d8bacfb --- /dev/null +++ b/apps/server/src/battle/bot-tank-loadouts.ts @@ -0,0 +1,135 @@ +/** + * Offline AI tank spawn ammunition selector: + * - Total carried rounds follow the vehicle's first-stage / autoloader ready rack, topped up + * when below the configured threshold (clamped to main gun capacity). + * - Primary shell prefers legal APFSDS, otherwise ranks anti-armor shells by 500 m penetration. + * - Secondary shell carries a small share of HE / HEAT / HESH when available for soft targets. + */ +import type { GroundAiLoadoutConfig } from '@wto/patcher'; +import type { TankAmmoProfile, TankBotAmmoData, TankShellChoice } from '../game-data/datasets/tank-bot-ammo.ts'; +import type { CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.ts'; +import { vehicleTypeOfClass } from '../research/vehicle-types.ts'; + +export interface BotTankBulletSlot { + readonly modName: string; + readonly count: number; +} + +export interface BotTankLoadout { + readonly weaponName: string; + readonly bullets: readonly BotTankBulletSlot[]; + readonly modifications: readonly string[]; +} + +export function selectBotTankLoadouts( + vehicles: readonly CatalogueVehicle[], + ammoData: TankBotAmmoData, + config: GroundAiLoadoutConfig, +): ReadonlyMap { + const result = new Map(); + for (const vehicle of vehicles) { + if (vehicleTypeOfClass(vehicle.unitClass) !== 'Tank' || vehicle.unitClass === 'exp_SPAA') continue; + const profile = ammoData[vehicle.name]; + if (!profile || profile.isBelt || profile.maxBullets <= 0) continue; + const loadout = chooseTankLoadout(profile, config); + if (loadout !== undefined) result.set(vehicle.name, loadout); + } + return result; +} + +function chooseTankLoadout(profile: TankAmmoProfile, config: GroundAiLoadoutConfig): BotTankLoadout | undefined { + const combatShells = profile.shells.filter((shell) => !isNonCombatShell(shell.bulletType)); + if (combatShells.length === 0) return undefined; + + const primary = pickPrimaryShell(combatShells); + if (!primary) return undefined; + const totalRounds = computeCarriedRounds(profile, config); + if (totalRounds <= 0) return undefined; + + const secondary = pickSecondaryShell(combatShells, primary); + const bullets = splitRounds(primary, secondary, totalRounds, config); + const modSet = new Set(); + for (const chosen of [primary, ...(bullets.length > 1 && secondary ? [secondary] : [])]) { + if (chosen.modName) modSet.add(chosen.modName); + for (const req of chosen.requires) modSet.add(req); + } + return { + weaponName: profile.weaponName, + bullets, + modifications: [...modSet].sort(), + }; +} + +function computeCarriedRounds(profile: TankAmmoProfile, config: GroundAiLoadoutConfig): number { + const want = profile.readyRack >= config.lowReadyRackThreshold + ? profile.readyRack + : config.topUpAmmoCount; + return Math.max(1, Math.min(want, profile.maxBullets)); +} + +function pickPrimaryShell(shells: readonly TankShellChoice[]): TankShellChoice | undefined { + const ranked = [...shells].sort((a, b) => compareAntiArmor(a, b)); + return ranked[0]; +} + +function compareAntiArmor(a: TankShellChoice, b: TankShellChoice): number { + const tierA = antiArmorTier(a.bulletType); + const tierB = antiArmorTier(b.bulletType); + if (tierA !== tierB) return tierB - tierA; + const scoreA = a.pen500Mm + (isApheFamily(a.bulletType) ? 12 : 0); + const scoreB = b.pen500Mm + (isApheFamily(b.bulletType) ? 12 : 0); + if (scoreA !== scoreB) return scoreB - scoreA; + if (a.speedMps !== b.speedMps) return b.speedMps - a.speedMps; + return a.modName.localeCompare(b.modName); +} + +function antiArmorTier(bulletType: string): number { + if (bulletType.includes('apds_fs')) return 5; + if (bulletType.includes('atgm')) return 4; + if (bulletType.includes('apds')) return 3; + if (bulletType.includes('heat') || isApheFamily(bulletType) || bulletType.startsWith('ap')) return 2; + if (bulletType.includes('hesh')) return 1; + return 0; +} + +function pickSecondaryShell(shells: readonly TankShellChoice[], primary: TankShellChoice): TankShellChoice | undefined { + const candidates = shells.filter((shell) => shell.modName !== primary.modName && isSoftTargetShell(shell.bulletType)); + if (candidates.length === 0) return undefined; + return [...candidates].sort((a, b) => { + const heA = a.bulletType.includes('he_frag') ? 2 : (a.bulletType.includes('hesh') ? 1 : 0); + const heB = b.bulletType.includes('he_frag') ? 2 : (b.bulletType.includes('hesh') ? 1 : 0); + if (heA !== heB) return heB - heA; + if (a.speedMps !== b.speedMps) return b.speedMps - a.speedMps; + return a.modName.localeCompare(b.modName); + })[0]; +} + +function splitRounds( + primary: TankShellChoice, + secondary: TankShellChoice | undefined, + totalRounds: number, + config: GroundAiLoadoutConfig, +): BotTankBulletSlot[] { + if (!secondary || config.primaryAmmoPct >= 100 || config.secondaryMinRounds <= 0 || totalRounds < config.secondaryMinRounds * 2 + 2) { + return [{ modName: primary.modName, count: totalRounds }]; + } + const wantSec = Math.round((totalRounds * (100 - config.primaryAmmoPct)) / 100); + const secCount = Math.min(totalRounds - 1, Math.max(config.secondaryMinRounds, wantSec)); + const priCount = totalRounds - secCount; + return [ + { modName: primary.modName, count: priCount }, + { modName: secondary.modName, count: secCount }, + ]; +} + +function isNonCombatShell(bulletType: string): boolean { + return bulletType.includes('smoke') || bulletType.includes('practice') || bulletType.includes('shrapnel'); +} + +function isSoftTargetShell(bulletType: string): boolean { + return bulletType.includes('he_frag') || bulletType.includes('hesh') || bulletType.includes('heat'); +} + +function isApheFamily(bulletType: string): boolean { + return bulletType.includes('aphe') || bulletType.includes('apcbc') || bulletType.includes('apbc'); +} diff --git a/apps/server/src/cli.ts b/apps/server/src/cli.ts index 2d4c45c..619b50d 100644 --- a/apps/server/src/cli.ts +++ b/apps/server/src/cli.ts @@ -7,24 +7,45 @@ * will start the service the same way. Stops on Ctrl+C. */ import { parseArgs } from 'node:util'; +import { discoverMods, type DiscoveredMod } from '@wto/mods'; import { LOOPBACK, startServer } from './server.ts'; +function resolveCliMods(modsDir: string | undefined, modIds: readonly string[] | undefined): DiscoveredMod[] { + if (!modsDir || !modIds || modIds.length === 0) return []; + const discovered = discoverMods(modsDir); + const byId = new Map(discovered.mods.map((mod) => [mod.manifest.id, mod])); + return modIds.map((id) => { + const mod = byId.get(id); + if (!mod) throw new Error(`enabled mod "${id}" was not found in ${modsDir}`); + return mod; + }); +} + async function main(): Promise { const { values } = parseArgs({ options: { game: { type: 'string' }, data: { type: 'string' }, port: { type: 'string' }, + 'mods-dir': { type: 'string' }, + mod: { type: 'string', multiple: true }, }, }); const port = Number(values.port); if (!values.game || !values.data || !Number.isInteger(port) || port < 1 || port > 65535) { - console.error('usage: cli.ts --game --data --port '); + console.error('usage: cli.ts --game --data --port [--mods-dir --mod ...]'); return 2; } let service; try { - service = await startServer({ gameFolder: values.game, dataFolder: values.data, port, report: (line) => console.log(line) }); + const mods = resolveCliMods(values['mods-dir'], values.mod); + service = await startServer({ + gameFolder: values.game, + dataFolder: values.data, + port, + report: (line) => console.log(line), + ...(mods.length > 0 ? { mods } : {}), + }); } catch (error) { const code = (error as NodeJS.ErrnoException).code; console.error(code === 'EADDRINUSE' ? `port ${port} is already in use; choose another port` : String(error)); diff --git a/apps/server/src/game-data/datasets/multiplayer-missions.ts b/apps/server/src/game-data/datasets/multiplayer-missions.ts index 97ea389..dc2d3b6 100644 --- a/apps/server/src/game-data/datasets/multiplayer-missions.ts +++ b/apps/server/src/game-data/datasets/multiplayer-missions.ts @@ -41,9 +41,13 @@ interface AirfieldLayoutData { readonly airfieldLayoutProblem?: string; } +export type GroundBattleMode = 'bttl' | 'conq' | 'dom'; + export interface MissionHeader extends AirfieldLayoutData { readonly name: string; readonly path: string; + /** Ground mission tactical layout derived from mislist category (or suffix fallback for events). */ + readonly groundMode?: GroundBattleMode; readonly level?: string; readonly type?: string; readonly environment?: string; @@ -72,7 +76,7 @@ export interface MultiplayerMissions { export const multiplayerMissions: Dataset = { id: 'multiplayer-missions', - version: 4, + version: 5, 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`); @@ -82,6 +86,7 @@ export const multiplayerMissions: Dataset = { missions: stringList(block, 'm'), })); + const groundModeByMission = indexGroundModes(categories); const paths = source.listFiles('mis.vromfs.bin'); const pathByName = missionPathsByLowerName(paths); const knownPaths = new Set(paths); @@ -94,12 +99,34 @@ export const multiplayerMissions: Dataset = { const document = source.readBlk('mis.vromfs.bin', path); const airfields = path.startsWith(AIR_HISTORICAL_MISSION_FOLDER) ? readAirfieldLayouts(source, document, knownPaths, airfieldsByPath) : { airfieldLayouts: [] }; - missions[name] = readHeader(name, path, document, airfields); + const groundMode = groundModeByMission.get(name) ?? groundModeFromName(name); + missions[name] = readHeader(name, path, document, airfields, groundMode); } return { categories, missions }; }, }; +function indexGroundModes(categories: readonly MissionCategory[]): Map { + const byName = new Map(); + for (const category of categories) { + const mode: GroundBattleMode | undefined = + category.name === 'air_ground_Bttl' ? 'bttl' + : category.name === 'air_ground_Conq' ? 'conq' + : category.name === 'air_ground_Dom' ? 'dom' + : undefined; + if (!mode) continue; + for (const name of category.missions) if (!byName.has(name)) byName.set(name, mode); + } + return byName; +} + +function groundModeFromName(name: string): GroundBattleMode | undefined { + if (/_Bttl\d*$/i.test(name)) return 'bttl'; + if (/_Conq\d*$/i.test(name)) return 'conq'; + if (/_Dom\d*$/i.test(name)) return 'dom'; + return undefined; +} + function missionPathsByLowerName(paths: readonly string[]): Map { const byName = new Map(); const repeated = new Set(); @@ -114,11 +141,12 @@ function missionPathsByLowerName(paths: readonly string[]): Map } function readHeader( - name: string, path: string, document: BlkBlock, airfields: AirfieldLayoutData, + name: string, path: string, document: BlkBlock, airfields: AirfieldLayoutData, groundMode?: GroundBattleMode, ): MissionHeader { const settings = blockAt(document, 'mission_settings'); const mission = blockAt(settings, 'mission'); const optional = { + groundMode, level: stringField(mission, 'level'), type: stringField(mission, 'type'), environment: stringField(mission, 'environment'), diff --git a/apps/server/src/game-data/datasets/tank-bot-ammo.ts b/apps/server/src/game-data/datasets/tank-bot-ammo.ts new file mode 100644 index 0000000..91d79ab --- /dev/null +++ b/apps/server/src/game-data/datasets/tank-bot-ammo.ts @@ -0,0 +1,244 @@ +/** + * Dataset: primary cannon weapon name, capacity, first-stage/autoloader ready-rack count, + * and selectable ammunition groups (with penetration and prerequisite modifications) for + * every ground tank model in `aces.vromfs.bin` + `char.vromfs.bin`. + */ +import { findBlock, type BlkBlock } from '@wto/blk'; +import type { Dataset, DatasetSource } from './dataset.ts'; +import { boolField, numberField, stringField, stringList } from './blk-fields.ts'; + +const VEHICLE_ECONOMY = 'config/wpcost.blk'; +const MODIFICATIONS_CONFIG = 'config/modifications.blk'; +const TANK_MODELS_PREFIX = 'gamedata/units/tankmodels/'; + +export interface TankShellChoice { + /** Modification name expected by ChangeUnitReflection.bullets[i] (`""` for stock default). */ + readonly modName: string; + readonly bulletType: string; + readonly speedMps: number; + /** Estimated normal penetration at 500 m (mm) for deterministic ranking. */ + readonly pen500Mm: number; + /** Transitive prerequisite modifications needed to unlock this shell. */ + readonly requires: readonly string[]; +} + +export interface TankAmmoProfile { + readonly weaponName: string; + readonly maxBullets: number; + readonly isBelt: boolean; + /** Total firstStage / autoLoad / ammoLoadedInGun shell slots (excluding separate charges). */ + readonly readyRack: number; + readonly shells: readonly TankShellChoice[]; +} + +export type TankBotAmmoData = Readonly>; + +interface GlobalModInfo { + readonly bulletMod?: string; + readonly requires: readonly string[]; +} + +interface WeaponBulletMeta { + readonly bulletType: string; + readonly speedMps: number; + readonly pen500Mm: number; +} + +export const tankBotAmmo: Dataset = { + id: 'tank-bot-ammo', + version: 2, + extract(source: DatasetSource): TankBotAmmoData { + const globalMods = readGlobalModInfo(source.readBlk('char.vromfs.bin', MODIFICATIONS_CONFIG)); + const wpcost = source.readBlk('char.vromfs.bin', VEHICLE_ECONOMY); + const acesPaths = new Set(source.listFiles('aces.vromfs.bin').map((p) => p.toLowerCase())); + const weaponCache = new Map }>(); + const out: Record = {}; + + for (const vehicleBlk of wpcost.blocks) { + const unitPath = `${TANK_MODELS_PREFIX}${vehicleBlk.name.toLowerCase()}.blk`; + if (!acesPaths.has(unitPath)) continue; + const profile = extractTankProfile(source, acesPaths, weaponCache, globalMods, vehicleBlk, unitPath); + if (profile !== undefined) out[vehicleBlk.name] = profile; + } + return out; + }, +}; + +function readGlobalModInfo(root: BlkBlock): ReadonlyMap { + const mods = findBlock(root, 'modifications'); + const map = new Map(); + for (const entry of mods?.blocks ?? []) { + const effects = findBlock(entry, 'effects'); + const bulletMod = stringField(effects, 'additiveBulletMod') ?? stringField(effects, 'bulletMod'); + map.set(entry.name, { + ...(bulletMod !== undefined ? { bulletMod } : {}), + requires: stringList(entry, 'reqModification'), + }); + } + return map; +} + +function extractTankProfile( + source: DatasetSource, + acesPaths: ReadonlySet, + weaponCache: Map }>, + globalMods: ReadonlyMap, + wpcostVehicle: BlkBlock, + unitPath: string, +): TankAmmoProfile | undefined { + const unitBlk = source.readBlk('aces.vromfs.bin', unitPath); + const mainWeapon = findMainGunBlock(unitBlk); + if (!mainWeapon) return undefined; + const rawBlkPath = stringField(mainWeapon, 'blk'); + const maxBullets = Math.trunc(numberField(mainWeapon, 'bullets') ?? 0); + if (!rawBlkPath || maxBullets <= 0) return undefined; + const lowerBlkPath = rawBlkPath.toLowerCase(); + if (!acesPaths.has(lowerBlkPath)) return undefined; + + const weaponName = basenameWithoutExt(rawBlkPath); + const weaponMeta = loadWeaponMeta(source, weaponCache, lowerBlkPath); + const readyRack = countReadyRackShells(unitBlk, stringField(mainWeapon, 'trigger') ?? 'gunner0'); + const shells = collectSelectableShells(wpcostVehicle, unitBlk, globalMods, weaponMeta); + if (shells.length === 0) return undefined; + return { weaponName, maxBullets, isBelt: weaponMeta.isBelt, readyRack, shells }; +} + +function findMainGunBlock(unitBlk: BlkBlock): BlkBlock | undefined { + const common = findBlock(unitBlk, 'commonWeapons'); + if (!common) return undefined; + return common.blocks.find((block) => + stringField(block, 'trigger') === 'gunner0' + && !(stringField(block, 'blk') ?? '').toLowerCase().includes('dummy_weapon')); +} + +function countReadyRackShells(unitBlk: BlkBlock, mainTrigger: string): number { + const stowages = findBlock(unitBlk, 'ammoStowages'); + if (!stowages) return 0; + let total = 0; + for (const stow of stowages.blocks) { + const triggers = stringList(stow, 'weaponTrigger'); + if (triggers.length > 0 && !triggers.includes(mainTrigger)) continue; + for (const cluster of stow.blocks) { + if (cluster.name !== 'shells') continue; + const isReady = boolField(cluster, 'firstStage') === true + || boolField(cluster, 'autoLoad') === true + || boolField(cluster, 'ammoLoadedInGun') === true; + if (!isReady) continue; + for (const slot of cluster.blocks) total += Math.max(0, Math.trunc(numberField(slot, 'count') ?? 0)); + } + } + return total; +} + +function loadWeaponMeta( + source: DatasetSource, + cache: Map }>, + lowerPath: string, +) { + const cached = cache.get(lowerPath); + if (cached) return cached; + const blk = source.readBlk('aces.vromfs.bin', lowerPath); + const isBelt = boolField(blk, 'isBulletBelt') === true; + const defaultBlock = findBlock(blk, 'bullet'); + const defaultBullet = defaultBlock ? parseBulletMeta(defaultBlock) : undefined; + const sets = new Map(); + for (const child of blk.blocks) { + if (child.name === 'bullet') continue; + const subBullet = findBlock(child, 'bullet'); + if (!subBullet) continue; + const meta = parseBulletMeta(subBullet); + if (meta) sets.set(child.name, meta); + } + const entry = { isBelt, ...(defaultBullet ? { defaultBullet } : {}), sets }; + cache.set(lowerPath, entry); + return entry; +} + +function parseBulletMeta(bullet: BlkBlock): WeaponBulletMeta | undefined { + const bulletType = (stringField(bullet, 'bulletType') ?? '').toLowerCase(); + if (!bulletType) return undefined; + const speedMps = numberField(bullet, 'speed') ?? 0; + const pen500Mm = estimatePen500Mm(bullet, bulletType, speedMps); + return { bulletType, speedMps, pen500Mm }; +} + +function estimatePen500Mm(bullet: BlkBlock, bulletType: string, speedMps: number): number { + const cum = numberField(findBlock(bullet, 'cumulativeDamage'), 'armorPower'); + const apBlock = findBlock(bullet, 'armorpower'); + const ap500 = numberField(apBlock, 'ArmorPower500m') ?? numberField(apBlock, 'ArmorPower0m') ?? 0; + if (bulletType.includes('apds_fs')) { + const dmgBlock = findBlock(bullet, 'damage'); + const kinetic = dmgBlock ? findBlock(dmgBlock, 'kinetic') : undefined; + const workLen = numberField(kinetic, 'lanzOdermattWorkingLength') + ?? numberField(kinetic, 'WorkingLength') + ?? numberField(kinetic, 'Length') + ?? 0; + const density = numberField(kinetic, 'lanzOdermattDensity') ?? numberField(kinetic, 'Density') ?? 17000; + if (workLen > 0) return Math.max(ap500, Math.round(workLen * Math.sqrt(density / 7850) * (speedMps / 1700) * 0.85)); + return Math.max(ap500, Math.round(speedMps * 0.24)); + } + if (cum !== undefined && cum > ap500) return cum; + if (ap500 > 0) return ap500; + const mass = numberField(bullet, 'mass') ?? 0; + const cal = numberField(bullet, 'damageCaliber') ?? numberField(bullet, 'caliber') ?? 0; + if (mass > 0 && cal > 0 && speedMps > 100 && !bulletType.includes('he_') && !bulletType.includes('smoke')) { + return Math.round(0.0022 * Math.pow(mass, 0.55) * Math.pow(speedMps, 1.43) / Math.pow(cal * 1000, 0.65)); + } + return 0; +} + +function collectSelectableShells( + wpcostVehicle: BlkBlock, + unitBlk: BlkBlock, + globalMods: ReadonlyMap, + weaponMeta: { defaultBullet?: WeaponBulletMeta; sets: Map }, +): TankShellChoice[] { + const out: TankShellChoice[] = []; + if (weaponMeta.defaultBullet) { + out.push({ modName: '', ...weaponMeta.defaultBullet, requires: [] }); + } + const wpModsBlock = findBlock(wpcostVehicle, 'modifications'); + const unitModsBlock = findBlock(unitBlk, 'modifications'); + const reqMap = new Map(); + for (const mod of wpModsBlock?.blocks ?? []) reqMap.set(mod.name, stringList(mod, 'reqModification')); + + for (const mod of wpModsBlock?.blocks ?? []) { + if (numberField(mod, 'ammoCount') === undefined) continue; + const unitMod = unitModsBlock ? findBlock(unitModsBlock, mod.name) : undefined; + const unitModEffects = unitMod ? findBlock(unitMod, 'effects') : undefined; + const setName = stringField(unitModEffects, 'additiveBulletMod') + ?? stringField(unitModEffects, 'bulletMod') + ?? globalMods.get(mod.name)?.bulletMod + ?? mod.name; + const meta = weaponMeta.sets.get(setName); + if (!meta) continue; + out.push({ + modName: mod.name, + ...meta, + requires: collectTransitiveReqs(mod.name, reqMap, globalMods), + }); + } + return out; +} + +function collectTransitiveReqs( + modName: string, + reqMap: ReadonlyMap, + globalMods: ReadonlyMap, +): string[] { + const seen = new Set(); + const queue = [...(reqMap.get(modName) ?? []), ...(globalMods.get(modName)?.requires ?? [])]; + while (queue.length > 0) { + const next = queue.pop()!; + if (!next || next === modName || seen.has(next)) continue; + seen.add(next); + for (const parent of reqMap.get(next) ?? []) queue.push(parent); + } + return [...seen].sort(); +} + +function basenameWithoutExt(path: string): string { + const slash = Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\')); + const file = slash >= 0 ? path.slice(slash + 1) : path; + return file.endsWith('.blk') ? file.slice(0, -4) : file; +} diff --git a/apps/server/src/game-data/datasets/vehicle-catalogue.ts b/apps/server/src/game-data/datasets/vehicle-catalogue.ts index 4a4da5e..fef1e6c 100644 --- a/apps/server/src/game-data/datasets/vehicle-catalogue.ts +++ b/apps/server/src/game-data/datasets/vehicle-catalogue.ts @@ -27,11 +27,14 @@ import type { Dataset } from './dataset.ts'; import { shopEntriesByName } from './shop-tree.ts'; const VEHICLE_ECONOMY = 'config/wpcost.blk'; +const UNIT_TAGS = 'config/unittags.blk'; export interface CatalogueVehicle { readonly name: string; readonly country: string; readonly unitClass: string; + /** True when config/unittags.blk tags the vehicle with type_light_tank. */ + readonly isLightTank?: boolean; readonly rank: number; /** wpcost.blk reqAir; absent when empty or missing. */ readonly requires?: string; @@ -70,15 +73,27 @@ export interface CatalogueVehicle { export const vehicleCatalogue: Dataset = { id: 'vehicle-catalogue', - version: 6, + version: 7, extract: (source) => { const shopEntries = shopEntriesByName(source); const treeOrder = new Map([...shopEntries.keys()].map((name, index) => [name, index])); - return source.readBlk('char.vromfs.bin', VEHICLE_ECONOMY).blocks.map((vehicle) => catalogueVehicle(vehicle, shopEntries.get(vehicle.name), treeOrder.get(vehicle.name) ?? -1)); + const lightTanks = lightTankNames(source.readBlk('char.vromfs.bin', UNIT_TAGS)); + return source.readBlk('char.vromfs.bin', VEHICLE_ECONOMY).blocks.map((vehicle) => + catalogueVehicle(vehicle, shopEntries.get(vehicle.name), treeOrder.get(vehicle.name) ?? -1, lightTanks.has(vehicle.name)), + ); }, }; -function catalogueVehicle(vehicle: BlkBlock, shopEntry: BlkBlock | undefined, treeOrder: number): CatalogueVehicle { +function lightTankNames(unitTagsRoot: BlkBlock): ReadonlySet { + const names = new Set(); + for (const unit of unitTagsRoot.blocks) { + const tags = unit.blocks.find((block) => block.name === 'tags'); + if (tags && boolField(tags, 'type_light_tank') === true) names.add(unit.name); + } + return names; +} + +function catalogueVehicle(vehicle: BlkBlock, shopEntry: BlkBlock | undefined, treeOrder: number, isLightTank: boolean): CatalogueVehicle { const requires = stringField(vehicle, 'reqAir'); const researchType = stringField(vehicle, 'researchType'); const requiredUnlock = stringField(shopEntry, 'reqUnlock'); @@ -90,6 +105,7 @@ function catalogueVehicle(vehicle: BlkBlock, shopEntry: BlkBlock | undefined, tr name: vehicle.name, country: stringField(vehicle, 'country') ?? '', unitClass: stringField(vehicle, 'unitClass') ?? '', + ...(isLightTank ? { isLightTank: true } : {}), rank: numberField(vehicle, 'rank') ?? 0, ...(requires ? { requires } : {}), researchPoints: numberField(vehicle, 'reqExp') ?? 0, diff --git a/apps/server/src/index.ts b/apps/server/src/index.ts index ad35f7a..220442d 100644 --- a/apps/server/src/index.ts +++ b/apps/server/src/index.ts @@ -11,5 +11,6 @@ export { editSaveAccount, editSaveCurrencies, listSaveSummaries, readSaveDetails export { listSaveAvatars, readSaveAvatar } from './saves/save-avatars.ts'; export { importOfficialBackup, previewOfficialBackup } from './saves/import/official-backup.ts'; export { prepareTransferredProfile } from './saves/transferred-profile.ts'; +export { loadGroundAiTuning, type GroundAiTuning } from './tuning/ground-ai-tuning.ts'; export { readLauncherTuning, writeLauncherTuning, type LauncherTuningPatch } from './tuning/launcher-tuning.ts'; export { multiVehiclePackIds } from './store/store-pack-ids.ts'; diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 1a76546..b58597d 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -10,6 +10,7 @@ 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 { selectBotTankLoadouts } from './battle/bot-tank-loadouts.ts'; import { actionTable } from './char/actions/action-table.ts'; import { CharService } from './char/char-service.ts'; import { ClanStore } from './clans/clan-store.ts'; @@ -31,6 +32,7 @@ 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 { tankBotAmmo } from './game-data/datasets/tank-bot-ammo.ts'; import { itemCatalogue } from './game-data/datasets/item-catalogue.ts'; import { multiplayerMissions, type MultiplayerMissions } from './game-data/datasets/multiplayer-missions.ts'; import { shopCountries } from './game-data/datasets/shop-countries.ts'; @@ -173,6 +175,9 @@ export async function startServer(options: ServerOptions): Promise modRuntime.runBattleFilterMissions(ctx), ); const economy = new BattleEconomy( diff --git a/apps/server/src/tuning/ground-ai-tuning.ts b/apps/server/src/tuning/ground-ai-tuning.ts new file mode 100644 index 0000000..1d65238 --- /dev/null +++ b/apps/server/src/tuning/ground-ai-tuning.ts @@ -0,0 +1,302 @@ +/** + * Typed, range-validated reader for `tuning/ground-ai.jsonc`. + */ +import type { DiscoveredMod } from '@wto/mods'; +import { GROUND_AI_MODES, type GroundAiConfig, type GroundAiMode } from '@wto/patcher'; +import type { TankLineupWeights } from '../battle/battle-ranks.ts'; +import { tuningFiles } from './tuning-loader.ts'; +import { TuningError, type TuningReader } from './tuning-reader.ts'; + +export interface GroundAiTuning extends GroundAiConfig { + /** Tank pool weights by class, used only when a custom ground AI mode is active. */ + readonly lineupWeights: TankLineupWeights; +} + +const DRIVE_MODES = new Set(['vehicle_phys', 'movesys']); + +export function loadGroundAiTuning( + dataFolder: string | null, + report: (line: string) => void, + mods: readonly DiscoveredMod[] = [], +): GroundAiTuning { + return readGroundAiTuning(tuningFiles(dataFolder, report, undefined, mods).read('ground-ai')); +} + +export function readGroundAiTuning(reader: TuningReader): GroundAiTuning { + const cadence = reader.object('cadence'); + const diag = reader.object('diagnostics'); + return { + mode: readMode(reader), + loadout: readLoadoutSection(reader.object('loadout')), + lineupWeights: readLineupWeights(reader.object('lineupWeights')), + cadence: { + maxBots: cadence.int('maxBots', { min: 1, max: 64 }), + macroTickSec: cadence.number('macroTickSec', { min: 0.1, max: 5 }), + tacticsTickSec: cadence.number('tacticsTickSec', { min: 0.05, max: 2 }), + navTickSec: cadence.number('navTickSec', { min: 0.05, max: 2 }), + }, + commander: readCommanderSection(reader.object('commander')), + macro: readMacroSection(reader.object('macro')), + crowd: readCrowdSection(reader.object('crowd')), + terrain: readTerrainSection(reader.object('terrain')), + navigation: readNavigationSection(reader.object('navigation')), + perception: readPerceptionSection(reader.object('perception')), + stateMachine: readStateMachineSection(reader.object('stateMachine')), + tactics: readTacticsSection(reader.object('tactics')), + estimation: readEstimationSection(reader.object('estimation')), + fireControl: readFireControlSection(reader.object('fireControl')), + diagnostics: { + telemetry: diag.bool('telemetry'), + telemetryIntervalSec: diag.number('telemetryIntervalSec', { min: 0.5, max: 60 }), + }, + }; +} + +function readMode(reader: TuningReader): GroundAiMode { + const mode = reader.string('mode'); + const known = GROUND_AI_MODES.find((candidate) => candidate === mode); + if (known === undefined) { + throw new TuningError(`tuning file ground-ai.jsonc: mode must be one of ${GROUND_AI_MODES.map((m) => `"${m}"`).join(', ')} (found "${mode}")`); + } + return known; +} + +function readLoadoutSection(loadout: TuningReader): GroundAiTuning['loadout'] { + return { + lowReadyRackThreshold: loadout.int('lowReadyRackThreshold', { min: 1, max: 60 }), + topUpAmmoCount: loadout.int('topUpAmmoCount', { min: 4, max: 80 }), + primaryAmmoPct: loadout.int('primaryAmmoPct', { min: 50, max: 100 }), + secondaryMinRounds: loadout.int('secondaryMinRounds', { min: 0, max: 20 }), + penetrationCompareDistM: loadout.int('penetrationCompareDistM', { min: 100, max: 2000 }), + }; +} + +function readLineupWeights(weights: TuningReader): TankLineupWeights { + const range = { min: 0.01, max: 10 }; + return { + spaa: weights.number('spaa', range), + lightTank: weights.number('lightTank', range), + tankDestroyer: weights.number('tankDestroyer', range), + heavyTank: weights.number('heavyTank', range), + mediumTank: weights.number('mediumTank', range), + other: weights.number('other', range), + }; +} + +function readCommanderSection(cmd: TuningReader): GroundAiTuning['commander'] { + const pct = { min: 0, max: 100 }; + const bttlAssaultPct = cmd.int('bttlAssaultPct', pct); + const bttlFlankPct = cmd.int('bttlFlankPct', pct); + const bttlOverwatchPct = cmd.int('bttlOverwatchPct', pct); + if (bttlAssaultPct + bttlFlankPct + bttlOverwatchPct > 100) { + throw new TuningError('tuning file ground-ai.jsonc: commander Bttl percentages must sum to <= 100'); + } + const conqAssaultPct = cmd.int('conqAssaultPct', pct); + const conqFlankPct = cmd.int('conqFlankPct', pct); + if (conqAssaultPct + conqFlankPct > 100) { + throw new TuningError('tuning file ground-ai.jsonc: commander Conq assault + flank percentages must sum to <= 100'); + } + const conqHoldDefendPct = cmd.int('conqHoldDefendPct', pct); + const conqHoldOverwatchPct = cmd.int('conqHoldOverwatchPct', pct); + if (conqHoldDefendPct + conqHoldOverwatchPct > 100) { + throw new TuningError('tuning file ground-ai.jsonc: commander Conq hold percentages must sum to <= 100'); + } + return { + rebalanceSec: cmd.number('rebalanceSec', { min: 1.0, max: 30.0 }), + roleHoldSec: cmd.number('roleHoldSec', { min: 0.0, max: 120.0 }), + bttlAssaultPct, + bttlFlankPct, + bttlOverwatchPct, + conqAssaultPct, + conqFlankPct, + conqHoldDefendPct, + conqHoldOverwatchPct, + domAssaultPct: cmd.int('domAssaultPct', pct), + domMaxDefendersPerCap: cmd.int('domMaxDefendersPerCap', { min: 0, max: 4 }), + overwatchStandOffM: cmd.number('overwatchStandOffM', { min: 25.0, max: 350.0 }), + flankStandOffM: cmd.number('flankStandOffM', { min: 25.0, max: 300.0 }), + spaaFollowOffsetM: cmd.number('spaaFollowOffsetM', { min: 40.0, max: 500.0 }), + flankMaxLengthRatio: cmd.number('flankMaxLengthRatio', { min: 1.05, max: 3.0 }), + flankMinSeparationM: cmd.number('flankMinSeparationM', { min: 15.0, max: 200.0 }), + rallyProgressFrac: cmd.number('rallyProgressFrac', { min: 0.1, max: 0.75 }), + rallyWaitSec: cmd.number('rallyWaitSec', { min: 3.0, max: 60.0 }), + rallyMinFrac: cmd.number('rallyMinFrac', { min: 0.25, max: 1.0 }), + rallyRadiusM: cmd.number('rallyRadiusM', { min: 15.0, max: 140.0 }), + recallSafeHoldSec: cmd.number('recallSafeHoldSec', { min: 3.0, max: 60.0 }), + }; +} + +function readMacroSection(macro: TuningReader): GroundAiTuning['macro'] { + const recaptureMinBots = macro.int('recaptureMinBots', { min: 1, max: 8 }); + const recaptureMaxBots = macro.int('recaptureMaxBots', { min: 1, max: 12 }); + if (recaptureMaxBots < recaptureMinBots) { + throw new TuningError('tuning file ground-ai.jsonc: macro.recaptureMaxBots must be >= macro.recaptureMinBots'); + } + return { + openingSplitSec: macro.number('openingSplitSec', { min: 0, max: 180 }), + capMaxInsiders: macro.int('capMaxInsiders', { min: 1, max: 8 }), + recaptureMinBots, + recaptureMaxBots, + capStickyBonusM: macro.number('capStickyBonusM', { min: 0, max: 800 }), + deathZoneRadiusM: macro.number('deathZoneRadiusM', { min: 10, max: 250 }), + deathZoneTtlSec: macro.number('deathZoneTtlSec', { min: 5, max: 300 }), + deathZoneMinKills: macro.int('deathZoneMinKills', { min: 1, max: 16 }), + spaaRearOffsetM: macro.number('spaaRearOffsetM', { min: 40, max: 600 }), + spaaRelocateSec: macro.number('spaaRelocateSec', { min: 5, max: 180 }), + enemySpawnAvoidM: macro.number('enemySpawnAvoidM', { min: 60, max: 600 }), + }; +} + +function readCrowdSection(crowd: TuningReader): GroundAiTuning['crowd'] { + return { + personalSpaceM: crowd.number('personalSpaceM', { min: 6, max: 40 }), + clusterRadiusM: crowd.number('clusterRadiusM', { min: 12, max: 80 }), + clusterMaxAllies: crowd.int('clusterMaxAllies', { min: 1, max: 10 }), + disperseStepM: crowd.number('disperseStepM', { min: 8, max: 65 }), + disperseHoldSec: crowd.number('disperseHoldSec', { min: 1, max: 15 }), + }; +} + +function readTerrainSection(terrain: TuningReader): GroundAiTuning['terrain'] { + return { + maxClimbSlopeDeg: terrain.number('maxClimbSlopeDeg', { min: 10, max: 42 }), + maxDropSlopeDeg: terrain.number('maxDropSlopeDeg', { min: 8, max: 40 }), + maxWaterDepthM: terrain.number('maxWaterDepthM', { min: 0.2, max: 2.5 }), + collisionMarginM: terrain.number('collisionMarginM', { min: 0.05, max: 2.0 }), + crestLookaheadM: terrain.number('crestLookaheadM', { min: 8, max: 80 }), + ridgeMaxDwellSec: terrain.number('ridgeMaxDwellSec', { min: 2, max: 60 }), + ridgeMaxShots: terrain.int('ridgeMaxShots', { min: 1, max: 10 }), + }; +} + +function readNavigationSection(nav: TuningReader): GroundAiTuning['navigation'] { + const driveMode = nav.string('driveMode'); + if (!DRIVE_MODES.has(driveMode)) { + throw new TuningError(`tuning file ground-ai.jsonc: navigation.driveMode must be "vehicle_phys" or "movesys" (found "${driveMode}")`); + } + const steerSign = nav.number('steerSign', { min: -1, max: 1 }); + if (steerSign !== 1 && steerSign !== -1) { + throw new TuningError('tuning file ground-ai.jsonc: navigation.steerSign must be 1 or -1'); + } + return { + driveMode, + maxPhysBots: nav.int('maxPhysBots', { min: 0, max: 64 }), + steerSign, + deadEchoSec: nav.number('deadEchoSec', { min: 0.3, max: 10 }), + controlTimeoutSec: nav.number('controlTimeoutSec', { min: 0.3, max: 10 }), + cornerBrakeAccel: nav.number('cornerBrakeAccel', { min: 0.5, max: 8 }), + pivotAngleDeg: nav.number('pivotAngleDeg', { min: 25, max: 150 }), + stuckWindowSec: nav.number('stuckWindowSec', { min: 1, max: 15 }), + stuckMinMoveM: nav.number('stuckMinMoveM', { min: 0.5, max: 10 }), + unstickReverseSec: nav.number('unstickReverseSec', { min: 0.8, max: 10 }), + tacticalReverseDistM: nav.number('tacticalReverseDistM', { min: 10, max: 90 }), + tacticalReverseMaxSec: nav.number('tacticalReverseMaxSec', { min: 2, max: 25 }), + }; +} + +function readPerceptionSection(perc: TuningReader): GroundAiTuning['perception'] { + return { + foliageTransparency: perc.number('foliageTransparency', { min: 0.001, max: 1.0 }), + nearSpotRangeM: perc.number('nearSpotRangeM', { min: 20, max: 250 }), + firingSpotRangeM: perc.number('firingSpotRangeM', { min: 150, max: 1500 }), + fastSpotSec: perc.number('fastSpotSec', { min: 0.05, max: 1.5 }), + normalSpotSec: perc.number('normalSpotSec', { min: 0.1, max: 3.0 }), + farSpotSec: perc.number('farSpotSec', { min: 0.3, max: 6.0 }), + decayPerSec: perc.number('decayPerSec', { min: 0.2, max: 10.0 }), + frontConeHalfDeg: perc.number('frontConeHalfDeg', { min: 10, max: 90 }), + peripheralCloseM: perc.number('peripheralCloseM', { min: 30, max: 250 }), + }; +} + +function readStateMachineSection(sm: TuningReader): GroundAiTuning['stateMachine'] { + const coverMinDistM = sm.number('coverMinDistM', { min: 2.0, max: 30.0 }); + const coverMaxDistM = sm.number('coverMaxDistM', { min: 6.0, max: 80.0 }); + if (coverMaxDistM <= coverMinDistM) { + throw new TuningError('tuning file ground-ai.jsonc: stateMachine.coverMaxDistM must be > coverMinDistM'); + } + return { + preaimAngleDeg: sm.number('preaimAngleDeg', { min: 1.0, max: 30.0 }), + shortHaltMaxSec: sm.number('shortHaltMaxSec', { min: 0.5, max: 12.0 }), + shortHaltCooldownSec: sm.number('shortHaltCooldownSec', { min: 0.5, max: 20.0 }), + turnLaunchSpeedMps: sm.number('turnLaunchSpeedMps', { min: 0.5, max: 6.0 }), + coverMinDistM, + coverMaxDistM, + coverRetreatBudgetSec: sm.number('coverRetreatBudgetSec', { min: 1.5, max: 20.0 }), + reloadAdvanceAngleDeg: sm.number('reloadAdvanceAngleDeg', { min: 0.0, max: 45.0 }), + hullAngleTriggerDeg: sm.number('hullAngleTriggerDeg', { min: 15.0, max: 75.0 }), + hullAngleTargetDeg: sm.number('hullAngleTargetDeg', { min: 0.0, max: 35.0 }), + maxTotalHaltSec: sm.number('maxTotalHaltSec', { min: 3.0, max: 40.0 }), + stalemateMissShots: sm.int('stalemateMissShots', { min: 1, max: 8 }), + stalemateNoShotHalts: sm.int('stalemateNoShotHalts', { min: 1, max: 6 }), + repositionMinMoveM: sm.number('repositionMinMoveM', { min: 5.0, max: 80.0 }), + repositionStepM: sm.number('repositionStepM', { min: 15.0, max: 120.0 }), + repairSafeEnemyDistM: sm.number('repairSafeEnemyDistM', { min: 30.0, max: 400.0 }), + }; +} + +function readTacticsSection(tactics: TuningReader): GroundAiTuning['tactics'] { + return { + visionRangeM: tactics.number('visionRangeM', { min: 200, max: 3500 }), + visionFovDeg: tactics.number('visionFovDeg', { min: 40, max: 180 }), + peripheralRangeM: tactics.number('peripheralRangeM', { min: 30, max: 800 }), + engineAudioRangeM: tactics.number('engineAudioRangeM', { min: 10, max: 250 }), + shotAudioRangeM: tactics.number('shotAudioRangeM', { min: 50, max: 1200 }), + radioShareRangeM: tactics.number('radioShareRangeM', { min: 50, max: 1500 }), + memoryTtlSec: tactics.number('memoryTtlSec', { min: 1, max: 45 }), + targetStickinessSec: tactics.number('targetStickinessSec', { min: 0.5, max: 20 }), + peekCooldownSec: tactics.number('peekCooldownSec', { min: 1, max: 30 }), + }; +} + +function readEstimationSection(est: TuningReader): GroundAiTuning['estimation'] { + const watchMinSec = est.number('watchMinSec', { min: 0.5, max: 10.0 }); + const watchMaxSec = est.number('watchMaxSec', { min: 1.0, max: 15.0 }); + if (watchMaxSec < watchMinSec) { + throw new TuningError('tuning file ground-ai.jsonc: estimation.watchMaxSec must be >= watchMinSec'); + } + const velSampleMinSpanSec = est.number('velSampleMinSpanSec', { min: 0.05, max: 2.0 }); + const velStableSpanSec = est.number('velStableSpanSec', { min: 0.2, max: 6.0 }); + if (velStableSpanSec <= velSampleMinSpanSec) { + throw new TuningError('tuning file ground-ai.jsonc: estimation.velStableSpanSec must be > velSampleMinSpanSec'); + } + return { + watchMinSec, + watchMaxSec, + velSampleMinSpanSec, + velStableSpanSec, + velJumpResetMps: est.number('velJumpResetMps', { min: 1.0, max: 20.0 }), + baseAimSigmaM: est.number('baseAimSigmaM', { min: 0.0, max: 2.0 }), + leadErrorFrac: est.number('leadErrorFrac', { min: 0.0, max: 1.0 }), + maxBiasM: est.number('maxBiasM', { min: 0.0, max: 6.0 }), + }; +} + +function readFireControlSection(fc: TuningReader): GroundAiTuning['fireControl'] { + const closeRangeM = fc.number('closeRangeM', { min: 30, max: 250 }); + const midRangeM = fc.number('midRangeM', { min: 100, max: 600 }); + const longRangeM = fc.number('longRangeM', { min: 300, max: 1500 }); + if (midRangeM <= closeRangeM || longRangeM <= midRangeM) { + throw new TuningError('tuning file ground-ai.jsonc: fireControl ranges must satisfy closeRangeM < midRangeM < longRangeM'); + } + return { + maxEngageRangeM: fc.number('maxEngageRangeM', { min: 150, max: 3000 }), + closeRangeM, + midRangeM, + longRangeM, + midSlowSpeedRatio: fc.number('midSlowSpeedRatio', { min: 0.1, max: 1.0 }), + midSlowMaxMps: fc.number('midSlowMaxMps', { min: 1.0, max: 15.0 }), + stopSpeedMaxMps: fc.number('stopSpeedMaxMps', { min: 0.1, max: 2.0 }), + longRangeWindowSec: fc.number('longRangeWindowSec', { min: 1.0, max: 15.0 }), + baseAlignDeg: fc.number('baseAlignDeg', { min: 0.1, max: 3.0 }), + closeHitRadiusM: fc.number('closeHitRadiusM', { min: 0.25, max: 2.2 }), + barrelSettleDegSec: fc.number('barrelSettleDegSec', { min: 0.2, max: 12.0 }), + closeSettleHoldSec: fc.number('closeSettleHoldSec', { min: 0.02, max: 0.5 }), + settleHoldSec: fc.number('settleHoldSec', { min: 0.05, max: 1.5 }), + unstabilizedStopSpeedMps: fc.number('unstabilizedStopSpeedMps', { min: 0.1, max: 3.0 }), + stabilizedCreepSpeedMps: fc.number('stabilizedCreepSpeedMps', { min: 1.5, max: 15.0 }), + friendlyCorridorM: fc.number('friendlyCorridorM', { min: 1.0, max: 10.0 }), + ballisticStepMaxM: fc.number('ballisticStepMaxM', { min: 5.0, max: 80.0 }), + ballisticSweepRadiusM: fc.number('ballisticSweepRadiusM', { min: 0.02, max: 0.5 }), + maxPreFireChecksPerTick: fc.int('maxPreFireChecksPerTick', { min: 1, max: 16 }), + }; +} diff --git a/apps/server/src/tuning/tuning.ts b/apps/server/src/tuning/tuning.ts index 047859c..22b2941 100644 --- a/apps/server/src/tuning/tuning.ts +++ b/apps/server/src/tuning/tuning.ts @@ -14,6 +14,7 @@ import { readResearchTuning, type ResearchTuning } from '../research/research-tu import { readRedeemTuning, type RedeemTuning } from '../store/redeem-tuning.ts'; import { readStoreTuning, type StoreTuning } from '../store/store-tuning.ts'; import type { DiscoveredMod } from '@wto/mods'; +import { readGroundAiTuning, type GroundAiTuning } from './ground-ai-tuning.ts'; import { readLimitsTuning, type LimitsTuning } from './limits-tuning.ts'; import { tuningFiles } from './tuning-loader.ts'; @@ -29,6 +30,7 @@ export interface Tuning { readonly clans: ClanTuning; readonly battle: BattleTuning; readonly battleEconomy: BattleEconomyTuning; + readonly groundAi: GroundAiTuning; readonly limits: LimitsTuning; } @@ -50,6 +52,7 @@ export function loadTuning( clans: readClanTuning(files.read('clans')), battle: readBattleTuning(files.read('battle')), battleEconomy: readBattleEconomyTuning(files.read('battle-economy')), + groundAi: readGroundAiTuning(files.read('ground-ai')), limits: readLimitsTuning(files.read('limits')), }; } diff --git a/apps/server/tuning/ground-ai.jsonc b/apps/server/tuning/ground-ai.jsonc new file mode 100644 index 0000000..94be90a --- /dev/null +++ b/apps/server/tuning/ground-ai.jsonc @@ -0,0 +1,196 @@ +// Ground battle AI configuration. +// Per-client overrides live in /tuning/ground-ai.jsonc. The game copy build compiles the +// layer settings into game/wtoai/wto_ai_config_common.das; the local server reads lineupWeights. +{ + // "full": every custom layer (default). + // "fire": stock movement and destinations, custom perception and fire permission. + // "drive": custom team orders and driving, stock aiming and firing (debugging). + // "stock": stock AI only, no scripts packed, stock lineup weights (troubleshooting). + "mode": "full", + + // AI tank spawn ammunition selection (offline values; ignored in "stock" mode). + // Carries first-stage / autoloader ready-rack capacity, topped up when below threshold, + // split between best anti-armor primary (APFSDS preferred) and HE/HEAT secondary when available. + "loadout": { + "lowReadyRackThreshold": 15, + "topUpAmmoCount": 22, + "primaryAmmoPct": 80, + "secondaryMinRounds": 3, + "penetrationCompareDistM": 500 + }, + + // Relative pick weights of AI tank classes in a battle's bot pool. Offline values; ignored in + // "stock" mode, where every vehicle keeps the stock weight of 1. + "lineupWeights": { + "spaa": 0.12, + "lightTank": 0.45, + "tankDestroyer": 0.55, + "heavyTank": 0.85, + "mediumTank": 1.15, + "other": 1.0 + }, + + "cadence": { + "maxBots": 64, + "macroTickSec": 0.5, + "tacticsTickSec": 0.25, + "navTickSec": 0.2 + }, + + // Team commander role quotas and timing (offline values). + "commander": { + "rebalanceSec": 5.0, + "roleHoldSec": 20.0, + "bttlAssaultPct": 45, + "bttlFlankPct": 15, + "bttlOverwatchPct": 20, + "conqAssaultPct": 50, + "conqFlankPct": 20, + "conqHoldDefendPct": 30, + "conqHoldOverwatchPct": 30, + "domAssaultPct": 70, + "domMaxDefendersPerCap": 1, + "overwatchStandOffM": 95.0, + "flankStandOffM": 75.0, + "spaaFollowOffsetM": 160.0, + "flankMaxLengthRatio": 1.6, + "flankMinSeparationM": 45.0, + "rallyProgressFrac": 0.40, + "rallyWaitSec": 25.0, + "rallyMinFrac": 0.66, + "rallyRadiusM": 55.0, + "recallSafeHoldSec": 15.0 + }, + + "macro": { + "openingSplitSec": 40.0, + "capMaxInsiders": 2, + "recaptureMinBots": 2, + "recaptureMaxBots": 4, + "capStickyBonusM": 165.0, + "deathZoneRadiusM": 55.0, + "deathZoneTtlSec": 60.0, + "deathZoneMinKills": 3, + "spaaRearOffsetM": 185.0, + "spaaRelocateSec": 28.0, + "enemySpawnAvoidM": 180.0 + }, + + "crowd": { + "personalSpaceM": 14.0, + "clusterRadiusM": 28.0, + "clusterMaxAllies": 2, + "disperseStepM": 24.0, + "disperseHoldSec": 4.2 + }, + + "terrain": { + "maxClimbSlopeDeg": 25.0, + "maxDropSlopeDeg": 20.0, + "maxWaterDepthM": 0.6, + "collisionMarginM": 0.3, + "crestLookaheadM": 28.0, + "ridgeMaxDwellSec": 10.0, + "ridgeMaxShots": 2 + }, + + "navigation": { + // "vehicle_phys" uses custom inputs with native ownership. "movesys" keeps stock movement. + "driveMode": "vehicle_phys", + "maxPhysBots": 64, + "steerSign": 1.0, + "deadEchoSec": 1.2, + "controlTimeoutSec": 1.0, + "cornerBrakeAccel": 1.75, + "pivotAngleDeg": 75.0, + "stuckWindowSec": 3.6, + "stuckMinMoveM": 2.0, + "unstickReverseSec": 3.0, + "tacticalReverseDistM": 34.0, + "tacticalReverseMaxSec": 9.5 + }, + + // Exposure-based visual perception (offline values; foliageTransparency matches stock infantry AI). + "perception": { + "foliageTransparency": 0.01, + "nearSpotRangeM": 90.0, + "firingSpotRangeM": 650.0, + "fastSpotSec": 0.25, + "normalSpotSec": 0.60, + "farSpotSec": 1.45, + "decayPerSec": 1.5, + "frontConeHalfDeg": 30.0, + "peripheralCloseM": 100.0 + }, + + // Per-bot hull state machine timings and thresholds (offline values). + "stateMachine": { + "preaimAngleDeg": 8.0, + "shortHaltMaxSec": 3.0, + "shortHaltCooldownSec": 4.0, + "turnLaunchSpeedMps": 2.1, + "coverMinDistM": 6.0, + "coverMaxDistM": 24.0, + "coverRetreatBudgetSec": 6.0, + "reloadAdvanceAngleDeg": 18.0, + "hullAngleTriggerDeg": 30.0, + "hullAngleTargetDeg": 15.0, + "maxTotalHaltSec": 12.0, + "stalemateMissShots": 2, + "stalemateNoShotHalts": 2, + "repositionMinMoveM": 20.0, + "repositionStepM": 48.0, + "repairSafeEnemyDistM": 140.0 + }, + + "tactics": { + "visionRangeM": 1250.0, + "visionFovDeg": 115.0, + "peripheralRangeM": 230.0, + "engineAudioRangeM": 65.0, + "shotAudioRangeM": 380.0, + "radioShareRangeM": 450.0, + "memoryTtlSec": 12.0, + "targetStickinessSec": 4.5, + "peekCooldownSec": 6.0 + }, + + // Target velocity estimation from own visual samples, last-seen watch, and bounded shot bias. + "estimation": { + "watchMinSec": 2.0, + "watchMaxSec": 5.0, + "velSampleMinSpanSec": 0.25, + "velStableSpanSec": 1.2, + "velJumpResetMps": 4.5, + "baseAimSigmaM": 0.28, + "leadErrorFrac": 0.26, + "maxBiasM": 2.2 + }, + + "fireControl": { + "maxEngageRangeM": 1250.0, + "closeRangeM": 100.0, + "midRangeM": 300.0, + "longRangeM": 800.0, + "midSlowSpeedRatio": 0.45, + "midSlowMaxMps": 5.5, + "stopSpeedMaxMps": 0.45, + "longRangeWindowSec": 4.0, + "baseAlignDeg": 0.42, + "closeHitRadiusM": 0.85, + "barrelSettleDegSec": 1.8, + "closeSettleHoldSec": 0.08, + "settleHoldSec": 0.20, + "unstabilizedStopSpeedMps": 0.45, + "stabilizedCreepSpeedMps": 5.5, + "friendlyCorridorM": 3.2, + "ballisticStepMaxM": 25.0, + "ballisticSweepRadiusM": 0.12, + "maxPreFireChecksPerTick": 2 + }, + + "diagnostics": { + "telemetry": false, + "telemetryIntervalSec": 5.0 + } +} diff --git a/game-ai/ground/wto_ai_combat_types_common.das b/game-ai/ground/wto_ai_combat_types_common.das new file mode 100644 index 0000000..6c30774 --- /dev/null +++ b/game-ai/ground/wto_ai_combat_types_common.das @@ -0,0 +1,113 @@ +// Zero-heap POD types for perception exposure, shell ballistics profiles, and fire control. +options indenting = 2 +options no_global_heap = true +module wto_ai_combat_types_common shared + +require ecs + +let public WTO_MAX_EXPOSURE_TRACKS = 8 +let public WTO_MAX_VEL_SAMPLES = 6 +let public WTO_MAX_SHELL_PROFILES = 12 + +let public WTO_BLOCK_NONE = 0 +let public WTO_BLOCK_TERRAIN = 1 +let public WTO_BLOCK_OBJECT = 2 +let public WTO_BLOCK_WRECK = 3 +let public WTO_BLOCK_VEHICLE = 4 +let public WTO_BLOCK_SMOKE = 5 +let public WTO_BLOCK_FOLIAGE = 6 + +let public WTO_DENY_OK = 0 +let public WTO_DENY_NO_TARGET = 1 +let public WTO_DENY_NOT_READY = 2 +let public WTO_DENY_SPEED = 3 +let public WTO_DENY_LONG_WINDOW = 4 +let public WTO_DENY_AIM_ERR = 5 +let public WTO_DENY_SETTLE = 6 +let public WTO_DENY_BUDGET = 7 +let public WTO_DENY_MUZZLE_HARD = 8 +let public WTO_DENY_ARC_HARD = 9 +let public WTO_DENY_FRIENDLY = 10 +let public WTO_DENY_MULTI_GUN = 11 + +[safe_when_uninitialized] +struct public WtoShellProfile + nameHash : uint = 0u + speedMps : float = 880.0 + dragCx : float = 0.35 + massKg : float = 10.0 + caliberM : float = 0.09 + isSoftShell : bool = false + isAntiArmor : bool = true + +[safe_when_uninitialized] +struct public WtoPerceiveState + targetEid : EntityId = INVALID_ENTITY_ID + targetIsAir : bool = false + hasClearLos : bool = false + visiblePointCount : int = 0 + goodLosSec : float = 0.0 + visibleAimPt : float3 = float3(0.0, 0.0, 0.0) + knownPos : float3 = float3(0.0, 0.0, 0.0) + estVel : float3 = float3(0.0, 0.0, 0.0) + velQuality : float = 0.0 + sampleTargetEid : EntityId = INVALID_ENTITY_ID + sampleCount : int = 0 + sampleHead : int = 0 + samplePos : float3[6] + sampleAt : float[6] + wasEngaging : bool = false + watchPos : float3 = float3(0.0, 0.0, 0.0) + watchUntil : float = -100.0 + oppKey : uint = 0u + oppBiasU : float = 0.0 + oppBiasV : float = 0.0 + oppSeeded : bool = false + lastSeenAt : float = -100.0 + lockedEid : EntityId = INVALID_ENTITY_ID + lockedUntil : float = -100.0 + alertYawRad : float = 0.0 + alertUntil : float = -100.0 + lastDamagedAt : float = -100.0 + lastHitYawRad : float = 0.0 + lastOffenderEid : EntityId = INVALID_ENTITY_ID + lastRadioSentAt : float = -100.0 + expEids : EntityId[8] + expScore : float[8] + expGoodLosSec : float[8] + +[safe_when_uninitialized] +struct public WtoFireState + turretNo : int = -1 + gunReady : bool = false + reloading : bool = false + gunDamaged : bool = false + loadedBulletIdx : int = -1 + activeSpeedMps : float = 880.0 + activeDragCx : float = 0.35 + activeMassKg : float = 10.0 + activeCaliberM : float = 0.09 + pitchBlocked : bool = false + pitchClampSec : float = 0.0 + cmdYawDeg : float = 0.0 + cmdPitchDeg : float = 0.0 + curYawDeg : float = 0.0 + curPitchDeg : float = 0.0 + prevPitchDeg : float = 0.0 + servoInit : bool = false + prevBarrelDir : float3 = float3(1.0, 0.0, 0.0) + prevBarrelAt : float = -100.0 + barrelOmegaDegSec : float = 0.0 + settleHoldSec : float = 0.0 + lastAligned : bool = false + lastAimErrDeg : float = 0.0 + lastShotAt : float = -100.0 + prevLoadedAmmo : int = -1 + pendingShotConfirm : bool = false + pendingShotAt : float = -100.0 + lastDenyReason : int = 0 + lastDenyBlock : int = 0 + lastDenyLogAt : float = -100.0 + shotCount : int = 0 + shotErrSumDeg : float = 0.0 + maxShotErrDeg : float = 0.0 diff --git a/game-ai/ground/wto_ai_commander_anchors_common.das b/game-ai/ground/wto_ai_commander_anchors_common.das new file mode 100644 index 0000000..d3bf471 --- /dev/null +++ b/game-ai/ground/wto_ai_commander_anchors_common.das @@ -0,0 +1,182 @@ +// Anchor point selection and safety helpers for the team commander. +options indenting = 2 +options no_global_heap = true +module wto_ai_commander_anchors_common shared + +require ecs +require math +require Dacoll +require %appGame.wtoai.wto_ai_config_common +require %appGame.wtoai.wto_ai_math_common +require %appGame.wtoai.wto_ai_order_common +require %appGame.wtoai.wto_ai_types_common +require %appGame.wtoai.wto_ai_terrain_common + +[never_inline] +def public wto_cmd_vehicle_penalty(unitRole, cmdRole : int) : float + if cmdRole == WTO_CMD_FLANK + if unitRole == WTO_ROLE_LIGHT + return -180.0 + if unitRole == WTO_ROLE_HEAVY + return 120.0 + if unitRole == WTO_ROLE_TD + return 160.0 + return 0.0 + if cmdRole == WTO_CMD_OVERWATCH || cmdRole == WTO_CMD_DEFEND + if unitRole == WTO_ROLE_TD + return -160.0 + if unitRole == WTO_ROLE_HEAVY + return -40.0 + if unitRole == WTO_ROLE_LIGHT + return 120.0 + return 0.0 + if cmdRole == WTO_CMD_ASSAULT + if unitRole == WTO_ROLE_MEDIUM || unitRole == WTO_ROLE_HEAVY + return -80.0 + if unitRole == WTO_ROLE_TD + return 140.0 + return 0.0 + return 0.0 + +[never_inline] +def public wto_cmd_log_summary(world : WtoWorldSnap const&; army : int; now : float; + candCount : int; cands : int[64]; candPos : float3[64]; + capAssigned, capInsiders : int[8]; spaaCount : int; + bots : WtoBotSlot[64]) + if !WTO_AI_DIAG_TELEMETRY + return + var rCnt : int[6] + for r in range(6) + rCnt[r] = 0 + rCnt[WTO_CMD_SPAA] = spaaCount + var atFront = 0 + for ci in range(candCount) + assume b = bots[cands[ci]] + rCnt[clamp(b.order.role, 0, 5)]++ + if wto_order_is_offensive(b.order.role) && b.order.capIndex >= 0 && wto_xz_dist_sq(candPos[ci], world.caps[b.order.capIndex].center) <= 40000.0 + atFront++ + print("WTO_AI|CMD|t={now}|army={army}|mode={world.battleMode}|n={candCount}|roles={rCnt[0]}/{rCnt[1]}/{rCnt[2]}/{rCnt[3]}/{rCnt[5]}|caps={capAssigned[0]}/{capAssigned[1]}/{capAssigned[2]}|in={capInsiders[0]}/{capInsiders[1]}/{capInsiders[2]}|front={atFront}\n") + +[never_inline] +def public wto_cmd_death_zone_kills(world : WtoWorldSnap const&; army : int; pos : float3; now : float) : int + let radSq = wto_sq(WTO_AI_MACRO_DEATH_ZONE_RAD_M) + var kills = 0 + for i in range(WTO_MAX_DEATHS) + assume d = world.deaths[i] + if d.army == army && (now - d.at) <= WTO_AI_MACRO_DEATH_ZONE_TTL_SEC && wto_xz_dist_sq(pos, d.pos) <= radSq + kills++ + return kills + +[never_inline] +def public wto_cmd_clamp_away_enemy_spawn(world : WtoWorldSnap const&; army : int; pos : float3) : float3 + let enemyArmy = army == 1 ? 2 : 1 + if enemyArmy < 1 || enemyArmy > 2 || !world.teamSpawnValid[enemyArmy] + return pos + let eSpawn = world.teamSpawnCenter[enemyArmy] + let minDist = WTO_AI_MACRO_ENEMY_SPAWN_AVOID_M + let dSq = wto_xz_dist_sq(pos, eSpawn) + if dSq >= minDist * minDist + return pos + let away = wto_xz_normalize(pos - eSpawn, float3(1.0, 0.0, 0.0)) + return float3(eSpawn.x + away.x * minDist, pos.y, eSpawn.z + away.z * minDist) + +[never_inline] +def private wto_try_anchor_candidate(world : WtoWorldSnap const&; army : int; rawPos : float3; + var outPos : float3&) : bool + var cand = wto_cmd_clamp_away_enemy_spawn(world, army, rawPos) + cand = wto_clamp_battle_xz(cand, world.battleCenter, world.battleRadius, 40.0) + if wto_terrain_point_valid(army, cand) + outPos = cand + return true + return false + +[never_inline] +def public wto_cmd_pick_role_anchor(world : WtoWorldSnap const&; army : int; eid : EntityId; + capIdx, cmdRole : int; insideCircle : bool) : float3 + assume cap = world.caps[capIdx] + let h = uint(eid) + let friendlySpawn = world.teamSpawnValid[army] ? world.teamSpawnCenter[army] : world.battleCenter + let toCap = wto_xz_normalize(cap.center - friendlySpawn, float3(1.0, 0.0, 0.0)) + let lat = float3(-toCap.z, 0.0, toCap.x) + var chosen = cap.center + + if cmdRole == WTO_CMD_ASSAULT && insideCircle + let slotAng = float(h % 5u) * (2.0 * WTO_PI / 5.0) + float(capIdx) * 0.7 + let inRad = clamp(cap.radius * 0.52, 7.0, max(8.0, cap.radius - 4.5)) + var pt = float3(cap.center.x + cos(slotAng) * inRad, cap.center.y, cap.center.z + sin(slotAng) * inRad) + if wto_terrain_point_valid(army, pt) + return pt + return cap.center + + let sideSign = (h & 1u) == 0u ? 1.0 : -1.0 + let tier = float((h / 2u) % 3u) + var latDist = cap.radius + 18.0 + tier * 12.0 + var backDist = 14.0 + tier * 10.0 + if cmdRole == WTO_CMD_FLANK + latDist = max(cap.radius + 20.0, WTO_AI_CMD_FLANK_STANDOFF_M + tier * 16.0) + backDist = 8.0 - tier * 12.0 + elif cmdRole == WTO_CMD_OVERWATCH + latDist = (tier - 1.0) * 34.0 + sideSign * 22.0 + backDist = max(cap.radius + 25.0, WTO_AI_CMD_OVERWATCH_STANDOFF_M + tier * 18.0) + elif cmdRole == WTO_CMD_DEFEND || cmdRole == WTO_CMD_RESERVE + latDist = sideSign * (cap.radius + 14.0 + tier * 12.0) + backDist = 12.0 + tier * 10.0 + + for attempt in range(4) + let flip = (attempt == 1 || attempt == 3) ? -1.0 : 1.0 + let scale = attempt >= 2 ? 0.6 : 1.0 + let cand = cap.center + lat * (sideSign * latDist * flip * scale) - toCap * (backDist * scale) + if wto_try_anchor_candidate(world, army, cand, chosen) + return chosen + return wto_clamp_battle_xz(cap.center - toCap * (cap.radius + 18.0), world.battleCenter, world.battleRadius, 40.0) + +[never_inline] +def private wto_cmd_has_open_sky(pos : float3) : bool + var p0 = pos + float3(0.0, 2.5, 0.0) + let upDir = float3(0.0, 1.0, 0.0) + return !rayhit_normalized(p0, upDir, 45.0, ETF_ALL, -1) + +[never_inline] +def public wto_cmd_assign_spaa(world : WtoWorldSnap const&; now : float; myPos, frontPt : float3; + airActive : bool; var slot : WtoBotSlot&) + let army = slot.army + assume ord = slot.order + let needNew = !ord.spaaAnchorValid || now >= ord.spaaRelocateAt || (slot.fire.lastShotAt > ord.spaaRelocateAt - WTO_AI_MACRO_SPAA_RELOCATE_SEC && (now - slot.fire.lastShotAt) > 3.0) + if needNew + let spawnPt = world.teamSpawnValid[army] ? world.teamSpawnCenter[army] : myPos + let toFront = wto_xz_normalize(frontPt - spawnPt, float3(1.0, 0.0, 0.0)) + let lat = float3(-toFront.z, 0.0, toFront.x) + let followOff = airActive ? (WTO_AI_CMD_SPAA_FOLLOW_OFFSET_M * 1.15) : WTO_AI_CMD_SPAA_FOLLOW_OFFSET_M + let base = frontPt - toFront * followOff + let tickIdx = max(0, int(now / max(5.0, WTO_AI_MACRO_SPAA_RELOCATE_SEC))) + var picked = myPos + var foundOpen = false + for attempt in range(5) + let phase = int((uint(slot.eid) + uint(tickIdx) + uint(attempt)) % 5u) + let side = float(phase - 2) * 42.0 + var cand = wto_clamp_battle_xz(base + lat * side, world.battleCenter, world.battleRadius, 45.0) + cand = wto_cmd_clamp_away_enemy_spawn(world, army, cand) + if !wto_terrain_point_valid(army, cand) + continue + if !foundOpen + picked = cand + if wto_cmd_has_open_sky(cand) + picked = cand + foundOpen = true + break + ord.spaaAnchorPos = picked + ord.spaaAnchorValid = true + ord.spaaRelocateAt = now + WTO_AI_MACRO_SPAA_RELOCATE_SEC + ord.role = WTO_CMD_SPAA + ord.capIndex = -1 + ord.laneId = 0 + ord.routeRelayValid = false + ord.rallyHold = false + ord.goalPos = ord.spaaAnchorPos + ord.urgency = airActive ? WTO_URGENCY_MED : WTO_URGENCY_LOW + ord.maxStopRangeM = wto_order_max_stop_range(WTO_CMD_SPAA, ord.urgency, WTO_AI_FC_MAX_RANGE_M) + ord.overwatchOutside = true + ord.cautious = false + ord.assignedAt = now + ord.expiresAt = now + WTO_AI_MACRO_SPAA_RELOCATE_SEC + ord.valid = true diff --git a/game-ai/ground/wto_ai_commander_common.das b/game-ai/ground/wto_ai_commander_common.das new file mode 100644 index 0000000..d766afd --- /dev/null +++ b/game-ai/ground/wto_ai_commander_common.das @@ -0,0 +1,197 @@ +// Whole-team commander (v1): mode-aware role quotas (Bttl / Conq / Dom), deterministic +// distance + vehicle-suitability matching, 20-second role hysteresis, separate total-assigned +// vs insider counters, and per-team assignment telemetry. +options indenting = 2 +options no_global_heap = true +module wto_ai_commander_common shared + +require ecs +require math +require %appGame.wtoai.wto_ai_config_common +require %appGame.wtoai.wto_ai_math_common +require %appGame.wtoai.wto_ai_order_common +require %appGame.wtoai.wto_ai_types_common +require %appGame.wtoai.wto_ai_world_common +require %appGame.wtoai.wto_ai_lanes_common +require %appGame.wtoai.wto_ai_commander_anchors_common +require %appGame.wtoai.wto_ai_commander_plans_common + +[never_inline] +def private wto_cmd_apply_order(world : WtoWorldSnap const&; army : int; now : float; + capIdx, cmdRole, urgency : int; lanes : WtoTeamLanes const&; + var capInsiders : int[8]&; var capAssigned : int[8]&; + var slot : WtoBotSlot&) + assume ord = slot.order + let sameTask = ord.valid && ord.role == cmdRole && ord.capIndex == capIdx + let insideCircle = cmdRole == WTO_CMD_ASSAULT && capInsiders[capIdx] < WTO_AI_MACRO_CAP_MAX_INSIDERS + if insideCircle + capInsiders[capIdx]++ + capAssigned[capIdx]++ + ord.role = cmdRole + ord.capIndex = capIdx + ord.urgency = urgency + ord.maxStopRangeM = wto_order_max_stop_range(cmdRole, urgency, WTO_AI_FC_MAX_RANGE_M) + ord.overwatchOutside = !insideCircle + ord.cautious = wto_cmd_death_zone_kills(world, army, world.caps[capIdx].center, now) >= WTO_AI_MACRO_DEATH_ZONE_MIN_KILLS + ord.goalPos = wto_cmd_pick_role_anchor(world, army, slot.eid, capIdx, cmdRole, insideCircle) + + // Assign validated navmesh lane (center / left flank / right flank) and rally staging point. + let ck = wto_lanes_cap_key(army, capIdx) + ord.laneId = WTO_LANE_CENTER + ord.routeRelayValid = false + ord.rallyHold = false + if cmdRole == WTO_CMD_FLANK + let prefSide = int(uint(slot.eid) & 1u) + let altSide = 1 - prefSide + if lanes.flankValid[ck * 2 + prefSide] + ord.laneId = prefSide + 1 + ord.routeRelayValid = true + ord.routeRelayPos = lanes.flankRelay[ck * 2 + prefSide] + elif lanes.flankValid[ck * 2 + altSide] + ord.laneId = altSide + 1 + ord.routeRelayValid = true + ord.routeRelayPos = lanes.flankRelay[ck * 2 + altSide] + if wto_order_is_offensive(cmdRole) + let sk = wto_lanes_sub_key(army, capIdx, ord.laneId) + if !lanes.rallyReleased[sk] && length_sq(lanes.rallyPos[sk]) > 1.0 + ord.rallyHold = true + ord.routeRelayValid = true + ord.routeRelayPos = lanes.rallyPos[sk] + + if !sameTask + ord.assignedAt = now + ord.expiresAt = now + max(10.0, WTO_AI_CMD_ROLE_HOLD_SEC * 2.0) + ord.valid = true + +[never_inline] +def private wto_cmd_match_and_log(world : WtoWorldSnap const&; army : int; now : float; forceRebalance : bool; + lanes : WtoTeamLanes const&; + candCount : int; cands : int[64]; candPos : float3[64]; + dCount : int; dCap : int[64]; dRole : int[64]; dUrg : int[64]; + spaaCount : int; var bots : WtoBotSlot[64]&) + var botUsed : bool[64] + var demUsed : bool[64] + for i in range(WTO_MAX_BOTS) + botUsed[i] = false + demUsed[i] = false + var capInsiders : int[8] + var capAssigned : int[8] + for c in range(WTO_MAX_CAPS) + capInsiders[c] = 0 + capAssigned[c] = 0 + if !forceRebalance + for ci in range(candCount) + let bIdx = cands[ci] + assume ord = bots[bIdx].order + if !ord.valid || (now - ord.assignedAt) >= WTO_AI_CMD_ROLE_HOLD_SEC || now >= ord.expiresAt + continue + for di in range(dCount) + if !demUsed[di] && dCap[di] == ord.capIndex && dRole[di] == ord.role + demUsed[di] = true + botUsed[ci] = true + wto_cmd_apply_order(world, army, now, dCap[di], dRole[di], dUrg[di], lanes, capInsiders, capAssigned, bots[bIdx]) + break + for di in range(dCount) + if demUsed[di] + continue + var bestCi = -1 + var bestScore = 1.0e12 + var bestEid = 0xffffffffu + let tgtPos = world.caps[dCap[di]].center + for ci in range(candCount) + if botUsed[ci] + continue + let bIdx = cands[ci] + let dist = sqrt(wto_xz_dist_sq(candPos[ci], tgtPos)) + let sc = dist + wto_cmd_vehicle_penalty(bots[bIdx].spec.role, dRole[di]) + let eidU = uint(bots[bIdx].eid) + if sc < bestScore - 0.1 || (abs(sc - bestScore) <= 0.1 && eidU < bestEid) + bestScore = sc + bestEid = eidU + bestCi = ci + if bestCi >= 0 + demUsed[di] = true + botUsed[bestCi] = true + wto_cmd_apply_order(world, army, now, dCap[di], dRole[di], dUrg[di], lanes, capInsiders, capAssigned, bots[cands[bestCi]]) + wto_cmd_log_summary(world, army, now, candCount, cands, candPos, capAssigned, capInsiders, spaaCount, bots) + +[never_inline] +def private wto_cmd_assign_army(world : WtoWorldSnap const&; army : int; now : float; + forceRebalance : bool; var lanes : WtoTeamLanes&; + var bots : WtoBotSlot[64]&) + var cands : int[64] + var candPos : float3[64] + var spaaIdx : int[64] + var spaaPos : float3[64] + var candCount = 0 + var spaaCount = 0 + for i in range(WTO_MAX_BOTS) + if !bots[i].used || bots[i].army != army + continue + let uIdx = wto_world_find_unit(world, bots[i].eid) + if uIdx < 0 + continue + if bots[i].spec.role == WTO_ROLE_SPAA + spaaIdx[spaaCount] = i + spaaPos[spaaCount] = world.units[uIdx].pos + spaaCount++ + else + cands[candCount] = i + candPos[candCount] = world.units[uIdx].pos + candCount++ + if world.capCount <= 0 + for ci in range(candCount) + assume ord = bots[cands[ci]].order + ord.role = WTO_CMD_ASSAULT + ord.capIndex = -1 + ord.laneId = WTO_LANE_CENTER + ord.routeRelayValid = false + ord.rallyHold = false + ord.goalPos = wto_cmd_clamp_away_enemy_spawn(world, army, world.battleCenter) + ord.urgency = WTO_URGENCY_MED + ord.maxStopRangeM = 300.0 + ord.assignedAt = now + ord.expiresAt = now + 30.0 + ord.valid = true + for si in range(spaaCount) + wto_cmd_assign_spaa(world, now, spaaPos[si], world.battleCenter, lanes.enemyAirActive[army], bots[spaaIdx[si]]) + return + var enemiesInCap : int[8] + wto_lanes_update_recall(world, army, now, lanes, enemiesInCap) + for c in range(world.capCount) + wto_lanes_ensure_cap(world, army, c, lanes) + var dCap : int[64] + var dRole : int[64] + var dUrg : int[64] + var dCount = 0 + var primaryCap = 0 + if candCount > 0 + if world.battleMode == WTO_MODE_BTTL + primaryCap = wto_cmd_plan_bttl(world, army, candCount, dCap, dRole, dUrg, dCount) + elif world.battleMode == WTO_MODE_CONQ || world.capCount == 1 + primaryCap = wto_cmd_plan_conq(world, army, candCount, dCap, dRole, dUrg, dCount) + else + primaryCap = wto_cmd_plan_dom(world, army, candCount, dCap, dRole, dUrg, dCount) + wto_cmd_apply_recall_demands(world, army, candCount, lanes, enemiesInCap, dCap, dRole, dUrg, dCount) + wto_cmd_match_and_log(world, army, now, forceRebalance, lanes, candCount, cands, candPos, dCount, dCap, dRole, dUrg, spaaCount, bots) + var frontPt = world.caps[clamp(primaryCap, 0, world.capCount - 1)].center + var assaultSum = float3(0.0, 0.0, 0.0) + var assaultCnt = 0 + for ci in range(candCount) + if bots[cands[ci]].order.role == WTO_CMD_ASSAULT + assaultSum += candPos[ci] + assaultCnt++ + if assaultCnt > 0 + frontPt = assaultSum / float(assaultCnt) + for si in range(spaaCount) + wto_cmd_assign_spaa(world, now, spaaPos[si], frontPt, lanes.enemyAirActive[army], bots[spaaIdx[si]]) + +[never_inline] +def public wto_commander_update_all(world : WtoWorldSnap const&; now : float; + forceRebalance : bool; var lanes : WtoTeamLanes&; + var bots : WtoBotSlot[64]&) + wto_lanes_update_team_intel(world, now, lanes) + wto_cmd_assign_army(world, 1, now, forceRebalance, lanes, bots) + wto_cmd_assign_army(world, 2, now, forceRebalance, lanes, bots) + wto_lanes_update_rallies(world, 1, now, lanes, bots) + wto_lanes_update_rallies(world, 2, now, lanes, bots) diff --git a/game-ai/ground/wto_ai_commander_plans_common.das b/game-ai/ground/wto_ai_commander_plans_common.das new file mode 100644 index 0000000..e479eef --- /dev/null +++ b/game-ai/ground/wto_ai_commander_plans_common.das @@ -0,0 +1,168 @@ +// Mode-aware team quota planners (Bttl / Conq / Dom) and dynamic recall demand overrides. +options indenting = 2 +options no_global_heap = true +module wto_ai_commander_plans_common shared + +require ecs +require math +require %appGame.wtoai.wto_ai_config_common +require %appGame.wtoai.wto_ai_math_common +require %appGame.wtoai.wto_ai_order_common +require %appGame.wtoai.wto_ai_types_common +require %appGame.wtoai.wto_ai_lanes_common + +[never_inline] +def private wto_cmd_push_demands(capIdx, role, urgency, count : int; + var dCap : int[64]&; var dRole : int[64]&; var dUrg : int[64]&; + var dCount : int&) + for _k in range(count) + if dCount >= WTO_MAX_BOTS + return + dCap[dCount] = capIdx + dRole[dCount] = role + dUrg[dCount] = urgency + dCount++ + +[never_inline] +def public wto_cmd_plan_bttl(world : WtoWorldSnap const&; army, n : int; + var dCap : int[64]&; var dRole : int[64]&; var dUrg : int[64]&; + var dCount : int&) : int + let spawnPt = world.teamSpawnValid[army] ? world.teamSpawnCenter[army] : world.battleCenter + var enemyCap = -1 + var friendlyCap = -1 + var bestEnemyD = 1.0e12 + var bestFriendD = 1.0e12 + for c in range(world.capCount) + let dSq = wto_xz_dist_sq(spawnPt, world.caps[c].center) + if world.caps[c].ownerArmy != army && dSq < bestEnemyD + bestEnemyD = dSq + enemyCap = c + elif world.caps[c].ownerArmy == army && dSq < bestFriendD + bestFriendD = dSq + friendlyCap = c + if enemyCap < 0 + enemyCap = friendlyCap >= 0 ? (world.capCount > 1 ? (1 - friendlyCap) : friendlyCap) : 0 + if friendlyCap < 0 + friendlyCap = enemyCap + let nAssault = clamp((n * WTO_AI_CMD_BTTL_ASSAULT_PCT + 50) / 100, 1, n) + let rem1 = max(0, n - nAssault) + let nFlank = min(rem1, (n * WTO_AI_CMD_BTTL_FLANK_PCT + 50) / 100) + let rem2 = max(0, rem1 - nFlank) + let nOverwatch = min(rem2, (n * WTO_AI_CMD_BTTL_OVERWATCH_PCT + 50) / 100) + let nDefend = max(0, rem2 - nOverwatch) + let defUrg = world.caps[friendlyCap].contested ? WTO_URGENCY_HIGH : WTO_URGENCY_LOW + wto_cmd_push_demands(enemyCap, WTO_CMD_ASSAULT, WTO_URGENCY_HIGH, nAssault, dCap, dRole, dUrg, dCount) + wto_cmd_push_demands(enemyCap, WTO_CMD_FLANK, WTO_URGENCY_HIGH, nFlank, dCap, dRole, dUrg, dCount) + wto_cmd_push_demands(enemyCap, WTO_CMD_OVERWATCH, WTO_URGENCY_MED, nOverwatch, dCap, dRole, dUrg, dCount) + wto_cmd_push_demands(friendlyCap, WTO_CMD_DEFEND, defUrg, nDefend, dCap, dRole, dUrg, dCount) + return enemyCap + +[never_inline] +def public wto_cmd_plan_conq(world : WtoWorldSnap const&; army, n : int; + var dCap : int[64]&; var dRole : int[64]&; var dUrg : int[64]&; + var dCount : int&) : int + if world.caps[0].ownerArmy != army + let nAssault = clamp((n * WTO_AI_CMD_CONQ_ASSAULT_PCT + 50) / 100, 1, n) + let rem1 = max(0, n - nAssault) + let nFlank = min(rem1, (n * WTO_AI_CMD_CONQ_FLANK_PCT + 50) / 100) + let nOverwatch = max(0, rem1 - nFlank) + wto_cmd_push_demands(0, WTO_CMD_ASSAULT, WTO_URGENCY_HIGH, nAssault, dCap, dRole, dUrg, dCount) + wto_cmd_push_demands(0, WTO_CMD_FLANK, WTO_URGENCY_HIGH, nFlank, dCap, dRole, dUrg, dCount) + wto_cmd_push_demands(0, WTO_CMD_OVERWATCH, WTO_URGENCY_MED, nOverwatch, dCap, dRole, dUrg, dCount) + else + let nDefend = min(n, (n * WTO_AI_CMD_CONQ_HOLD_DEFEND_PCT + 50) / 100) + let rem1 = max(0, n - nDefend) + let nOverwatch = min(rem1, (n * WTO_AI_CMD_CONQ_HOLD_OVERWATCH_PCT + 50) / 100) + let nFlank = max(0, rem1 - nOverwatch) + let defUrg = world.caps[0].contested ? WTO_URGENCY_HIGH : WTO_URGENCY_LOW + wto_cmd_push_demands(0, WTO_CMD_DEFEND, defUrg, nDefend, dCap, dRole, dUrg, dCount) + wto_cmd_push_demands(0, WTO_CMD_OVERWATCH, WTO_URGENCY_MED, nOverwatch, dCap, dRole, dUrg, dCount) + wto_cmd_push_demands(0, WTO_CMD_FLANK, WTO_URGENCY_MED, nFlank, dCap, dRole, dUrg, dCount) + return 0 + +[never_inline] +def public wto_cmd_plan_dom(world : WtoWorldSnap const&; army, n : int; + var dCap : int[64]&; var dRole : int[64]&; var dUrg : int[64]&; + var dCount : int&) : int + let spawnPt = world.teamSpawnValid[army] ? world.teamSpawnCenter[army] : world.battleCenter + var prio : int[2] + prio[0] = -1 + prio[1] = -1 + var prioCnt = 0 + var bestMidScore = 1.0e12 + for c in range(world.capCount) + if world.caps[c].ownerArmy != army + let sc = wto_xz_dist_sq(world.caps[c].center, world.battleCenter) + if sc < bestMidScore + bestMidScore = sc + prio[0] = c + if prio[0] >= 0 + prioCnt = 1 + var bestNear = 1.0e12 + for c in range(world.capCount) + if c != prio[0] && world.caps[c].ownerArmy != army + let sc = wto_xz_dist_sq(world.caps[c].center, spawnPt) + if sc < bestNear + bestNear = sc + prio[1] = c + if prio[1] >= 0 + prioCnt = 2 + var remaining = n + for c in range(world.capCount) + if world.caps[c].ownerArmy == army && remaining > (prioCnt > 0 ? 1 : 0) + let keep = min(WTO_AI_CMD_DOM_MAX_DEFENDERS, remaining - (prioCnt > 0 ? 1 : 0)) + let urg = world.caps[c].contested ? WTO_URGENCY_HIGH : WTO_URGENCY_LOW + wto_cmd_push_demands(c, WTO_CMD_DEFEND, urg, keep, dCap, dRole, dUrg, dCount) + remaining -= keep + if prioCnt == 0 + let perCap = max(1, remaining / max(1, world.capCount)) + for c in range(world.capCount) + let take = c == world.capCount - 1 ? remaining : min(remaining, perCap) + let urg = world.caps[c].contested ? WTO_URGENCY_HIGH : WTO_URGENCY_LOW + wto_cmd_push_demands(c, WTO_CMD_OVERWATCH, urg, take, dCap, dRole, dUrg, dCount) + remaining -= take + return 0 + let firstShare = prioCnt == 1 ? remaining : (remaining + 1) / 2 + for p in range(prioCnt) + let share = p == 0 ? firstShare : (remaining - firstShare) + if share <= 0 + continue + let nAssault = clamp((share * WTO_AI_CMD_DOM_ASSAULT_PCT + 50) / 100, 1, share) + let nOverwatch = max(0, share - nAssault) + wto_cmd_push_demands(prio[p], WTO_CMD_ASSAULT, WTO_URGENCY_HIGH, nAssault, dCap, dRole, dUrg, dCount) + wto_cmd_push_demands(prio[p], WTO_CMD_OVERWATCH, WTO_URGENCY_MED, nOverwatch, dCap, dRole, dUrg, dCount) + return prio[0] + +[never_inline] +def public wto_cmd_apply_recall_demands(world : WtoWorldSnap const&; army, n : int; + lanes : WtoTeamLanes const&; enemiesInCap : int[8]; + var dCap : int[64]&; var dRole : int[64]&; + var dUrg : int[64]&; dCount : int) + for c in range(world.capCount) + let k = wto_lanes_cap_key(army, c) + if !lanes.recallActive[k] + continue + let needed = clamp(enemiesInCap[c] + 1, 1, max(1, n - 1)) + var curDef = 0 + var curOff = 0 + for di in range(dCount) + if dCap[di] == c && dRole[di] == WTO_CMD_DEFEND + dUrg[di] = WTO_URGENCY_HIGH + curDef++ + if wto_order_is_offensive(dRole[di]) + curOff++ + for stage in range(2) + for di in range(dCount) + if curDef >= needed + break + if dCap[di] == c && dRole[di] == WTO_CMD_DEFEND + continue + let isSupport = dRole[di] == WTO_CMD_RESERVE || dRole[di] == WTO_CMD_OVERWATCH + let canPullOff = stage == 1 && wto_order_is_offensive(dRole[di]) && curOff > 1 + if (stage == 0 && isSupport) || canPullOff + if wto_order_is_offensive(dRole[di]) + curOff-- + dCap[di] = c + dRole[di] = WTO_CMD_DEFEND + dUrg[di] = WTO_URGENCY_HIGH + curDef++ diff --git a/game-ai/ground/wto_ai_cover_common.das b/game-ai/ground/wto_ai_cover_common.das new file mode 100644 index 0000000..4098094 --- /dev/null +++ b/game-ai/ground/wto_ai_cover_common.das @@ -0,0 +1,121 @@ +// Cover memory, hull concealment check, 9-candidate retreat cover search, and +// enemy-free repair cover search (plan sections 5.1, 6, 6.1). +options indenting = 2 +options no_global_heap = true +module wto_ai_cover_common shared + +require ecs +require math +require %appGame.wtoai.wto_ai_config_common +require %appGame.wtoai.wto_ai_math_common +require %appGame.wtoai.wto_ai_combat_types_common +require %appGame.wtoai.wto_ai_types_common +require %appGame.wtoai.wto_ai_terrain_common +require %appGame.wtoai.wto_ai_sight_common + +[never_inline] +def public wto_cover_is_hull_concealed(world : WtoWorldSnap const&; + selfEid, targetEid : EntityId; + myPos, threatPos : float3) : bool + let myHull = myPos + float3(0.0, 1.15, 0.0) + let tgtEye = threatPos + float3(0.0, 1.85, 0.0) + return wto_sight_hard_segment_blocked(world, selfEid, targetEid, myHull, tgtEye, 0.0, 0.45, 0.65) != WTO_BLOCK_NONE + +[never_inline] +def public wto_cover_update_memory(world : WtoWorldSnap const&; now : float; + myPos : float3; var slot : WtoBotSlot&) + assume tac = slot.tactics + assume p = slot.perceive + if tac.state == WTO_STATE_RETREAT_COVER || tac.state == WTO_STATE_COVER_RELOAD || tac.state == WTO_STATE_DISABLED + return + if !p.targetEid || p.targetIsAir || (now - p.lastSeenAt) > WTO_AI_TACTICS_MEMORY_TTL_SEC + return + if wto_cover_is_hull_concealed(world, slot.eid, p.targetEid, myPos, p.knownPos) + tac.lastCoverPos = myPos + tac.lastCoverValid = true + tac.lastCoverAt = now + +[never_inline] +def private wto_cover_enemy_danger(world : WtoWorldSnap const&; now : float; + army : int; cand : float3) : float + var danger = 0.0 + let safeR = WTO_AI_SM_REPAIR_SAFE_DIST_M + let safeRSq = safeR * safeR + for i in range(world.unitCount) + assume u = world.units[i] + if !u.isAlive || !u.isGround || u.army == army + continue + let dSq = wto_xz_dist_sq(cand, u.pos) + if dSq < safeRSq + let d = sqrt(dSq) + danger += (safeR - d) * 2.5 + for r in range(WTO_MAX_RADIO) + assume sp = world.radioSpots[r] + if sp.untilAt <= now || sp.army != army + continue + let dSq = wto_xz_dist_sq(cand, sp.pos) + if dSq < safeRSq + let d = sqrt(dSq) + danger += (safeR - d) * 1.2 + return danger + +[never_inline] +def private wto_cover_eval_candidate(world : WtoWorldSnap const&; now : float; + myPos, threatPos, spawnDir : float3; + avoidEnemies : bool; isOriginalCover : bool; + candIn : float3; slot : WtoBotSlot const&; + var bestScore : float&; var outPos : float3&) : bool + var cand = wto_clamp_battle_xz(candIn, world.battleCenter, world.battleRadius, 35.0) + if !wto_terrain_point_valid(slot.army, cand) + return false + if !wto_cover_is_hull_concealed(world, slot.eid, slot.perceive.targetEid, cand, threatPos) + return false + let dist = sqrt(wto_xz_dist_sq(myPos, cand)) + var sc = dist + if isOriginalCover + sc -= 14.0 + let stepDir = wto_xz_normalize(cand - myPos, spawnDir) + sc -= dot(stepDir, spawnDir) * (avoidEnemies ? 18.0 : 6.0) + if avoidEnemies + sc += wto_cover_enemy_danger(world, now, slot.army, cand) + if sc < bestScore + bestScore = sc + outPos = cand + return true + return false + +[never_inline] +def public wto_cover_pick_candidate(world : WtoWorldSnap const&; now : float; + myPos, threatPos : float3; avoidEnemies : bool; + slot : WtoBotSlot const&; var outPos : float3&) : bool + let threatDir = wto_xz_normalize(threatPos - myPos, float3(1.0, 0.0, 0.0)) + let away = -threatDir + let lat = float3(-threatDir.z, 0.0, threatDir.x) + let spawnDir = world.teamSpawnValid[slot.army] ? wto_xz_normalize(world.teamSpawnCenter[slot.army] - myPos, away) : away + var bestScore = 1.0e9 + var found = false + + // Candidate 0: remembered last cover position along the peek path. + assume tac = slot.tactics + if tac.lastCoverValid && (now - tac.lastCoverAt) <= 25.0 + let dOrig = sqrt(wto_xz_dist_sq(myPos, tac.lastCoverPos)) + if dOrig >= WTO_AI_SM_COVER_MIN_DIST_M && dOrig <= (avoidEnemies ? 45.0 : WTO_AI_SM_COVER_MAX_DIST_M) + if wto_cover_eval_candidate(world, now, myPos, threatPos, spawnDir, avoidEnemies, true, tac.lastCoverPos, slot, bestScore, outPos) + found = true + + // Candidates 1..8: two rings (rear + side-rear) around current position. + let r1 = avoidEnemies ? 24.0 : 14.0 + let r2 = avoidEnemies ? 44.0 : 24.0 + var offsets : float3[8] + offsets[0] = away * r1 + offsets[1] = wto_xz_normalize(away + lat * 0.75, away) * r1 + offsets[2] = wto_xz_normalize(away - lat * 0.75, away) * r1 + offsets[3] = lat * r1 + offsets[4] = -lat * r1 + offsets[5] = away * r2 + offsets[6] = wto_xz_normalize(away + lat * 0.9, away) * r2 + offsets[7] = wto_xz_normalize(away - lat * 0.9, away) * r2 + for k in range(8) + if wto_cover_eval_candidate(world, now, myPos, threatPos, spawnDir, avoidEnemies, false, myPos + offsets[k], slot, bestScore, outPos) + found = true + return found diff --git a/game-ai/ground/wto_ai_crowd_common.das b/game-ai/ground/wto_ai_crowd_common.das new file mode 100644 index 0000000..6b33a4d --- /dev/null +++ b/game-ai/ground/wto_ai_crowd_common.das @@ -0,0 +1,128 @@ +// Anti-clustering telemetry & active dispersion solver: measures local friendly density around +// every tracked bot, updates match-wide crowd statistics for `.clog`, and computes drivable +// lateral/oblique dispersion anchors whenever allies bunch up. +options indenting = 2 +options no_global_heap = true +module wto_ai_crowd_common shared + +require ecs +require math +require %appGame.wtoai.wto_ai_config_common +require %appGame.wtoai.wto_ai_math_common +require %appGame.wtoai.wto_ai_types_common +require %appGame.wtoai.wto_ai_terrain_common +require %appGame.wtoai.wto_ai_world_common + +[never_inline] +def public wto_crowd_point_penalty(world : WtoWorldSnap const&; army : int; selfEid : EntityId; + pt : float3) : float + let rad = max(12.0, WTO_AI_CROWD_CLUSTER_RADIUS_M) + let radSq = rad * rad + var pen = 0.0 + for i in range(world.unitCount) + assume u = world.units[i] + if !u.isAlive || !u.isGround || u.army != army || u.eid == selfEid + continue + let dSq = wto_xz_dist_sq(pt, u.pos) + if dSq < radSq + let d = sqrt(dSq) + pen += (1.0 - d / rad) * 24.0 + if d < WTO_AI_CROWD_PERSONAL_SPACE_M + pen += (WTO_AI_CROWD_PERSONAL_SPACE_M - d) * 4.5 + return pen + +[never_inline] +def private wto_eval_bot_crowd(world : WtoWorldSnap const&; myPos : float3; mySpeed : float; + slot : WtoBotSlot const&; var outInfo : WtoCrowdInfo&) + outInfo = WtoCrowdInfo() + let personalSq = wto_sq(WTO_AI_CROWD_PERSONAL_SPACE_M) + let clusterSq = wto_sq(WTO_AI_CROWD_CLUSTER_RADIUS_M) + var repulse = float3(0.0, 0.0, 0.0) + var nearestSpeed = 0.0 + var higherPriorityAllies = 0 + for i in range(world.unitCount) + assume u = world.units[i] + if !u.isAlive || !u.isGround || u.army != slot.army || u.eid == slot.eid + continue + let dSq = wto_xz_dist_sq(myPos, u.pos) + if dSq >= clusterSq + continue + let d = max(0.5, sqrt(dSq)) + outInfo.clusterAllyCount++ + if u.isHuman || uint(u.eid) < uint(slot.eid) + higherPriorityAllies++ + if d < outInfo.nearestAllyDistM + outInfo.nearestAllyDistM = d + outInfo.nearestAllyEid = u.eid + nearestSpeed = wto_xz_len(u.vel) + if dSq <= personalSq + outInfo.nearPersonalCount++ + let away = wto_xz_normalize(myPos - u.pos, float3(1.0, 0.0, 0.0)) + let w = clamp((WTO_AI_CROWD_CLUSTER_RADIUS_M - d) / max(4.0, d), 0.15, 6.0) + repulse += away * w + let hashYaw = float(int(uint(slot.eid) % 7u) - 3) * 0.45 + let fallbackDir = float3(cos(hashYaw), 0.0, sin(hashYaw)) + outInfo.repulseDirXZ = wto_xz_normalize(repulse, fallbackDir) + // Trigger dispersion when personal space is violated (yielding to human or lower-eid leader, + // or whenever both tanks are nearly parked) OR when local cluster exceeds max allies. + let yieldPair = higherPriorityAllies > 0 || (mySpeed < 1.5 && nearestSpeed < 1.5) + if outInfo.nearPersonalCount > 0 && yieldPair + outInfo.isCrowded = true + elif outInfo.clusterAllyCount >= WTO_AI_CROWD_CLUSTER_MAX_ALLIES && higherPriorityAllies >= 1 + outInfo.isCrowded = true + +[never_inline] +def public wto_crowd_update_all(world : WtoWorldSnap const&; var bots : WtoBotSlot[64]&; + var summary : WtoCrowdSummary&) + summary.crowdedBotCount = 0 + summary.maxClusterSize = 1 + summary.minPairDistM = 999.0 + for i in range(WTO_MAX_BOTS) + if !bots[i].used + continue + let uIdx = wto_world_find_unit(world, bots[i].eid) + if uIdx < 0 + bots[i].crowd = WtoCrowdInfo() + continue + let myPos = world.units[uIdx].pos + let mySpd = wto_xz_len(world.units[uIdx].vel) + wto_eval_bot_crowd(world, myPos, mySpd, bots[i], bots[i].crowd) + if bots[i].crowd.isCrowded + summary.crowdedBotCount++ + summary.maxClusterSize = max(summary.maxClusterSize, bots[i].crowd.clusterAllyCount + 1) + summary.minPairDistM = min(summary.minPairDistM, bots[i].crowd.nearestAllyDistM) + +// Pick a drivable dispersion target 22..34m laterally/away from the cluster that maximizes +// spacing from teammates without stepping onto a cliff or into enemy spawn. +[never_inline] +def public wto_crowd_pick_disperse_pos(world : WtoWorldSnap const&; army : int; selfEid : EntityId; + myPos, threatDirXZ : float3; crowd : WtoCrowdInfo const&) : float3 + let fwd = wto_xz_normalize(threatDirXZ, float3(1.0, 0.0, 0.0)) + let lat = float3(-fwd.z, 0.0, fwd.x) + let rep = wto_xz_normalize(crowd.repulseDirXZ, lat) + let baseYaw = atan2(rep.z, rep.x) + let stepM = WTO_AI_CROWD_DISPERSE_STEP_M + let sideBias = (uint(selfEid) & 1u) == 0u ? 1.0 : -1.0 + var bestPos = myPos + rep * stepM + var bestScore = -1.0e9 + for k in range(8) + let angOff = float(k - 3) * 0.52 * sideBias + let candYaw = baseYaw + angOff + let dir = float3(cos(candYaw), 0.0, sin(candYaw)) + var cand = float3(myPos.x + dir.x * stepM, myPos.y, myPos.z + dir.z * stepM) + cand = wto_clamp_battle_xz(cand, world.battleCenter, world.battleRadius, 35.0) + if !wto_terrain_point_valid(army, cand) + continue + if wto_terrain_has_cliff_ahead(myPos, dir, min(stepM, 18.0)) + continue + if wto_terrain_hard_ray(myPos + float3(0.0, 1.3, 0.0), dir, min(stepM, 16.0)) < 9.0 + continue + // Prefer lateral dispersion over pushing blindly forward into enemy guns. + let fwdProj = dot(dir, fwd) + let repAlign = dot(dir, rep) * 14.0 + let latBonus = (1.0 - abs(fwdProj)) * 12.0 - max(0.0, fwdProj) * 8.0 + let score = repAlign + latBonus - wto_crowd_point_penalty(world, army, selfEid, cand) + if score > bestScore + bestScore = score + bestPos = cand + return bestPos diff --git a/game-ai/ground/wto_ai_diag_common.das b/game-ai/ground/wto_ai_diag_common.das new file mode 100644 index 0000000..1aebff1 --- /dev/null +++ b/game-ai/ground/wto_ai_diag_common.das @@ -0,0 +1,64 @@ +// Periodic telemetry and sample logging for the ground AI runtime. +options indenting = 2 +options no_global_heap = true +module wto_ai_diag_common shared + +require ecs +require math +require pathfinder +require %appGame.wtoai.wto_ai_types_common +require %appGame.wtoai.wto_ai_world_common + +[never_inline] +def private wto_log_bot_and_cap_samples(world : WtoWorldSnap const&; bots : WtoBotSlot[64]) + var sampled = 0 + for i in range(WTO_MAX_BOTS) + if !bots[i].used || sampled >= 2 + continue + assume b = bots[i] + print("WTO_AI|BOT_SAMPLE|eid={uint(b.eid)}|role={b.spec.role}|stab={b.spec.hasVertStab}|v0={b.fire.activeSpeedMps}|st={b.tactics.state}|allyD={b.crowd.nearestAllyDistM}|clust={b.crowd.clusterAllyCount}|ridge={b.tactics.onExposedRidge}|los={b.perceive.hasClearLos}|fc={b.fire.gunReady}/{b.fire.reloading}/{b.fire.lastAligned}|err={b.fire.lastAimErrDeg}|omB={b.fire.barrelOmegaDegSec}|mode={b.driveCmd.mode}|v={b.drive.lastVFwd}|clr={b.nav.frontClearM}/{b.nav.rearClearM}|wp={b.route.corridorIdx}/{b.route.corridorLen}|proj={b.route.lastStartOk}/{b.route.lastGoalOk}\n") + sampled++ + for c in range(world.capCount) + assume z = world.caps[c] + print("WTO_AI|CAP|idx={c}|owner={z.ownerArmy}|rad={z.radius}|prog={z.progress}\n") + +[never_inline] +def public wto_diag_log_telemetry(world : WtoWorldSnap const&; now : float; + bots : WtoBotSlot[64]; crowd : WtoCrowdSummary const&) + var active = 0 + var routeB = 0 + var revNow = 0 + var engNow = 0 + var dispNow = 0 + var ridgeNow = 0 + var revEvents = 0 + var ridgeWithdraws = 0 + var detours = 0 + var shots = 0 + var errSum = 0.0 + var maxErr = 0.0 + var roles : int[5] + for r in range(5) + roles[r] = 0 + for i in range(WTO_MAX_BOTS) + if !bots[i].used + continue + assume b = bots[i] + active++ + roles[clamp(b.spec.role, 0, 4)]++ + routeB += b.drive.routeBOwned ? 1 : 0 + revNow += b.driveCmd.mode == WTO_DRIVE_REVERSE ? 1 : 0 + engNow += b.tactics.state == WTO_STATE_SHORT_HALT ? 1 : 0 + dispNow += b.tactics.state == WTO_STATE_DISPERSE ? 1 : 0 + ridgeNow += b.tactics.onExposedRidge ? 1 : 0 + revEvents += b.nav.reverseCount + ridgeWithdraws += b.nav.ridgeWithdrawEvents + detours += b.route.detourCount + shots += b.fire.shotCount + errSum += b.fire.shotErrSumDeg + maxErr = max(maxErr, b.fire.maxShotErrDeg) + let avgErr = shots > 0 ? (errSum / float(shots)) : 0.0 + let jams = wto_world_active_jams(world, now) + let nm1 = pathfinder_is_loaded_ex(1) + print("WTO_AI|STAT|t={now}|bots={active}|roles={roles[0]}/{roles[1]}/{roles[2]}/{roles[3]}/{roles[4]}|crowd={crowd.crowdedBotCount}|maxClust={crowd.maxClusterSize}|minAllyD={crowd.minPairDistM}|dispNow={dispNow}|dispEv={crowd.disperseEvents}|ridgeNow={ridgeNow}|ridgeRevEv={ridgeWithdraws}|eng={engNow}|revNow={revNow}|revEv={revEvents}|jams={jams}|detours={detours}|shots={shots}|avgAimErr={avgErr}|maxAimErr={maxErr}|routeB={routeB}|caps={world.capCount}|nm1={nm1}\n") + wto_log_bot_and_cap_samples(world, bots) diff --git a/game-ai/ground/wto_ai_drive_common.das b/game-ai/ground/wto_ai_drive_common.das new file mode 100644 index 0000000..a45386e --- /dev/null +++ b/game-ai/ground/wto_ai_drive_common.das @@ -0,0 +1,234 @@ +// Chassis drive actuator: translates `WtoDriveCmd` into closed-loop `VehiclePhysActor` axes +// (throttle, steering, brakes, auto-transmission) with space-aware 3-point turns, smooth +// long-distance reverse control, and dead-echo watchdog return to stock movement. +options indenting = 2 +options no_global_heap = true +module wto_ai_drive_common shared + +require ecs +require math +require DagorMath +require DagorDataBlock +require DagorSystem +require Mission +require Unit +require IGroundModel +require vehicle +require %appGame.wtoai.wto_ai_config_common +require %appGame.wtoai.wto_ai_math_common +require %appGame.wtoai.wto_ai_types_common + +[never_inline] +def public wto_drive_announce_script_ready() + let own = (WTO_AI_ENABLED && WTO_AI_LAYER_NAVIGATION && WTO_AI_NAV_DRIVE_MODE == "vehicle_phys") ? "1" : "0" + using() <| $(var blk : DataBlock) + add(blk, "ownMovement", own) + call_mission_action("wtoGroundAiScriptReady", blk) + +[never_inline] +def public wto_drive_request_control(eid : EntityId; holdMs : int) + using() <| $(var blk : DataBlock) + add(blk, "eid", "{uint(eid)}") + add(blk, "holdMs", "{holdMs}") + call_mission_action("wtoGroundAiDriveControl", blk) + +[never_inline] +def public wto_drive_release_all() + using() <| $(var blk : DataBlock) + add(blk, "eid", "0") + add(blk, "holdMs", "0") + call_mission_action("wtoGroundAiDriveControl", blk) + +[never_inline] +def private wto_set_phys_axes(var actor : VehiclePhysActor&; thr, str, brk, handBrk : float) + actor.phys.producedCT |> ground_control_state_setAutomaticTransmission(true) + actor.phys.producedCT |> ground_control_state_setCruiseControl(int8(0)) + actor.phys.producedCT |> ground_control_state_setAxisValue(EGroundControlAxis.GCA_THROTTLE, clamp(thr, -1.0, 1.0)) + actor.phys.producedCT |> ground_control_state_setAxisValue(EGroundControlAxis.GCA_STEERING, clamp(str, -1.0, 1.0)) + actor.phys.producedCT |> ground_control_state_setAxisValue(EGroundControlAxis.GCA_BRAKE_LEFT, clamp(brk, 0.0, 1.0)) + actor.phys.producedCT |> ground_control_state_setAxisValue(EGroundControlAxis.GCA_BRAKE_RIGHT, clamp(brk, 0.0, 1.0)) + actor.phys.producedCT |> ground_control_state_setAxisValue(EGroundControlAxis.GCA_CLUTCH, 0.0) + actor.phys.producedCT |> ground_control_state_setAxisValue(EGroundControlAxis.GCA_HAND_BRAKE, clamp(handBrk, 0.0, 1.0)) + +[never_inline] +def private wto_check_echo_watchdog(unitMissionName : string; var actor : VehiclePhysActor&; + dt : float; var slot : WtoBotSlot&) : bool + assume st = slot.drive + let appThr = ground_control_state_getAxisValue(actor.phys.appliedCT, EGroundControlAxis.GCA_THROTTLE) + let appStr = ground_control_state_getAxisValue(actor.phys.appliedCT, EGroundControlAxis.GCA_STEERING) + let wantsThrottle = abs(st.prevThr) >= 0.35 + let wantsSteering = abs(st.prevStr) >= 0.45 + let throttleEchoed = !wantsThrottle || abs(appThr) >= 0.05 + let steeringEchoed = !wantsSteering || abs(appStr) >= 0.05 + if !throttleEchoed || !steeringEchoed + st.deadEchoSec += clamp(dt, 0.0, 0.15) + if st.deadEchoSec >= WTO_AI_NAV_DEAD_ECHO_SEC + if !st.failLogged + print("WTO_AI|PHYS_STALL|actor={unitMissionName}|eid={uint(slot.eid)}\n") + return false + else + st.deadEchoSec = 0.0 + return true + +[never_inline] +def private wto_compute_pivot_axes(cmd : WtoDriveCmd const&; spec : WtoVehicleSpec const&; + fwd, left : float3; vFwd, omega : float; + var outThr, outStr, outBrk : float&) + let wish = wto_xz_normalize(cmd.desiredDir, fwd) + let errRad = atan2(dot(wish, left), dot(wish, fwd)) + let turnSign = errRad >= 0.0 ? 1.0 : -1.0 + if abs(vFwd) > 3.6 + outThr = vFwd > 0.0 ? -0.9 : 0.9 + outBrk = 1.0 + outStr = turnSign * WTO_AI_NAV_STEER_SIGN + return + let openFront = cmd.frontClearM >= spec.halfLen + 3.5 + if openFront + // Two-beat turn micro: launch straight to 2nd gear before applying full steering. + outThr = 1.0 + outStr = abs(vFwd) < WTO_AI_SM_TURN_LAUNCH_MPS ? 0.0 : (turnSign * WTO_AI_NAV_STEER_SIGN) + return + if spec.canPivot && cmd.frontClearM >= spec.halfLen + 1.2 && cmd.rearClearM >= spec.halfLen + 1.0 + outThr = 0.0 + outStr = clamp(turnSign - omega * 0.35, -1.0, 1.0) * WTO_AI_NAV_STEER_SIGN + return + // Tight front obstacle: execute clean 3-point reverse turn instead of ramming the wall. + outThr = vFwd > -WTO_AI_SM_TURN_LAUNCH_MPS ? -1.0 : -0.6 + outStr = (abs(vFwd) < 1.2 ? 0.0 : -turnSign) * WTO_AI_NAV_STEER_SIGN + +[never_inline] +def private wto_compute_reverse_axes(cmd : WtoDriveCmd const&; spec : WtoVehicleSpec const&; + fwd, left : float3; vFwd, omega : float; + var outThr, outStr, outBrk, outHand : float&) + if cmd.rearClearM < 2.1 + outThr = 0.0 + outBrk = 1.0 + outHand = 1.0 + return + if vFwd > 0.30 + outThr = -1.0 + outBrk = 1.0 + return + let rear = -fwd + let wishRear = wto_xz_normalize(cmd.desiredDir, rear) + // Coordinate-free signed rear angle: >0 means desired rear travel lies toward hull LEFT (+Z). + let rearErr = atan2(dot(wishRear, left), dot(wishRear, rear)) + outStr = clamp(rearErr * 1.45 + omega * 0.28, -1.0, 1.0) * WTO_AI_NAV_STEER_SIGN + let maxSafeRev = min(spec.vMaxRev, sqrt(max(1.0, (cmd.rearClearM - 1.8) * 2.2))) + let vTarget = -clamp(cmd.speedMps, 1.2, max(1.4, maxSafeRev)) + let vErr = vTarget - vFwd + outThr = vErr < -0.15 ? clamp(-0.52 + vErr * 0.32, -1.0, -0.35) : -0.28 + +[never_inline] +def private wto_compute_cruise_axes(cmd : WtoDriveCmd const&; spec : WtoVehicleSpec const&; + fwd, left : float3; vFwd, omega : float; + var outThr, outStr, outBrk : float&) + let wish = wto_xz_normalize(cmd.desiredDir, fwd) + let yawErr = atan2(dot(wish, left), dot(wish, fwd)) + outStr = clamp(yawErr * 1.38 - omega * 0.28, -1.0, 1.0) * WTO_AI_NAV_STEER_SIGN + let absErr = abs(yawErr) + var vLimit = min(cmd.speedMps, spec.vMaxFwd) + if absErr > 0.22 + let radiusEst = max(4.0, 14.0 / max(0.25, absErr)) + vLimit = min(vLimit, sqrt(WTO_AI_NAV_CORNER_BRAKE_ACCEL * radiusEst)) + if cmd.frontClearM < 12.0 + vLimit = min(vLimit, max(2.2, (cmd.frontClearM - 2.0) * 0.75)) + let vErr = vLimit - vFwd + if vErr < -1.5 + outThr = 0.0 + outBrk = clamp((-vErr - 1.2) * 0.35, 0.2, 1.0) + elif vErr >= 0.6 + outThr = 1.0 + else + outThr = clamp(0.45 + vErr * 0.45, 0.15, 1.0) + +[never_inline] +def private wto_drive_is_immobilized(actor : VehiclePhysActor const&) : bool + assume dmg = actor.phys.currentState.damageState + return (!dmg.allowMoveControl || dmg.engineReadyness <= 0.0 || + dmg.driverReadyness <= 0.0 || (dmg.trackLBroken && dmg.trackRBroken)) + +[never_inline] +def private wto_drive_halt_on_failure(var actor : VehiclePhysActor&; + var slot : WtoBotSlot&; reason : string) + assume st = slot.drive + if !st.failLogged + st.failLogged = true + print("WTO_AI|DRIVE_FAIL|eid={uint(slot.eid)}|reason={reason}\n") + st.prevThr = 0.0 + st.prevStr = 0.0 + st.deadEchoSec = 0.0 + wto_set_phys_axes(actor, 0.0, 0.0, 1.0, 1.0) + +[never_inline] +def private wto_ensure_phys_owner(gm : IGroundModel const?; var actor : VehiclePhysActor&; + var slot : WtoBotSlot&) : bool + assume st = slot.drive + if gm == null || gm.moveSys == null + return false + if !st.routeBOwned || !gm.moveSys.inactive + wto_drive_request_control(slot.eid, 1000) + if !gm.moveSys.inactive + return false + if !st.routeBOwned + slot.spec.isTracked = actor.phys.trackWidth > 0.01 + slot.spec.canPivot = slot.spec.isTracked && actor.phys.haveSeparateBrakes + st.routeBOwned = true + return st.routeBOwned + +[never_inline] +def public wto_drive_step_phys(var unit : Unit?; unitMissionName : string; + gm : IGroundModel const?; var actor : VehiclePhysActor&; + dt, now : float; var slot : WtoBotSlot&) + if unit == null || actor.physEdit == null + return + if !wto_ensure_phys_owner(gm, actor, slot) + return + if !slot.driveCmd.valid || (!slot.order.valid && !WTO_AI_LAYER_TACTICS) + wto_drive_halt_on_failure(actor, slot, "invalid_drive_cmd") + return + if now > slot.nextNavAt + WTO_AI_NAV_TICK_SEC * 2.0 + wto_drive_halt_on_failure(actor, slot, "stale_nav_tick") + return + let immobile = wto_drive_is_immobilized(actor) + slot.tactics.immobilized = immobile + if immobile + slot.drive.prevThr = 0.0 + slot.drive.prevStr = 0.0 + slot.drive.deadEchoSec = 0.0 + wto_set_phys_axes(actor, 0.0, 0.0, 1.0, 1.0) + return + if !wto_check_echo_watchdog(unitMissionName, actor, dt, slot) + wto_drive_halt_on_failure(actor, slot, "dead_echo") + return + slot.drive.failLogged = false + vehicle_actor_set_allow_move_control(actor, true) + assume st = slot.drive + assume cmd = slot.driveCmd + let fwd = wto_xz_normalize(unit.unitTm[0], float3(1.0, 0.0, 0.0)) + let left = float3(-fwd.z, 0.0, fwd.x) + let curYaw = atan2(fwd.z, fwd.x) + let vFwd = dot(vehicle_phys_getCurrentStateVelocity(actor.phys), fwd) + st.lastVFwd = vFwd + let age = now - st.prevYawAt + st.omegaYawRad = (age > 1.0e-4 && age <= 0.25) ? lerp(clamp(wto_wrap_rad(curYaw - st.prevYaw) / age, -3.0, 3.0), st.omegaYawRad, 0.6) : 0.0 + st.prevYaw = curYaw + st.prevYawAt = now + + var thr = 0.0 + var str = 0.0 + var brk = 0.0 + var hand = 0.0 + if !cmd.valid || cmd.mode == WTO_DRIVE_HALT || cmd.speedMps <= 0.05 + thr = abs(vFwd) > 0.35 ? (vFwd > 0.0 ? -1.0 : 1.0) : 0.0 + brk = 1.0 + hand = abs(vFwd) > 0.35 ? 0.0 : 1.0 + elif cmd.mode == WTO_DRIVE_PIVOT + wto_compute_pivot_axes(cmd, slot.spec, fwd, left, vFwd, st.omegaYawRad, thr, str, brk) + elif cmd.mode == WTO_DRIVE_REVERSE + wto_compute_reverse_axes(cmd, slot.spec, fwd, left, vFwd, st.omegaYawRad, thr, str, brk, hand) + else + wto_compute_cruise_axes(cmd, slot.spec, fwd, left, vFwd, st.omegaYawRad, thr, str, brk) + st.prevThr = thr + st.prevStr = str + wto_set_phys_axes(actor, thr, str, brk, hand) diff --git a/game-ai/ground/wto_ai_estimate_common.das b/game-ai/ground/wto_ai_estimate_common.das new file mode 100644 index 0000000..59fdb91 --- /dev/null +++ b/game-ai/ground/wto_ai_estimate_common.das @@ -0,0 +1,134 @@ +// Own-sight target velocity estimator, bounded 2-5 s last-seen exit watch, and +// once-per-opportunity bounded aiming bias (never reads true target velocity). +options indenting = 2 +options no_global_heap = true +module wto_ai_estimate_common shared + +require ecs +require math +require %appGame.wtoai.wto_ai_config_common +require %appGame.wtoai.wto_ai_math_common +require %appGame.wtoai.wto_ai_combat_types_common +require %appGame.wtoai.wto_ai_types_common + +[never_inline] +def private wto_est_hash(seed : uint) : uint + var x = seed ^ 0x9e3779b9u + x = (x ^ (x >> 16u)) * 0x85ebca6bu + x = (x ^ (x >> 13u)) * 0xc2b2ae35u + return x ^ (x >> 16u) + +[never_inline] +def private wto_est_rand01(seed : uint) : float + return float(wto_est_hash(seed) & 0xffffu) / 65535.0 + +[never_inline] +def public wto_est_reset_samples(var p : WtoPerceiveState&) + p.sampleCount = 0 + p.sampleHead = 0 + p.estVel = float3(0.0, 0.0, 0.0) + p.velQuality = 0.0 + p.oppSeeded = false + +[never_inline] +def public wto_est_push_visual_sample(now : float; tgtEid : EntityId; tgtPos : float3; + var p : WtoPerceiveState&) + if p.sampleTargetEid != tgtEid + p.sampleTargetEid = tgtEid + wto_est_reset_samples(p) + if p.sampleCount > 0 + let lastIdx = (p.sampleHead + WTO_MAX_VEL_SAMPLES - 1) % WTO_MAX_VEL_SAMPLES + if (now - p.sampleAt[lastIdx]) < 0.05 + return + let dst = p.sampleHead + p.samplePos[dst] = tgtPos + p.sampleAt[dst] = now + p.sampleHead = (dst + 1) % WTO_MAX_VEL_SAMPLES + p.sampleCount = min(p.sampleCount + 1, WTO_MAX_VEL_SAMPLES) + + // Find oldest still-fresh sample (<= 1.8 s old) to compute smoothed observed velocity. + var oldIdx = dst + var oldestAt = now + for k in range(p.sampleCount) + let idx = (dst + WTO_MAX_VEL_SAMPLES - k) % WTO_MAX_VEL_SAMPLES + let t = p.sampleAt[idx] + if (now - t) <= 1.8 && t < oldestAt + oldestAt = t + oldIdx = idx + let span = now - oldestAt + if span < WTO_AI_EST_MIN_SPAN_SEC + p.estVel = float3(0.0, 0.0, 0.0) + p.velQuality = 0.0 + return + var vRaw = (tgtPos - p.samplePos[oldIdx]) / span + let rawSpd = length(vRaw) + if rawSpd > 34.0 + vRaw = vRaw * (34.0 / rawSpd) + let vDiff = length(vRaw - p.estVel) + if p.velQuality > 0.25 && vDiff > WTO_AI_EST_JUMP_RESET_MPS + p.oppSeeded = false + p.estVel = lerp(p.estVel, vRaw, 0.58) + p.velQuality *= 0.35 + return + p.estVel = p.velQuality <= 0.01 ? vRaw : lerp(p.estVel, vRaw, 0.38) + let spanQ = clamp((span - WTO_AI_EST_MIN_SPAN_SEC) / max(0.1, WTO_AI_EST_STABLE_SPAN_SEC - WTO_AI_EST_MIN_SPAN_SEC), 0.0, 1.0) + let steadyQ = clamp(1.0 - vDiff * 0.07, 0.35, 1.0) + p.velQuality = spanQ * steadyQ + +[never_inline] +def public wto_est_on_los_lost(now : float; selfEid : EntityId; var p : WtoPerceiveState&) + wto_est_reset_samples(p) + if !p.wasEngaging + return + p.wasEngaging = false + if !p.targetEid || p.targetIsAir + return + p.watchPos = length_sq(p.visibleAimPt) > 1.0 ? p.visibleAimPt : (p.knownPos + float3(0.0, 1.4, 0.0)) + let seed = uint(selfEid) ^ (uint(p.targetEid) * 2654435761u) ^ uint(max(0.0, now * 100.0)) + let frac = wto_est_rand01(seed) + let dur = lerp(WTO_AI_EST_WATCH_MIN_SEC, WTO_AI_EST_WATCH_MAX_SEC, frac) + p.watchUntil = now + dur + if WTO_AI_DIAG_TELEMETRY + print("WTO_AI|WATCH|eid={uint(selfEid)}|tgt={uint(p.targetEid)}|dur={dur}\n") + +[never_inline] +def public wto_est_compute_biased_lead(muzzlePos, myVel, aimBase : float3; + var slot : WtoBotSlot&; + var outLeadPt : float3&) : float + assume p = slot.perceive + let rawDelta = aimBase - muzzlePos + let rawDist = length(rawDelta) + let dragLoss = clamp(slot.fire.activeDragCx * 0.00011 * rawDist, 0.0, 0.28) + let vEff = max(120.0, slot.fire.activeSpeedMps * (1.0 - dragLoss)) + + // Lead uses ONLY our own visual velocity estimate, scaled by observation quality. + let leadScale = p.sampleCount >= 2 ? clamp(0.35 + 0.65 * p.velQuality, 0.0, 1.0) : 0.0 + let usedVel = p.estVel * leadScale + var leadPt = aimBase + var tof = 0.0 + for _iter in range(2) + tof = clamp(length(leadPt - muzzlePos) / vEff, 0.0, 3.5) + leadPt = aimBase + usedVel * tof - myVel * (tof * 0.85) + + // Sample bounded natural bias ONCE per shooting opportunity (target + shot + state + 12m grid). + let gx = uint(int(muzzlePos.x / 12.0) + 4096) + let gz = uint(int(muzzlePos.z / 12.0) + 4096) + let key = (uint(p.targetEid) ^ (uint(slot.fire.shotCount) * 2654435761u) ^ + (uint(slot.tactics.state) * 40503u) ^ (gx * 73856093u) ^ (gz * 19349663u)) + if !p.oppSeeded || p.oppKey != key + p.oppKey = key + p.oppSeeded = true + let sBase = key ^ (uint(slot.eid) * 2246822519u) + p.oppBiasU = (wto_est_rand01(sBase) + wto_est_rand01(sBase ^ 0x517cc1b7u)) - 1.0 + p.oppBiasV = (wto_est_rand01(sBase ^ 0x9e3779b9u) + wto_est_rand01(sBase ^ 0x85ebca6bu)) - 1.0 + + // Error envelope shrinks naturally as observation quality converges. + let tgtSpd = length(p.estVel) + let leadSpread = tgtSpd * tof * WTO_AI_EST_LEAD_ERR_FRAC * (1.0 - 0.72 * p.velQuality) + let distSpread = WTO_AI_EST_BASE_SIGMA_M * clamp(rawDist / 350.0, 0.25, 2.6) * (1.2 - 0.55 * p.velQuality) + let latOff = clamp((leadSpread + distSpread) * p.oppBiasU, -WTO_AI_EST_MAX_BIAS_M, WTO_AI_EST_MAX_BIAS_M) + let vertOff = clamp(distSpread * 0.65 * p.oppBiasV, -WTO_AI_EST_MAX_BIAS_M * 0.5, WTO_AI_EST_MAX_BIAS_M * 0.5) + let toAimXZ = wto_xz_normalize(rawDelta, float3(1.0, 0.0, 0.0)) + let latAxis = float3(-toAimXZ.z, 0.0, toAimXZ.x) + outLeadPt = leadPt + latAxis * latOff + float3(0.0, vertOff, 0.0) + return rawDist diff --git a/game-ai/ground/wto_ai_fire_common.das b/game-ai/ground/wto_ai_fire_common.das new file mode 100644 index 0000000..ba6260a --- /dev/null +++ b/game-ai/ground/wto_ai_fire_common.das @@ -0,0 +1,296 @@ +// Turret servo, active loaded-shell inspection, and ballistic aim solver. +// All ground weapon firing goes exclusively through wto_fire_gate_try_shoot. +options indenting = 2 +options no_global_heap = true +module wto_ai_fire_common shared + +require ecs +require app +require math +require strings +require DagorMath +require Mission +require Unit +require IGroundModel +require Weapon +require Ballistics +require %game.utils.utils_common +require %appGame.wtoai.wto_ai_config_common +require %appGame.wtoai.wto_ai_math_common +require %appGame.wtoai.wto_ai_combat_types_common +require %appGame.wtoai.wto_ai_types_common +require %appGame.wtoai.wto_ai_world_common +require %appGame.wtoai.wto_ai_estimate_common +require %appGame.wtoai.wto_ai_fire_gate_common + +[never_inline] +def private wto_world_to_hull_deg(worldDir, hullFwd, hullUp, hullLeft : float3; + var outYawDeg, outPitchDeg : float&) + let len = length(worldDir) + if len < 1.0e-5 + outYawDeg = 0.0 + outPitchDeg = 0.0 + return + let d = worldDir / len + let f = dot(d, hullFwd) + let u = dot(d, hullUp) + let l = dot(d, hullLeft) + let horiz = sqrt(f * f + l * l) + outYawDeg = horiz > 1.0e-5 ? (-atan2(l, f) * WTO_RAD_TO_DEG) : 0.0 + outPitchDeg = clamp(atan2(u, max(1.0e-5, horiz)) * WTO_RAD_TO_DEG, -24.0, 65.0) + +[never_inline] +def private wto_hull_deg_to_world(yawDeg, pitchDeg : float; hullFwd, hullUp, hullLeft : float3) : float3 + let yr = yawDeg * WTO_DEG_TO_RAD + let pr = pitchDeg * WTO_DEG_TO_RAD + let cp = cos(pr) + let dir = hullFwd * (cp * cos(yr)) - hullLeft * (cp * sin(yr)) + hullUp * sin(pr) + let l = length(dir) + return l > 1.0e-5 ? (dir / l) : hullFwd + +[never_inline] +def private wto_sync_active_shell(gun : WTGun const?; spec : WtoVehicleSpec const&; var fc : WtoFireState&) + if gun == null + return + let chosenIdx = int(gun.chosenBulletType) + if fc.loadedBulletIdx == chosenIdx && fc.activeSpeedMps > 80.0 + return + fc.loadedBulletIdx = chosenIdx + fc.activeSpeedMps = spec.muzzleSpeedMps + fc.activeDragCx = spec.shellDragCx + fc.activeMassKg = spec.shellMassKg + fc.activeCaliberM = spec.shellCaliberM + if chosenIdx >= 0 && chosenIdx < length(gun.properties.bulletSets) + assume bs = gun.properties.bulletSets[chosenIdx] + if length(bs.bullet) > 0 && bs.bullet[0] != null + let bName = bs.bullet[0].getName + if !empty(bName) + let h = ecs_hash(bName) + for i in range(spec.shellCount) + if spec.shells[i].nameHash == h + fc.activeSpeedMps = spec.shells[i].speedMps + fc.activeDragCx = spec.shells[i].dragCx + fc.activeMassKg = spec.shells[i].massKg + fc.activeCaliberM = spec.shells[i].caliberM + return + +[never_inline] +def private wto_select_next_shell(var gun : WTGun?; spec : WtoVehicleSpec const&; wantSoft : bool) + if gun == null || spec.isAutocannonBelt + return + let setCount = length(gun.properties.bulletSets) + if setCount < 2 + return + var bestSoft = -1 + var bestArmor = -1 + var firstAvail = -1 + for bsIdx in range(setCount) + assume bs = gun.properties.bulletSets[bsIdx] + if bs.bulletsCount <= 0 || length(bs.bullet) <= 0 || bs.bullet[0] == null + continue + if firstAvail < 0 + firstAvail = bsIdx + let bName = bs.bullet[0].getName + if empty(bName) + continue + let h = ecs_hash(bName) + for si in range(spec.shellCount) + if spec.shells[si].nameHash != h + continue + if spec.shells[si].isSoftShell && bestSoft < 0 + bestSoft = bsIdx + elif spec.shells[si].isAntiArmor && bestArmor < 0 + bestArmor = bsIdx + break + var wantIdx = wantSoft ? (bestSoft >= 0 ? bestSoft : bestArmor) : (bestArmor >= 0 ? bestArmor : firstAvail) + if wantIdx < 0 + wantIdx = firstAvail + if wantIdx >= 0 && int(gun.nextBulletType) != wantIdx + gun.nextBulletType = uint8(wantIdx) + +[never_inline] +def private wto_inspect_primary_weapon(var unit : Unit?; now : float; + spec : WtoVehicleSpec const&; wantSoftShell : bool; + var fc : WtoFireState&) + fc.turretNo = -1 + fc.gunReady = false + fc.reloading = false + fc.gunDamaged = false + if unit == null || unit.weap == null + return + var anyGun = false + var anyAlive = false + var anyReserve = false + var totalLoaded = 0 + foreach_primary_gun(unit.weap.Weapons) <| $(var weapon) + if weapon == null || weapon.isDummyGun + return + var gun = as_gun(weapon) + if gun == null + if weapon.prop.launcher && weapon.countBullets > 0 + anyGun = true + anyAlive = true + anyReserve = true + if fc.turretNo < 0 + fc.turretNo = weapon.turretNo + fc.gunReady = true + totalLoaded += weapon.countBullets + return + anyGun = true + if gun.isInoperable + return + anyAlive = true + if fc.turretNo < 0 + fc.turretNo = weapon.turretNo + wto_select_next_shell(gun, spec, wantSoftShell) + wto_sync_active_shell(gun, spec, fc) + if gun.isReadyToShoot + fc.gunReady = true + totalLoaded += max(0, gun.currentLoadedAmmoCount) + if gun.currentLoadedAmmoCount > 0 || gun.currentBulletSet.bulletsCount > 0 || weapon.countBullets > 0 + anyReserve = true + fc.gunDamaged = anyGun && !anyAlive + fc.reloading = anyAlive && !fc.gunReady && anyReserve + if fc.pendingShotConfirm + if (fc.prevLoadedAmmo >= 0 && totalLoaded < fc.prevLoadedAmmo) || !fc.gunReady + fc.shotCount++ + fc.pendingShotConfirm = false + elif (now - fc.pendingShotAt) > 0.35 + fc.pendingShotConfirm = false + fc.prevLoadedAmmo = totalLoaded + +[never_inline] +def private wto_solve_ballistic_aim(muzzlePos, myVel : float3; var slot : WtoBotSlot&; + aimBase : float3; var outAimPt, outWishDir : float3&) : float + var leadPt = aimBase + let rawDist = wto_est_compute_biased_lead(muzzlePos, myVel, aimBase, slot, leadPt) + let dragLoss = clamp(slot.fire.activeDragCx * 0.00011 * rawDist, 0.0, 0.28) + let vEff = max(120.0, slot.fire.activeSpeedMps * (1.0 - dragLoss)) + outAimPt = leadPt + var arcDir = float3(0.0, 0.0, 0.0) + if calculate_arc_low_start_dir(muzzlePos, leadPt, vEff, arcDir) && length_sq(arcDir) > 0.25 + outWishDir = normalize(arcDir) + else + let d = max(1.0, length(leadPt - muzzlePos)) + let tof = d / vEff + let dropComp = float3(0.0, 0.5 * 9.81 * tof * tof, 0.0) + outWishDir = normalize(leadPt + dropComp - muzzlePos) + return rawDist + +[never_inline] +def private wto_sample_turret_muzzle(unit : Unit const?; turretNo : int; + var outPos, outDir : float3&) : bool + if unit == null || unit.weap == null + return false + for tIdx, turret in iter_range(unit.weap.turret), unit.weap.turret + if (turretNo >= 0 && tIdx != turretNo) || (turretNo < 0 && int(turret.triggerGroupNo) != int(WeaponTriggerGroups.TRIGGER_GROUP_PRIMARY)) + continue + let weapon = get_weapon(unit.weap.Weapons, int(turret.triggerNo), int(turret.weaponIndex)) + if weapon == null + continue + var gunTm : float3x4 + weapon_calcShootTm(weapon, unit.unitTm, gunTm) + if length_sq(gunTm[0]) > 0.25 + outPos = gunTm[3] + outDir = normalize(gunTm[0]) + return true + return false + +[never_inline] +def private wto_drive_turret_and_sample_barrel(var unit : Unit?; dt, now : float; + wishYawDeg, wishPitchDeg : float; + var slot : WtoBotSlot&; + var outMuzzlePos, outLiveDir : float3&) + assume fc = slot.fire + let dtStep = clamp(dt, 0.005, 0.12) + for tIdx, turret in iter_range(unit.weap.turret), unit.weap.turret + if (fc.turretNo >= 0 && tIdx != fc.turretNo) || (fc.turretNo < 0 && int(turret.triggerGroupNo) != int(WeaponTriggerGroups.TRIGGER_GROUP_PRIMARY)) + continue + fc.curYawDeg = turret.currentState.yaw + fc.curPitchDeg = turret.currentState.pitch + if !fc.servoInit + fc.cmdYawDeg = fc.curYawDeg + fc.cmdPitchDeg = fc.curPitchDeg + fc.prevPitchDeg = fc.curPitchDeg + fc.servoInit = true + let pitchSpd = abs(fc.curPitchDeg - fc.prevPitchDeg) / dtStep + fc.prevPitchDeg = fc.curPitchDeg + if slot.perceive.hasClearLos && wishPitchDeg < fc.curPitchDeg - 2.3 && pitchSpd < 0.8 + fc.pitchClampSec = min(2.0, fc.pitchClampSec + dtStep) + fc.pitchBlocked = fc.pitchClampSec >= 0.75 + else + fc.pitchClampSec = max(0.0, fc.pitchClampSec - dtStep * 2.5) + if fc.pitchClampSec <= 0.05 + fc.pitchBlocked = false + let maxYawStep = max(24.0, slot.spec.turretYawSpd * 1.1) * dtStep + let maxPitchStep = max(10.0, slot.spec.turretPitchSpd * 1.1) * dtStep + let yawDelta = clamp(wto_wrap_deg(wishYawDeg - fc.curYawDeg), -maxYawStep, maxYawStep) + let pitchDelta = clamp(wishPitchDeg - fc.curPitchDeg, -maxPitchStep, maxPitchStep) + fc.cmdYawDeg = wto_wrap_deg(fc.curYawDeg + yawDelta) + fc.cmdPitchDeg = clamp(fc.curPitchDeg + pitchDelta, slot.spec.minPitchDeg - 2.0, slot.spec.maxPitchDeg + 2.0) + turret.yawLim = fc.cmdYawDeg + turret.pitchLim = fc.cmdPitchDeg + break + var uPos = unit.pos + updateWeaponAnims(*unit.weap, dtStep, 1.0, uPos) + if !wto_sample_turret_muzzle(unit, fc.turretNo, outMuzzlePos, outLiveDir) + outLiveDir = wto_hull_deg_to_world(fc.curYawDeg, fc.curPitchDeg, unit.unitTm[0], unit.unitTm[1], unit.unitTm[2]) + let bAge = now - fc.prevBarrelAt + if bAge > 1.0e-4 && bAge <= 0.25 + let stepDeg = acos(clamp(dot(outLiveDir, fc.prevBarrelDir), -1.0, 1.0)) * WTO_RAD_TO_DEG + fc.barrelOmegaDegSec = lerp(stepDeg / bAge, fc.barrelOmegaDegSec, 0.45) + else + fc.barrelOmegaDegSec = 0.0 + fc.prevBarrelDir = outLiveDir + fc.prevBarrelAt = now + +[never_inline] +def public wto_fire_update(world : WtoWorldSnap const&; var unit : Unit?; + now, dt : float; var slot : WtoBotSlot&; var fireBudget : int&) + if !WTO_AI_LAYER_FIRE_CONTROL || unit == null || unit.weap == null + return + // SPAA vs aircraft only delegates to stock air-target fire control (never ground targets). + if slot.tactics.spaaYieldAir + var gm = as_gm(unit) + if gm != null + *gm |> set_check_visibility_target(true) + *gm |> set_ignore_stop_for_fire(true) + set_unit_attack_type(unit, "attack_target") + return + set_unit_attack_type(unit, "dont_aim") + var wantSoftShell = false + if slot.perceive.hasClearLos && !!slot.perceive.targetEid && !slot.perceive.targetIsAir + let tgtIdx = wto_world_find_unit(world, slot.perceive.targetEid) + if tgtIdx >= 0 + wantSoftShell = world.units[tgtIdx].isLightTag || world.units[tgtIdx].halfWid < 1.35 + wto_inspect_primary_weapon(unit, now, slot.spec, wantSoftShell, slot.fire) + var muzzlePos = unit.pos + float3(0.0, 1.95, 0.0) + var liveBarrelDir = unit.unitTm[0] + let _preSample = wto_sample_turret_muzzle(unit, slot.fire.turretNo, muzzlePos, liveBarrelDir) + + let hFwd = unit.unitTm[0] + var wishWorldDir = hFwd + var aimPt = muzzlePos + hFwd * 50.0 + var distToTgt = 9999.0 + let engageValid = (slot.perceive.hasClearLos && !!slot.perceive.targetEid && !slot.perceive.targetIsAir && + !(slot.spec.role == WTO_ROLE_SPAA && slot.tactics.state == WTO_STATE_DISABLED)) + if engageValid + let baseAim = slot.perceive.visibleAimPt + distToTgt = wto_solve_ballistic_aim(muzzlePos, unit.vel, slot, baseAim, aimPt, wishWorldDir) + elif now < slot.perceive.watchUntil + wishWorldDir = normalize(slot.perceive.watchPos - muzzlePos) + elif !!slot.perceive.targetEid && (now - slot.perceive.lastSeenAt) <= WTO_AI_TACTICS_MEMORY_TTL_SEC + wishWorldDir = normalize((slot.perceive.knownPos + float3(0.0, 1.4, 0.0)) - muzzlePos) + elif now < slot.perceive.alertUntil + wishWorldDir = float3(cos(slot.perceive.alertYawRad), 0.0, sin(slot.perceive.alertYawRad)) + + var wishYaw = 0.0 + var wishPitch = 0.0 + wto_world_to_hull_deg(wishWorldDir, hFwd, unit.unitTm[1], unit.unitTm[2], wishYaw, wishPitch) + wto_drive_turret_and_sample_barrel(unit, dt, now, wishYaw, wishPitch, slot, muzzlePos, liveBarrelDir) + if !engageValid || distToTgt > WTO_AI_FC_MAX_RANGE_M + slot.fire.settleHoldSec = 0.0 + slot.fire.lastAligned = false + return + let distXZ = sqrt(wto_xz_dist_sq(unit.pos, slot.perceive.knownPos)) + wto_fire_gate_try_shoot(world, unit, now, dt, distXZ, muzzlePos, aimPt, liveBarrelDir, wishWorldDir, slot, fireBudget) diff --git a/game-ai/ground/wto_ai_fire_gate_common.das b/game-ai/ground/wto_ai_fire_gate_common.das new file mode 100644 index 0000000..96e1356 --- /dev/null +++ b/game-ai/ground/wto_ai_fire_gate_common.das @@ -0,0 +1,199 @@ +// Single fire-permission gate for every ground weapon (main cannon, launcher, SPAA self-defense). +// Every shot must pass visual confirmation, weapon readiness, distance-tier speed limits, +// 800 m continuous LOS window, aim settle, frame pre-fire budget, muzzle hard-ray, drag-integrated +// ballistic trajectory sweep, predicted friendly corridor, and multi-barrel group validation. +options indenting = 2 +options no_global_heap = true +module wto_ai_fire_gate_common shared + +require ecs +require math +require DagorMath +require Mission +require Unit +require Weapon +require %game.utils.utils_common +require %appGame.wtoai.wto_ai_config_common +require %appGame.wtoai.wto_ai_math_common +require %appGame.wtoai.wto_ai_combat_types_common +require %appGame.wtoai.wto_ai_types_common +require %appGame.wtoai.wto_ai_sight_common + +[never_inline] +def private wto_gate_friendly_segment_clear(world : WtoWorldSnap const&; selfEid : EntityId; + army : int; p0, p1 : float3; tMid : float) : bool + let delta = p1 - p0 + let segLen = length(delta) + if segLen < 0.2 + return true + let dir = delta / segLen + for i in range(world.unitCount) + assume u = world.units[i] + if !u.isAlive || !u.isGround || u.army != army || u.eid == selfEid + continue + let predPos = u.pos + u.vel * tMid + float3(0.0, 1.3, 0.0) + let along = clamp(dot(predPos - p0, dir), 0.0, segLen) + let clearR = WTO_AI_FC_FRIENDLY_CORRIDOR_M + u.halfWid + if length_sq(predPos - (p0 + dir * along)) < clearR * clearR + return false + return true + +[never_inline] +def private wto_gate_check_ballistic_arc(world : WtoWorldSnap const&; + selfEid, targetEid : EntityId; army : int; + muzzlePos, liveDir, carrierVel, aimPt : float3; + speedMps, dragCx, massKg, caliberM : float; + var outBlock : int&) : int + let toAim = aimPt - muzzlePos + let targetDist = length(toAim) + if targetDist < 1.5 + return WTO_DENY_OK + let toAimDir = toAim / targetDist + let area = 0.25 * WTO_PI * caliberM * caliberM + let dragK = 0.5 * 1.225 * dragCx * area / max(0.1, massKg) + var cur = muzzlePos + var vel = liveDir * max(80.0, speedMps) + carrierVel + var t = 0.0 + var traveled = 0.0 + for step in range(64) + let spd = length(vel) + if spd < 20.0 + return WTO_DENY_AIM_ERR + let remain = max(0.5, targetDist - traveled) + let segWant = min(WTO_AI_FC_BALLISTIC_STEP_M, remain) + let dt = clamp(segWant / spd, 0.004, 0.14) + let accel = float3(0.0, -9.81, 0.0) - vel * (dragK * spd) + var next = cur + vel * dt + accel * (0.5 * dt * dt) + let nextProj = dot(next - muzzlePos, toAimDir) + let isLast = nextProj >= targetDist - 0.5 + if isLast && nextProj > targetDist && length_sq(next - cur) > 0.01 + let curProj = dot(cur - muzzlePos, toAimDir) + let frac = clamp((targetDist - curProj) / max(0.01, nextProj - curProj), 0.0, 1.0) + next = lerp(cur, next, frac) + let trimS = step == 0 ? 0.35 : 0.0 + let trimE = isLast ? 0.65 : 0.0 + let blk = wto_sight_hard_segment_blocked(world, selfEid, targetEid, cur, next, WTO_AI_FC_BALLISTIC_SWEEP_R_M, trimS, trimE) + if blk != WTO_BLOCK_NONE + outBlock = blk + return WTO_DENY_ARC_HARD + if !wto_gate_friendly_segment_clear(world, selfEid, army, cur, next, t + dt * 0.5) + return WTO_DENY_FRIENDLY + traveled += length(next - cur) + cur = next + vel = vel + accel * dt + t += dt + if isLast + let missTol = max(3.2, targetDist * 0.012) + if length_sq(cur - aimPt) > missTol * missTol + return WTO_DENY_AIM_ERR + return WTO_DENY_OK + return WTO_DENY_AIM_ERR + +[never_inline] +def private wto_gate_check_barrel(world : WtoWorldSnap const&; unit : Unit const?; + slot : WtoBotSlot const&; muzzlePos, liveDir, aimPt : float3; + var outBlock : int&) : int + let straightBlk = wto_sight_hard_segment_blocked(world, slot.eid, slot.perceive.targetEid, muzzlePos, aimPt, 0.05, 0.35, 0.65) + if straightBlk != WTO_BLOCK_NONE + outBlock = straightBlk + return WTO_DENY_MUZZLE_HARD + return wto_gate_check_ballistic_arc(world, slot.eid, slot.perceive.targetEid, slot.army, + muzzlePos, liveDir, unit.vel, aimPt, + slot.fire.activeSpeedMps, slot.fire.activeDragCx, slot.fire.activeMassKg, slot.fire.activeCaliberM, outBlock) + +[never_inline] +def private wto_gate_check_all_primary_guns(world : WtoWorldSnap const&; unit : Unit const?; + slot : WtoBotSlot const&; primaryMuzzle, primaryDir, aimPt : float3; + var outBlock : int&) : int + let primaryRes = wto_gate_check_barrel(world, unit, slot, primaryMuzzle, primaryDir, aimPt, outBlock) + if primaryRes != WTO_DENY_OK + return primaryRes + if unit == null || unit.weap == null + return WTO_DENY_OK + for tIdx, turret in iter_range(unit.weap.turret), unit.weap.turret + if tIdx == slot.fire.turretNo || int(turret.triggerGroupNo) != int(WeaponTriggerGroups.TRIGGER_GROUP_PRIMARY) + continue + let weapon = get_weapon(unit.weap.Weapons, int(turret.triggerNo), int(turret.weaponIndex)) + if weapon == null || weapon.isDummyGun + continue + var gunTm : float3x4 + weapon_calcShootTm(weapon, unit.unitTm, gunTm) + if length_sq(gunTm[0]) <= 0.25 + continue + let secRes = wto_gate_check_barrel(world, unit, slot, gunTm[3], normalize(gunTm[0]), aimPt, outBlock) + if secRes != WTO_DENY_OK + return secRes == WTO_DENY_FRIENDLY ? WTO_DENY_FRIENDLY : WTO_DENY_MULTI_GUN + return WTO_DENY_OK + +[never_inline] +def private wto_gate_speed_allowed(distXZ, measuredSpeed : float; spec : WtoVehicleSpec const&) : bool + if distXZ > WTO_AI_FC_MID_RANGE_M + return measuredSpeed <= WTO_AI_FC_STOP_SPEED_MAX_MPS + if distXZ > WTO_AI_FC_CLOSE_RANGE_M + let slowCap = min(spec.vMaxFwd * WTO_AI_FC_MID_SLOW_RATIO, WTO_AI_FC_MID_SLOW_MAX_MPS) + return measuredSpeed <= slowCap + return true + +[never_inline] +def private wto_gate_log_deny(now, distXZ, measuredSpeed : float; reason, blk : int; var slot : WtoBotSlot&) + assume fc = slot.fire + let changed = fc.lastDenyReason != reason || fc.lastDenyBlock != blk + fc.lastDenyReason = reason + fc.lastDenyBlock = blk + if WTO_AI_DIAG_TELEMETRY && reason >= WTO_DENY_SPEED && (changed || (now - fc.lastDenyLogAt) >= 4.0) + fc.lastDenyLogAt = now + print("WTO_AI|DENY|eid={uint(slot.eid)}|reason={reason}|block={blk}|dist={distXZ}|spd={measuredSpeed}\n") + +[never_inline] +def public wto_fire_gate_try_shoot(world : WtoWorldSnap const&; var unit : Unit?; + now, dt, distXZ : float; muzzlePos, aimPt, liveDir, wishDir : float3; + var slot : WtoBotSlot&; var fireBudget : int&) + assume fc = slot.fire + let aimErrDeg = acos(clamp(dot(liveDir, wishDir), -1.0, 1.0)) * WTO_RAD_TO_DEG + fc.lastAimErrDeg = aimErrDeg + let measuredSpeed = length(unit.vel) + let speedOk = wto_gate_speed_allowed(distXZ, measuredSpeed, slot.spec) + let allowErrDeg = clamp(atan2(WTO_AI_FC_CLOSE_HIT_RADIUS_M, max(distXZ, 6.0)) * WTO_RAD_TO_DEG, WTO_AI_FC_BASE_ALIGN_DEG, 2.4) + let settled = aimErrDeg <= allowErrDeg && fc.barrelOmegaDegSec <= WTO_AI_FC_BARREL_SETTLE_DEG_SEC && speedOk + fc.lastAligned = settled + fc.settleHoldSec = settled ? (fc.settleHoldSec + clamp(dt, 0.005, 0.10)) : max(0.0, fc.settleHoldSec - dt * 2.0) + + let minCadence = slot.spec.isAutocannonBelt ? 0.12 : 0.65 + if !fc.gunReady || (now - fc.lastShotAt) < minCadence + wto_gate_log_deny(now, distXZ, measuredSpeed, WTO_DENY_NOT_READY, WTO_BLOCK_NONE, slot) + return + if !speedOk + wto_gate_log_deny(now, distXZ, measuredSpeed, WTO_DENY_SPEED, WTO_BLOCK_NONE, slot) + return + if distXZ > WTO_AI_FC_LONG_RANGE_M && (slot.perceive.goodLosSec < WTO_AI_FC_LONG_WINDOW_SEC || slot.perceive.visiblePointCount < 2) + wto_gate_log_deny(now, distXZ, measuredSpeed, WTO_DENY_LONG_WINDOW, WTO_BLOCK_NONE, slot) + return + if aimErrDeg > allowErrDeg + wto_gate_log_deny(now, distXZ, measuredSpeed, WTO_DENY_AIM_ERR, WTO_BLOCK_NONE, slot) + return + let reqHold = distXZ <= WTO_AI_FC_CLOSE_RANGE_M ? WTO_AI_FC_CLOSE_SETTLE_HOLD_SEC : WTO_AI_FC_SETTLE_HOLD_SEC + if fc.settleHoldSec < reqHold + wto_gate_log_deny(now, distXZ, measuredSpeed, WTO_DENY_SETTLE, WTO_BLOCK_NONE, slot) + return + if fireBudget <= 0 + wto_gate_log_deny(now, distXZ, measuredSpeed, WTO_DENY_BUDGET, WTO_BLOCK_NONE, slot) + return + fireBudget-- + var blk = WTO_BLOCK_NONE + let gateRes = wto_gate_check_all_primary_guns(world, unit, slot, muzzlePos, liveDir, aimPt, blk) + if gateRes != WTO_DENY_OK + wto_gate_log_deny(now, distXZ, measuredSpeed, gateRes, blk, slot) + return + + unit_single_shot(unit, int(WeaponTriggerGroups.TRIGGER_GROUP_PRIMARY)) + fc.lastShotAt = now + fc.pendingShotConfirm = true + fc.pendingShotAt = now + fc.lastDenyReason = WTO_DENY_OK + fc.lastDenyBlock = WTO_BLOCK_NONE + fc.shotErrSumDeg += aimErrDeg + fc.maxShotErrDeg = max(fc.maxShotErrDeg, aimErrDeg) + if !slot.spec.isAutocannonBelt + fc.settleHoldSec = 0.0 + if WTO_AI_DIAG_TELEMETRY + print("WTO_AI|SHOT|eid={uint(slot.eid)}|tgt={uint(slot.perceive.targetEid)}|dist={distXZ}|spd={measuredSpeed}|v0={fc.activeSpeedMps}|err={aimErrDeg}\n") diff --git a/game-ai/ground/wto_ai_lanes_common.das b/game-ai/ground/wto_ai_lanes_common.das new file mode 100644 index 0000000..25e52cf --- /dev/null +++ b/game-ai/ground/wto_ai_lanes_common.das @@ -0,0 +1,234 @@ +// Team-level navmesh flank lanes (center / left / right), 40% rally staging & launch state, +// cap recall timers, and enemy air threat tracking. +options indenting = 2 +options no_global_heap = true +module wto_ai_lanes_common shared + +require ecs +require math +require pathfinder +require %appGame.wtoai.wto_ai_config_common +require %appGame.wtoai.wto_ai_math_common +require %appGame.wtoai.wto_ai_order_common +require %appGame.wtoai.wto_ai_types_common +require %appGame.wtoai.wto_ai_terrain_common +require %appGame.wtoai.wto_ai_world_common + +let public WTO_LANE_CENTER = 0 +let public WTO_LANE_LEFT = 1 +let public WTO_LANE_RIGHT = 2 + +[safe_when_uninitialized] +struct public WtoTeamLanes + built : bool[16] + centerLen : float[16] + centerMid : float3[16] + flankValid : bool[32] + flankRelay : float3[32] + rallyPos : float3[48] + rallyStartAt : float[48] + rallyReleased : bool[48] + capSafeSince : float[16] + recallActive : bool[16] + enemyAirActive : bool[3] + enemyAirSeenAt : float[3] + +[never_inline] +def public wto_lanes_cap_key(army, capIdx : int) : int + return clamp(army - 1, 0, 1) * 8 + clamp(capIdx, 0, 7) + +[never_inline] +def public wto_lanes_sub_key(army, capIdx, laneId : int) : int + return wto_lanes_cap_key(army, capIdx) * 3 + clamp(laneId, 0, 2) + +[never_inline] +def public wto_lanes_reset(var lanes : WtoTeamLanes&) + for i in range(16) + lanes.built[i] = false + lanes.centerLen[i] = 0.0 + lanes.centerMid[i] = float3(0.0, 0.0, 0.0) + lanes.capSafeSince[i] = -100.0 + lanes.recallActive[i] = false + for i in range(32) + lanes.flankValid[i] = false + lanes.flankRelay[i] = float3(0.0, 0.0, 0.0) + for i in range(48) + lanes.rallyPos[i] = float3(0.0, 0.0, 0.0) + lanes.rallyStartAt[i] = -100.0 + lanes.rallyReleased[i] = false + for a in range(3) + lanes.enemyAirActive[a] = false + lanes.enemyAirSeenAt[a] = -100.0 + +[never_inline] +def public wto_lanes_reset_rallies(var lanes : WtoTeamLanes&) + for i in range(48) + lanes.rallyStartAt[i] = -100.0 + lanes.rallyReleased[i] = false + +[never_inline] +def private wto_nav_project_pt(navIdx : int; var pt : float3&) : bool + if project_to_nearest_navmesh_point_no_obstacles_ex(navIdx, pt, float3(28.0, 64.0, 28.0)) + return true + return project_to_nearest_navmesh_point_no_obstacles_ex(navIdx, pt, float3(150.0, 120.0, 150.0)) + +[never_inline] +def private wto_measure_nav_path(navIdx : int; fromPt, toPt : float3; sampleFrac : float; + var outLen : float&; var outSample : float3&) : bool + var sPt = fromPt + var gPt = toPt + if !wto_nav_project_pt(navIdx, sPt) || !wto_nav_project_pt(navIdx, gPt) + return false + var ok = false + var totalLen = 0.0 + var sample = lerp(sPt, gPt, sampleFrac) + find_path_ex(navIdx, sPt, gPt, float3(32.0, 48.0, 32.0), 9.0, 2.5, null) <| $(path : array#) + let n = length(path) + if n < 2 + return + ok = true + for i in range(1, n) + totalLen += length(path[i] - path[i - 1]) + let targetD = totalLen * clamp(sampleFrac, 0.05, 0.95) + var acc = 0.0 + sample = path[n - 1] + for i in range(1, n) + let seg = length(path[i] - path[i - 1]) + if acc + seg >= targetD && seg > 0.01 + sample = lerp(path[i - 1], path[i], (targetD - acc) / seg) + break + acc += seg + outLen = totalLen + outSample = sample + return ok && totalLen > 1.0 + +[never_inline] +def public wto_lanes_ensure_cap(world : WtoWorldSnap const&; army, capIdx : int; + var lanes : WtoTeamLanes&) + let k = wto_lanes_cap_key(army, capIdx) + if lanes.built[k] || capIdx < 0 || capIdx >= world.capCount || !world.teamSpawnValid[army] + return + let navIdx = pathfinder_is_loaded_ex(1) ? 1 : (pathfinder_is_loaded_ex(0) ? 0 : -1) + if navIdx < 0 + return + lanes.built[k] = true + let spawnPt = world.teamSpawnCenter[army] + let capPt = world.caps[capIdx].center + var cLen = 0.0 + var cRally = lerp(spawnPt, capPt, WTO_AI_CMD_RALLY_PROG_FRAC) + if !wto_measure_nav_path(navIdx, spawnPt, capPt, WTO_AI_CMD_RALLY_PROG_FRAC, cLen, cRally) + cLen = max(80.0, sqrt(wto_xz_dist_sq(spawnPt, capPt))) + var cMid = lerp(spawnPt, capPt, 0.5) + var dummyLen = 0.0 + let _midOk = wto_measure_nav_path(navIdx, spawnPt, capPt, 0.5, dummyLen, cMid) + lanes.centerLen[k] = cLen + lanes.centerMid[k] = cMid + lanes.rallyPos[k * 3 + WTO_LANE_CENTER] = cRally + + let toCap = wto_xz_normalize(capPt - spawnPt, float3(1.0, 0.0, 0.0)) + let lat = float3(-toCap.z, 0.0, toCap.x) + let straightD = sqrt(wto_xz_dist_sq(spawnPt, capPt)) + let swing = clamp(straightD * 0.34, 80.0, 260.0) + for side in range(2) + let sign = side == 0 ? 1.0 : -1.0 + var relay = wto_clamp_battle_xz(lerp(spawnPt, capPt, 0.5) + lat * (sign * swing), world.battleCenter, world.battleRadius, 45.0) + let fKey = k * 2 + side + lanes.flankValid[fKey] = false + if !wto_nav_project_pt(navIdx, relay) || !wto_terrain_point_valid(army, relay) + continue + if sqrt(wto_xz_dist_sq(relay, cMid)) < WTO_AI_CMD_FLANK_MIN_SEP_M + continue + var len1 = 0.0 + var len2 = 0.0 + var rPt = lerp(spawnPt, relay, 0.8) + var dummy = relay + if !wto_measure_nav_path(navIdx, spawnPt, relay, 0.8, len1, rPt) + continue + if !wto_measure_nav_path(navIdx, relay, capPt, 0.5, len2, dummy) + continue + if (len1 + len2) > cLen * WTO_AI_CMD_FLANK_MAX_RATIO + continue + lanes.flankValid[fKey] = true + lanes.flankRelay[fKey] = relay + lanes.rallyPos[k * 3 + side + 1] = rPt + +[never_inline] +def public wto_lanes_update_team_intel(world : WtoWorldSnap const&; now : float; + var lanes : WtoTeamLanes&) + let airMaxSq = wto_sq(3200.0) + for a in range(1, 3) + var sawAir = false + for i in range(world.unitCount) + assume u = world.units[i] + if u.isAlive && u.isAir && u.army != a && wto_xz_dist_sq(u.pos, world.battleCenter) <= airMaxSq + sawAir = true + break + if sawAir + lanes.enemyAirSeenAt[a] = now + lanes.enemyAirActive[a] = sawAir || (now - lanes.enemyAirSeenAt[a]) <= 12.0 + +[never_inline] +def public wto_lanes_update_recall(world : WtoWorldSnap const&; army : int; now : float; + var lanes : WtoTeamLanes&; var outEnemiesInCap : int[8]&) + for c in range(WTO_MAX_CAPS) + outEnemiesInCap[c] = 0 + for c in range(world.capCount) + let k = wto_lanes_cap_key(army, c) + if world.caps[c].ownerArmy != army + lanes.recallActive[k] = false + lanes.capSafeSince[k] = now + continue + let radSq = wto_sq(world.caps[c].radius + 35.0) + var enemies = 0 + for i in range(world.unitCount) + assume u = world.units[i] + if u.isAlive && u.isGround && u.army != army && wto_xz_dist_sq(u.pos, world.caps[c].center) <= radSq + enemies++ + outEnemiesInCap[c] = enemies + if world.caps[c].contested || enemies > 0 + if !lanes.recallActive[k] && WTO_AI_DIAG_TELEMETRY + print("WTO_AI|RECALL|t={now}|army={army}|cap={c}|enemies={enemies}|contested={world.caps[c].contested}\n") + lanes.recallActive[k] = true + lanes.capSafeSince[k] = now + elif lanes.recallActive[k] && (now - lanes.capSafeSince[k]) >= WTO_AI_CMD_RECALL_SAFE_SEC + lanes.recallActive[k] = false + +[never_inline] +def public wto_lanes_update_rallies(world : WtoWorldSnap const&; army : int; now : float; + var lanes : WtoTeamLanes&; var bots : WtoBotSlot[64]&) + let rallyRadSq = wto_sq(WTO_AI_CMD_RALLY_RADIUS_M) + for c in range(world.capCount) + wto_lanes_ensure_cap(world, army, c, lanes) + for lane in range(3) + let sk = wto_lanes_sub_key(army, c, lane) + if lanes.rallyReleased[sk] + continue + let rPos = lanes.rallyPos[sk] + if length_sq(rPos) < 1.0 + lanes.rallyReleased[sk] = true + continue + let rDistToCapSq = wto_xz_dist_sq(rPos, world.caps[c].center) + var assigned = 0 + var arrived = 0 + for i in range(WTO_MAX_BOTS) + assume b = bots[i] + if !b.used || b.army != army || !b.order.valid || b.order.capIndex != c || b.order.laneId != lane || !wto_order_is_offensive(b.order.role) + continue + let uIdx = wto_world_find_unit(world, b.eid) + if uIdx < 0 + continue + assigned++ + let pos = world.units[uIdx].pos + if wto_xz_dist_sq(pos, rPos) <= rallyRadSq || wto_xz_dist_sq(pos, world.caps[c].center) < rDistToCapSq + arrived++ + if assigned <= 1 + lanes.rallyReleased[sk] = true + continue + if arrived > 0 && lanes.rallyStartAt[sk] < 0.0 + lanes.rallyStartAt[sk] = now + let enough = float(arrived) >= float(assigned) * WTO_AI_CMD_RALLY_MIN_FRAC + let timedOut = lanes.rallyStartAt[sk] >= 0.0 && (now - lanes.rallyStartAt[sk]) >= WTO_AI_CMD_RALLY_WAIT_SEC + if enough || timedOut + lanes.rallyReleased[sk] = true + if WTO_AI_DIAG_TELEMETRY + print("WTO_AI|RALLY_GO|t={now}|army={army}|cap={c}|lane={lane}|arrived={arrived}/{assigned}|timeout={timedOut}\n") diff --git a/game-ai/ground/wto_ai_math_common.das b/game-ai/ground/wto_ai_math_common.das new file mode 100644 index 0000000..b531f3a --- /dev/null +++ b/game-ai/ground/wto_ai_math_common.das @@ -0,0 +1,57 @@ +// Pure zero-heap scalar, angle, and XZ plane math helpers for WTOffline's ground AI modules. +options indenting = 2 +options no_global_heap = true +module wto_ai_math_common shared + +require math + +let public WTO_PI = 3.14159265 +let public WTO_RAD_TO_DEG = 57.29577951 +let public WTO_DEG_TO_RAD = 0.01745329 + +def public wto_sq(x : float) : float + return x * x + +def public wto_is_finite(x : float) : bool + return x == x && x > -1.0e20 && x < 1.0e20 + +def public wto_is_finite3(v : float3) : bool + return wto_is_finite(v.x) && wto_is_finite(v.y) && wto_is_finite(v.z) + +def public wto_xz_dist_sq(a, b : float3) : float + return wto_sq(a.x - b.x) + wto_sq(a.z - b.z) + +def public wto_xz_len(v : float3) : float + return sqrt(v.x * v.x + v.z * v.z) + +def public wto_xz_normalize(v, fallback : float3) : float3 + let l = sqrt(v.x * v.x + v.z * v.z) + return l > 1.0e-4 ? float3(v.x / l, 0.0, v.z / l) : fallback + +def public wto_wrap_rad(angle : float) : float + var a = angle + while a > WTO_PI + a -= 2.0 * WTO_PI + while a < -WTO_PI + a += 2.0 * WTO_PI + return a + +def public wto_wrap_deg(angle : float) : float + var a = angle + while a > 180.0 + a -= 360.0 + while a < -180.0 + a += 360.0 + return a + +def public wto_clamp_battle_xz(pos, center : float3; radius, margin : float) : float3 + if radius <= margin + 10.0 + return pos + let maxR = radius - margin + let dx = pos.x - center.x + let dz = pos.z - center.z + let dSq = dx * dx + dz * dz + if dSq <= maxR * maxR + return pos + let s = maxR / max(1.0, sqrt(dSq)) + return float3(center.x + dx * s, pos.y, center.z + dz * s) diff --git a/game-ai/ground/wto_ai_nav_common.das b/game-ai/ground/wto_ai_nav_common.das new file mode 100644 index 0000000..f067fe1 --- /dev/null +++ b/game-ai/ground/wto_ai_nav_common.das @@ -0,0 +1,258 @@ +// Bidirectional non-holonomic local planner: +// - Directed 7-arc reverse trajectory planner for ridge withdrawals, tactical peeks, cliff escapes, +// and jam unsticking (enabling sustained 30-50m reverse transfers); +// - Stationary combat hull discipline (zero hull-pivot whip on turreted tanks during ENGAGE_HALT); +// - Forward 9-arc DWA rollout with cliff rejection, TTC ally overtaking, and jam/crowd penalties. +options indenting = 2 +options no_global_heap = true +module wto_ai_nav_common shared + +require ecs +require math +require %appGame.wtoai.wto_ai_config_common +require %appGame.wtoai.wto_ai_math_common +require %appGame.wtoai.wto_ai_types_common +require %appGame.wtoai.wto_ai_terrain_common +require %appGame.wtoai.wto_ai_world_common +require %appGame.wtoai.wto_ai_crowd_common +require %appGame.wtoai.wto_ai_route_common + +[never_inline] +def private wto_wreck_or_ally_clearance(world : WtoWorldSnap const&; selfEid : EntityId; + pt : float3; tSec, selfRad : float) : float + var pen = 0.0 + for w in range(world.wreckCount) + let r = selfRad + max(world.wrecks[w].halfLen, world.wrecks[w].halfWid) + WTO_AI_TERRAIN_MARGIN_M + let dSq = wto_xz_dist_sq(pt, world.wrecks[w].pos) + if dSq < r * r + return 1.0e6 + elif dSq < wto_sq(r + 3.5) + pen += 18.0 + for i in range(world.unitCount) + assume u = world.units[i] + if !u.isAlive || !u.isGround || u.eid == selfEid + continue + let predPos = u.pos + u.vel * min(tSec, 1.6) + let r = selfRad + max(u.halfLen, u.halfWid) + WTO_AI_TERRAIN_MARGIN_M + let dSq = wto_xz_dist_sq(pt, predPos) + if dSq < r * r + return 1.0e6 + elif dSq < wto_sq(r + 5.0) + pen += 22.0 + return pen + +// Evaluate 7 curved rear trajectories (`16m` behind chassis) toward `reverseGoal`. +[never_inline] +def private wto_eval_reverse_arcs(world : WtoWorldSnap const&; now : float; + myPos, hullFwd, reverseGoal : float3; + var slot : WtoBotSlot&; var outRearDir : float3&) : bool + let rearBase = -wto_xz_normalize(hullFwd, float3(1.0, 0.0, 0.0)) + let baseYaw = atan2(rearBase.z, rearBase.x) + let wishDir = wto_xz_normalize(reverseGoal - myPos, rearBase) + let selfRad = max(slot.spec.halfWid, 1.65) + var bestScore = -1.0e9 + var found = false + outRearDir = rearBase + for a in range(7) + let steerFrac = float(a - 3) / 3.0 + let arcCurv = steerFrac * 0.042 + var cur = myPos + var blocked = false + var arcPen = abs(steerFrac) * 2.5 + for s in range(1, 5) + let dist = float(s) * 3.8 + let yaw = baseYaw + arcCurv * dist + let stepDir = float3(cos(yaw), 0.0, sin(yaw)) + let nx = cur.x + stepDir.x * 3.8 + let nz = cur.z + stepDir.z * 3.8 + var gy = cur.y + if !wto_terrain_drivable_y(cur, nx, nz, gy) + blocked = true + break + if wto_terrain_hard_ray(cur + float3(0.0, 1.25, 0.0), stepDir, 4.2) < 3.7 + blocked = true + break + let nxt = float3(nx, gy, nz) + let dynPen = wto_wreck_or_ally_clearance(world, slot.eid, nxt, dist / max(1.8, slot.spec.vMaxRev), selfRad) + if dynPen >= 1.0e5 + blocked = true + break + arcPen += dynPen * 0.25 + wto_crowd_point_penalty(world, slot.army, slot.eid, nxt) * 0.2 + cur = nxt + if blocked + continue + let firstYaw = baseYaw + arcCurv * 5.5 + let candDir = float3(cos(firstYaw), 0.0, sin(firstYaw)) + if wto_terrain_has_cliff_ahead(myPos, candDir, 15.0) + continue + let score = dot(candDir, wishDir) * 35.0 - arcPen - wto_world_jam_penalty(world, cur, now) * 0.4 + if score > bestScore + bestScore = score + outRearDir = candDir + found = true + return found + +// Evaluate 9 curved forward trajectories (`22m` ahead) with hard cliff rejection and traffic cost. +[never_inline] +def private wto_eval_forward_arcs(world : WtoWorldSnap const&; now : float; + myPos, hullFwd, wishDir : float3; speedCmd : float; + var slot : WtoBotSlot&; var outFwdDir : float3&) : bool + let fwdBase = wto_xz_normalize(hullFwd, float3(1.0, 0.0, 0.0)) + let baseYaw = atan2(fwdBase.z, fwdBase.x) + let selfRad = max(slot.spec.halfWid, 1.65) + var bestScore = -1.0e9 + var found = false + outFwdDir = wishDir + for a in range(9) + let steerFrac = float(a - 4) / 4.0 + let arcCurv = steerFrac * 0.038 + let firstYaw = baseYaw + arcCurv * 6.5 + let candDir = float3(cos(firstYaw), 0.0, sin(firstYaw)) + if wto_terrain_has_cliff_ahead(myPos, candDir, WTO_AI_TERRAIN_CREST_LOOKAHEAD_M) + continue + var cur = myPos + var blocked = false + var arcPen = abs(steerFrac) * 2.2 + for s in range(1, 6) + let dist = float(s) * 4.2 + let yaw = baseYaw + arcCurv * dist + let stepDir = float3(cos(yaw), 0.0, sin(yaw)) + let nx = cur.x + stepDir.x * 4.2 + let nz = cur.z + stepDir.z * 4.2 + var gy = cur.y + if !wto_terrain_drivable_y(cur, nx, nz, gy) + blocked = true + break + if wto_terrain_hard_ray(cur + float3(0.0, 1.3, 0.0), stepDir, 4.6) < 4.1 + blocked = true + break + let nxt = float3(nx, gy, nz) + let dynPen = wto_wreck_or_ally_clearance(world, slot.eid, nxt, dist / max(2.5, speedCmd), selfRad) + if dynPen >= 1.0e5 + blocked = true + break + arcPen += dynPen * 0.3 + wto_crowd_point_penalty(world, slot.army, slot.eid, nxt) * 0.35 + cur = nxt + if blocked + continue + let align = dot(candDir, wishDir) * 40.0 + dot(candDir, slot.nav.steerDir) * 4.5 + let score = align - arcPen - wto_world_jam_penalty(world, cur, now) + if score > bestScore + bestScore = score + outFwdDir = candDir + found = true + return found + +[never_inline] +def private wto_set_drive_cmd(var cmd : WtoDriveCmd&; mode : int; targetPos, desiredDir : float3; + speedMps, frontClr, rearClr : float) + cmd.valid = true + cmd.mode = mode + cmd.targetPos = targetPos + cmd.desiredDir = desiredDir + cmd.speedMps = speedMps + cmd.frontClearM = frontClr + cmd.rearClearM = rearClr + +[never_inline] +def private wto_handle_stationary_engage(myPos, hullFwd : float3; var slot : WtoBotSlot&) + // Casemate / limited-traverse TDs rotate hull ONLY while target is outside 78% of gun arc. + if slot.spec.isLimitedTraverse && !!slot.perceive.targetEid + let toTgt = wto_xz_normalize(slot.perceive.knownPos - myPos, hullFwd) + let angDeg = acos(clamp(dot(toTgt, hullFwd), -1.0, 1.0)) * WTO_RAD_TO_DEG + if angDeg > slot.spec.yawLimitDeg * 0.78 + wto_set_drive_cmd(slot.driveCmd, WTO_DRIVE_PIVOT, myPos + toTgt * 18.0, toTgt, 2.0, slot.nav.frontClearM, slot.nav.rearClearM) + return + // Turreted tanks (and aligned TDs) hold chassis completely still so barrel settles cleanly! + wto_set_drive_cmd(slot.driveCmd, WTO_DRIVE_HALT, myPos, hullFwd, 0.0, slot.nav.frontClearM, slot.nav.rearClearM) + +[never_inline] +def private wto_check_stuck_watchdog(var world : WtoWorldSnap&; now : float; + myPos, wishDir : float3; var slot : WtoBotSlot&) + assume nav = slot.nav + let movingIntent = slot.tactics.desiredSpeedMps > 1.2 && now >= nav.reverseUntil + if !movingIntent + nav.stuckOrigin = myPos + nav.stuckCheckAt = now + WTO_AI_NAV_STUCK_WINDOW_SEC + return + if nav.stuckCheckAt < -50.0 + nav.stuckOrigin = myPos + nav.stuckCheckAt = now + WTO_AI_NAV_STUCK_WINDOW_SEC + return + if now < nav.stuckCheckAt + return + let moved = sqrt(wto_xz_dist_sq(myPos, nav.stuckOrigin)) + nav.stuckOrigin = myPos + nav.stuckCheckAt = now + WTO_AI_NAV_STUCK_WINDOW_SEC + if moved >= WTO_AI_NAV_STUCK_MIN_MOVE_M + return + wto_world_record_jam(world, myPos + wishDir * 6.0, now) + wto_route_request_detour(world, now, myPos, wishDir, slot) + let backIdx = clamp(slot.route.corridorIdx - 2, 0, max(0, slot.route.corridorLen - 1)) + nav.reverseAnchor = slot.route.corridorLen > 0 ? slot.route.corridor[backIdx] : (myPos - wishDir * 22.0) + nav.reverseUntil = now + max(WTO_AI_NAV_UNSTICK_REV_SEC, 3.6) + nav.reverseCount++ + +[never_inline] +def private wto_try_reverse_drive(world : WtoWorldSnap const&; now : float; + myPos, hullFwd : float3; var slot : WtoBotSlot&) : bool + let stMode = slot.tactics.state + let wantTacRev = stMode == WTO_STATE_RIDGE_WITHDRAW || (stMode == WTO_STATE_RETREAT_COVER && slot.tactics.retreatReverse) + if !wantTacRev && now >= slot.nav.reverseUntil + return false + let revGoal = wantTacRev ? slot.tactics.moveGoal : slot.nav.reverseAnchor + var rearDir = -hullFwd + if slot.nav.rearClearM > 2.4 && wto_eval_reverse_arcs(world, now, myPos, hullFwd, revGoal, slot, rearDir) + slot.nav.steerDir = rearDir + wto_set_drive_cmd(slot.driveCmd, WTO_DRIVE_REVERSE, myPos + rearDir * 18.0, rearDir, max(2.0, slot.spec.vMaxRev), slot.nav.frontClearM, slot.nav.rearClearM) + return true + slot.nav.reverseUntil = -100.0 + return false + +[never_inline] +def public wto_nav_update(var world : WtoWorldSnap&; now : float; + myPos, rawHullFwd : float3; var slot : WtoBotSlot&) + if !WTO_AI_LAYER_NAVIGATION + slot.driveCmd.valid = false + return + let hullFwd = wto_xz_normalize(rawHullFwd, float3(1.0, 0.0, 0.0)) + let probeBase = myPos + float3(0.0, 1.25, 0.0) + slot.nav.frontClearM = wto_terrain_hard_ray(probeBase, hullFwd, 24.0) + slot.nav.rearClearM = wto_terrain_hard_ray(probeBase, -hullFwd, 18.0) + slot.nav.cliffAhead = wto_terrain_has_cliff_ahead(myPos, hullFwd, WTO_AI_TERRAIN_CREST_LOOKAHEAD_M) + + if slot.tactics.state == WTO_STATE_HULL_ANGLE + slot.nav.stuckCheckAt = now + WTO_AI_NAV_STUCK_WINDOW_SEC + let wishAngle = wto_xz_normalize(slot.tactics.hullAngleDir, hullFwd) + let angErr = acos(clamp(dot(wishAngle, hullFwd), -1.0, 1.0)) * WTO_RAD_TO_DEG + if angErr > 8.0 + wto_set_drive_cmd(slot.driveCmd, WTO_DRIVE_PIVOT, myPos + wishAngle * 14.0, wishAngle, 0.0, slot.nav.frontClearM, slot.nav.rearClearM) + else + wto_set_drive_cmd(slot.driveCmd, WTO_DRIVE_HALT, myPos, hullFwd, 0.0, slot.nav.frontClearM, slot.nav.rearClearM) + return + if slot.tactics.state == WTO_STATE_SHORT_HALT || slot.tactics.state == WTO_STATE_COVER_RELOAD || slot.tactics.desiredSpeedMps <= 0.05 + slot.nav.stuckCheckAt = now + WTO_AI_NAV_STUCK_WINDOW_SEC + wto_handle_stationary_engage(myPos, hullFwd, slot) + return + if wto_try_reverse_drive(world, now, myPos, hullFwd, slot) + return + + let wp = wto_route_select_waypoint(world, now, myPos, slot.tactics.moveGoal, slot) + let wishDir = wto_xz_normalize(wp - myPos, hullFwd) + wto_check_stuck_watchdog(world, now, myPos, wishDir, slot) + + var bestDir = wishDir + if !wto_eval_forward_arcs(world, now, myPos, hullFwd, wishDir, slot.tactics.desiredSpeedMps, slot, bestDir) + if slot.nav.rearClearM > 3.2 + slot.nav.reverseAnchor = myPos - hullFwd * 26.0 + slot.nav.reverseUntil = now + 4.8 + slot.nav.reverseCount++ + wto_set_drive_cmd(slot.driveCmd, WTO_DRIVE_REVERSE, slot.nav.reverseAnchor, -hullFwd, max(2.0, slot.spec.vMaxRev), slot.nav.frontClearM, slot.nav.rearClearM) + return + bestDir = wishDir + + slot.nav.steerDir = bestDir + let turnDeg = acos(clamp(dot(wishDir, hullFwd), -1.0, 1.0)) * WTO_RAD_TO_DEG + let needPivot = turnDeg >= WTO_AI_NAV_PIVOT_ANGLE_DEG || (slot.nav.frontClearM < slot.spec.halfLen + 1.8 && turnDeg > 32.0) + let cmdDir = needPivot ? wishDir : bestDir + wto_set_drive_cmd(slot.driveCmd, needPivot ? WTO_DRIVE_PIVOT : WTO_DRIVE_CRUISE, myPos + cmdDir * 22.0, cmdDir, slot.tactics.desiredSpeedMps, slot.nav.frontClearM, slot.nav.rearClearM) diff --git a/game-ai/ground/wto_ai_order_common.das b/game-ai/ground/wto_ai_order_common.das new file mode 100644 index 0000000..bc4a6fa --- /dev/null +++ b/game-ai/ground/wto_ai_order_common.das @@ -0,0 +1,57 @@ +// Task order contract between the team commander and per-bot hull behavior. +// Every per-bot decision reads `WtoTaskOrder` rather than guessing team intent. +options indenting = 2 +options no_global_heap = true +module wto_ai_order_common shared + +let public WTO_MODE_UNKNOWN = 0 +let public WTO_MODE_BTTL = 1 +let public WTO_MODE_CONQ = 2 +let public WTO_MODE_DOM = 3 + +let public WTO_CMD_ASSAULT = 0 +let public WTO_CMD_FLANK = 1 +let public WTO_CMD_OVERWATCH = 2 +let public WTO_CMD_DEFEND = 3 +let public WTO_CMD_RESERVE = 4 +let public WTO_CMD_SPAA = 5 + +let public WTO_URGENCY_LOW = 0 +let public WTO_URGENCY_MED = 1 +let public WTO_URGENCY_HIGH = 2 + +[safe_when_uninitialized] +struct public WtoTaskOrder + valid : bool = false + role : int = 0 + capIndex : int = -1 + laneId : int = 0 + goalPos : float3 = float3(0.0, 0.0, 0.0) + routeRelayValid : bool = false + routeRelayPos : float3 = float3(0.0, 0.0, 0.0) + rallyHold : bool = false + urgency : int = 1 + maxStopRangeM : float = 800.0 + assignedAt : float = -100.0 + expiresAt : float = -100.0 + cautious : bool = false + overwatchOutside : bool = false + spaaAnchorValid : bool = false + spaaAnchorPos : float3 = float3(0.0, 0.0, 0.0) + spaaRelocateAt : float = -100.0 + +[never_inline] +def public wto_order_is_offensive(role : int) : bool + return role == WTO_CMD_ASSAULT || role == WTO_CMD_FLANK + +[never_inline] +def public wto_order_max_stop_range(role, urgency : int; maxEngageRangeM : float) : float + if role == WTO_CMD_ASSAULT || role == WTO_CMD_FLANK + return 300.0 + if role == WTO_CMD_OVERWATCH + return maxEngageRangeM + if role == WTO_CMD_DEFEND + return urgency == WTO_URGENCY_HIGH ? 300.0 : maxEngageRangeM + if role == WTO_CMD_RESERVE + return 800.0 + return 300.0 diff --git a/game-ai/ground/wto_ai_perceive_common.das b/game-ai/ground/wto_ai_perceive_common.das new file mode 100644 index 0000000..afb560b --- /dev/null +++ b/game-ai/ground/wto_ai_perceive_common.das @@ -0,0 +1,233 @@ +// Exposure-integrated visual perception with strict foliage/smoke/hard occlusion, +// directional-only audio/hit/radio clues, and frozen last-seen memory. +options indenting = 2 +options no_global_heap = true +module wto_ai_perceive_common shared + +require ecs +require math +require %appGame.wtoai.wto_ai_config_common +require %appGame.wtoai.wto_ai_math_common +require %appGame.wtoai.wto_ai_combat_types_common +require %appGame.wtoai.wto_ai_types_common +require %appGame.wtoai.wto_ai_terrain_common +require %appGame.wtoai.wto_ai_sight_common +require %appGame.wtoai.wto_ai_estimate_common +require %appGame.wtoai.wto_ai_world_common + +[never_inline] +def private wto_exp_find_or_alloc(var p : WtoPerceiveState&; eid : EntityId) : int + var freeIdx = -1 + var minIdx = 0 + var minScore = 2.0 + for i in range(WTO_MAX_EXPOSURE_TRACKS) + if p.expEids[i] == eid + return i + if !p.expEids[i] && freeIdx < 0 + freeIdx = i + if p.expScore[i] < minScore + minScore = p.expScore[i] + minIdx = i + let dst = freeIdx >= 0 ? freeIdx : minIdx + p.expEids[dst] = eid + p.expScore[dst] = 0.0 + p.expGoodLosSec[dst] = 0.0 + return dst + +[never_inline] +def private wto_exp_decay_all(world : WtoWorldSnap const&; dt : float; var p : WtoPerceiveState&) + let decay = WTO_AI_PERC_DECAY_PER_SEC * dt + for i in range(WTO_MAX_EXPOSURE_TRACKS) + if !p.expEids[i] + continue + let uIdx = wto_world_find_unit(world, p.expEids[i]) + if uIdx < 0 || !world.units[uIdx].isAlive + p.expEids[i] = INVALID_ENTITY_ID + p.expScore[i] = 0.0 + p.expGoodLosSec[i] = 0.0 + continue + p.expScore[i] = max(0.0, p.expScore[i] - decay) + if p.expScore[i] <= 0.001 + p.expEids[i] = INVALID_ENTITY_ID + p.expScore[i] = 0.0 + p.expGoodLosSec[i] = 0.0 + +[never_inline] +def private wto_spot_fill_time(dist : float; cosAngle : float; isShooting : bool; visCount : int) : float + let cosFront = cos(WTO_AI_PERC_FRONT_CONE_DEG * WTO_DEG_TO_RAD) + var t = WTO_AI_PERC_FAR_SPOT_SEC + if dist < WTO_AI_PERC_NEAR_SPOT_M || (isShooting && dist < WTO_AI_PERC_FIRING_SPOT_M) + t = WTO_AI_PERC_FAST_SPOT_SEC + elif dist <= 550.0 && cosAngle >= cosFront + t = WTO_AI_PERC_NORMAL_SPOT_SEC + if visCount >= 3 + t *= 0.85 + return max(0.08, t) + +[never_inline] +def private wto_update_audio_and_radio_alerts(world : WtoWorldSnap const&; now : float; + myPos : float3; var slot : WtoBotSlot&) + assume p = slot.perceive + // Priority A: Recent hit direction captured at impact time (never reveals hidden true position). + if (now - p.lastDamagedAt) <= 4.0 && !!p.lastOffenderEid + p.alertYawRad = p.lastHitYawRad + p.alertUntil = now + 4.5 + return + // Priority B: Close enemy engine / cannon sound direction clue. + var bestAudioDist = 1.0e9 + for i in range(world.unitCount) + assume u = world.units[i] + if !u.isAlive || !u.isGround || u.army == slot.army + continue + let d = sqrt(wto_xz_dist_sq(myPos, u.pos)) + let engRange = WTO_AI_TACTICS_ENGINE_AUDIO_M * (0.35 + 0.65 * u.engineRpm) + let heard = d <= engRange || (u.isShooting && d <= WTO_AI_TACTICS_SHOT_AUDIO_M) + if heard && d < bestAudioDist + bestAudioDist = d + let dir = u.pos - myPos + p.alertYawRad = atan2(dir.z, dir.x) + p.alertUntil = now + 3.2 + if bestAudioDist < 1.0e8 + return + // Priority C: Friendly radio spot direction clue (alert only, never enables firing). + let radioSq = wto_sq(WTO_AI_TACTICS_RADIO_SHARE_M) + for r in range(WTO_MAX_RADIO) + assume sp = world.radioSpots[r] + if sp.untilAt > now && sp.army == slot.army && wto_xz_dist_sq(myPos, sp.pos) <= radioSq + let dir = sp.pos - myPos + p.alertYawRad = atan2(dir.z, dir.x) + p.alertUntil = now + 2.8 + return + +[never_inline] +def private wto_scan_visual_exposure(world : WtoWorldSnap const&; now, dt : float; + myEye, lookDir : float3; var slot : WtoBotSlot&; + var outBestIdx, outVisCount : int&; + var outGoodLosSec : float&; var outAimPt : float3&) + assume p = slot.perceive + let cosHalfFov = cos(0.5 * WTO_AI_TACTICS_VISION_FOV_DEG * WTO_DEG_TO_RAD) + let isSpaa = slot.spec.role == WTO_ROLE_SPAA + let decay = WTO_AI_PERC_DECAY_PER_SEC * dt + var bestScore = 1.0e9 + outBestIdx = -1 + outVisCount = 0 + outGoodLosSec = 0.0 + for i in range(world.unitCount) + assume u = world.units[i] + if !u.isAlive || u.army == slot.army || (u.isAir && !isSpaa) + continue + let delta = u.pos - myEye + let dist = length(delta) + let maxRange = u.isAir ? 2600.0 : WTO_AI_TACTICS_VISION_RANGE_M + if dist > maxRange || dist < 1.0 + continue + let dirXZ = wto_xz_normalize(delta, lookDir) + let cosAng = dot(dirXZ, lookDir) + let inFov = cosAng >= cosHalfFov || (dist <= WTO_AI_PERC_PERIPH_CLOSE_M && cosAng >= 0.0) + if !inFov && !u.isAir + continue + let maxSamples = dist > WTO_AI_FC_LONG_RANGE_M ? 2 : 4 + var samplePt = u.pos + float3(0.0, 1.3, 0.0) + let vis = wto_sight_check_target_samples(world, slot.eid, myEye, u, maxSamples, samplePt) + if vis <= 0 + for k in range(WTO_MAX_EXPOSURE_TRACKS) + if p.expEids[k] == u.eid + p.expGoodLosSec[k] = 0.0 + continue + let tIdx = wto_exp_find_or_alloc(p, u.eid) + let fillSec = wto_spot_fill_time(dist, cosAng, u.isShooting, vis) + p.expScore[tIdx] = clamp(p.expScore[tIdx] + decay + dt / fillSec, 0.0, 1.0) + p.expGoodLosSec[tIdx] = vis >= 2 ? (p.expGoodLosSec[tIdx] + dt) : 0.0 + if p.expScore[tIdx] < 0.999 + continue + var score = dist - (u.isAir && isSpaa ? 900.0 : 0.0) + if u.eid == p.lockedEid && now < p.lockedUntil + score -= 320.0 + elif u.eid == p.lastOffenderEid && (now - p.lastDamagedAt) <= 5.0 + score -= 90.0 + elif u.isShooting && dist < 220.0 + score -= 35.0 + if dist < 45.0 + score -= 180.0 + if score < bestScore + bestScore = score + outBestIdx = i + outVisCount = vis + outGoodLosSec = p.expGoodLosSec[tIdx] + outAimPt = samplePt + +[never_inline] +def public wto_perceive_update(var world : WtoWorldSnap&; now, dt : float; + myPos, hullFwd : float3; var slot : WtoBotSlot&) + assume p = slot.perceive + let myEye = myPos + float3(0.0, 2.15, 0.0) + var lookDir = wto_xz_normalize(hullFwd, float3(1.0, 0.0, 0.0)) + if slot.fire.servoInit + let worldYaw = atan2(hullFwd.z, hullFwd.x) - slot.fire.curYawDeg * WTO_DEG_TO_RAD + lookDir = float3(cos(worldYaw), 0.0, sin(worldYaw)) + + wto_exp_decay_all(world, dt, p) + var bestIdx = -1 + var visCount = 0 + var goodLosSec = 0.0 + var aimPt = myPos + wto_scan_visual_exposure(world, now, dt, myEye, lookDir, slot, bestIdx, visCount, goodLosSec, aimPt) + if bestIdx >= 0 + assume tgt = world.units[bestIdx] + p.targetEid = tgt.eid + p.targetIsAir = tgt.isAir + p.hasClearLos = true + p.visiblePointCount = visCount + p.goodLosSec = goodLosSec + p.visibleAimPt = aimPt + p.knownPos = tgt.pos + p.lastSeenAt = now + p.wasEngaging = !tgt.isAir + p.watchUntil = -100.0 + wto_est_push_visual_sample(now, tgt.eid, tgt.pos, p) + if p.lockedEid != tgt.eid || now >= p.lockedUntil - 0.5 + p.lockedEid = tgt.eid + p.lockedUntil = now + WTO_AI_TACTICS_STICKY_SEC + if !tgt.isAir && (now - p.lastRadioSentAt) >= 2.5 + p.lastRadioSentAt = now + wto_world_broadcast_radio(world, slot.army, tgt.eid, tgt.pos, now) + return + + // Lost visual confirmation: immediately revoke LOS, freeze exit point for 2-5 s watch, zero velocity. + p.hasClearLos = false + p.visiblePointCount = 0 + p.goodLosSec = 0.0 + wto_est_on_los_lost(now, slot.eid, p) + let tgtIdx = wto_world_find_unit(world, p.targetEid) + if !!p.targetEid && (tgtIdx < 0 || !world.units[tgtIdx].isAlive || (now - p.lastSeenAt) > WTO_AI_TACTICS_MEMORY_TTL_SEC) + p.targetEid = INVALID_ENTITY_ID + p.lockedEid = INVALID_ENTITY_ID + p.watchUntil = -100.0 + wto_update_audio_and_radio_alerts(world, now, myPos, slot) + +[never_inline] +def public wto_perceive_pick_hunt_pos(world : WtoWorldSnap const&; army : int; eid : EntityId; + myPos : float3; now : float; var outPos : float3&) : bool + var bestDistSq = wto_sq(min(WTO_AI_TACTICS_RADIO_SHARE_M, 560.0)) + var found = false + var spotPos = myPos + for r in range(WTO_MAX_RADIO) + assume sp = world.radioSpots[r] + if sp.untilAt <= now || sp.army != army + continue + let dSq = wto_xz_dist_sq(myPos, sp.pos) + if dSq < bestDistSq && dSq > 2500.0 + bestDistSq = dSq + spotPos = sp.pos + found = true + if !found + return false + let toSpot = wto_xz_normalize(spotPos - myPos, float3(1.0, 0.0, 0.0)) + let lat = float3(-toSpot.z, 0.0, toSpot.x) + let fanOffset = float(int(uint(eid) % 5u) - 2) * 28.0 + var cand = spotPos - toSpot * 65.0 + lat * fanOffset + cand = wto_clamp_battle_xz(cand, world.battleCenter, world.battleRadius, 40.0) + if !wto_terrain_point_valid(army, cand) + cand = spotPos + outPos = cand + return true diff --git a/game-ai/ground/wto_ai_route_common.das b/game-ai/ground/wto_ai_route_common.das new file mode 100644 index 0000000..086eef2 --- /dev/null +++ b/game-ai/ground/wto_ai_route_common.das @@ -0,0 +1,169 @@ +// Corridor route planner: wide-projected `nm1` NavMesh pathfinding (fixing off-road hill caps), +// 5-wing lateral approach relays, crest-safe cross-country shortcuts, and corridor-independent +// jam/cluster bypass waypoints. +options indenting = 2 +options no_global_heap = true +module wto_ai_route_common shared + +require ecs +require math +require pathfinder +require %appGame.wtoai.wto_ai_config_common +require %appGame.wtoai.wto_ai_math_common +require %appGame.wtoai.wto_ai_types_common +require %appGame.wtoai.wto_ai_terrain_common +require %appGame.wtoai.wto_ai_world_common +require %appGame.wtoai.wto_ai_crowd_common + +[never_inline] +def private wto_project_nav_wide(navIdx : int; var pt : float3&) : bool + if project_to_nearest_navmesh_point_no_obstacles_ex(navIdx, pt, float3(28.0, 64.0, 28.0)) + return true + return project_to_nearest_navmesh_point_no_obstacles_ex(navIdx, pt, float3(165.0, 130.0, 165.0)) + +[never_inline] +def private wto_replan_corridor(now : float; myPos, goal : float3; var rt : WtoRouteState&) + rt.nextReplanAt = now + 2.8 + rt.corridorGoal = goal + rt.corridorLen = 0 + rt.corridorIdx = 0 + let navIdx = pathfinder_is_loaded_ex(1) ? 1 : (pathfinder_is_loaded_ex(0) ? 0 : -1) + if navIdx < 0 + rt.lastStartOk = false + rt.lastGoalOk = false + return + var sPt = myPos + var gPt = goal + rt.lastStartOk = wto_project_nav_wide(navIdx, sPt) + rt.lastGoalOk = wto_project_nav_wide(navIdx, gPt) + if !rt.lastStartOk || !rt.lastGoalOk + return + let maxKeep = WTO_MAX_PATH_PTS - 1 + find_path_ex(navIdx, sPt, gPt, float3(32.0, 48.0, 32.0), 9.0, 2.5, null) <| $(path : array#) + let total = length(path) + if total <= 0 + return + rt.corridor[0] = path[0] + rt.corridorLen = 1 + let minStepSq = total > maxKeep ? wto_sq(max(12.0, float(total) * 9.0 / float(maxKeep))) : 0.0 + for i in range(1, total) + if rt.corridorLen >= maxKeep + break + let prev = rt.corridor[rt.corridorLen - 1] + var isCorner = false + if i + 1 < total + let d0 = wto_xz_normalize(path[i] - prev, float3(1.0, 0.0, 0.0)) + let d1 = wto_xz_normalize(path[i + 1] - path[i], d0) + isCorner = dot(d0, d1) < 0.86 + if i == total - 1 || isCorner || wto_xz_dist_sq(prev, path[i]) >= minStepSq + rt.corridor[rt.corridorLen] = path[i] + rt.corridorLen++ + if rt.corridorLen < maxKeep && wto_xz_dist_sq(rt.corridor[rt.corridorLen - 1], path[total - 1]) > 9.0 + rt.corridor[rt.corridorLen] = path[total - 1] + rt.corridorLen++ + if rt.corridorLen > 0 && rt.corridorLen < WTO_MAX_PATH_PTS && wto_xz_dist_sq(rt.corridor[rt.corridorLen - 1], goal) > 64.0 + rt.corridor[rt.corridorLen] = goal + rt.corridorLen++ + +// Validate a crest-safe cross-country shortcut (<= 145m) with zero cliff drop-offs or jams. +[never_inline] +def private wto_try_shortcut(world : WtoWorldSnap const&; now : float; myPos, target : float3; + var slot : WtoBotSlot&) + assume rt = slot.route + rt.shortcutValid = false + rt.nextShortcutAt = now + 1.1 + let dist = sqrt(wto_xz_dist_sq(myPos, target)) + if dist < 22.0 || dist > 145.0 + return + let dir = wto_xz_normalize(target - myPos, float3(1.0, 0.0, 0.0)) + if wto_terrain_has_cliff_ahead(myPos, dir, min(dist, WTO_AI_TERRAIN_CREST_LOOKAHEAD_M + 8.0)) + return + let steps = clamp(int(dist / 7.5), 2, 20) + var prev = myPos + for s in range(1, steps + 1) + let d = (dist * float(s)) / float(steps) + let tx = myPos.x + dir.x * d + let tz = myPos.z + dir.z * d + var gy = prev.y + if !wto_terrain_drivable_y(prev, tx, tz, gy) + return + let samplePt = float3(tx, gy, tz) + if wto_world_jam_penalty(world, samplePt, now) > 4.0 || wto_crowd_point_penalty(world, slot.army, slot.eid, samplePt) > 18.0 + return + if wto_terrain_hard_ray(prev + float3(0.0, 1.3, 0.0), dir, 8.0) < 7.5 + return + prev = samplePt + rt.shortcutPos = target + rt.shortcutValid = true + +// Generate a lateral bypass waypoint around an obstacle/jam, even when no NavMesh corridor exists. +[never_inline] +def public wto_route_request_detour(world : WtoWorldSnap const&; now : float; + myPos, blockedDir : float3; var slot : WtoBotSlot&) + assume rt = slot.route + let fwd = wto_xz_normalize(blockedDir, float3(1.0, 0.0, 0.0)) + let lat = float3(-fwd.z, 0.0, fwd.x) + let pref = ((uint(slot.eid) + uint(rt.detourCount)) & 1u) == 0u ? 1.0 : -1.0 + var bestScore = -1.0e9 + var found = false + var bestPt = myPos + for k in range(4) + let side = (k % 2 == 0 ? pref : -pref) * (k < 2 ? 38.0 : 56.0) + let fwdStep = k < 2 ? 22.0 : 12.0 + var cand = wto_clamp_battle_xz(myPos + fwd * fwdStep + lat * side, world.battleCenter, world.battleRadius, 35.0) + if !wto_terrain_point_valid(slot.army, cand) + continue + let candDir = wto_xz_normalize(cand - myPos, lat) + if wto_terrain_has_cliff_ahead(myPos, candDir, 18.0) + continue + if wto_terrain_hard_ray(myPos + float3(0.0, 1.3, 0.0), candDir, 16.0) < 10.0 + continue + let score = -wto_world_jam_penalty(world, cand, now) - wto_crowd_point_penalty(world, slot.army, slot.eid, cand) + if score > bestScore + bestScore = score + bestPt = cand + found = true + if found + rt.detourPos = bestPt + rt.detourValid = true + rt.detourUntil = now + 11.0 + rt.detourCount++ + +[never_inline] +def public wto_route_select_waypoint(world : WtoWorldSnap const&; now : float; + myPos, finalGoal : float3; var slot : WtoBotSlot&) : float3 + assume rt = slot.route + if rt.detourValid + if now < rt.detourUntil && wto_xz_dist_sq(myPos, rt.detourPos) > 100.0 + return rt.detourPos + rt.detourValid = false + + if !rt.wingInit + rt.wingInit = true + rt.laneOffsetM = float(int((uint(slot.eid) / 5u) % 5u) - 2) * 4.0 + let st = slot.tactics.state + let useRelay = (st == WTO_STATE_MARCH || st == WTO_STATE_PREAIM || st == WTO_STATE_RELOAD_ADVANCE) && slot.order.routeRelayValid + var activeGoal = finalGoal + if useRelay + let relay = slot.order.routeRelayPos + let distMeToRelaySq = wto_xz_dist_sq(myPos, relay) + let distMeToGoalSq = wto_xz_dist_sq(myPos, finalGoal) + let distRelayToGoalSq = wto_xz_dist_sq(relay, finalGoal) + if slot.order.rallyHold || (distMeToRelaySq > 1444.0 && distMeToGoalSq > distRelayToGoalSq) + activeGoal = relay + + if now >= rt.nextShortcutAt + wto_try_shortcut(world, now, myPos, activeGoal, slot) + if rt.shortcutValid && wto_xz_dist_sq(rt.shortcutPos, activeGoal) <= 144.0 + return activeGoal + + if now >= rt.nextReplanAt || wto_xz_dist_sq(rt.corridorGoal, activeGoal) > 400.0 + wto_replan_corridor(now, myPos, activeGoal, rt) + while rt.corridorIdx < rt.corridorLen - 1 && wto_xz_dist_sq(myPos, rt.corridor[rt.corridorIdx]) <= 256.0 + rt.corridorIdx++ + if rt.corridorLen > 0 && rt.corridorIdx < rt.corridorLen + let wp = rt.corridor[rt.corridorIdx] + let toWp = wto_xz_normalize(wp - myPos, float3(1.0, 0.0, 0.0)) + let lat = float3(-toWp.z, 0.0, toWp.x) + return wp + lat * clamp(rt.laneOffsetM, -6.0, 6.0) + return activeGoal diff --git a/game-ai/ground/wto_ai_runtime.das b/game-ai/ground/wto_ai_runtime.das new file mode 100644 index 0000000..775e92b --- /dev/null +++ b/game-ai/ground/wto_ai_runtime.das @@ -0,0 +1,286 @@ +// Thin ECS orchestrator for WTOffline's modular ground AI system. +// Frame pipeline: world snapshot -> crowd density -> macro objectives -> tactics & perception -> +// corridor & bidirectional local nav -> chassis drive actuator -> deterministic fire control. +options indenting = 2 +options no_global_variables = false +options no_global_heap = true +options stack = 65536 + +require ecs +require app +require math +require DagorMath +require dm +require WTDamageModel +require Unit +require IGroundModel +require HeavyVehicleModel +require vehicle +require pathfinder +require %appGame.wt_events +require %game.events +require %game.unit.unit_events +require %appGame.wtoai.wto_ai_config_common +require %appGame.wtoai.wto_ai_order_common +require %appGame.wtoai.wto_ai_combat_types_common +require %appGame.wtoai.wto_ai_types_common +require %appGame.wtoai.wto_ai_specs_common +require %appGame.wtoai.wto_ai_world_common +require %appGame.wtoai.wto_ai_crowd_common +require %appGame.wtoai.wto_ai_lanes_common +require %appGame.wtoai.wto_ai_commander_common +require %appGame.wtoai.wto_ai_perceive_common +require %appGame.wtoai.wto_ai_tactics_common +require %appGame.wtoai.wto_ai_nav_common +require %appGame.wtoai.wto_ai_drive_common +require %appGame.wtoai.wto_ai_fire_common +require %appGame.wtoai.wto_ai_diag_common + +var private @safe_when_uninitialized g_world : WtoWorldSnap +var private @safe_when_uninitialized g_crowd : WtoCrowdSummary +var private @safe_when_uninitialized g_lanes : WtoTeamLanes +var private @safe_when_uninitialized g_bots : WtoBotSlot[64] +var private g_last_world_frame : float = -1.0 +var private g_next_cmd_at : float = 0.0 +var private g_next_rally_at : float = 0.0 +var private g_cmd_dirty : bool = true +var private g_last_zone_ver : int = -1 +var private g_fire_budget : int = 0 +var private g_next_diag_at : float = 0.0 + +def private wto_any_layer_active() : bool + return WTO_AI_ENABLED && (WTO_AI_LAYER_MACRO || WTO_AI_LAYER_TACTICS || WTO_AI_LAYER_NAVIGATION || WTO_AI_LAYER_FIRE_CONTROL) + +[init] +def wto_ai_script_init() + wto_drive_announce_script_ready() + +[never_inline] +def private wto_reset_runtime() + wto_world_reset(g_world) + wto_lanes_reset(g_lanes) + g_crowd = WtoCrowdSummary() + g_last_world_frame = -1.0 + g_next_cmd_at = 0.0 + g_next_rally_at = 0.0 + g_cmd_dirty = true + g_last_zone_ver = -1 + g_next_diag_at = 0.0 + for i in range(WTO_MAX_BOTS) + if g_bots[i].drive.routeBOwned + wto_drive_request_control(g_bots[i].eid, 0) + g_bots[i] = WtoBotSlot() + wto_drive_release_all() + +[never_inline] +def private wto_find_slot(eid : EntityId) : int + let cap = min(WTO_MAX_BOTS, WTO_AI_MAX_TRACKED_BOTS) + for i in range(cap) + if g_bots[i].used && g_bots[i].eid == eid + return i + return -1 + +[never_inline] +def private wto_acquire_slot(eid : EntityId; army : int; now : float) : int + let cap = min(WTO_MAX_BOTS, WTO_AI_MAX_TRACKED_BOTS) + var freeIdx = -1 + for i in range(cap) + if g_bots[i].used && g_bots[i].eid == eid + g_bots[i].army = army + g_bots[i].lastSeenAt = now + return i + if !g_bots[i].used && freeIdx < 0 + freeIdx = i + if freeIdx >= 0 + g_bots[freeIdx] = WtoBotSlot() + g_bots[freeIdx].used = true + g_bots[freeIdx].eid = eid + g_bots[freeIdx].army = army + g_bots[freeIdx].lastSeenAt = now + g_bots[freeIdx].nextTacticsAt = now - 0.01 + g_bots[freeIdx].nextNavAt = now - 0.01 + g_bots[freeIdx].route.nextReplanAt = now - 0.01 + g_cmd_dirty = true + return freeIdx + +[never_inline] +def private wto_phys_slot_available() : bool + if WTO_AI_NAV_MAX_PHYS_BOTS <= 0 + return false + var count = 0 + for i in range(WTO_MAX_BOTS) + if g_bots[i].used && g_bots[i].drive.routeBOwned && !g_bots[i].drive.routeAFallback + count++ + if count >= WTO_AI_NAV_MAX_PHYS_BOTS + return false + return true + +[es(tag=server, on_event=(EventMissionUnload, EventEntityManagerBeforeClear, EventEcsMissionLoaded))] +def wto_ai_mission_reset_es(evt : Event) + wto_reset_runtime() + wto_drive_announce_script_ready() + +[es(tag=server)] +def wto_ai_zone_captured_es(evt : EventZoneCaptured) + if !wto_any_layer_active() + return + g_world.zoneVersion++ + g_cmd_dirty = true + print("WTO_AI|ZONE_CAP|area={evt.areaId}|from={int(evt.wasArmy)}|to={int(evt.army)}\n") + +[es(tag=server, on_event=(EventOnUnitDead, EventUnitBecameDead))] +def wto_ai_unit_dead_es(evt : Event; eid : EntityId; unit__ref : UnitRef) + let u = unit__ref.unit + if u != null && as_gm(u) != null && (int(u.army) == 1 || int(u.army) == 2) + wto_world_record_death(g_world, eid, int(u.army), u.pos, float(get_app().usefulTotalTime)) + let idx = wto_find_slot(eid) + if idx >= 0 + if g_bots[idx].drive.routeBOwned + wto_drive_request_control(eid, 0) + g_bots[idx] = WtoBotSlot() + g_cmd_dirty = true + for i in range(WTO_MAX_BOTS) + if g_bots[i].used && g_bots[i].tactics.engageTargetEid == eid + g_bots[i].tactics.engageShotsNoEffect = 0 + g_bots[i].tactics.engageNoShotHalts = 0 + g_bots[i].tactics.engageTotalHaltSec = 0.0 + +[es(tag=server, on_disappear, on_event=EventUnitRespawn)] +def wto_ai_unit_cleanup_es(evt : Event; eid : EntityId) + let idx = wto_find_slot(eid) + if idx >= 0 + if g_bots[idx].drive.routeBOwned + wto_drive_request_control(eid, 0) + g_bots[idx] = WtoBotSlot() + g_cmd_dirty = true + for i in range(WTO_MAX_BOTS) + if g_bots[i].used && g_bots[i].tactics.engageTargetEid == eid + g_bots[i].tactics.engageShotsNoEffect = 0 + g_bots[i].tactics.engageNoShotHalts = 0 + g_bots[i].tactics.engageTotalHaltSec = 0.0 + +[es(tag=server)] +def wto_ai_unit_damage_es(evt : EventUnitDamage; eid : EntityId; unit__ref : UnitRef) + if !wto_any_layer_active() || !WTO_AI_LAYER_TACTICS + return + let offEid = evt.offender.eid + let u = unit__ref.unit + if u == null || !offEid || offEid == eid + return + let now = float(get_app().usefulTotalTime) + let vicArmy = int(u.army) + // Outgoing effective damage confirmation for our firing bot (resets stalemate counters). + let offBotIdx = wto_find_slot(offEid) + if offBotIdx >= 0 && g_bots[offBotIdx].army != vicArmy && uint(evt.hpFixed) < uint(evt.prevHpFixed) + assume tac = g_bots[offBotIdx].tactics + if tac.engageTargetEid == eid || g_bots[offBotIdx].perceive.targetEid == eid + tac.engageShotsNoEffect = 0 + tac.engageNoShotHalts = 0 + tac.lastEffectAt = now + // Incoming hit direction cue for our damaged bot (never leaks hidden offender coords). + let idx = wto_find_slot(eid) + if idx < 0 + return + let offUnitIdx = wto_world_find_unit(g_world, offEid) + if offUnitIdx >= 0 && g_world.units[offUnitIdx].army == g_bots[idx].army + return + let imp = evt.pos - u.pos + g_bots[idx].perceive.lastHitYawRad = (imp.x * imp.x + imp.z * imp.z) > 0.04 ? atan2(imp.z, imp.x) : atan2(u.unitTm[0].z, u.unitTm[0].x) + g_bots[idx].perceive.lastDamagedAt = now + g_bots[idx].perceive.lastOffenderEid = offEid + +[es(tag=server, before=wto_ai_pipeline_es)] +def wto_ai_world_tick_es(act : UpdateStageInfoAct) + if !wto_any_layer_active() || !is_app_in_flight() + return + if abs(act.curTime - g_last_world_frame) <= 1.0e-4 + return + g_last_world_frame = act.curTime + g_fire_budget = WTO_AI_FC_MAX_CHECKS_PER_TICK + let now = float(get_app().usefulTotalTime) + if g_world.valid && now < g_world.time - 1.0 + wto_reset_runtime() + for i in range(WTO_MAX_BOTS) + if g_bots[i].used && (now - g_bots[i].lastSeenAt) > 3.5 + g_bots[i] = WtoBotSlot() + if !g_world.valid + wto_drive_announce_script_ready() + print("WTO_AI|RUNTIME_READY\n") + wto_world_refresh(now, g_world) + wto_crowd_update_all(g_world, g_bots, g_crowd) + let zoneChanged = g_world.zoneVersion != g_last_zone_ver + if zoneChanged + g_last_zone_ver = g_world.zoneVersion + wto_lanes_reset_rallies(g_lanes) + g_cmd_dirty = true + if WTO_AI_LAYER_MACRO && (now >= g_next_cmd_at || g_cmd_dirty) + g_next_cmd_at = now + WTO_AI_CMD_REBALANCE_SEC + g_next_rally_at = now + 1.0 + g_cmd_dirty = false + wto_commander_update_all(g_world, now, zoneChanged, g_lanes, g_bots) + elif WTO_AI_LAYER_MACRO && now >= g_next_rally_at + g_next_rally_at = now + 1.0 + wto_lanes_update_rallies(g_world, 1, now, g_lanes, g_bots) + wto_lanes_update_rallies(g_world, 2, now, g_lanes, g_bots) + for i in range(WTO_MAX_BOTS) + assume b = g_bots[i] + if b.used && b.order.valid && b.order.rallyHold && b.order.capIndex >= 0 + let sk = wto_lanes_sub_key(b.army, b.order.capIndex, b.order.laneId) + if g_lanes.rallyReleased[sk] + b.order.rallyHold = false + if b.order.role == WTO_CMD_FLANK && b.order.laneId > 0 + let ck = wto_lanes_cap_key(b.army, b.order.capIndex) + b.order.routeRelayValid = g_lanes.flankValid[ck * 2 + b.order.laneId - 1] + b.order.routeRelayPos = g_lanes.flankRelay[ck * 2 + b.order.laneId - 1] + else + b.order.routeRelayValid = false + if WTO_AI_DIAG_TELEMETRY && now >= g_next_diag_at + g_next_diag_at = now + WTO_AI_DIAG_INTERVAL_SEC + wto_diag_log_telemetry(g_world, now, g_bots, g_crowd) + +[es(tag=server, no_order)] +def wto_ai_pipeline_es(act : UpdateStageInfoAct; eid : EntityId; var unit__ref : UnitRef&; + unit__className : string = ""; + repair_system_remaining_repair_time : float = -1.0) + if !wto_any_layer_active() || !g_world.valid + return + var unit = unit__ref.unit + if unit == null || !unit.isAlive || unit.isDelayed || unit.isHumanPlayer + return + let army = int(unit.army) + let gm = as_gm(unit) + if (army != 1 && army != 2) || gm == null || gm.moveSys == null || as_hv(unit) == null + return + let now = float(get_app().usefulTotalTime) + let idx = wto_acquire_slot(eid, army, now) + if idx < 0 + return + assume slot = g_bots[idx] + if !slot.prepared + slot.prepared = true + wto_specs_load(eid, unit__className, unit, gm, slot.spec) + if now >= slot.nextTacticsAt + slot.nextTacticsAt = now + WTO_AI_TACTICS_TICK_SEC + if WTO_AI_LAYER_TACTICS || WTO_AI_LAYER_FIRE_CONTROL + wto_perceive_update(g_world, now, WTO_AI_TACTICS_TICK_SEC, unit.pos, unit.unitTm[0], slot) + wto_tactics_update(g_world, now, WTO_AI_TACTICS_TICK_SEC, unit.pos, unit.unitTm[0], unit.isBurn, repair_system_remaining_repair_time, slot, g_crowd) + if now >= slot.nextNavAt + slot.nextNavAt = now + WTO_AI_NAV_TICK_SEC + wto_nav_update(g_world, now, unit.pos, unit.unitTm[0], slot) + wto_fire_update(g_world, unit, now, act.dt, slot, g_fire_budget) + +[es(tag=server, after=wto_ai_pipeline_es)] +def wto_ai_phys_tick_es(act : UpdateStageInfoAct; eid : EntityId; var unit__ref : UnitRef&; + unit__missionName : string; var vehicle_net_phys : VehiclePhysActor&) + if !wto_any_layer_active() || !WTO_AI_LAYER_NAVIGATION || WTO_AI_NAV_DRIVE_MODE != "vehicle_phys" + return + var unit = unit__ref.unit + if unit == null || !unit.isAlive || unit.isDelayed || unit.isHumanPlayer || vehicle_net_phys.physEdit == null + return + let idx = wto_find_slot(eid) + if idx < 0 + return + if !g_bots[idx].drive.routeBOwned && !wto_phys_slot_available() + return + let now = float(get_app().usefulTotalTime) + wto_drive_step_phys(unit, unit__missionName, as_gm(unit), vehicle_net_phys, act.dt, now, g_bots[idx]) diff --git a/game-ai/ground/wto_ai_sight_common.das b/game-ai/ground/wto_ai_sight_common.das new file mode 100644 index 0000000..efa53bd --- /dev/null +++ b/game-ai/ground/wto_ai_sight_common.das @@ -0,0 +1,126 @@ +// Scene visibility, foliage transparency, smoke, and strict hard-occlusion queries. +// Completely separate from driving's soft-obstacle avoidance in wto_ai_terrain_common. +options indenting = 2 +options no_global_heap = true +module wto_ai_sight_common shared + +require ecs +require math +require DagorMath +require Dacoll +require RendInst +require PhysMat +require SmokeOccluder +require %appGame.wtoai.wto_ai_config_common +require %appGame.wtoai.wto_ai_math_common +require %appGame.wtoai.wto_ai_combat_types_common +require %appGame.wtoai.wto_ai_types_common + +let private SIGHT_TERRAIN_MASK = ETF_LMESH | ETF_HEIGHTMAP | ETF_STRUCTURES | ETF_FRT + +[never_inline] +def private wto_seg_hits_box_xz(p0, segDir : float3; segLen : float; + boxPos : float3; halfLen, halfWid, heightM : float) : bool + let rad = max(halfLen, halfWid) * 0.88 + let center = boxPos + float3(0.0, heightM * 0.5, 0.0) + let rel = center - p0 + let along = dot(rel, segDir) + if along < 0.25 || along > segLen - 0.25 + return false + let closest = p0 + segDir * along + let dy = abs(closest.y - center.y) + if dy > heightM * 0.55 + 0.35 + return false + let dx = closest.x - center.x + let dz = closest.z - center.z + return (dx * dx + dz * dz) <= rad * rad + +[never_inline] +def public wto_sight_units_block_segment(world : WtoWorldSnap const&; + selfEid, targetEid : EntityId; + p0, segDir : float3; segLen : float) : int + for w in range(world.wreckCount) + assume wr = world.wrecks[w] + if wr.eid != selfEid && wr.eid != targetEid + if wto_seg_hits_box_xz(p0, segDir, segLen, wr.pos, wr.halfLen, wr.halfWid, 2.2) + return WTO_BLOCK_WRECK + for i in range(world.unitCount) + assume u = world.units[i] + if !u.isAlive || !u.isGround || u.eid == selfEid || u.eid == targetEid + continue + if wto_seg_hits_box_xz(p0, segDir, segLen, u.pos, u.halfLen, u.halfWid, 2.3) + return WTO_BLOCK_VEHICLE + return WTO_BLOCK_NONE + +[never_inline] +def public wto_sight_hard_segment_blocked(world : WtoWorldSnap const&; + selfEid, targetEid : EntityId; + fromPos, toPos : float3; + sweepRadius : float; trimStartM, trimEndM : float) : int + let delta = toPos - fromPos + let fullLen = length(delta) + if fullLen <= trimStartM + trimEndM + 0.2 + return WTO_BLOCK_NONE + let dir = delta / fullLen + var p0 = fromPos + dir * trimStartM + let traceLen = fullLen - trimStartM - trimEndM + if rayhit_normalized(p0, dir, traceLen, SIGHT_TERRAIN_MASK, PHYSMAT_INVALID) + return WTO_BLOCK_TERRAIN + if rayhit_normalized(p0, dir, traceLen, ETF_RI, PHYSMAT_INVALID) + return WTO_BLOCK_OBJECT + if rayhit_normalized(p0, dir, traceLen, ETF_RI_PHYS, PHYSMAT_INVALID) + return WTO_BLOCK_OBJECT + if sweepRadius > 0.02 + var s1 = p0 + dir * traceLen + var queryOut = ShapeQueryOutput() + if sphere_cast(p0, s1, sweepRadius, queryOut) + return WTO_BLOCK_OBJECT + return wto_sight_units_block_segment(world, selfEid, targetEid, p0, dir, traceLen) + +[never_inline] +def public wto_sight_visual_clear(world : WtoWorldSnap const&; + selfEid, targetEid : EntityId; + eyePos, targetPt : float3) : int + let delta = targetPt - eyePos + let dist = length(delta) + if dist <= 1.2 + return WTO_BLOCK_NONE + let dir = delta / dist + let traceLen = max(0.4, dist - 1.1) + var p0 = eyePos + var p1 = targetPt + if rayhit_smoke_occluders(p0, p1) + return WTO_BLOCK_SMOKE + let aimMat = get_material_id("aimRay") + if rayhit_normalized(p0, dir, traceLen, ETF_ALL, aimMat) + return WTO_BLOCK_TERRAIN + if traceTransparencyRayRIGenNormalized(p0, dir, traceLen, WTO_AI_PERC_FOLIAGE_TRANS) + return WTO_BLOCK_FOLIAGE + return wto_sight_units_block_segment(world, selfEid, targetEid, p0, dir, traceLen) + +[never_inline] +def public wto_sight_check_target_samples(world : WtoWorldSnap const&; + selfEid : EntityId; eyePos : float3; + tgt : WtoUnitSnap const&; maxSamples : int; + var outBestPt : float3&) : int + if tgt.isAir + outBestPt = tgt.pos + return wto_sight_visual_clear(world, selfEid, tgt.eid, eyePos, tgt.pos) == WTO_BLOCK_NONE ? 2 : 0 + let fwd = wto_xz_normalize(tgt.hullFwd, float3(1.0, 0.0, 0.0)) + let left = float3(-fwd.z, 0.0, fwd.x) + let sideOff = max(0.75, tgt.halfWid * 0.72) + var pts : float3[4] + pts[0] = tgt.pos + float3(0.0, 1.15, 0.0) + pts[1] = tgt.pos + float3(0.0, 1.95, 0.0) + pts[2] = tgt.pos + left * sideOff + float3(0.0, 1.25, 0.0) + pts[3] = tgt.pos - left * sideOff + float3(0.0, 1.25, 0.0) + let count = clamp(maxSamples, 1, 4) + var vis = 0 + var picked = false + for s in range(count) + if wto_sight_visual_clear(world, selfEid, tgt.eid, eyePos, pts[s]) == WTO_BLOCK_NONE + if !picked + outBestPt = pts[s] + picked = true + vis++ + return vis diff --git a/game-ai/ground/wto_ai_specs_common.das b/game-ai/ground/wto_ai_specs_common.das new file mode 100644 index 0000000..b7e9339 --- /dev/null +++ b/game-ai/ground/wto_ai_specs_common.das @@ -0,0 +1,202 @@ +// Authoritative per-vehicle specification loader: reads unit & weapon DataBlocks once per +// spawned bot (`gamedata/units/.blk`) to extract exact role, gun stabilizer, +// traverse limits, turret slew rates, shell muzzle velocity, and reverse speed capability. +options indenting = 2 +options no_global_heap = true +module wto_ai_specs_common shared + +require ecs +require app +require math +require strings +require DagorMath +require DagorDataBlock +require Unit +require IGroundModel +require HeavyVehicleModel +require Weapon +require %game.utils.utils_common +require %appGame.wtoai.wto_ai_math_common +require %appGame.wtoai.wto_ai_combat_types_common +require %appGame.wtoai.wto_ai_types_common + +[never_inline] +def private wto_parse_role_strings(unitType : string; expClass : string; isLightTag : bool) : int + if unitType == "typeSPAA" || expClass == "exp_SPAA" + return WTO_ROLE_SPAA + if unitType == "typeTankDestroyer" || expClass == "exp_tank_destroyer" + return WTO_ROLE_TD + if unitType == "typeHeavyTank" || expClass == "exp_heavy_tank" + return WTO_ROLE_HEAVY + if unitType == "typeLightTank" || isLightTag + return WTO_ROLE_LIGHT + return WTO_ROLE_MEDIUM + +[never_inline] +def private wto_parse_turret_limits(turretBlk : DataBlock const?; var spec : WtoVehicleSpec&) + if turretBlk == null + return + let lim1 = *turretBlk |> datablock_getPoint4("lim1", float4(0.0, 0.0, 0.0, 0.0)) + let lim2 = *turretBlk |> datablock_getPoint4("lim2", float4(0.0, 0.0, 0.0, 0.0)) + var maxAbsYaw = 0.0 + var minPitch = 0.0 + var maxPitch = 0.0 + if abs(lim1.x) > 0.1 || abs(lim1.y) > 0.1 + maxAbsYaw = max(maxAbsYaw, max(abs(lim1.x), abs(lim1.y))) + minPitch = min(minPitch, lim1.z) + maxPitch = max(maxPitch, lim1.w) + if abs(lim2.x) > 0.1 || abs(lim2.y) > 0.1 + maxAbsYaw = max(maxAbsYaw, max(abs(lim2.x), abs(lim2.y))) + minPitch = min(minPitch, lim2.z) + maxPitch = max(maxPitch, lim2.w) + let limitsBlk = *turretBlk |> datablock_get_block_by_name("limits") + if limitsBlk != null + let yawRange = *limitsBlk |> datablock_getPoint2("yaw", float2(0.0, 0.0)) + let pitchRange = *limitsBlk |> datablock_getPoint2("pitch", float2(0.0, 0.0)) + if abs(yawRange.x) > 0.1 || abs(yawRange.y) > 0.1 + maxAbsYaw = max(maxAbsYaw, max(abs(yawRange.x), abs(yawRange.y))) + if pitchRange.x < -0.1 || pitchRange.y > 0.1 + minPitch = min(minPitch, pitchRange.x) + maxPitch = max(maxPitch, pitchRange.y) + if maxAbsYaw > 0.5 + spec.yawLimitDeg = clamp(maxAbsYaw, 4.0, 180.0) + spec.isLimitedTraverse = spec.yawLimitDeg < 75.0 + if minPitch < -0.5 + spec.minPitchDeg = clamp(minPitch, -25.0, -2.0) + if maxPitch > 1.0 + spec.maxPitchDeg = clamp(maxPitch, 8.0, 88.0) + +[never_inline] +def private wto_record_shell_block(bBlk : DataBlock const&; var spec : WtoVehicleSpec&; isDefault : bool) + let spd = bBlk |> datablock_getReal("speed", 0.0) + if spd <= 80.0 || spd >= 2600.0 + return + let cx = clamp(bBlk |> datablock_getReal("Cx", 0.35), 0.05, 1.5) + let mass = clamp(bBlk |> datablock_getReal("mass", 10.0), 0.05, 250.0) + let rawCal = bBlk |> datablock_getReal("ballisticCaliber", 0.0) + let cal = clamp(rawCal > 0.002 ? rawCal : bBlk |> datablock_getReal("caliber", 0.09), 0.005, 0.4) + if isDefault && spec.shellCount == 0 + spec.muzzleSpeedMps = spd + spec.shellDragCx = cx + spec.shellMassKg = mass + spec.shellCaliberM = cal + let bName = bBlk |> datablock_getStr("bulletName", "") + if empty(bName) || spec.shellCount >= WTO_MAX_SHELL_PROFILES + return + let h = ecs_hash(bName) + for i in range(spec.shellCount) + if spec.shells[i].nameHash == h + return + let idx = spec.shellCount + let bt = bBlk |> datablock_getStr("bulletType", "") + let isSoft = find(bt, "he_frag") >= 0 || find(bt, "hesh") >= 0 + let isNonCombat = find(bt, "smoke") >= 0 || find(bt, "practice") >= 0 || find(bt, "shrapnel") >= 0 + spec.shells[idx].nameHash = h + spec.shells[idx].speedMps = spd + spec.shells[idx].dragCx = cx + spec.shells[idx].massKg = mass + spec.shells[idx].caliberM = cal + spec.shells[idx].isSoftShell = isSoft + spec.shells[idx].isAntiArmor = !isSoft && !isNonCombat + spec.shellCount = idx + 1 + +[never_inline] +def private wto_parse_weapon_blk(weapBlkPath : string; var spec : WtoVehicleSpec&) + if empty(weapBlkPath) || find(weapBlkPath, "dummy_weapon") >= 0 + return + datablock_load_cached(weapBlkPath, DataBlockReadFlag.ROBUST) <| $(wBlk) + let isRocket = wBlk |> datablock_getBool("rocketGun", false) + let isCannon = wBlk |> datablock_getBool("cannon", false) + let isBelt = wBlk |> datablock_getBool("isBulletBelt", false) + if isRocket && !isCannon + return + spec.isAutocannonBelt = isBelt + spec.shellCount = 0 + datablock_for_each_block(wBlk, "bullet") <| $(bBlk) + wto_record_shell_block(bBlk, spec, true) + datablock_for_each_block(wBlk) <| $(subBlk) + datablock_for_each_block(subBlk, "bullet") <| $(bBlk) + wto_record_shell_block(bBlk, spec, false) + +[never_inline] +def private wto_parse_unit_blk(className : string; isLightTag : bool; var spec : WtoVehicleSpec&) : bool + if empty(className) + return false + let relPath = find(className, "/") >= 0 ? ("gamedata/units/" + className + ".blk") : ("gamedata/units/tankModels/" + className + ".blk") + var loaded = false + datablock_load_cached(relPath, DataBlockReadFlag.ROBUST) <| $(mBlk) + if mBlk.paramCount == 0u && mBlk.blockCount == 0u + return + loaded = true + let uType = mBlk |> datablock_getStr("type", "") + let expCls = mBlk |> datablock_getStr("expClass", "") + spec.role = wto_parse_role_strings(uType, expCls, isLightTag) + let fwdKmh = mBlk |> datablock_getReal("maxFwdSpeed", 0.0) + let revKmh = mBlk |> datablock_getReal("maxRevSpeed", 0.0) + if fwdKmh > 5.0 + spec.vMaxFwd = clamp(fwdKmh / 3.6, 4.0, 28.0) + if revKmh > 1.0 + spec.vMaxRev = clamp(revKmh / 3.6, 1.0, 16.0) + let commonBlk = mBlk |> datablock_get_block_by_name("commonWeapons") + if commonBlk == null + return + var primaryParsed = false + datablock_for_each_block(*commonBlk, "Weapon") <| $(weapBlk) + if primaryParsed + return + let trig = weapBlk |> datablock_getStr("triggerGroup", "primary") + let wPath = weapBlk |> datablock_getStr("blk", "") + if trig != "primary" || empty(wPath) || find(wPath, "dummy_weapon") >= 0 || find(wPath, "machinegun") >= 0 + return + primaryParsed = true + let sy = weapBlk |> datablock_getReal("speedYaw", 24.0) + let sp = weapBlk |> datablock_getReal("speedPitch", 8.0) + spec.turretYawSpd = clamp(sy, 4.0, 120.0) + spec.turretPitchSpd = clamp(sp, 2.0, 90.0) + let stabBlk = weapBlk |> datablock_get_block_by_name("gunStabilizer") + if stabBlk != null + spec.hasVertStab = *stabBlk |> datablock_getBool("hasVertical", false) + wto_parse_turret_limits(weapBlk |> datablock_get_block_by_name("turret"), spec) + wto_parse_weapon_blk(wPath, spec) + return loaded + +[never_inline] +def private wto_apply_runtime_fallbacks(unit : Unit const?; gm : IGroundModel const?; + isLightTag : bool; blkLoaded : bool; var spec : WtoVehicleSpec&) + if gm != null + let box = gm.bodyBoundingBox + spec.halfLen = max(2.0, max(abs(box.boxMin.x), abs(box.boxMax.x)) + 0.15) + spec.halfWid = max(1.0, max(abs(box.boxMin.z), abs(box.boxMax.z)) + 0.18) + let hv = unit != null ? as_hv(unit) : null + if hv != null && hv.getMaxSpeed > 1.5 && wto_is_finite(hv.getMaxSpeed) + spec.vMaxFwd = min(spec.vMaxFwd, hv.getMaxSpeed) + if unit == null || unit.weap == null + return + var gunCount = 0 + var launcherCount = 0 + foreach_primary_gun(unit.weap.Weapons) <| $(weapon) + if weapon == null || weapon.isDummyGun + return + if weapon.prop.launcher + launcherCount++ + elif as_gun(weapon) != null + gunCount++ + spec.isPureLauncher = gunCount == 0 && launcherCount > 0 + if length(unit.weap.turret) == 0 && gunCount > 0 + spec.isLimitedTraverse = true + spec.yawLimitDeg = min(spec.yawLimitDeg, 12.0) + if !blkLoaded + if spec.isLimitedTraverse + spec.role = WTO_ROLE_TD + elif isLightTag + spec.role = WTO_ROLE_LIGHT + elif spec.vMaxFwd <= 10.5 && spec.halfLen >= 3.3 + spec.role = WTO_ROLE_HEAVY + +[never_inline] +def public wto_specs_load(eid : EntityId; className : string; unit : Unit const?; + gm : IGroundModel const?; var spec : WtoVehicleSpec&) + let isLightTag = has(eid, "unit_tag__light_vehicle") + let blkLoaded = wto_parse_unit_blk(className, isLightTag, spec) + wto_apply_runtime_fallbacks(unit, gm, isLightTag, blkLoaded, spec) + spec.ready = true diff --git a/game-ai/ground/wto_ai_tactics_actions_common.das b/game-ai/ground/wto_ai_tactics_actions_common.das new file mode 100644 index 0000000..7162148 --- /dev/null +++ b/game-ai/ground/wto_ai_tactics_actions_common.das @@ -0,0 +1,193 @@ +// Tactics action handlers: damage retreat & repair (plan 6.1), cover retreat & 3-way reload +// actions, and stalemate detection / reposition unlock. +options indenting = 2 +options no_global_heap = true +module wto_ai_tactics_actions_common shared + +require ecs +require math +require %game.unit.repair_system_events +require %appGame.wtoai.wto_ai_config_common +require %appGame.wtoai.wto_ai_math_common +require %appGame.wtoai.wto_ai_order_common +require %appGame.wtoai.wto_ai_combat_types_common +require %appGame.wtoai.wto_ai_types_common +require %appGame.wtoai.wto_ai_terrain_common +require %appGame.wtoai.wto_ai_cover_common + +[never_inline] +def public wto_sm_set_state(now : float; newState : int; goalPos : float3; speedMps : float; + reason : string; distXZ : float; var slot : WtoBotSlot&) + assume tac = slot.tactics + if tac.state != newState + if WTO_AI_DIAG_TELEMETRY + print("WTO_AI|STATE|t={now}|eid={uint(slot.eid)}|from={tac.state}|to={newState}|reason={reason}|dist={distXZ}|v={slot.drive.lastVFwd}\n") + tac.state = newState + tac.stateEnteredAt = now + if newState == WTO_STATE_SHORT_HALT + tac.haltEnterAt = now + tac.haltStartShots = slot.fire.shotCount + tac.moveGoal = goalPos + tac.desiredSpeedMps = speedMps + +[never_inline] +def public wto_friendly_retreat_dir(world : WtoWorldSnap const&; army : int; + myPos, threatDir : float3) : float3 + if world.teamSpawnValid[army] + let toSpawn = wto_xz_normalize(world.teamSpawnCenter[army] - myPos, -threatDir) + let blended = toSpawn * 0.65 - threatDir * 0.35 + return wto_xz_normalize(blended, toSpawn) + return wto_xz_normalize(-threatDir, float3(1.0, 0.0, 0.0)) + +[never_inline] +def public wto_sm_handle_disabled_and_repair(world : WtoWorldSnap const&; now : float; + myPos, threatPos, threatDir : float3; + isBurn : bool; repairRemainingSec, distXZ : float; + var slot : WtoBotSlot&) : bool + assume tac = slot.tactics + assume p = slot.perceive + tac.spaaYieldAir = false + if slot.spec.role == WTO_ROLE_SPAA + if p.hasClearLos && p.targetIsAir && !!p.targetEid + tac.spaaYieldAir = true + wto_sm_set_state(now, WTO_STATE_MARCH, myPos, 0.0, "spaa_air_engage", distXZ, slot) + return true + if p.hasClearLos && !p.targetIsAir && !!p.targetEid && distXZ < 220.0 + let backDir = wto_friendly_retreat_dir(world, slot.army, myPos, threatDir) + let goal = wto_clamp_battle_xz(myPos + backDir * 70.0, world.battleCenter, world.battleRadius, 40.0) + wto_sm_set_state(now, WTO_STATE_DISABLED, goal, slot.spec.vMaxFwd, "spaa_evade_tank", distXZ, slot) + return true + + // Engine/tracks broken (cannot move): halt in place and request native repair; gun keeps self-defending. + if tac.immobilized + tac.repairCoverValid = false + if !isBurn && repairRemainingSec <= 0.0 + sendEvent(slot.eid, EventRepairSystemRequestRepair(repair = true)) + wto_sm_set_state(now, WTO_STATE_DISABLED, myPos, 0.0, "immobilized_repair", distXZ, slot) + return true + + // Main gun damaged or burning while mobile: immediately retreat to an enemy-free cover and repair there. + if slot.fire.gunDamaged || isBurn + let inSafeSpot = (tac.repairCoverValid && wto_xz_dist_sq(myPos, tac.repairCoverGoal) <= 25.0) || (wto_cover_is_hull_concealed(world, slot.eid, p.targetEid, myPos, threatPos) && distXZ > 90.0) + if inSafeSpot + if !isBurn && repairRemainingSec <= 0.0 + sendEvent(slot.eid, EventRepairSystemRequestRepair(repair = true)) + wto_sm_set_state(now, WTO_STATE_DISABLED, myPos, 0.0, "cover_repair_hold", distXZ, slot) + return true + if !tac.repairCoverValid + var cov = myPos + if wto_cover_pick_candidate(world, now, myPos, threatPos, true, slot, cov) + tac.repairCoverGoal = cov + else + let backDir = wto_friendly_retreat_dir(world, slot.army, myPos, threatDir) + tac.repairCoverGoal = wto_clamp_battle_xz(myPos + backDir * 75.0, world.battleCenter, world.battleRadius, 40.0) + tac.repairCoverValid = true + wto_sm_set_state(now, WTO_STATE_DISABLED, tac.repairCoverGoal, slot.spec.vMaxFwd, slot.fire.gunDamaged ? "gun_damaged_retreat" : "burn_retreat", distXZ, slot) + return true + + tac.repairCoverValid = false + if repairRemainingSec > 0.0 + wto_sm_set_state(now, WTO_STATE_DISABLED, myPos, 0.0, "finishing_repair", distXZ, slot) + return true + return false + +[never_inline] +def public wto_sm_continue_cover_retreat(world : WtoWorldSnap const&; now : float; + myPos, threatPos : float3; distXZ : float; + var slot : WtoBotSlot&) : bool + assume tac = slot.tactics + if tac.state == WTO_STATE_RETREAT_COVER + let arrived = wto_xz_dist_sq(myPos, tac.retreatTarget) <= 12.25 + let concealed = wto_cover_is_hull_concealed(world, slot.eid, slot.perceive.targetEid, myPos, threatPos) + if arrived || concealed + wto_sm_set_state(now, WTO_STATE_COVER_RELOAD, myPos, 0.0, "cover_reached", distXZ, slot) + return true + if now >= tac.retreatUntil + return false + let spd = tac.retreatReverse ? max(2.2, slot.spec.vMaxRev) : (slot.spec.vMaxFwd * 0.92) + wto_sm_set_state(now, WTO_STATE_RETREAT_COVER, tac.retreatTarget, spd, "cover_retreating", distXZ, slot) + return true + if tac.state == WTO_STATE_COVER_RELOAD + if slot.fire.reloading + wto_sm_set_state(now, WTO_STATE_COVER_RELOAD, myPos, 0.0, "cover_reloading", distXZ, slot) + return true + return false + return false + +[never_inline] +def public wto_sm_start_reload_action(world : WtoWorldSnap const&; now : float; + myPos, hullFwd, threatPos, baseGoal : float3; + distXZ, distGoal : float; var slot : WtoBotSlot&) : bool + assume tac = slot.tactics + // Option 1: pull back into remembered or nearby cover (6..24m). + var cov = myPos + if wto_cover_pick_candidate(world, now, myPos, threatPos, false, slot, cov) + let toCov = wto_xz_normalize(cov - myPos, -hullFwd) + let behindHull = dot(toCov, hullFwd) < -0.15 + tac.retreatTarget = cov + tac.retreatUntil = now + WTO_AI_SM_COVER_RETREAT_SEC + tac.retreatReverse = behindHull && slot.nav.rearClearM > 3.2 && slot.spec.vMaxRev >= 2.0 + let spd = tac.retreatReverse ? max(2.2, slot.spec.vMaxRev) : (slot.spec.vMaxFwd * 0.92) + wto_sm_set_state(now, WTO_STATE_RETREAT_COVER, cov, spd, "reload_pullback", distXZ, slot) + return true + // Option 2: no near cover and offensive/advancing -> zigzag push toward objective. + if wto_order_is_offensive(slot.order.role) || distGoal > 35.0 + let toGoal = wto_xz_normalize(baseGoal - myPos, hullFwd) + let zigSign = (uint(slot.eid) & 1u) == 0u ? 1.0 : -1.0 + let ang = zigSign * WTO_AI_SM_RELOAD_ADV_DEG * WTO_DEG_TO_RAD + let zigDir = float3(toGoal.x * cos(ang) - toGoal.z * sin(ang), 0.0, toGoal.x * sin(ang) + toGoal.z * cos(ang)) + let zigGoal = wto_clamp_battle_xz(myPos + zigDir * min(distGoal, 48.0), world.battleCenter, world.battleRadius, 35.0) + wto_sm_set_state(now, WTO_STATE_RELOAD_ADVANCE, zigGoal, slot.spec.vMaxFwd * 0.92, "reload_advance", distXZ, slot) + return true + // Option 3: defensive hold with side/rear exposed > 30 deg -> angle hull front +/-15 deg toward threat. + let toThreat = wto_xz_normalize(threatPos - myPos, hullFwd) + let exposureDeg = acos(clamp(dot(hullFwd, toThreat), -1.0, 1.0)) * WTO_RAD_TO_DEG + let hasPivotRoom = slot.nav.frontClearM >= slot.spec.halfLen + 1.5 && slot.nav.rearClearM >= slot.spec.halfLen + 1.2 + if exposureDeg > WTO_AI_SM_HULL_ANGLE_TRIG_DEG && hasPivotRoom + let angSign = (uint(slot.eid) & 1u) == 0u ? 1.0 : -1.0 + let ang = angSign * WTO_AI_SM_HULL_ANGLE_TGT_DEG * WTO_DEG_TO_RAD + tac.hullAngleDir = float3(toThreat.x * cos(ang) - toThreat.z * sin(ang), 0.0, toThreat.x * sin(ang) + toThreat.z * cos(ang)) + wto_sm_set_state(now, WTO_STATE_HULL_ANGLE, myPos, 0.0, "reload_angle_hull", distXZ, slot) + return true + return false + +[never_inline] +def public wto_sm_handle_reposition(world : WtoWorldSnap const&; now : float; + myPos, threatDir, baseGoal : float3; + distXZ : float; var slot : WtoBotSlot&) : bool + assume tac = slot.tactics + if tac.repositionActive + let movedSq = wto_xz_dist_sq(myPos, tac.repositionOrigin) + let remSq = wto_xz_dist_sq(myPos, tac.repositionGoal) + if movedSq >= wto_sq(WTO_AI_SM_REPOS_MIN_MOVE_M) || remSq <= 64.0 + tac.repositionActive = false + tac.engageTotalHaltSec = 0.0 + return false + if distXZ <= WTO_AI_FC_CLOSE_RANGE_M + return false + wto_sm_set_state(now, WTO_STATE_REPOSITION, tac.repositionGoal, slot.spec.vMaxFwd * 0.92, "reposition_move", distXZ, slot) + return true + + let shotTimeoutOk = (now - slot.fire.lastShotAt) >= 1.2 + let staleShots = tac.engageShotsNoEffect >= WTO_AI_SM_STALE_MISS_SHOTS && shotTimeoutOk + let staleHalts = tac.engageNoShotHalts >= WTO_AI_SM_STALE_NOSHOT_HALTS + let staleTime = tac.engageTotalHaltSec >= WTO_AI_SM_MAX_TOTAL_HALT_SEC + if !staleShots && !staleHalts && !staleTime + return false + let lat = float3(-threatDir.z, 0.0, threatDir.x) + let side = (uint(slot.eid) & 1u) == 0u ? 1.0 : -1.0 + var goal = baseGoal + for attempt in range(2) + let s = attempt == 0 ? side : -side + var cand = wto_clamp_battle_xz(myPos + lat * (s * WTO_AI_SM_REPOS_STEP_M) + threatDir * 14.0, world.battleCenter, world.battleRadius, 35.0) + if wto_terrain_point_valid(slot.army, cand) + goal = cand + break + tac.repositionOrigin = myPos + tac.repositionGoal = goal + tac.repositionActive = true + tac.engageShotsNoEffect = 0 + tac.engageNoShotHalts = 0 + tac.engageTotalHaltSec = 0.0 + wto_sm_set_state(now, WTO_STATE_REPOSITION, goal, slot.spec.vMaxFwd * 0.92, staleShots ? "stale_no_effect" : (staleHalts ? "stale_no_shot" : "stale_halt_time"), distXZ, slot) + return true diff --git a/game-ai/ground/wto_ai_tactics_common.das b/game-ai/ground/wto_ai_tactics_common.das new file mode 100644 index 0000000..4023467 --- /dev/null +++ b/game-ai/ground/wto_ai_tactics_common.das @@ -0,0 +1,194 @@ +// Per-bot hull state machine orchestrator: strict priority arbitration across safety/repair, +// active cover retreat, ridge withdrawal, stalemate reposition, short-halt budget, dispersion, +// 3-way reload actions, and distance-tier x task-order movement/shooting. +options indenting = 2 +options no_global_heap = true +module wto_ai_tactics_common shared + +require ecs +require math +require %appGame.wtoai.wto_ai_config_common +require %appGame.wtoai.wto_ai_math_common +require %appGame.wtoai.wto_ai_order_common +require %appGame.wtoai.wto_ai_combat_types_common +require %appGame.wtoai.wto_ai_types_common +require %appGame.wtoai.wto_ai_terrain_common +require %appGame.wtoai.wto_ai_crowd_common +require %appGame.wtoai.wto_ai_cover_common +require %appGame.wtoai.wto_ai_tactics_actions_common + +[never_inline] +def private wto_sm_sync_engagement_counters(dt : float; var slot : WtoBotSlot&) + assume tac = slot.tactics + assume p = slot.perceive + if p.hasClearLos && !!p.targetEid && !p.targetIsAir && tac.engageTargetEid != p.targetEid + tac.engageTargetEid = p.targetEid + tac.engageShotsNoEffect = 0 + tac.engageNoShotHalts = 0 + tac.engageTotalHaltSec = 0.0 + if tac.state == WTO_STATE_SHORT_HALT + tac.engageTotalHaltSec += dt + +[never_inline] +def private wto_sm_handle_ridge(world : WtoWorldSnap const&; now : float; + myPos, threatDir : float3; distXZ : float; + var slot : WtoBotSlot&) : bool + assume tac = slot.tactics + if now < tac.withdrawUntil + wto_sm_set_state(now, WTO_STATE_RIDGE_WITHDRAW, tac.withdrawAnchor, max(2.2, slot.spec.vMaxRev), "ridge_hold", distXZ, slot) + return true + let backDir = wto_friendly_retreat_dir(world, slot.army, myPos, threatDir) + if !wto_terrain_is_exposed_ridge(myPos, threatDir, backDir) + tac.onExposedRidge = false + return false + if !tac.onExposedRidge + tac.onExposedRidge = true + tac.ridgeEnterAt = now + tac.ridgeShotsStart = slot.fire.shotCount + let dwellOver = (now - tac.ridgeEnterAt) >= WTO_AI_TERRAIN_RIDGE_MAX_DWELL_SEC + let shotsOver = (slot.fire.shotCount - tac.ridgeShotsStart) >= WTO_AI_TERRAIN_RIDGE_MAX_SHOTS + if dwellOver || shotsOver || slot.fire.pitchBlocked + let lat = float3(-backDir.z, 0.0, backDir.x) + let side = (uint(slot.eid) & 1u) == 0u ? 1.0 : -1.0 + var anc = myPos + backDir * WTO_AI_NAV_TAC_REV_DIST_M + lat * (side * 16.0) + anc = wto_clamp_battle_xz(anc, world.battleCenter, world.battleRadius, 40.0) + tac.withdrawAnchor = anc + tac.withdrawUntil = now + WTO_AI_NAV_TAC_REV_MAX_SEC + tac.onExposedRidge = false + slot.nav.ridgeWithdrawEvents++ + wto_sm_set_state(now, WTO_STATE_RIDGE_WITHDRAW, anc, max(2.2, slot.spec.vMaxRev), "ridge_withdraw", distXZ, slot) + return true + return false + +[never_inline] +def private wto_sm_continue_short_halt(now : float; myPos : float3; hasGroundTgt : bool; + distXZ : float; var slot : WtoBotSlot&) : bool + assume tac = slot.tactics + if tac.state != WTO_STATE_SHORT_HALT + return false + if slot.fire.shotCount > tac.haltStartShots || slot.fire.reloading + if slot.fire.shotCount > tac.haltStartShots + tac.engageShotsNoEffect += slot.fire.shotCount - tac.haltStartShots + tac.haltStartShots = slot.fire.shotCount + return false + if !hasGroundTgt || distXZ > WTO_AI_FC_MAX_RANGE_M + return false + let maxStop = slot.order.valid ? slot.order.maxStopRangeM : WTO_AI_FC_MAX_RANGE_M + if distXZ > maxStop + return false + if distXZ > WTO_AI_FC_LONG_RANGE_M && (slot.perceive.goodLosSec < WTO_AI_FC_LONG_WINDOW_SEC || slot.perceive.visiblePointCount < 2) + return false + if (now - tac.haltEnterAt) >= WTO_AI_SM_SHORT_HALT_MAX_SEC + tac.engageNoShotHalts++ + tac.shortHaltCooldownUntil = now + WTO_AI_SM_SHORT_HALT_COOLDOWN_SEC + return false + wto_sm_set_state(now, WTO_STATE_SHORT_HALT, myPos, 0.0, "halt_continue", distXZ, slot) + return true + +[never_inline] +def private wto_sm_handle_dispersion(world : WtoWorldSnap const&; now : float; + myPos, threatDir : float3; distXZ : float; + var slot : WtoBotSlot&; var crowdSummary : WtoCrowdSummary&) : bool + assume tac = slot.tactics + if distXZ <= WTO_AI_FC_CLOSE_RANGE_M + return false + if now < tac.disperseUntil && wto_xz_dist_sq(myPos, tac.disperseGoal) > 25.0 + wto_sm_set_state(now, WTO_STATE_DISPERSE, tac.disperseGoal, slot.spec.vMaxFwd * 0.85, "disperse_hold", distXZ, slot) + return true + if !slot.crowd.isCrowded + return false + tac.disperseGoal = wto_crowd_pick_disperse_pos(world, slot.army, slot.eid, myPos, threatDir, slot.crowd) + tac.disperseUntil = now + WTO_AI_CROWD_DISPERSE_HOLD_SEC + crowdSummary.disperseEvents++ + wto_sm_set_state(now, WTO_STATE_DISPERSE, tac.disperseGoal, slot.spec.vMaxFwd * 0.85, "disperse_start", distXZ, slot) + return true + +[never_inline] +def private wto_sm_march_speed(slot : WtoBotSlot const&; distGoal : float) : float + if distGoal <= 8.0 + return 0.0 + let capScale = slot.order.cautious ? 0.78 : 0.98 + return distGoal < 24.0 ? min(slot.spec.vMaxFwd * 0.55, 6.0) : (slot.spec.vMaxFwd * capScale) + +[never_inline] +def private wto_sm_handle_combat(world : WtoWorldSnap const&; now : float; + myPos, hullFwd, threatPos, baseGoal : float3; + distXZ, distGoal : float; var slot : WtoBotSlot&) : bool + assume tac = slot.tactics + assume fc = slot.fire + let marchSpd = wto_sm_march_speed(slot, distGoal) + if fc.reloading + return wto_sm_start_reload_action(world, now, myPos, hullFwd, threatPos, baseGoal, distXZ, distGoal, slot) + if distXZ <= WTO_AI_FC_CLOSE_RANGE_M + let closeSpd = slot.spec.hasVertStab ? (slot.spec.vMaxFwd * 0.92) : min(slot.spec.vMaxFwd * 0.65, WTO_AI_FC_MID_SLOW_MAX_MPS) + wto_sm_set_state(now, WTO_STATE_RUN_AND_GUN, baseGoal, max(2.5, closeSpd), "close_run_gun", distXZ, slot) + return true + let urgentPush = slot.order.urgency == WTO_URGENCY_HIGH || distGoal > 130.0 + if distXZ <= WTO_AI_FC_MID_RANGE_M && urgentPush + let slowCap = min(slot.spec.vMaxFwd * WTO_AI_FC_MID_SLOW_RATIO, WTO_AI_FC_MID_SLOW_MAX_MPS) + wto_sm_set_state(now, WTO_STATE_RUN_AND_GUN, baseGoal, max(2.2, slowCap), "mid_slow_fire", distXZ, slot) + return true + let maxStop = slot.order.valid ? slot.order.maxStopRangeM : WTO_AI_FC_MAX_RANGE_M + if distXZ > maxStop || distXZ > WTO_AI_FC_MAX_RANGE_M || tac.repositionActive + return false + if distXZ > WTO_AI_FC_LONG_RANGE_M && (slot.perceive.goodLosSec < WTO_AI_FC_LONG_WINDOW_SEC || slot.perceive.visiblePointCount < 2) + return false + if now < tac.shortHaltCooldownUntil + return false + let aimReady = fc.gunReady && (fc.lastAimErrDeg <= WTO_AI_SM_PREAIM_DEG || slot.spec.isLimitedTraverse) + if !aimReady + wto_sm_set_state(now, WTO_STATE_PREAIM, baseGoal, marchSpd, "preaim_move", distXZ, slot) + return true + wto_sm_set_state(now, WTO_STATE_SHORT_HALT, myPos, 0.0, "short_halt_ready", distXZ, slot) + return true + +[never_inline] +def public wto_tactics_update(world : WtoWorldSnap const&; now, dt : float; + myPos, rawHullFwd : float3; isBurn : bool; + repairRemainingSec : float; + var slot : WtoBotSlot&; var crowdSummary : WtoCrowdSummary&) + let hullFwd = wto_xz_normalize(rawHullFwd, float3(1.0, 0.0, 0.0)) + let baseGoal = slot.order.valid ? slot.order.goalPos : world.battleCenter + let distGoal = sqrt(wto_xz_dist_sq(myPos, baseGoal)) + if !WTO_AI_LAYER_TACTICS + wto_sm_set_state(now, WTO_STATE_MARCH, slot.order.valid ? slot.order.goalPos : myPos, slot.spec.vMaxFwd * 0.9, "layer_off", 9999.0, slot) + return + assume p = slot.perceive + let hasGroundTgt = p.hasClearLos && !!p.targetEid && !p.targetIsAir + let distXZ = hasGroundTgt ? sqrt(wto_xz_dist_sq(myPos, p.knownPos)) : 9999.0 + let threatPos = !!p.targetEid ? p.knownPos : baseGoal + let threatDir = wto_xz_normalize(threatPos - myPos, hullFwd) + + wto_sm_sync_engagement_counters(dt, slot) + wto_cover_update_memory(world, now, myPos, slot) + if wto_sm_handle_disabled_and_repair(world, now, myPos, threatPos, threatDir, isBurn, repairRemainingSec, distXZ, slot) + return + if wto_sm_continue_cover_retreat(world, now, myPos, threatPos, distXZ, slot) + return + if wto_sm_handle_ridge(world, now, myPos, threatDir, distXZ, slot) + return + if wto_sm_handle_reposition(world, now, myPos, threatDir, baseGoal, distXZ, slot) + return + if wto_sm_continue_short_halt(now, myPos, hasGroundTgt, distXZ, slot) + return + if wto_sm_handle_dispersion(world, now, myPos, threatDir, distXZ, slot, crowdSummary) + return + if hasGroundTgt && wto_sm_handle_combat(world, now, myPos, hullFwd, threatPos, baseGoal, distXZ, distGoal, slot) + return + if slot.fire.reloading && !!p.targetEid && (now - p.lastSeenAt) <= WTO_AI_TACTICS_MEMORY_TTL_SEC + if wto_sm_start_reload_action(world, now, myPos, hullFwd, threatPos, baseGoal, distXZ, distGoal, slot) + return + // Stationary overwatch/defend bots hold their firing post briefly to watch the enemy's last exit point; + // marching/pushing bots keep advancing while the turret watches. + if !hasGroundTgt && now < p.watchUntil && slot.order.urgency != WTO_URGENCY_HIGH && distGoal <= 35.0 + wto_sm_set_state(now, WTO_STATE_MARCH, myPos, 0.0, "watch_last_exit", distXZ, slot) + return + // Hold at the 40% rally staging point until the group launches (unless threatened inside 300 m). + if slot.order.rallyHold && slot.order.routeRelayValid && distXZ > WTO_AI_FC_MID_RANGE_M + let rallyHoldRad = max(18.0, WTO_AI_CMD_RALLY_RADIUS_M * 0.55) + if wto_xz_dist_sq(myPos, slot.order.routeRelayPos) <= rallyHoldRad * rallyHoldRad + wto_sm_set_state(now, WTO_STATE_MARCH, myPos, 0.0, "rally_wait", distXZ, slot) + return + let marchSpd = wto_sm_march_speed(slot, distGoal) + let marchGoal = distGoal <= 8.0 ? myPos : baseGoal + wto_sm_set_state(now, WTO_STATE_MARCH, marchGoal, marchSpd, "march_task", distXZ, slot) diff --git a/game-ai/ground/wto_ai_terrain_common.das b/game-ai/ground/wto_ai_terrain_common.das new file mode 100644 index 0000000..88bbfe0 --- /dev/null +++ b/game-ai/ground/wto_ai_terrain_common.das @@ -0,0 +1,261 @@ +// 3D terrain, foliage-filtered obstacle raycasting, cliff drop-off lookahead, exposed high-ground +// ridge detection, and smoke/foliage-filtered line-of-sight checks. +options indenting = 2 +options no_global_heap = true +module wto_ai_terrain_common shared + +require ecs +require math +require strings +require DagorMath +require Mission +require Dacoll +require RendInst +require PhysMat +require SmokeOccluder +require %appGame.wtoai.wto_ai_config_common +require %appGame.wtoai.wto_ai_math_common +require %appGame.wtoai.wto_ai_types_common + +let private TERRAIN_STATIC_MASK = ETF_STRUCTURES | ETF_FRT +let private TERRAIN_GROUND_MASK = ETF_LMESH | ETF_HEIGHTMAP | ETF_STRUCTURES | ETF_FRT +let private TERRAIN_LOS_MASK = ETF_LMESH | ETF_HEIGHTMAP | ETF_STRUCTURES | ETF_FRT + +[never_inline] +def private wto_ri_is_soft_foliage(name : string) : bool + if empty(name) + return false + if (find(name, "house") >= 0 || find(name, "building") >= 0 || find(name, "bridge") >= 0 || + find(name, "wall") >= 0 || find(name, "bunker") >= 0 || find(name, "rock") >= 0 || + find(name, "cliff") >= 0 || find(name, "stone") >= 0 || find(name, "concrete") >= 0 || + find(name, "brick") >= 0 || find(name, "container") >= 0 || find(name, "wagon") >= 0 || + find(name, "train") >= 0 || find(name, "pillar") >= 0 || find(name, "barricade") >= 0) + return false + return (starts_with(name, "tree_") || find(name, "_tree_") >= 0 || starts_with(name, "bush_") || + find(name, "_bush_") >= 0 || starts_with(name, "shrub_") || find(name, "_shrub_") >= 0 || + starts_with(name, "hedge_") || find(name, "_hedge_") >= 0 || starts_with(name, "genus_") || + find(name, "_pine_") >= 0 || find(name, "_oak_") >= 0 || find(name, "_birch_") >= 0 || + find(name, "_spruce_") >= 0 || find(name, "_palm_") >= 0 || find(name, "_reed_") >= 0 || + find(name, "lamp") >= 0 || find(name, "fence_wood") >= 0 || find(name, "wooden_fence") >= 0 || + find(name, "sign_") >= 0 || find(name, "bench") >= 0 || find(name, "hay") >= 0) + +[never_inline] +def public wto_terrain_ri_is_hard(desc : RendInstDesc const&; acceptInvalid : bool = false) : bool + if desc.isValid && desc.isRiExtra && desc.riExtraHandle != RIEX_HANDLE_NULL + let handle = desc.riExtraHandle + let poolId = uint(handle_to_ri_type(handle)) + if rendinst_isRIExtraGenPosInst(poolId) + return false + let initHp = riex_getInitialHP(handle) + let isWall = riex_isWalls(poolId) + let immortal = riex_isImmortal(poolId) + if !isWall && wto_ri_is_soft_foliage(riex_getRIGenExtraName(poolId)) + return false + if immortal || riex_isInvincible(handle) || isWall || initHp >= 250.0 + return true + let bsphRad = riex_getBsphRad(poolId) + return bsphRad >= 1.65 && initHp >= 65.0 + if !desc.isValid + return acceptInvalid + if rendinst_isRIGenPosInst(desc) || wto_ri_is_soft_foliage(getRIGenResName(desc)) + return false + if !rendinst_isRIGenDestr(desc) + return true + let box = getRIGenBBox(desc) + let ext = box.boxMax - box.boxMin + return max(ext.x, ext.z) >= 2.2 && ext.y >= 1.4 + +[never_inline] +def public wto_terrain_hard_ray(startPos, dir : float3; maxRange : float) : float + if maxRange <= 0.0 + return 0.0 + var structDist = maxRange + var sTraveled = 0.0 + for _hop in range(0, 4) + var hitD = maxRange - sTraveled + if hitD <= 0.0 + break + var mat = PHYSMAT_INVALID + var norm = float3(0.0) + var desc = RendInstDesc() + let origin = startPos + dir * sTraveled + if !traceray_normalized(origin, dir, hitD, mat, norm, TERRAIN_STATIC_MASK, desc, PHYSMAT_INVALID) + break + if norm.y < 0.72 + structDist = clamp(sTraveled + hitD, 0.0, maxRange) + break + sTraveled += max(0.0, hitD) + 0.5 + var traveled = 0.0 + for _hop in range(0, 4) + var hitDist = structDist - traveled + if hitDist <= 0.0 + break + var mat = PHYSMAT_INVALID + var norm = float3(0.0) + var desc = RendInstDesc() + let origin = startPos + dir * traveled + if !traceray_normalized(origin, dir, hitDist, mat, norm, ETF_RI | ETF_RI_PHYS, desc, PHYSMAT_INVALID) + break + if norm.y < 0.72 && wto_terrain_ri_is_hard(desc, true) + return clamp(traveled + hitDist, 0.0, structDist) + traveled += max(0.0, hitDist) + 0.35 + return structDist + +[never_inline] +def private wto_trace_bridge_deck(refY, testX, testZ, maxUp, maxDown : float; + var outY, outNormY : float&) : bool + let topY = refY + min(maxUp, 2.8) + 0.45 + let span = max(0.5, topY - (refY - maxDown - 0.5)) + var traveled = 0.0 + let downDir = float3(0.0, -1.0, 0.0) + for _hop in range(0, 4) + var hitD = span - traveled + if hitD <= 0.0 + break + var mat = PHYSMAT_INVALID + var norm = float3(0.0) + var desc = RendInstDesc() + let origin = float3(testX, topY - traveled, testZ) + if !traceray_normalized(origin, downDir, hitD, mat, norm, ETF_RI | ETF_RI_PHYS, desc, PHYSMAT_INVALID) + break + let hitY = topY - traveled - max(0.0, hitD) + if hitY > refY + maxUp || !wto_terrain_ri_is_hard(desc, false) + traveled += max(0.0, hitD) + 0.35 + continue + outY = hitY + outNormY = norm.y + return true + return false + +[never_inline] +def public wto_terrain_drivable_yn(refPos : float3; testX, testZ : float; + var outGroundY, outNormY : float&) : bool + outGroundY = refPos.y + outNormY = 1.0 + let horizDist = max(1.0, sqrt(wto_sq(testX - refPos.x) + wto_sq(testZ - refPos.z))) + let climbTan = tan(WTO_AI_TERRAIN_MAX_CLIMB_DEG * WTO_DEG_TO_RAD) + let dropTan = tan(WTO_AI_TERRAIN_MAX_DROP_DEG * WTO_DEG_TO_RAD) + let maxUp = min(3.6, horizDist * climbTan + 0.38) + let maxDown = min(3.0, horizDist * dropTan + 0.35) + let probeTop = float3(testX, refPos.y + min(max(2.2, maxUp + 0.6), 3.0), testZ) + var drop = max(7.0, maxDown + 4.5) + var baseNorm = float3(0.0, 1.0, 0.0) + let baseHit = tracedown_normalized(probeTop, drop, baseNorm, TERRAIN_GROUND_MASK) + let baseY = probeTop.y - drop + var riY = 0.0 + var riNormY = 0.0 + let riHit = wto_trace_bridge_deck(refPos.y, testX, testZ, maxUp, maxDown, riY, riNormY) + var ok = false + if riHit && riY <= refPos.y + maxUp && riY >= refPos.y - maxDown && riNormY >= 0.68 + if !baseHit || riY > baseY + 0.15 || baseNorm.y < 0.82 + outGroundY = riY + outNormY = riNormY + ok = true + let minNormY = cos(max(WTO_AI_TERRAIN_MAX_CLIMB_DEG, WTO_AI_TERRAIN_MAX_DROP_DEG) * WTO_DEG_TO_RAD) + if !ok && baseHit && refPos.y - baseY <= maxDown && baseY - refPos.y <= maxUp && baseNorm.y >= minNormY + outGroundY = baseY + outNormY = baseNorm.y + ok = true + if !ok + return false + let waterProbe = float3(testX, outGroundY + 0.5, testZ) + var waterY = 0.0 + if traceht_water(waterProbe, waterY) && waterY - outGroundY > WTO_AI_TERRAIN_MAX_WATER_M + return false + return true + +[never_inline] +def public wto_terrain_drivable_y(refPos : float3; testX, testZ : float; var outGroundY : float&) : bool + var ny = 1.0 + return wto_terrain_drivable_yn(refPos, testX, testZ, outGroundY, ny) + +[never_inline] +def public wto_terrain_point_valid(army : int; var pt : float3&) : bool + let checkPt = pt + if !das_is_in_battle_area(checkPt, true, army, 0.0, false, false) + return false + let probeTop = float3(pt.x, pt.y + 80.0, pt.z) + var drop = 220.0 + var norm = float3(0.0, 1.0, 0.0) + if !tracedown_normalized(probeTop, drop, norm, TERRAIN_GROUND_MASK) || norm.y < 0.82 + return false + let gy = probeTop.y - drop + let waterProbe = float3(pt.x, gy + 0.5, pt.z) + var waterY = 0.0 + if traceht_water(waterProbe, waterY) && waterY - gy > WTO_AI_TERRAIN_MAX_WATER_M + return false + pt.y = gy + return true + +// Detect sheer cliff drop-offs or deep water beyond an uphill/flat crest along `dirXZ`. +[never_inline] +def public wto_terrain_has_cliff_ahead(startPos, dirXZ : float3; lookaheadM : float) : bool + let dir = wto_xz_normalize(dirXZ, float3(1.0, 0.0, 0.0)) + let stepM = 3.5 + let steps = clamp(int(lookaheadM / stepM), 2, 10) + let dropTan = tan(WTO_AI_TERRAIN_MAX_DROP_DEG * WTO_DEG_TO_RAD) + let minDropNormY = cos((WTO_AI_TERRAIN_MAX_DROP_DEG + 4.0) * WTO_DEG_TO_RAD) + var curY = startPos.y + var peakY = startPos.y + for s in range(1, steps + 1) + let d = float(s) * stepM + let tx = startPos.x + dir.x * d + let tz = startPos.z + dir.z * d + let top = float3(tx, curY + 4.0, tz) + var drop = 18.0 + var norm = float3(0.0, 1.0, 0.0) + if !tracedown_normalized(top, drop, norm, TERRAIN_GROUND_MASK) + return true + let gy = top.y - drop + var deckY = 0.0 + var deckNormY = 0.0 + if wto_trace_bridge_deck(curY, tx, tz, 3.0, 3.0, deckY, deckNormY) && deckNormY >= 0.72 && deckY > gy + 0.3 + curY = deckY + peakY = max(peakY, deckY) + continue + let stepDrop = curY - gy + if stepDrop > stepM * dropTan + 0.48 + return true + if stepDrop > 0.8 && norm.y < minDropNormY + return true + if peakY - gy > 2.6 && norm.y < 0.80 + return true + let wProbe = float3(tx, gy + 0.5, tz) + var wY = 0.0 + if traceht_water(wProbe, wY) && wY - gy > WTO_AI_TERRAIN_MAX_WATER_M + return true + curY = gy + peakY = max(peakY, gy) + return false + +// True when perched on an elevated plateau/ridge whose enemy-facing edge drops off into a cliff +// while the friendly rear has a drivable gentler back-slope. +[never_inline] +def public wto_terrain_is_exposed_ridge(pos, threatDirXZ, backDirXZ : float3) : bool + if !wto_terrain_has_cliff_ahead(pos, threatDirXZ, WTO_AI_TERRAIN_CREST_LOOKAHEAD_M) + return false + let bDir = wto_xz_normalize(backDirXZ, -wto_xz_normalize(threatDirXZ, float3(1.0, 0.0, 0.0))) + var backY = pos.y + let bx = pos.x + bDir.x * 10.0 + let bz = pos.z + bDir.z * 10.0 + if !wto_terrain_drivable_y(pos, bx, bz, backY) + return false + return backY <= pos.y + 1.4 + +// Foliage-ignoring LOS check: blocks on terrain, buildings, smoke screens, and hard RendInsts, +// while seeing cleanly through soft bushes/leaves without 4 Hz aim flicker. +[never_inline] +def public wto_terrain_los_clear(fromPos, toPos : float3) : bool + let delta = toPos - fromPos + let dist = length(delta) + if dist <= 1.5 + return true + let dir = delta / dist + let traceLen = max(0.5, dist - 1.2) + var p0 = fromPos + var p1 = toPos + if rayhit_smoke_occluders(p0, p1) + return false + if rayhit_normalized(p0, dir, traceLen, TERRAIN_LOS_MASK, -1) + return false + return wto_terrain_hard_ray(p0, dir, traceLen) >= traceLen - 0.25 diff --git a/game-ai/ground/wto_ai_types_common.das b/game-ai/ground/wto_ai_types_common.das new file mode 100644 index 0000000..6835707 --- /dev/null +++ b/game-ai/ground/wto_ai_types_common.das @@ -0,0 +1,280 @@ +// Shared zero-heap POD data structures and domain constants for WTOffline's ground AI pipeline. +options indenting = 2 +options no_global_heap = true +module wto_ai_types_common shared + +require ecs +require %appGame.wtoai.wto_ai_order_common +require %appGame.wtoai.wto_ai_combat_types_common + +let public WTO_MAX_BOTS = 64 +let public WTO_MAX_UNITS = 96 +let public WTO_MAX_WRECKS = 64 +let public WTO_MAX_CAPS = 8 +let public WTO_MAX_PATH_PTS = 32 +let public WTO_MAX_DEATHS = 32 +let public WTO_MAX_JAMS = 24 +let public WTO_MAX_RADIO = 24 + +let public WTO_ROLE_MEDIUM = 0 +let public WTO_ROLE_LIGHT = 1 +let public WTO_ROLE_HEAVY = 2 +let public WTO_ROLE_TD = 3 +let public WTO_ROLE_SPAA = 4 + +let public WTO_STATE_MARCH = 0 +let public WTO_STATE_RUN_AND_GUN = 1 +let public WTO_STATE_PREAIM = 2 +let public WTO_STATE_SHORT_HALT = 3 +let public WTO_STATE_RETREAT_COVER = 4 +let public WTO_STATE_COVER_RELOAD = 5 +let public WTO_STATE_RELOAD_ADVANCE = 6 +let public WTO_STATE_HULL_ANGLE = 7 +let public WTO_STATE_REPOSITION = 8 +let public WTO_STATE_DISABLED = 9 +let public WTO_STATE_DISPERSE = 10 +let public WTO_STATE_RIDGE_WITHDRAW = 11 + +let public WTO_DRIVE_HALT = 0 +let public WTO_DRIVE_CRUISE = 1 +let public WTO_DRIVE_PIVOT = 2 +let public WTO_DRIVE_REVERSE = 3 + +[safe_when_uninitialized] +struct public WtoVehicleSpec + ready : bool = false + role : int = 0 + hasVertStab : bool = false + isLimitedTraverse : bool = false + yawLimitDeg : float = 180.0 + minPitchDeg : float = -8.0 + maxPitchDeg : float = 22.0 + turretYawSpd : float = 24.0 + turretPitchSpd : float = 8.0 + muzzleSpeedMps : float = 880.0 + shellDragCx : float = 0.35 + shellMassKg : float = 10.0 + shellCaliberM : float = 0.09 + shellCount : int = 0 + shells : WtoShellProfile[12] + isAutocannonBelt : bool = false + isPureLauncher : bool = false + halfLen : float = 3.4 + halfWid : float = 1.75 + isTracked : bool = true + canPivot : bool = false + vMaxFwd : float = 13.5 + vMaxRev : float = 3.2 + +[safe_when_uninitialized] +struct public WtoUnitSnap + eid : EntityId = INVALID_ENTITY_ID + army : int = 0 + pos : float3 = float3(0.0, 0.0, 0.0) + vel : float3 = float3(0.0, 0.0, 0.0) + hullFwd : float3 = float3(1.0, 0.0, 0.0) + halfLen : float = 3.4 + halfWid : float = 1.75 + engineRpm : float = 0.0 + isAlive : bool = false + isGround : bool = false + isAir : bool = false + isLightTag : bool = false + isShooting : bool = false + isBurn : bool = false + isHuman : bool = false + +[safe_when_uninitialized] +struct public WtoWreckSnap + eid : EntityId = INVALID_ENTITY_ID + pos : float3 = float3(0.0, 0.0, 0.0) + halfLen : float = 3.4 + halfWid : float = 1.75 + +[safe_when_uninitialized] +struct public WtoCapSnap + zoneId : int = -1 + center : float3 = float3(0.0, 0.0, 0.0) + radius : float = 25.0 + ownerArmy : int = 0 + progress : float = 0.0 + contested : bool = false + +[safe_when_uninitialized] +struct public WtoDeathEvent + pos : float3 = float3(0.0, 0.0, 0.0) + army : int = 0 + at : float = -100.0 + +[safe_when_uninitialized] +struct public WtoJamZone + pos : float3 = float3(0.0, 0.0, 0.0) + untilAt : float = -100.0 + hits : int = 0 + +[safe_when_uninitialized] +struct public WtoRadioSpot + pos : float3 = float3(0.0, 0.0, 0.0) + army : int = 0 + targetEid : EntityId = INVALID_ENTITY_ID + untilAt : float = -100.0 + +[safe_when_uninitialized] +struct public WtoWorldSnap + valid : bool = false + time : float = 0.0 + matchStartAt : float = -100.0 + unitCount : int = 0 + units : WtoUnitSnap[96] + wreckCount : int = 0 + wrecks : WtoWreckSnap[64] + deadIdCursor : int = 0 + recordedDeadEids : EntityId[64] + battleMode : int = 0 + zoneVersion : int = 0 + capCount : int = 0 + caps : WtoCapSnap[8] + nextCapRefreshAt : float = -100.0 + battleCenter : float3 = float3(0.0, 0.0, 0.0) + battleRadius : float = 0.0 + teamSpawnFromPoints : bool[3] + teamSpawnValid : bool[3] + teamSpawnCenter : float3[3] + deathCursor : int = 0 + deaths : WtoDeathEvent[32] + jamCursor : int = 0 + jams : WtoJamZone[24] + radioCursor : int = 0 + radioSpots : WtoRadioSpot[24] + +[safe_when_uninitialized] +struct public WtoCrowdInfo + nearestAllyEid : EntityId = INVALID_ENTITY_ID + nearestAllyDistM : float = 999.0 + nearPersonalCount : int = 0 + clusterAllyCount : int = 0 + repulseDirXZ : float3 = float3(0.0, 0.0, 0.0) + isCrowded : bool = false + +[safe_when_uninitialized] +struct public WtoCrowdSummary + crowdedBotCount : int = 0 + maxClusterSize : int = 1 + minPairDistM : float = 999.0 + disperseEvents : int = 0 + +[safe_when_uninitialized] +struct public WtoTacticsState + state : int = 0 + stateEnteredAt : float = -100.0 + moveGoal : float3 = float3(0.0, 0.0, 0.0) + desiredSpeedMps : float = 10.0 + haltEnterAt : float = -100.0 + haltStartShots : int = 0 + shortHaltCooldownUntil : float = -100.0 + immobilized : bool = false + lastCoverPos : float3 = float3(0.0, 0.0, 0.0) + lastCoverValid : bool = false + lastCoverAt : float = -100.0 + retreatTarget : float3 = float3(0.0, 0.0, 0.0) + retreatUntil : float = -100.0 + retreatReverse : bool = false + hullAngleDir : float3 = float3(1.0, 0.0, 0.0) + repositionGoal : float3 = float3(0.0, 0.0, 0.0) + repositionOrigin : float3 = float3(0.0, 0.0, 0.0) + repositionActive : bool = false + engageTargetEid : EntityId = INVALID_ENTITY_ID + engageShotsNoEffect : int = 0 + engageNoShotHalts : int = 0 + engageTotalHaltSec : float = 0.0 + lastEffectAt : float = -100.0 + repairCoverGoal : float3 = float3(0.0, 0.0, 0.0) + repairCoverValid : bool = false + spaaYieldAir : bool = false + onExposedRidge : bool = false + ridgeEnterAt : float = -100.0 + ridgeShotsStart : int = 0 + withdrawAnchor : float3 = float3(0.0, 0.0, 0.0) + withdrawUntil : float = -100.0 + disperseGoal : float3 = float3(0.0, 0.0, 0.0) + disperseUntil : float = -100.0 + +[safe_when_uninitialized] +struct public WtoRouteState + corridor : float3[32] + corridorLen : int = 0 + corridorIdx : int = 0 + corridorGoal : float3 = float3(0.0, 0.0, 0.0) + nextReplanAt : float = -100.0 + nextShortcutAt : float = -100.0 + wingInit : bool = false + wingSign : int = 0 + laneOffsetM : float = 0.0 + wingCapIdx : int = -2 + wingRelayPos : float3 = float3(0.0, 0.0, 0.0) + wingRelayValid : bool = false + shortcutPos : float3 = float3(0.0, 0.0, 0.0) + shortcutValid : bool = false + detourPos : float3 = float3(0.0, 0.0, 0.0) + detourValid : bool = false + detourUntil : float = -100.0 + detourCount : int = 0 + lastStartOk : bool = false + lastGoalOk : bool = false + +[safe_when_uninitialized] +struct public WtoNavState + steerDir : float3 = float3(1.0, 0.0, 0.0) + frontClearM : float = 30.0 + rearClearM : float = 16.0 + cliffAhead : bool = false + stuckOrigin : float3 = float3(0.0, 0.0, 0.0) + stuckCheckAt : float = -100.0 + reverseAnchor : float3 = float3(0.0, 0.0, 0.0) + reverseUntil : float = -100.0 + reverseCount : int = 0 + ridgeWithdrawEvents : int = 0 + +[safe_when_uninitialized] +struct public WtoDriveCmd + valid : bool = false + mode : int = 0 + targetPos : float3 = float3(0.0, 0.0, 0.0) + desiredDir : float3 = float3(1.0, 0.0, 0.0) + speedMps : float = 0.0 + frontClearM : float = 30.0 + rearClearM : float = 16.0 + +[safe_when_uninitialized] +struct public WtoDriveState + routeBOwned : bool = false + routeAFallback : bool = false + failLogged : bool = false + nextControlRequestAt : float = -1.0 + deadEchoSec : float = 0.0 + prevYaw : float = 0.0 + prevYawAt : float = -100.0 + omegaYawRad : float = 0.0 + prevThr : float = 0.0 + prevStr : float = 0.0 + lastVFwd : float = 0.0 + +[safe_when_uninitialized] +struct public WtoBotSlot + used : bool = false + eid : EntityId = INVALID_ENTITY_ID + army : int = 0 + lastSeenAt : float = -100.0 + prepared : bool = false + nextTacticsAt : float = -100.0 + nextNavAt : float = -100.0 + spec : WtoVehicleSpec = WtoVehicleSpec() + crowd : WtoCrowdInfo = WtoCrowdInfo() + order : WtoTaskOrder = WtoTaskOrder() + perceive : WtoPerceiveState = WtoPerceiveState() + tactics : WtoTacticsState = WtoTacticsState() + route : WtoRouteState = WtoRouteState() + nav : WtoNavState = WtoNavState() + driveCmd : WtoDriveCmd = WtoDriveCmd() + drive : WtoDriveState = WtoDriveState() + fire : WtoFireState = WtoFireState() diff --git a/game-ai/ground/wto_ai_world_common.das b/game-ai/ground/wto_ai_world_common.das new file mode 100644 index 0000000..475be20 --- /dev/null +++ b/game-ai/ground/wto_ai_world_common.das @@ -0,0 +1,197 @@ +// World observation layer: builds one flat per-frame snapshot of units, wrecks, +// capture zones, respawn anchors, and ring buffers for deaths, jams, and radio spots. +options indenting = 2 +options no_global_heap = true +module wto_ai_world_common shared + +require ecs +require math +require DagorMath +require Unit +require IGroundModel +require HeavyVehicleModel +require %appGame.wtoai.wto_ai_math_common +require %appGame.wtoai.wto_ai_order_common +require %appGame.wtoai.wto_ai_types_common +require %appGame.wtoai.wto_ai_world_zones_common + +[never_inline] +def public wto_world_reset(var snap : WtoWorldSnap&) + snap.valid = false + snap.time = 0.0 + snap.matchStartAt = -100.0 + snap.unitCount = 0 + snap.wreckCount = 0 + snap.deadIdCursor = 0 + snap.battleMode = WTO_MODE_UNKNOWN + snap.zoneVersion = 0 + snap.capCount = 0 + snap.nextCapRefreshAt = -100.0 + snap.battleCenter = float3(0.0, 0.0, 0.0) + snap.battleRadius = 0.0 + snap.deathCursor = 0 + snap.jamCursor = 0 + snap.radioCursor = 0 + for a in range(3) + snap.teamSpawnFromPoints[a] = false + snap.teamSpawnValid[a] = false + snap.teamSpawnCenter[a] = float3(0.0, 0.0, 0.0) + for i in range(WTO_MAX_WRECKS) + snap.recordedDeadEids[i] = INVALID_ENTITY_ID + for i in range(WTO_MAX_DEATHS) + snap.deaths[i] = WtoDeathEvent() + for i in range(WTO_MAX_JAMS) + snap.jams[i] = WtoJamZone() + for i in range(WTO_MAX_RADIO) + snap.radioSpots[i] = WtoRadioSpot() + +[never_inline] +def public wto_world_record_death(var snap : WtoWorldSnap&; eid : EntityId; army : int; pos : float3; now : float) + if !wto_is_finite3(pos) + return + if !!eid + for i in range(WTO_MAX_WRECKS) + if snap.recordedDeadEids[i] == eid + return + snap.recordedDeadEids[snap.deadIdCursor % WTO_MAX_WRECKS] = eid + snap.deadIdCursor = (snap.deadIdCursor + 1) % 100000 + let idx = snap.deathCursor % WTO_MAX_DEATHS + snap.deaths[idx].pos = pos + snap.deaths[idx].army = army + snap.deaths[idx].at = now + snap.deathCursor = (snap.deathCursor + 1) % 100000 + +[never_inline] +def public wto_world_record_jam(var snap : WtoWorldSnap&; pos : float3; now : float) + if !wto_is_finite3(pos) + return + for i in range(WTO_MAX_JAMS) + if snap.jams[i].untilAt > now && wto_xz_dist_sq(snap.jams[i].pos, pos) <= 324.0 + snap.jams[i].pos = lerp(snap.jams[i].pos, pos, 0.35) + snap.jams[i].untilAt = now + 26.0 + snap.jams[i].hits = min(snap.jams[i].hits + 1, 12) + return + let idx = snap.jamCursor % WTO_MAX_JAMS + snap.jams[idx].pos = pos + snap.jams[idx].untilAt = now + 24.0 + snap.jams[idx].hits = 1 + snap.jamCursor = (snap.jamCursor + 1) % 100000 + +[never_inline] +def public wto_world_active_jams(snap : WtoWorldSnap const&; now : float) : int + var cnt = 0 + for i in range(WTO_MAX_JAMS) + if snap.jams[i].untilAt > now + cnt++ + return cnt + +[never_inline] +def public wto_world_jam_penalty(snap : WtoWorldSnap const&; pt : float3; now : float) : float + var pen = 0.0 + for i in range(WTO_MAX_JAMS) + if snap.jams[i].untilAt <= now + continue + let dSq = wto_xz_dist_sq(pt, snap.jams[i].pos) + if dSq < 676.0 + let frac = 1.0 - sqrt(dSq) / 26.0 + pen += frac * (16.0 + float(snap.jams[i].hits) * 4.0) + return pen + +[never_inline] +def public wto_world_broadcast_radio(var snap : WtoWorldSnap&; army : int; + targetEid : EntityId; pos : float3; now : float) + for i in range(WTO_MAX_RADIO) + if snap.radioSpots[i].untilAt > now && snap.radioSpots[i].army == army && snap.radioSpots[i].targetEid == targetEid + snap.radioSpots[i].pos = pos + snap.radioSpots[i].untilAt = now + 14.0 + return + let idx = snap.radioCursor % WTO_MAX_RADIO + snap.radioSpots[idx].pos = pos + snap.radioSpots[idx].army = army + snap.radioSpots[idx].targetEid = targetEid + snap.radioSpots[idx].untilAt = now + 14.0 + snap.radioCursor = (snap.radioCursor + 1) % 100000 + +[never_inline] +def public wto_world_find_unit(snap : WtoWorldSnap const&; eid : EntityId) : int + if !eid + return -1 + for i in range(snap.unitCount) + if snap.units[i].eid == eid + return i + return -1 + +[never_inline] +def private wto_record_wreck_once(var snap : WtoWorldSnap&; eid : EntityId; u : Unit const?; gm : IGroundModel const?) + if gm == null || snap.wreckCount >= WTO_MAX_WRECKS + return + let box = gm.bodyBoundingBox + let wIdx = snap.wreckCount + snap.wrecks[wIdx].eid = eid + snap.wrecks[wIdx].pos = u.pos + snap.wrecks[wIdx].halfLen = max(2.0, max(abs(box.boxMin.x), abs(box.boxMax.x))) + snap.wrecks[wIdx].halfWid = max(1.1, max(abs(box.boxMin.z), abs(box.boxMax.z))) + snap.wreckCount = wIdx + 1 + +[never_inline] +def private wto_refresh_units(var snap : WtoWorldSnap&) + snap.unitCount = 0 + snap.wreckCount = 0 + let maxDistSq = wto_sq(max(snap.battleRadius * 2.5, 2200.0)) + query() <| $ [es] (eid : EntityId; unit__ref : UnitRef) + let u = unit__ref.unit + if u == null || u.isDelayed + return + let gm = as_gm(u) + if snap.battleRadius > 1.0 && gm != null && wto_xz_dist_sq(u.pos, snap.battleCenter) > maxDistSq + return + if !u.isAlive + wto_record_wreck_once(snap, eid, u, gm) + return + if snap.unitCount >= WTO_MAX_UNITS + return + let army = int(u.army) + if army != 1 && army != 2 + return + let isGround = gm != null && gm.moveSys != null && as_hv(u) != null + let isAir = u.isFlightModelWrap + if !isGround && !isAir + return + var halfLen = 3.4 + var halfWid = 1.75 + if gm != null + let box = gm.bodyBoundingBox + halfLen = max(1.8, max(abs(box.boxMin.x), abs(box.boxMax.x))) + halfWid = max(0.9, max(abs(box.boxMin.z), abs(box.boxMax.z))) + let idx = snap.unitCount + snap.units[idx].eid = eid + snap.units[idx].army = army + snap.units[idx].pos = u.pos + snap.units[idx].vel = u.vel + snap.units[idx].hullFwd = wto_xz_normalize(u.unitTm[0], float3(1.0, 0.0, 0.0)) + snap.units[idx].halfLen = halfLen + snap.units[idx].halfWid = halfWid + snap.units[idx].engineRpm = gm != null ? clamp(abs(gm.engineRelativeRPM), 0.0, 1.2) : 0.0 + snap.units[idx].isAlive = true + snap.units[idx].isGround = isGround + snap.units[idx].isAir = isAir + snap.units[idx].isLightTag = false + snap.units[idx].isShooting = gm != null && (gm.isShooting || gm.hasMissilesInFlight) + snap.units[idx].isBurn = u.isBurn + snap.units[idx].isHuman = u.isHumanPlayer + snap.unitCount = idx + 1 + for i in range(snap.unitCount) + if snap.units[i].isGround + snap.units[i].isLightTag = has(snap.units[i].eid, "unit_tag__light_vehicle") + +[never_inline] +def public wto_world_refresh(now : float; var snap : WtoWorldSnap&) + snap.time = now + if snap.matchStartAt < -50.0 + snap.matchStartAt = now + wto_refresh_units(snap) + if now >= snap.nextCapRefreshAt + snap.nextCapRefreshAt = now + 0.5 + wto_world_refresh_caps(snap) + wto_world_refresh_bounds_and_spawns(snap) + snap.valid = true diff --git a/game-ai/ground/wto_ai_world_zones_common.das b/game-ai/ground/wto_ai_world_zones_common.das new file mode 100644 index 0000000..f8ddd82 --- /dev/null +++ b/game-ai/ground/wto_ai_world_zones_common.das @@ -0,0 +1,185 @@ +// Capture zone, battle mode detection, and team spawn anchor resolution for the world snapshot. +options indenting = 2 +options no_global_heap = true +module wto_ai_world_zones_common shared + +require ecs +require math +require strings +require DagorMath +require Mission +require Unit +require Dacoll +require %appGame.wtoai.wto_ai_math_common +require %appGame.wtoai.wto_ai_order_common +require %appGame.wtoai.wto_ai_types_common + +[never_inline] +def private wto_snap_cap_y(x, refY, z : float) : float + let top = float3(x, refY + 25.0, z) + var drop = 65.0 + if tracedown_normalized(top, drop, ETF_LMESH | ETF_HEIGHTMAP | ETF_STRUCTURES) + return top.y - drop + let hiTop = float3(x, max(refY + 120.0, 800.0), z) + var hiDrop = hiTop.y + 200.0 + if tracedown_normalized(hiTop, hiDrop, ETF_LMESH | ETF_HEIGHTMAP) + return hiTop.y - hiDrop + return refY + +[never_inline] +def private wto_detect_battle_mode(var snap : WtoWorldSnap&; nameHint : int) + if snap.battleMode != WTO_MODE_UNKNOWN || snap.capCount <= 0 + return + var own0 = 0 + var own1 = 0 + var own2 = 0 + for i in range(snap.capCount) + let o = snap.caps[i].ownerArmy + if o == 1 + own1++ + elif o == 2 + own2++ + else + own0++ + if nameHint != WTO_MODE_UNKNOWN + snap.battleMode = nameHint + elif own1 >= 1 && own2 >= 1 + snap.battleMode = WTO_MODE_BTTL + elif snap.capCount == 1 + snap.battleMode = WTO_MODE_CONQ + else + snap.battleMode = WTO_MODE_DOM + print("WTO_AI|MODE|mode={snap.battleMode}|caps={snap.capCount}|own={own0}/{own1}/{own2}\n") + +[never_inline] +def private wto_collect_zone_entities(var pIds : int[8]&; var pPos : float3[8]&; + var pRad : float[8]&; var pOwn : int[8]&; + var nameHint : int&) : int + var pCount = 0 + query() <| $ [es] (capture_zone__zoneId : int; transform : float3x4; + capture_zone__name : string = ""; sphere_zone__radius : float = 0.0; + capzone__approximateRadius : float = 0.0; capzone__owningTeam : int = -1) + if pCount >= WTO_MAX_CAPS || capture_zone__zoneId < 0 + return + if nameHint == WTO_MODE_UNKNOWN && !empty(capture_zone__name) + if find(capture_zone__name, "bttl") >= 0 + nameHint = WTO_MODE_BTTL + elif find(capture_zone__name, "conq") >= 0 + nameHint = WTO_MODE_CONQ + elif find(capture_zone__name, "dom") >= 0 + nameHint = WTO_MODE_DOM + var rad = max(sphere_zone__radius, capzone__approximateRadius) + if rad <= 2.0 && !empty(capture_zone__name) + let areaId = get_area_id(capture_zone__name) + if areaId >= 0 + let lim = get_area_limits_xz(areaId) + rad = 0.25 * (abs(lim.z - lim.x) + abs(lim.w - lim.y)) + if rad <= 2.0 + rad = 0.5 * min(length(transform[0]), length(transform[2])) + pIds[pCount] = capture_zone__zoneId + pPos[pCount] = transform[3] + pRad[pCount] = clamp(rad > 2.0 ? rad : 25.0, 10.0, 180.0) + pOwn[pCount] = (capzone__owningTeam == 1 || capzone__owningTeam == 2) ? capzone__owningTeam : 0 + pCount++ + return pCount + +[never_inline] +def public wto_world_refresh_caps(var snap : WtoWorldSnap&) + let prevCount = snap.capCount + var prevOwners : int[8] + for i in range(WTO_MAX_CAPS) + prevOwners[i] = i < prevCount ? snap.caps[i].ownerArmy : -1 + snap.capCount = 0 + var pIds : int[8] + var pPos : float3[8] + var pRad : float[8] + var pOwn : int[8] + var nameHint = WTO_MODE_UNKNOWN + let pCount = wto_collect_zone_entities(pIds, pPos, pRad, pOwn, nameHint) + for_each_capture_zone() <| $(zone : CaptureZone) + if snap.capCount >= WTO_MAX_CAPS || !zone.isEnabled + return + var f = -1 + for p in range(pCount) + if pIds[p] == zone.id + f = p + break + if f < 0 + return + let c = float3(pPos[f].x, wto_snap_cap_y(pPos[f].x, pPos[f].y, pPos[f].z), pPos[f].z) + let cIdx = snap.capCount + let own = pOwn[f] + let prog = float(zone.captureProgressVal) + snap.caps[cIdx].zoneId = zone.id + snap.caps[cIdx].center = c + snap.caps[cIdx].radius = pRad[f] + snap.caps[cIdx].ownerArmy = own + snap.caps[cIdx].progress = prog + snap.caps[cIdx].contested = (own == 1 && prog > -99.0) || (own == 2 && prog < 99.0) || (own == 0 && abs(prog) > 1.0) + snap.capCount = cIdx + 1 + wto_detect_battle_mode(snap, nameHint) + var changed = snap.capCount != prevCount + for i in range(snap.capCount) + if !changed && snap.caps[i].ownerArmy != prevOwners[i] + changed = true + if changed + snap.zoneVersion++ + +[never_inline] +def private wto_resolve_team_spawns(var snap : WtoWorldSnap&) + if snap.teamSpawnFromPoints[1] && snap.teamSpawnFromPoints[2] + return + var sumPos : float3[3] + var spCnt : int[3] + for a in range(3) + sumPos[a] = float3(0.0, 0.0, 0.0) + spCnt[a] = 0 + let maxDistSq = wto_sq(max(snap.battleRadius * 2.2, 2200.0)) + get_respawn_points() <| $(active, resptype, team, pos) + if !active || (team != 1 && team != 2) + return + if resptype == "human" || resptype == "aircraft" || resptype == "helicopter" + return + if snap.battleRadius > 1.0 && wto_xz_dist_sq(pos, snap.battleCenter) > maxDistSq + return + sumPos[team] += pos + spCnt[team]++ + for a in range(1, 3) + if spCnt[a] > 0 + snap.teamSpawnCenter[a] = sumPos[a] / float(spCnt[a]) + snap.teamSpawnValid[a] = true + snap.teamSpawnFromPoints[a] = true + elif !snap.teamSpawnValid[a] + var uSum = float3(0.0, 0.0, 0.0) + var uCnt = 0 + for i in range(snap.unitCount) + assume u = snap.units[i] + if u.isAlive && u.isGround && u.army == a + uSum += u.pos + uCnt++ + if uCnt > 0 + snap.teamSpawnCenter[a] = uSum / float(uCnt) + snap.teamSpawnValid[a] = true + +[never_inline] +def public wto_world_refresh_bounds_and_spawns(var snap : WtoWorldSnap&) + var sum = float3(0.0, 0.0, 0.0) + for i in range(snap.capCount) + sum += snap.caps[i].center + if snap.capCount > 0 + snap.battleCenter = sum / float(snap.capCount) + var maxDSq = 0.0 + for i in range(snap.capCount) + maxDSq = max(maxDSq, wto_xz_dist_sq(snap.caps[i].center, snap.battleCenter)) + snap.battleRadius = clamp(sqrt(maxDSq) + 650.0, 850.0, 2400.0) + wto_resolve_team_spawns(snap) + if snap.capCount == 0 + var fallbackSum = float3(0.0, 0.0, 0.0) + var fallbackCnt = 0 + for a in range(1, 3) + if snap.teamSpawnValid[a] + fallbackSum += snap.teamSpawnCenter[a] + fallbackCnt++ + if fallbackCnt > 0 + snap.battleCenter = fallbackSum / float(fallbackCnt) + snap.battleRadius = 1200.0 diff --git a/native/wto-net/build.ps1 b/native/wto-net/build.ps1 index 1584a70..7b7d267 100644 --- a/native/wto-net/build.ps1 +++ b/native/wto-net/build.ps1 @@ -23,7 +23,7 @@ New-Item -ItemType Directory -Force $obj | Out-Null $sources = @( "$src\dll_main.c", "$src\hook_config.c", "$src\redirect_rules.c", "$src\resolver_hooks.c", "$src\connection_hooks.c", "$src\local_mp_core.c", "$src\local_mp_values.c", "$src\local_mp_players.c", "$src\local_mp_loadout.c", "$src\local_mp_actions.c", "$src\local_mp_awards.c", "$src\local_mp_kills.c", "$src\local_mp_events.c", "$src\local_mp_scores.c", "$src\local_mp_nuke.c", "$src\local_mp_support.c", - "$src\local_mp_damage_notifications.c", "$src\local_mp_air_events.c", + "$src\local_mp_damage_notifications.c", "$src\local_mp_air_events.c", "$src\local_mp_ground_ai.c", "$mh\src\hook.c", "$mh\src\buffer.c", "$mh\src\trampoline.c", "$mh\src\hde\hde64.c" ) | ForEach-Object { '"' + (Resolve-Path $_) + '"' } diff --git a/native/wto-net/src/local_mp_core.c b/native/wto-net/src/local_mp_core.c index 167a3aa..eab31d5 100644 --- a/native/wto-net/src/local_mp_core.c +++ b/native/wto-net/src/local_mp_core.c @@ -143,6 +143,7 @@ static const LocalMpModule MODULES[] = { { "local_mp_support", install_local_mp_support_hooks }, { "local_mp_damage_notifications", install_local_mp_damage_notification_hooks }, { "local_mp_air_events", install_local_mp_air_event_hooks }, + { "local_mp_ground_ai", install_local_mp_ground_ai_hooks }, }; static void use_core_values(void) diff --git a/native/wto-net/src/local_mp_ground_ai.c b/native/wto-net/src/local_mp_ground_ai.c new file mode 100644 index 0000000..9dbbcf7 --- /dev/null +++ b/native/wto-net/src/local_mp_ground_ai.c @@ -0,0 +1,196 @@ +/* + * Global stock-tankBot replacement gate for LocalMP battles. + * + * When WTOffline's ground AI daScript compiles and loads cleanly with custom movement enabled, + * its [init] hook announces "wtoGroundAiScriptReady". Once announced, stock "tankBot" behavior + * trees are never attached to LocalMP bot tanks and their MoveSystem stays paused for the + * lifetime of the vehicle (no mid-battle fallback or tug-of-war with stock AI). + * + * If the script fails to compile, is missing, or the player chooses "stock" mode, the ready + * signal never arrives and stock tankBot runs untouched. + */ +#include "hook_config.h" +#include "local_mp_internal.h" +#include "local_mp_offsets.h" + +#include +#include +#include + +#define SCRIPT_READY_ACTION "wtoGroundAiScriptReady" +#define DRIVE_CONTROL_ACTION "wtoGroundAiDriveControl" + +typedef void (__fastcall *MissionActionFn)(const char *name, const void *blk); +typedef uint8_t *(__fastcall *AsGroundModelFn)(uint8_t *unit); +typedef uint8_t (__fastcall *DriveToPosUpdateFn)(void *node, void *agent, float dt); + +typedef struct GroundAiDriveControl { + uint8_t *unit; + uint8_t *move_system; + uint32_t eid; +} GroundAiDriveControl; + +static MissionActionFn orig_mission_action; +static DriveToPosUpdateFn orig_drive_to_pos_update; +static AsGroundModelFn as_ground_model; + +static volatile LONG g_script_owns_movement; +static GroundAiDriveControl controls[UINT8_MAX + 1]; +static SRWLOCK control_lock = SRWLOCK_INIT; + +static uint8_t *get_move_system(uint8_t *unit) +{ + uint8_t *ground_model = unit ? as_ground_model(unit) : NULL; + return ground_model ? *(uint8_t **)(ground_model + g_lmp.ground_ai_move_system) : NULL; +} + +static uint8_t *get_bot_owner(uint8_t *unit, uint32_t eid) +{ + uint8_t *owner = *(uint8_t **)(unit + LMP_UNIT_OFF_MPLAYER); + if (owner == NULL || local_mp_is_local_mplayer(owner) || + owner != local_mp_find_mplayer(-1, owner[LMP_MP_OFF_PID]) || + *(int64_t *)(owner + LMP_MP_OFF_USER_ID) >= -1 || + *(uint32_t *)(owner + LMP_MP_OFF_UNIT_EID) != eid) + return NULL; + return owner; +} + +static void clear_slot(GroundAiDriveControl *control, const char *reason) +{ + log_line("local_mp: ground AI cleared drive slot eid=%#lx (%s)", (unsigned long)control->eid, reason); + memset(control, 0, sizeof(*control)); +} + +static void clear_by_eid(uint32_t eid, const char *reason) +{ + size_t i; + for (i = 0; i < sizeof(controls) / sizeof(controls[0]); i++) { + if (controls[i].unit == NULL) + continue; + if (eid == 0 || controls[i].eid == eid) + clear_slot(&controls[i], reason); + } +} + +static void acquire_drive_control(uint32_t eid) +{ + uint8_t *unit; + uint8_t *move_system; + uint8_t *owner; + GroundAiDriveControl *control; + + if (eid == 0 || !local_mp_is_host() || !InterlockedCompareExchange(&g_script_owns_movement, 0, 0)) + return; + unit = (uint8_t *)g_lmp_get_unit_by_eid(eid); + move_system = get_move_system(unit); + owner = move_system ? get_bot_owner(unit, eid) : NULL; + if (owner == NULL) + return; + control = &controls[owner[LMP_MP_OFF_PID]]; + if (control->unit != NULL && + (control->eid != eid || control->unit != unit || control->move_system != move_system)) + clear_slot(control, "vehicle changed"); + + move_system[g_lmp.ground_ai_move_inactive] = 1; + if (control->unit == NULL) { + control->unit = unit; + control->move_system = move_system; + control->eid = eid; + log_line("local_mp: ground AI owns drive eid=%#lx", (unsigned long)eid); + } +} + +static int read_uint(const void *blk, const char *key, uint32_t *out) +{ + const char *value = g_lmp_datablock_get_str(blk, key, ""); + char *end; + unsigned long parsed; + + if (value == NULL || *value < '0' || *value > '9') + return 0; + errno = 0; + parsed = strtoul(value, &end, 0); + if (errno != 0 || *end != 0) + return 0; + *out = (uint32_t)parsed; + return 1; +} + +static uint8_t __fastcall hook_drive_to_pos_update(void *node, void *agent, float dt) +{ + /* Keep the BehTree object initialized on the unit so vehicle physics steps normally, + * but short-circuit stock driveToPos to ER_SUCCESS (1) whenever our AI script is active. */ + if (local_mp_is_host() && InterlockedCompareExchange(&g_script_owns_movement, 0, 0)) + return 1; + return orig_drive_to_pos_update(node, agent, dt); +} + +static void __fastcall hook_mission_action(const char *name, const void *blk) +{ + uint32_t eid = 0, hold_ms = 0, own = 0; + + if (name != NULL && strcmp(name, SCRIPT_READY_ACTION) == 0) { + if (blk != NULL && read_uint(blk, "ownMovement", &own)) { + LONG prev = InterlockedExchange(&g_script_owns_movement, own ? 1 : 0); + if (prev != (own ? 1 : 0)) { + log_line("local_mp: ground AI script ready (ownMovement=%u; stock tankBot %s)", + (unsigned)(own ? 1 : 0), own ? "disabled" : "kept"); + } + } + return; + } + if (name == NULL || strcmp(name, DRIVE_CONTROL_ACTION) != 0) { + orig_mission_action(name, blk); + return; + } + if (blk == NULL || !read_uint(blk, "eid", &eid) || !read_uint(blk, "holdMs", &hold_ms)) + return; + AcquireSRWLockExclusive(&control_lock); + if (hold_ms == 0) + clear_by_eid(eid, eid == 0 ? "mission reset" : "unit ended"); + else + acquire_drive_control(eid); + ReleaseSRWLockExclusive(&control_lock); +} + +void local_mp_ground_ai_update(float dt) +{ + size_t i; + int hosting; + (void)dt; + + if (orig_mission_action == NULL) + return; + hosting = local_mp_is_host(); + AcquireSRWLockExclusive(&control_lock); + for (i = 0; i < sizeof(controls) / sizeof(controls[0]); i++) { + GroundAiDriveControl *control = &controls[i]; + uint8_t *unit, *owner; + if (control->unit == NULL) + continue; + if (!hosting) { + clear_slot(control, "session ended"); + continue; + } + unit = (uint8_t *)g_lmp_get_unit_by_eid(control->eid); + owner = unit == control->unit ? get_bot_owner(unit, control->eid) : NULL; + if (owner == NULL || owner[LMP_MP_OFF_PID] != i || get_move_system(unit) != control->move_system) { + clear_slot(control, "vehicle changed"); + continue; + } + /* Keep stock MoveSystem permanently paused while this bot tank is alive. */ + control->move_system[g_lmp.ground_ai_move_inactive] = 1; + } + ReleaseSRWLockExclusive(&control_lock); +} + +int install_local_mp_ground_ai_hooks(void) +{ + LocalMpHookSpec hooks[] = { + { "das_call_mission_action", g_lmp.ground_ai_mission_action, (void *)&hook_mission_action, (void **)&orig_mission_action }, + { "drive_to_pos_update", g_lmp.ground_ai_drive_to_pos_update, (void *)&hook_drive_to_pos_update, (void **)&orig_drive_to_pos_update }, + }; + + as_ground_model = (AsGroundModelFn)g_lmp.ground_ai_as_ground_model; + return local_mp_queue_hooks("local_mp_ground_ai", hooks, sizeof(hooks) / sizeof(hooks[0])); +} diff --git a/native/wto-net/src/local_mp_internal.h b/native/wto-net/src/local_mp_internal.h index 3dc4326..6034edb 100644 --- a/native/wto-net/src/local_mp_internal.h +++ b/native/wto-net/src/local_mp_internal.h @@ -106,3 +106,5 @@ int install_local_mp_nuke_hooks(void); int install_local_mp_support_hooks(void); int install_local_mp_damage_notification_hooks(void); int install_local_mp_air_event_hooks(void); +int install_local_mp_ground_ai_hooks(void); +void local_mp_ground_ai_update(float dt); diff --git a/native/wto-net/src/local_mp_loadout.c b/native/wto-net/src/local_mp_loadout.c index 341974d..3c4e1ad 100644 --- a/native/wto-net/src/local_mp_loadout.c +++ b/native/wto-net/src/local_mp_loadout.c @@ -13,8 +13,19 @@ #include "MinHook.h" +#include #include +typedef struct ReflBulletEntry { + const char *weapon_name; + const char *bullet_mod; + uint16_t count; + uint8_t trigger_group; + uint8_t pad[5]; +} ReflBulletEntry; + +C_ASSERT(sizeof(ReflBulletEntry) == 24); + typedef void (__fastcall *SemChangeAircraftSendFn)( void *self, const char *unit_name, const char *weapon_name, const void *modifications_blk, const char *skin_name, const void *custom_preset_blk, uint8_t flags_byte, @@ -39,9 +50,9 @@ typedef uint64_t (__fastcall *StrHashFnv1Fn)(const char *str, size_t len); typedef int32_t (__fastcall *NameMapAddNameIdFn)(void *map, const char *str, size_t len, uint64_t hash); static SemChangeAircraftSendFn orig_sem_send; +static UnitChangeAircraftFn orig_unit_change_aircraft; static ReflCtorFn fn_refl_ctor; static ReflDtorFn fn_refl_dtor; -static UnitChangeAircraftFn fn_unit_change_aircraft; static DataBlockSetFromFn fn_datablock_set_from; static DataBlockDtorFn fn_datablock_dtor; static BulletSetVecAssignFn fn_bullet_vec_assign; @@ -120,6 +131,93 @@ static void apply_mplayer_spawn_base(uint8_t *mplayer, int32_t req_base_id) *(float *)(mplayer + LMP_MP_OFF_SPAWN_POS_Z) = 0.0f; } +static int is_bot_unit(const uint8_t *unit) +{ + const uint8_t *owner = *(const uint8_t *const *)(unit + LMP_UNIT_OFF_MPLAYER); + return owner != NULL && !local_mp_is_local_mplayer(owner) && + *(const int64_t *)(owner + LMP_MP_OFF_USER_ID) < -1; +} + +static int parse_bullet_pair(const char *token, char *mod_buf, size_t mod_size, uint16_t *out_count) +{ + const char *colon = strchr(token, ':'); + size_t mod_len; + unsigned long parsed; + char *end; + + if (colon == NULL) + return 0; + mod_len = (size_t)(colon - token); + if (mod_len >= mod_size) + return 0; + memcpy(mod_buf, token, mod_len); + mod_buf[mod_len] = '\0'; + parsed = strtoul(colon + 1, &end, 10); + if (end == colon + 1 || (*end != '\0' && *end != '|') || parsed == 0 || parsed > 0xfffeu) + return 0; + *out_count = (uint16_t)parsed; + return 1; +} + +static void apply_bot_tank_ammo(const uint8_t *unit, uint8_t *refl) +{ + const char *raw_name, *unit_name, *spec, *p1, *p2; + char key[128], weapon[96], b0[96], b1[96]; + uint16_t c0 = 0, c1 = 0; + size_t wlen; + ReflBulletEntry slots[2]; + size_t count = 0; + + if (g_local_mp_mission_settings == NULL || g_lmp_datablock_get_str == NULL || !is_bot_unit(unit)) + return; + raw_name = *(const char *const *)(refl + LMP_REFL_OFF_UNIT_NAME); + if (raw_name == NULL || *raw_name == '\0') + return; + unit_name = strncmp(raw_name, "tankModels/", 11) == 0 ? raw_name + 11 : raw_name; + if (strlen(unit_name) + 9 >= sizeof(key)) + return; + memcpy(key, "wtoAmmo_", 8); + strcpy_s(key + 8, sizeof(key) - 8, unit_name); + spec = g_lmp_datablock_get_str(g_local_mp_mission_settings + LMP_MIS_OFF_CUSTOM_BOTS, key, ""); + if (spec == NULL || *spec == '\0') + return; + p1 = strchr(spec, '|'); + if (p1 == NULL) + return; + wlen = (size_t)(p1 - spec); + if (wlen == 0 || wlen >= sizeof(weapon)) + return; + memcpy(weapon, spec, wlen); + weapon[wlen] = '\0'; + if (!parse_bullet_pair(p1 + 1, b0, sizeof(b0), &c0)) + return; + + memset(slots, 0, sizeof(slots)); + slots[0].weapon_name = weapon; + slots[0].bullet_mod = b0; + slots[0].count = c0; + slots[0].trigger_group = 0xffu; + count = 1; + p2 = strchr(p1 + 1, '|'); + if (p2 != NULL && parse_bullet_pair(p2 + 1, b1, sizeof(b1), &c1)) { + slots[1].weapon_name = weapon; + slots[1].bullet_mod = b1; + slots[1].count = c1; + slots[1].trigger_group = 0xffu; + count = 2; + } + fn_bullet_vec_assign(refl + LMP_REFL_OFF_BULLETS_VEC, &slots[0], &slots[count]); + log_line("local_mp: bot tank ammo unit='%s' weapon='%s' b0='%s':%u b1='%s':%u", + unit_name, weapon, b0, (unsigned)c0, count > 1 ? b1 : "", (unsigned)c1); +} + +static uint8_t __fastcall hook_unit_change_aircraft(void *unit, void *refl, uint8_t async) +{ + if (local_mp_is_host() && unit != NULL && refl != NULL && async == 0) + apply_bot_tank_ammo((const uint8_t *)unit, (uint8_t *)refl); + return orig_unit_change_aircraft(unit, refl, async); +} + static void __fastcall hook_sem_change_aircraft_send( void *self, const char *unit_name, const char *weapon_name, const void *modifications_blk, const char *skin_name, const void *custom_preset_blk, uint8_t flags_byte, @@ -182,7 +280,7 @@ static void __fastcall hook_sem_change_aircraft_send( refl[LMP_REFL_OFF_VERT_TARGETING] = vertical_targeting ? 1u : 0u; *(float *)(refl + LMP_REFL_OFF_BOMB_FUSE) = bomb_activation_time; - fn_unit_change_aircraft(hero, refl, 1); + orig_unit_change_aircraft(hero, refl, 1); fn_refl_dtor(refl); if (mplayer[LMP_MP_OFF_GUI_STATE] != LMP_GUI_STATE_PILOT_CONTROL && @@ -198,6 +296,7 @@ int install_local_mp_loadout_hooks(void) { const LocalMpHookSpec hooks[] = { { "sem_change_aircraft_send", g_lmp.sem_change_aircraft_send, (void *)&hook_sem_change_aircraft_send, (void **)&orig_sem_send }, + { "unit_change_aircraft", g_lmp.unit_change_aircraft, (void *)&hook_unit_change_aircraft, (void **)&orig_unit_change_aircraft }, }; /* The reflection is built in a fixed stack buffer; its bullet sets vector is its last member. */ @@ -208,7 +307,6 @@ int install_local_mp_loadout_hooks(void) } fn_refl_ctor = (ReflCtorFn)g_lmp.refl_ctor; fn_refl_dtor = (ReflDtorFn)g_lmp.refl_dtor; - fn_unit_change_aircraft = (UnitChangeAircraftFn)g_lmp.unit_change_aircraft; fn_datablock_set_from = (DataBlockSetFromFn)g_lmp.datablock_set_from; fn_datablock_dtor = (DataBlockDtorFn)g_lmp.datablock_dtor; fn_bullet_vec_assign = (BulletSetVecAssignFn)g_lmp.bullet_vec_assign; diff --git a/native/wto-net/src/local_mp_players.c b/native/wto-net/src/local_mp_players.c index 8005f93..a329671 100644 --- a/native/wto-net/src/local_mp_players.c +++ b/native/wto-net/src/local_mp_players.c @@ -166,6 +166,7 @@ static void __fastcall hook_gui_state_update(uint8_t *gui_state_obj, float dt) uint8_t *mplayer; orig_gui_state_update(gui_state_obj, dt); + local_mp_ground_ai_update(dt); if (!local_mp_is_host()) { g_accept_pending = 0; diff --git a/native/wto-net/src/local_mp_values.c b/native/wto-net/src/local_mp_values.c index 1bb0fd7..59736d4 100644 --- a/native/wto-net/src/local_mp_values.c +++ b/native/wto-net/src/local_mp_values.c @@ -41,6 +41,7 @@ typedef struct LmpValueSpec { #define SUPPORT "local_mp_support" #define DAMAGE_NOTICES "local_mp_damage_notifications" #define AIR_EVENTS "local_mp_air_events" +#define GROUND_AI "local_mp_ground_ai" static const LmpValueSpec SPECS[] = { A(CORE, "do_respawn_player", do_respawn_player), O(CORE, "do_respawn_player.app_score_rules", app_score_rules), @@ -187,6 +188,12 @@ static const LmpValueSpec SPECS[] = { A(AIR_EVENTS, "air_event_orientation.call", air_event_orientation), A(AIR_EVENTS, "send_unit_respawn", send_unit_respawn), A(AIR_EVENTS, "send_unit_respawn_broadcast.mpi_sendto", mpi_sendto), + + A(GROUND_AI, "ground_ai_mission_binding.action", ground_ai_mission_action), + A(GROUND_AI, "ground_ai_as_ground_model", ground_ai_as_ground_model), + A(GROUND_AI, "ground_ai_drive_to_pos_update", ground_ai_drive_to_pos_update), + O(GROUND_AI, "ground_ai_move_properties.move_system", ground_ai_move_system), + O(GROUND_AI, "ground_ai_move_annotation.inactive", ground_ai_move_inactive), }; static void store(const LmpValueSpec *spec, int64_t value, uint8_t *base) diff --git a/native/wto-net/src/local_mp_values.h b/native/wto-net/src/local_mp_values.h index a97bebf..139be54 100644 --- a/native/wto-net/src/local_mp_values.h +++ b/native/wto-net/src/local_mp_values.h @@ -88,6 +88,9 @@ typedef struct LmpValues { uint8_t *air_event_orientation, *send_unit_respawn, *mpi_sendto; size_t mis_mode_name, gp_ks_rules, gp_ks_rule_count, ks_rule_tag, ks_rule_air_ai_mult, ks_rule_ground_ai_mult; size_t ks_rule_spawn_pos, ks_rule_spawn_pos_count, ks_spawn_pos_stride, mp_ks_progress, app_terrain; + /* local_mp_ground_ai */ + uint8_t *ground_ai_mission_action, *ground_ai_as_ground_model, *ground_ai_drive_to_pos_update; + size_t ground_ai_move_system, ground_ai_move_inactive; } LmpValues; extern LmpValues g_lmp; diff --git a/packages/patcher/src/build-game-copy.ts b/packages/patcher/src/build-game-copy.ts index d3700b0..2666592 100644 --- a/packages/patcher/src/build-game-copy.ts +++ b/packages/patcher/src/build-game-copy.ts @@ -16,6 +16,14 @@ import { rebuildCharPack, type CharPackResult } from './char-pack.ts'; import { blockingFailures } from './essential-features.ts'; import { patchExecutableWithMods, type ModExePatchFailure } from './executable.ts'; import { GAME_FILES } from './game-copy.ts'; +import { + GAME_PACK_FILE, + rebuildGamePack, + validateGroundAiGamePack, + type GamePackResult, + type GroundAiBuildInputs, +} from './ground-ai/game-pack.ts'; +import { groundAiOwnsMovement, isGroundAiActive } from './ground-ai/ground-ai-config.ts'; import { rebuildGuiPack } from './gui-pack.ts'; import { rebuildMainPack } from './main-pack.ts'; import { collectModAddonMounts, type ModAddonMount } from './mods/addon-register.ts'; @@ -57,8 +65,10 @@ export interface GameCopyInputs { readonly hookLogging?: boolean; /** Ordered list of enabled additive mods to overlay onto this build. */ readonly mods?: readonly DiscoveredMod[]; - /** Stock bytes of optional packs (lang/mis/game/ui/*) touched by enabled mods. */ + /** Stock bytes of optional packs (lang/mis/game/ui/*) touched by enabled mods or ground AI. */ readonly extraStockPacks?: Partial>; + /** Optional modular ground AI scripts and tuning compiled into `game.vromfs.bin` when active. */ + readonly groundAi?: GroundAiBuildInputs; } /** One file of the game copy, by its path relative to the copy folder. */ @@ -96,6 +106,8 @@ export interface GameCopyBuild { readonly engineAddresses: readonly AddressChange[]; /** Store bundle GUIDs registered in config/gui.blk. */ readonly bundleGuids: number; + /** Injected ground AI modules when `groundAi` is active; undefined when stock AI is kept. */ + readonly gamePack?: Omit; /** Details of additive mod overlays applied during this build. */ readonly mods: ModBuildReport; } @@ -114,12 +126,61 @@ export function buildGameCopy(inputs: GameCopyInputs): GameCopyBuild { const folders = patchSetFolders(inputs.patches); const enabledMods = inputs.mods ?? []; const packOverlays: PackOverlayReport[] = []; + const groundAiActive = inputs.groundAi !== undefined && isGroundAiActive(inputs.groundAi.config); const executable = patchExecutableWithMods(inputs.stock.executable, folders.exe, enabledMods); const stockImage = new PeImage(inputs.stock.executable); - const native = resolveNativeModules(stockImage, loadNativeModules(folders.native)); + const customGroundDrive = groundAiActive && inputs.groundAi !== undefined && groundAiOwnsMovement(inputs.groundAi.config) && + inputs.groundAi.config.navigation.driveMode === 'vehicle_phys'; + const nativeDefinitions = loadNativeModules(folders.native) + .filter((module) => customGroundDrive || module.module !== 'local_mp_ground_ai'); + const native = resolveNativeModules(stockImage, nativeDefinitions); + const core = buildCorePacks(inputs, endpoint, folders.gui, enabledMods, packOverlays); - const coreGuiPack = rebuildGuiPack(inputs.stock.guiPack, endpoint, folders.gui); + const executableFolder = dirname(GAME_FILES.executable); + const hookSettings = networkHookSettings(endpoint, stockImage, native.values, { + loggingEnabled: inputs.hookLogging ?? true, + }); + const files: GameCopyFile[] = [ + { path: GAME_FILES.charPack, content: core.charPack }, + { path: GAME_FILES.mainPack, content: core.mainPack }, + { path: GAME_FILES.guiPack, content: core.guiPack }, + { path: GAME_FILES.executable, content: executable.executable }, + { path: join(executableFolder, NETWORK_HOOK_LIBRARY), content: inputs.networkHookLibrary }, + { path: join(executableFolder, hookSettings.name), content: hookSettings.content }, + ]; + + const gamePackReport = appendOptionalPackFiles(files, packOverlays, inputs, enabledMods, groundAiActive); + const failures = [...executable.plan.failures, ...core.guiFailures, ...native.failures]; + return { + files, + endpoint, + exePatches: { applied: executable.plan.writes.map((write) => ({ patchId: write.patchId, rva: write.rva })), failures: executable.plan.failures }, + guiPatches: { applied: core.appliedGuiPatches, failures: core.guiFailures }, + nativeModules: { available: [...native.available.keys()], failures: native.failures }, + blocking: blockingFailures(failures), + charPack: core.charReport, + engineAddresses: core.engineAddresses, + bundleGuids: core.bundleCount, + ...(gamePackReport ? { gamePack: gamePackReport } : {}), + mods: { + enabledModIds: enabledMods.map((mod) => mod.manifest.id), + packOverlays, + addonMounts: core.addonMounts, + guiPatches: { applied: core.modGuiApplied, failures: core.modGuiFailures }, + exePatches: { applied: executable.modApplied, failures: executable.modFailures }, + }, + }; +} + +function buildCorePacks( + inputs: GameCopyInputs, + endpoint: LocalEndpoint, + guiPatchFolder: string, + enabledMods: readonly DiscoveredMod[], + packOverlays: PackOverlayReport[], +) { + const coreGuiPack = rebuildGuiPack(inputs.stock.guiPack, endpoint, guiPatchFolder); const appliedGuiPatches = coreGuiPack.applied.map((item) => item.patch.id); const guiPackFileOverlay = applyModPackOverlays(coreGuiPack.pack, 'gui.vromfs.bin', enabledMods); if (guiPackFileOverlay.report.operationsApplied > 0) packOverlays.push(guiPackFileOverlay.report); @@ -135,8 +196,6 @@ export function buildGameCopy(inputs: GameCopyInputs): GameCopyBuild { const charOverlay = applyModPackOverlays(coreCharPack, 'char.vromfs.bin', enabledMods); if (charOverlay.report.operationsApplied > 0) packOverlays.push(charOverlay.report); - // Derive store bundle GUIDs from the mod-overlaid charPack so newly added mod gift vehicles - // automatically receive deterministic offline store bundle GUIDs. const bundles = offlinePackBundleGuids(charOverlay.pack, inputs.multiVehiclePackIds); const addonMounts = collectModAddonMounts(enabledMods); const coreMainPack = rebuildMainPack( @@ -148,22 +207,47 @@ export function buildGameCopy(inputs: GameCopyInputs): GameCopyBuild { const mainOverlay = applyModPackOverlays(coreMainPack.pack, 'aces.vromfs.bin', enabledMods); if (mainOverlay.report.operationsApplied > 0) packOverlays.push(mainOverlay.report); - const executableFolder = dirname(GAME_FILES.executable); - const hookSettings = networkHookSettings(endpoint, stockImage, native.values, { - loggingEnabled: inputs.hookLogging ?? true, - }); - const files: GameCopyFile[] = [ - { path: GAME_FILES.charPack, content: charOverlay.pack }, - { path: GAME_FILES.mainPack, content: mainOverlay.pack }, - { path: GAME_FILES.guiPack, content: modGuiResult.pack }, - { path: GAME_FILES.executable, content: executable.executable }, - { path: join(executableFolder, NETWORK_HOOK_LIBRARY), content: inputs.networkHookLibrary }, - { path: join(executableFolder, hookSettings.name), content: hookSettings.content }, - ]; + return { + charPack: charOverlay.pack, + mainPack: mainOverlay.pack, + guiPack: modGuiResult.pack, + charReport, + appliedGuiPatches, + guiFailures: coreGuiPack.failures, + modGuiApplied: modGuiResult.applied, + modGuiFailures: modGuiResult.failures, + engineAddresses: coreMainPack.addresses, + bundleCount: bundles.length, + addonMounts, + }; +} + +function appendOptionalPackFiles( + files: GameCopyFile[], + packOverlays: PackOverlayReport[], + inputs: GameCopyInputs, + enabledMods: readonly DiscoveredMod[], + groundAiActive: boolean, +): Omit | undefined { + let gamePackReport: Omit | undefined; + if (groundAiActive && inputs.groundAi) { + const stockGameBytes = inputs.extraStockPacks?.[GAME_PACK_FILE]; + if (!stockGameBytes) { + throw new Error(`ground AI requires stock pack "${GAME_PACK_FILE}" in extraStockPacks`); + } + const { pack: aiGamePack, ...report } = rebuildGamePack(stockGameBytes, inputs.groundAi); + const overlay = applyModPackOverlays(aiGamePack, GAME_PACK_FILE, enabledMods); + if (overlay.report.operationsApplied > 0) { + validateGroundAiGamePack(overlay.pack, report.modules); + packOverlays.push(overlay.report); + } + files.push({ path: GAME_PACK_FILE, content: overlay.pack }); + gamePackReport = report; + } - // Rebuild any optional client packs (lang, mis, game, ui/atlases, ui/images) touched by enabled mods. for (const pack of touchedClientPacks(enabledMods)) { if (CORE_BUILD_PACKS.has(pack)) continue; + if (groundAiActive && pack === GAME_PACK_FILE) continue; const stockBytes = inputs.extraStockPacks?.[pack]; if (!stockBytes) { throw new Error(`mod overlay requires stock pack "${pack}" in extraStockPacks`); @@ -174,24 +258,5 @@ export function buildGameCopy(inputs: GameCopyInputs): GameCopyBuild { files.push({ path: join(...pack.split('/')), content: overlay.pack }); } } - - const failures = [...executable.plan.failures, ...coreGuiPack.failures, ...native.failures]; - return { - files, - endpoint, - exePatches: { applied: executable.plan.writes.map((write) => ({ patchId: write.patchId, rva: write.rva })), failures: executable.plan.failures }, - guiPatches: { applied: appliedGuiPatches, failures: coreGuiPack.failures }, - nativeModules: { available: [...native.available.keys()], failures: native.failures }, - blocking: blockingFailures(failures), - charPack: charReport, - engineAddresses: coreMainPack.addresses, - bundleGuids: bundles.length, - mods: { - enabledModIds: enabledMods.map((mod) => mod.manifest.id), - packOverlays, - addonMounts, - guiPatches: { applied: modGuiResult.applied, failures: modGuiResult.failures }, - exePatches: { applied: executable.modApplied, failures: executable.modFailures }, - }, - }; + return gamePackReport; } diff --git a/packages/patcher/src/ground-ai/game-pack.ts b/packages/patcher/src/ground-ai/game-pack.ts new file mode 100644 index 0000000..9b782cf --- /dev/null +++ b/packages/patcher/src/ground-ai/game-pack.ts @@ -0,0 +1,109 @@ +/** + * Rebuild `game.vromfs.bin` with WTOffline's modular ground AI daScript files injected under + * `game/wtoai/` and one anchored `load_optional_folder("%appGame/wtoai")` line in `game/main.das`. + */ +import { readdirSync, readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { getFile, putFile, readArchive, writeArchive, type Archive } from '@wto/vromfs'; +import { compileGroundAiConfigDas, type GroundAiConfig } from './ground-ai-config.ts'; + +export const GAME_PACK_FILE = 'game.vromfs.bin'; +export const GAME_MAIN_SCRIPT_PATH = 'game/main.das'; +export const GAME_AI_ARCHIVE_FOLDER = 'game/wtoai'; +export const GAME_AI_CONFIG_FILE = 'wto_ai_config_common.das'; + +const GAME_MAIN_ANCHOR = 'ok = load_optional_folder("%appGame/ai") && ok'; +// A failure in the optional AI folder must not fail the stock loader. +const GAME_MAIN_INJECT = 'load_optional_folder("%appGame/wtoai")'; +const GAME_AI_ENTRY = `${GAME_AI_ARCHIVE_FOLDER}/wto_ai_runtime.das`; +const MODULE_NAME = /^[a-z0-9_]+\.das$/; +const LOCAL_MODULE_REQUIRE = /^[ \t]*require[ \t]+%appGame\.wtoai\.([a-z0-9_]+)\b/gm; + +export interface GroundAiBuildInputs { + readonly scriptsFolder: string; + readonly config: GroundAiConfig; +} + +export interface GamePackResult { + readonly pack: Uint8Array; + readonly archiveFolder: string; + readonly modules: readonly string[]; +} + +export function rebuildGamePack(stockGamePack: Uint8Array, inputs: GroundAiBuildInputs): GamePackResult { + const archive = readArchive(stockGamePack); + const mainText = new TextDecoder('utf-8').decode(getFile(archive, GAME_MAIN_SCRIPT_PATH)); + putFile(archive, GAME_MAIN_SCRIPT_PATH, new TextEncoder().encode(injectLoaderLine(mainText))); + + const encoder = new TextEncoder(); + const modules: string[] = []; + const configPath = `${GAME_AI_ARCHIVE_FOLDER}/${GAME_AI_CONFIG_FILE}`; + if (archive.files.has(configPath)) throw new Error(`game.vromfs.bin already contains ${configPath}`); + putFile(archive, configPath, encoder.encode(compileGroundAiConfigDas(inputs.config))); + modules.push(configPath); + + const scriptFiles = readdirSync(inputs.scriptsFolder, { withFileTypes: true }) + .filter((entry) => entry.isFile() && entry.name.endsWith('.das')) + .map((entry) => entry.name) + .sort(); + + for (const name of scriptFiles) { + if (!MODULE_NAME.test(name)) throw new Error(`invalid ground AI daScript module name: ${name}`); + if (name === GAME_AI_CONFIG_FILE) throw new Error(`${GAME_AI_CONFIG_FILE} is generated at build time`); + const archivePath = `${GAME_AI_ARCHIVE_FOLDER}/${name}`; + if (archive.files.has(archivePath)) throw new Error(`game.vromfs.bin already contains ${archivePath}`); + putFile(archive, archivePath, readFileSync(join(inputs.scriptsFolder, name))); + modules.push(archivePath); + } + + validateGroundAiArchive(archive, modules); + return { pack: writeArchive(archive), archiveFolder: GAME_AI_ARCHIVE_FOLDER, modules }; +} + +export function validateGroundAiGamePack(pack: Uint8Array, modules: readonly string[]): void { + validateGroundAiArchive(readArchive(pack), modules); +} + +function validateGroundAiArchive(archive: Archive, modules: readonly string[]): void { + const decoder = new TextDecoder('utf-8'); + const mainLines = decoder.decode(getFile(archive, GAME_MAIN_SCRIPT_PATH)).split(/\r?\n/); + const aiLoaders = mainLines.filter((line) => line.trim() === GAME_MAIN_INJECT); + const anchor = mainLines.findIndex((line) => line.trim() === GAME_MAIN_ANCHOR); + const indentation = mainLines[anchor]?.match(/^[ \t]*/)?.[0]; + if (aiLoaders.length !== 1 || indentation === undefined || + mainLines[anchor + 1]?.trimEnd() !== indentation + GAME_MAIN_INJECT) { + throw new Error(`ground AI loader is missing or displaced in ${GAME_MAIN_SCRIPT_PATH}`); + } + + const required = new Set([GAME_AI_ENTRY, ...modules]); + for (const scriptPath of required) { + const bytes = archive.files.get(scriptPath); + const source = bytes === undefined ? '' : decoder.decode(bytes); + if (!source.trim()) throw new Error(`missing or empty ground AI script in ${GAME_PACK_FILE}: ${scriptPath}`); + for (const match of source.matchAll(LOCAL_MODULE_REQUIRE)) { + required.add(`${GAME_AI_ARCHIVE_FOLDER}/${match[1]}.das`); + } + } +} + +function injectLoaderLine(source: string): string { + if (source.includes(GAME_MAIN_INJECT)) { + throw new Error(`${GAME_MAIN_SCRIPT_PATH} already contains ${GAME_MAIN_INJECT}`); + } + const eol = source.includes('\r\n') ? '\r\n' : '\n'; + const normalized = source.replaceAll('\r\n', '\n'); + const pattern = new RegExp(`^([ \\t]*)${escapeRegExp(GAME_MAIN_ANCHOR)}[ \\t]*$`, 'gm'); + const matches = [...normalized.matchAll(pattern)]; + if (matches.length !== 1) { + throw new Error(`expected 1 loader anchor in ${GAME_MAIN_SCRIPT_PATH}, found ${matches.length}`); + } + const match = matches[0]!; + const indent = match[1] ?? ''; + const end = match.index! + match[0].length; + const patched = `${normalized.slice(0, end)}\n${indent}${GAME_MAIN_INJECT}${normalized.slice(end)}`; + return eol === '\r\n' ? patched.replaceAll('\n', '\r\n') : patched; +} + +function escapeRegExp(text: string): string { + return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} diff --git a/packages/patcher/src/ground-ai/ground-ai-config.ts b/packages/patcher/src/ground-ai/ground-ai-config.ts new file mode 100644 index 0000000..afdbdc4 --- /dev/null +++ b/packages/patcher/src/ground-ai/ground-ai-config.ts @@ -0,0 +1,364 @@ +/** + * Ground AI configuration contract shared between `@wto/server` tuning and `@wto/patcher` + * build-time daScript constant compilation (`game/wtoai/wto_ai_config_common.das`). + */ + +/** + * Which parts of the ground AI replace stock behavior. Each mode is a complete combination: + * - `stock`: stock tankBot moves, aims and fires; no scripts are packed. + * - `fire`: stock movement and destinations; custom perception and fire permission. + * - `drive`: custom team orders and driving; stock aiming and firing (debugging). + * - `full`: every custom layer. + */ +export const GROUND_AI_MODES = ['stock', 'fire', 'drive', 'full'] as const; +export type GroundAiMode = (typeof GROUND_AI_MODES)[number]; + +export interface GroundAiLoadoutConfig { + readonly lowReadyRackThreshold: number; + readonly topUpAmmoCount: number; + readonly primaryAmmoPct: number; + readonly secondaryMinRounds: number; + readonly penetrationCompareDistM: number; +} + +export interface GroundAiConfig { + readonly mode: GroundAiMode; + readonly loadout: GroundAiLoadoutConfig; + readonly cadence: { + readonly maxBots: number; + readonly macroTickSec: number; + readonly tacticsTickSec: number; + readonly navTickSec: number; + }; + readonly commander: { + readonly rebalanceSec: number; + readonly roleHoldSec: number; + readonly bttlAssaultPct: number; + readonly bttlFlankPct: number; + readonly bttlOverwatchPct: number; + readonly conqAssaultPct: number; + readonly conqFlankPct: number; + readonly conqHoldDefendPct: number; + readonly conqHoldOverwatchPct: number; + readonly domAssaultPct: number; + readonly domMaxDefendersPerCap: number; + readonly overwatchStandOffM: number; + readonly flankStandOffM: number; + readonly spaaFollowOffsetM: number; + readonly flankMaxLengthRatio: number; + readonly flankMinSeparationM: number; + readonly rallyProgressFrac: number; + readonly rallyWaitSec: number; + readonly rallyMinFrac: number; + readonly rallyRadiusM: number; + readonly recallSafeHoldSec: number; + }; + readonly macro: { + readonly openingSplitSec: number; + readonly capMaxInsiders: number; + readonly recaptureMinBots: number; + readonly recaptureMaxBots: number; + readonly capStickyBonusM: number; + readonly deathZoneRadiusM: number; + readonly deathZoneTtlSec: number; + readonly deathZoneMinKills: number; + readonly spaaRearOffsetM: number; + readonly spaaRelocateSec: number; + readonly enemySpawnAvoidM: number; + }; + readonly crowd: { + readonly personalSpaceM: number; + readonly clusterRadiusM: number; + readonly clusterMaxAllies: number; + readonly disperseStepM: number; + readonly disperseHoldSec: number; + }; + readonly terrain: { + readonly maxClimbSlopeDeg: number; + readonly maxDropSlopeDeg: number; + readonly maxWaterDepthM: number; + readonly collisionMarginM: number; + readonly crestLookaheadM: number; + readonly ridgeMaxDwellSec: number; + readonly ridgeMaxShots: number; + }; + readonly navigation: { + readonly driveMode: string; + readonly maxPhysBots: number; + readonly steerSign: number; + readonly deadEchoSec: number; + readonly controlTimeoutSec: number; + readonly cornerBrakeAccel: number; + readonly pivotAngleDeg: number; + readonly stuckWindowSec: number; + readonly stuckMinMoveM: number; + readonly unstickReverseSec: number; + readonly tacticalReverseDistM: number; + readonly tacticalReverseMaxSec: number; + }; + readonly perception: { + readonly foliageTransparency: number; + readonly nearSpotRangeM: number; + readonly firingSpotRangeM: number; + readonly fastSpotSec: number; + readonly normalSpotSec: number; + readonly farSpotSec: number; + readonly decayPerSec: number; + readonly frontConeHalfDeg: number; + readonly peripheralCloseM: number; + }; + readonly stateMachine: { + readonly preaimAngleDeg: number; + readonly shortHaltMaxSec: number; + readonly shortHaltCooldownSec: number; + readonly turnLaunchSpeedMps: number; + readonly coverMinDistM: number; + readonly coverMaxDistM: number; + readonly coverRetreatBudgetSec: number; + readonly reloadAdvanceAngleDeg: number; + readonly hullAngleTriggerDeg: number; + readonly hullAngleTargetDeg: number; + readonly maxTotalHaltSec: number; + readonly stalemateMissShots: number; + readonly stalemateNoShotHalts: number; + readonly repositionMinMoveM: number; + readonly repositionStepM: number; + readonly repairSafeEnemyDistM: number; + }; + readonly tactics: { + readonly visionRangeM: number; + readonly visionFovDeg: number; + readonly peripheralRangeM: number; + readonly engineAudioRangeM: number; + readonly shotAudioRangeM: number; + readonly radioShareRangeM: number; + readonly memoryTtlSec: number; + readonly targetStickinessSec: number; + readonly peekCooldownSec: number; + }; + readonly estimation: { + readonly watchMinSec: number; + readonly watchMaxSec: number; + readonly velSampleMinSpanSec: number; + readonly velStableSpanSec: number; + readonly velJumpResetMps: number; + readonly baseAimSigmaM: number; + readonly leadErrorFrac: number; + readonly maxBiasM: number; + }; + readonly fireControl: { + readonly maxEngageRangeM: number; + readonly closeRangeM: number; + readonly midRangeM: number; + readonly longRangeM: number; + readonly midSlowSpeedRatio: number; + readonly midSlowMaxMps: number; + readonly stopSpeedMaxMps: number; + readonly longRangeWindowSec: number; + readonly baseAlignDeg: number; + readonly closeHitRadiusM: number; + readonly barrelSettleDegSec: number; + readonly closeSettleHoldSec: number; + readonly settleHoldSec: number; + readonly unstabilizedStopSpeedMps: number; + readonly stabilizedCreepSpeedMps: number; + readonly friendlyCorridorM: number; + readonly ballisticStepMaxM: number; + readonly ballisticSweepRadiusM: number; + readonly maxPreFireChecksPerTick: number; + }; + readonly diagnostics: { + readonly telemetry: boolean; + readonly telemetryIntervalSec: number; + }; +} + +export function isGroundAiActive(config: GroundAiConfig | undefined): boolean { + return config !== undefined && config.mode !== 'stock'; +} + +/** True when custom team orders and driving replace stock movement. */ +export function groundAiOwnsMovement(config: GroundAiConfig): boolean { + return config.mode === 'drive' || config.mode === 'full'; +} + +/** True when custom perception and fire permission replace stock aiming and firing. */ +export function groundAiOwnsFire(config: GroundAiConfig): boolean { + return config.mode === 'fire' || config.mode === 'full'; +} + +type DasEntry = readonly [name: string, kind: 'bool' | 'int' | 'float' | 'string', value: boolean | number | string]; + +export function compileGroundAiConfigDas(config: GroundAiConfig): string { + const entries = collectConfigEntries(config); + const lines = [ + '// Auto-generated from tuning/ground-ai.jsonc during game copy build. Do not edit by hand.', + 'options indenting = 2', + 'options no_global_heap = true', + 'module wto_ai_config_common shared', + '', + ]; + for (const [name, kind, value] of entries) { + lines.push(`let public ${name} : ${kind} = ${formatDasLiteral(name, kind, value)}`); + } + lines.push(''); + return lines.join('\n'); +} + +function collectConfigEntries(c: GroundAiConfig): readonly DasEntry[] { + const movement = groundAiOwnsMovement(c); + const fire = groundAiOwnsFire(c); + return [ + ['WTO_AI_ENABLED', 'bool', isGroundAiActive(c)], + ['WTO_AI_LAYER_MACRO', 'bool', movement], + // Perception runs inside the tactics layer, so every custom mode keeps it on. + ['WTO_AI_LAYER_TACTICS', 'bool', movement || fire], + ['WTO_AI_LAYER_NAVIGATION', 'bool', movement], + ['WTO_AI_LAYER_FIRE_CONTROL', 'bool', fire], + ['WTO_AI_MAX_TRACKED_BOTS', 'int', c.cadence.maxBots], + ['WTO_AI_MACRO_TICK_SEC', 'float', c.cadence.macroTickSec], + ['WTO_AI_TACTICS_TICK_SEC', 'float', c.cadence.tacticsTickSec], + ['WTO_AI_NAV_TICK_SEC', 'float', c.cadence.navTickSec], + ['WTO_AI_CMD_REBALANCE_SEC', 'float', c.commander.rebalanceSec], + ['WTO_AI_CMD_ROLE_HOLD_SEC', 'float', c.commander.roleHoldSec], + ['WTO_AI_CMD_BTTL_ASSAULT_PCT', 'int', c.commander.bttlAssaultPct], + ['WTO_AI_CMD_BTTL_FLANK_PCT', 'int', c.commander.bttlFlankPct], + ['WTO_AI_CMD_BTTL_OVERWATCH_PCT', 'int', c.commander.bttlOverwatchPct], + ['WTO_AI_CMD_CONQ_ASSAULT_PCT', 'int', c.commander.conqAssaultPct], + ['WTO_AI_CMD_CONQ_FLANK_PCT', 'int', c.commander.conqFlankPct], + ['WTO_AI_CMD_CONQ_HOLD_DEFEND_PCT', 'int', c.commander.conqHoldDefendPct], + ['WTO_AI_CMD_CONQ_HOLD_OVERWATCH_PCT', 'int', c.commander.conqHoldOverwatchPct], + ['WTO_AI_CMD_DOM_ASSAULT_PCT', 'int', c.commander.domAssaultPct], + ['WTO_AI_CMD_DOM_MAX_DEFENDERS', 'int', c.commander.domMaxDefendersPerCap], + ['WTO_AI_CMD_OVERWATCH_STANDOFF_M', 'float', c.commander.overwatchStandOffM], + ['WTO_AI_CMD_FLANK_STANDOFF_M', 'float', c.commander.flankStandOffM], + ['WTO_AI_CMD_SPAA_FOLLOW_OFFSET_M', 'float', c.commander.spaaFollowOffsetM], + ['WTO_AI_CMD_FLANK_MAX_RATIO', 'float', c.commander.flankMaxLengthRatio], + ['WTO_AI_CMD_FLANK_MIN_SEP_M', 'float', c.commander.flankMinSeparationM], + ['WTO_AI_CMD_RALLY_PROG_FRAC', 'float', c.commander.rallyProgressFrac], + ['WTO_AI_CMD_RALLY_WAIT_SEC', 'float', c.commander.rallyWaitSec], + ['WTO_AI_CMD_RALLY_MIN_FRAC', 'float', c.commander.rallyMinFrac], + ['WTO_AI_CMD_RALLY_RADIUS_M', 'float', c.commander.rallyRadiusM], + ['WTO_AI_CMD_RECALL_SAFE_SEC', 'float', c.commander.recallSafeHoldSec], + ['WTO_AI_MACRO_OPENING_SPLIT_SEC', 'float', c.macro.openingSplitSec], + ['WTO_AI_MACRO_CAP_MAX_INSIDERS', 'int', c.macro.capMaxInsiders], + ['WTO_AI_MACRO_RECAP_MIN_BOTS', 'int', c.macro.recaptureMinBots], + ['WTO_AI_MACRO_RECAP_MAX_BOTS', 'int', c.macro.recaptureMaxBots], + ['WTO_AI_MACRO_CAP_STICKY_BONUS_M', 'float', c.macro.capStickyBonusM], + ['WTO_AI_MACRO_DEATH_ZONE_RAD_M', 'float', c.macro.deathZoneRadiusM], + ['WTO_AI_MACRO_DEATH_ZONE_TTL_SEC', 'float', c.macro.deathZoneTtlSec], + ['WTO_AI_MACRO_DEATH_ZONE_MIN_KILLS', 'int', c.macro.deathZoneMinKills], + ['WTO_AI_MACRO_SPAA_REAR_OFFSET_M', 'float', c.macro.spaaRearOffsetM], + ['WTO_AI_MACRO_SPAA_RELOCATE_SEC', 'float', c.macro.spaaRelocateSec], + ['WTO_AI_MACRO_ENEMY_SPAWN_AVOID_M', 'float', c.macro.enemySpawnAvoidM], + ['WTO_AI_CROWD_PERSONAL_SPACE_M', 'float', c.crowd.personalSpaceM], + ['WTO_AI_CROWD_CLUSTER_RADIUS_M', 'float', c.crowd.clusterRadiusM], + ['WTO_AI_CROWD_CLUSTER_MAX_ALLIES', 'int', c.crowd.clusterMaxAllies], + ['WTO_AI_CROWD_DISPERSE_STEP_M', 'float', c.crowd.disperseStepM], + ['WTO_AI_CROWD_DISPERSE_HOLD_SEC', 'float', c.crowd.disperseHoldSec], + ['WTO_AI_TERRAIN_MAX_CLIMB_DEG', 'float', c.terrain.maxClimbSlopeDeg], + ['WTO_AI_TERRAIN_MAX_DROP_DEG', 'float', c.terrain.maxDropSlopeDeg], + ['WTO_AI_TERRAIN_MAX_WATER_M', 'float', c.terrain.maxWaterDepthM], + ['WTO_AI_TERRAIN_MARGIN_M', 'float', c.terrain.collisionMarginM], + ['WTO_AI_TERRAIN_CREST_LOOKAHEAD_M', 'float', c.terrain.crestLookaheadM], + ['WTO_AI_TERRAIN_RIDGE_MAX_DWELL_SEC', 'float', c.terrain.ridgeMaxDwellSec], + ['WTO_AI_TERRAIN_RIDGE_MAX_SHOTS', 'int', c.terrain.ridgeMaxShots], + ['WTO_AI_NAV_DRIVE_MODE', 'string', c.navigation.driveMode], + ['WTO_AI_NAV_MAX_PHYS_BOTS', 'int', c.navigation.maxPhysBots], + ['WTO_AI_NAV_STEER_SIGN', 'float', c.navigation.steerSign], + ['WTO_AI_NAV_DEAD_ECHO_SEC', 'float', c.navigation.deadEchoSec], + ['WTO_AI_NAV_CONTROL_TIMEOUT_SEC', 'float', c.navigation.controlTimeoutSec], + ['WTO_AI_NAV_CORNER_BRAKE_ACCEL', 'float', c.navigation.cornerBrakeAccel], + ['WTO_AI_NAV_PIVOT_ANGLE_DEG', 'float', c.navigation.pivotAngleDeg], + ['WTO_AI_NAV_STUCK_WINDOW_SEC', 'float', c.navigation.stuckWindowSec], + ['WTO_AI_NAV_STUCK_MIN_MOVE_M', 'float', c.navigation.stuckMinMoveM], + ['WTO_AI_NAV_UNSTICK_REV_SEC', 'float', c.navigation.unstickReverseSec], + ['WTO_AI_NAV_TAC_REV_DIST_M', 'float', c.navigation.tacticalReverseDistM], + ['WTO_AI_NAV_TAC_REV_MAX_SEC', 'float', c.navigation.tacticalReverseMaxSec], + ['WTO_AI_PERC_FOLIAGE_TRANS', 'float', c.perception.foliageTransparency], + ['WTO_AI_PERC_NEAR_SPOT_M', 'float', c.perception.nearSpotRangeM], + ['WTO_AI_PERC_FIRING_SPOT_M', 'float', c.perception.firingSpotRangeM], + ['WTO_AI_PERC_FAST_SPOT_SEC', 'float', c.perception.fastSpotSec], + ['WTO_AI_PERC_NORMAL_SPOT_SEC', 'float', c.perception.normalSpotSec], + ['WTO_AI_PERC_FAR_SPOT_SEC', 'float', c.perception.farSpotSec], + ['WTO_AI_PERC_DECAY_PER_SEC', 'float', c.perception.decayPerSec], + ['WTO_AI_PERC_FRONT_CONE_DEG', 'float', c.perception.frontConeHalfDeg], + ['WTO_AI_PERC_PERIPH_CLOSE_M', 'float', c.perception.peripheralCloseM], + ['WTO_AI_SM_PREAIM_DEG', 'float', c.stateMachine.preaimAngleDeg], + ['WTO_AI_SM_SHORT_HALT_MAX_SEC', 'float', c.stateMachine.shortHaltMaxSec], + ['WTO_AI_SM_SHORT_HALT_COOLDOWN_SEC', 'float', c.stateMachine.shortHaltCooldownSec], + ['WTO_AI_SM_TURN_LAUNCH_MPS', 'float', c.stateMachine.turnLaunchSpeedMps], + ['WTO_AI_SM_COVER_MIN_DIST_M', 'float', c.stateMachine.coverMinDistM], + ['WTO_AI_SM_COVER_MAX_DIST_M', 'float', c.stateMachine.coverMaxDistM], + ['WTO_AI_SM_COVER_RETREAT_SEC', 'float', c.stateMachine.coverRetreatBudgetSec], + ['WTO_AI_SM_RELOAD_ADV_DEG', 'float', c.stateMachine.reloadAdvanceAngleDeg], + ['WTO_AI_SM_HULL_ANGLE_TRIG_DEG', 'float', c.stateMachine.hullAngleTriggerDeg], + ['WTO_AI_SM_HULL_ANGLE_TGT_DEG', 'float', c.stateMachine.hullAngleTargetDeg], + ['WTO_AI_SM_MAX_TOTAL_HALT_SEC', 'float', c.stateMachine.maxTotalHaltSec], + ['WTO_AI_SM_STALE_MISS_SHOTS', 'int', c.stateMachine.stalemateMissShots], + ['WTO_AI_SM_STALE_NOSHOT_HALTS', 'int', c.stateMachine.stalemateNoShotHalts], + ['WTO_AI_SM_REPOS_MIN_MOVE_M', 'float', c.stateMachine.repositionMinMoveM], + ['WTO_AI_SM_REPOS_STEP_M', 'float', c.stateMachine.repositionStepM], + ['WTO_AI_SM_REPAIR_SAFE_DIST_M', 'float', c.stateMachine.repairSafeEnemyDistM], + ['WTO_AI_TACTICS_VISION_RANGE_M', 'float', c.tactics.visionRangeM], + ['WTO_AI_TACTICS_VISION_FOV_DEG', 'float', c.tactics.visionFovDeg], + ['WTO_AI_TACTICS_PERIPHERAL_RANGE_M', 'float', c.tactics.peripheralRangeM], + ['WTO_AI_TACTICS_ENGINE_AUDIO_M', 'float', c.tactics.engineAudioRangeM], + ['WTO_AI_TACTICS_SHOT_AUDIO_M', 'float', c.tactics.shotAudioRangeM], + ['WTO_AI_TACTICS_RADIO_SHARE_M', 'float', c.tactics.radioShareRangeM], + ['WTO_AI_TACTICS_MEMORY_TTL_SEC', 'float', c.tactics.memoryTtlSec], + ['WTO_AI_TACTICS_STICKY_SEC', 'float', c.tactics.targetStickinessSec], + ['WTO_AI_TACTICS_PEEK_COOLDOWN_SEC', 'float', c.tactics.peekCooldownSec], + ['WTO_AI_EST_WATCH_MIN_SEC', 'float', c.estimation.watchMinSec], + ['WTO_AI_EST_WATCH_MAX_SEC', 'float', c.estimation.watchMaxSec], + ['WTO_AI_EST_MIN_SPAN_SEC', 'float', c.estimation.velSampleMinSpanSec], + ['WTO_AI_EST_STABLE_SPAN_SEC', 'float', c.estimation.velStableSpanSec], + ['WTO_AI_EST_JUMP_RESET_MPS', 'float', c.estimation.velJumpResetMps], + ['WTO_AI_EST_BASE_SIGMA_M', 'float', c.estimation.baseAimSigmaM], + ['WTO_AI_EST_LEAD_ERR_FRAC', 'float', c.estimation.leadErrorFrac], + ['WTO_AI_EST_MAX_BIAS_M', 'float', c.estimation.maxBiasM], + ['WTO_AI_FC_MAX_RANGE_M', 'float', c.fireControl.maxEngageRangeM], + ['WTO_AI_FC_CLOSE_RANGE_M', 'float', c.fireControl.closeRangeM], + ['WTO_AI_FC_MID_RANGE_M', 'float', c.fireControl.midRangeM], + ['WTO_AI_FC_LONG_RANGE_M', 'float', c.fireControl.longRangeM], + ['WTO_AI_FC_MID_SLOW_RATIO', 'float', c.fireControl.midSlowSpeedRatio], + ['WTO_AI_FC_MID_SLOW_MAX_MPS', 'float', c.fireControl.midSlowMaxMps], + ['WTO_AI_FC_STOP_SPEED_MAX_MPS', 'float', c.fireControl.stopSpeedMaxMps], + ['WTO_AI_FC_LONG_WINDOW_SEC', 'float', c.fireControl.longRangeWindowSec], + ['WTO_AI_FC_BASE_ALIGN_DEG', 'float', c.fireControl.baseAlignDeg], + ['WTO_AI_FC_CLOSE_HIT_RADIUS_M', 'float', c.fireControl.closeHitRadiusM], + ['WTO_AI_FC_BARREL_SETTLE_DEG_SEC', 'float', c.fireControl.barrelSettleDegSec], + ['WTO_AI_FC_CLOSE_SETTLE_HOLD_SEC', 'float', c.fireControl.closeSettleHoldSec], + ['WTO_AI_FC_SETTLE_HOLD_SEC', 'float', c.fireControl.settleHoldSec], + ['WTO_AI_FC_UNSTAB_STOP_MPS', 'float', c.fireControl.unstabilizedStopSpeedMps], + ['WTO_AI_FC_STAB_CREEP_MPS', 'float', c.fireControl.stabilizedCreepSpeedMps], + ['WTO_AI_FC_FRIENDLY_CORRIDOR_M', 'float', c.fireControl.friendlyCorridorM], + ['WTO_AI_FC_BALLISTIC_STEP_M', 'float', c.fireControl.ballisticStepMaxM], + ['WTO_AI_FC_BALLISTIC_SWEEP_R_M', 'float', c.fireControl.ballisticSweepRadiusM], + ['WTO_AI_FC_MAX_CHECKS_PER_TICK', 'int', c.fireControl.maxPreFireChecksPerTick], + ['WTO_AI_DIAG_TELEMETRY', 'bool', c.diagnostics.telemetry], + ['WTO_AI_DIAG_INTERVAL_SEC', 'float', c.diagnostics.telemetryIntervalSec], + ]; +} + +function formatDasLiteral(name: string, kind: 'bool' | 'int' | 'float' | 'string', value: boolean | number | string): string { + if (kind === 'bool') { + if (typeof value !== 'boolean') throw new Error(`ground AI config ${name} must be boolean`); + return value ? 'true' : 'false'; + } + if (kind === 'int') { + if (typeof value !== 'number' || !Number.isInteger(value) || value < -2147483648 || value > 2147483647) { + throw new Error(`ground AI config ${name} must be a 32-bit integer`); + } + return String(value); + } + if (kind === 'float') { + if (typeof value !== 'number' || !Number.isFinite(value)) throw new Error(`ground AI config ${name} must be finite`); + const text = String(value); + return text.includes('.') || text.includes('e') || text.includes('E') ? text : `${text}.0`; + } + if (typeof value !== 'string' || /[\r\n\0]/.test(value)) { + throw new Error(`ground AI config ${name} must be a single-line string`); + } + return `"${value.replaceAll('\\', '\\\\').replaceAll('"', '\\"')}"`; +} diff --git a/packages/patcher/src/index.ts b/packages/patcher/src/index.ts index 400e759..dff2b03 100644 --- a/packages/patcher/src/index.ts +++ b/packages/patcher/src/index.ts @@ -58,9 +58,32 @@ export { isHardlinkableResource, type HardlinkResourceRules, } from './hardlink-resources.ts'; +export { + GAME_AI_ARCHIVE_FOLDER, + GAME_AI_CONFIG_FILE, + GAME_PACK_FILE, + rebuildGamePack, + type GamePackResult, + type GroundAiBuildInputs, +} from './ground-ai/game-pack.ts'; +export { + compileGroundAiConfigDas, + GROUND_AI_MODES, + isGroundAiActive, + type GroundAiConfig, + type GroundAiLoadoutConfig, + type GroundAiMode, +} from './ground-ai/ground-ai-config.ts'; export { rebuildGuiPack, type AppliedGuiPatch, type GuiPackResult } from './gui-pack.ts'; export { loadGuiPatches, type GuiScriptEdit, type GuiScriptPatch, type GuiScriptVariant } from './gui-patch-definition.ts'; -export { ENGINE_SETTINGS_PATH, EXTRA_STORE_BUNDLE_GUID_MAP, EXTRA_STORE_BUNDLE_GUIDS, rebuildMainPack, type MainPackResult } from './main-pack.ts'; +export { + AI_LIST_PATH, + ENGINE_SETTINGS_PATH, + EXTRA_STORE_BUNDLE_GUID_MAP, + EXTRA_STORE_BUNDLE_GUIDS, + rebuildMainPack, + type MainPackResult, +} from './main-pack.ts'; export { redirectAddresses, type AddressChange } from './network/address-rewrite.ts'; export { hostPort, localEndpoint, localUrl, type LocalEndpoint } from './network/local-endpoint.ts'; export { NETWORK_HOOK_LIBRARY, networkHookSettings } from './network/network-hook.ts'; diff --git a/packages/patcher/src/main-pack.ts b/packages/patcher/src/main-pack.ts index 26a6123..00f2b7e 100644 --- a/packages/patcher/src/main-pack.ts +++ b/packages/patcher/src/main-pack.ts @@ -20,6 +20,7 @@ import { editPackBlks } from './pack-edit.ts'; export const ENGINE_SETTINGS_PATH = 'config/settings.blk'; export const GUI_CONFIG_PATH = 'config/gui.blk'; +export const AI_LIST_PATH = 'gamedata/ai/ailist.blk'; const NETWORK_BLOCK = 'network'; /** @@ -46,10 +47,10 @@ export function rebuildMainPack( extraAddonFolders: readonly string[] = [], ): MainPackResult { let addresses: AddressChange[] = []; - const pack = editPackBlks(stockPack, [ + const edits = [ { path: ENGINE_SETTINGS_PATH, - edit: (root) => { + edit: (root: BlkBlock) => { const network = findBlock(root, NETWORK_BLOCK); if (!network) throw new Error(`${ENGINE_SETTINGS_PATH} has no "${NETWORK_BLOCK}" block; this game build differs from the verified ones`); addresses = redirectAddresses(network, endpoint, [NETWORK_BLOCK]); @@ -58,9 +59,10 @@ export function rebuildMainPack( }, { path: GUI_CONFIG_PATH, - edit: (root) => registerStoreBundleGuids(root, [...EXTRA_STORE_BUNDLE_GUIDS, ...extraBundles]), + edit: (root: BlkBlock) => registerStoreBundleGuids(root, [...EXTRA_STORE_BUNDLE_GUIDS, ...extraBundles]), }, - ]); + ]; + const pack = editPackBlks(stockPack, edits); return { pack, addresses }; } diff --git a/patches/native/local_mp_ground_ai.jsonc b/patches/native/local_mp_ground_ai.jsonc new file mode 100644 index 0000000..2c6d023 --- /dev/null +++ b/patches/native/local_mp_ground_ai.jsonc @@ -0,0 +1,78 @@ +// Temporary movement ownership for custom ground AI on a LocalMP host. +// The local server cannot restore the MoveSystem flag if a game script stops running. +// Without this module, stock tank movement keeps ownership of the vehicle. +{ + "module": "local_mp_ground_ai", + "features": ["K-AI opponents and teammates"], + "requires": ["local_mp_core", "local_mp_players"], + "sites": { + // daScript call_mission_action binding, capturing the registered native function. + // 2.61.0.37: 0xa6be4d -> 0xa63750. 2.61.0.58: 0xa6eb0d -> 0xa66410. + "ground_ai_mission_binding": { + "variants": [{ + "written_for": "2.61.0.37", + "locate": { + "method": "string_ref", + "string": "call_mission_action", + "lea_at": 0, + "pattern": "48 8d 15 ?? ?? ?? ?? 4c 8d 05 ?? ?? ?? ?? e8 ?? ?? ?? ?? 80 8e 30 01 00 00 04 48 8d 05 ?? ?? ?? ?? 48 89 06 48 8d 05 ?? ?? ?? ?? 48 89 86 b0 01 00 00", + "captures": { + "action": { "offset": 39, "type": "rel32" } + } + } + }] + }, + // Leaf shared by the two daScript as_gm overloads. The mask is the engine's ground-model check. + // 2.61.0.37: 0xa1f1f0. 2.61.0.58: 0xa21ea0. + "ground_ai_as_ground_model": { + "variants": [{ + "written_for": "2.61.0.37", + "locate": { + "method": "signature", + "pattern": "48 85 c9 74 15 8b 91 ?? ?? ?? ?? f7 d2 31 c0 f7 c2 00 80 01 00 48 0f 44 c1 c3 31 c0 c3" + } + }] + }, + // IGroundModel's avoidObstacles property handler reads its MoveSystem pointer. + // 2.61.0.37: 0x424334. 2.61.0.58: 0x4248d4. + "ground_ai_move_properties": { + "variants": [{ + "written_for": "2.61.0.37", + "locate": { + "method": "string_ref", + "string": "avoidObstacles", + "lea_at": 0, + "pattern": "48 8d 15 ?? ?? ?? ?? 4c 8d 44 24 24 48 89 d9 e8 ?? ?? ?? ?? 84 c0 74 13 48 8b 87 ?? ?? ?? ?? 48 85 c0 74 07 c6 80 ?? ?? ?? ?? 01", + "captures": { + "move_system": { "offset": 27, "type": "u32" } + } + } + }] + }, + // The MoveSystem daScript annotation registers the bool field named "inactive". + // 2.61.0.37: 0xa1c374. 2.61.0.58: 0xa1f024. + "ground_ai_move_annotation": { + "variants": [{ + "written_for": "2.61.0.37", + "locate": { + "method": "signature", + "pattern": "48 b8 69 6e 61 63 74 69 76 65 48 89 44 24 30 c6 44 24 38 00 c6 44 24 67 0f 48 89 44 24 50 c6 44 24 58 00 48 8b 8b a8 01 00 00 e8 ?? ?? ?? ?? 48 89 84 24 a0 00 00 00 4c 89 74 24 20 48 8d 54 24 50 4c 8d 44 24 30 48 89 d9 41 b9 ?? ?? ?? ?? e8 ?? ?? ?? ??" + ,"captures": { + "inactive": { "offset": 75, "type": "u32" } + } + } + }] + }, + // driveToPos::update (vtable[1] of the tankBot driveToPos behavior node). + // 2.61.0.37: 0x861370. 2.61.0.58: 0x863a90. + "ground_ai_drive_to_pos_update": { + "variants": [{ + "written_for": "2.61.0.37", + "locate": { + "method": "signature", + "pattern": "41 57 41 56 41 55 41 54 56 57 55 53 48 81 ec 98 02 00 00 44 0f 29 bc 24 80 02 00 00 44 0f 29 b4 24 70 02 00 00 44 0f 29 ac 24 60 02 00 00 44 0f 29 a4 24 50 02 00 00 44 0f 29 9c 24 40 02 00 00 44 0f 29 94 24 30 02 00 00 44 0f 29 8c 24 20 02 00 00 44 0f 29 84 24 10 02 00 00 0f 29 bc 24 00 02 00 00 0f 29 b4 24 f0 01 00 00 44 0f 28 da 49 89 cf 48 8b 3d ?? ?? ?? ?? 44 8b 72 08 0f b6 87 f3 00 00 00 48 8b 9f 60 06 00 00 48 85 db 40 0f 94 c5 40 08 c5 40 f6 c5 01 75 09 48 89 d9 ff 15 ?? ?? ?? ?? 44" + } + }] + } + } +} diff --git a/scripts/build-game-copy.ts b/scripts/build-game-copy.ts index d83334e..cfd760a 100644 --- a/scripts/build-game-copy.ts +++ b/scripts/build-game-copy.ts @@ -24,25 +24,43 @@ import { join } from 'node:path'; import { fileURLToPath } from 'node:url'; import { parseArgs } from 'node:util'; import type { PatchFailure } from '@wto/exepatch'; +import { discoverMods, touchedClientPacks, type DiscoveredMod, type ModdableClientPack } from '@wto/mods'; import { assertWritableCopy, buildGameCopy, + computeModsBuildFingerprint, copyPlayerDecalCache, + CORE_BUILD_PACKS, + GAME_PACK_FILE, + isGroundAiActive, NETWORK_HOOK_LIBRARY, playerDecalCacheProblem, + prepareOptionalStockPacks, readPlayerDecalIndexFiles, readStockGameFiles, + syncExternalModFiles, writeGameCopy, type GameCopyBuild, } from '@wto/patcher'; -import { multiVehiclePackIds } from '@wto/server'; +import { loadGroundAiTuning, multiVehiclePackIds } from '@wto/server'; const REPOSITORY = fileURLToPath(new URL('..', import.meta.url)); const USAGE = 'usage: build-game-copy.ts --game --out --port --data ' - + '[--patches ] [--native ] [--decal-cache ] ' - + '[--skip-unavailable] [--verbose]'; + + '[--patches ] [--native ] [--ground-ai ] ' + + '[--mods-dir --mod ...] [--decal-cache ] [--skip-unavailable] [--verbose]'; -function main(): number { +function resolveCliMods(modsDir: string | undefined, modIds: readonly string[] | undefined): DiscoveredMod[] { + if (!modsDir || !modIds || modIds.length === 0) return []; + const discovered = discoverMods(modsDir); + const byId = new Map(discovered.mods.map((mod) => [mod.manifest.id, mod])); + return modIds.map((id) => { + const mod = byId.get(id); + if (!mod) throw new Error(`enabled mod "${id}" was not found in ${modsDir}`); + return mod; + }); +} + +function parseCliOptions() { const { values } = parseArgs({ options: { game: { type: 'string' }, @@ -51,11 +69,19 @@ function main(): number { data: { type: 'string' }, patches: { type: 'string', default: join(REPOSITORY, 'patches') }, native: { type: 'string', default: join(REPOSITORY, 'build', 'native') }, + 'ground-ai': { type: 'string', default: join(REPOSITORY, 'game-ai', 'ground') }, + 'mods-dir': { type: 'string' }, + mod: { type: 'string', multiple: true }, 'decal-cache': { type: 'string' }, 'skip-unavailable': { type: 'boolean', default: false }, verbose: { type: 'boolean', default: false }, }, }); + return values; +} + +function main(): number { + const values = parseCliOptions(); if (!values.game || !values.out || !values.port || !values.data) { console.error(USAGE); return 2; @@ -73,18 +99,43 @@ function main(): number { return 1; } + const port = Number(values.port); + const enabledMods = resolveCliMods(values['mods-dir'], values.mod); + const groundAiConfig = loadGroundAiTuning(values.data, (line) => console.log(line), enabledMods); + const touchedSet = new Set( + touchedClientPacks(enabledMods).filter((pack) => !CORE_BUILD_PACKS.has(pack)), + ); + if (isGroundAiActive(groundAiConfig)) touchedSet.add(GAME_PACK_FILE); + const optionalPacksInBuild = [...touchedSet]; + const extraStockPacks = optionalPacksInBuild.length > 0 + ? prepareOptionalStockPacks(values.out, values.game, optionalPacksInBuild) + : undefined; const decalIndexFiles = decalCache === undefined ? undefined : readPlayerDecalIndexFiles(decalCache); + const build = buildGameCopy({ stock: readStockGameFiles(values.game), - port: Number(values.port), + port, patches: values.patches, networkHookLibrary: readFileSync(hookLibraryPath), - multiVehiclePackIds: multiVehiclePackIds(values.data, (line) => console.log(line)), + multiVehiclePackIds: multiVehiclePackIds(values.data, (line) => console.log(line), enabledMods), placeholderDecals: decalCache === undefined, ...(decalIndexFiles ? { decalIndexFiles } : {}), + ...(enabledMods.length > 0 ? { mods: enabledMods } : {}), + ...(extraStockPacks ? { extraStockPacks } : {}), + groundAi: { scriptsFolder: values['ground-ai'], config: groundAiConfig }, }); report(build, values.verbose); + return finishCliWrite(values, build, enabledMods, optionalPacksInBuild, groundAiConfig, port); +} +function finishCliWrite( + values: ReturnType, + build: GameCopyBuild, + enabledMods: readonly DiscoveredMod[], + optionalPacksInBuild: readonly ModdableClientPack[], + groundAiConfig: ReturnType, + port: number, +): number { const failures = [...build.exePatches.failures, ...build.guiPatches.failures, ...build.nativeModules.failures]; if (build.blocking.length) { console.error(`essential patch(es) unavailable: ${build.blocking.map((failure) => failure.patchId).join(', ')}; nothing was written`); @@ -95,9 +146,16 @@ function main(): number { return 1; } - for (const path of writeGameCopy(values.out, build.files)) console.log(`wrote ${path}`); - if (decalCache !== undefined) { - const copied = copyPlayerDecalCache(decalCache, values.out); + for (const path of writeGameCopy(values.out!, build.files)) console.log(`wrote ${path}`); + const fingerprint = computeModsBuildFingerprint( + enabledMods, + port, + `${values.patches}|groundAi=${JSON.stringify(groundAiConfig)}`, + ); + const deploy = syncExternalModFiles(values.out!, values.game!, enabledMods, optionalPacksInBuild, fingerprint); + for (const restored of deploy.restoredOptionalPacks) console.log(`restored stock ${restored}`); + if (values['decal-cache'] !== undefined) { + const copied = copyPlayerDecalCache(values['decal-cache'], values.out!); console.log(`copied the player's web cache to ${copied.copiedTo} (decal indexes: ${copied.decalIndexes.join(', ')})`); } return 0; @@ -126,6 +184,9 @@ function report(build: GameCopyBuild, verbose: boolean): void { console.log(`wto_ws.cfg: ${build.nativeModules.available.length} native module(s) ready, ${build.nativeModules.failures.length} unavailable`); if (verbose) for (const module of build.nativeModules.available) console.log(` ready ${module}`); reportFailures(build.nativeModules.failures); + if (build.gamePack) { + console.log(`${GAME_PACK_FILE}: ${build.gamePack.modules.length} ground AI module(s) packed in ${build.gamePack.archiveFolder}`); + } } function reportFailures(failures: readonly PatchFailure[]): void { diff --git a/scripts/build-windows-installer.ts b/scripts/build-windows-installer.ts index 80de38f..f318533 100644 --- a/scripts/build-windows-installer.ts +++ b/scripts/build-windows-installer.ts @@ -71,6 +71,7 @@ async function stageInstaller(stage: string, manifest: LauncherManifest): Promis await cp(join(repository, 'LICENSE'), join(resources, 'LICENSE-WTOffline')); await cp(join(native, 'wto_ws.dll'), join(resources, 'native', 'wto_ws.dll')); await cp(join(repository, 'mod-dev-docs', 'templates'), join(resources, 'mod-templates'), { recursive: true }); + await cp(join(repository, 'game-ai', 'ground'), join(resources, 'game-ai', 'ground'), { recursive: true }); for (const folder of ['exe', 'gui', 'native', 'versions']) { await cp(join(repository, 'patches', folder), join(resources, 'patches', folder), { recursive: true }); }