Files
WT-Offline/tools/navgen/bake/bake.cpp
T
N0VAN0M4LY 4191d59168 feat(navgen): bake road materials and directional cover
Decode LMp2 terrain materials and decals into navigable road areas. Preserve usable cover bearings and verify left and right corner approaches independently on the standard tank mesh.

Verified with Rust and MSVC builds, TypeScript checks, and offline baking on Berlin, Poland, and Hurtgen for 2.61.0.58.
2026-12-04 12:36:07 +08:00

1324 lines
58 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 <tuple>
#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 CoverBake {
float minCoverHeightM;
float peekMinM;
float peekMaxM;
float retreatMinM;
};
struct PoisData {
CoverBake cover{};
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;
static constexpr float kCoverScanM = 5.2f;
static constexpr float kPeekSightM = 14.0f;
static constexpr float kHullDownSightM = 22.0f;
static constexpr float kCoverHeightToleranceM = 1.2f;
struct GeoData {
WtoGeoHeader hdr{};
std::vector<float> heights;
WtoGeoRoadMask roads{};
std::vector<uint8_t> roadCells;
std::vector<Vec3> obsVerts;
std::vector<ObsTri> obsTris;
float minY = 1e9f;
float maxY = -1e9f;
bool isRoad(float wx, float wz) const {
if (roadCells.empty()) return false;
float x = (wx - roads.origin[0]) / roads.cellSize;
float z = (wz - roads.origin[1]) / roads.cellSize;
if (x < 0.0f || z < 0.0f || x >= roads.size || z >= roads.size) return false;
return roadCells[(size_t)z * roads.size + (size_t)x] != 0;
}
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 (out.hdr.flags & WTO_GEO_FLAG_ROAD_MASK) {
in.read(reinterpret_cast<char *>(&out.roads), sizeof(WtoGeoRoadMask));
// Same allocation limit as the extractor.
if (!in || out.roads.size == 0 || out.roads.size > 8192 ||
!(out.roads.cellSize > 0.0f) || !std::isfinite(out.roads.cellSize) ||
!std::isfinite(out.roads.origin[0]) || !std::isfinite(out.roads.origin[1])) return false;
out.roadCells.resize((size_t)out.roads.size * out.roads.size);
in.read(reinterpret_cast<char *>(out.roadCells.data()), out.roadCells.size());
}
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;
}
static float readJsonNumber(const std::string &json, const char *key, float fallback) {
size_t pos = json.find(std::string("\"") + key + "\"");
if (pos == std::string::npos) return fallback;
pos = json.find(':', pos);
if (pos == std::string::npos) return fallback;
const char *start = json.c_str() + pos + 1;
char *end = nullptr;
float value = std::strtof(start, &end);
return end != start && std::isfinite(value) ? value : fallback;
}
/* 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 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 = readJsonNumber(obj, "x", 0.0f);
pt.y = readJsonNumber(obj, "y", 0.0f);
pt.z = readJsonNumber(obj, "z", 0.0f);
pt.radius = readJsonNumber(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>());
out.cover = {
readJsonNumber(content, "minCoverHeightM", -1.0f),
readJsonNumber(content, "peekMinM", -1.0f),
readJsonNumber(content, "peekMaxM", -1.0f),
readJsonNumber(content, "retreatMinM", -1.0f)
};
if (out.cover.minCoverHeightM <= 0.0f || out.cover.peekMinM <= 0.0f ||
out.cover.peekMaxM < out.cover.peekMinM || out.cover.peekMaxM >= kTileWorldSize ||
out.cover.retreatMinM <= 0.0f || out.cover.retreatMinM >= kTileWorldSize) {
std::fprintf(stderr, "Invalid cover baking settings in %s. Regenerate it with mission-bounds.mts.\n", path.c_str());
return false;
}
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;
}
static int coverBorderCells(const CoverBake &tuning) {
float reach = std::max(kHullDownSightM, std::hypot(tuning.peekMaxM, kPeekSightM));
return (int)std::ceil(reach / kCellSize) + 1;
}
static bool isCoverArea(unsigned char area) {
return area != RC_NULL_AREA && area != WTO_AREA_DEEP_WATER && area != WTO_AREA_SHALLOW_WATER;
}
static bool isCoverBoundary(const rcCompactHeightfield &field, int x, int z, const rcCompactSpan &span) {
for (int dir = 0; dir < 4; ++dir) {
int connection = rcGetCon(span, dir);
if (connection == RC_NOT_CONNECTED) return true;
int nx = x + rcGetDirOffsetX(dir);
int nz = z + rcGetDirOffsetY(dir);
if (field.areas[field.cells[nx + nz * field.width].index + connection] == RC_NULL_AREA) return true;
}
return false;
}
static bool findCornerPeek(
const rcCompactHeightfield &field, const rcHeightfield &hard, const GeoData &geo,
const CoverBake &tuning, const WtoCoverPoint &cover, float side, float (&point)[3]
) {
const float dx = cover.coverDir[0], dz = cover.coverDir[1];
for (float distance = tuning.peekMinM; distance <= tuning.peekMaxM; distance += field.cs) {
const float x = cover.pos[0] - dz * side * distance;
const float z = cover.pos[2] + dx * side * distance;
const int gx = (int)std::floor((x - field.bmin[0]) / field.cs);
const int gz = (int)std::floor((z - field.bmin[2]) / field.cs);
if (gx < 0 || gz < 0 || gx >= field.width || gz >= field.height) break;
const rcCompactCell &cell = field.cells[gx + gz * field.width];
for (unsigned int i = cell.index; i < cell.index + cell.count; ++i) {
if (!isCoverArea(field.areas[i])) continue;
float y = field.bmin[1] + field.spans[i].y * field.ch;
if (std::fabs(y - cover.pos[1]) > kCoverHeightToleranceM) continue;
if (hfTraceBand(hard, geo, x, z, dx, dz, kPeekSightM, y + 1.8f, y + 2.6f)) continue;
point[0] = x;
point[1] = y;
point[2] = z;
return true;
}
}
return false;
}
static void bakeTileCovers(
const rcCompactHeightfield &field, const rcHeightfield &hard, const GeoData &geo,
const rcConfig &cfg, const CoverBake &tuning, std::vector<WtoCoverPoint> &covers
) {
static const float directions[8][2] = {
{ 1.0f, 0.0f }, { 0.70710678f, 0.70710678f }, { 0.0f, 1.0f }, { -0.70710678f, 0.70710678f },
{ -1.0f, 0.0f }, { -0.70710678f, -0.70710678f }, { 0.0f, -1.0f }, { 0.70710678f, -0.70710678f }
};
const int innerEnd = cfg.borderSize + cfg.tileSize;
for (int z = cfg.borderSize; z < innerEnd; ++z) {
for (int x = cfg.borderSize; x < innerEnd; ++x) {
const rcCompactCell &cell = field.cells[x + z * field.width];
for (unsigned int i = cell.index; i < cell.index + cell.count; ++i) {
const rcCompactSpan &span = field.spans[i];
if (!isCoverArea(field.areas[i]) || !isCoverBoundary(field, x, z, span)) continue;
Vec3 pos{ cfg.bmin[0] + (x + 0.5f) * cfg.cs, cfg.bmin[1] + span.y * cfg.ch,
cfg.bmin[2] + (z + 0.5f) * cfg.cs };
// Every usable bearing goes through the same checks, including opposite faces of one object.
for (const auto &dir : directions) {
float dx = dir[0], dz = dir[1];
int hullHits = 0, turretHits = 0;
float totalHeight = 0.0f;
for (int column = -2; column <= 2; ++column) {
float offset = column * 0.9f; // Five samples across a 3.6 m hull.
float sx = pos.x - dz * offset, sz = pos.z + dx * offset;
float top = pos.y;
if (!hfTraceBand(hard, geo, sx, sz, dx, dz, kCoverScanM, pos.y + 0.65f, pos.y + 1.80f, &top)) continue;
++hullHits;
totalHeight += std::max(0.0f, top - pos.y);
turretHits += hfTraceBand(hard, geo, sx, sz, dx, dz, kCoverScanM, pos.y + 2.05f, pos.y + 2.85f);
}
if (hullHits < 4 || totalHeight < tuning.minCoverHeightM * hullHits) continue;
float width = 3.6f;
for (float off : { -2.6f, 2.6f }) {
if (hfTraceBand(hard, geo, pos.x - dz * off, pos.z + dx * off, dx, dz,
kCoverScanM, pos.y + 0.65f, pos.y + 1.80f)) width += 1.0f;
}
WtoCoverPoint cover{};
cover.pos[0] = pos.x; cover.pos[1] = pos.y; cover.pos[2] = pos.z;
cover.coverDir[0] = dx; cover.coverDir[1] = dz;
cover.halfAngleDeg = width >= 5.0f ? 42.0f : 32.0f;
cover.heightM = totalHeight / hullHits;
cover.widthM = width;
if (turretHits >= 3) {
cover.kind = WTO_COVER_FULL;
cover.hasPeekLeft = findCornerPeek(field, hard, geo, tuning, cover, -1.0f, cover.peekLeft);
cover.hasPeekRight = findCornerPeek(field, hard, geo, tuning, cover, 1.0f, cover.peekRight);
} else {
if (hfTraceBand(hard, geo, pos.x, pos.z, dx, dz, kHullDownSightM, pos.y + 2.15f, pos.y + 2.75f)) continue;
cover.kind = WTO_COVER_HULLDOWN;
}
covers.push_back(cover);
}
}
}
}
}
static void markRoadAreas(rcCompactHeightfield &field, const GeoData &geo) {
if (geo.roadCells.empty()) return;
for (int z = 0; z < field.height; ++z) {
const float wz = field.bmin[2] + (z + 0.5f) * field.cs;
for (int x = 0; x < field.width; ++x) {
const float wx = field.bmin[0] + (x + 0.5f) * field.cs;
if (!geo.isRoad(wx, wz)) continue;
const rcCompactCell &cell = field.cells[x + z * field.width];
for (unsigned int i = cell.index; i < cell.index + cell.count; ++i) {
if (field.areas[i] == WTO_AREA_GROUND) field.areas[i] = WTO_AREA_ROAD;
}
}
}
}
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,
const CoverBake &coverTuning, 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;
// Cover and corner rays must see hard collision on the other side of tile boundaries.
if (bakeCovers) cfg.borderSize = std::max(cfg.borderSize, coverBorderCells(coverTuning));
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;
}
}
}
}
}
}
if (hardHf) bakeTileCovers(*chf, *hardHf, geo, cfg, coverTuning, res.covers);
rcFreeHeightField(hardHf);
hardHf = nullptr;
/* Smooth isolated single-voxel slope/area noise slivers before region building */
rcMedianFilterWalkableArea(&ctx, *chf);
rcMedianFilterWalkableArea(&ctx, *chf);
markRoadAreas(*chf, geo);
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 dtPolyRef verifyCoverPosition(dtNavMeshQuery &query, const dtQueryFilter &filter, float (&point)[3]) {
const float extent[3] = { kCellSize, kCoverHeightToleranceM, kCellSize };
dtPolyRef ref = 0;
float nearest[3];
bool overPoly = false;
if (dtStatusFailed(query.findNearestPoly(point, extent, &filter, &ref, nearest, &overPoly)) ||
!ref || !overPoly || std::fabs(nearest[1] - point[1]) > kCoverHeightToleranceM) return 0;
point[1] = nearest[1]; // Keep the XZ from the collision probe.
return ref;
}
static bool clearCoverCorridor(dtNavMeshQuery &query, const dtQueryFilter &filter,
dtPolyRef startRef, const float *start, const float *end, dtPolyRef endRef = 0) {
float fraction = 0.0f, normal[3];
dtPolyRef trail[32];
int count = 0;
dtStatus status = query.raycast(startRef, start, end, &filter, &fraction, normal, trail, &count, 32);
return dtStatusSucceed(status) && !dtStatusDetail(status, DT_BUFFER_TOO_SMALL) &&
fraction >= 1.0f && (!endRef || (count > 0 && trail[count - 1] == endRef));
}
static bool verifyCover(WtoCoverPoint &cover, dtNavMeshQuery &query,
const dtQueryFilter &filter, float retreatMinM) {
dtPolyRef startRef = verifyCoverPosition(query, filter, cover.pos);
if (!startRef) return false;
const float heading = std::atan2(-cover.coverDir[1], -cover.coverDir[0]);
bool hasRetreat = false;
for (float offset : { 0.0f, 0.45f, -0.45f }) {
float rx = std::cos(heading + offset), rz = std::sin(heading + offset);
float end[3] = { cover.pos[0] + rx * retreatMinM, cover.pos[1], cover.pos[2] + rz * retreatMinM };
if (!clearCoverCorridor(query, filter, startRef, cover.pos, end)) continue;
cover.retreatDir[0] = rx;
cover.retreatDir[1] = rz;
hasRetreat = true;
break;
}
if (!hasRetreat) return false;
auto validatePeek = [&](float (&point)[3]) {
dtPolyRef endRef = verifyCoverPosition(query, filter, point);
return endRef && clearCoverCorridor(query, filter, startRef, cover.pos, point, endRef);
};
cover.hasPeekLeft = cover.hasPeekLeft && validatePeek(cover.peekLeft);
cover.hasPeekRight = cover.hasPeekRight && validatePeek(cover.peekRight);
return true;
}
static unsigned int peekCount(const WtoCoverPoint &cover) {
return cover.hasPeekLeft + cover.hasPeekRight;
}
static std::vector<WtoCoverPoint> filterAndDedupeCovers(
const std::vector<WtoCoverPoint> &raw, dtNavMeshQuery &query, const CoverBake &tuning
) {
dtQueryFilter filter;
filter.setIncludeFlags(WTO_FLAG_WALK);
filter.setExcludeFlags(WTO_FLAG_DEEP_WATER | WTO_FLAG_BLOCKED);
std::vector<WtoCoverPoint> usable;
for (WtoCoverPoint cover : raw) {
if (verifyCover(cover, query, filter, tuning.retreatMinM)) usable.push_back(cover);
}
std::sort(usable.begin(), usable.end(), [](const WtoCoverPoint &a, const WtoCoverPoint &b) {
auto rank = [](const WtoCoverPoint &c) {
return std::make_tuple(peekCount(c), c.widthM, c.heightM);
};
if (rank(a) != rank(b)) return rank(a) > rank(b);
return std::tie(a.pos[0], a.pos[1], a.pos[2], a.coverDir[0], a.coverDir[1]) <
std::tie(b.pos[0], b.pos[1], b.pos[2], b.coverDir[0], b.coverDir[1]);
});
std::vector<WtoCoverPoint> kept;
const float maxLevelDifference = kTiers[WTO_NAV_TIER_STANDARD].maxClimb;
for (const auto &cover : usable) {
bool duplicate = std::any_of(kept.begin(), kept.end(), [&](const WtoCoverPoint &other) {
if (cover.kind != other.kind || std::fabs(cover.pos[1] - other.pos[1]) > maxLevelDifference) return false;
float dx = other.pos[0] - cover.pos[0], dz = other.pos[2] - cover.pos[2];
float dot = other.coverDir[0] * cover.coverDir[0] + other.coverDir[1] * cover.coverDir[1];
// Adjacent samples facing the same way are redundant. Perpendicular and opposite faces remain usable.
return dx * dx + dz * dz < 49.0f && dot > 0.78f;
});
if (!duplicate) kept.push_back(cover);
}
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 = coverBorderCells(pois.cover) * kCellSize;
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, pois.cover, 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], pois.cover);
int fullCnt = 0, hdCnt = 0, peekCnt = 0, bothPeeks = 0;
for (const auto &c : covers) {
if (c.kind == WTO_COVER_FULL) fullCnt++; else hdCnt++;
if (peekCount(c) > 0) peekCnt++;
if (peekCount(c) == 2) bothPeeks++;
}
std::printf(" Covers: raw=%zu -> verified=%zu (full=%d, hulldown=%d, withPeek=%d, bothPeeks=%d)\n",
rawCovers.size(), covers.size(), fullCnt, hdCnt, peekCnt, bothPeeks);
/* 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<uint16_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, Bit 8: road */
dtQueryFilter anyF;
anyF.setIncludeFlags(0xFFFF);
anyF.setExcludeFlags(WTO_FLAG_BLOCKED);
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;
uint16_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;
else if (area == WTO_AREA_ROAD) fl |= 256;
}
}
}
}
}
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("WTOPREV2", 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() * sizeof(uint16_t));
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;
}