feat(ground-ai): add offline tank navmesh and cover baking prototype

Add Stage 0 offline map geometry extraction and Recast/Detour baking tools for ground AI navigation on feat/tank-ai-nav:

- Vendor upstream recastnavigation Recast and Detour sources (zlib license) under native/third_party/recastnavigation.
- Define shared .wtogeo and .wtonav binary layouts in native/wto-nav/wto_nav_format.h.
- Add mission-bounds.mts to collect union ground battle areas, spawns, and capture zones across mission templates.
- Add Rust extractor (tools/navgen/extract) using wt-unpack and config/rendinst_dmg.blk destructionImpulse thresholds to classify hard solids, bridges, crushable objects, and tree trunks in Dagor world space.
- Add multi-threaded MSVC C++ baker (tools/navgen/bake) producing 3 vehicle-width tiled Detour navmeshes, island pruning, dual-height voxel tank covers (full, hull-down, corner peek, retreat-verified), 8m tactical grids, and spawn-to-cap connectivity checks.
- Add zero-dependency PNG top-down preview renderer (tools/navgen/render-preview.py).

Verified: Rust release build (0 warnings), MSVC x64 baker build (0 warnings), root typecheck, and end-to-end extraction/baking/100% 3-tier connectivity and preview rendering on avg_berlin, avg_poland, and avg_hurtgen (2.61.0.58).
This commit is contained in:
N0VAN0M4LY committed 2026-12-04 11:33:32 +08:00
1 parent 688406bb76
commit 842ee23fa4
40 files changed
+22824

No files matched your search

File diff suppressed because it is too large. Load diff
+32
View File
@@ -0,0 +1,32 @@
<#
Build tools/navgen/bake/wto_navgen_bake.exe using MSVC x64 C++ (Visual Studio).
Links vendored upstream Recast + Detour (zlib license) from native/third_party/recastnavigation.
#>
param([string]$Out = (Join-Path $PSScriptRoot '..\..\..\build\navgen'))
$ErrorActionPreference = 'Stop'
$vswhere = Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio\Installer\vswhere.exe'
$vs = & $vswhere -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath
if (-not $vs) { throw 'Visual Studio with x64 C++ tools was not found' }
$vcvars = Join-Path $vs 'VC\Auxiliary\Build\vcvars64.bat'
$root = Resolve-Path (Join-Path $PSScriptRoot '..\..\..')
$rc = Join-Path $root 'native\third_party\recastnavigation\Recast'
$dt = Join-Path $root 'native\third_party\recastnavigation\Detour'
$navInc = Join-Path $root 'native\wto-nav'
New-Item -ItemType Directory -Force $Out | Out-Null
$obj = Join-Path $Out 'obj'
New-Item -ItemType Directory -Force $obj | Out-Null
$sources = @(
(Join-Path $PSScriptRoot 'bake.cpp')
) + (Get-ChildItem "$rc\Source\*.cpp").FullName + (Get-ChildItem "$dt\Source\*.cpp").FullName
$quoted = $sources | ForEach-Object { '"' + $_ + '"' }
$exe = Join-Path $Out 'wto_navgen_bake.exe'
$cmd = "`"$vcvars`" >nul && cl /nologo /O2 /EHsc /std:c++17 /MT /W3 /D_CRT_SECURE_NO_WARNINGS " +
"/I`"$rc\Include`" /I`"$dt\Include`" /I`"$navInc`" " +
"/Fo`"$obj\\`" $($quoted -join ' ') /Fe`"$exe`""
cmd /c $cmd
if ($LASTEXITCODE -ne 0) { throw "cl failed with exit code $LASTEXITCODE" }
Write-Output $exe
+534
View File
@@ -0,0 +1,534 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "adler2"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
[[package]]
name = "anstream"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85c097ce94629611e0a15ef1078a2fe2ce3b4a0f4b44708e85eeb09dd5f188eb"
dependencies = [
"anstyle",
"anstyle-parse",
"anstyle-query",
"anstyle-wincon",
"colorchoice",
"is_terminal_polyfill",
"utf8parse",
]
[[package]]
name = "anstyle"
version = "1.0.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c7a9e344b352bef7873e51ff425c2f90d5aa2a252db2b84289c93ff30beb3d7"
[[package]]
name = "anstyle-parse"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a0571a23d2188b4aae7adc1df454cc81d6232cf37674fa717ac119f6c74d0dc1"
dependencies = [
"utf8parse",
]
[[package]]
name = "anstyle-query"
version = "1.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "76a5cf9d05ffa9c878c447b33b069605e890ebcd36d2761f86367873c2ecaa7f"
dependencies = [
"windows-sys",
]
[[package]]
name = "anstyle-wincon"
version = "3.0.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2c2d00c1b2d84cef823d89d4da02ad8ff1e76c969e029da990b40f16dc834221"
dependencies = [
"anstyle",
"once_cell_polyfill",
"windows-sys",
]
[[package]]
name = "anyhow"
version = "1.0.105"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2cb931c189b85683d69a5cfad41d4d418671e1ac413dd209f3f2fc31e3cfd902"
[[package]]
name = "bcn-decode"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a3d5cf71fc14b37654892fc02d25b45ddca03d4245e352510e3c55bdc5cda1f"
[[package]]
name = "bitflags"
version = "2.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
[[package]]
name = "block-buffer"
version = "0.10.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
dependencies = [
"generic-array",
]
[[package]]
name = "byteorder"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34fb07aac3b9f547c7af8dc897dfe73c10847b6c71130c364bdd7891d979c816"
[[package]]
name = "cfg-if"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
[[package]]
name = "clap"
version = "4.6.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "50066ca966813ca8957ee15361752f19424a8ff620dbe9c8993d9f99d99b04b3"
dependencies = [
"clap_builder",
"clap_derive",
]
[[package]]
name = "clap_builder"
version = "4.6.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a0ed97c96ef4efb3cc84e09fa388df4463e7cc3224ec38d7b1d9e45749333590"
dependencies = [
"anstream",
"anstyle",
"clap_lex",
"strsim",
]
[[package]]
name = "clap_derive"
version = "4.6.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4c174f11f949b9ca8c60580925e282b9cbd5454750e506f08648b2038080cd7"
dependencies = [
"heck",
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "clap_lex"
version = "1.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79"
[[package]]
name = "colorchoice"
version = "1.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f7f11958434c85b6efac08f8299dc08bd263184ce080232e2168940cda4368e"
[[package]]
name = "crc32fast"
version = "1.5.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fd9ae8fcb3ea71b0b26338b4ffb13006bb175de8fd07921089a906ce7e5e6945"
dependencies = [
"cfg-if",
]
[[package]]
name = "crypto-common"
version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
dependencies = [
"generic-array",
"typenum",
]
[[package]]
name = "digest"
version = "0.10.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
dependencies = [
"block-buffer",
"crypto-common",
]
[[package]]
name = "equivalent"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"
[[package]]
name = "fdeflate"
version = "0.3.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c"
dependencies = [
"simd-adler32",
]
[[package]]
name = "flate2"
version = "1.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4"
dependencies = [
"crc32fast",
"miniz_oxide 0.9.1",
"zlib-rs",
]
[[package]]
name = "foldhash"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
[[package]]
name = "generic-array"
version = "0.14.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
dependencies = [
"typenum",
"version_check",
]
[[package]]
name = "hashbrown"
version = "0.17.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc"
[[package]]
name = "heck"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]
name = "indexmap"
version = "2.14.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
dependencies = [
"equivalent",
"hashbrown",
]
[[package]]
name = "is_terminal_polyfill"
version = "1.70.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
[[package]]
name = "itoa"
version = "1.0.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
[[package]]
name = "lewton"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "777b48df9aaab155475a83a7df3070395ea1ac6902f5cd062b8f2b028075c030"
dependencies = [
"byteorder",
"tinyvec",
]
[[package]]
name = "libc"
version = "0.2.191"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
[[package]]
name = "lztans"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4bad6ebd0a522f78e2889049a78d31ec62cd646a37524215fa00ea548b20bed0"
[[package]]
name = "md-5"
version = "0.10.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf"
dependencies = [
"cfg-if",
"digest",
]
[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "memmap2"
version = "0.9.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6b0ca1155a9ecc25aa12e8313a119f32edf0255fea2f44839c4ac0a12b2ac157"
dependencies = [
"libc",
]
[[package]]
name = "miniz_oxide"
version = "0.8.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"
dependencies = [
"adler2",
"simd-adler32",
]
[[package]]
name = "miniz_oxide"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c"
dependencies = [
"adler2",
"simd-adler32",
]
[[package]]
name = "once_cell_polyfill"
version = "1.70.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
[[package]]
name = "png"
version = "0.18.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61"
dependencies = [
"bitflags",
"crc32fast",
"fdeflate",
"flate2",
"miniz_oxide 0.8.9",
]
[[package]]
name = "proc-macro2"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
"proc-macro2",
]
[[package]]
name = "ruzstd"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a7c1c839d570d835527c9a5e4db7cb2198683a988cb9d7293fc8674e6bd58fc8"
dependencies = [
"twox-hash",
]
[[package]]
name = "serde"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
dependencies = [
"serde_core",
"serde_derive",
]
[[package]]
name = "serde_core"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "serde_json"
version = "1.0.154"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
dependencies = [
"foldhash",
"indexmap",
"itoa",
"memchr",
"serde",
"serde_core",
"zmij",
]
[[package]]
name = "simd-adler32"
version = "0.3.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
[[package]]
name = "strsim"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
[[package]]
name = "syn"
version = "3.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "tinyvec"
version = "1.13.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee"
[[package]]
name = "twox-hash"
version = "2.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "86a801b3cea342a06d468c8710662aa29e5e05e4f5c0d62f00bbb7f2ad7941c2"
[[package]]
name = "typenum"
version = "1.20.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
[[package]]
name = "unicode-ident"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
[[package]]
name = "utf8parse"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
[[package]]
name = "version_check"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
[[package]]
name = "windows-link"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f4e57b2aae53a240c62b65069a63eaf8d5fa747f5d0d8e670c5210a98847bce4"
[[package]]
name = "windows-sys"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eed2df9f5f458664c87437f6758f0d93085b06433bf66b2b84c23c19f3d2012c"
dependencies = [
"windows-link",
]
[[package]]
name = "wt-formats"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8cc92320ebb10137ea72419d36b91febc1aa597af3ee762d75282d3980575d89"
dependencies = [
"bcn-decode",
"flate2",
"lztans",
"png",
"ruzstd",
]
[[package]]
name = "wt-unpack"
version = "0.5.1"
source = "git+https://github.com/patodois/wt-unpack?rev=01d5b7603ae35e261a676d9b7b644c521dd303a0#01d5b7603ae35e261a676d9b7b644c521dd303a0"
dependencies = [
"anyhow",
"clap",
"lewton",
"lztans",
"md-5",
"memmap2",
"png",
"ruzstd",
"serde_json",
"wt-formats",
]
[[package]]
name = "wto-navgen-extract"
version = "0.1.0"
dependencies = [
"anyhow",
"serde",
"serde_json",
"wt-formats",
"wt-unpack",
]
[[package]]
name = "zlib-rs"
version = "0.6.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa76918995d776d9dd34d371030be228d021137449771493d56e29f77e4148ac"
[[package]]
name = "zmij"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
+16
View File
@@ -0,0 +1,16 @@
[package]
name = "wto-navgen-extract"
version = "0.1.0"
edition = "2021"
description = "Offline Dagor level geometry and collision extractor for WTOffline tank navigation"
[dependencies]
anyhow = "1"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
wt-formats = "0.1.0"
wt-unpack = { git = "https://github.com/patodois/wt-unpack", rev = "01d5b7603ae35e261a676d9b7b644c521dd303a0" }
[profile.release]
opt-level = 3
lto = "thin"
+550
View File
@@ -0,0 +1,550 @@
use std::collections::{HashMap, HashSet};
use std::fs::{self, File};
use std::io::{BufWriter, Write};
use std::path::{Path, PathBuf};
use std::time::Instant;
use anyhow::{bail, Context, Result};
use serde::Deserialize;
use wt_formats::grp::GrpPack;
use wt_unpack::blk::{self, Value};
use wt_unpack::collision::{Collision, CollisionNode, NodeKind, COLLISION};
use wt_unpack::level::{Heightmap, Level};
use wt_unpack::rendinst::ResourceIndex;
use wt_unpack::vromfs::Vromfs;
const WTO_GEO_MAGIC: &[u8; 8] = b"WTOGEO\0\x01";
const WTO_GEO_VERSION: u32 = 1;
const OBS_HARD_SOLID: u8 = 0;
const OBS_BRIDGE_DECK: u8 = 1;
const OBS_CRUSHABLE: u8 = 2;
const OBS_TREE_THICK: u8 = 3;
const OBS_TREE_THIN: u8 = 4;
#[derive(Debug, Deserialize)]
struct LevelPois {
level: String,
#[serde(rename = "levelPath")]
level_path: String,
#[serde(rename = "boundsMin")]
bounds_min: [f32; 2],
#[serde(rename = "boundsMax")]
bounds_max: [f32; 2],
}
#[derive(Debug, Clone)]
struct PoolMeta {
is_bridge: bool,
is_crushable: bool,
is_soft_foliage: bool,
}
#[derive(Debug)]
struct CachedCollision {
max_radius: f32,
tris: Vec<([f32; 3], [f32; 3], [f32; 3], u8)>,
}
fn parse_args() -> Result<(PathBuf, PathBuf, PathBuf)> {
let mut game: Option<PathBuf> = None;
let mut pois: Option<PathBuf> = None;
let mut out: Option<PathBuf> = None;
let mut args = std::env::args().skip(1);
while let Some(a) = args.next() {
match a.as_str() {
"--game" => game = args.next().map(PathBuf::from),
"--pois" => pois = args.next().map(PathBuf::from),
"--out" => out = args.next().map(PathBuf::from),
other => bail!("unknown argument: {other}"),
}
}
Ok((
game.context("missing --game <clientDir>")?,
pois.context("missing --pois <level.pois.json>")?,
out.context("missing --out <level.wtogeo>")?,
))
}
struct AcesMeta {
water_level: f32,
/// Authoritative tank-crushable impulse threshold from `config/rendinst_dmg.blk` (lowercase name -> destructionImpulse).
destr_impulse: HashMap<String, f32>,
}
fn read_aces_meta(game: &Path, level_name: &str) -> AcesMeta {
let mut meta = AcesMeta { water_level: -1.0e6, destr_impulse: HashMap::new() };
let aces_path = game.join("aces.vromfs.bin");
let Ok(raw) = fs::read(&aces_path) else { return meta; };
let Ok(arc) = Vromfs::parse(&raw) else { return meta; };
let shared = arc
.files
.iter()
.find(|f| f.name == wt_unpack::vromfs::SHARED_NAMEMAP_NAME)
.and_then(|nm| blk::SharedContext::from_namemap(&nm.data).ok())
.map(|(mut ctx, dict_name)| {
if let Some(df) = arc.files.iter().find(|f| f.name.eq_ignore_ascii_case(&dict_name)) {
ctx.dict = Some(df.data.clone());
}
ctx
});
let target = format!("levels/{}.blk", level_name.to_lowercase());
if let Some(entry) = arc.files.iter().find(|f| f.name.eq_ignore_ascii_case(&target)) {
if let Ok(doc) = blk::parse(&entry.data, shared.as_ref()) {
for (name, value) in &doc.params {
if name.eq_ignore_ascii_case("water_level") {
match value {
Value::Real(v) => meta.water_level = *v,
Value::Int(v) => meta.water_level = *v as f32,
_ => {}
}
}
}
}
}
if let Some(dmg_entry) = arc.files.iter().find(|f| f.name.eq_ignore_ascii_case("config/rendinst_dmg.blk")) {
if let Ok(doc) = blk::parse(&dmg_entry.data, shared.as_ref()) {
for b in &doc.blocks {
let mut rname: Option<&str> = None;
let mut impulse: Option<f32> = None;
for (k, v) in &b.params {
if k.eq_ignore_ascii_case("name") {
if let Value::Str(s) = v { rname = Some(s.as_str()); }
} else if k.eq_ignore_ascii_case("destructionImpulse") {
match v {
Value::Real(x) => impulse = Some(*x),
Value::Int(x) => impulse = Some(*x as f32),
_ => {}
}
}
}
if let (Some(n), Some(imp)) = (rname, impulse) {
meta.destr_impulse.insert(n.to_lowercase(), imp);
}
}
}
}
meta
}
fn classify_pool(name: &str, destr_impulse: Option<f32>) -> PoolMeta {
let lower = name.to_lowercase();
let is_bridge = lower.contains("bridge")
|| lower.contains("viaduct")
|| lower.contains("overpass")
|| lower.contains("pontoon")
|| lower.contains("jetty")
|| lower.contains("pier");
let always_hard = lower.contains("rock")
|| lower.contains("cliff")
|| lower.contains("bunker")
|| lower.contains("house")
|| lower.contains("building")
|| lower.contains("castle")
|| lower.contains("tower")
|| lower.contains("church")
|| lower.contains("factory")
|| lower.contains("hangar")
|| lower.contains("wagon")
|| lower.contains("train")
|| lower.contains("locomotive")
|| lower.contains("container")
|| lower.contains("tank_wreck")
|| is_bridge;
let is_soft_foliage = !always_hard
&& (lower.starts_with("bush_")
|| lower.contains("_bush_")
|| lower.starts_with("shrub_")
|| lower.contains("_shrub_")
|| lower.contains("grass")
|| lower.contains("reed")
|| lower.contains("flower")
|| lower.contains("fern"));
// Authoritative War Thunder physics: objects in `config/rendinst_dmg.blk` with low
// `destructionImpulse` (<= 45,000 N*s) are crushed on contact by moving tanks (wooden fences,
// lamp posts, hedges, benches, sheds, destructible thin walls, small trees).
let is_crushable = !always_hard
&& match destr_impulse {
Some(imp) if imp > 0.0 && imp <= 45_000.0 => true,
_ => lower.contains("fence_wood")
|| lower.contains("wooden_fence")
|| lower.contains("hedge")
|| lower.contains("sign_")
|| lower.contains("bench")
|| lower.contains("hay"),
};
PoolMeta { is_bridge, is_crushable, is_soft_foliage }
}
fn transform_point(tm: &[[f32; 3]; 4], p: [f32; 3]) -> [f32; 3] {
[
tm[0][0] * p[0] + tm[1][0] * p[1] + tm[2][0] * p[2] + tm[3][0],
tm[0][1] * p[0] + tm[1][1] * p[1] + tm[2][1] * p[2] + tm[3][1],
tm[0][2] * p[0] + tm[1][2] * p[1] + tm[2][2] * p[2] + tm[3][2],
]
}
fn det3(tm: &[[f32; 3]; 4]) -> f32 {
let [a, b, c] = [tm[0], tm[1], tm[2]];
a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0])
+ a[2] * (b[0] * c[1] - b[1] * c[0])
}
fn box_tris(n: &CollisionNode) -> Vec<([f32; 3], [f32; 3], [f32; 3])> {
let [lo, hi] = n.bbox;
let c = |i: usize| {
n.to_object([
if i & 1 == 0 { lo[0] } else { hi[0] },
if i & 2 == 0 { lo[1] } else { hi[1] },
if i & 4 == 0 { lo[2] } else { hi[2] },
])
};
let pts: Vec<[f32; 3]> = (0..8).map(c).collect();
let quads = [[0, 2, 3, 1], [4, 5, 7, 6], [0, 1, 5, 4], [2, 6, 7, 3], [0, 4, 6, 2], [1, 3, 7, 5]];
let mut tris = Vec::with_capacity(12);
for q in quads {
tris.push((pts[q[0]], pts[q[1]], pts[q[2]]));
tris.push((pts[q[0]], pts[q[2]], pts[q[3]]));
}
tris
}
fn capsule_tris(a: [f32; 3], b: [f32; 3], r: f32) -> Vec<([f32; 3], [f32; 3], [f32; 3])> {
let dx = b[0] - a[0];
let dy = b[1] - a[1];
let dz = b[2] - a[2];
let len = (dx * dx + dy * dy + dz * dz).sqrt();
let axis = if len > 1e-4 { [dx / len, dy / len, dz / len] } else { [0.0, 1.0, 0.0] };
let up = if axis[1].abs() < 0.9 { [0.0, 1.0, 0.0] } else { [1.0, 0.0, 0.0] };
let cross = |u: [f32; 3], v: [f32; 3]| {
[u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]]
};
let norm = |v: [f32; 3]| {
let l = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt().max(1e-6);
[v[0] / l, v[1] / l, v[2] / l]
};
let u = norm(cross(axis, up));
let v = norm(cross(axis, u));
let segs = 6usize;
let mut ring_a = Vec::with_capacity(segs);
let mut ring_b = Vec::with_capacity(segs);
for i in 0..segs {
let ang = (i as f32) * std::f32::consts::TAU / (segs as f32);
let (ca, sa) = (ang.cos() * r, ang.sin() * r);
let off = [u[0] * ca + v[0] * sa, u[1] * ca + v[1] * sa, u[2] * ca + v[2] * sa];
ring_a.push([a[0] + off[0], a[1] + off[1], a[2] + off[2]]);
ring_b.push([b[0] + off[0], b[1] + off[1], b[2] + off[2]]);
}
let mut tris = Vec::with_capacity(segs * 2);
for i in 0..segs {
let j = (i + 1) % segs;
tris.push((ring_a[i], ring_a[j], ring_b[j]));
tris.push((ring_a[i], ring_b[j], ring_b[i]));
}
tris
}
fn tri_normal_y(a: [f32; 3], b: [f32; 3], c: [f32; 3]) -> f32 {
let e1 = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
let e2 = [c[0] - a[0], c[1] - a[1], c[2] - a[2]];
let nx = e1[1] * e2[2] - e1[2] * e2[1];
let ny = e1[2] * e2[0] - e1[0] * e2[2];
let nz = e1[0] * e2[1] - e1[1] * e2[0];
let len = (nx * nx + ny * ny + nz * nz).sqrt();
if len > 1e-6 { (ny / len).abs() } else { 0.0 }
}
fn build_cached_collision(c: &Collision, meta: &PoolMeta) -> Option<CachedCollision> {
if meta.is_soft_foliage {
return None;
}
let mut tris = Vec::new();
for n in &c.nodes {
// Vehicles only collide with physics_collidable nodes (behavior bit 1).
if !n.physics_collidable() {
continue;
}
let mat_soft = !n.materials.is_empty()
&& n.materials.iter().all(|m| {
let ml = m.to_lowercase();
ml.contains("bush") || ml.contains("foliage") || ml.contains("leaves") || ml.contains("glass")
});
if mat_soft {
continue;
}
let scale = det3(&n.tm).abs().cbrt();
match n.kind {
NodeKind::Mesh | NodeKind::Convex => {
if n.indices.len() < 3 {
continue;
}
for t in n.indices.chunks_exact(3) {
let p0 = n.to_object(n.positions[t[0] as usize]);
let p1 = n.to_object(n.positions[t[1] as usize]);
let p2 = n.to_object(n.positions[t[2] as usize]);
let cls = if meta.is_bridge && tri_normal_y(p0, p1, p2) >= 0.72 {
OBS_BRIDGE_DECK
} else if meta.is_crushable {
OBS_CRUSHABLE
} else {
OBS_HARD_SOLID
};
tris.push((p0, p1, p2, cls));
}
}
NodeKind::Box => {
for (p0, p1, p2) in box_tris(n) {
let cls = if meta.is_bridge && tri_normal_y(p0, p1, p2) >= 0.72 {
OBS_BRIDGE_DECK
} else if meta.is_crushable {
OBS_CRUSHABLE
} else {
OBS_HARD_SOLID
};
tris.push((p0, p1, p2, cls));
}
}
NodeKind::Capsule => {
if let Some(cap) = n.capsule {
let a = n.to_object(cap.a);
let b = n.to_object(cap.b);
let r = (cap.radius * scale).max(0.08);
let cls = if r >= 0.28 { OBS_TREE_THICK } else { OBS_TREE_THIN };
for (p0, p1, p2) in capsule_tris(a, b, r) {
tris.push((p0, p1, p2, cls));
}
}
}
NodeKind::Points | NodeKind::Sphere => {}
}
}
if tris.is_empty() {
return None;
}
let bmin = c.bbox[0];
let bmax = c.bbox[1];
let max_r = [bmin[0].abs().max(bmax[0].abs()), bmin[2].abs().max(bmax[2].abs())]
.iter()
.copied()
.fold(0.0f32, f32::max)
* 1.42;
Some(CachedCollision { max_radius: max_r.max(4.0), tris })
}
fn crop_heightmap(hm: &Heightmap, min_x: f32, min_z: f32, max_x: f32, max_z: f32) -> (u32, u32, [f32; 2], Vec<f32>) {
let cs = hm.cell_size;
let x0 = (((min_x - hm.origin[0]) / cs).floor() as i32).clamp(0, (hm.width as i32) - 2) as u32;
let z0 = (((min_z - hm.origin[1]) / cs).floor() as i32).clamp(0, (hm.height as i32) - 2) as u32;
let x1 = (((max_x - hm.origin[0]) / cs).ceil() as i32).clamp((x0 as i32) + 1, (hm.width as i32) - 1) as u32;
let z1 = (((max_z - hm.origin[1]) / cs).ceil() as i32).clamp((z0 as i32) + 1, (hm.height as i32) - 1) as u32;
let cw = x1 - x0 + 1;
let ch = z1 - z0 + 1;
let mut heights = Vec::with_capacity((cw * ch) as usize);
for z in z0..=z1 {
let row = (z as usize) * (hm.width as usize);
for x in x0..=x1 {
heights.push(hm.metres(hm.data[row + x as usize]));
}
}
let origin = [hm.origin[0] + (x0 as f32) * cs, hm.origin[1] + (z0 as f32) * cs];
(cw, ch, origin, heights)
}
fn main() -> Result<()> {
let t0 = Instant::now();
let (game_dir, pois_path, out_path) = parse_args()?;
let pois: LevelPois = serde_json::from_str(
&fs::read_to_string(&pois_path).with_context(|| format!("reading {}", pois_path.display()))?,
)?;
let level_file = game_dir.join(&pois.level_path);
let raw = fs::read(&level_file).with_context(|| format!("reading {}", level_file.display()))?;
let level = Level::parse(&raw).with_context(|| format!("parsing {}", level_file.display()))?;
let ever_sha1 = level.export_info()?.and_then(|e| e.sha1).unwrap_or([0u8; 20]);
let aces_meta = read_aces_meta(&game_dir, &pois.level);
let water_level = aces_meta.water_level;
if let Some(pm) = level.phys_map_info()? {
println!(
" LMp2: {}x{} scale={:.2}m origin=({:.0},{:.0}) mats={:?}",
pm.size[0],
pm.size[1],
pm.metres_per_texel,
pm.world_origin[0],
pm.world_origin[1],
&pm.materials[..pm.materials.len().min(10)]
);
}
let hm = level.heightmap()?.with_context(|| format!("{} has no HM2 heightmap", pois.level))?;
let (cw, ch, crop_origin, heights) = crop_heightmap(
&hm,
pois.bounds_min[0],
pois.bounds_min[1],
pois.bounds_max[0],
pois.bounds_max[1],
);
let crop_max_x = crop_origin[0] + ((cw - 1) as f32) * hm.cell_size;
let crop_max_z = crop_origin[1] + ((ch - 1) as f32) * hm.cell_size;
println!(
"{}: HM2 full={}x{} cs={:.2}m -> crop={}x{} [{:.0}..{:.0}]x[{:.0}..{:.0}] water={:.2}m",
pois.level,
hm.width,
hm.height,
hm.cell_size,
cw,
ch,
crop_origin[0],
crop_max_x,
crop_origin[1],
crop_max_z,
water_level
);
// Collect distinct placed RendInst pools from RIGz
let layers = level.rendinst_layers()?;
let mut pool_names: HashSet<String> = HashSet::new();
for layer in &layers {
for (pool, cnt) in layer.pools.iter().zip(layer.counts()) {
if cnt > 0 {
pool_names.insert(pool.name.clone());
}
}
}
let res_index = ResourceIndex::build(&game_dir, &[COLLISION])?;
// Group collision loads by .grp file so each pack is read once
let mut by_pack: HashMap<PathBuf, Vec<(String, String)>> = HashMap::new();
let mut no_collision = 0usize;
for name in &pool_names {
let res_name = format!("{name}_collision");
if let Some(p) = res_index.find(COLLISION, &res_name) {
by_pack.entry(p.to_path_buf()).or_default().push((name.clone(), res_name));
} else {
no_collision += 1;
}
}
let mut cached_cols: HashMap<String, CachedCollision> = HashMap::new();
for (pack_path, items) in &by_pack {
let Ok(bytes) = fs::read(pack_path) else { continue };
let Ok(pack) = GrpPack::parse(&bytes) else { continue };
for (pool_name, res_name) in items {
let Some(res) = pack.find(res_name, COLLISION) else { continue };
let Ok(col) = Collision::parse(res_name, pack.data(res)) else { continue };
let imp = aces_meta.destr_impulse.get(&pool_name.to_lowercase()).copied();
let meta = classify_pool(pool_name, imp);
if let Some(cc) = build_cached_collision(&col, &meta) {
cached_cols.insert(pool_name.clone(), cc);
}
}
}
// Stream placed collision triangles inside the cropped battle area
let pad = 16.0;
let mut verts: Vec<[f32; 3]> = Vec::with_capacity(200_000);
let mut tris: Vec<([u32; 3], u8)> = Vec::with_capacity(100_000);
let mut inst_used = 0usize;
let mut cls_counts = [0usize; 5];
for layer in &layers {
let instances = layer.instances()?;
for inst in instances {
let Some(pool) = layer.pools.get(inst.pool) else { continue };
let Some(cc) = cached_cols.get(&pool.name) else { continue };
let pos = inst.tm[3];
// Quick XZ culling using instance scale + object bounding radius
let sx = (inst.tm[0][0].powi(2) + inst.tm[0][1].powi(2) + inst.tm[0][2].powi(2)).sqrt();
let sz = (inst.tm[2][0].powi(2) + inst.tm[2][1].powi(2) + inst.tm[2][2].powi(2)).sqrt();
let rad = cc.max_radius * sx.max(sz).max(1.0);
if pos[0] + rad < crop_origin[0] - pad
|| pos[0] - rad > crop_max_x + pad
|| pos[2] + rad < crop_origin[1] - pad
|| pos[2] - rad > crop_max_z + pad
{
continue;
}
inst_used += 1;
for &(p0, p1, p2, cls) in &cc.tris {
let w0 = transform_point(&inst.tm, p0);
let w1 = transform_point(&inst.tm, p1);
let w2 = transform_point(&inst.tm, p2);
let base = verts.len() as u32;
verts.push(w0);
verts.push(w1);
verts.push(w2);
tris.push(([base, base + 1, base + 2], cls));
if (cls as usize) < cls_counts.len() {
cls_counts[cls as usize] += 1;
}
}
}
}
println!(
" RIGz: pools={} cols={} noCol={} instancesInBounds={} obsTris={} [hard={} bridge={} crush={} treeThick={} treeThin={}] ({:.2}s)",
pool_names.len(),
cached_cols.len(),
no_collision,
inst_used,
tris.len(),
cls_counts[0],
cls_counts[1],
cls_counts[2],
cls_counts[3],
cls_counts[4],
t0.elapsed().as_secs_f32()
);
if let Some(parent) = out_path.parent() {
fs::create_dir_all(parent)?;
}
let mut w = BufWriter::new(File::create(&out_path)?);
// WtoGeoHeader (must match native/wto-nav/wto_nav_format.h byte-for-byte)
w.write_all(WTO_GEO_MAGIC)?;
w.write_all(&WTO_GEO_VERSION.to_le_bytes())?;
w.write_all(&0u32.to_le_bytes())?; // flags
w.write_all(&ever_sha1)?;
w.write_all(&water_level.to_le_bytes())?;
w.write_all(&crop_origin[0].to_le_bytes())?;
w.write_all(&crop_origin[1].to_le_bytes())?;
w.write_all(&crop_max_x.to_le_bytes())?;
w.write_all(&crop_max_z.to_le_bytes())?;
w.write_all(&cw.to_le_bytes())?;
w.write_all(&ch.to_le_bytes())?;
w.write_all(&hm.cell_size.to_le_bytes())?;
w.write_all(&crop_origin[0].to_le_bytes())?;
w.write_all(&crop_origin[1].to_le_bytes())?;
w.write_all(&(verts.len() as u32).to_le_bytes())?;
w.write_all(&(tris.len() as u32).to_le_bytes())?;
// Heightmap float32 samples
for h in &heights {
w.write_all(&h.to_le_bytes())?;
}
// Obstacle vertices (float32 x 3)
for v in &verts {
w.write_all(&v[0].to_le_bytes())?;
w.write_all(&v[1].to_le_bytes())?;
w.write_all(&v[2].to_le_bytes())?;
}
// Obstacle triangles (uint32 x 3 + uint8 class)
for (idx, cls) in &tris {
w.write_all(&idx[0].to_le_bytes())?;
w.write_all(&idx[1].to_le_bytes())?;
w.write_all(&idx[2].to_le_bytes())?;
w.write_all(&[*cls])?;
}
w.flush()?;
println!(" wrote {} ({:.1} MB)", out_path.display(), fs::metadata(&out_path)?.len() as f64 / (1024.0 * 1024.0));
Ok(())
}
+278
View File
@@ -0,0 +1,278 @@
/**
* Extract union battle-area bounds, tank spawn points, and capture zones for ground
* levels from `char.vromfs.bin` (`config/mislist.blk`) and `mis.vromfs.bin` (recursively
* resolving `imports/import_record` mission templates).
*
* Usage:
* node --experimental-strip-types tools/navgen/mission-bounds.mts \
* --game "J:\GAME\WTLab\client-2.61.0.58" \
* --out "build\nav-work" \
* --levels avg_berlin,avg_poland,avg_hurtgen
*/
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { join, resolve } from 'node:path';
import { readArchive, getFile, NAME_MAP_PATH } from '../../packages/vromfs/src/index.ts';
import { decodeBlk, parseSharedNameMap, findBlock, findParam, type BlkBlock, type SharedNameContext } from '../../packages/blk/src/index.ts';
interface PoiPoint {
readonly name: string;
readonly x: number;
readonly y: number;
readonly z: number;
readonly radius: number;
readonly mission: string;
}
interface LevelPois {
readonly level: string;
readonly levelPath: string;
readonly missions: readonly string[];
readonly boundsMin: readonly [number, number];
readonly boundsMax: readonly [number, number];
readonly team1Spawns: readonly PoiPoint[];
readonly team2Spawns: readonly PoiPoint[];
readonly captureZones: readonly PoiPoint[];
}
function parseArgs(argv: string[]) {
let gameDir = '';
let outDir = '';
let levelsFilter: Set<string> | null = null;
for (let i = 0; i < argv.length; i++) {
const a = argv[i]!;
if (a === '--game') gameDir = argv[++i] ?? '';
else if (a === '--out') outDir = argv[++i] ?? '';
else if (a === '--levels') {
const raw = argv[++i] ?? '';
levelsFilter = new Set(raw.split(',').map((s) => s.trim().toLowerCase()).filter(Boolean));
}
}
if (!gameDir || !outDir) {
throw new Error('Usage: --game <clientDir> --out <workDir> [--levels avg_berlin,avg_poland,avg_hurtgen]');
}
return { gameDir: resolve(gameDir), outDir: resolve(outDir), levelsFilter };
}
function openPack(packPath: string) {
const arc = readArchive(readFileSync(packPath));
const dicts = [...arc.files.keys()].filter((k) => k.endsWith('.dict'));
const dictionary = dicts.length ? arc.files.get(dicts[0]!) : undefined;
const names = arc.files.has(NAME_MAP_PATH) ? parseSharedNameMap(getFile(arc, NAME_MAP_PATH), dictionary).names : [];
const shared: SharedNameContext = { names, dictionary };
const lowerMap = new Map<string, string>();
for (const k of arc.files.keys()) lowerMap.set(k.toLowerCase(), k);
return {
arc,
lowerMap,
has(rel: string): boolean { return lowerMap.has(rel.toLowerCase()); },
readBlk(rel: string): BlkBlock {
const actual = lowerMap.get(rel.toLowerCase());
if (!actual) throw new Error(`missing ${rel} in ${packPath}`);
return decodeBlk(getFile(arc, actual), shared);
},
};
}
function val(b: BlkBlock | undefined, name: string): any {
const p = b ? findParam(b, name) : undefined;
return p ? (p.value as any).value : undefined;
}
function listParams(b: BlkBlock | undefined, name: string): any[] {
if (!b) return [];
return b.params.filter((p) => p.name === name).map((p) => (p.value as any).value);
}
function collectAreasRecursive(
misPack: ReturnType<typeof openPack>,
blkPath: string,
visited: Set<string>,
outAreas: BlkBlock[],
) {
const key = blkPath.toLowerCase();
if (visited.has(key) || !misPack.has(key)) return;
visited.add(key);
let blk: BlkBlock;
try { blk = misPack.readBlk(key); } catch { return; }
const areas = findBlock(blk, 'areas');
if (areas) {
for (const sub of areas.blocks) outAreas.push(sub);
}
const imports = findBlock(blk, 'imports');
if (imports) {
for (const rec of imports.blocks) {
if (rec.name !== 'import_record') continue;
const impAreas = val(rec, 'importAreas');
if (impAreas === false) continue;
const file = String(val(rec, 'file') ?? '').replace(/\\/g, '/').replace(/^\/+/, '');
if (file) collectAreasRecursive(misPack, file, visited, outAreas);
}
}
}
function areaCornersXZ(area: BlkBlock): { minX: number; maxX: number; minZ: number; maxZ: number; cx: number; cy: number; cz: number; rad: number } | null {
const tm = val(area, 'tm');
if (Array.isArray(tm) && tm.length === 12) {
const cx = Number(tm[9]);
const cy = Number(tm[10]);
const cz = Number(tm[11]);
// Box extents in Dagor area tm: half-axes are 0.5 * axis vector length for Box, full radius for Sphere/Cylinder
const typeStr = String(val(area, 'type') ?? '');
const axX = Math.abs(tm[0]) + Math.abs(tm[3]) + Math.abs(tm[6]);
const axZ = Math.abs(tm[2]) + Math.abs(tm[5]) + Math.abs(tm[8]);
const halfX = typeStr === 'Sphere' || typeStr === 'Cylinder' ? Math.hypot(tm[0], tm[1], tm[2]) : 0.5 * axX;
const halfZ = typeStr === 'Sphere' || typeStr === 'Cylinder' ? Math.hypot(tm[6], tm[7], tm[8]) : 0.5 * axZ;
const rad = Math.max(8, 0.5 * (halfX + halfZ));
return { minX: cx - halfX, maxX: cx + halfX, minZ: cz - halfZ, maxZ: cz + halfZ, cx, cy, cz, rad };
}
const obj = findBlock(area, 'props');
const pos = val(area, 'pos') ?? val(obj, 'pos');
if (Array.isArray(pos) && pos.length >= 3) {
const rad = Number(val(area, 'radius') ?? 15);
return { minX: pos[0] - rad, maxX: pos[0] + rad, minZ: pos[2] - rad, maxZ: pos[2] + rad, cx: pos[0], cy: pos[1], cz: pos[2], rad };
}
return null;
}
function dedupePois(pts: PoiPoint[], minDistM: number): PoiPoint[] {
const out: PoiPoint[] = [];
const d2 = minDistM * minDistM;
for (const p of pts) {
if (out.some((o) => (o.x - p.x) ** 2 + (o.z - p.z) ** 2 < d2)) continue;
out.push(p);
}
return out;
}
function main() {
const { gameDir, outDir, levelsFilter } = parseArgs(process.argv.slice(2));
mkdirSync(outDir, { recursive: true });
const charPack = openPack(join(gameDir, 'char.vromfs.bin'));
const misPack = openPack(join(gameDir, 'mis.vromfs.bin'));
const mislist = charPack.readBlk('config/mislist.blk');
const skirmish = findBlock(mislist, 'skirmish');
if (!skirmish) throw new Error('config/mislist.blk missing skirmish');
const pathByLowerName = new Map<string, string>();
for (const k of misPack.arc.files.keys()) {
if (!k.toLowerCase().startsWith('gamedata/missions/') || !k.toLowerCase().endsWith('.blk')) continue;
const base = k.slice(k.lastIndexOf('/') + 1, -4).toLowerCase();
pathByLowerName.set(base, k);
}
const targetCats = new Set(['air_ground_Dom', 'air_ground_Conq', 'air_ground_Bttl']);
const missionNames = new Set<string>();
for (const cat of skirmish.blocks) {
if (targetCats.has(cat.name)) {
for (const m of listParams(cat, 'm')) {
if (!String(m).toLowerCase().includes('newbie')) missionNames.add(String(m));
}
} else if (cat.name === 'test') {
for (const m of listParams(cat, 'm')) {
if (/^great_war_/i.test(String(m))) missionNames.add(String(m));
}
}
}
interface Acc {
levelPath: string;
missions: string[];
minX: number; maxX: number; minZ: number; maxZ: number;
hasBattleBox: boolean;
t1Spawns: PoiPoint[];
t2Spawns: PoiPoint[];
caps: PoiPoint[];
}
const byLevel = new Map<string, Acc>();
for (const mName of missionNames) {
const mPath = pathByLowerName.get(mName.toLowerCase());
if (!mPath) continue;
const doc = misPack.readBlk(mPath);
const ms = findBlock(doc, 'mission_settings');
const mis = findBlock(ms, 'mission');
if (val(mis, 'isTanksAllowed') === false) continue;
const levelPath = String(val(mis, 'level') ?? '');
if (!levelPath) continue;
const levelKey = levelPath.replace(/^levels\//i, '').replace(/\.bin$/i, '').toLowerCase();
if (levelsFilter && !levelsFilter.has(levelKey)) continue;
let acc = byLevel.get(levelKey);
if (!acc) {
acc = {
levelPath, missions: [],
minX: Infinity, maxX: -Infinity, minZ: Infinity, maxZ: -Infinity,
hasBattleBox: false, t1Spawns: [], t2Spawns: [], caps: [],
};
byLevel.set(levelKey, acc);
}
acc.missions.push(mName);
const areas: BlkBlock[] = [];
collectAreasRecursive(misPack, mPath, new Set<string>(), areas);
for (const a of areas) {
const n = a.name.toLowerCase();
// Ignore aircraft/heli spawns & zones
if (/air|heli|bomber|fighter|carrier|ship|boat|naval|sea/.test(n)) continue;
const box = areaCornersXZ(a);
if (!box) continue;
if (n.includes('battle_area') && !n.includes('air') && !n.includes('ship')) {
const w = box.maxX - box.minX;
const h = box.maxZ - box.minZ;
if (w >= 300 && w <= 8000 && h >= 300 && h <= 8000) {
acc.minX = Math.min(acc.minX, box.minX);
acc.maxX = Math.max(acc.maxX, box.maxX);
acc.minZ = Math.min(acc.minZ, box.minZ);
acc.maxZ = Math.max(acc.maxZ, box.maxZ);
acc.hasBattleBox = true;
}
} else if (n.includes('capture_area') || n.includes('capture_zone') || n.includes('cap_zone')) {
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')) {
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')) {
acc.t2Spawns.push({ name: a.name, x: box.cx, y: box.cy, z: box.cz, radius: box.rad, mission: mName });
}
}
}
}
for (const [levelKey, acc] of byLevel) {
const t1 = dedupePois(acc.t1Spawns, 90);
const t2 = dedupePois(acc.t2Spawns, 90);
const caps = dedupePois(acc.caps, 30);
// Ensure all spawns & caps are covered inside bounds (with 160m margin)
for (const p of [...t1, ...t2, ...caps]) {
acc.minX = Math.min(acc.minX, p.x - 160);
acc.maxX = Math.max(acc.maxX, p.x + 160);
acc.minZ = Math.min(acc.minZ, p.z - 160);
acc.maxZ = Math.max(acc.maxZ, p.z + 160);
}
// Expand battle-area union by 120m safety padding
const margin = 120;
const out: LevelPois = {
level: levelKey,
levelPath: acc.levelPath,
missions: acc.missions.sort(),
boundsMin: [Math.floor(acc.minX - margin), Math.floor(acc.minZ - margin)],
boundsMax: [Math.ceil(acc.maxX + margin), Math.ceil(acc.maxZ + margin)],
team1Spawns: t1,
team2Spawns: t2,
captureZones: caps,
};
const outPath = join(outDir, `${levelKey}.pois.json`);
writeFileSync(outPath, `${JSON.stringify(out, null, 2)}\n`, 'utf8');
console.log(`${levelKey}: missions=${out.missions.length} bounds=[${out.boundsMin[0]}..${out.boundsMax[0]}] x [${out.boundsMin[1]}..${out.boundsMax[1]}] (${out.boundsMax[0] - out.boundsMin[0]}m x ${out.boundsMax[1] - out.boundsMin[1]}m) t1Spawns=${t1.length} t2Spawns=${t2.length} caps=${caps.length}`);
}
}
main();
+252
View File
@@ -0,0 +1,252 @@
"""Render top-down PNG inspection maps (`*_nav.png` and `*_cover.png`) from `.preview.bin` + `.pois.json`.
Zero external dependencies (Python stdlib `struct` + `zlib` only).
"""
import argparse
import json
import math
import os
import struct
import zlib
def write_png(path: str, width: int, height: int, rgb: bytearray) -> None:
def chunk(tag: bytes, data: bytes) -> bytes:
crc = zlib.crc32(tag + data) & 0xFFFFFFFF
return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", crc)
raw = bytearray()
stride = width * 3
for y in range(height):
raw.append(0)
row = y * stride
raw.extend(rgb[row : row + stride])
ihdr = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)
png = b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr) + chunk(b"IDAT", zlib.compress(bytes(raw), 6)) + chunk(b"IEND", b"")
os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
with open(path, "wb") as f:
f.write(png)
def set_px(rgb: bytearray, w: int, h: int, x: int, y: int, r: int, g: int, b: int) -> None:
if 0 <= x < w and 0 <= y < h:
idx = (y * w + x) * 3
rgb[idx] = r
rgb[idx + 1] = g
rgb[idx + 2] = b
def draw_line(rgb: bytearray, w: int, h: int, x0: int, y0: int, x1: int, y1: int, col, thick: int = 1) -> None:
dx = abs(x1 - x0)
dy = abs(y1 - y0)
sx = 1 if x0 < x1 else -1
sy = 1 if y0 < y1 else -1
err = dx - dy
r, g, b = col
while True:
for oy in range(-thick // 2, thick // 2 + 1):
for ox in range(-thick // 2, thick // 2 + 1):
set_px(rgb, w, h, x0 + ox, y0 + oy, r, g, b)
if x0 == x1 and y0 == y1:
break
e2 = 2 * err
if e2 > -dy:
err -= dy
x0 += sx
if e2 < dx:
err += dx
y0 += sy
def draw_circle(rgb: bytearray, w: int, h: int, cx: int, cy: int, rad: int, col, fill: bool = False) -> None:
r, g, b = col
r2 = rad * rad
for dy in range(-rad, rad + 1):
for dx in range(-rad, rad + 1):
d2 = dx * dx + dy * dy
if fill and d2 <= r2:
set_px(rgb, w, h, cx + dx, cy + dy, r, g, b)
elif not fill and abs(d2 - r2) <= max(2, rad * 2):
set_px(rgb, w, h, cx + dx, cy + dy, r, g, b)
def draw_square(rgb: bytearray, w: int, h: int, cx: int, cy: int, half: int, col) -> None:
r, g, b = col
for dy in range(-half, half + 1):
for dx in range(-half, half + 1):
set_px(rgb, w, h, cx + dx, cy + dy, r, g, b)
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--preview", required=True)
ap.add_argument("--pois", required=True)
ap.add_argument("--out-dir", required=True)
ap.add_argument("--name", required=True)
args = ap.parse_args()
with open(args.preview, "rb") as f:
data = f.read()
with open(args.pois, "r", encoding="utf-8") as f:
pois = json.load(f)
assert data[:8] == b"WTOPREV1", "bad preview magic"
off = 8
pw, ph, min_x, min_z, max_x, max_z, water_y = struct.unpack_from("<IIfffff", data, off)
off += 28
n_px = pw * ph
heights = struct.unpack_from(f"<{n_px}f", data, off)
off += n_px * 4
flags = data[off : off + n_px]
off += n_px
cover_cnt = struct.unpack_from("<I", data, off)[0]
off += 4
covers = []
# WtoCoverPoint = 16 floats (64B? wait: pos[3]+dir[2]+ret[2]+peekL[3]+peekR[3]+halfAng+h+w = 16 floats = 64B + 4B = 68B)
cov_fmt = "<3f2f2f3f3f3f4B"
cov_sz = struct.calcsize(cov_fmt)
for _ in range(cover_cnt):
covers.append(struct.unpack_from(cov_fmt, data, off))
off += cov_sz
tac_cols, tac_rows = struct.unpack_from("<II", data, off)
off += 8
tac = data[off : off + tac_cols * tac_rows * 4]
off += tac_cols * tac_rows * 4
path_cnt = struct.unpack_from("<I", data, off)[0]
off += 4
paths = []
for _ in range(path_cnt):
npts = struct.unpack_from("<I", data, off)[0]
off += 4
pts = struct.unpack_from(f"<{npts * 3}f", data, off)
off += npts * 12
paths.append([(pts[i * 3], pts[i * 3 + 2]) for i in range(npts)])
def world_to_px(wx: float, wz: float):
px = int((wx - min_x) / max(1e-3, max_x - min_x) * (pw - 1))
py = int((max_z - wz) / max(1e-3, max_z - min_z) * (ph - 1)) # North (+Z) up
return px, py
h_min = min(heights)
h_max = max(heights)
h_span = max(1.0, h_max - h_min)
nav_rgb = bytearray(pw * ph * 3)
cov_rgb = bytearray(pw * ph * 3)
for rz in range(ph):
py = ph - 1 - rz # Flip Z so North (+Z) is top of image
row_off = rz * pw
for rx in range(pw):
h = heights[row_off + rx]
fl = flags[row_off + rx]
# Base terrain shade with 5m contour lines
t = (h - h_min) / h_span
base = int(38 + t * 52)
if abs((h % 5.0)) < 0.25:
base = max(20, base - 16)
# Nav map color:
# Dark gray = unwalkable obstacle / steep cliff
# Deep blue = deep water, Cyan-blue = shallow water
# Bright green = T2 (wide heavy) + T1 + T0 walkable
# Mid-green = T1 + T0 walkable (standard tank fits, wide heavy doesn't)
# Yellow-green = T0 only (narrow tank alley)
# Orange = chokepoint, Purple-tint = crushable/forest, Teal = bridge
r, g, b = base, base, base
if fl & 16: # deep water
r, g, b = 22, 58, 125
elif fl & 8: # shallow water
r, g, b = 55, 130, 185
elif fl & 128: # bridge
r, g, b = 70, 210, 210
elif fl & 32: # chokepoint
r, g, b = 220, 145, 45
elif fl & 64: # crushable/forest
r, g, b = int(base * 0.6 + 65), int(base * 0.8 + 85), int(base * 0.5 + 35)
elif fl & 4: # T2 wide walkable
r, g, b = int(base * 0.5 + 48), int(base * 0.7 + 125), int(base * 0.5 + 52)
elif fl & 2: # T1 standard walkable
r, g, b = int(base * 0.5 + 88), int(base * 0.7 + 115), int(base * 0.4 + 40)
elif fl & 1: # T0 narrow only
r, g, b = 185, 175, 65
else:
# Hard obstacle / cliff
r, g, b = max(18, base - 18), max(18, base - 18), max(22, base - 14)
idx = (py * pw + rx) * 3
nav_rgb[idx] = min(255, r)
nav_rgb[idx + 1] = min(255, g)
nav_rgb[idx + 2] = min(255, b)
# Cover map background: muted terrain + exposure tint
tx = min(tac_cols - 1, int(rx * tac_cols / pw))
tz = min(tac_rows - 1, int(rz * tac_rows / ph))
exp_v = tac[(tz * tac_cols + tx) * 4] if tac_cols > 0 and tac_rows > 0 else 0
if fl & 16:
cr, cg, cb = 20, 48, 95
elif fl & 2:
cr = min(255, int(base * 0.85 + exp_v * 0.18))
cg = min(255, int(base * 0.90 + 20))
cb = min(255, int(base * 0.85))
else:
cr, cg, cb = 26, 26, 30
cov_rgb[idx] = cr
cov_rgb[idx + 1] = cg
cov_rgb[idx + 2] = cb
# Overlay sample Detour paths (bright cyan) on nav map
for path in paths:
for i in range(len(path) - 1):
x0, y0 = world_to_px(*path[i])
x1, y1 = world_to_px(*path[i + 1])
draw_line(nav_rgb, pw, ph, x0, y0, x1, y1, (0, 245, 255), thick=2)
# Overlay spawns & capture zones on BOTH maps
for rgb in (nav_rgb, cov_rgb):
for sp in pois.get("team1Spawns", []):
x, y = world_to_px(sp["x"], sp["z"])
draw_square(rgb, pw, ph, x, y, 5, (40, 130, 255))
draw_square(rgb, pw, ph, x, y, 2, (255, 255, 255))
for sp in pois.get("team2Spawns", []):
x, y = world_to_px(sp["x"], sp["z"])
draw_square(rgb, pw, ph, x, y, 5, (255, 65, 65))
draw_square(rgb, pw, ph, x, y, 2, (255, 255, 255))
for cap in pois.get("captureZones", []):
x, y = world_to_px(cap["x"], cap["z"])
rad_px = max(8, int(cap.get("radius", 25.0) / max(1.0, max_x - min_x) * pw))
draw_circle(rgb, pw, ph, x, y, rad_px, (255, 215, 0), fill=False)
draw_circle(rgb, pw, ph, x, y, 4, (255, 230, 40), fill=True)
# Overlay covers on cover map: Blue=FULL, Green=HULLDOWN, Yellow=PEEK
for c in covers:
px_w, py_w, pz_w = c[0], c[1], c[2]
dx, dz = c[3], c[4]
peek_l = (c[7], c[9])
peek_r = (c[10], c[12])
kind = c[16]
has_pl, has_pr = c[17], c[18]
x, y = world_to_px(px_w, pz_w)
col = (60, 165, 255) if kind == 1 else (55, 240, 100)
draw_circle(cov_rgb, pw, ph, x, y, 2, col, fill=True)
# Direction tick pointing toward blocked threat
x2, y2 = world_to_px(px_w + dx * 8.0, pz_w + dz * 8.0)
draw_line(cov_rgb, pw, ph, x, y, x2, y2, col, thick=1)
if has_pl:
lx, ly = world_to_px(*peek_l)
draw_circle(cov_rgb, pw, ph, lx, ly, 1, (255, 240, 60), fill=True)
if has_pr:
rx2, ry2 = world_to_px(*peek_r)
draw_circle(cov_rgb, pw, ph, rx2, ry2, 1, (255, 240, 60), fill=True)
nav_out = os.path.join(args.out_dir, f"{args.name}_nav.png")
cov_out = os.path.join(args.out_dir, f"{args.name}_cover.png")
write_png(nav_out, pw, ph, nav_rgb)
write_png(cov_out, pw, ph, cov_rgb)
print(f"Rendered {nav_out} and {cov_out} (covers={len(covers)}, paths={len(paths)})")
if __name__ == "__main__":
main()