Files
WT-Offline/tools/navgen/bake/bake.cpp
T
N0VAN0M4LY 842ee23fa4 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).
2026-12-04 11:33:32 +08:00

1260 lines
55 KiB
C++

/*
* Offline Recast + Detour + Voxel Cover baker for WTOffline ground AI.
*
* Reads:
* - `<level>.wtogeo` (Dagor world heightmap + classified collision triangles)
* - `<level>.pois.json` (union battle area, team spawns, capture zones)
* Produces:
* - `<level>.wtonav` (3-tier tiled Detour meshes + baked tank covers + 8m tactical grid)
* - `<level>.preview.bin` (compact raster + covers + sample Detour paths for PNG inspection)
*/
#include "wto_nav_format.h"
#include "Recast.h"
#include "DetourNavMesh.h"
#include "DetourNavMeshBuilder.h"
#include "DetourNavMeshQuery.h"
#include "DetourCommon.h"
#include <algorithm>
#include <atomic>
#include <chrono>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <mutex>
#include <queue>
#include <string>
#include <thread>
#include <unordered_set>
#include <vector>
static constexpr float kPi = 3.14159265358979323846f;
static constexpr float kDegToRad = kPi / 180.0f;
struct Vec3 { float x, y, z; };
struct ObsTri {
uint32_t i0, i1, i2;
uint8_t cls;
};
struct PoiPt {
std::string name;
float x, y, z, radius;
};
struct PoisData {
std::vector<PoiPt> t1Spawns;
std::vector<PoiPt> t2Spawns;
std::vector<PoiPt> caps;
};
struct TierSpec {
const char *name;
float agentRadius;
float agentHeight;
float maxSlopeDeg;
float maxClimb;
};
static const TierSpec kTiers[WTO_NAV_TIER_COUNT] = {
{ "T0_narrow", 1.65f, 2.6f, 30.0f, 0.65f },
{ "T1_standard", 2.05f, 2.6f, 28.0f, 0.65f },
{ "T2_wide", 2.45f, 2.6f, 22.0f, 0.55f },
};
static constexpr float kCellSize = 0.50f;
static constexpr float kCellHeight = 0.25f;
static constexpr int kTileSize = 256; /* 128.0 m per tile */
static constexpr float kTileWorldSize = kTileSize * kCellSize;
static constexpr float kShallowWaterMaxM = 0.60f;
static constexpr float kShallowWaterMinM = 0.05f;
static constexpr float kRoughSlopeDeg = 18.0f;
struct GeoData {
WtoGeoHeader hdr{};
std::vector<float> heights;
std::vector<Vec3> obsVerts;
std::vector<ObsTri> obsTris;
float minY = 1e9f;
float maxY = -1e9f;
float sampleHeight(float wx, float wz) const {
float fx = (wx - hdr.hmOrigin[0]) / hdr.hmCellSize;
float fz = (wz - hdr.hmOrigin[1]) / hdr.hmCellSize;
int x0 = std::clamp((int)std::floor(fx), 0, (int)hdr.hmWidth - 2);
int z0 = std::clamp((int)std::floor(fz), 0, (int)hdr.hmHeight - 2);
float tx = std::clamp(fx - x0, 0.0f, 1.0f);
float tz = std::clamp(fz - z0, 0.0f, 1.0f);
float h00 = heights[(size_t)z0 * hdr.hmWidth + x0];
float h10 = heights[(size_t)z0 * hdr.hmWidth + x0 + 1];
float h01 = heights[(size_t)(z0 + 1) * hdr.hmWidth + x0];
float h11 = heights[(size_t)(z0 + 1) * hdr.hmWidth + x0 + 1];
float h0 = h00 + (h10 - h00) * tx;
float h1 = h01 + (h11 - h01) * tx;
return h0 + (h1 - h0) * tz;
}
};
static bool loadGeo(const std::string &path, GeoData &out) {
std::ifstream in(path, std::ios::binary);
if (!in) return false;
in.read(reinterpret_cast<char *>(&out.hdr), sizeof(WtoGeoHeader));
if (!in || std::memcmp(out.hdr.magic, WTO_GEO_MAGIC, 8) != 0 || out.hdr.version != WTO_GEO_VERSION) {
std::fprintf(stderr, "Invalid .wtogeo header: %s\n", path.c_str());
return false;
}
size_t hmCount = (size_t)out.hdr.hmWidth * out.hdr.hmHeight;
out.heights.resize(hmCount);
in.read(reinterpret_cast<char *>(out.heights.data()), hmCount * sizeof(float));
out.obsVerts.resize(out.hdr.obsVertCount);
in.read(reinterpret_cast<char *>(out.obsVerts.data()), out.hdr.obsVertCount * sizeof(Vec3));
out.obsTris.resize(out.hdr.obsTriCount);
for (uint32_t i = 0; i < out.hdr.obsTriCount; ++i) {
uint32_t idx[3];
uint8_t cls = 0;
in.read(reinterpret_cast<char *>(idx), sizeof(idx));
in.read(reinterpret_cast<char *>(&cls), 1);
out.obsTris[i] = { idx[0], idx[1], idx[2], cls };
}
if (!in) return false;
for (float h : out.heights) {
if (h < out.minY) out.minY = h;
if (h > out.maxY) out.maxY = h;
}
for (const auto &v : out.obsVerts) {
if (std::isfinite(v.y)) {
if (v.y < out.minY) out.minY = v.y;
if (v.y > out.maxY) out.maxY = v.y;
}
}
if (out.hdr.waterLevel > -1e5f) {
out.minY = std::min(out.minY, out.hdr.waterLevel - 2.0f);
out.maxY = std::max(out.maxY, out.hdr.waterLevel + 2.0f);
}
out.minY -= 2.0f;
out.maxY += 6.0f;
return true;
}
/* Minimal JSON array extractor for `.pois.json` (team1Spawns / team2Spawns / captureZones). */
static void parsePoiArray(const std::string &json, const std::string &key, std::vector<PoiPt> &out) {
std::string needle = "\"" + key + "\"";
size_t pos = json.find(needle);
if (pos == std::string::npos) return;
size_t lb = json.find('[', pos);
if (lb == std::string::npos) return;
int depth = 0;
size_t i = lb;
for (; i < json.size(); ++i) {
if (json[i] == '[') depth++;
else if (json[i] == ']') { depth--; if (depth == 0) break; }
}
std::string slice = json.substr(lb, i - lb + 1);
auto readNum = [](const std::string &obj, const char *field, float def) -> float {
std::string fn = std::string("\"") + field + "\"";
size_t p = obj.find(fn);
if (p == std::string::npos) return def;
p = obj.find(':', p);
if (p == std::string::npos) return def;
return std::strtof(obj.c_str() + p + 1, nullptr);
};
auto readStr = [](const std::string &obj, const char *field) -> std::string {
std::string fn = std::string("\"") + field + "\"";
size_t p = obj.find(fn);
if (p == std::string::npos) return "";
p = obj.find(':', p);
size_t q1 = obj.find('"', p);
size_t q2 = (q1 != std::string::npos) ? obj.find('"', q1 + 1) : std::string::npos;
return (q1 != std::string::npos && q2 != std::string::npos) ? obj.substr(q1 + 1, q2 - q1 - 1) : "";
};
size_t cur = 0;
while (true) {
size_t ob = slice.find('{', cur);
if (ob == std::string::npos) break;
size_t cb = slice.find('}', ob);
if (cb == std::string::npos) break;
std::string obj = slice.substr(ob, cb - ob + 1);
PoiPt pt;
pt.name = readStr(obj, "name");
pt.x = readNum(obj, "x", 0.0f);
pt.y = readNum(obj, "y", 0.0f);
pt.z = readNum(obj, "z", 0.0f);
pt.radius = readNum(obj, "radius", 15.0f);
out.push_back(pt);
cur = cb + 1;
}
}
static bool loadPois(const std::string &path, PoisData &out) {
std::ifstream in(path);
if (!in) return false;
std::string content((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
parsePoiArray(content, "team1Spawns", out.t1Spawns);
parsePoiArray(content, "team2Spawns", out.t2Spawns);
parsePoiArray(content, "captureZones", out.caps);
return true;
}
static inline float triNormalYRightHanded(const Vec3 &a, const Vec3 &b, const Vec3 &c) {
float e1x = b.x - a.x, e1y = b.y - a.y, e1z = b.z - a.z;
float e2x = c.x - a.x, e2y = c.y - a.y, e2z = c.z - a.z;
float nx = e1y * e2z - e1z * e2y;
float ny = e1z * e2x - e1x * e2z;
float nz = e1x * e2y - e1y * e2x;
float len = std::sqrt(nx * nx + ny * ny + nz * nz);
return len > 1e-6f ? (ny / len) : 0.0f;
}
/* Query whether a hard solid span exists in rcHeightfield at (wx, wz) intersecting [yLo, yHi]. */
static bool hfHasSolidInBand(const rcHeightfield &hf, float wx, float wz, float yLo, float yHi, float *outTopY = nullptr) {
int gx = (int)std::floor((wx - hf.bmin[0]) / hf.cs);
int gz = (int)std::floor((wz - hf.bmin[2]) / hf.cs);
if (gx < 0 || gz < 0 || gx >= hf.width || gz >= hf.height) return false;
int sminBand = (int)std::floor((yLo - hf.bmin[1]) / hf.ch);
int smaxBand = (int)std::ceil((yHi - hf.bmin[1]) / hf.ch);
float maxTop = -1e9f;
bool hit = false;
for (const rcSpan *s = hf.spans[gx + gz * hf.width]; s; s = s->next) {
if ((int)s->smax >= sminBand && (int)s->smin <= smaxBand) {
hit = true;
float topY = hf.bmin[1] + s->smax * hf.ch;
if (topY > maxTop) maxTop = topY;
}
}
if (hit && outTopY) *outTopY = maxTop;
return hit;
}
/* Raycast along XZ inside tile's hard-obstacle heightfield to check occlusion in [yLo, yHi]. */
static bool hfTraceBand(const rcHeightfield &hardHf, const GeoData &geo,
float ox, float oz, float dx, float dz,
float maxDist, float yLo, float yHi, float *outTopY = nullptr) {
float step = hardHf.cs * 0.85f;
for (float d = 0.6f; d <= maxDist; d += step) {
float px = ox + dx * d;
float pz = oz + dz * d;
float topY = -1e9f;
if (hfHasSolidInBand(hardHf, px, pz, yLo, yHi, &topY)) {
if (outTopY) *outTopY = topY;
return true;
}
/* Terrain ridge / cliff rise above yLo also acts as natural hard earth cover! */
float gy = geo.sampleHeight(px, pz);
if (gy >= yLo + 0.35f) {
if (outTopY) *outTopY = gy;
return true;
}
}
return false;
}
struct BuiltTile {
int tx = 0;
int tz = 0;
unsigned char *data = nullptr;
int dataSize = 0;
};
struct TileBakeResult {
BuiltTile tile;
std::vector<WtoCoverPoint> covers;
};
static TileBakeResult buildSingleTile(
const GeoData &geo,
const std::vector<uint32_t> &triBucket,
const TierSpec &tier,
int tx, int tz,
float mapMinX, float mapMinZ,
bool bakeCovers
) {
TileBakeResult res;
res.tile.tx = tx;
res.tile.tz = tz;
rcContext ctx(false);
rcConfig cfg{};
cfg.cs = kCellSize;
cfg.ch = kCellHeight;
cfg.walkableSlopeAngle = tier.maxSlopeDeg;
cfg.walkableHeight = (int)std::ceil(tier.agentHeight / cfg.ch);
cfg.walkableClimb = (int)std::floor(tier.maxClimb / cfg.ch);
cfg.walkableRadius = (int)std::ceil(tier.agentRadius / cfg.cs);
cfg.maxEdgeLen = (int)(24.0f / cfg.cs);
cfg.maxSimplificationError = 1.8f;
cfg.minRegionArea = 32; /* ~8.0 m^2 (smaller than 1 tank footprint) */
cfg.mergeRegionArea = 400;
cfg.maxVertsPerPoly = 6;
cfg.tileSize = kTileSize;
cfg.borderSize = cfg.walkableRadius + 3;
cfg.width = cfg.tileSize + cfg.borderSize * 2;
cfg.height = cfg.tileSize + cfg.borderSize * 2;
cfg.detailSampleDist = 12.0f * cfg.cs;
cfg.detailSampleMaxError = 2.0f * cfg.ch;
float borderWorld = cfg.borderSize * cfg.cs;
cfg.bmin[0] = mapMinX + tx * kTileWorldSize - borderWorld;
cfg.bmin[1] = geo.minY;
cfg.bmin[2] = mapMinZ + tz * kTileWorldSize - borderWorld;
cfg.bmax[0] = mapMinX + (tx + 1) * kTileWorldSize + borderWorld;
cfg.bmax[1] = geo.maxY;
cfg.bmax[2] = mapMinZ + (tz + 1) * kTileWorldSize + borderWorld;
rcHeightfield *solid = rcAllocHeightfield();
if (!solid || !rcCreateHeightfield(&ctx, *solid, cfg.width, cfg.height, cfg.bmin, cfg.bmax, cfg.cs, cfg.ch)) {
rcFreeHeightField(solid);
return res;
}
rcHeightfield *hardHf = nullptr;
if (bakeCovers) {
hardHf = rcAllocHeightfield();
if (!hardHf || !rcCreateHeightfield(&ctx, *hardHf, cfg.width, cfg.height, cfg.bmin, cfg.bmax, cfg.cs, cfg.ch)) {
rcFreeHeightField(hardHf);
hardHf = nullptr;
}
}
/* 1. Rasterize overlapping heightmap cells directly (zero global terrain tri copy) */
const float hmCs = geo.hdr.hmCellSize;
const float cosMaxSlope = std::cos(tier.maxSlopeDeg * kDegToRad);
const float cosRoughSlope = std::cos(kRoughSlopeDeg * kDegToRad);
const float waterY = geo.hdr.waterLevel;
const bool hasWater = waterY > -1e5f;
int hx0 = std::clamp((int)std::floor((cfg.bmin[0] - geo.hdr.hmOrigin[0]) / hmCs) - 1, 0, (int)geo.hdr.hmWidth - 2);
int hz0 = std::clamp((int)std::floor((cfg.bmin[2] - geo.hdr.hmOrigin[1]) / hmCs) - 1, 0, (int)geo.hdr.hmHeight - 2);
int hx1 = std::clamp((int)std::ceil((cfg.bmax[0] - geo.hdr.hmOrigin[0]) / hmCs) + 1, hx0 + 1, (int)geo.hdr.hmWidth - 1);
int hz1 = std::clamp((int)std::ceil((cfg.bmax[2] - geo.hdr.hmOrigin[1]) / hmCs) + 1, hz0 + 1, (int)geo.hdr.hmHeight - 1);
auto classifyTerrainTri = [&](const Vec3 &a, const Vec3 &b, const Vec3 &c) -> unsigned char {
float ny = triNormalYRightHanded(a, b, c);
if (ny < cosMaxSlope) return RC_NULL_AREA;
float cy = (a.y + b.y + c.y) * (1.0f / 3.0f);
if (hasWater) {
float depth = waterY - cy;
if (depth > kShallowWaterMaxM) return WTO_AREA_DEEP_WATER;
if (depth > kShallowWaterMinM) return WTO_AREA_SHALLOW_WATER;
}
if (ny < cosRoughSlope) return WTO_AREA_ROUGH;
return WTO_AREA_GROUND;
};
for (int gz = hz0; gz < hz1; ++gz) {
float z0 = geo.hdr.hmOrigin[1] + gz * hmCs;
float z1 = z0 + hmCs;
const float *row0 = &geo.heights[(size_t)gz * geo.hdr.hmWidth];
const float *row1 = &geo.heights[(size_t)(gz + 1) * geo.hdr.hmWidth];
for (int gx = hx0; gx < hx1; ++gx) {
float x0 = geo.hdr.hmOrigin[0] + gx * hmCs;
float x1 = x0 + hmCs;
Vec3 v00{ x0, row0[gx], z0 };
Vec3 v10{ x1, row0[gx + 1], z0 };
Vec3 v01{ x0, row1[gx], z1 };
Vec3 v11{ x1, row1[gx + 1], z1 };
/* CCW when viewed from +Y -> right-handed +Y normal */
unsigned char a1 = classifyTerrainTri(v00, v01, v10);
unsigned char a2 = classifyTerrainTri(v10, v01, v11);
rcRasterizeTriangle(&ctx, &v00.x, &v01.x, &v10.x, a1, *solid, cfg.walkableClimb);
rcRasterizeTriangle(&ctx, &v10.x, &v01.x, &v11.x, a2, *solid, cfg.walkableClimb);
}
}
/* 2. Rasterize obstacle triangles from this tile's spatial bucket */
struct SoftMark { float minX, minY, minZ, maxX, maxY, maxZ; uint8_t area; };
std::vector<SoftMark> softMarks;
for (uint32_t ti : triBucket) {
const ObsTri &t = geo.obsTris[ti];
const Vec3 &v0 = geo.obsVerts[t.i0];
const Vec3 &v1 = geo.obsVerts[t.i1];
const Vec3 &v2 = geo.obsVerts[t.i2];
if (t.cls == WTO_OBS_HARD_SOLID || t.cls == WTO_OBS_TREE_THICK) {
rcRasterizeTriangle(&ctx, &v0.x, &v1.x, &v2.x, RC_NULL_AREA, *solid, cfg.walkableClimb);
if (hardHf && t.cls == WTO_OBS_HARD_SOLID) {
rcRasterizeTriangle(&ctx, &v0.x, &v1.x, &v2.x, 1, *hardHf, 1);
}
} else if (t.cls == WTO_OBS_BRIDGE_DECK) {
float ny = triNormalYRightHanded(v0, v1, v2);
if (std::fabs(ny) >= cosMaxSlope) {
if (ny >= 0.0f) rcRasterizeTriangle(&ctx, &v0.x, &v1.x, &v2.x, WTO_AREA_BRIDGE, *solid, cfg.walkableClimb);
else rcRasterizeTriangle(&ctx, &v0.x, &v2.x, &v1.x, WTO_AREA_BRIDGE, *solid, cfg.walkableClimb);
} else {
rcRasterizeTriangle(&ctx, &v0.x, &v1.x, &v2.x, RC_NULL_AREA, *solid, cfg.walkableClimb);
}
} else if (t.cls == WTO_OBS_CRUSHABLE || t.cls == WTO_OBS_TREE_THIN) {
SoftMark sm;
sm.minX = std::min({ v0.x, v1.x, v2.x });
sm.maxX = std::max({ v0.x, v1.x, v2.x });
sm.minY = std::min({ v0.y, v1.y, v2.y });
sm.maxY = std::max({ v0.y, v1.y, v2.y });
sm.minZ = std::min({ v0.z, v1.z, v2.z });
sm.maxZ = std::max({ v0.z, v1.z, v2.z });
sm.area = (t.cls == WTO_OBS_CRUSHABLE) ? WTO_AREA_CRUSHABLE : WTO_AREA_FOREST;
softMarks.push_back(sm);
}
}
rcFilterLowHangingWalkableObstacles(&ctx, cfg.walkableClimb, *solid);
rcFilterLedgeSpans(&ctx, cfg.walkableHeight, cfg.walkableClimb, *solid);
rcFilterWalkableLowHeightSpans(&ctx, cfg.walkableHeight, *solid);
rcCompactHeightfield *chf = rcAllocCompactHeightfield();
if (!chf || !rcBuildCompactHeightfield(&ctx, cfg.walkableHeight, cfg.walkableClimb, *solid, *chf)) {
rcFreeHeightField(solid);
rcFreeHeightField(hardHf);
rcFreeCompactHeightfield(chf);
return res;
}
rcFreeHeightField(solid);
solid = nullptr;
/* Erode walkable area by tank radius (guaranteed full hull clearance from hard obstacles!) */
if (!rcErodeWalkableArea(&ctx, cfg.walkableRadius, *chf)) {
rcFreeHeightField(hardHf);
rcFreeCompactHeightfield(chf);
return res;
}
/* Tag crushable fences & thin forest areas directly onto overlapping walkable cells (O(N), fast!) */
for (const auto &sm : softMarks) {
int gx0 = std::clamp((int)std::floor((sm.minX - 0.4f - cfg.bmin[0]) / cfg.cs), 0, chf->width - 1);
int gx1 = std::clamp((int)std::floor((sm.maxX + 0.4f - cfg.bmin[0]) / cfg.cs), 0, chf->width - 1);
int gz0 = std::clamp((int)std::floor((sm.minZ - 0.4f - cfg.bmin[2]) / cfg.cs), 0, chf->height - 1);
int gz1 = std::clamp((int)std::floor((sm.maxZ + 0.4f - cfg.bmin[2]) / cfg.cs), 0, chf->height - 1);
for (int gz = gz0; gz <= gz1; ++gz) {
for (int gx = gx0; gx <= gx1; ++gx) {
const rcCompactCell &c = chf->cells[gx + gz * chf->width];
for (int si = (int)c.index, ni = (int)(c.index + c.count); si < ni; ++si) {
if (chf->areas[si] == WTO_AREA_GROUND || chf->areas[si] == WTO_AREA_ROUGH) {
float sy = cfg.bmin[1] + chf->spans[si].y * cfg.ch;
if (sy >= sm.minY - 1.5f && sy <= sm.maxY + 0.5f) {
chf->areas[si] = sm.area;
}
}
}
}
}
}
/* 3. Bake tank-qualified covers directly from eroded Tier-1 walkable boundary + hardHf */
if (bakeCovers && hardHf) {
const int b = cfg.borderSize;
const int innerEnd = b + cfg.tileSize;
static const float kDirs[8][2] = {
{ 1.0f, 0.0f }, { 0.7071f, 0.7071f }, { 0.0f, 1.0f }, { -0.7071f, 0.7071f },
{ -1.0f, 0.0f }, { -0.7071f, -0.7071f }, { 0.0f, -1.0f }, { 0.7071f, -0.7071f }
};
for (int z = b; z < innerEnd; z += 4) {
for (int x = b; x < innerEnd; x += 4) {
const rcCompactCell &c = chf->cells[x + z * chf->width];
for (int si = (int)c.index, ni = (int)(c.index + c.count); si < ni; ++si) {
unsigned char area = chf->areas[si];
if (area == RC_NULL_AREA || area == WTO_AREA_DEEP_WATER || area == WTO_AREA_SHALLOW_WATER) continue;
/* Check if any 4-neighbor (at distance 1..2 cells) was eroded to RC_NULL_AREA or disconnected */
const rcCompactSpan &s = chf->spans[si];
bool isBoundary = false;
for (int d = 0; d < 4; ++d) {
int con = rcGetCon(s, d);
if (con == RC_NOT_CONNECTED) { isBoundary = true; break; }
int nx = x + rcGetDirOffsetX(d);
int nz = z + rcGetDirOffsetY(d);
int nsi = (int)chf->cells[nx + nz * chf->width].index + con;
if (chf->areas[nsi] == RC_NULL_AREA) { isBoundary = true; break; }
}
if (!isBoundary) continue;
float wx = cfg.bmin[0] + (x + 0.5f) * cfg.cs;
float wy = cfg.bmin[1] + s.y * cfg.ch;
float wz = cfg.bmin[2] + (z + 0.5f) * cfg.cs;
/* Find strongest hard-obstacle direction within 2.0..5.2 m */
int bestDir = -1;
float bestWidth = 0.0f;
float bestHeight = 0.0f;
bool bestTurretBlocked = false;
for (int di = 0; di < 8; ++di) {
float dx = kDirs[di][0], dz = kDirs[di][1];
float px = -dz, pz = dx; /* tangent */
int hullHits = 0;
int turretHits = 0;
float hSum = 0.0f;
/* 5 lateral samples across 3.6 m hull width (-1.8, -0.9, 0, +0.9, +1.8) */
for (int li = -2; li <= 2; ++li) {
float off = li * 0.9f;
float sx = wx + px * off;
float sz = wz + pz * off;
float topY = wy;
if (hfTraceBand(*hardHf, geo, sx, sz, dx, dz, 5.2f, wy + 0.65f, wy + 1.80f, &topY)) {
hullHits++;
hSum += std::max(0.0f, topY - wy);
if (hfTraceBand(*hardHf, geo, sx, sz, dx, dz, 5.2f, wy + 2.05f, wy + 2.85f)) {
turretHits++;
}
}
}
if (hullHits < 4) continue; /* Require >= 80% hull width blocked (eliminates thin posts & narrow rocks) */
float avgH = hSum / (float)hullHits;
if (avgH < 1.55f) continue; /* Eliminate low rocks (< 1.55 m) */
/* Check extra lateral span for continuous obstacle width */
float wMeters = 3.6f;
if (hfTraceBand(*hardHf, geo, wx + px * 2.6f, wz + pz * 2.6f, dx, dz, 5.2f, wy + 0.65f, wy + 1.80f)) wMeters += 1.0f;
if (hfTraceBand(*hardHf, geo, wx - px * 2.6f, wz - pz * 2.6f, dx, dz, 5.2f, wy + 0.65f, wy + 1.80f)) wMeters += 1.0f;
if (wMeters > bestWidth || (wMeters == bestWidth && avgH > bestHeight)) {
bestDir = di;
bestWidth = wMeters;
bestHeight = avgH;
bestTurretBlocked = (turretHits >= 3);
}
}
if (bestDir < 0) continue;
float dx = kDirs[bestDir][0], dz = kDirs[bestDir][1];
float px = -dz, pz = dx;
WtoCoverPoint cp{};
cp.pos[0] = wx; cp.pos[1] = wy; cp.pos[2] = wz;
cp.coverDir[0] = dx; cp.coverDir[1] = dz;
cp.retreatDir[0] = -dx; cp.retreatDir[1] = -dz;
cp.halfAngleDeg = bestWidth >= 5.0f ? 42.0f : 32.0f;
cp.heightM = bestHeight;
cp.widthM = bestWidth;
if (bestTurretBlocked) {
cp.kind = WTO_COVER_FULL;
/* Probe corner peek left/right at 4.2 m */
for (int side = -1; side <= 1; side += 2) {
float kx = wx + px * (side * 4.2f);
float kz = wz + pz * (side * 4.2f);
int kgx = (int)std::floor((kx - cfg.bmin[0]) / cfg.cs);
int kgz = (int)std::floor((kz - cfg.bmin[2]) / cfg.cs);
if (kgx >= 0 && kgz >= 0 && kgx < chf->width && kgz < chf->height) {
const rcCompactCell &kc = chf->cells[kgx + kgz * chf->width];
bool walkablePeek = false;
float ky = wy;
for (int ksi = (int)kc.index, kni = (int)(kc.index + kc.count); ksi < kni; ++ksi) {
if (chf->areas[ksi] != RC_NULL_AREA && chf->areas[ksi] != WTO_AREA_DEEP_WATER) {
float sy = cfg.bmin[1] + chf->spans[ksi].y * cfg.ch;
if (std::fabs(sy - wy) <= 1.2f) { walkablePeek = true; ky = sy; break; }
}
}
if (walkablePeek && !hfTraceBand(*hardHf, geo, kx, kz, dx, dz, 14.0f, ky + 1.8f, ky + 2.6f)) {
if (side < 0) {
cp.hasPeekLeft = 1;
cp.peekLeft[0] = kx; cp.peekLeft[1] = ky; cp.peekLeft[2] = kz;
} else {
cp.hasPeekRight = 1;
cp.peekRight[0] = kx; cp.peekRight[1] = ky; cp.peekRight[2] = kz;
}
}
}
}
res.covers.push_back(cp);
} else {
/* Hull-down candidate: verify forward 22 m clear at turret height */
if (!hfTraceBand(*hardHf, geo, wx, wz, dx, dz, 22.0f, wy + 2.15f, wy + 2.75f)) {
cp.kind = WTO_COVER_HULLDOWN;
res.covers.push_back(cp);
}
}
}
}
}
}
rcFreeHeightField(hardHf);
hardHf = nullptr;
/* Smooth isolated single-voxel slope/area noise slivers before region building */
rcMedianFilterWalkableArea(&ctx, *chf);
rcMedianFilterWalkableArea(&ctx, *chf);
if (!rcBuildDistanceField(&ctx, *chf) ||
!rcBuildRegions(&ctx, *chf, cfg.borderSize, cfg.minRegionArea, cfg.mergeRegionArea)) {
rcFreeCompactHeightfield(chf);
return res;
}
rcContourSet *cset = rcAllocContourSet();
if (!cset || !rcBuildContours(&ctx, *chf, cfg.maxSimplificationError, cfg.maxEdgeLen, *cset)) {
rcFreeCompactHeightfield(chf);
rcFreeContourSet(cset);
return res;
}
rcPolyMesh *pmesh = rcAllocPolyMesh();
if (!pmesh || !rcBuildPolyMesh(&ctx, *cset, cfg.maxVertsPerPoly, *pmesh)) {
rcFreeCompactHeightfield(chf);
rcFreeContourSet(cset);
rcFreePolyMesh(pmesh);
return res;
}
rcPolyMeshDetail *dmesh = rcAllocPolyMeshDetail();
if (!dmesh || !rcBuildPolyMeshDetail(&ctx, *pmesh, *chf, cfg.detailSampleDist, cfg.detailSampleMaxError, *dmesh)) {
rcFreeCompactHeightfield(chf);
rcFreeContourSet(cset);
rcFreePolyMesh(pmesh);
rcFreePolyMeshDetail(dmesh);
return res;
}
rcFreeCompactHeightfield(chf);
rcFreeContourSet(cset);
if (pmesh->npolys == 0) {
rcFreePolyMesh(pmesh);
rcFreePolyMeshDetail(dmesh);
return res;
}
/* Assign initial polygon flags from Area ID */
for (int i = 0; i < pmesh->npolys; ++i) {
unsigned char a = pmesh->areas[i];
if (a == WTO_AREA_DEEP_WATER) pmesh->flags[i] = WTO_FLAG_DEEP_WATER;
else if (a == WTO_AREA_SHALLOW_WATER) pmesh->flags[i] = WTO_FLAG_WALK | WTO_FLAG_SHALLOW_WATER;
else if (a == WTO_AREA_NO_GO) pmesh->flags[i] = WTO_FLAG_BLOCKED;
else if (a != RC_NULL_AREA) pmesh->flags[i] = WTO_FLAG_WALK;
else pmesh->flags[i] = 0;
}
dtNavMeshCreateParams params{};
params.verts = pmesh->verts;
params.vertCount = pmesh->nverts;
params.polys = pmesh->polys;
params.polyAreas = pmesh->areas;
params.polyFlags = pmesh->flags;
params.polyCount = pmesh->npolys;
params.nvp = pmesh->nvp;
params.detailMeshes = dmesh->meshes;
params.detailVerts = dmesh->verts;
params.detailVertsCount = dmesh->nverts;
params.detailTris = dmesh->tris;
params.detailTriCount = dmesh->ntris;
params.walkableHeight = tier.agentHeight;
params.walkableRadius = tier.agentRadius;
params.walkableClimb = tier.maxClimb;
params.tileX = tx;
params.tileY = tz;
params.tileLayer = 0;
rcVcopy(params.bmin, pmesh->bmin);
rcVcopy(params.bmax, pmesh->bmax);
params.cs = cfg.cs;
params.ch = cfg.ch;
params.buildBvTree = true;
unsigned char *navData = nullptr;
int navDataSize = 0;
if (dtCreateNavMeshData(&params, &navData, &navDataSize)) {
res.tile.data = navData;
res.tile.dataSize = navDataSize;
}
rcFreePolyMesh(pmesh);
rcFreePolyMeshDetail(dmesh);
return res;
}
static dtNavMesh *assembleNavMesh(const dtNavMeshParams &nmParams, const std::vector<BuiltTile> &tiles) {
dtNavMesh *mesh = dtAllocNavMesh();
if (!mesh || dtStatusFailed(mesh->init(&nmParams))) {
dtFreeNavMesh(mesh);
return nullptr;
}
for (const auto &t : tiles) {
if (!t.data || t.dataSize <= 0) continue;
unsigned char *copy = (unsigned char *)dtAlloc(t.dataSize, DT_ALLOC_PERM);
std::memcpy(copy, t.data, t.dataSize);
if (dtStatusFailed(mesh->addTile(copy, t.dataSize, DT_TILE_FREE_DATA, 0, nullptr))) {
dtFree(copy);
}
}
return mesh;
}
/* Flood-fill walkable polygons from all mission spawns and block disconnected interior islands
* (hollow building interiors, flat roofs, sealed courtyards) so queries never snap inside them. */
static int pruneUnreachableIslands(dtNavMesh *mesh, dtNavMeshQuery *query, const GeoData &geo, const PoisData &pois) {
dtQueryFilter wf;
wf.setIncludeFlags(WTO_FLAG_WALK);
wf.setExcludeFlags(WTO_FLAG_DEEP_WATER | WTO_FLAG_BLOCKED);
const float ext[3] = { 16.0f, 16.0f, 16.0f };
std::unordered_set<dtPolyRef> visited;
std::queue<dtPolyRef> q;
auto seed = [&](const PoiPt &pt) {
float p[3] = { pt.x, geo.sampleHeight(pt.x, pt.z), pt.z };
dtPolyRef ref = 0; float npt[3];
if (dtStatusSucceed(query->findNearestPoly(p, ext, &wf, &ref, npt)) && ref) {
if (visited.insert(ref).second) q.push(ref);
}
};
for (const auto &s : pois.t1Spawns) seed(s);
for (const auto &s : pois.t2Spawns) seed(s);
if (visited.empty()) return 0;
const dtNavMesh *cm = mesh;
while (!q.empty()) {
dtPolyRef cur = q.front();
q.pop();
const dtMeshTile *tile = nullptr;
const dtPoly *poly = nullptr;
if (dtStatusFailed(cm->getTileAndPolyByRef(cur, &tile, &poly))) continue;
for (unsigned int li = poly->firstLink; li != DT_NULL_LINK; li = tile->links[li].next) {
dtPolyRef nref = tile->links[li].ref;
if (!nref) continue;
const dtMeshTile *nt = nullptr;
const dtPoly *np = nullptr;
if (dtStatusFailed(cm->getTileAndPolyByRef(nref, &nt, &np))) continue;
if ((np->flags & WTO_FLAG_WALK) == 0 || (np->flags & (WTO_FLAG_DEEP_WATER | WTO_FLAG_BLOCKED)) != 0) continue;
if (visited.insert(nref).second) q.push(nref);
}
}
int pruned = 0;
for (int i = 0; i < cm->getMaxTiles(); ++i) {
const dtMeshTile *tile = cm->getTile(i);
if (!tile || !tile->header) continue;
dtPolyRef base = cm->getPolyRefBase(tile);
for (int p = 0; p < tile->header->polyCount; ++p) {
const dtPoly &poly = tile->polys[p];
if ((poly.flags & WTO_FLAG_WALK) == 0 || (poly.flags & WTO_FLAG_DEEP_WATER) != 0) continue;
dtPolyRef ref = base | (dtPolyRef)p;
if (visited.find(ref) == visited.end()) {
mesh->setPolyArea(ref, WTO_AREA_NO_GO);
mesh->setPolyFlags(ref, WTO_FLAG_BLOCKED);
pruned++;
}
}
}
return pruned;
}
static void markChokepoints(dtNavMesh *mesh, dtNavMeshQuery *query, float chokeDistM) {
dtQueryFilter filter;
filter.setIncludeFlags(WTO_FLAG_WALK);
filter.setExcludeFlags(WTO_FLAG_DEEP_WATER | WTO_FLAG_BLOCKED);
const dtNavMesh *cmesh = mesh;
for (int i = 0; i < cmesh->getMaxTiles(); ++i) {
const dtMeshTile *tile = cmesh->getTile(i);
if (!tile || !tile->header) continue;
dtPolyRef base = cmesh->getPolyRefBase(tile);
for (int p = 0; p < tile->header->polyCount; ++p) {
const dtPoly &poly = tile->polys[p];
if (poly.getType() == DT_POLYTYPE_OFFMESH_CONNECTION) continue;
uint8_t area = poly.getArea();
if (area == WTO_AREA_DEEP_WATER || area == WTO_AREA_SHALLOW_WATER) continue;
float cx = 0, cy = 0, cz = 0;
for (int v = 0; v < poly.vertCount; ++v) {
const float *vp = &tile->verts[poly.verts[v] * 3];
cx += vp[0]; cy += vp[1]; cz += vp[2];
}
float inv = 1.0f / (float)poly.vertCount;
float pos[3] = { cx * inv, cy * inv, cz * inv };
dtPolyRef ref = base | (dtPolyRef)p;
float hitDist = 999.0f;
float hitPos[3], hitNorm[3];
if (dtStatusSucceed(query->findDistanceToWall(ref, pos, chokeDistM + 1.0f, &filter, &hitDist, hitPos, hitNorm))) {
if (hitDist < chokeDistM) {
mesh->setPolyArea(ref, WTO_AREA_CHOKEPOINT);
mesh->setPolyFlags(ref, poly.flags | WTO_FLAG_CHOKEPOINT);
}
}
}
}
}
static std::vector<WtoCoverPoint> filterAndDedupeCovers(
const std::vector<WtoCoverPoint> &raw,
dtNavMeshQuery *q1
) {
dtQueryFilter filter;
filter.setIncludeFlags(WTO_FLAG_WALK);
filter.setExcludeFlags(WTO_FLAG_DEEP_WATER | WTO_FLAG_BLOCKED);
const float ext[3] = { 3.0f, 4.0f, 3.0f };
/* Sort by quality: hulldown & corner-peek full covers first, then wider/taller covers */
std::vector<size_t> order(raw.size());
for (size_t i = 0; i < raw.size(); ++i) order[i] = i;
std::sort(order.begin(), order.end(), [&](size_t a, size_t b) {
auto score = [](const WtoCoverPoint &c) {
float s = c.widthM * 2.0f + std::min(c.heightM, 4.0f);
if (c.kind == WTO_COVER_HULLDOWN) s += 3.0f;
if (c.hasPeekLeft || c.hasPeekRight) s += 2.5f;
return s;
};
return score(raw[a]) > score(raw[b]);
});
std::vector<WtoCoverPoint> kept;
kept.reserve(2048);
static const float kRetreatAngles[3] = { 0.0f, 0.45f, -0.45f };
for (size_t idx : order) {
WtoCoverPoint cp = raw[idx];
bool dup = false;
for (const auto &k : kept) {
float dx = k.pos[0] - cp.pos[0];
float dz = k.pos[2] - cp.pos[2];
if (dx * dx + dz * dz < 49.0f) { /* 7 m dedupe radius */
float dot = k.coverDir[0] * cp.coverDir[0] + k.coverDir[1] * cp.coverDir[1];
if (dot > 0.78f && k.kind == cp.kind) { dup = true; break; }
}
}
if (dup) continue;
/* Verify parking spot is on T1 navmesh and has >= 8 m safe retreat corridor */
dtPolyRef startRef = 0;
float nearest[3];
if (dtStatusFailed(q1->findNearestPoly(cp.pos, ext, &filter, &startRef, nearest)) || !startRef) continue;
float snapSq = (nearest[0] - cp.pos[0]) * (nearest[0] - cp.pos[0]) + (nearest[2] - cp.pos[2]) * (nearest[2] - cp.pos[2]);
if (snapSq > 9.0f) continue;
cp.pos[0] = nearest[0]; cp.pos[1] = nearest[1]; cp.pos[2] = nearest[2];
bool retreatOk = false;
float baseAng = std::atan2(-cp.coverDir[1], -cp.coverDir[0]);
for (float da : kRetreatAngles) {
float rx = std::cos(baseAng + da);
float rz = std::sin(baseAng + da);
float endPt[3] = { cp.pos[0] + rx * 8.5f, cp.pos[1], cp.pos[2] + rz * 8.5f };
float t = 0.0f;
float hitNorm[3];
dtPolyRef polys[32];
int npolys = 0;
if (dtStatusSucceed(q1->raycast(startRef, cp.pos, endPt, &filter, &t, hitNorm, polys, &npolys, 32))) {
if (t >= 0.92f) {
cp.retreatDir[0] = rx;
cp.retreatDir[1] = rz;
retreatOk = true;
break;
}
}
}
if (!retreatOk) continue;
kept.push_back(cp);
}
return kept;
}
static void serializeTier(const dtNavMeshParams &params, const std::vector<BuiltTile> &tiles, std::vector<uint8_t> &out) {
auto append = [&](const void *p, size_t n) {
size_t o = out.size();
out.resize(o + n);
std::memcpy(out.data() + o, p, n);
};
append(&params, sizeof(params));
uint32_t validCount = 0;
for (const auto &t : tiles) if (t.data && t.dataSize > 0) validCount++;
append(&validCount, sizeof(validCount));
for (const auto &t : tiles) {
if (!t.data || t.dataSize <= 0) continue;
uint32_t sz = (uint32_t)t.dataSize;
append(&sz, sizeof(sz));
append(t.data, t.dataSize);
}
}
int main(int argc, char **argv) {
std::string geoPath, poisPath, outNavPath, outPreviewPath;
for (int i = 1; i + 1 < argc; i += 2) {
std::string a = argv[i];
if (a == "--geo") geoPath = argv[i + 1];
else if (a == "--pois") poisPath = argv[i + 1];
else if (a == "--out") outNavPath = argv[i + 1];
else if (a == "--preview") outPreviewPath = argv[i + 1];
}
if (geoPath.empty() || poisPath.empty() || outNavPath.empty()) {
std::fprintf(stderr, "Usage: wto_navgen_bake --geo <in.wtogeo> --pois <in.pois.json> --out <out.wtonav> [--preview <out.preview.bin>]\n");
return 2;
}
auto t0 = std::chrono::steady_clock::now();
GeoData geo;
if (!loadGeo(geoPath, geo)) return 1;
PoisData pois;
if (!loadPois(poisPath, pois)) {
std::fprintf(stderr, "Failed to read POIs: %s\n", poisPath.c_str());
return 1;
}
float mapMinX = geo.hdr.boundsMin[0];
float mapMinZ = geo.hdr.boundsMin[1];
float mapMaxX = geo.hdr.boundsMax[0];
float mapMaxZ = geo.hdr.boundsMax[1];
int tilesX = (int)std::ceil((mapMaxX - mapMinX) / kTileWorldSize);
int tilesZ = (int)std::ceil((mapMaxZ - mapMinZ) / kTileWorldSize);
int totalTiles = tilesX * tilesZ;
std::printf("Bake %s: %.0fx%.0fm (%dx%d = %d tiles) obsTris=%u\n",
geoPath.c_str(), mapMaxX - mapMinX, mapMaxZ - mapMinZ, tilesX, tilesZ, totalTiles, geo.hdr.obsTriCount);
/* Bucket obstacle triangles once into overlapping tiles */
const float pad = 4.5f;
std::vector<std::vector<uint32_t>> buckets((size_t)totalTiles);
for (uint32_t ti = 0; ti < geo.hdr.obsTriCount; ++ti) {
const auto &t = geo.obsTris[ti];
const Vec3 &v0 = geo.obsVerts[t.i0];
const Vec3 &v1 = geo.obsVerts[t.i1];
const Vec3 &v2 = geo.obsVerts[t.i2];
float tminX = std::min({ v0.x, v1.x, v2.x }) - pad;
float tmaxX = std::max({ v0.x, v1.x, v2.x }) + pad;
float tminZ = std::min({ v0.z, v1.z, v2.z }) - pad;
float tmaxZ = std::max({ v0.z, v1.z, v2.z }) + pad;
int tx0 = std::clamp((int)std::floor((tminX - mapMinX) / kTileWorldSize), 0, tilesX - 1);
int tx1 = std::clamp((int)std::floor((tmaxX - mapMinX) / kTileWorldSize), 0, tilesX - 1);
int tz0 = std::clamp((int)std::floor((tminZ - mapMinZ) / kTileWorldSize), 0, tilesZ - 1);
int tz1 = std::clamp((int)std::floor((tmaxZ - mapMinZ) / kTileWorldSize), 0, tilesZ - 1);
for (int tz = tz0; tz <= tz1; ++tz) {
for (int tx = tx0; tx <= tx1; ++tx) {
buckets[(size_t)tz * tilesX + tx].push_back(ti);
}
}
}
dtNavMeshParams nmParams{};
nmParams.orig[0] = mapMinX;
nmParams.orig[1] = geo.minY;
nmParams.orig[2] = mapMinZ;
nmParams.tileWidth = kTileWorldSize;
nmParams.tileHeight = kTileWorldSize;
int tileBits = dtIlog2(dtNextPow2((unsigned int)totalTiles));
if (tileBits > 16) tileBits = 16;
nmParams.maxTiles = 1 << tileBits;
nmParams.maxPolys = 1 << (22 - tileBits);
dtNavMesh *meshes[WTO_NAV_TIER_COUNT] = {};
dtNavMeshQuery *queries[WTO_NAV_TIER_COUNT] = {};
std::vector<BuiltTile> tierTiles[WTO_NAV_TIER_COUNT];
std::vector<WtoCoverPoint> rawCovers;
unsigned int nWorkers = std::max(1u, std::thread::hardware_concurrency());
for (uint32_t tierIdx = 0; tierIdx < WTO_NAV_TIER_COUNT; ++tierIdx) {
const bool doCovers = (tierIdx == WTO_NAV_TIER_STANDARD);
tierTiles[tierIdx].resize((size_t)totalTiles);
std::atomic<int> nextTile{ 0 };
std::mutex covMtx;
std::vector<std::thread> workers;
for (unsigned int w = 0; w < nWorkers; ++w) {
workers.emplace_back([&]() {
std::vector<WtoCoverPoint> localCov;
while (true) {
int idx = nextTile.fetch_add(1);
if (idx >= totalTiles) break;
int tx = idx % tilesX;
int tz = idx / tilesX;
auto br = buildSingleTile(geo, buckets[(size_t)idx], kTiers[tierIdx], tx, tz, mapMinX, mapMinZ, doCovers);
tierTiles[tierIdx][(size_t)idx] = br.tile;
if (doCovers && !br.covers.empty()) {
localCov.insert(localCov.end(), br.covers.begin(), br.covers.end());
}
}
if (doCovers && !localCov.empty()) {
std::lock_guard<std::mutex> lk(covMtx);
rawCovers.insert(rawCovers.end(), localCov.begin(), localCov.end());
}
});
}
for (auto &th : workers) th.join();
meshes[tierIdx] = assembleNavMesh(nmParams, tierTiles[tierIdx]);
queries[tierIdx] = dtAllocNavMeshQuery();
queries[tierIdx]->init(meshes[tierIdx], 65535);
int builtCnt = 0, polyCnt = 0;
for (const auto &bt : tierTiles[tierIdx]) if (bt.data) builtCnt++;
const dtNavMesh *cm = meshes[tierIdx];
for (int i = 0; i < cm->getMaxTiles(); ++i) {
const dtMeshTile *tl = cm->getTile(i);
if (tl && tl->header) polyCnt += tl->header->polyCount;
}
int pruned = pruneUnreachableIslands(meshes[tierIdx], queries[tierIdx], geo, pois);
if (tierIdx == WTO_NAV_TIER_STANDARD) {
markChokepoints(meshes[tierIdx], queries[tierIdx], 3.8f);
}
std::printf(" %s (r=%.2fm): tiles=%d/%d polys=%d prunedIslands=%d\n",
kTiers[tierIdx].name, kTiers[tierIdx].agentRadius, builtCnt, totalTiles, polyCnt, pruned);
}
/* Dedupe + retreat-verify tank covers on Tier 1 */
std::vector<WtoCoverPoint> covers = filterAndDedupeCovers(rawCovers, queries[WTO_NAV_TIER_STANDARD]);
int fullCnt = 0, hdCnt = 0, peekCnt = 0;
for (const auto &c : covers) {
if (c.kind == WTO_COVER_FULL) fullCnt++; else hdCnt++;
if (c.hasPeekLeft || c.hasPeekRight) peekCnt++;
}
std::printf(" Covers: raw=%zu -> verified=%zu (full=%d, hulldown=%d, withPeek=%d)\n",
rawCovers.size(), covers.size(), fullCnt, hdCnt, peekCnt);
/* Build 8m tactical grid (clearance + simple terrain-horizon exposure) */
const float tacCellM = 8.0f;
uint32_t tacCols = (uint32_t)std::ceil((mapMaxX - mapMinX) / tacCellM);
uint32_t tacRows = (uint32_t)std::ceil((mapMaxZ - mapMinZ) / tacCellM);
std::vector<WtoTacticalCell> tacGrid((size_t)tacCols * tacRows);
{
dtQueryFilter wf;
wf.setIncludeFlags(WTO_FLAG_WALK);
wf.setExcludeFlags(WTO_FLAG_DEEP_WATER | WTO_FLAG_BLOCKED);
const float ext[3] = { 4.5f, 6.0f, 4.5f };
dtNavMeshQuery *q1 = queries[WTO_NAV_TIER_STANDARD];
for (uint32_t rz = 0; rz < tacRows; ++rz) {
float wz = mapMinZ + (rz + 0.5f) * tacCellM;
for (uint32_t cx = 0; cx < tacCols; ++cx) {
float wx = mapMinX + (cx + 0.5f) * tacCellM;
float gy = geo.sampleHeight(wx, wz);
float pt[3] = { wx, gy, wz };
WtoTacticalCell cell{ 128, 0, 128, 128 };
dtPolyRef ref = 0;
float npt[3];
if (dtStatusSucceed(q1->findNearestPoly(pt, ext, &wf, &ref, npt)) && ref) {
float dist = 32.0f, hp[3], hn[3];
if (dtStatusSucceed(q1->findDistanceToWall(ref, npt, 32.0f, &wf, &dist, hp, hn))) {
cell.clearanceHalfM = (uint8_t)std::clamp((int)std::round(dist * 2.0f), 0, 255);
}
/* Horizon exposure: sample 8 azimuths at 40m..240m against heightmap */
int openRays = 0;
for (int a = 0; a < 8; ++a) {
float ang = a * (kPi * 0.25f);
float dx = std::cos(ang), dz = std::sin(ang);
bool blocked = false;
for (float d = 40.0f; d <= 240.0f; d += 40.0f) {
float sx = wx + dx * d, sz = wz + dz * d;
if (sx < mapMinX || sx > mapMaxX || sz < mapMinZ || sz > mapMaxZ) break;
if (geo.sampleHeight(sx, sz) > gy + 3.2f) { blocked = true; break; }
}
if (!blocked) openRays++;
}
cell.exposure = (uint8_t)((openRays * 255) / 8);
}
tacGrid[(size_t)rz * tacCols + cx] = cell;
}
}
}
/* Connectivity audit: all spawns -> all capture zones on T0, T1, T2 */
struct SamplePath { std::vector<float> pts; };
std::vector<SamplePath> samplePaths;
{
dtQueryFilter pf;
pf.setIncludeFlags(WTO_FLAG_WALK);
pf.setExcludeFlags(WTO_FLAG_DEEP_WATER | WTO_FLAG_BLOCKED);
pf.setAreaCost(WTO_AREA_ROAD, 0.75f);
pf.setAreaCost(WTO_AREA_BRIDGE, 0.90f);
pf.setAreaCost(WTO_AREA_GROUND, 1.00f);
pf.setAreaCost(WTO_AREA_ROUGH, 1.65f);
pf.setAreaCost(WTO_AREA_FOREST, 2.10f);
pf.setAreaCost(WTO_AREA_CRUSHABLE, 2.40f);
pf.setAreaCost(WTO_AREA_SHALLOW_WATER, 2.60f);
pf.setAreaCost(WTO_AREA_CHOKEPOINT, 1.80f);
const float snapExt[3] = { 12.0f, 12.0f, 12.0f };
std::vector<PoiPt> allSpawns = pois.t1Spawns;
allSpawns.insert(allSpawns.end(), pois.t2Spawns.begin(), pois.t2Spawns.end());
for (uint32_t ti = 0; ti < WTO_NAV_TIER_COUNT; ++ti) {
int totalPairs = 0, fullOk = 0, partialOk = 0, snapFail = 0;
dtNavMeshQuery *q = queries[ti];
for (size_t si = 0; si < allSpawns.size(); ++si) {
float sp[3] = { allSpawns[si].x, geo.sampleHeight(allSpawns[si].x, allSpawns[si].z), allSpawns[si].z };
dtPolyRef sRef = 0; float sNear[3];
bool sOk = dtStatusSucceed(q->findNearestPoly(sp, snapExt, &pf, &sRef, sNear)) && sRef;
for (size_t ci = 0; ci < pois.caps.size(); ++ci) {
totalPairs++;
float cp[3] = { pois.caps[ci].x, geo.sampleHeight(pois.caps[ci].x, pois.caps[ci].z), pois.caps[ci].z };
dtPolyRef cRef = 0; float cNear[3];
bool cOk = dtStatusSucceed(q->findNearestPoly(cp, snapExt, &pf, &cRef, cNear)) && cRef;
if (!sOk || !cOk) { snapFail++; continue; }
dtPolyRef polys[4096];
int npolys = 0;
dtStatus st = q->findPath(sRef, cRef, sNear, cNear, &pf, polys, &npolys, 4096);
if (dtStatusSucceed(st) && npolys > 0 && polys[npolys - 1] == cRef) {
fullOk++;
if (ti == WTO_NAV_TIER_STANDARD && samplePaths.size() < 12 && (si % std::max<size_t>(1, allSpawns.size() / 6) == 0)) {
float straight[512 * 3];
int nstraight = 0;
if (dtStatusSucceed(q->findStraightPath(sNear, cNear, polys, npolys, straight, nullptr, nullptr, &nstraight, 512)) && nstraight >= 2) {
SamplePath spath;
spath.pts.assign(straight, straight + nstraight * 3);
samplePaths.push_back(std::move(spath));
}
}
} else if (dtStatusSucceed(st) && npolys > 0) {
partialOk++;
if (ti == WTO_NAV_TIER_STANDARD && partialOk <= 4) {
std::printf(" [partial] %s (%.0f,%.0f) -> %s (%.0f,%.0f) npolys=%d outOfNodes=%d\n",
allSpawns[si].name.c_str(), allSpawns[si].x, allSpawns[si].z,
pois.caps[ci].name.c_str(), pois.caps[ci].x, pois.caps[ci].z,
npolys, (st & DT_OUT_OF_NODES) ? 1 : 0);
}
}
}
}
std::printf(" Connectivity %s: full=%d/%d (%.1f%%) partial=%d snapFail=%d\n",
kTiers[ti].name, fullOk, totalPairs,
totalPairs > 0 ? (100.0f * fullOk / totalPairs) : 100.0f,
partialOk, snapFail);
}
}
/* Serialize final `.wtonav` binary */
std::vector<uint8_t> tierBlobs[WTO_NAV_TIER_COUNT];
for (uint32_t ti = 0; ti < WTO_NAV_TIER_COUNT; ++ti) {
/* Re-copy modified tiles (with chokepoint flags on T1) directly from assembled dtNavMesh */
const dtNavMesh *cm = meshes[ti];
std::vector<BuiltTile> finalTiles;
for (int i = 0; i < cm->getMaxTiles(); ++i) {
const dtMeshTile *tl = cm->getTile(i);
if (tl && tl->header && tl->data && tl->dataSize > 0) {
BuiltTile bt;
bt.data = tl->data;
bt.dataSize = tl->dataSize;
finalTiles.push_back(bt);
}
}
serializeTier(nmParams, finalTiles, tierBlobs[ti]);
}
WtoNavHeader nh{};
std::memcpy(nh.magic, WTO_NAV_MAGIC, 8);
nh.version = WTO_NAV_VERSION;
std::memcpy(nh.everSha1, geo.hdr.everSha1, 20);
nh.bmin[0] = mapMinX; nh.bmin[1] = geo.minY; nh.bmin[2] = mapMinZ;
nh.bmax[0] = mapMaxX; nh.bmax[1] = geo.maxY; nh.bmax[2] = mapMaxZ;
nh.waterLevel = geo.hdr.waterLevel;
nh.tierCount = WTO_NAV_TIER_COUNT;
uint32_t curOff = (uint32_t)sizeof(WtoNavHeader);
for (uint32_t ti = 0; ti < WTO_NAV_TIER_COUNT; ++ti) {
nh.tierOffsets[ti] = curOff;
nh.tierSizes[ti] = (uint32_t)tierBlobs[ti].size();
curOff += nh.tierSizes[ti];
}
nh.coverOffset = curOff;
nh.coverCount = (uint32_t)covers.size();
curOff += (uint32_t)(covers.size() * sizeof(WtoCoverPoint));
nh.tacOffset = curOff;
nh.tacCols = tacCols;
nh.tacRows = tacRows;
nh.tacCellM = tacCellM;
nh.tacOrigin[0] = mapMinX;
nh.tacOrigin[1] = mapMinZ;
{
std::ofstream out(outNavPath, std::ios::binary);
out.write(reinterpret_cast<const char *>(&nh), sizeof(nh));
for (uint32_t ti = 0; ti < WTO_NAV_TIER_COUNT; ++ti) {
out.write(reinterpret_cast<const char *>(tierBlobs[ti].data()), tierBlobs[ti].size());
}
if (!covers.empty()) {
out.write(reinterpret_cast<const char *>(covers.data()), covers.size() * sizeof(WtoCoverPoint));
}
if (!tacGrid.empty()) {
out.write(reinterpret_cast<const char *>(tacGrid.data()), tacGrid.size() * sizeof(WtoTacticalCell));
}
std::printf(" Wrote %s (%.2f MB uncompressed)\n", outNavPath.c_str(), (double)(curOff + tacGrid.size() * sizeof(WtoTacticalCell)) / (1024.0 * 1024.0));
}
/* Write compact raster preview data for PNG visual inspection */
if (!outPreviewPath.empty()) {
const uint32_t pw = 1024, ph = 1024;
std::vector<float> pHeight((size_t)pw * ph);
std::vector<uint8_t> pFlags((size_t)pw * ph, 0);
/* Bit 0: T0 walkable, Bit 1: T1 walkable, Bit 2: T2 walkable, Bit 3: shallow water,
* Bit 4: deep water, Bit 5: chokepoint, Bit 6: crushable/forest, Bit 7: bridge */
dtQueryFilter anyF;
anyF.setIncludeFlags(0xFFFF);
anyF.setExcludeFlags(0);
const float ext[3] = { 0.8f, 6.0f, 0.8f };
std::atomic<uint32_t> nextRow{ 0 };
std::vector<std::thread> pWorkers;
for (unsigned int w = 0; w < nWorkers; ++w) {
pWorkers.emplace_back([&]() {
dtNavMeshQuery *lq[WTO_NAV_TIER_COUNT];
for (uint32_t ti = 0; ti < WTO_NAV_TIER_COUNT; ++ti) {
lq[ti] = dtAllocNavMeshQuery();
lq[ti]->init(meshes[ti], 256);
}
while (true) {
uint32_t rz = nextRow.fetch_add(1);
if (rz >= ph) break;
float wz = mapMinZ + ((rz + 0.5f) / ph) * (mapMaxZ - mapMinZ);
for (uint32_t rx = 0; rx < pw; ++rx) {
float wx = mapMinX + ((rx + 0.5f) / pw) * (mapMaxX - mapMinX);
float gy = geo.sampleHeight(wx, wz);
pHeight[(size_t)rz * pw + rx] = gy;
uint8_t fl = 0;
float pt[3] = { wx, gy, wz };
for (uint32_t ti = 0; ti < WTO_NAV_TIER_COUNT; ++ti) {
dtPolyRef ref = 0;
float npt[3];
if (dtStatusSucceed(lq[ti]->findNearestPoly(pt, ext, &anyF, &ref, npt)) && ref) {
float d2 = (npt[0] - wx) * (npt[0] - wx) + (npt[2] - wz) * (npt[2] - wz);
if (d2 <= 1.0f) {
unsigned char area = 0;
meshes[ti]->getPolyArea(ref, &area);
if (area == WTO_AREA_DEEP_WATER) fl |= 16;
else {
fl |= (1u << ti);
if (ti == WTO_NAV_TIER_STANDARD) {
if (area == WTO_AREA_SHALLOW_WATER) fl |= 8;
else if (area == WTO_AREA_CHOKEPOINT) fl |= 32;
else if (area == WTO_AREA_CRUSHABLE || area == WTO_AREA_FOREST) fl |= 64;
else if (area == WTO_AREA_BRIDGE) fl |= 128;
}
}
}
}
}
pFlags[(size_t)rz * pw + rx] = fl;
}
}
for (uint32_t ti = 0; ti < WTO_NAV_TIER_COUNT; ++ti) dtFreeNavMeshQuery(lq[ti]);
});
}
for (auto &th : pWorkers) th.join();
std::ofstream pout(outPreviewPath, std::ios::binary);
pout.write("WTOPREV1", 8);
pout.write(reinterpret_cast<const char *>(&pw), 4);
pout.write(reinterpret_cast<const char *>(&ph), 4);
pout.write(reinterpret_cast<const char *>(&mapMinX), 4);
pout.write(reinterpret_cast<const char *>(&mapMinZ), 4);
pout.write(reinterpret_cast<const char *>(&mapMaxX), 4);
pout.write(reinterpret_cast<const char *>(&mapMaxZ), 4);
pout.write(reinterpret_cast<const char *>(&geo.hdr.waterLevel), 4);
pout.write(reinterpret_cast<const char *>(pHeight.data()), pHeight.size() * sizeof(float));
pout.write(reinterpret_cast<const char *>(pFlags.data()), pFlags.size());
uint32_t cCnt = (uint32_t)covers.size();
pout.write(reinterpret_cast<const char *>(&cCnt), 4);
if (cCnt > 0) pout.write(reinterpret_cast<const char *>(covers.data()), cCnt * sizeof(WtoCoverPoint));
pout.write(reinterpret_cast<const char *>(&tacCols), 4);
pout.write(reinterpret_cast<const char *>(&tacRows), 4);
if (!tacGrid.empty()) pout.write(reinterpret_cast<const char *>(tacGrid.data()), tacGrid.size() * sizeof(WtoTacticalCell));
uint32_t pCnt = (uint32_t)samplePaths.size();
pout.write(reinterpret_cast<const char *>(&pCnt), 4);
for (const auto &sp : samplePaths) {
uint32_t npts = (uint32_t)(sp.pts.size() / 3);
pout.write(reinterpret_cast<const char *>(&npts), 4);
pout.write(reinterpret_cast<const char *>(sp.pts.data()), sp.pts.size() * sizeof(float));
}
}
for (uint32_t ti = 0; ti < WTO_NAV_TIER_COUNT; ++ti) {
dtFreeNavMeshQuery(queries[ti]);
dtFreeNavMesh(meshes[ti]);
for (auto &bt : tierTiles[ti]) dtFree(bt.data);
}
auto elapsed = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
std::printf("Done in %.2fs\n", elapsed);
return 0;
}