merge(ground-ai): merge feat/tank-ai phase 1 into main

This commit is contained in:
N0VAN0M4LY committed 2026-12-04 02:50:48 +08:00
commit 0af4183cb1
58 files changed
+6900 -84

No files matched your search

+103 -38
View File
@@ -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<Record<ModdableClientPack, Uint8Array>>;
/** 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<GamePackResult, 'pack'>;
/** 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<GamePackResult, 'pack'> | undefined {
let gamePackReport: Omit<GamePackResult, 'pack'> | 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;
}
+109
View File
@@ -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, '\\$&');
}
@@ -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('"', '\\"')}"`;
}
+24 -1
View File
@@ -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';
+6 -4
View File
@@ -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 };
}