diff --git a/apps/launcher/src/main/services/resources/resource-paths.ts b/apps/launcher/src/main/services/resources/resource-paths.ts index 0ff8410..3871a36 100644 --- a/apps/launcher/src/main/services/resources/resource-paths.ts +++ b/apps/launcher/src/main/services/resources/resource-paths.ts @@ -21,6 +21,8 @@ export interface ResourcePaths { readonly modTemplates: string; /** Modular ground AI daScript sources injected into `game.vromfs.bin` when active. */ readonly groundAiScripts: string; + /** Location of the baseline navigation maps, when included with the launcher. */ + readonly bundledMapNavFolder: string; } export function resourcePaths(): ResourcePaths { @@ -38,6 +40,7 @@ export function bundledResourcePaths(): ResourcePaths { appIcon: join(process.resourcesPath, 'icon.ico'), modTemplates: join(process.resourcesPath, 'mod-templates'), groundAiScripts: join(process.resourcesPath, 'game-ai', 'ground'), + bundledMapNavFolder: join(process.resourcesPath, 'map-nav', 'maps'), }; } // The app path is apps/launcher; the repository is two levels up. @@ -48,6 +51,7 @@ export function bundledResourcePaths(): ResourcePaths { appIcon: join(repository, 'apps', 'launcher', 'resources', 'icon.ico'), modTemplates: join(repository, 'mod-dev-docs', 'templates'), groundAiScripts: join(repository, 'game-ai', 'ground'), + bundledMapNavFolder: join(repository, 'build', 'map-nav', 'maps'), }; } diff --git a/apps/launcher/src/main/workers/build-protocol.ts b/apps/launcher/src/main/workers/build-protocol.ts index 3b0a1a6..ba27d7c 100644 --- a/apps/launcher/src/main/workers/build-protocol.ts +++ b/apps/launcher/src/main/workers/build-protocol.ts @@ -10,6 +10,7 @@ export interface BuildRequest { readonly patches: string; readonly networkHookLibrary: string; readonly groundAiScripts: string; + readonly bundledMapNavFolder: string; readonly decalCache?: string; readonly hookLogging: boolean; readonly acceptedUnavailable: readonly string[]; diff --git a/apps/launcher/src/main/workers/build-worker.ts b/apps/launcher/src/main/workers/build-worker.ts index 000a450..900c8cc 100644 --- a/apps/launcher/src/main/workers/build-worker.ts +++ b/apps/launcher/src/main/workers/build-worker.ts @@ -1,5 +1,5 @@ -import { readFileSync, realpathSync } from 'node:fs'; -import { relative } from 'node:path'; +import { readFileSync, realpathSync, statSync } from 'node:fs'; +import { join, relative } from 'node:path'; import type { MessageEvent } from 'electron'; import { discoverMods, touchedClientPacks, type DiscoveredMod, type ModdableClientPack } from '@wto/mods'; import { @@ -95,6 +95,8 @@ function build(request: BuildRequest): void { const extraStockPacks = optionalPacksInBuild.length > 0 ? prepareOptionalStockPacks(request.copyPath, request.stockPath, optionalPacksInBuild) : undefined; + const mapNavFolder = [join(request.dataPath, 'map-nav', 'maps'), request.bundledMapNavFolder] + .find((folder) => statSync(folder, { throwIfNoEntry: false })?.isDirectory()); const result = buildGameCopy({ stock: readStockGameFiles(request.stockPath), @@ -105,6 +107,7 @@ function build(request: BuildRequest): void { placeholderDecals: decalCache === undefined, ...(decalIndexFiles ? { decalIndexFiles } : {}), hookLogging: request.hookLogging, + ...(mapNavFolder === undefined ? {} : { mapNavFolder }), ...(enabledMods.length > 0 ? { mods: enabledMods } : {}), ...(extraStockPacks ? { extraStockPacks } : {}), groundAi: { scriptsFolder: request.groundAiScripts, config: groundAiConfig }, diff --git a/tools/navgen/bake-maps.mts b/tools/navgen/bake-maps.mts new file mode 100644 index 0000000..6535fde --- /dev/null +++ b/tools/navgen/bake-maps.mts @@ -0,0 +1,109 @@ +/** + * Build the navigation and cover data for the ground mission pool of a local game copy. + * Compile the Rust extractor and C++ baker first. + * + * node tools/navgen/bake-maps.mts --game --out + * [--levels ] [--extract ] [--bake ] [--jobs ] + */ +import { spawn } from 'node:child_process'; +import { mkdir, mkdtemp, open, readdir, readFile, rename, stat } from 'node:fs/promises'; +import { join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { parseArgs } from 'node:util'; + +const repository = fileURLToPath(new URL('../../', import.meta.url)); +const { values } = parseArgs({ + options: { + game: { type: 'string' }, + out: { type: 'string' }, + levels: { type: 'string' }, + extract: { type: 'string', default: join(repository, 'tools/navgen/extract/target/release/wto-navgen-extract.exe') }, + bake: { type: 'string', default: join(repository, 'build/navgen/wto_navgen_bake.exe') }, + jobs: { type: 'string', default: '1' }, + }, +}); + +async function run(executable: string, args: string[], log?: string): Promise { + const output = log === undefined ? undefined : await open(log, 'w'); + try { + await new Promise((done, fail) => { + const child = spawn(executable, args, { + cwd: repository, + stdio: output ? ['ignore', output.fd, output.fd] : 'inherit', + windowsHide: true, + }); + child.once('error', fail); + child.once('exit', (code, signal) => { + if (code === 0) done(); + else fail(new Error(`${executable} exited with ${code ?? signal}${log ? ` (see ${log})` : ''}`)); + }); + }); + } finally { + await output?.close(); + } +} + +async function main(): Promise { + const jobs = Number(values.jobs); + if (!values.game || !values.out || !Number.isSafeInteger(jobs) || jobs < 1) { + throw new Error('Usage: --game --out [--levels ] [--extract ] [--bake ] [--jobs ]'); + } + const game = resolve(values.game); + const output = resolve(values.out); + const extract = resolve(values.extract); + const bake = resolve(values.bake); + const maps = join(output, 'maps'); + await Promise.all([stat(extract), stat(bake), mkdir(maps, { recursive: true })]); + const work = await mkdtemp(join(output, 'bake-')); + const args = [join(repository, 'tools/navgen/mission-bounds.mts'), '--game', game, '--out', work]; + if (values.levels !== undefined) args.push('--levels', values.levels); + await run(process.execPath, args, join(work, 'missions.log')); + + const suffix = '.pois.json'; + const levels = (await readdir(work)).filter((name) => /^[a-z0-9_]+\.pois\.json$/.test(name)) + .map((name) => name.slice(0, -suffix.length)); + if (levels.length === 0) throw new Error(`No ground levels found. See ${join(work, 'missions.log')}.`); + if (values.levels) { + const missing = values.levels.split(',').map((level) => level.trim().toLowerCase()) + .filter((level) => !levels.includes(level)); + if (missing.length) throw new Error(`Levels missing from the mission pool: ${missing.join(', ')}`); + } + + console.log(`Baking ${levels.length} ground levels. Logs: ${work}`); + let next = 0; + let finished = 0; + const failures: string[] = []; + const worker = async (): Promise => { + while (next < levels.length) { + const level = levels[next++]!; + const pois = join(work, level + suffix); + const geo = join(work, level + '.wtogeo'); + const candidate = join(work, level + '.wtonav'); + try { + await run(extract, ['--game', game, '--pois', pois, '--out', geo, + '--report', join(work, level + '.extract-report.json')], join(work, level + '.extract.log')); + const bakeLog = join(work, level + '.bake.log'); + await run(bake, ['--geo', geo, '--pois', pois, '--out', candidate], bakeLog); + const log = await readFile(bakeLog, 'utf8'); + const routes = [...log.matchAll(/Connectivity \S+: full=(\d+)\/(\d+)/g)]; + if (routes.length !== 3 || routes.some(([, , total]) => Number(total) === 0)) { + throw new Error('Missing spawn-to-capture checks. See ' + bakeLog); + } + if (routes.some(([, full, total]) => full !== total)) { + console.warn(level + ': incomplete paths in ' + bakeLog); + } + const { size } = await stat(candidate); + if (size === 0) throw new Error('The baker wrote an empty map.'); + await rename(candidate, join(maps, level + '.wtonav')); + console.log(`[${++finished}/${levels.length}] ${level} (${(size / 2 ** 20).toFixed(1)} MiB)`); + } catch (error) { + failures.push(level); + console.error(`[${++finished}/${levels.length}] ${level}: ${error instanceof Error ? error.message : error}`); + } + } + }; + await Promise.all(Array.from({ length: Math.min(jobs, levels.length) }, worker)); + if (failures.length) throw new Error(`Map generation failed for ${failures.join(', ')}.`); +} + +await main(); diff --git a/tools/navgen/mission-bounds.mts b/tools/navgen/mission-bounds.mts index bd3b178..f90c0f8 100644 --- a/tools/navgen/mission-bounds.mts +++ b/tools/navgen/mission-bounds.mts @@ -297,11 +297,10 @@ function main() { if (!n.includes('brief') && box.rad >= 5 && box.rad <= 250) { acc.caps.push({ name: a.name, x: box.cx, y: box.cy, z: box.cz, radius: box.rad, mission: mName }); } - } else if (n.includes('tankspawn') || (n.includes('spawn') && /t1|t2|team1|team2|tank/.test(n))) { - if (n.includes('brief')) continue; - if (n.includes('t1_') || n.includes('team1') || n.includes('_t1')) { + } else if (n.includes('spawn') && !n.includes('brief')) { + if (n.includes('t1_') || n.includes('team1') || n.includes('_t1') || n.startsWith('teama_spawn_')) { acc.t1Spawns.push({ name: a.name, x: box.cx, y: box.cy, z: box.cz, radius: box.rad, mission: mName }); - } else if (n.includes('t2_') || n.includes('team2') || n.includes('_t2')) { + } else if (n.includes('t2_') || n.includes('team2') || n.includes('_t2') || n.startsWith('teamb_spawn_')) { acc.t2Spawns.push({ name: a.name, x: box.cx, y: box.cy, z: box.cz, radius: box.rad, mission: mName }); } } diff --git a/tools/navgen/package-maps.mts b/tools/navgen/package-maps.mts new file mode 100644 index 0000000..8d383a2 --- /dev/null +++ b/tools/navgen/package-maps.mts @@ -0,0 +1,92 @@ +/** + * Package the baked navigation data for the launcher data directory. + * node tools/navgen/package-maps.mts --maps --inventory --out + * --version --game-version [--unsigned] + * + * Signed packages use the project's PATCH_SIGNING_KEY. The unpacked map-nav directory is also + * usable locally. Each release archive contains that directory, ready to extract into the data root. + */ +import { execFileSync } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import { mkdir, mkdtemp, readFile, readdir, rename, writeFile } from 'node:fs/promises'; +import { join, resolve } from 'node:path'; +import { parseArgs } from 'node:util'; +import { isPackVersion, packSigningPublicKey, signEd25519, verifyEd25519 } from '@wto/patcher'; +import { readNavPack } from '../../packages/ground-sim/src/map/wtonav.ts'; + +const { values } = parseArgs({ + options: { + maps: { type: 'string' }, + inventory: { type: 'string' }, + out: { type: 'string' }, + version: { type: 'string' }, + 'game-version': { type: 'string' }, + unsigned: { type: 'boolean', default: false }, + }, +}); + +async function main(): Promise { + const { maps, inventory, out, version, 'game-version': gameVersion } = values; + if (!maps || !inventory || !out || !version || !isPackVersion(version) || !gameVersion || + !/^\d+\.\d+\.\d+\.\d+$/.test(gameVersion)) { + throw new Error('Supply --maps, --inventory, --out, --version YYYY.MM.DD[.N] and --game-version x.y.z.n.'); + } + const privateKey = values.unsigned ? undefined : process.env['PATCH_SIGNING_KEY']; + if (!privateKey && !values.unsigned) throw new Error('Set PATCH_SIGNING_KEY or use --unsigned for local use.'); + const output = resolve(out); + const levels = (await readdir(inventory)).filter((file) => /^[a-z0-9_]+\.pois\.json$/.test(file)) + .map((file) => file.slice(0, -'.pois.json'.length)).sort(); + if (levels.length === 0) throw new Error('The mission inventory is empty.'); + + await mkdir(output, { recursive: true }); + const staging = await mkdtemp(join(output, 'map-nav-stage-')); + const pack = join(staging, 'map-nav'); + await mkdir(join(pack, 'maps'), { recursive: true }); + const entries = []; + for (const level of levels) { + const filename = level + '.wtonav'; + const bytes = await readFile(join(maps, filename)); + const { header, tiers } = readNavPack(bytes); + if (tiers.some((tier) => tier.polyCount === 0) || /^0+$/.test(header.everSha1)) { + throw new Error('Incomplete navigation data for ' + level); + } + entries.push({ + level, + everSha1: header.everSha1, + size: bytes.length, + sha256: createHash('sha256').update(bytes).digest('hex'), + covers: header.coverCount, + }); + await writeFile(join(pack, 'maps', filename), bytes); + } + + const app = JSON.parse(await readFile(new URL('../../apps/launcher/package.json', import.meta.url), 'utf8')) as { version: string }; + const manifest = JSON.stringify({ + format: 1, + version, + minAppVersion: app.version, + gameVersions: [gameVersion], + createdAt: new Date().toISOString(), + maps: entries, + }, null, 2) + '\n'; + await writeFile(join(pack, 'manifest.json'), manifest); + const stem = 'wtoffline-map-nav-' + version; + const archive = join(staging, stem + '.zip'); + execFileSync('tar', ['-a', '-c', '-f', archive, '-C', staging, 'map-nav'], { stdio: 'inherit', windowsHide: true }); + if (privateKey) { + const bytes = await readFile(archive); + const signature = signEd25519(bytes, privateKey); + const publicKey = packSigningPublicKey(); + if (!publicKey || !verifyEd25519(bytes, signature, publicKey)) { + throw new Error('The map archive signature did not verify against the project public key.'); + } + await writeFile(join(staging, stem + '.zip.sig'), signature); + } + await writeFile(join(staging, stem + '.manifest.json'), manifest); + const release = join(output, version); + await rename(staging, release); + console.log('Packaged ' + entries.length + ' maps in ' + join(release, stem + '.zip')); + console.log('Unpacked maps: ' + join(release, 'map-nav')); +} + +await main();