Files
WT-Offline/tools/navgen/bake/bake.cpp
T
N0VAN0M4LY 413bd55c54 fix(ground-ai): spread team routes, pass vehicles and keep off deep water
First in-game run of the path follower on Berlin and Poland showed whole
teams queueing on one road, bots ramming stopped teammates and wrecks,
bots clipping building corners, bots sliding into the Poland river and
the same bot getting stuck at the same spot dozens of times.

Native engine (native/wto-nav):
- Team traffic: a bot's finished path counts for its team for
  trafficHoldSec; the team's later searches pay trafficCostPerPath more
  per counted path through a polygon (up to trafficCostMaxMul), so
  teammates spread over parallel routes. A slot's previous path stops
  counting when it asks for a new one.
- Path corners are moved up to cornerOffsetM away from the edge they
  turn around, when the mesh allows both legs; off-mesh link endpoints
  stay put.
- path_request takes the team; load_map takes the new settings;
  get_stats reports live traffic paths and moved corners.

Bake (tools/navgen):
- Water deeper than navBake.maxFordDepthM (0.9 m, was a fixed 0.6 m)
  is a wall before erosion, so walkable ground keeps the tier radius
  from it, plus deepWaterMarginM on banks lower than
  deepWaterBankHeightM above the water line. Quays and ramps above it
  keep only the radius. The preview marks deep water from the terrain.

Ground AI scripts:
- The lookahead point is pulled back along the path until the mesh
  allows the straight line to it, so corners are no longer cut through
  buildings.
- New traffic module replaces the fixed sideways step: hull length and
  width along the heading; stopped vehicles, wrecks and parked players
  are passed on the side with room, or the bot stops short and after
  blockWaitSec marks the spot and plans again; moving traffic ahead is
  followed; oncoming traffic is passed in the open and in narrow
  passages the bigger vehicle goes first. Wrecks carry their heading.
- A hull pressed against a vehicle or wreck backs off after
  contactReverseSec instead of the full stuck window.
- Jams and confirmed obstacles cost far more, and a given-up place is
  all but closed (giveUpRadiusM, giveUpCostMul), so replanning leaves
  instead of returning to it.

Tuning: navEngine trafficCostPerPath, trafficCostMaxMul, trafficHoldSec,
cornerOffsetM; pathFollow stationarySpeedMps, passMarginM, passSpeedMps,
blockWaitSec, blockTtlSec, contactGapM, contactReverseSec, giveUpRadiusM,
giveUpCostMul; avoidShiftM removed; jamCostMul 4 -> 12, rubbleCostMul
8 -> 25; navBake maxFordDepthM, deepWaterMarginM, deepWaterBankHeightM
(bake only). Launcher fields and en/zh-CN labels updated (978/978 keys).

Checked: root and launcher typecheck, MSVC build with no warnings in
project code, check-patches for 2.61.0.58 and 2.61.0.60, rebake of
avg_berlin, avg_poland and avg_hurtgen (all spawn-to-zone pairs still
connected on every tier), offline run on the new avg_poland pack (eight
same-team paths spread over different roads, traffic released after
the hold time, corners moved, pump within budget), isolated game copy
build. daScript compilation and in-battle behaviour still need the
in-game run.
2026-12-05 21:39:07 +08:00

1741 lines
79 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 <array>
#include <atomic>
#include <cfloat>
#include <chrono>
#include <cmath>
#include <deque>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <limits>
#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;
};
/* navBake water settings (ground-ai.jsonc, copied into the POI file by mission-bounds.mts). */
struct WaterBake {
float maxFordDepthM; /* Deeper water is a wall */
float marginM; /* Extra room kept from it on low banks */
float bankHeightM; /* Banks up to this height above the water line get the extra room */
};
struct PoisData {
CoverBake cover{};
float chokepointMaxWidthVehicles = 0.0f;
WaterBake water{ -1.0f, -1.0f, -1.0f };
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 kShallowWaterMinM = 0.05f;
static constexpr float kRoughSlopeDeg = 18.0f;
static constexpr float kCoverProbeStartM = 0.6f;
static constexpr float kCoverScanM = 5.2f;
static constexpr float kHullLowerM = 0.65f;
static constexpr float kHullUpperM = 1.80f;
static constexpr float kTurretLowerM = 2.05f;
static constexpr float kHullColumnSpacingM = 0.9f;
static constexpr float kExtraCoverColumnM = 2.6f;
static constexpr float kGeometryToleranceM = 0.001f;
// Intermediate Recast area. Its serialized area is ground.
static constexpr unsigned char kPlatformArea = RC_WALKABLE_AREA - 1;
// Intermediate Recast area bit that splits chokepoint polygons from their surroundings. It is
// stripped from the serialized area and becomes WTO_FLAG_CHOKEPOINT.
static constexpr unsigned char kChokeAreaBit = 0x20;
static bool hasCoverGeometry(uint8_t cls) {
return cls == WTO_OBS_HARD_SOLID || cls == WTO_OBS_PLATFORM;
}
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<WtoGeoDownhillLink> downhillLinks;
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 < 1u || 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 (out.hdr.flags & WTO_GEO_FLAG_DOWNHILL_LINKS) {
uint32_t count = 0;
in.read(reinterpret_cast<char *>(&count), sizeof(count));
if (!in || count > UINT16_MAX) return false;
out.downhillLinks.resize(count);
in.read(reinterpret_cast<char *>(out.downhillLinks.data()), count * sizeof(WtoGeoDownhillLink));
for (const auto &link : out.downhillLinks) {
if (!std::all_of(std::begin(link.endpoints), std::end(link.endpoints), [](float v) { return std::isfinite(v); }) ||
!(link.radiusM > 0.0f) || !std::isfinite(link.radiusM) || link.endpoints[1] <= link.endpoints[4] ||
!link.tierMask || link.tierMask >= (1u << WTO_NAV_TIER_COUNT)) return false;
}
}
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;
}
out.chokepointMaxWidthVehicles = readJsonNumber(content, "chokepointMaxWidthVehicles", -1.0f);
out.water = {
readJsonNumber(content, "maxFordDepthM", -1.0f),
readJsonNumber(content, "deepWaterMarginM", -1.0f),
readJsonNumber(content, "deepWaterBankHeightM", -1.0f)
};
if (!(out.chokepointMaxWidthVehicles >= 1.0f && out.chokepointMaxWidthVehicles <= 4.0f) ||
!(out.water.maxFordDepthM >= 0.1f && out.water.maxFordDepthM <= 3.0f) ||
!(out.water.marginM >= 0.0f && out.water.marginM <= 10.0f) ||
!(out.water.bankHeightM >= 0.0f && out.water.bankHeightM <= 10.0f)) {
std::fprintf(stderr, "Invalid navigation 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;
}
static bool hasCoverVoxel(const rcHeightfield &field, float x, float z, float low, float high) {
int gx = (int)std::floor((x - field.bmin[0]) / field.cs);
int gz = (int)std::floor((z - field.bmin[2]) / field.cs);
if (gx < 0 || gz < 0 || gx >= field.width || gz >= field.height) return false;
int first = (int)std::floor((low - field.bmin[1]) / field.ch);
int last = (int)std::ceil((high - field.bmin[1]) / field.ch);
for (const rcSpan *span = field.spans[gx + gz * field.width]; span; span = span->next) {
if ((int)span->smax >= first && (int)span->smin <= last) return true;
}
return false;
}
// The voxel bands only nominate a pose. The final test is done on source geometry after snapping Y.
static bool hasCoverCandidate(const rcHeightfield &field, const GeoData &geo,
float x, float z, float dx, float dz, float baseY) {
float low = baseY + kHullLowerM;
float high = baseY + kHullUpperM;
for (float d = kCoverProbeStartM; d <= kCoverScanM; d += field.cs * 0.85f) {
float px = x + dx * d, pz = z + dz * d;
if (hasCoverVoxel(field, px, pz, low, high) || geo.sampleHeight(px, pz) >= low + 0.35f) 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;
}
/* Turns deep water into a wall before erosion, so walkable ground keeps the tier's radius from it
* like from any obstacle. Returns the indices of the water spans for wallOffWaterBank. */
static std::vector<int> wallOffDeepWater(rcCompactHeightfield &chf) {
std::vector<int> water;
for (int i = 0; i < chf.spanCount; ++i) {
if (chf.areas[i] == WTO_AREA_DEEP_WATER) {
chf.areas[i] = RC_NULL_AREA;
water.push_back(i);
}
}
return water;
}
/* After erosion: removes every span within `reachCells` of deep water (radius plus bank margin)
* whose surface is at most `maxSpanY` (cells), i.e. low bank that slopes into the water. The walk
* follows span connections and stops at higher ground, so bridges, quays and ramps above the
* water line keep only the erosion. Each span keeps the cell of its nearest water source; a span
* is revisited when a closer source reaches it. */
static void wallOffWaterBank(rcCompactHeightfield &chf, const std::vector<int> &water, float reachCells, int maxSpanY) {
if (water.empty() || !(reachCells > 0.0f)) return;
std::vector<int> cellOf(chf.spanCount, -1);
for (int z = 0; z < chf.height; ++z) {
for (int x = 0; x < chf.width; ++x) {
const rcCompactCell &c = chf.cells[x + z * chf.width];
for (int i = (int)c.index, n = (int)(c.index + c.count); i < n; ++i) cellOf[i] = x + z * chf.width;
}
}
const float limit = reachCells * reachCells;
std::vector<int> source(chf.spanCount, -1);
std::vector<float> best(chf.spanCount, FLT_MAX);
std::deque<int> open;
for (int i : water) {
source[i] = cellOf[i];
best[i] = 0.0f;
open.push_back(i);
}
while (!open.empty()) {
const int i = open.front();
open.pop_front();
const int cell = cellOf[i];
const int x = cell % chf.width, z = cell / chf.width;
const int sx = source[i] % chf.width, sz = source[i] / chf.width;
for (int dir = 0; dir < 4; ++dir) {
const int con = rcGetCon(chf.spans[i], dir);
if (con == RC_NOT_CONNECTED) continue;
const int nx = x + rcGetDirOffsetX(dir), nz = z + rcGetDirOffsetY(dir);
const int ni = (int)chf.cells[nx + nz * chf.width].index + con;
const float d2 = (float)((nx - sx) * (nx - sx) + (nz - sz) * (nz - sz));
if (d2 > limit || d2 >= best[ni] || (int)chf.spans[ni].y > maxSpanY) continue;
best[ni] = d2;
source[ni] = source[i];
open.push_back(ni);
}
}
for (int i = 0; i < chf.spanCount; ++i) {
if (best[i] < FLT_MAX) chf.areas[i] = RC_NULL_AREA;
}
}
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 void bakeTileCovers(
const rcCompactHeightfield &field, const rcHeightfield &hard, const GeoData &geo,
const rcConfig &cfg, 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 };
for (const auto &dir : directions) {
float dx = dir[0], dz = dir[1];
int hullHits = 0;
for (int column = -2; column <= 2; ++column) {
float offset = column * kHullColumnSpacingM;
hullHits += hasCoverCandidate(hard, geo, pos.x - dz * offset, pos.z + dx * offset, dx, dz, pos.y);
}
if (hullHits < 4) continue;
WtoCoverPoint pose{};
pose.pos[0] = pos.x; pose.pos[1] = pos.y; pose.pos[2] = pos.z;
pose.coverDir[0] = dx; pose.coverDir[1] = dz;
covers.push_back(pose);
}
}
}
}
}
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_ROUGH) field.areas[i] = WTO_AREA_ROAD;
}
}
}
}
/* Visits the up to eight spans around span `i` at cell (x, z) that it connects to. */
template <typename Fn>
static void forEachNeighborSpan(const rcCompactHeightfield &field, int x, int z, int i, Fn &&fn) {
const rcCompactSpan &span = field.spans[i];
for (int dir = 0; dir < 4; ++dir) {
int con = rcGetCon(span, dir);
if (con == RC_NOT_CONNECTED) continue;
int ax = x + rcGetDirOffsetX(dir);
int az = z + rcGetDirOffsetY(dir);
int ai = (int)field.cells[ax + az * field.width].index + con;
fn(ai, false);
int dir2 = (dir + 1) & 3;
int con2 = rcGetCon(field.spans[ai], dir2);
if (con2 == RC_NOT_CONNECTED) continue;
int bx = ax + rcGetDirOffsetX(dir2);
int bz = az + rcGetDirOffsetY(dir2);
fn((int)field.cells[bx + bz * field.width].index + con2, true);
}
}
/*
* Flags narrow passages on the eroded compact heightfield. Erosion already removed the vehicle's
* own half width, so a span's chamfer distance to the nearest impassable span is the room left
* beside the vehicle. A span lies in a chokepoint when no passable span within reach has at least
* `clearanceM` of room; spans that touch a wall beside open ground keep their plain surface.
*/
static int markChokepointSpans(rcCompactHeightfield &field, float clearanceM) {
auto passable = [](unsigned char area) {
return area != RC_NULL_AREA && area != WTO_AREA_DEEP_WATER && area != WTO_AREA_NO_GO;
};
const int threshold = (int)std::lround(2.0f * clearanceM / field.cs); /* 2 = one cell */
const int reachCells = (int)std::ceil(clearanceM / field.cs) + 1;
const int n = field.spanCount;
std::vector<uint16_t> dist((size_t)n, 0);
for (int i = 0; i < n; ++i) dist[(size_t)i] = passable(field.areas[i]) ? 0xffff : 0;
/* Distances beyond the threshold need not be exact, so relax only as far as it reaches. */
for (int pass = 0; pass <= threshold / 2 + 1; ++pass) {
for (int z = 0; z < field.height; ++z) {
for (int x = 0; x < field.width; ++x) {
const rcCompactCell &cell = field.cells[x + z * field.width];
for (int i = (int)cell.index, end = (int)(cell.index + cell.count); i < end; ++i) {
if (!dist[(size_t)i]) continue;
uint16_t best = dist[(size_t)i];
forEachNeighborSpan(field, x, z, i, [&](int ni, bool diagonal) {
int d = (int)dist[(size_t)ni] + (diagonal ? 3 : 2);
if (d < best) best = (uint16_t)d;
});
dist[(size_t)i] = best;
}
}
}
}
std::vector<uint16_t> room = dist, next((size_t)n);
for (int step = 0; step < reachCells; ++step) {
for (int z = 0; z < field.height; ++z) {
for (int x = 0; x < field.width; ++x) {
const rcCompactCell &cell = field.cells[x + z * field.width];
for (int i = (int)cell.index, end = (int)(cell.index + cell.count); i < end; ++i) {
uint16_t best = room[(size_t)i];
if (dist[(size_t)i]) {
forEachNeighborSpan(field, x, z, i, [&](int ni, bool) {
if (dist[(size_t)ni] && room[(size_t)ni] > best) best = room[(size_t)ni];
});
}
next[(size_t)i] = best;
}
}
}
room.swap(next);
}
int marked = 0;
for (int i = 0; i < n; ++i) {
unsigned char area = field.areas[i];
if (!dist[(size_t)i] || room[(size_t)i] >= threshold || area >= kChokeAreaBit) continue;
field.areas[i] = (unsigned char)(area | kChokeAreaBit);
marked++;
}
return marked;
}
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,
uint32_t tierIndex,
int tx, int tz,
float mapMinX, float mapMinZ,
const CoverBake &coverTuning, bool bakeCovers,
float chokeClearanceM, const WaterBake &water
) {
TileBakeResult res;
res.tile.tx = tx;
res.tile.tz = tz;
const TierSpec &tier = kTiers[tierIndex];
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 + (int)std::ceil(water.marginM / cfg.cs) + 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));
// Erosion walls off the heightfield edge; chokepoint reach must stay clear of that band.
if (chokeClearanceM > 0.0f) {
cfg.borderSize = std::max(cfg.borderSize, cfg.walkableRadius + 2 * (int)std::ceil(chokeClearanceM / cfg.cs) + 4);
}
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 > water.maxFordDepthM) 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_HARD_NO_COVER || 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_PLATFORM || t.cls == WTO_OBS_PLATFORM_NO_COVER) {
float ny = triNormalYRightHanded(v0, v1, v2);
unsigned char area = ny >= cosMaxSlope ? kPlatformArea : RC_NULL_AREA;
rcRasterizeTriangle(&ctx, &v0.x, &v1.x, &v2.x, area, *solid, cfg.walkableClimb);
if (hardHf && hasCoverGeometry(t.cls)) 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 and
* deep water), then keep the bank margin from deep water on top of it. */
const std::vector<int> deepWater = wallOffDeepWater(*chf);
if (!rcErodeWalkableArea(&ctx, cfg.walkableRadius, *chf)) {
rcFreeHeightField(hardHf);
rcFreeCompactHeightfield(chf);
return res;
}
wallOffWaterBank(*chf, deepWater, (tier.agentRadius + water.marginM) / cfg.cs,
(int)std::floor((waterY + water.bankHeightM - cfg.bmin[1]) / cfg.ch));
/* 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, 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 (chokeClearanceM > 0.0f) markChokepointSpans(*chf, chokeClearanceM);
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];
const bool choke = a != RC_NULL_AREA && a < kPlatformArea && (a & kChokeAreaBit);
if (choke) a = pmesh->areas[i] = (unsigned char)(a & ~kChokeAreaBit);
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 == WTO_AREA_ROAD) pmesh->flags[i] = WTO_FLAG_WALK | WTO_FLAG_ROAD;
else if (a == kPlatformArea) {
pmesh->areas[i] = WTO_AREA_GROUND;
pmesh->flags[i] = WTO_FLAG_WALK | WTO_FLAG_PLATFORM;
} else if (a != RC_NULL_AREA) pmesh->flags[i] = WTO_FLAG_WALK;
else pmesh->flags[i] = 0;
if (choke && (pmesh->flags[i] & WTO_FLAG_WALK)) pmesh->flags[i] |= WTO_FLAG_CHOKEPOINT;
}
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;
std::vector<float> endpoints, radii;
std::vector<unsigned short> linkFlags;
std::vector<unsigned char> linkAreas, linkDirections;
std::vector<unsigned int> linkIds;
for (size_t i = 0; i < geo.downhillLinks.size(); ++i) {
const auto &link = geo.downhillLinks[i];
if (!(link.tierMask & (1u << tierIndex))) continue;
float x = link.endpoints[0], z = link.endpoints[2];
if (x < params.bmin[0] || x >= params.bmax[0] || z < params.bmin[2] || z >= params.bmax[2]) continue;
endpoints.insert(endpoints.end(), std::begin(link.endpoints), std::end(link.endpoints));
radii.push_back(link.radiusM);
linkFlags.push_back(WTO_FLAG_WALK | WTO_FLAG_DOWNHILL);
linkAreas.push_back(WTO_AREA_ROUGH);
linkDirections.push_back(0);
linkIds.push_back((unsigned int)i + 1);
}
params.offMeshConCount = (int)linkIds.size();
params.offMeshConVerts = endpoints.data();
params.offMeshConRad = radii.data();
params.offMeshConFlags = linkFlags.data();
params.offMeshConAreas = linkAreas.data();
params.offMeshConDir = linkDirections.data();
params.offMeshConUserID = linkIds.data();
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 bool hasPolygonLink(const dtNavMesh &mesh, dtPolyRef from, dtPolyRef to) {
const dtMeshTile *tile = nullptr;
const dtPoly *poly = nullptr;
if (dtStatusFailed(mesh.getTileAndPolyByRef(from, &tile, &poly))) return false;
for (unsigned int i = poly->firstLink; i != DT_NULL_LINK; i = tile->links[i].next) {
if (tile->links[i].ref == to) return true;
}
return false;
}
static bool verifyDownhillLinks(const dtNavMesh &mesh, const GeoData &geo, uint32_t tierIndex) {
if (geo.downhillLinks.empty()) return true;
std::vector<bool> attached(geo.downhillLinks.size());
for (int i = 0; i < mesh.getMaxTiles(); ++i) {
const dtMeshTile *tile = mesh.getTile(i);
if (!tile || !tile->header) continue;
for (int n = 0; n < tile->header->offMeshConCount; ++n) {
const dtOffMeshConnection &con = tile->offMeshCons[n];
if (con.userId == 0 || con.userId > attached.size() || attached[con.userId - 1] ||
(con.flags & DT_OFFMESH_CON_BIDIR)) return false;
const dtPoly &poly = tile->polys[con.poly];
if ((poly.flags & WTO_FLAG_DOWNHILL) == 0) return false;
dtPolyRef ref = mesh.getPolyRefBase(tile) | con.poly;
dtPolyRef endpoints[2] = {};
for (unsigned int j = poly.firstLink; j != DT_NULL_LINK; j = tile->links[j].next) {
const dtLink &link = tile->links[j];
if (link.edge < 2) endpoints[link.edge] = link.ref;
}
unsigned short startFlags = 0, endFlags = 0;
if (!endpoints[0] || !endpoints[1] || endpoints[0] == endpoints[1] ||
dtStatusFailed(mesh.getPolyFlags(endpoints[0], &startFlags)) ||
dtStatusFailed(mesh.getPolyFlags(endpoints[1], &endFlags)) ||
!(startFlags & WTO_FLAG_WALK) || !(endFlags & WTO_FLAG_WALK) ||
!hasPolygonLink(mesh, endpoints[0], ref) || hasPolygonLink(mesh, endpoints[1], ref)) {
std::fprintf(stderr, "Downhill link %u (%.2f, %.2f -> %.2f, %.2f) unattached on %s.\n", con.userId,
con.pos[0], con.pos[2], con.pos[3], con.pos[5], kTiers[tierIndex].name);
return false;
}
const float *from = &tile->verts[poly.verts[0] * 3];
const float *to = &tile->verts[poly.verts[1] * 3];
if (from[1] <= to[1]) return false;
attached[con.userId - 1] = true;
std::printf(" Downhill link %u on %s: (%.2f, %.2f, %.2f) -> (%.2f, %.2f, %.2f)\n",
con.userId, kTiers[tierIndex].name, from[0], from[1], from[2], to[0], to[1], to[2]);
}
}
for (size_t i = 0; i < geo.downhillLinks.size(); ++i) {
bool expected = (geo.downhillLinks[i].tierMask & (1u << tierIndex)) != 0;
if (expected != (bool)attached[i]) {
std::fprintf(stderr, "Missing downhill link %zu on %s\n", i + 1, kTiers[tierIndex].name);
return false;
}
}
return true;
}
static int countChokepointPolys(const dtNavMesh &mesh) {
int count = 0;
for (int i = 0; i < mesh.getMaxTiles(); ++i) {
const dtMeshTile *tile = mesh.getTile(i);
if (!tile || !tile->header) continue;
for (int p = 0; p < tile->header->polyCount; ++p) {
if (tile->polys[p].flags & WTO_FLAG_CHOKEPOINT) count++;
}
}
return count;
}
struct CoverRay {
float x, z, dx, dz, range;
};
struct CoverSpan {
float bottom, top;
};
// Cut each triangle by the vertical plane through the probe, then clip the cut
// segment to the horizontal ray length. Its Y interval is the silhouette seen
// from the parking point at this column.
static bool coverTriangleSpan(const CoverRay &ray, const Vec3 &a, const Vec3 &b, const Vec3 &c,
CoverSpan &out) {
const Vec3 points[3] = { a, b, c };
float along[3], across[3];
for (int i = 0; i < 3; ++i) {
float x = points[i].x - ray.x, z = points[i].z - ray.z;
along[i] = x * ray.dx + z * ray.dz;
across[i] = z * ray.dx - x * ray.dz;
}
struct CutPoint { float distance, y; };
CutPoint cut[3];
int count = 0;
for (int i = 0; i < 3; ++i) {
const int j = (i + 1) % 3;
if (across[i] == 0.0f) {
cut[count++] = { along[i], points[i].y };
} else if ((across[i] < 0.0f && across[j] > 0.0f) || (across[i] > 0.0f && across[j] < 0.0f)) {
float fraction = across[i] / (across[i] - across[j]);
cut[count++] = {
along[i] + (along[j] - along[i]) * fraction,
points[i].y + (points[j].y - points[i].y) * fraction
};
}
}
if (count != 2) return false;
if (cut[0].distance > cut[1].distance) std::swap(cut[0], cut[1]);
if (cut[1].distance < kCoverProbeStartM || cut[0].distance > ray.range) return false;
float length = cut[1].distance - cut[0].distance;
if (length > kGeometryToleranceM) {
float from = std::max(kCoverProbeStartM, cut[0].distance);
float to = std::min(ray.range, cut[1].distance);
float rise = cut[1].y - cut[0].y;
float y0 = cut[0].y + (from - cut[0].distance) / length * rise;
float y1 = cut[0].y + (to - cut[0].distance) / length * rise;
out = { std::min(y0, y1), std::max(y0, y1) };
} else {
out = { std::min(cut[0].y, cut[1].y), std::max(cut[0].y, cut[1].y) };
}
return true;
}
class CoverGeometry {
public:
explicit CoverGeometry(const GeoData &geo) : geo(geo) {
cols = std::max(1, (int)std::ceil((geo.hdr.boundsMax[0] - geo.hdr.boundsMin[0]) / indexCellM));
rows = std::max(1, (int)std::ceil((geo.hdr.boundsMax[1] - geo.hdr.boundsMin[1]) / indexCellM));
cells.resize((size_t)cols * rows);
for (uint32_t i = 0; i < geo.obsTris.size(); ++i) {
const auto &tri = geo.obsTris[i];
if (!hasCoverGeometry(tri.cls)) continue;
const auto &a = geo.obsVerts[tri.i0];
const auto &b = geo.obsVerts[tri.i1];
const auto &c = geo.obsVerts[tri.i2];
int firstX = column(std::min({ a.x, b.x, c.x }));
int lastX = column(std::max({ a.x, b.x, c.x }));
int firstZ = row(std::min({ a.z, b.z, c.z }));
int lastZ = row(std::max({ a.z, b.z, c.z }));
for (int z = firstZ; z <= lastZ; ++z) {
for (int x = firstX; x <= lastX; ++x) cells[(size_t)z * cols + x].push_back(i);
}
}
}
void collect(const CoverRay &ray, float lower, std::vector<CoverSpan> &spans) const {
spans.clear();
const float endX = ray.x + ray.dx * ray.range;
const float endZ = ray.z + ray.dz * ray.range;
float terrainTop = geo.sampleHeight(endX, endZ);
for (float d = kCoverProbeStartM; d < ray.range; d += kCellSize * 0.85f) {
terrainTop = std::max(terrainTop, geo.sampleHeight(ray.x + ray.dx * d, ray.z + ray.dz * d));
}
if (terrainTop >= lower) spans.push_back({ lower, terrainTop });
const float startX = ray.x + ray.dx * kCoverProbeStartM;
const float startZ = ray.z + ray.dz * kCoverProbeStartM;
const float xmin = std::min(startX, endX), xmax = std::max(startX, endX);
const float zmin = std::min(startZ, endZ), zmax = std::max(startZ, endZ);
const int lastX = column(xmax), lastZ = row(zmax);
for (int z = row(zmin); z <= lastZ; ++z) {
for (int x = column(xmin); x <= lastX; ++x) {
for (uint32_t i : cells[(size_t)z * cols + x]) {
const auto &tri = geo.obsTris[i];
const auto &a = geo.obsVerts[tri.i0];
const auto &b = geo.obsVerts[tri.i1];
const auto &c = geo.obsVerts[tri.i2];
if (std::max({ a.y, b.y, c.y }) < lower ||
std::max({ a.x, b.x, c.x }) < xmin || std::min({ a.x, b.x, c.x }) > xmax ||
std::max({ a.z, b.z, c.z }) < zmin || std::min({ a.z, b.z, c.z }) > zmax) continue;
CoverSpan span;
if (coverTriangleSpan(ray, a, b, c, span) && span.top >= lower) spans.push_back(span);
}
}
}
}
private:
static constexpr float indexCellM = kTileWorldSize / 16.0f;
const GeoData &geo;
int cols = 0, rows = 0;
std::vector<std::vector<uint32_t>> cells;
int column(float x) const { return std::clamp((int)std::floor((x - geo.hdr.boundsMin[0]) / indexCellM), 0, cols - 1); }
int row(float z) const { return std::clamp((int)std::floor((z - geo.hdr.boundsMin[1]) / indexCellM), 0, rows - 1); }
};
static float coverColumnHeight(const CoverGeometry &geometry, const WtoCoverPoint &cover, float offset,
std::vector<CoverSpan> &spans) {
float dx = cover.coverDir[0], dz = cover.coverDir[1];
float lower = cover.pos[1] + kHullLowerM;
geometry.collect({ cover.pos[0] - dz * offset, cover.pos[2] + dx * offset, dx, dz, kCoverScanM }, lower, spans);
std::sort(spans.begin(), spans.end(), [](const CoverSpan &a, const CoverSpan &b) { return a.bottom < b.bottom; });
if (spans.empty() || spans.front().bottom > lower + kGeometryToleranceM) return -std::numeric_limits<float>::infinity();
float top = lower;
for (const auto &span : spans) {
if (span.bottom > top + kGeometryToleranceM) break;
top = std::max(top, span.top);
}
return top - cover.pos[1];
}
static bool coveredSightBand(const CoverGeometry &geometry, const float *pos, const float *direction, float range,
float low, float high, std::vector<CoverSpan> &spans) {
geometry.collect({ pos[0], pos[2], direction[0], direction[1], range }, pos[1] + low, spans);
return std::any_of(spans.begin(), spans.end(), [&](const CoverSpan &span) { return span.bottom <= pos[1] + high; });
}
static bool qualifyCover(WtoCoverPoint &cover, const CoverGeometry &geometry,
const CoverBake &tuning, std::vector<CoverSpan> &spans) {
std::array<float, 5> heights;
for (size_t i = 0; i < heights.size(); ++i) {
heights[i] = coverColumnHeight(geometry, cover, ((int)i - 2) * kHullColumnSpacingM, spans);
}
std::sort(heights.begin(), heights.end(), [](float a, float b) { return a > b; });
// Four columns must each hide the hull through the required height.
if (heights[3] < tuning.minCoverHeightM) return false;
cover.heightM = heights[3];
const bool full = heights[2] >= kTurretLowerM;
if (!full && coveredSightBand(geometry, cover.pos, cover.coverDir, kHullDownSightM, 2.15f, 2.75f, spans)) return false;
cover.kind = full ? WTO_COVER_FULL : WTO_COVER_HULLDOWN;
cover.widthM = 4.0f * kHullColumnSpacingM;
for (float offset : { -kExtraCoverColumnM, kExtraCoverColumnM }) {
if (coverColumnHeight(geometry, cover, offset, spans) >= tuning.minCoverHeightM) cover.widthM += 1.0f;
}
cover.halfAngleDeg = cover.widthM >= 5.0f ? 42.0f : 32.0f;
return true;
}
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 findCornerPeek(WtoCoverPoint &cover, dtNavMeshQuery &query, const dtQueryFilter &filter,
dtPolyRef startRef, const CoverGeometry &geometry, const CoverBake &tuning,
float side, float (&point)[3], std::vector<CoverSpan> &spans) {
dtQueryFilter dry = filter;
dry.setExcludeFlags(filter.getExcludeFlags() | WTO_FLAG_SHALLOW_WATER);
for (float distance = tuning.peekMinM; distance <= tuning.peekMaxM; distance += kCellSize) {
float candidate[3] = {
cover.pos[0] - cover.coverDir[1] * side * distance,
cover.pos[1],
cover.pos[2] + cover.coverDir[0] * side * distance
};
dtPolyRef endRef = verifyCoverPosition(query, dry, candidate);
if (!endRef || !clearCoverCorridor(query, filter, startRef, cover.pos, candidate, endRef)) continue;
if (coveredSightBand(geometry, candidate, cover.coverDir, kPeekSightM, 1.8f, 2.6f, spans)) continue;
std::copy(candidate, candidate + 3, point);
return true;
}
return false;
}
static bool verifyCover(WtoCoverPoint &cover, dtNavMeshQuery &query, const dtQueryFilter &filter,
const CoverGeometry &geometry, const CoverBake &tuning, std::vector<CoverSpan> &spans) {
dtPolyRef startRef = verifyCoverPosition(query, filter, cover.pos);
if (!startRef || !qualifyCover(cover, geometry, tuning, spans)) 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 * tuning.retreatMinM, cover.pos[1], cover.pos[2] + rz * tuning.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;
if (cover.kind == WTO_COVER_FULL) {
cover.hasPeekLeft = findCornerPeek(cover, query, filter, startRef, geometry, tuning, -1.0f, cover.peekLeft, spans);
cover.hasPeekRight = findCornerPeek(cover, query, filter, startRef, geometry, tuning, 1.0f, cover.peekRight, spans);
}
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, const GeoData &geo
) {
dtQueryFilter filter;
filter.setIncludeFlags(WTO_FLAG_WALK);
filter.setExcludeFlags(WTO_FLAG_DEEP_WATER | WTO_FLAG_BLOCKED);
const CoverGeometry geometry(geo);
std::vector<CoverSpan> spans;
std::vector<WtoCoverPoint> usable;
for (WtoCoverPoint cover : raw) {
if (verifyCover(cover, query, filter, geometry, tuning, spans)) 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;
uint32_t previewSize = 1024;
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];
else if (a == "--preview-size") {
char *end = nullptr;
unsigned long size = std::strtoul(argv[i + 1], &end, 10);
if (*end != '\0' || size == 0 || size > 8192) {
std::fprintf(stderr, "Preview size must be between 1 and 8192 pixels.\n");
return 2;
}
previewSize = (uint32_t)size;
}
}
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>] [--preview-size <pixels>]\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);
/* Room beside the vehicle left in a passage exactly chokepointMaxWidthVehicles wide. */
const float chokeClearanceM = (pois.chokepointMaxWidthVehicles - 1.0f) * kTiers[tierIdx].agentRadius;
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], tierIdx, tx, tz, mapMinX, mapMinZ, pois.cover, doCovers,
chokeClearanceM, pois.water);
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 (!verifyDownhillLinks(*meshes[tierIdx], geo, tierIdx)) return 1;
std::printf(" %s (r=%.2fm): tiles=%d/%d polys=%d chokepointPolys=%d prunedIslands=%d\n",
kTiers[tierIdx].name, kTiers[tierIdx].agentRadius, builtCnt, totalTiles, polyCnt,
countChokepointPolys(*meshes[tierIdx]), pruned);
}
/* Dedupe + retreat-verify tank covers on Tier 1 */
std::vector<WtoCoverPoint> covers = filterAndDedupeCovers(rawCovers, *queries[WTO_NAV_TIER_STANDARD], pois.cover, geo);
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);
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 = previewSize, ph = previewSize;
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, Bit 9: platform */
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) {
unsigned short flags = 0;
meshes[ti]->getPolyFlags(ref, &flags);
if (area == WTO_AREA_SHALLOW_WATER) fl |= 8;
if (flags & WTO_FLAG_CHOKEPOINT) fl |= 32;
if (area == WTO_AREA_CRUSHABLE || area == WTO_AREA_FOREST) fl |= 64;
if (area == WTO_AREA_BRIDGE) fl |= 128;
if ((flags & WTO_FLAG_ROAD) || area == WTO_AREA_ROAD) fl |= 256;
if (flags & WTO_FLAG_PLATFORM) fl |= 512;
}
}
}
}
}
/* Deep water is no longer part of any mesh; mark it from the terrain. */
if ((fl & 7u) == 0 && geo.hdr.waterLevel > -1e5f && geo.hdr.waterLevel - gy > pois.water.maxFordDepthM)
fl |= 16;
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));
}
if (!geo.downhillLinks.empty()) {
uint32_t count = (uint32_t)geo.downhillLinks.size();
pout.write(reinterpret_cast<const char *>(&count), sizeof(count));
pout.write(reinterpret_cast<const char *>(geo.downhillLinks.data()), count * sizeof(WtoGeoDownhillLink));
}
}
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;
}