From 4ac3484f562a0d2c6e587bd24bd83fb97ded6862 Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Thu, 3 Dec 2026 12:07:30 +0800 Subject: [PATCH] feat(patcher,server): wire ground AI tuning, bot weights, and pack build Add ground-ai.jsonc tuning validation, realistic tank class weights for customBots pools, on-demand game.vromfs.bin / ailist.blk injection in @wto/patcher, and launcher/CLI build integration while keeping all ground AI layers disabled by default in shipped configuration. --- .../main/services/resources/resource-paths.ts | 4 + .../src/main/workers/build-protocol.ts | 1 + .../launcher/src/main/workers/build-worker.ts | 49 +++-- apps/server/src/battle/battle-ranks.ts | 17 +- apps/server/src/cli.ts | 25 ++- .../game-data/datasets/vehicle-catalogue.ts | 22 +- apps/server/src/index.ts | 1 + apps/server/src/tuning/ground-ai-tuning.ts | 144 +++++++++++++ apps/server/src/tuning/tuning.ts | 3 + apps/server/tuning/ground-ai.jsonc | 94 ++++++++ packages/patcher/src/build-game-copy.ts | 133 ++++++++---- packages/patcher/src/ground-ai/game-pack.ts | 79 +++++++ .../patcher/src/ground-ai/ground-ai-config.ts | 200 ++++++++++++++++++ packages/patcher/src/index.ts | 23 +- packages/patcher/src/main-pack.ts | 36 +++- scripts/build-game-copy.ts | 79 ++++++- scripts/build-windows-installer.ts | 1 + 17 files changed, 836 insertions(+), 75 deletions(-) create mode 100644 apps/server/src/tuning/ground-ai-tuning.ts create mode 100644 apps/server/tuning/ground-ai.jsonc create mode 100644 packages/patcher/src/ground-ai/game-pack.ts create mode 100644 packages/patcher/src/ground-ai/ground-ai-config.ts 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-ranks.ts b/apps/server/src/battle/battle-ranks.ts index d05ae3c..11991f0 100644 --- a/apps/server/src/battle/battle-ranks.ts +++ b/apps/server/src/battle/battle-ranks.ts @@ -160,14 +160,15 @@ function pickCategoryPool( const mrank = vehicleMrank(vehicle, query.difficulty, query.requiredClass); return mrank >= query.minMrank && mrank <= query.maxMrank; }); - const source = inWindow.length > 0 ? inWindow : sortedByCloseness.slice(0, query.limitPerType); - return roundRobinByCountry(source, orderedCountries, query.limitPerType); + const source = inWindow.length > 0 ? inWindow : sortedByCloseness.slice(0, query.limitPerType); + return roundRobinByCountry(source, orderedCountries, query.limitPerType, category); } function roundRobinByCountry( vehicles: readonly CatalogueVehicle[], orderedCountries: readonly string[], limit: number, + category: 'tank' | 'aircraft' | 'ship', ): BotPoolEntry[] { const buckets = new Map(orderedCountries.map((country) => [country, []])); for (const vehicle of vehicles) buckets.get(vehicle.country)?.push(vehicle); @@ -177,7 +178,8 @@ 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 }); + const weight = category === 'tank' ? tankBotPoolWeight(vehicle) : 1; + out.push({ name: vehicle.name, country: stripCountryPrefix(country), weight }); added = true; if (out.length >= limit) break; } @@ -186,6 +188,15 @@ function roundRobinByCountry( return out; } +function tankBotPoolWeight(vehicle: CatalogueVehicle): number { + if (vehicle.unitClass === 'exp_SPAA') return 0.12; + if (vehicle.isLightTank) return 0.45; + if (vehicle.unitClass === 'exp_tank_destroyer') return 0.55; + if (vehicle.unitClass === 'exp_heavy_tank') return 0.85; + if (vehicle.unitClass === 'exp_tank') return 1.15; + return 1; +} + function unitClassOfVehicleType(type: VehicleType | undefined): UnitClass | undefined { if (type === 'Tank') return 'tank'; if (type === 'Aircraft') return 'aircraft'; 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/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/tuning/ground-ai-tuning.ts b/apps/server/src/tuning/ground-ai-tuning.ts new file mode 100644 index 0000000..83a7d28 --- /dev/null +++ b/apps/server/src/tuning/ground-ai-tuning.ts @@ -0,0 +1,144 @@ +/** + * Typed, range-validated reader for `tuning/ground-ai.jsonc`. + */ +import type { DiscoveredMod } from '@wto/mods'; +import type { GroundAiConfig } from '@wto/patcher'; +import { tuningFiles } from './tuning-loader.ts'; +import { TuningError, type TuningReader } from './tuning-reader.ts'; + +export type GroundAiTuning = GroundAiConfig; + +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 layers = reader.object('layers'); + const cadence = reader.object('cadence'); + const diag = reader.object('diagnostics'); + return { + enabled: reader.bool('enabled'), + layers: { + macro: layers.bool('macro'), + tactics: layers.bool('tactics'), + navigation: layers.bool('navigation'), + fireControl: layers.bool('fireControl'), + }, + 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 }), + }, + macro: readMacroSection(reader.object('macro')), + crowd: readCrowdSection(reader.object('crowd')), + terrain: readTerrainSection(reader.object('terrain')), + navigation: readNavigationSection(reader.object('navigation')), + tactics: readTacticsSection(reader.object('tactics')), + fireControl: readFireControlSection(reader.object('fireControl')), + diagnostics: { + telemetry: diag.bool('telemetry'), + telemetryIntervalSec: diag.number('telemetryIntervalSec', { min: 0.5, max: 60 }), + }, + }; +} + +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 }), + 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 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 readFireControlSection(fc: TuningReader): GroundAiTuning['fireControl'] { + return { + maxEngageRangeM: fc.number('maxEngageRangeM', { min: 150, max: 3000 }), + 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 }), + 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 }), + }; +} 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..5c23058 --- /dev/null +++ b/apps/server/tuning/ground-ai.jsonc @@ -0,0 +1,94 @@ +// Ground battle AI modular configuration. +// Shipped defaults keep takeover layers off; per-client overrides live in /tuning/ground-ai.jsonc +// and compile into game/wtoai/wto_ai_config_common.das when building the game copy. +{ + "enabled": true, + + "layers": { + "macro": false, + "tactics": false, + "navigation": false, + "fireControl": false + }, + + "cadence": { + "maxBots": 64, + "macroTickSec": 0.5, + "tacticsTickSec": 0.25, + "navTickSec": 0.2 + }, + + "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": { + "driveMode": "vehicle_phys", + "maxPhysBots": 64, + "steerSign": 1.0, + "deadEchoSec": 1.2, + "cornerBrakeAccel": 1.75, + "pivotAngleDeg": 75.0, + "stuckWindowSec": 3.6, + "stuckMinMoveM": 2.0, + "unstickReverseSec": 3.0, + "tacticalReverseDistM": 34.0, + "tacticalReverseMaxSec": 9.5 + }, + + "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 + }, + + "fireControl": { + "maxEngageRangeM": 1350.0, + "baseAlignDeg": 0.42, + "closeHitRadiusM": 0.85, + "barrelSettleDegSec": 1.8, + "settleHoldSec": 0.2, + "unstabilizedStopSpeedMps": 0.45, + "stabilizedCreepSpeedMps": 5.5, + "friendlyCorridorM": 3.2 + }, + + "diagnostics": { + "telemetry": false, + "telemetryIntervalSec": 5.0 + } +} diff --git a/packages/patcher/src/build-game-copy.ts b/packages/patcher/src/build-game-copy.ts index d3700b0..86da7ee 100644 --- a/packages/patcher/src/build-game-copy.ts +++ b/packages/patcher/src/build-game-copy.ts @@ -16,6 +16,13 @@ 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, + type GamePackResult, + type GroundAiBuildInputs, +} from './ground-ai/game-pack.ts'; +import { 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 +64,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 +105,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 +125,58 @@ 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 core = buildCorePacks(inputs, endpoint, folders.gui, enabledMods, packOverlays, groundAiActive); - 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[], + groundAiActive: boolean, +) { + 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 +192,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( @@ -144,26 +199,49 @@ export function buildGameCopy(inputs: GameCopyInputs): GameCopyBuild { endpoint, bundles, addonMounts.map((mount) => mount.mountFolder), + { yieldStockTankDrive: groundAiActive && inputs.groundAi!.config.layers.navigation }, ); 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) 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 +252,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..85f7014 --- /dev/null +++ b/packages/patcher/src/ground-ai/game-pack.ts @@ -0,0 +1,79 @@ +/** + * 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 } 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'; +const GAME_MAIN_INJECT = 'ok = load_optional_folder("%appGame/wtoai") && ok'; +const MODULE_NAME = /^[a-z0-9_]+\.das$/; + +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); + } + + return { pack: writeArchive(archive), archiveFolder: GAME_AI_ARCHIVE_FOLDER, modules }; +} + +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..e81d417 --- /dev/null +++ b/packages/patcher/src/ground-ai/ground-ai-config.ts @@ -0,0 +1,200 @@ +/** + * Ground AI configuration contract shared between `@wto/server` tuning and `@wto/patcher` + * build-time daScript constant compilation (`game/wtoai/wto_ai_config_common.das`). + */ + +export interface GroundAiConfig { + readonly enabled: boolean; + readonly layers: { + readonly macro: boolean; + readonly tactics: boolean; + readonly navigation: boolean; + readonly fireControl: boolean; + }; + readonly cadence: { + readonly maxBots: number; + readonly macroTickSec: number; + readonly tacticsTickSec: number; + readonly navTickSec: 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 cornerBrakeAccel: number; + readonly pivotAngleDeg: number; + readonly stuckWindowSec: number; + readonly stuckMinMoveM: number; + readonly unstickReverseSec: number; + readonly tacticalReverseDistM: number; + readonly tacticalReverseMaxSec: 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 fireControl: { + readonly maxEngageRangeM: number; + readonly baseAlignDeg: number; + readonly closeHitRadiusM: number; + readonly barrelSettleDegSec: number; + readonly settleHoldSec: number; + readonly unstabilizedStopSpeedMps: number; + readonly stabilizedCreepSpeedMps: number; + readonly friendlyCorridorM: number; + }; + readonly diagnostics: { + readonly telemetry: boolean; + readonly telemetryIntervalSec: number; + }; +} + +export function isGroundAiActive(config: GroundAiConfig | undefined): boolean { + if (!config || !config.enabled) return false; + const { macro, tactics, navigation, fireControl } = config.layers; + return macro || tactics || navigation || fireControl; +} + +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[] { + return [ + ['WTO_AI_ENABLED', 'bool', c.enabled], + ['WTO_AI_LAYER_MACRO', 'bool', c.layers.macro], + ['WTO_AI_LAYER_TACTICS', 'bool', c.layers.tactics], + ['WTO_AI_LAYER_NAVIGATION', 'bool', c.layers.navigation], + ['WTO_AI_LAYER_FIRE_CONTROL', 'bool', c.layers.fireControl], + ['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_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_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_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_FC_MAX_RANGE_M', 'float', c.fireControl.maxEngageRangeM], + ['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_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_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..631db46 100644 --- a/packages/patcher/src/index.ts +++ b/packages/patcher/src/index.ts @@ -58,9 +58,30 @@ 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, + isGroundAiActive, + type GroundAiConfig, +} 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 MainPackOptions, + 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..f61d508 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'; /** @@ -34,9 +35,15 @@ export const EXTRA_STORE_BUNDLE_GUIDS: ReadonlyArray> = Object.fromEntries(EXTRA_STORE_BUNDLE_GUIDS); +export interface MainPackOptions { + /** Replace stock tankBot behavior children with `success` so custom chassis control owns steering. */ + readonly yieldStockTankDrive?: boolean; +} + export interface MainPackResult { readonly pack: Uint8Array; readonly addresses: readonly AddressChange[]; + readonly yieldedStockTankDrive: boolean; } export function rebuildMainPack( @@ -44,12 +51,13 @@ export function rebuildMainPack( endpoint: LocalEndpoint, extraBundles: ReadonlyArray = [], extraAddonFolders: readonly string[] = [], + options: MainPackOptions = {}, ): 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,10 +66,15 @@ 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]), }, - ]); - return { pack, addresses }; + ...(options.yieldStockTankDrive ? [{ + path: AI_LIST_PATH, + edit: (root: BlkBlock) => yieldTankBotBehaviorTree(root), + }] : []), + ]; + const pack = editPackBlks(stockPack, edits); + return { pack, addresses, yieldedStockTankDrive: options.yieldStockTankDrive === true }; } function registerStoreBundleGuids(guiRoot: BlkBlock, bundles: ReadonlyArray): void { @@ -70,3 +83,16 @@ function registerStoreBundleGuids(guiRoot: BlkBlock, bundles: ReadonlyArray + block.name === 'selector' && + block.params.some((param) => param.name === 'name' && param.value.type === 'string' && param.value.value === 'tankBot'), + ); + if (matches.length !== 1) { + throw new Error(`expected 1 "tankBot" selector in ${AI_LIST_PATH}, found ${matches.length}`); + } + const tankBot = matches[0]!; + tankBot.blocks.length = 0; + tankBot.blocks.push({ name: 'success', params: [], blocks: [] }); +} diff --git a/scripts/build-game-copy.ts b/scripts/build-game-copy.ts index d83334e..60ddbc3 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) ready 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 }); }