diff --git a/apps/ai-lab/.gitignore b/apps/ai-lab/.gitignore new file mode 100644 index 0000000..2429ea8 --- /dev/null +++ b/apps/ai-lab/.gitignore @@ -0,0 +1,2 @@ +lab.local.json +.cache/ diff --git a/apps/ai-lab/index.html b/apps/ai-lab/index.html new file mode 100644 index 0000000..403ef2d --- /dev/null +++ b/apps/ai-lab/index.html @@ -0,0 +1,12 @@ + + + + + + WTOffline AI Lab + + +
+ + + diff --git a/apps/ai-lab/lab.local.example.json b/apps/ai-lab/lab.local.example.json new file mode 100644 index 0000000..8341569 --- /dev/null +++ b/apps/ai-lab/lab.local.example.json @@ -0,0 +1,5 @@ +{ + "mapsDir": "J:/GAME/WTOfflineProject-tank-ai/build/nav-stage2-fix/maps", + "logsDir": "J:/GAME/WTLab/client-2.61.0.58/.game_logs", + "python": "J:/GAME/WTOfflineProject/.venv/Scripts/python.exe" +} diff --git a/apps/ai-lab/package.json b/apps/ai-lab/package.json new file mode 100644 index 0000000..0330bcb --- /dev/null +++ b/apps/ai-lab/package.json @@ -0,0 +1,22 @@ +{ + "name": "@wto/ai-lab", + "version": "0.1.0", + "private": true, + "description": "Ground AI lab: replay viewer for battle traces and simulator runs.", + "type": "module", + "scripts": { + "dev": "vite", + "typecheck": "tsc --noEmit -p tsconfig.json" + }, + "dependencies": { + "@wto/ground-sim": "*", + "react": "^19.2.8", + "react-dom": "^19.2.8" + }, + "devDependencies": { + "@types/react": "^19.2.17", + "@types/react-dom": "^19.2.3", + "@vitejs/plugin-react": "^5.2.0", + "vite": "^7.3.6" + } +} diff --git a/apps/ai-lab/server/lab-api.ts b/apps/ai-lab/server/lab-api.ts new file mode 100644 index 0000000..78c31db --- /dev/null +++ b/apps/ai-lab/server/lab-api.ts @@ -0,0 +1,118 @@ +/** + * Dev-server API of the AI lab (local only): + * GET /api/maps levels that have a navigation pack in mapsDir + * GET /api/maps/file?name= a pack or POI file of mapsDir + * GET /api/logs game logs (.clog) in logsDir, newest first + * GET /api/logs/text?name= a log decrypted with wtotools (cached until the log changes) + * Paths come from lab.local.json next to this app (see lab.local.example.json). + */ +import { execFile } from 'node:child_process'; +import { createReadStream, existsSync, mkdirSync, readFileSync, readdirSync, statSync } from 'node:fs'; +import type { ServerResponse } from 'node:http'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import type { Connect, Plugin } from 'vite'; + +interface LabConfig { + readonly mapsDir: string; + readonly logsDir: string; + readonly python: string; +} + +const APP_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); +const CACHE_DIR = path.join(APP_DIR, '.cache'); +const SAFE_NAME = /^[\w.-]+$/; + +function loadConfig(): LabConfig { + const file = path.join(APP_DIR, 'lab.local.json'); + const raw = existsSync(file) ? (JSON.parse(readFileSync(file, 'utf8')) as Record) : {}; + const str = (key: string, fallback: string): string => (typeof raw[key] === 'string' ? (raw[key] as string) : fallback); + return { + mapsDir: str('mapsDir', path.resolve(APP_DIR, '../../build/nav-stage2-fix/maps')), + logsDir: str('logsDir', ''), + python: str('python', 'python'), + }; +} + +function sendJson(res: ServerResponse, status: number, body: unknown): void { + res.statusCode = status; + res.setHeader('Content-Type', 'application/json; charset=utf-8'); + res.end(JSON.stringify(body)); +} + +function sendFile(res: ServerResponse, file: string, type: string): void { + res.statusCode = 200; + res.setHeader('Content-Type', type); + createReadStream(file).pipe(res); +} + +function listMaps(cfg: LabConfig): { level: string; pois: boolean }[] { + if (!existsSync(cfg.mapsDir)) return []; + return readdirSync(cfg.mapsDir) + .filter((f) => f.endsWith('.wtonav')) + .map((f) => { + const level = f.slice(0, -'.wtonav'.length); + return { level, pois: existsSync(path.join(cfg.mapsDir, `${level}.pois.json`)) }; + }); +} + +function listLogs(cfg: LabConfig): { name: string; size: number; mtime: number }[] { + if (cfg.logsDir === '' || !existsSync(cfg.logsDir)) return []; + return readdirSync(cfg.logsDir) + .filter((f) => f.endsWith('.clog')) + .map((name) => { + const st = statSync(path.join(cfg.logsDir, name)); + return { name, size: st.size, mtime: st.mtimeMs }; + }) + .sort((a, b) => b.mtime - a.mtime); +} + +/** Decrypts `name` into the cache unless the cached text is newer than the log. */ +function decryptLog(cfg: LabConfig, name: string): Promise { + const source = path.join(cfg.logsDir, name); + const out = path.join(CACHE_DIR, `${name}.txt`); + mkdirSync(CACHE_DIR, { recursive: true }); + if (existsSync(out) && statSync(out).mtimeMs >= statSync(source).mtimeMs) return Promise.resolve(out); + return new Promise((resolve, reject) => { + execFile(cfg.python, ['-m', 'wtotools.cli', 'decrypt-clog', source, '--out', out], { timeout: 180_000 }, (err, _stdout, stderr) => { + if (err !== null) reject(new Error(`decrypt-clog failed: ${stderr || err.message}`)); + else resolve(out); + }); + }); +} + +async function handle(cfg: LabConfig, url: URL, res: ServerResponse): Promise { + const name = url.searchParams.get('name') ?? ''; + if (url.pathname === '/api/maps') { sendJson(res, 200, listMaps(cfg)); return true; } + if (url.pathname === '/api/logs') { sendJson(res, 200, listLogs(cfg)); return true; } + if (url.pathname !== '/api/maps/file' && url.pathname !== '/api/logs/text') return false; + if (!SAFE_NAME.test(name)) { sendJson(res, 400, { error: 'bad file name' }); return true; } + if (url.pathname === '/api/maps/file') { + const file = path.join(cfg.mapsDir, name); + if (!existsSync(file)) sendJson(res, 404, { error: `no ${name} in ${cfg.mapsDir}` }); + else sendFile(res, file, name.endsWith('.json') ? 'application/json' : 'application/octet-stream'); + return true; + } + if (!name.endsWith('.clog') || !existsSync(path.join(cfg.logsDir, name))) { + sendJson(res, 404, { error: `no log ${name}` }); + return true; + } + sendFile(res, await decryptLog(cfg, name), 'text/plain; charset=utf-8'); + return true; +} + +export function labApi(): Plugin { + return { + name: 'wto-ai-lab-api', + configureServer(server) { + const middleware: Connect.NextHandleFunction = (req, res, next) => { + const url = new URL(req.url ?? '/', 'http://localhost'); + if (!url.pathname.startsWith('/api/')) { next(); return; } + handle(loadConfig(), url, res) + .then((handled) => { if (!handled) sendJson(res, 404, { error: 'unknown endpoint' }); }) + .catch((err: unknown) => sendJson(res, 500, { error: err instanceof Error ? err.message : String(err) })); + }; + server.middlewares.use(middleware); + }, + }; +} diff --git a/apps/ai-lab/src/App.tsx b/apps/ai-lab/src/App.tsx new file mode 100644 index 0000000..161f5cd --- /dev/null +++ b/apps/ai-lab/src/App.tsx @@ -0,0 +1,139 @@ +/** AI lab replay viewer: pick a game log, a battle in it, and play it back on the map. */ +import type { TraceBattle } from '@wto/ground-sim'; +import { useEffect, useMemo, useState } from 'react'; +import { fetchLogs, fetchMaps, loadLog, loadMap, type LogEntry, type MapData, type MapEntry } from './data.ts'; +import type { Layers } from './draw.ts'; +import { sceneAt } from './frames.ts'; +import { Inspector } from './Inspector.tsx'; +import { buildMapLayer } from './mapLayer.ts'; +import { MapView } from './MapView.tsx'; +import { Timeline } from './Timeline.tsx'; + +const LAYER_LABELS: Readonly> = { + goals: '目标点', links: '目标连线', cones: '炮塔视野', labels: '标签', events: '开火与受击', +}; + +function logLabel(l: LogEntry): string { + const when = new Date(l.mtime).toLocaleString(); + return `${l.name}(${(l.size / 1e6).toFixed(1)} MB,${when})`; +} + +export function App(): React.JSX.Element { + const [maps, setMaps] = useState([]); + const [logs, setLogs] = useState([]); + const [logName, setLogName] = useState(''); + const [battles, setBattles] = useState([]); + const [battleIdx, setBattleIdx] = useState(0); + const [mapData, setMapData] = useState(undefined); + const [exposure, setExposure] = useState(false); + const [covers, setCovers] = useState(false); + const [layers, setLayers] = useState({ goals: true, links: true, cones: false, labels: false, events: true }); + const [t, setT] = useState(0); + const [playing, setPlaying] = useState(false); + const [speed, setSpeed] = useState(4); + const [selected, setSelected] = useState(undefined); + const [status, setStatus] = useState(''); + + const refreshLogs = (): void => { fetchLogs().then(setLogs).catch((e: unknown) => setStatus(String(e))); }; + useEffect(() => { + fetchMaps().then(setMaps).catch((e: unknown) => setStatus(String(e))); + refreshLogs(); + }, []); + + const openLog = (name: string): void => { + setLogName(name); + setPlaying(false); + setStatus('正在解密和读取日志…'); + loadLog(name).then((list) => { + setBattles(list); + // The longest battle that has bots in its trace; a battle left right after loading has none. + let pick = list.length - 1; + let best = 0; + list.forEach((b, i) => { + const withBots = b.frames.filter((f) => f.bots.size > 0).length; + if (withBots > best) { best = withBots; pick = i; } + }); + setBattleIdx(Math.max(0, pick)); + setStatus(list.length === 0 ? '这份日志里没有对局。' : ''); + }).catch((e: unknown) => setStatus(String(e))); + }; + + const battle = battles[battleIdx]; + const level = battle?.level; + useEffect(() => { + setT(battle?.startT ?? 0); + setSelected(undefined); + }, [battle]); + useEffect(() => { + const entry = maps.find((m) => m.level === level); + setMapData(undefined); + if (entry === undefined) return; + loadMap(entry).then(setMapData).catch((e: unknown) => setStatus(String(e))); + }, [level, maps]); + + const mapLayer = useMemo( + () => (mapData === undefined ? undefined : buildMapLayer(mapData.pack, { tier: 1, exposure, covers })), + [mapData, exposure, covers], + ); + const bounds = useMemo((): readonly [number, number, number, number] | undefined => { + if (mapData === undefined) return undefined; + const p = mapData.pois; + if (p !== undefined) return [p.boundsMin[0], p.boundsMin[1], p.boundsMax[0], p.boundsMax[1]]; + return [mapData.pack.header.bmin[0], mapData.pack.header.bmin[2], mapData.pack.header.bmax[0], mapData.pack.header.bmax[2]]; + }, [mapData]); + + useEffect(() => { + if (!playing || battle === undefined) return; + let last = performance.now(); + let handle = requestAnimationFrame(function step(now) { + const dt = (now - last) / 1000; + last = now; + setT((cur) => { + const next = cur + dt * speed; + if (next >= battle.endT) { setPlaying(false); return battle.endT; } + return next; + }); + handle = requestAnimationFrame(step); + }); + return () => cancelAnimationFrame(handle); + }, [playing, speed, battle]); + + const scene = useMemo(() => (battle === undefined ? undefined : sceneAt(battle, t)), [battle, t]); + + return ( +
+
+ + + {battles.length > 1 && ( + + )} + {(Object.keys(LAYER_LABELS) as (keyof Layers)[]).map((k) => ( + + ))} + + + {status !== '' && {status}} + {battle !== undefined && battle.frames.length === 0 && 这一局没有轨迹(游戏里没开 diagnostics.trace)。} +
+
+ + {battle !== undefined && } +
+ {battle !== undefined && ( + + )} +
+ ); +} diff --git a/apps/ai-lab/src/Inspector.tsx b/apps/ai-lab/src/Inspector.tsx new file mode 100644 index 0000000..a0d6c88 --- /dev/null +++ b/apps/ai-lab/src/Inspector.tsx @@ -0,0 +1,94 @@ +/** Details of the selected vehicle at the current time, its recent log events, and the legends. */ +import type { TraceBattle, TraceEvent } from '@wto/ground-sim'; +import { eventsBetween, type SceneAt } from './frames.ts'; +import { + BEHAVIOR_COLORS, BEHAVIOR_ZH, CLASS_ZH, COMMAND_ZH, DENY_COLORS, DENY_ZH, LANE_ZH, LOOK_COLORS, LOOK_ZH, + STATE_ZH, URGENCY_ZH, zh, +} from './labels.ts'; + +interface Props { + readonly battle: TraceBattle; + readonly scene: SceneAt | undefined; + readonly selected: string | undefined; +} + +const RECENT_SEC = 20; + +function angleDiff(a: number, b: number): number { + return Math.abs(((((a - b) % 360) + 540) % 360) - 180); +} + +function involves(e: TraceEvent, eid: string): boolean { + return e.eid === eid || e.fields['tgt'] === eid || e.fields['off'] === eid || e.fields['target'] === eid; +} + +function eventText(e: TraceEvent): string { + return Object.entries(e.fields) + .filter(([k]) => k !== 't' && k !== 'eid') + .map(([k, v]) => `${k}=${v}`) + .join(' '); +} + +function Legend({ names, colors }: { names: readonly string[]; colors: readonly string[] }): React.JSX.Element { + return ( +
+ {names.map((n, i) => ( + {n} + ))} +
+ ); +} + +function Row({ k, v }: { k: string; v: string }): React.JSX.Element { + return {k}{v}; +} + +export function Inspector({ battle, scene, selected }: Props): React.JSX.Element { + const u = selected !== undefined ? scene?.units.get(selected) : undefined; + const b = u?.bot; + const recent = selected !== undefined && scene !== undefined + ? eventsBetween(battle, scene.t - RECENT_SEC, scene.t).filter((e) => involves(e, selected)).reverse() + : []; + return ( + + ); +} diff --git a/apps/ai-lab/src/MapView.tsx b/apps/ai-lab/src/MapView.tsx new file mode 100644 index 0000000..14e3b67 --- /dev/null +++ b/apps/ai-lab/src/MapView.tsx @@ -0,0 +1,87 @@ +/** The battle map: drag to pan, wheel to zoom, click a vehicle to select it. */ +import type { TraceBattle } from '@wto/ground-sim'; +import { useEffect, useRef, useState } from 'react'; +import { drawScene, type Layers } from './draw.ts'; +import type { SceneAt } from './frames.ts'; +import type { MapLayer } from './mapLayer.ts'; +import { fitView, toScreen, zoomAt, type View } from './view.ts'; + +interface Props { + readonly map: MapLayer | undefined; + readonly bounds: readonly [number, number, number, number] | undefined; + readonly battle: TraceBattle | undefined; + readonly scene: SceneAt | undefined; + readonly selected: string | undefined; + readonly layers: Layers; + readonly onSelect: (eid: string | undefined) => void; +} + +const PICK_PX = 14; + +export function MapView({ map, bounds, battle, scene, selected, layers, onSelect }: Props): React.JSX.Element { + const canvasRef = useRef(null); + const [view, setView] = useState({ cx: 0, cz: 0, scale: 1, w: 800, h: 600 }); + const drag = useRef<{ x: number; y: number; moved: boolean } | undefined>(undefined); + + useEffect(() => { + const canvas = canvasRef.current; + if (canvas === null) return; + const resize = (): void => { + const r = canvas.getBoundingClientRect(); + canvas.width = Math.max(1, Math.floor(r.width)); + canvas.height = Math.max(1, Math.floor(r.height)); + setView((v) => ({ ...v, w: canvas.width, h: canvas.height })); + }; + const obs = new ResizeObserver(resize); + obs.observe(canvas); + resize(); + return () => obs.disconnect(); + }, []); + + useEffect(() => { + if (bounds === undefined) return; + setView((v) => fitView(bounds[0], bounds[1], bounds[2], bounds[3], v.w, v.h)); + }, [bounds]); + + useEffect(() => { + const ctx = canvasRef.current?.getContext('2d'); + if (ctx === undefined || ctx === null) return; + drawScene(ctx, view, map, battle, scene, selected, layers); + }, [view, map, battle, scene, selected, layers]); + + const pick = (sx: number, sy: number): string | undefined => { + let best: string | undefined; + let bestD = PICK_PX * PICK_PX; + for (const u of scene?.units.values() ?? []) { + const [x, y] = toScreen(view, u.x, u.z); + const d = (x - sx) ** 2 + (y - sy) ** 2; + if (d < bestD) { bestD = d; best = u.unit.eid; } + } + return best; + }; + + return ( + setView((v) => zoomAt(v, e.nativeEvent.offsetX, e.nativeEvent.offsetY, e.deltaY < 0 ? 1.2 : 1 / 1.2))} + onMouseDown={(e) => { drag.current = { x: e.clientX, y: e.clientY, moved: false }; }} + onMouseMove={(e) => { + const d = drag.current; + if (d === undefined) return; + const dx = e.clientX - d.x; + const dy = e.clientY - d.y; + if (Math.abs(dx) + Math.abs(dy) > 2) d.moved = true; + d.x = e.clientX; + d.y = e.clientY; + setView((v) => ({ ...v, cx: v.cx - dx / v.scale, cz: v.cz + dy / v.scale })); + }} + onMouseUp={(e) => { + const d = drag.current; + drag.current = undefined; + if (d !== undefined && !d.moved) onSelect(pick(e.nativeEvent.offsetX, e.nativeEvent.offsetY)); + }} + onMouseLeave={() => { drag.current = undefined; }} + /> + ); +} diff --git a/apps/ai-lab/src/Timeline.tsx b/apps/ai-lab/src/Timeline.tsx new file mode 100644 index 0000000..ad19e4a --- /dev/null +++ b/apps/ai-lab/src/Timeline.tsx @@ -0,0 +1,86 @@ +/** + * Playback controls and, for the selected bot, three strips over the whole battle: its behavior, + * the reason it did not fire, and why its turret pointed where it did. Click a strip to seek. + */ +import type { TraceBattle } from '@wto/ground-sim'; +import { useEffect, useRef } from 'react'; +import { BEHAVIOR_COLORS, DENY_COLORS, LOOK_COLORS } from './labels.ts'; + +interface Props { + readonly battle: TraceBattle; + readonly t: number; + readonly playing: boolean; + readonly speed: number; + readonly selected: string | undefined; + readonly onSeek: (t: number) => void; + readonly onPlaying: (playing: boolean) => void; + readonly onSpeed: (speed: number) => void; +} + +const SPEEDS = [0.5, 1, 2, 4, 8, 16]; +const STRIP_H = 10; + +function drawStrips(canvas: HTMLCanvasElement, battle: TraceBattle, eid: string | undefined, t: number): void { + const ctx = canvas.getContext('2d'); + if (ctx === null) return; + const w = canvas.width; + const span = Math.max(1, battle.endT - battle.startT); + ctx.fillStyle = '#16181a'; + ctx.fillRect(0, 0, w, canvas.height); + if (eid !== undefined) { + const frames = battle.frames; + for (let i = 0; i < frames.length; i++) { + const f = frames[i]; + const bot = f?.bots.get(eid); + if (f === undefined || bot === undefined) continue; + const x0 = ((f.t - battle.startT) / span) * w; + const x1 = (((frames[i + 1]?.t ?? f.t + 0.5) - battle.startT) / span) * w; + const bw = Math.max(1, x1 - x0); + ctx.fillStyle = BEHAVIOR_COLORS[bot.behavior] ?? '#444'; + ctx.fillRect(x0, 0, bw, STRIP_H); + ctx.fillStyle = DENY_COLORS[bot.deny] ?? '#444'; + ctx.fillRect(x0, STRIP_H + 2, bw, STRIP_H); + ctx.fillStyle = LOOK_COLORS[bot.lookReason] ?? '#444'; + ctx.fillRect(x0, 2 * (STRIP_H + 2), bw, STRIP_H); + } + } + const cx = ((t - battle.startT) / span) * w; + ctx.fillStyle = '#fff'; + ctx.fillRect(cx - 1, 0, 2, canvas.height); +} + +export function Timeline({ battle, t, playing, speed, selected, onSeek, onPlaying, onSpeed }: Props): React.JSX.Element { + const stripRef = useRef(null); + useEffect(() => { + const c = stripRef.current; + if (c === null) return; + c.width = Math.max(1, Math.floor(c.getBoundingClientRect().width)); + drawStrips(c, battle, selected, t); + }, [battle, selected, t]); + + return ( +
+
+ + + {t.toFixed(1)} s / {battle.endT.toFixed(0)} s + onSeek(Number(e.target.value))} + /> +
+
行为拒绝开火炮塔依据
+ { + const w = e.currentTarget.width; + onSeek(battle.startT + (e.nativeEvent.offsetX / w) * (battle.endT - battle.startT)); + }} + /> +
+ ); +} diff --git a/apps/ai-lab/src/data.ts b/apps/ai-lab/src/data.ts new file mode 100644 index 0000000..7bd8a73 --- /dev/null +++ b/apps/ai-lab/src/data.ts @@ -0,0 +1,48 @@ +/** Loading maps and logs through the lab's dev-server API (server/lab-api.ts). */ +import { parsePois, parseTraceLog, readNavPack, type MapPois, type NavPack, type TraceBattle } from '@wto/ground-sim'; + +export interface LogEntry { + readonly name: string; + readonly size: number; + readonly mtime: number; +} + +export interface MapEntry { + readonly level: string; + readonly pois: boolean; +} + +export interface MapData { + readonly pack: NavPack; + readonly pois: MapPois | undefined; +} + +async function get(url: string): Promise { + const res = await fetch(url); + if (!res.ok) { + const body = await res.text(); + throw new Error(`${url}: ${res.status} ${body}`); + } + return res; +} + +export async function fetchMaps(): Promise { + return (await (await get('/api/maps')).json()) as MapEntry[]; +} + +export async function fetchLogs(): Promise { + return (await (await get('/api/logs')).json()) as LogEntry[]; +} + +export async function loadLog(name: string): Promise { + const text = await (await get(`/api/logs/text?name=${encodeURIComponent(name)}`)).text(); + return parseTraceLog(text); +} + +export async function loadMap(entry: MapEntry): Promise { + const bytes = new Uint8Array(await (await get(`/api/maps/file?name=${encodeURIComponent(`${entry.level}.wtonav`)}`)).arrayBuffer()); + const pois = entry.pois + ? parsePois(await (await get(`/api/maps/file?name=${encodeURIComponent(`${entry.level}.pois.json`)}`)).text()) + : undefined; + return { pack: readNavPack(bytes), pois }; +} diff --git a/apps/ai-lab/src/draw.ts b/apps/ai-lab/src/draw.ts new file mode 100644 index 0000000..e1313e4 --- /dev/null +++ b/apps/ai-lab/src/draw.ts @@ -0,0 +1,168 @@ +/** Everything drawn over the static map for one moment of the replay. */ +import { BEHAVIOR_NAMES, type TraceBattle } from '@wto/ground-sim'; +import { eventsBetween, type SceneAt, type UnitAt } from './frames.ts'; +import type { MapLayer } from './mapLayer.ts'; +import { screenDir, toScreen, type View } from './view.ts'; + +export interface Layers { + readonly goals: boolean; + readonly links: boolean; + readonly cones: boolean; + readonly labels: boolean; + readonly events: boolean; +} + +export const ARMY_COLORS: Readonly> = { 1: '#4aa3ff', 2: '#ff5c5c' }; + +const GUN_FOV_HALF_DEG = 30; +const CONE_M = 120; +const EVENT_WINDOW_SEC = 2; + +function line(ctx: CanvasRenderingContext2D, ax: number, ay: number, bx: number, by: number): void { + ctx.beginPath(); + ctx.moveTo(ax, ay); + ctx.lineTo(bx, by); + ctx.stroke(); +} + +function drawHull(ctx: CanvasRenderingContext2D, v: View, u: UnitAt, selected: boolean): void { + const [sx, sy] = toScreen(v, u.x, u.z); + const [dx, dy] = screenDir(u.yaw); + const len = Math.max(5, (u.unit.light ? 3 : 3.6) * v.scale); + const wid = Math.max(3, 1.7 * v.scale); + ctx.save(); + ctx.translate(sx, sy); + ctx.rotate(Math.atan2(dy, dx)); + ctx.fillStyle = u.unit.alive ? (ARMY_COLORS[u.unit.army] ?? '#ccc') : '#555'; + ctx.fillRect(-len, -wid, len * 2, wid * 2); + ctx.fillStyle = '#fff'; + ctx.fillRect(len * 0.6, -wid * 0.5, len * 0.4, wid); + if (u.unit.human || selected) { + ctx.strokeStyle = selected ? '#ffe14a' : '#fff'; + ctx.lineWidth = selected ? 3 : 1.5; + ctx.strokeRect(-len - 2, -wid - 2, len * 2 + 4, wid * 2 + 4); + } + ctx.restore(); +} + +function drawBotIntent(ctx: CanvasRenderingContext2D, v: View, u: UnitAt, scene: SceneAt, layers: Layers): void { + const bot = u.bot; + if (bot === undefined || !u.unit.alive) return; + const [sx, sy] = toScreen(v, u.x, u.z); + if (layers.goals && bot.hasOrder) { + const [gx, gy] = toScreen(v, bot.goalX, bot.goalZ); + ctx.setLineDash([4, 6]); + ctx.strokeStyle = 'rgba(255,255,255,0.25)'; + ctx.lineWidth = 1; + line(ctx, sx, sy, gx, gy); + ctx.setLineDash([]); + } + if (bot.gunYaw !== undefined) { + const [dx, dy] = screenDir(bot.gunYaw); + if (layers.cones) { + const r = CONE_M * v.scale; + const a = Math.atan2(dy, dx); + const half = (GUN_FOV_HALF_DEG * Math.PI) / 180; + ctx.fillStyle = 'rgba(255,255,200,0.07)'; + ctx.beginPath(); + ctx.moveTo(sx, sy); + ctx.arc(sx, sy, r, a - half, a + half); + ctx.closePath(); + ctx.fill(); + } + const gl = Math.max(14, 8 * v.scale); + ctx.strokeStyle = '#fff'; + ctx.lineWidth = 2; + line(ctx, sx, sy, sx + dx * gl, sy + dy * gl); + } + const [wx, wy] = screenDir(bot.wishYaw); + const wl = Math.max(22, 14 * v.scale); + ctx.setLineDash([2, 3]); + ctx.strokeStyle = 'rgba(255,225,74,0.8)'; + ctx.lineWidth = 1; + line(ctx, sx, sy, sx + wx * wl, sy + wy * wl); + ctx.setLineDash([]); + if (!layers.links) return; + const target = scene.units.get(bot.target); + if (target !== undefined && bot.target !== '0') { + const [tx, ty] = toScreen(v, target.x, target.z); + ctx.strokeStyle = bot.targetInSight ? 'rgba(255,70,70,0.85)' : 'rgba(255,70,70,0.3)'; + ctx.lineWidth = 1.5; + line(ctx, sx, sy, tx, ty); + } + const look = scene.units.get(bot.lookAt); + if (look !== undefined && bot.lookAt !== bot.target) { + const [lx, ly] = toScreen(v, look.x, look.z); + ctx.strokeStyle = 'rgba(255,160,40,0.85)'; + ctx.lineWidth = 1.5; + line(ctx, sx, sy, lx, ly); + } +} + +function drawLabel(ctx: CanvasRenderingContext2D, v: View, u: UnitAt): void { + const [sx, sy] = toScreen(v, u.x, u.z); + const name = u.bot !== undefined ? (BEHAVIOR_NAMES[u.bot.behavior] ?? '?') : u.unit.human ? 'player' : ''; + ctx.fillStyle = 'rgba(255,255,255,0.85)'; + ctx.font = '11px sans-serif'; + ctx.fillText(`${u.unit.eid.replace(/^0x/, '')} ${name}`, sx + 8, sy - 8); +} + +function drawEvents(ctx: CanvasRenderingContext2D, v: View, battle: TraceBattle, scene: SceneAt): void { + for (const e of eventsBetween(battle, scene.t - EVENT_WINDOW_SEC, scene.t)) { + const fade = 1 - (scene.t - e.t) / EVENT_WINDOW_SEC; + if (e.kind === 'SHOT' && e.eid !== undefined) { + const from = scene.units.get(e.eid); + const to = scene.units.get(e.fields['tgt'] ?? ''); + if (from === undefined || to === undefined) continue; + const [ax, ay] = toScreen(v, from.x, from.z); + const [bx, by] = toScreen(v, to.x, to.z); + ctx.strokeStyle = `rgba(255,255,120,${fade})`; + ctx.lineWidth = 2; + line(ctx, ax, ay, bx, by); + } else if (e.kind === 'HIT') { + const [hx, hy] = toScreen(v, Number(e.fields['x']), Number(e.fields['z'])); + ctx.fillStyle = e.fields['drop'] === '1' ? `rgba(255,60,60,${fade})` : `rgba(200,200,200,${fade})`; + ctx.beginPath(); + ctx.arc(hx, hy, 4, 0, Math.PI * 2); + ctx.fill(); + } + } +} + +function drawDeaths(ctx: CanvasRenderingContext2D, v: View, battle: TraceBattle, t: number): void { + ctx.lineWidth = 2; + for (const e of eventsBetween(battle, battle.startT, t)) { + if (e.kind !== 'DEATH') continue; + const [x, y] = toScreen(v, Number(e.fields['x']), Number(e.fields['z'])); + ctx.strokeStyle = e.fields['army'] === '1' ? 'rgba(74,163,255,0.6)' : 'rgba(255,92,92,0.6)'; + line(ctx, x - 5, y - 5, x + 5, y + 5); + line(ctx, x - 5, y + 5, x + 5, y - 5); + } +} + +export function drawScene(ctx: CanvasRenderingContext2D, v: View, map: MapLayer | undefined, battle: TraceBattle | undefined, + scene: SceneAt | undefined, selected: string | undefined, layers: Layers): void { + ctx.fillStyle = '#0b0c0d'; + ctx.fillRect(0, 0, v.w, v.h); + if (map !== undefined) { + const [mx, my] = toScreen(v, map.x0, map.z1); + const k = v.scale / map.pxPerM; + ctx.imageSmoothingEnabled = k < 1; + ctx.drawImage(map.canvas, mx, my, map.canvas.width * k, map.canvas.height * k); + } + if (battle === undefined || scene === undefined) return; + for (const cap of scene.caps) { + const [cx, cy] = toScreen(v, cap.x, cap.z); + ctx.strokeStyle = ARMY_COLORS[cap.owner] ?? '#ddd'; + ctx.lineWidth = 2; + ctx.beginPath(); + ctx.arc(cx, cy, Math.max(4, cap.r * v.scale), 0, Math.PI * 2); + ctx.stroke(); + } + drawDeaths(ctx, v, battle, scene.t); + const units = [...scene.units.values()]; + for (const u of units) drawBotIntent(ctx, v, u, scene, layers); + if (layers.events) drawEvents(ctx, v, battle, scene); + for (const u of units) drawHull(ctx, v, u, u.unit.eid === selected); + if (layers.labels) for (const u of units) if (u.unit.alive) drawLabel(ctx, v, u); +} diff --git a/apps/ai-lab/src/frames.ts b/apps/ai-lab/src/frames.ts new file mode 100644 index 0000000..ce5f04f --- /dev/null +++ b/apps/ai-lab/src/frames.ts @@ -0,0 +1,73 @@ +/** Looking up the battle state at any time between two trace samples. */ +import type { BotSample, CapSample, TraceBattle, TraceEvent, UnitSample } from '@wto/ground-sim'; + +export interface UnitAt { + readonly unit: UnitSample; + /** Interpolated position and heading. */ + readonly x: number; + readonly z: number; + readonly yaw: number; + /** Decision state of the sample at or before the time; undefined for players. */ + readonly bot: BotSample | undefined; +} + +export interface SceneAt { + readonly t: number; + readonly units: Map; + readonly caps: CapSample[]; +} + +/** Index of the last frame at or before `t` (-1 before the first). */ +export function frameIndexAt(battle: TraceBattle, t: number): number { + let lo = 0; + let hi = battle.frames.length - 1; + let found = -1; + while (lo <= hi) { + const mid = (lo + hi) >> 1; + if ((battle.frames[mid]?.t ?? Infinity) <= t) { found = mid; lo = mid + 1; } else hi = mid - 1; + } + return found; +} + +function lerpYaw(a: number, b: number, k: number): number { + const d = ((((b - a) % 360) + 540) % 360) - 180; + return a + d * k; +} + +export function sceneAt(battle: TraceBattle, t: number): SceneAt { + const i = Math.max(0, frameIndexAt(battle, t)); + const a = battle.frames[i]; + const b = battle.frames[i + 1]; + const units = new Map(); + if (a === undefined) return { t, units, caps: [] }; + const k = b !== undefined && b.t > a.t ? Math.min(1, Math.max(0, (t - a.t) / (b.t - a.t))) : 0; + for (const [eid, ua] of a.units) { + const ub = b?.units.get(eid); + const move = ub !== undefined && ua.alive && ub.alive ? k : 0; + units.set(eid, { + unit: ua, + x: ua.x + ((ub?.x ?? ua.x) - ua.x) * move, + z: ua.z + ((ub?.z ?? ua.z) - ua.z) * move, + yaw: lerpYaw(ua.yaw, ub?.yaw ?? ua.yaw, move), + bot: a.bots.get(eid), + }); + } + return { t, units, caps: a.caps }; +} + +/** Events with time in [from, to], from the sorted event list. */ +export function eventsBetween(battle: TraceBattle, from: number, to: number): TraceEvent[] { + let lo = 0; + let hi = battle.events.length; + while (lo < hi) { + const mid = (lo + hi) >> 1; + if ((battle.events[mid]?.t ?? Infinity) < from) lo = mid + 1; else hi = mid; + } + const out: TraceEvent[] = []; + for (let i = lo; i < battle.events.length; i++) { + const e = battle.events[i]; + if (e === undefined || e.t > to) break; + out.push(e); + } + return out; +} diff --git a/apps/ai-lab/src/labels.ts b/apps/ai-lab/src/labels.ts new file mode 100644 index 0000000..b3fde12 --- /dev/null +++ b/apps/ai-lab/src/labels.ts @@ -0,0 +1,37 @@ +/** Chinese display names for the trace codes (the codes themselves are in @wto/ground-sim). */ + +export const BEHAVIOR_ZH = ['推进', '交战推进', '短停', '回掩体', '换位', '守位', '疏散', '撤回', '维修'] as const; + +export const BEHAVIOR_COLORS = ['#6c8ebf', '#e0884a', '#e5d34a', '#8fbf6c', '#b07cc6', '#5fb8b0', '#9a9a9a', '#c65f5f', '#7a5a3a'] as const; + +export const STATE_ZH: Readonly> = { + 0: '行军', 1: '行进交战', 3: '短停', 4: '退入掩体', 5: '掩体装填', 7: '原地守位', 8: '换位', + 9: '失能', 10: '疏散', 11: '坡脊撤回', +}; + +export const DENY_ZH = [ + '放行', '无目标', '炮未就绪', '命中概率不足', '远距窗口不足', '瞄准误差', '等待炮管稳定', '检查预算', + '炮口有硬物', '弹道有硬物', '友军', '多炮检查', '射界外', '点射间歇', +] as const; + +export const DENY_COLORS = [ + '#4caf50', '#333', '#666', '#e53935', '#8e24aa', '#fb8c00', '#fdd835', '#90a4ae', + '#6d4c41', '#795548', '#03a9f4', '#9e9e9e', '#d81b60', '#26a69a', +] as const; + +export const LOOK_ZH = ['—', '交战目标', '威胁', '目标消失处', '记忆位置', '线索', '扫视'] as const; + +export const LOOK_COLORS = ['#333', '#e53935', '#fb8c00', '#fdd835', '#8e24aa', '#03a9f4', '#607d8b'] as const; + +export const COMMAND_ZH = ['主攻', '侧翼', '架枪', '防守', '预备', '防空'] as const; + +export const URGENCY_ZH = ['低', '中', '高'] as const; + +export const LANE_ZH = ['中路', '左翼', '右翼'] as const; + +export const CLASS_ZH = ['中坦', '轻坦', '重坦', '歼击车', '防空'] as const; + +export function zh(names: readonly string[] | Readonly>, code: number): string { + const name = Array.isArray(names) ? names[code] : (names as Readonly>)[code]; + return name ?? String(code); +} diff --git a/apps/ai-lab/src/main.tsx b/apps/ai-lab/src/main.tsx new file mode 100644 index 0000000..90c7cf0 --- /dev/null +++ b/apps/ai-lab/src/main.tsx @@ -0,0 +1,7 @@ +import { StrictMode } from 'react'; +import { createRoot } from 'react-dom/client'; +import { App } from './App.tsx'; +import './style.css'; + +const root = document.getElementById('root'); +if (root !== null) createRoot(root).render(); diff --git a/apps/ai-lab/src/mapLayer.ts b/apps/ai-lab/src/mapLayer.ts new file mode 100644 index 0000000..de2a125 --- /dev/null +++ b/apps/ai-lab/src/mapLayer.ts @@ -0,0 +1,88 @@ +/** + * The static map drawn once into an offscreen canvas: walkable polygons of one mesh tier coloured + * by surface, optionally the tactical grid's exposure and the baked cover points. + */ +import { NAV_AREA_NAMES, type NavPack } from '@wto/ground-sim'; + +export interface MapLayer { + readonly canvas: HTMLCanvasElement; + /** World x of the canvas's left edge and world z of its top edge. */ + readonly x0: number; + readonly z1: number; + readonly pxPerM: number; +} + +export interface MapLayerOptions { + readonly tier: number; + readonly exposure: boolean; + readonly covers: boolean; +} + +const AREA_COLORS: Readonly> = { + road: '#77786a', bridge: '#a0a090', ground: '#3d4a33', rough: '#5a4d34', forest: '#29402a', + crushable: '#4f5f35', shallowWater: '#35607a', chokepoint: '#7a6a35', exposed: '#5f5f33', + deepWater: '#1d3a66', noGo: '#3a2626', +}; + +export function buildMapLayer(pack: NavPack, opts: MapLayerOptions): MapLayer { + const [x0, , z0] = pack.header.bmin; + const [x1, , z1] = pack.header.bmax; + const pxPerM = Math.min(2, 4096 / Math.max(x1 - x0, z1 - z0)); + const canvas = document.createElement('canvas'); + canvas.width = Math.ceil((x1 - x0) * pxPerM); + canvas.height = Math.ceil((z1 - z0) * pxPerM); + const ctx = canvas.getContext('2d'); + if (ctx === null) return { canvas, x0, z1, pxPerM }; + ctx.fillStyle = '#121416'; + ctx.fillRect(0, 0, canvas.width, canvas.height); + const tier = pack.tiers[opts.tier] ?? pack.tiers[1]; + if (tier !== undefined) { + for (let area = 1; area < NAV_AREA_NAMES.length; area++) { + ctx.beginPath(); + for (let i = 0; i < tier.polyCount; i++) { + if (tier.areas[i] !== area) continue; + const ring = tier.rings[i]; + if (ring === undefined) continue; + for (let k = 0; k < ring.length; k += 2) { + const px = ((ring[k] ?? 0) - x0) * pxPerM; + const py = (z1 - (ring[k + 1] ?? 0)) * pxPerM; + if (k === 0) ctx.moveTo(px, py); + else ctx.lineTo(px, py); + } + ctx.closePath(); + } + ctx.fillStyle = AREA_COLORS[NAV_AREA_NAMES[area] ?? ''] ?? '#444'; + ctx.fill(); + } + } + if (opts.exposure) drawExposure(ctx, pack, x0, z1, pxPerM); + if (opts.covers) drawCovers(ctx, pack, x0, z1, pxPerM); + return { canvas, x0, z1, pxPerM }; +} + +function drawExposure(ctx: CanvasRenderingContext2D, pack: NavPack, x0: number, z1: number, pxPerM: number): void { + const g = pack.tactical; + const cell = g.cellM * pxPerM; + for (let r = 0; r < g.rows; r++) { + for (let c = 0; c < g.cols; c++) { + const e = g.exposure[r * g.cols + c] ?? 0; + if (e < 16) continue; + ctx.fillStyle = `rgba(255, 80, 40, ${(e / 255) * 0.45})`; + const wx = g.origin[0] + c * g.cellM; + const wz = g.origin[1] + r * g.cellM; + ctx.fillRect((wx - x0) * pxPerM, (z1 - wz - g.cellM) * pxPerM, cell, cell); + } + } +} + +function drawCovers(ctx: CanvasRenderingContext2D, pack: NavPack, x0: number, z1: number, pxPerM: number): void { + for (const cv of pack.covers) { + const px = (cv.pos[0] - x0) * pxPerM; + const py = (z1 - cv.pos[2]) * pxPerM; + ctx.strokeStyle = cv.kind === 1 ? 'rgba(120, 220, 255, 0.8)' : 'rgba(255, 230, 120, 0.8)'; + ctx.beginPath(); + ctx.moveTo(px, py); + ctx.lineTo(px + cv.coverDir[0] * 6 * pxPerM, py - cv.coverDir[1] * 6 * pxPerM); + ctx.stroke(); + } +} diff --git a/apps/ai-lab/src/style.css b/apps/ai-lab/src/style.css new file mode 100644 index 0000000..7e1c828 --- /dev/null +++ b/apps/ai-lab/src/style.css @@ -0,0 +1,26 @@ +* { box-sizing: border-box; } +html, body, #root { margin: 0; height: 100%; background: #0b0c0d; color: #ddd; font: 13px/1.4 system-ui, 'Microsoft YaHei', sans-serif; } +.app { display: flex; flex-direction: column; height: 100%; } +header { display: flex; flex-wrap: wrap; gap: 10px; align-items: center; padding: 6px 10px; background: #16181a; border-bottom: 1px solid #2a2d30; } +header select { max-width: 420px; } +header label { display: inline-flex; align-items: center; gap: 3px; } +.status { color: #ffb74d; } +main { flex: 1; display: flex; min-height: 0; } +canvas.map { flex: 1; min-width: 0; height: 100%; cursor: grab; display: block; } +.inspector { width: 360px; overflow-y: auto; padding: 8px 10px; background: #121416; border-left: 1px solid #2a2d30; } +.inspector table { width: 100%; border-collapse: collapse; } +.inspector th { text-align: left; color: #999; font-weight: normal; padding: 2px 8px 2px 0; white-space: nowrap; vertical-align: top; } +.inspector td { padding: 2px 0; } +.inspector h4 { margin: 12px 0 4px; color: #aaa; font-weight: normal; } +.hint { color: #999; } +.events { font-size: 12px; } +.events div { padding: 1px 0; border-bottom: 1px solid #1d2023; word-break: break-all; } +.events span { color: #999; } +.legend { display: flex; flex-wrap: wrap; gap: 4px 10px; font-size: 12px; } +.legend i { display: inline-block; width: 10px; height: 10px; margin-right: 3px; vertical-align: -1px; } +.timeline { padding: 6px 10px; background: #16181a; border-top: 1px solid #2a2d30; } +.controls { display: flex; gap: 8px; align-items: center; } +.controls input[type='range'] { flex: 1; } +.time { min-width: 120px; font-variant-numeric: tabular-nums; } +.strip-labels { display: flex; gap: 12px; font-size: 11px; color: #888; margin-top: 4px; } +canvas.strips { width: 100%; height: 36px; display: block; cursor: pointer; } diff --git a/apps/ai-lab/src/view.ts b/apps/ai-lab/src/view.ts new file mode 100644 index 0000000..6bfe133 --- /dev/null +++ b/apps/ai-lab/src/view.ts @@ -0,0 +1,39 @@ +/** + * Top-down view of the battle: world x to the right, world z up (Dagor is Y-up). Headings are + * degrees of atan2(z, x), as the trace writes them. + */ +export interface View { + /** World point at the centre of the canvas. */ + readonly cx: number; + readonly cz: number; + /** Screen pixels per world metre. */ + readonly scale: number; + readonly w: number; + readonly h: number; +} + +export function toScreen(v: View, x: number, z: number): [number, number] { + return [v.w / 2 + (x - v.cx) * v.scale, v.h / 2 - (z - v.cz) * v.scale]; +} + +export function toWorld(v: View, sx: number, sy: number): [number, number] { + return [v.cx + (sx - v.w / 2) / v.scale, v.cz - (sy - v.h / 2) / v.scale]; +} + +/** Screen direction (unit vector) of a world heading. */ +export function screenDir(yawDeg: number): [number, number] { + const r = (yawDeg * Math.PI) / 180; + return [Math.cos(r), -Math.sin(r)]; +} + +export function fitView(minX: number, minZ: number, maxX: number, maxZ: number, w: number, h: number): View { + const scale = Math.min(w / Math.max(1, maxX - minX), h / Math.max(1, maxZ - minZ)) * 0.95; + return { cx: (minX + maxX) / 2, cz: (minZ + maxZ) / 2, scale, w, h }; +} + +/** Zoom by `factor` keeping the world point under the screen point (sx, sy) in place. */ +export function zoomAt(v: View, sx: number, sy: number, factor: number): View { + const [wx, wz] = toWorld(v, sx, sy); + const scale = Math.min(40, Math.max(0.05, v.scale * factor)); + return { ...v, scale, cx: wx - (sx - v.w / 2) / scale, cz: wz + (sy - v.h / 2) / scale }; +} diff --git a/apps/ai-lab/tsconfig.json b/apps/ai-lab/tsconfig.json new file mode 100644 index 0000000..1cb6c15 --- /dev/null +++ b/apps/ai-lab/tsconfig.json @@ -0,0 +1,23 @@ +{ + // The lab is a Vite page plus its dev-server API (server/), so it has its own settings and stays + // out of the root typecheck, like the launcher. + "compilerOptions": { + "target": "ES2023", + "module": "ESNext", + "moduleResolution": "bundler", + "lib": ["ES2023", "DOM", "DOM.Iterable"], + "types": ["node"], + "jsx": "react-jsx", + "strict": true, + "noUncheckedIndexedAccess": true, + "noImplicitOverride": true, + "exactOptionalPropertyTypes": true, + "verbatimModuleSyntax": true, + "allowImportingTsExtensions": true, + "noEmit": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "useDefineForClassFields": true + }, + "include": ["src/**/*.ts", "src/**/*.tsx", "server/**/*.ts", "vite.config.ts"] +} diff --git a/apps/ai-lab/vite.config.ts b/apps/ai-lab/vite.config.ts new file mode 100644 index 0000000..9df6a8a --- /dev/null +++ b/apps/ai-lab/vite.config.ts @@ -0,0 +1,8 @@ +import react from '@vitejs/plugin-react'; +import { defineConfig } from 'vite'; +import { labApi } from './server/lab-api.ts'; + +export default defineConfig({ + plugins: [react(), labApi()], + server: { host: '127.0.0.1', port: 47180, strictPort: false }, +}); diff --git a/apps/launcher/src/renderer/src/i18n/locales/en.json b/apps/launcher/src/renderer/src/i18n/locales/en.json index be4ecb9..5ae089d 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/en.json +++ b/apps/launcher/src/renderer/src/i18n/locales/en.json @@ -881,7 +881,9 @@ "statsLogIntervalSec": "Battle statistics logging interval", "statsSampleSec": "Statistics sampling interval per bot", "statsSampleRangeM": "Range of the nearest-enemy statistics sample", - "statsRearArcDeg": "Rear arc counted as showing the rear" + "statsRearArcDeg": "Rear arc counted as showing the rear", + "trace": "Log the AI replay trace", + "traceIntervalSec": "AI replay trace sampling interval" } }, "shared": "These settings apply to all saves in this client.", diff --git a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json index 612b6cb..c434dfb 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json +++ b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json @@ -881,7 +881,9 @@ "statsLogIntervalSec": "每局统计的输出间隔", "statsSampleSec": "每辆车的统计抽查间隔", "statsSampleRangeM": "统计抽查最近敌人的范围", - "statsRearArcDeg": "算作车尾对敌的后方扇区角度" + "statsRearArcDeg": "算作车尾对敌的后方扇区角度", + "trace": "输出 AI 回放轨迹", + "traceIntervalSec": "回放轨迹的采样间隔" } }, "shared": "这些数值适用于此客户端的全部存档。", diff --git a/apps/launcher/src/renderer/src/pages/tuning/bot-tuning-fields.ts b/apps/launcher/src/renderer/src/pages/tuning/bot-tuning-fields.ts index 5ed854e..f66dd1d 100644 --- a/apps/launcher/src/renderer/src/pages/tuning/bot-tuning-fields.ts +++ b/apps/launcher/src/renderer/src/pages/tuning/bot-tuning-fields.ts @@ -466,6 +466,8 @@ export const BOT_TUNING_GROUPS: readonly BotTuningGroup[] = [ num('diagnostics', 'statsSampleSec', 0.2, 5, 's'), num('diagnostics', 'statsSampleRangeM', 50, 1000, 'm'), num('diagnostics', 'statsRearArcDeg', 30, 180, '°'), + { id: 'groundAi.diagnostics.trace', section: 'diagnostics', field: 'trace', kind: 'bool' }, + num('diagnostics', 'traceIntervalSec', 0.1, 5, 's'), ], }, ]; diff --git a/apps/launcher/src/shared/schemas/tuning.ts b/apps/launcher/src/shared/schemas/tuning.ts index 402b07f..d19d88f 100644 --- a/apps/launcher/src/shared/schemas/tuning.ts +++ b/apps/launcher/src/shared/schemas/tuning.ts @@ -329,6 +329,8 @@ const GroundAiDiagnosticsSchema = z.object({ statsSampleSec: z.number().min(0.2).max(5), statsSampleRangeM: z.number().min(50).max(1000), statsRearArcDeg: z.number().min(30).max(180), + trace: z.boolean(), + traceIntervalSec: z.number().min(0.1).max(5), }); export const GroundAiTuningSchema = z.object({ diff --git a/apps/server/src/tuning/ground-ai-tuning.ts b/apps/server/src/tuning/ground-ai-tuning.ts index 2da0bca..6871479 100644 --- a/apps/server/src/tuning/ground-ai-tuning.ts +++ b/apps/server/src/tuning/ground-ai-tuning.ts @@ -69,6 +69,8 @@ export function readGroundAiTuning(reader: TuningReader): GroundAiTuning { statsSampleSec: diag.number('statsSampleSec', { min: 0.2, max: 5 }), statsSampleRangeM: diag.number('statsSampleRangeM', { min: 50, max: 1000 }), statsRearArcDeg: diag.number('statsRearArcDeg', { min: 30, max: 180 }), + trace: diag.bool('trace'), + traceIntervalSec: diag.number('traceIntervalSec', { min: 0.1, max: 5 }), }, }; } diff --git a/apps/server/tuning/ground-ai.jsonc b/apps/server/tuning/ground-ai.jsonc index c7f96cf..7240d18 100644 --- a/apps/server/tuning/ground-ai.jsonc +++ b/apps/server/tuning/ground-ai.jsonc @@ -458,6 +458,11 @@ "statsLogIntervalSec": 60.0, "statsSampleSec": 1.0, "statsSampleRangeM": 300.0, - "statsRearArcDeg": 120.0 + "statsRearArcDeg": 120.0, + // Replay trace for the AI viewer (WTO_AI|TRACE_*, HIT, DEATH): every traceIntervalSec the + // capture zones, every ground unit and every bot's decision state. About 10 MB of log for + // 32 bots over 15 minutes at 0.5 s. + "trace": true, + "traceIntervalSec": 0.5 } } diff --git a/game-ai/ground/wto_ai_combat_types_common.das b/game-ai/ground/wto_ai_combat_types_common.das index f2cbd77..9174bb9 100644 --- a/game-ai/ground/wto_ai_combat_types_common.das +++ b/game-ai/ground/wto_ai_combat_types_common.das @@ -112,12 +112,23 @@ struct public WtoThreatTable topIdx : int = -1 topVisibleIdx : int = -1 +// Why the turret points where it does this frame (WtoTurretState.lookReason, replay trace). +let public WTO_LOOK_NONE = 0 +let public WTO_LOOK_ENGAGE = 1 +let public WTO_LOOK_THREAT = 2 +let public WTO_LOOK_WATCH = 3 +let public WTO_LOOK_MEMORY = 4 +let public WTO_LOOK_CUE = 5 +let public WTO_LOOK_SCAN = 6 + // Turret channel (decision layer design, section 5): the threat it is looking at and until when -// that look is held. +// that look is held, plus the world direction it was asked for this frame and why. [safe_when_uninitialized] struct public WtoTurretState lookEid : EntityId = INVALID_ENTITY_ID holdUntil : float = -100.0 + lookReason : int = 0 + wishDir : float3 = float3(1.0, 0.0, 0.0) [safe_when_uninitialized] struct public WtoWeaponBurst diff --git a/game-ai/ground/wto_ai_fire_common.das b/game-ai/ground/wto_ai_fire_common.das index 4bcf52b..1213d5d 100644 --- a/game-ai/ground/wto_ai_fire_common.das +++ b/game-ai/ground/wto_ai_fire_common.das @@ -272,8 +272,10 @@ def public wto_fire_update(world : WtoWorldSnap const&; var unit : Unit?; classN let aimBase = slot.perceive.visibleAimPt distToTgt = wto_solve_ballistic_aim(muzzlePos, unit.vel, aimBase, slot.fire.activeSpeedMps, slot.fire.activeDragCx, slot.fire.activeMassKg, slot.fire.activeCaliberM, slot, aimPt, wishWorldDir) auxAimed = wto_fire_aux_aim(unit, className, dt, distXZ, slot) + slot.turret.lookReason = WTO_LOOK_ENGAGE else wishWorldDir = wto_turret_look_dir(now, muzzlePos, unit.pos, hFwd, slot) + slot.turret.wishDir = wishWorldDir var wishYaw = 0.0 var wishPitch = 0.0 wto_world_to_hull_deg(wishWorldDir, hFwd, unit.unitTm[1], unit.unitTm[2], wishYaw, wishPitch) diff --git a/game-ai/ground/wto_ai_runtime.das b/game-ai/ground/wto_ai_runtime.das index a25c5f9..7fcefd5 100644 --- a/game-ai/ground/wto_ai_runtime.das +++ b/game-ai/ground/wto_ai_runtime.das @@ -43,6 +43,7 @@ require %appGame.wtoai.wto_ai_diag_common require %appGame.wtoai.wto_ai_stats_common require %appGame.wtoai.wto_ai_slots_common require %appGame.wtoai.wto_ai_threat_common +require %appGame.wtoai.wto_ai_trace_common var private @safe_when_uninitialized g_world : WtoWorldSnap var private @safe_when_uninitialized g_crowd : WtoCrowdSummary @@ -57,6 +58,8 @@ var private g_fire_budget : int = 0 var private g_next_diag_at : float = 0.0 var private @safe_when_uninitialized g_navmesh : WtoNavmeshBattle var private @safe_when_uninitialized g_stats : WtoBattleStats +var private g_next_trace_at : float = 0.0 +var private g_trace_due : bool = false // Custom ground AI must only run inside a real multiplayer battle. Single-player test // drives also dispatch tag=server ECS, but their target vehicles must never be taken over. @@ -81,6 +84,8 @@ def private wto_reset_runtime() g_cmd_dirty = true g_last_zone_ver = -1 g_next_diag_at = 0.0 + g_next_trace_at = 0.0 + g_trace_due = false wto_navmesh_battle_reset(g_navmesh) wto_slots_reset_all(g_bots) @@ -109,6 +114,7 @@ def wto_ai_unit_dead_es(evt : Event; eid : EntityId; unit__ref : UnitRef) if u != null && as_gm(u) != null && (int(u.army) == 1 || int(u.army) == 2) let now = float(get_app().usefulTotalTime) wto_world_record_death(g_world, eid, int(u.army), u.pos, now) + wto_trace_death(now, eid, int(u.army), u.pos) wto_route_report_wreck(g_navmesh.state, now, u.pos, g_bots) if wto_slots_forget(g_bots, eid) g_cmd_dirty = true @@ -127,6 +133,7 @@ def wto_ai_unit_damage_es(evt : EventUnitDamage; eid : EntityId; unit__ref : Uni if u == null || !offEid || offEid == eid return let hpDropped = uint(evt.hpFixed) < uint(evt.prevHpFixed) + wto_trace_hit(float(get_app().usefulTotalTime), eid, offEid, evt.pos, evt.damage, evt.damageTypeId, hpDropped) wto_slots_on_damage(g_world, g_bots, eid, offEid, u, evt.pos, hpDropped, float(get_app().usefulTotalTime)) [es(tag=server, before=wto_ai_pipeline_es)] @@ -166,6 +173,7 @@ def wto_ai_world_tick_es(act : UpdateStageInfoAct) g_next_diag_at = now + WTO_AI_DIAG_INTERVAL_SEC wto_diag_log_telemetry(g_world, now, g_bots, g_crowd) wto_navmesh_log_stats(g_navmesh) + g_trace_due = wto_trace_tick(g_world, now, g_bots, g_next_trace_at) wto_stats_tick(now, g_stats) [es(tag=server, before=wto_ai_pipeline_es)] @@ -218,6 +226,8 @@ def wto_ai_pipeline_es(act : UpdateStageInfoAct; eid : EntityId; var unit__ref : slot.nextNavAt = now + WTO_AI_NAV_TICK_SEC wto_nav_update(g_world, g_navmesh.state, idx, now, unit.pos, unit.unitTm[0], slot) wto_stats_bot_frame(g_world, now, act.dt, unit.pos, unit.unitTm[0], slot, g_stats) + if g_trace_due + wto_trace_bot(now, slot) [es(tag=server, after=wto_ai_pipeline_es)] def wto_ai_phys_tick_es(act : UpdateStageInfoAct; eid : EntityId; var unit__ref : UnitRef&; diff --git a/game-ai/ground/wto_ai_trace_common.das b/game-ai/ground/wto_ai_trace_common.das new file mode 100644 index 0000000..c6bfb2c --- /dev/null +++ b/game-ai/ground/wto_ai_trace_common.das @@ -0,0 +1,86 @@ +// Replay trace for the ground AI viewer (apps/ai-lab), written every diagnostics.traceIntervalSec: +// WTO_AI|TRACE_CAP capture zones (position, radius, owner, progress) +// WTO_AI|TRACE_U every ground unit, bots and players alike (position, hull heading, speed) +// WTO_AI|TRACE_B every bot's decision state (order, behavior, targets, turret, trigger) +// and as they happen: WTO_AI|HIT (part damage with its offender) and WTO_AI|DEATH. +// Positions are whole metres, headings whole degrees of atan2(z, x) in world space. +// The simulator writes the same lines, so this module uses no engine module. +options indenting = 2 +options no_global_heap = true +module wto_ai_trace_common shared + +require ecs +require math +require %appGame.wtoai.wto_ai_config_common +require %appGame.wtoai.wto_ai_math_common +require %appGame.wtoai.wto_ai_combat_types_common +require %appGame.wtoai.wto_ai_types_common + +def private wto_tr_m(v : float) : int + return int(floor(v + 0.5)) + +def private wto_tr_yaw(dir : float3) : int + return int(floor(atan2(dir.z, dir.x) * WTO_RAD_TO_DEG + 0.5)) + +def private wto_tr_b(flag : bool) : int + return flag ? 1 : 0 + +def private wto_tr_is_bot(bots : WtoBotSlot[64] const&; eid : EntityId) : int + for i in range(WTO_MAX_BOTS) + if bots[i].used && bots[i].eid == eid + return 1 + return 0 + +// True when this frame writes a trace sample; then the capture zones and all ground units are +// written at once, and the pipeline adds one TRACE_B line per bot. +[never_inline] +def public wto_trace_tick(world : WtoWorldSnap const&; now : float; bots : WtoBotSlot[64] const&; + var nextAt : float&) : bool + if !WTO_AI_TRACE_ENABLED || now < nextAt + return false + nextAt = now + WTO_AI_TRACE_SEC + for c in range(world.capCount) + assume z = world.caps[c] + print("WTO_AI|TRACE_CAP|t={now}|idx={c}|x={wto_tr_m(z.center.x)}|z={wto_tr_m(z.center.z)}|r={wto_tr_m(z.radius)}|owner={z.ownerArmy}|prog={z.progress}\n") + for i in range(world.unitCount) + assume u = world.units[i] + if !u.isGround + continue + let bot = wto_tr_is_bot(bots, u.eid) + print("WTO_AI|TRACE_U|t={now}|eid={uint(u.eid)}|army={u.army}|bot={bot}|human={wto_tr_b(u.isHuman)}|alive={wto_tr_b(u.isAlive)}|x={wto_tr_m(u.pos.x)}|y={wto_tr_m(u.pos.y)}|z={wto_tr_m(u.pos.z)}|yaw={wto_tr_yaw(u.hullFwd)}|v={length(u.vel)}|shoot={wto_tr_b(u.isShooting)}|light={wto_tr_b(u.isLightTag)}\n") + return true + +def private wto_tr_threat_eid(slot : WtoBotSlot const&; idx : int) : uint + return idx >= 0 && idx < slot.threat.count ? uint(slot.threat.entries[idx].eid) : 0u + +// The thing the turret aims at: the engaged target or the threat it looks at; 0 otherwise. +def private wto_tr_look_eid(slot : WtoBotSlot const&) : uint + let why = slot.turret.lookReason + if why == WTO_LOOK_ENGAGE + return uint(slot.perceive.targetEid) + if why == WTO_LOOK_THREAT + return uint(slot.turret.lookEid) + return 0u + +[never_inline] +def public wto_trace_bot(now : float; slot : WtoBotSlot const&) + assume o = slot.order + assume tac = slot.tactics + assume p = slot.perceive + assume tr = slot.trigger + let gx = o.valid ? wto_tr_m(o.goalPos.x) : 0 + let gz = o.valid ? wto_tr_m(o.goalPos.z) : 0 + let gun = slot.fire.hasBarrelSight ? wto_tr_yaw(slot.fire.barrelSight) : 9999 + let topEid = wto_tr_threat_eid(slot, slot.threat.topIdx) + let topVis = wto_tr_threat_eid(slot, slot.threat.topVisibleIdx) + print("WTO_AI|TRACE_B|t={now}|eid={uint(slot.eid)}|cls={slot.spec.role}|ord={wto_tr_b(o.valid)}|cmd={o.role}|urg={o.urgency}|cap={o.capIndex}|lane={o.laneId}|gx={gx}|gz={gz}|bhv={tac.behavior}|bs={tac.behaviorScore}|st={tac.state}|wantV={tac.desiredSpeedMps}|vf={slot.drive.lastVFwd}|rev={wto_tr_b(tac.reverseTravel)}|tgt={uint(p.targetEid)}|los={wto_tr_b(p.hasClearLos)}|threats={slot.threat.count}|top={topEid}|topVis={topVis}|look={wto_tr_look_eid(slot)}|why={slot.turret.lookReason}|wish={wto_tr_yaw(slot.turret.wishDir)}|gun={gun}|ready={wto_tr_b(slot.fire.gunReady)}|reload={wto_tr_b(slot.fire.reloading)}|deny={slot.fire.lastDenyReason}|p={tr.hitProb}|thr={tr.threshold}|reqV={tr.wantSpeedMps}\n") + +// Part damage on any unit with its offender, so the viewer can draw who hit whom and the last +// offender before a death. `dropped` tells whether the part lost hit points. +def public wto_trace_hit(now : float; victim, offender : EntityId; pos : float3; damage : float; damageType : int; dropped : bool) + if WTO_AI_TRACE_ENABLED + print("WTO_AI|HIT|t={now}|eid={uint(victim)}|off={uint(offender)}|x={wto_tr_m(pos.x)}|z={wto_tr_m(pos.z)}|dmg={damage}|type={damageType}|drop={wto_tr_b(dropped)}\n") + +def public wto_trace_death(now : float; eid : EntityId; army : int; pos : float3) + if WTO_AI_TRACE_ENABLED + print("WTO_AI|DEATH|t={now}|eid={uint(eid)}|army={army}|x={wto_tr_m(pos.x)}|z={wto_tr_m(pos.z)}\n") diff --git a/game-ai/ground/wto_ai_turret_common.das b/game-ai/ground/wto_ai_turret_common.das index 7db5a26..6084464 100644 --- a/game-ai/ground/wto_ai_turret_common.das +++ b/game-ai/ground/wto_ai_turret_common.das @@ -60,13 +60,19 @@ def private wto_turret_scan_dir(now : float; myPos, hullFwd : float3; slot : Wto [never_inline] def public wto_turret_look_dir(now : float; muzzlePos, myPos, hullFwd : float3; var slot : WtoBotSlot&) : float3 assume p = slot.perceive + assume tr = slot.turret let threat = wto_turret_pick_threat(now, slot) if threat >= 0 + tr.lookReason = WTO_LOOK_THREAT return normalize((slot.threat.entries[threat].pos + float3(0.0, 1.4, 0.0)) - muzzlePos) if now < p.watchUntil + tr.lookReason = WTO_LOOK_WATCH return normalize(p.watchPos - muzzlePos) if !!p.targetEid && (now - p.lastSeenAt) <= WTO_AI_TACTICS_MEMORY_TTL_SEC + tr.lookReason = WTO_LOOK_MEMORY return normalize((p.knownPos + float3(0.0, 1.4, 0.0)) - muzzlePos) if now < p.alertUntil + tr.lookReason = WTO_LOOK_CUE return float3(cos(p.alertYawRad), 0.0, sin(p.alertYawRad)) + tr.lookReason = WTO_LOOK_SCAN return wto_turret_scan_dir(now, myPos, hullFwd, slot) diff --git a/packages/ground-sim/package.json b/packages/ground-sim/package.json new file mode 100644 index 0000000..f10191f --- /dev/null +++ b/packages/ground-sim/package.json @@ -0,0 +1,9 @@ +{ + "name": "@wto/ground-sim", + "version": "0.1.0", + "private": true, + "type": "module", + "exports": { + ".": "./src/index.ts" + } +} diff --git a/packages/ground-sim/src/index.ts b/packages/ground-sim/src/index.ts new file mode 100644 index 0000000..c769fef --- /dev/null +++ b/packages/ground-sim/src/index.ts @@ -0,0 +1,15 @@ +/** + * Ground AI lab: map data readers and the replay trace shared by the replay viewer (apps/ai-lab) + * and the simulator (docs: tank-ai-revision-plan, section 3). + */ +export { + NAV_AREA_NAMES, NAV_FLAG, NAV_TIER_NAMES, NavPackError, readNavPack, + type NavCover, type NavHeader, type NavPack, type NavTactical, type NavTier, +} from './map/wtonav.ts'; +export { parsePois, type MapPoint, type MapPois } from './map/pois.ts'; +export { + BEHAVIOR_NAMES, BLOCK_NAMES, COMMAND_NAMES, DENY_NAMES, LANE_NAMES, LOOK_NAMES, STATE_NAMES, + URGENCY_NAMES, VEHICLE_CLASS_NAMES, nameOf, +} from './trace/names.ts'; +export { parseTraceLog } from './trace/parse.ts'; +export type { BotSample, CapSample, TraceBattle, TraceEvent, TraceFrame, UnitSample } from './trace/types.ts'; diff --git a/packages/ground-sim/src/map/pois.ts b/packages/ground-sim/src/map/pois.ts new file mode 100644 index 0000000..e2f4293 --- /dev/null +++ b/packages/ground-sim/src/map/pois.ts @@ -0,0 +1,51 @@ +/** + * Points of interest written next to each navigation pack (`.pois.json`, tools/navgen): + * battle bounds, and per mission the team spawns and the capture zones. + */ + +export interface MapPoint { + readonly name: string; + readonly x: number; + readonly y: number; + readonly z: number; + readonly radius: number; + readonly mission: string; +} + +export interface MapPois { + readonly level: string; + readonly missions: string[]; + readonly boundsMin: readonly [number, number]; + readonly boundsMax: readonly [number, number]; + readonly team1Spawns: MapPoint[]; + readonly team2Spawns: MapPoint[]; + readonly captureZones: MapPoint[]; +} + +function points(value: unknown): MapPoint[] { + if (!Array.isArray(value)) return []; + return value.flatMap((p: unknown): MapPoint[] => { + if (typeof p !== 'object' || p === null) return []; + const r = p as Record; + const n = (k: string): number => (typeof r[k] === 'number' ? (r[k] as number) : 0); + return [{ name: String(r['name'] ?? ''), x: n('x'), y: n('y'), z: n('z'), radius: n('radius'), mission: String(r['mission'] ?? '') }]; + }); +} + +function pair(value: unknown): readonly [number, number] { + return Array.isArray(value) && typeof value[0] === 'number' && typeof value[1] === 'number' ? [value[0], value[1]] : [0, 0]; +} + +/** Parses the text of a `.pois.json` file. */ +export function parsePois(text: string): MapPois { + const raw = JSON.parse(text) as Record; + return { + level: String(raw['level'] ?? ''), + missions: Array.isArray(raw['missions']) ? raw['missions'].map(String) : [], + boundsMin: pair(raw['boundsMin']), + boundsMax: pair(raw['boundsMax']), + team1Spawns: points(raw['team1Spawns']), + team2Spawns: points(raw['team2Spawns']), + captureZones: points(raw['captureZones']), + }; +} diff --git a/packages/ground-sim/src/map/wtonav.ts b/packages/ground-sim/src/map/wtonav.ts new file mode 100644 index 0000000..438ac89 --- /dev/null +++ b/packages/ground-sim/src/map/wtonav.ts @@ -0,0 +1,226 @@ +/** + * Reader for the baked `.wtonav` navigation pack (native/wto-nav/wto_nav_format.h): the header, + * the walkable polygons of each mesh tier (upstream Detour tile data), the cover points and the + * 8 m tactical grid. Only plain views over the bytes, so it runs in Node and in the browser. + */ + +export const NAV_TIER_NAMES = ['narrow', 'standard', 'wide'] as const; + +/** Detour polygon area ids written by the baker (WtoPolyArea). */ +export const NAV_AREA_NAMES = [ + 'unwalkable', 'road', 'bridge', 'ground', 'rough', 'forest', 'crushable', + 'shallowWater', 'chokepoint', 'exposed', 'deepWater', 'noGo', +] as const; + +/** Detour polygon flags (WtoPolyFlag). */ +export const NAV_FLAG = { + walk: 0x01, shallowWater: 0x02, deepWater: 0x04, chokepoint: 0x08, + blocked: 0x10, road: 0x20, downhill: 0x40, platform: 0x80, +} as const; + +export interface NavHeader { + readonly version: number; + readonly flags: number; + readonly everSha1: string; + readonly bmin: readonly [number, number, number]; + readonly bmax: readonly [number, number, number]; + readonly waterLevel: number; + readonly coverCount: number; + readonly tacCols: number; + readonly tacRows: number; + readonly tacCellM: number; + readonly tacOrigin: readonly [number, number]; +} + +/** + * Every ground polygon of one tier. `ring[i]` is the polygon's outline as x, z pairs in world + * metres; `y[i]` the mean height of its corners. + */ +export interface NavTier { + readonly polyCount: number; + readonly rings: Float32Array[]; + readonly heights: Float32Array; + readonly areas: Uint8Array; + readonly flags: Uint16Array; +} + +export interface NavCover { + readonly pos: readonly [number, number, number]; + readonly coverDir: readonly [number, number]; + readonly retreatDir: readonly [number, number]; + readonly halfAngleDeg: number; + readonly heightM: number; + readonly widthM: number; + /** 1 full cover, 2 hull-down. */ + readonly kind: number; +} + +/** Tactical grid, row-major from tacOrigin: each cell is exposure, clearance, team 1 and 2 priors. */ +export interface NavTactical { + readonly cols: number; + readonly rows: number; + readonly cellM: number; + readonly origin: readonly [number, number]; + readonly exposure: Uint8Array; + readonly clearanceHalfM: Uint8Array; +} + +export interface NavPack { + readonly header: NavHeader; + readonly tiers: NavTier[]; + readonly covers: NavCover[]; + readonly tactical: NavTactical; +} + +export class NavPackError extends Error {} + +const NAV_MAGIC = 'WTONAV\0\x01'; +const NAV_VERSION = 1; +const TIER_COUNT = 3; +const HEADER_BYTES = 124; +const COVER_BYTES = 68; +const NAV_PARAMS_BYTES = 28; +const TILE_HEADER_BYTES = 100; +const POLY_BYTES = 32; +const VERTS_PER_POLY = 6; +const DT_NULL_IDX = 0xffff; +const DT_POLYTYPE_GROUND = 0; + +function align4(n: number): number { + return (n + 3) & ~3; +} + +function readHeader(view: DataView): NavHeader & { tierOffsets: number[]; tierSizes: number[]; coverOffset: number; tacOffset: number } { + if (view.byteLength < HEADER_BYTES) throw new NavPackError('file shorter than the pack header'); + let magic = ''; + for (let i = 0; i < 8; i++) magic += String.fromCharCode(view.getUint8(i)); + const version = view.getUint32(8, true); + if (magic !== NAV_MAGIC || version !== NAV_VERSION || view.getUint32(64, true) !== TIER_COUNT) { + throw new NavPackError(`not a version ${NAV_VERSION} navigation pack`); + } + let sha = ''; + for (let i = 0; i < 20; i++) sha += view.getUint8(16 + i).toString(16).padStart(2, '0'); + const f = (at: number): number => view.getFloat32(at, true); + const u = (at: number): number => view.getUint32(at, true); + return { + version, + flags: u(12), + everSha1: sha, + bmin: [f(36), f(40), f(44)], + bmax: [f(48), f(52), f(56)], + waterLevel: f(60), + tierOffsets: [u(68), u(72), u(76)], + tierSizes: [u(80), u(84), u(88)], + coverOffset: u(92), + coverCount: u(96), + tacOffset: u(100), + tacCols: u(104), + tacRows: u(108), + tacCellM: f(112), + tacOrigin: [f(116), f(120)], + }; +} + +interface TierBuilder { + rings: Float32Array[]; + heights: number[]; + areas: number[]; + flags: number[]; +} + +function readTile(view: DataView, at: number, size: number, out: TierBuilder): void { + if (size < TILE_HEADER_BYTES) throw new NavPackError('Detour tile shorter than its header'); + const polyCount = view.getInt32(at + 24, true); + const vertCount = view.getInt32(at + 28, true); + const vertsAt = at + align4(TILE_HEADER_BYTES); + const polysAt = vertsAt + align4(vertCount * 12); + if (polysAt + polyCount * POLY_BYTES > at + size) throw new NavPackError('Detour tile polygons truncated'); + for (let p = 0; p < polyCount; p++) { + const pa = polysAt + p * POLY_BYTES; + const n = view.getUint8(pa + 30); + const areaAndType = view.getUint8(pa + 31); + if (areaAndType >> 6 !== DT_POLYTYPE_GROUND || n < 3) continue; + const ring = new Float32Array(n * 2); + let ySum = 0; + for (let k = 0; k < n && k < VERTS_PER_POLY; k++) { + const vi = view.getUint16(pa + 4 + k * 2, true); + if (vi === DT_NULL_IDX || vi >= vertCount) throw new NavPackError('Detour polygon vertex out of range'); + const va = vertsAt + vi * 12; + ring[k * 2] = view.getFloat32(va, true); + ySum += view.getFloat32(va + 4, true); + ring[k * 2 + 1] = view.getFloat32(va + 8, true); + } + out.rings.push(ring); + out.heights.push(ySum / n); + out.areas.push(areaAndType & 0x3f); + out.flags.push(view.getUint16(pa + 28, true)); + } +} + +function readTier(view: DataView, offset: number, size: number): NavTier { + if (offset + size > view.byteLength || size < NAV_PARAMS_BYTES + 4) throw new NavPackError('tier outside the file'); + const end = offset + size; + const tileCount = view.getUint32(offset + NAV_PARAMS_BYTES, true); + let at = offset + NAV_PARAMS_BYTES + 4; + const out: TierBuilder = { rings: [], heights: [], areas: [], flags: [] }; + for (let t = 0; t < tileCount; t++) { + if (at + 4 > end) throw new NavPackError(`tile ${t} header truncated`); + const tileSize = view.getUint32(at, true); + at += 4; + if (tileSize === 0 || at + tileSize > end) throw new NavPackError(`tile ${t} truncated`); + readTile(view, at, tileSize, out); + at += tileSize; + } + return { + polyCount: out.rings.length, + rings: out.rings, + heights: Float32Array.from(out.heights), + areas: Uint8Array.from(out.areas), + flags: Uint16Array.from(out.flags), + }; +} + +function readCovers(view: DataView, offset: number, count: number): NavCover[] { + if (offset + count * COVER_BYTES > view.byteLength) throw new NavPackError('cover points outside the file'); + const covers: NavCover[] = []; + for (let i = 0; i < count; i++) { + const a = offset + i * COVER_BYTES; + const f = (k: number): number => view.getFloat32(a + k * 4, true); + covers.push({ + pos: [f(0), f(1), f(2)], + coverDir: [f(3), f(4)], + retreatDir: [f(5), f(6)], + halfAngleDeg: f(13), + heightM: f(14), + widthM: f(15), + kind: view.getUint8(a + 64), + }); + } + return covers; +} + +function readTactical(view: DataView, h: ReturnType): NavTactical { + const cells = h.tacCols * h.tacRows; + if (h.tacOffset + cells * 4 > view.byteLength) throw new NavPackError('tactical grid outside the file'); + const exposure = new Uint8Array(cells); + const clearance = new Uint8Array(cells); + for (let i = 0; i < cells; i++) { + exposure[i] = view.getUint8(h.tacOffset + i * 4); + clearance[i] = view.getUint8(h.tacOffset + i * 4 + 1); + } + return { cols: h.tacCols, rows: h.tacRows, cellM: h.tacCellM, origin: h.tacOrigin, exposure, clearanceHalfM: clearance }; +} + +/** Parses a whole `.wtonav` file. Throws NavPackError when the bytes are not a valid pack. */ +export function readNavPack(bytes: Uint8Array): NavPack { + const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + const h = readHeader(view); + const tiers: NavTier[] = []; + for (let t = 0; t < TIER_COUNT; t++) tiers.push(readTier(view, h.tierOffsets[t] ?? 0, h.tierSizes[t] ?? 0)); + const header: NavHeader = { + version: h.version, flags: h.flags, everSha1: h.everSha1, bmin: h.bmin, bmax: h.bmax, + waterLevel: h.waterLevel, coverCount: h.coverCount, tacCols: h.tacCols, tacRows: h.tacRows, + tacCellM: h.tacCellM, tacOrigin: h.tacOrigin, + }; + return { header, tiers, covers: readCovers(view, h.coverOffset, h.coverCount), tactical: readTactical(view, h) }; +} diff --git a/packages/ground-sim/src/trace/names.ts b/packages/ground-sim/src/trace/names.ts new file mode 100644 index 0000000..d8a5720 --- /dev/null +++ b/packages/ground-sim/src/trace/names.ts @@ -0,0 +1,34 @@ +/** + * Display names of the numeric codes the ground AI writes into its log lines. They mirror the + * `let public WTO_*` constants of game-ai/ground; index = code. + */ + +export const BEHAVIOR_NAMES = ['advance', 'engage', 'halt', 'cover', 'reposition', 'hold', 'disperse', 'withdraw', 'repair'] as const; + +export const STATE_NAMES: Readonly> = { + 0: 'march', 1: 'runAndGun', 3: 'shortHalt', 4: 'retreatCover', 5: 'coverReload', + 7: 'hullAngle', 8: 'reposition', 9: 'disabled', 10: 'disperse', 11: 'ridgeWithdraw', +}; + +export const DENY_NAMES = [ + 'ok', 'noTarget', 'notReady', 'hitProb', 'longWindow', 'aimErr', 'settle', 'budget', + 'muzzleHard', 'arcHard', 'friendly', 'multiGun', 'traverse', 'burstPause', +] as const; + +export const BLOCK_NAMES = ['none', 'terrain', 'object', 'wreck', 'vehicle', 'smoke', 'foliage'] as const; + +export const COMMAND_NAMES = ['assault', 'flank', 'overwatch', 'defend', 'reserve', 'spaa'] as const; + +export const URGENCY_NAMES = ['low', 'medium', 'high'] as const; + +export const LANE_NAMES = ['center', 'left', 'right'] as const; + +export const VEHICLE_CLASS_NAMES = ['medium', 'light', 'heavy', 'td', 'spaa'] as const; + +/** Why the turret points where it does (WTO_LOOK_*). */ +export const LOOK_NAMES = ['none', 'engage', 'threat', 'watch', 'memory', 'cue', 'scan'] as const; + +export function nameOf(names: readonly string[] | Readonly>, code: number): string { + const name = Array.isArray(names) ? names[code] : (names as Readonly>)[code]; + return name ?? String(code); +} diff --git a/packages/ground-sim/src/trace/parse.ts b/packages/ground-sim/src/trace/parse.ts new file mode 100644 index 0000000..899c89e --- /dev/null +++ b/packages/ground-sim/src/trace/parse.ts @@ -0,0 +1,136 @@ +/** + * Reads the ground AI replay trace out of a decrypted game log (wtotools decrypt-clog). Every + * `WTO_AI|` line is ` [D] WTO_AI|KIND|key=value|...`. A battle starts at + * RUNTIME_READY; lines before the first one (hangar) are skipped. TRACE_CAP, TRACE_U and TRACE_B + * lines with the same time form one frame; all other kinds become events. Lines without a `t` field get + * their mission time from the log clock, offset by the last line that had both. + */ +import type { BotSample, CapSample, TraceBattle, TraceEvent, TraceFrame, UnitSample } from './types.ts'; + +type Fields = Record; + +interface MutableBattle { + level: string | undefined; + frames: TraceFrame[]; + events: TraceEvent[]; +} + +const MARK = 'WTO_AI|'; + +function splitLine(line: string): { clock: number; kind: string; fields: Fields } | undefined { + const at = line.indexOf(MARK); + if (at < 0) return undefined; + const clock = Number.parseFloat(line); + const parts = line.slice(at + MARK.length).trimEnd().split('|'); + const kind = parts[0] ?? ''; + const fields: Fields = {}; + for (let i = 1; i < parts.length; i++) { + const part = parts[i] ?? ''; + const eq = part.indexOf('='); + if (eq > 0) fields[part.slice(0, eq)] = part.slice(eq + 1); + } + return { clock, kind, fields }; +} + +function num(f: Fields, key: string): number { + const v = Number(f[key]); + return Number.isFinite(v) ? v : 0; +} + +function flag(f: Fields, key: string): boolean { + return f[key] === '1'; +} + +function id(f: Fields, key: string): string { + return f[key] ?? '0'; +} + +function readCap(f: Fields): CapSample { + return { idx: num(f, 'idx'), x: num(f, 'x'), z: num(f, 'z'), r: num(f, 'r'), owner: num(f, 'owner'), progress: num(f, 'prog') }; +} + +function readUnit(f: Fields): UnitSample { + return { + eid: id(f, 'eid'), army: num(f, 'army'), bot: flag(f, 'bot'), human: flag(f, 'human'), alive: flag(f, 'alive'), + x: num(f, 'x'), y: num(f, 'y'), z: num(f, 'z'), yaw: num(f, 'yaw'), speed: num(f, 'v'), + shooting: flag(f, 'shoot'), light: flag(f, 'light'), + }; +} + +function readBot(f: Fields): BotSample { + const gun = num(f, 'gun'); + return { + eid: id(f, 'eid'), vehicleClass: num(f, 'cls'), hasOrder: flag(f, 'ord'), command: num(f, 'cmd'), + urgency: num(f, 'urg'), capIdx: num(f, 'cap'), lane: num(f, 'lane'), goalX: num(f, 'gx'), goalZ: num(f, 'gz'), + behavior: num(f, 'bhv'), behaviorScore: num(f, 'bs'), state: num(f, 'st'), wantSpeed: num(f, 'wantV'), + forwardSpeed: num(f, 'vf'), reverseTravel: flag(f, 'rev'), target: id(f, 'tgt'), targetInSight: flag(f, 'los'), + threatCount: num(f, 'threats'), topThreat: id(f, 'top'), topVisibleThreat: id(f, 'topVis'), + lookAt: id(f, 'look'), lookReason: num(f, 'why'), wishYaw: num(f, 'wish'), + gunYaw: gun === 9999 ? undefined : gun, gunReady: flag(f, 'ready'), reloading: flag(f, 'reload'), + deny: num(f, 'deny'), hitProb: num(f, 'p'), threshold: num(f, 'thr'), requestedSpeed: num(f, 'reqV'), + }; +} + +function frameAt(battle: MutableBattle, t: number): TraceFrame { + const last = battle.frames[battle.frames.length - 1]; + if (last !== undefined && last.t === t) return last; + const frame: TraceFrame = { t, caps: [], units: new Map(), bots: new Map() }; + battle.frames.push(frame); + return frame; +} + +function finish(b: MutableBattle): TraceBattle { + b.events.sort((a, c) => a.t - c.t); + const firstFrame = b.frames[0]; + const lastFrame = b.frames[b.frames.length - 1]; + const firstEvent = b.events[0]; + const lastEvent = b.events[b.events.length - 1]; + const startT = Math.min(firstFrame?.t ?? Infinity, firstEvent?.t ?? Infinity); + const endT = Math.max(lastFrame?.t ?? -Infinity, lastEvent?.t ?? -Infinity); + return { level: b.level, frames: b.frames, events: b.events, startT: Number.isFinite(startT) ? startT : 0, endT: Number.isFinite(endT) ? endT : 0 }; +} + +/** All battles of one decrypted log, in log order. Battles without any trace frame are kept. */ +export function parseTraceLog(text: string): TraceBattle[] { + const battles: TraceBattle[] = []; + let current: MutableBattle | undefined; + let pendingLevel: string | undefined; + let clockOffset: number | undefined; + const open = (): MutableBattle => { + if (current !== undefined) battles.push(finish(current)); + current = { level: pendingLevel, frames: [], events: [] }; + return current; + }; + for (const line of text.split('\n')) { + const parsed = splitLine(line); + if (parsed === undefined) continue; + const { clock, kind, fields } = parsed; + if (kind.startsWith('NAVMESH') && fields['level'] !== undefined && fields['level'] !== '') { + pendingLevel = fields['level']; + if (current !== undefined && current.level === undefined) current.level = pendingLevel; + } + if (kind === 'RUNTIME_READY') { + open(); + clockOffset = undefined; + continue; + } + const hasT = fields['t'] !== undefined; + let t: number; + if (hasT) { + t = num(fields, 't'); + if (Number.isFinite(clock)) clockOffset = clock - t; + } else if (clockOffset !== undefined && Number.isFinite(clock)) { + t = clock - clockOffset; + } else { + continue; + } + const battle: MutableBattle | undefined = current; + if (battle === undefined) continue; + if (kind === 'TRACE_CAP') frameAt(battle, t).caps.push(readCap(fields)); + else if (kind === 'TRACE_U') { const u = readUnit(fields); frameAt(battle, t).units.set(u.eid, u); } + else if (kind === 'TRACE_B') { const b = readBot(fields); frameAt(battle, t).bots.set(b.eid, b); } + else battle.events.push({ t, kind, eid: fields['eid'], fields }); + } + if (current !== undefined) battles.push(finish(current)); + return battles; +} diff --git a/packages/ground-sim/src/trace/types.ts b/packages/ground-sim/src/trace/types.ts new file mode 100644 index 0000000..f859b04 --- /dev/null +++ b/packages/ground-sim/src/trace/types.ts @@ -0,0 +1,90 @@ +/** + * One battle of the ground AI replay trace (game-ai/ground/wto_ai_trace_common.das), as read from + * a decrypted game log or written by the simulator. Times are mission seconds; positions world + * metres; headings degrees of atan2(z, x). Entity ids stay the strings the log prints. + */ + +export interface CapSample { + readonly idx: number; + readonly x: number; + readonly z: number; + readonly r: number; + readonly owner: number; + readonly progress: number; +} + +export interface UnitSample { + readonly eid: string; + readonly army: number; + readonly bot: boolean; + readonly human: boolean; + readonly alive: boolean; + readonly x: number; + readonly y: number; + readonly z: number; + readonly yaw: number; + readonly speed: number; + readonly shooting: boolean; + readonly light: boolean; +} + +export interface BotSample { + readonly eid: string; + readonly vehicleClass: number; + readonly hasOrder: boolean; + readonly command: number; + readonly urgency: number; + readonly capIdx: number; + readonly lane: number; + readonly goalX: number; + readonly goalZ: number; + readonly behavior: number; + readonly behaviorScore: number; + readonly state: number; + readonly wantSpeed: number; + readonly forwardSpeed: number; + readonly reverseTravel: boolean; + /** Perception target; "0" when none. */ + readonly target: string; + readonly targetInSight: boolean; + readonly threatCount: number; + readonly topThreat: string; + readonly topVisibleThreat: string; + /** What the turret aims at (engaged target or watched threat); "0" otherwise. */ + readonly lookAt: string; + readonly lookReason: number; + readonly wishYaw: number; + /** Live barrel heading; undefined when the barrel could not be sampled. */ + readonly gunYaw: number | undefined; + readonly gunReady: boolean; + readonly reloading: boolean; + readonly deny: number; + readonly hitProb: number; + readonly threshold: number; + readonly requestedSpeed: number; +} + +export interface TraceFrame { + readonly t: number; + readonly caps: CapSample[]; + readonly units: Map; + readonly bots: Map; +} + +/** Any other WTO_AI line of the battle (SHOT, HIT, DEATH, BEHAVIOR, DENY, TURRET_FOCUS, NAV_*...). */ +export interface TraceEvent { + readonly t: number; + readonly kind: string; + /** Entity the line is about (its `eid` field), when it has one. */ + readonly eid: string | undefined; + readonly fields: Readonly>; +} + +export interface TraceBattle { + /** Level name from the navigation pack line (e.g. avg_berlin), when logged. */ + readonly level: string | undefined; + readonly frames: TraceFrame[]; + readonly events: TraceEvent[]; + readonly startT: number; + readonly endT: number; +} diff --git a/packages/patcher/src/ground-ai/ground-ai-config.ts b/packages/patcher/src/ground-ai/ground-ai-config.ts index 25b7479..5c3e003 100644 --- a/packages/patcher/src/ground-ai/ground-ai-config.ts +++ b/packages/patcher/src/ground-ai/ground-ai-config.ts @@ -339,6 +339,8 @@ export interface GroundAiConfig { readonly statsSampleSec: number; readonly statsSampleRangeM: number; readonly statsRearArcDeg: number; + readonly trace: boolean; + readonly traceIntervalSec: number; }; } @@ -590,6 +592,8 @@ function collectConfigEntries(c: GroundAiConfig): readonly DasEntry[] { ['WTO_AI_STATS_SAMPLE_SEC', 'float', c.diagnostics.statsSampleSec], ['WTO_AI_STATS_RANGE_M', 'float', c.diagnostics.statsSampleRangeM], ['WTO_AI_STATS_REAR_ARC_DEG', 'float', c.diagnostics.statsRearArcDeg], + ['WTO_AI_TRACE_ENABLED', 'bool', c.diagnostics.trace], + ['WTO_AI_TRACE_SEC', 'float', c.diagnostics.traceIntervalSec], ]; } diff --git a/tsconfig.json b/tsconfig.json index a039a22..e5e004e 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -17,6 +17,7 @@ }, "include": ["apps/*/src/**/*.ts", "packages/*/src/**/*.ts", "scripts/**/*.ts"], // The launcher is an Electron app with a window: it has its own tsconfig.node.json and - // tsconfig.web.json and its own typecheck script. - "exclude": ["apps/launcher/**"] + // tsconfig.web.json and its own typecheck script. The AI lab (apps/ai-lab) is a Vite page with + // its own tsconfig.json and typecheck script too. + "exclude": ["apps/launcher/**", "apps/ai-lab/**"] }