Files
WT-Offline/native/wto-nav/wto_nav_paths.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

403 lines
14 KiB
C++

/*
* Queued path searches (wto_nav_runtime.h): every slot holds at most one request. Requests are
* searched one at a time, oldest first, with Detour's sliced search; wto_nav_pump advances the
* search in small iteration chunks until its per-frame time budget is spent, so one long path
* across a 4 km map spreads over several frames instead of stalling one.
*
* Paths of a traffic group (a team) are remembered per slot for trafficHoldSec: their polygons
* cost more for the group's later searches, so a team spreads over parallel routes instead of
* queueing on one road. Finished corners are pulled away from the edges they turn around, so a
* vehicle cutting a corner does not clip the building the mesh was eroded from.
*/
#include "wto_nav_internal.h"
#include <float.h>
#include <string.h>
namespace wtonav {
namespace {
constexpr int kIterChunk = 64; /* Detour node expansions between budget checks */
constexpr float kStraightCos = 0.985f; /* Corners turning less than ~10 degrees stay put */
constexpr int kCornerRayPolys = 256;
enum class JobState : uint8_t { Empty, Queued, Running, Done };
struct PathJob {
uint32_t ticket;
JobState state;
uint32_t tier;
uint32_t filter;
int group; /* 0-based traffic group, -1 none */
dtPolyRef startRef;
dtPolyRef goalRef;
float startPt[3];
float goalPt[3];
double searchMicros;
uint32_t frames;
uint32_t lastPump;
WtoNavPathResult result;
float corners[WTO_NAV_RT_MAX_CORNERS * 3];
};
/* Polygons of a slot's last finished path while they count as its group's traffic. */
struct Occupancy {
int group = -1;
uint32_t tier = 0;
float until = 0.0f;
std::vector<uint32_t> polys;
};
PathJob g_jobs[WTO_NAV_RT_PATH_SLOTS];
Occupancy g_occupancy[WTO_NAV_RT_PATH_SLOTS];
uint32_t g_next_ticket = 1;
uint32_t g_pump_serial;
float g_pump_now;
int g_active = -1; /* Slot whose search owns its tier's path query */
dtPolyRef g_poly_path[kMaxPathPolys];
dtPolyRef g_corner_refs[WTO_NAV_RT_MAX_CORNERS];
unsigned char g_corner_flags[WTO_NAV_RT_MAX_CORNERS];
dtPolyRef g_ray_polys[kCornerRayPolys];
void release(Occupancy &occ)
{
if (occ.group >= 0 && g_pack != nullptr) {
std::vector<uint16_t> &counts = g_pack->traffic[occ.tier][occ.group];
for (uint32_t at : occ.polys) {
if (at < counts.size() && counts[at] != 0)
counts[at]--;
}
}
occ.group = -1;
occ.polys.clear();
}
void occupy(Occupancy &occ, const PathJob &job, int count)
{
release(occ);
if (job.group < 0 || !(g_tuning.trafficCostPerPath > 0.0f) || !(g_tuning.trafficHoldSec > 0.0f))
return;
std::vector<uint16_t> &counts = g_pack->traffic[job.tier][job.group];
for (int i = 0; i < count; i++) {
const int at = poly_index(*g_pack, job.tier, g_poly_path[i]);
if (at < 0 || counts[(size_t)at] == UINT16_MAX)
continue;
counts[(size_t)at]++;
occ.polys.push_back((uint32_t)at);
}
occ.group = job.group;
occ.tier = job.tier;
occ.until = g_pump_now + g_tuning.trafficHoldSec;
}
void expire_occupancy(float now)
{
for (Occupancy &occ : g_occupancy) {
if (occ.group >= 0 && occ.until < now)
release(occ);
}
}
void normalize_xz(float v[3])
{
v[1] = 0.0f;
const float len = dtMathSqrtf(v[0] * v[0] + v[2] * v[2]);
if (len > 1e-4f) {
v[0] /= len;
v[2] /= len;
} else {
v[0] = v[2] = 0.0f;
}
}
/* Whether the mesh lets a vehicle go straight from `from` (on `ref`) to `to`; `end` gets the
* polygon reached. */
bool open_line(const dtNavMeshQuery *query, const dtQueryFilter &filter, dtPolyRef ref, const float from[3],
const float to[3], dtPolyRef *end)
{
float t = 0.0f, normal[3];
int visited = 0;
if (dtStatusFailed(query->raycast(ref, from, to, &filter, &t, normal, g_ray_polys, &visited, kCornerRayPolys)) ||
t != FLT_MAX || visited <= 0)
return false;
if (end != nullptr)
*end = g_ray_polys[visited - 1];
return true;
}
/* Moves corner i (between corners i-1 and i+1) up to cornerOffsetM away from the edge it turns
* around, keeping both legs and the move itself on the mesh. */
bool push_corner(const dtNavMeshQuery *query, const dtQueryFilter &filter, float *corners, int i, dtPolyRef prev_ref)
{
float *c = corners + i * 3;
const float *p = c - 3, *n = c + 3;
float in[3] = { c[0] - p[0], 0.0f, c[2] - p[2] }, out[3] = { n[0] - c[0], 0.0f, n[2] - c[2] };
normalize_xz(in);
normalize_xz(out);
if (dtVdot2D(in, out) > kStraightCos)
return false;
float push[3] = { in[0] - out[0], 0.0f, in[2] - out[2] };
normalize_xz(push);
for (float scale = 1.0f; scale > 0.2f; scale *= 0.5f) {
const float step = g_tuning.cornerOffsetM * scale;
float moved[3] = { c[0] + push[0] * step, c[1], c[2] + push[2] * step };
dtPolyRef moved_ref = 0;
if (!open_line(query, filter, g_corner_refs[i], c, moved, &moved_ref) ||
!open_line(query, filter, prev_ref, p, moved, nullptr) ||
!open_line(query, filter, moved_ref, moved, n, nullptr))
continue;
float height = 0.0f;
if (dtStatusSucceed(query->getPolyHeight(moved_ref, moved, &height)))
moved[1] = height;
dtVcopy(c, moved);
g_corner_refs[i] = moved_ref;
return true;
}
return false;
}
/* Corners on either end of an off-mesh link (one-way downhill) stay where they are. */
void push_corners(const PathJob &job, float *corners, int count)
{
if (!(g_tuning.cornerOffsetM > 0.0f) || count < 3)
return;
const dtNavMeshQuery *query = g_pack->pointQueries[job.tier];
const QueryFilter &filter = g_filters[job.filter];
for (int i = 1; i < count - 1; i++) {
const bool linked = (g_corner_flags[i] | g_corner_flags[i - 1]) & DT_STRAIGHTPATH_OFFMESH_CONNECTION;
if (!linked && g_corner_refs[i] != 0 && g_corner_refs[i - 1] != 0 &&
push_corner(query, filter, corners, i, g_corner_refs[i - 1]))
g_stats.cornersMoved++;
}
}
void finish(PathJob &job, WtoNavPathStatus status)
{
job.state = JobState::Done;
job.result.status = status;
if (g_pack == nullptr)
return;
g_stats.queries++;
if (status != WTO_NAV_PATH_FULL)
g_stats.failures++;
g_stats.totalMicros += job.searchMicros;
if (job.searchMicros > g_stats.maxMicros)
g_stats.maxMicros = job.searchMicros;
if (job.frames > g_stats.maxFrames)
g_stats.maxFrames = job.frames;
}
/* Snaps start and goal; on success the job is queued, otherwise it is finished. */
void prepare(PathJob &job, const WtoNavPathRequest &req)
{
if (g_pack == nullptr || req.tier >= WTO_NAV_TIER_COUNT || req.filter >= WTO_NAV_RT_FILTER_COUNT || !(req.snapM > 0.0f)) {
finish(job, WTO_NAV_PATH_FAILED);
return;
}
const dtNavMeshQuery *query = g_pack->pointQueries[req.tier];
const QueryFilter &filter = g_filters[req.filter];
if (!snap_to_mesh(query, filter, req.snapM, g_pack->heightSpan, req.start, &job.startRef, job.startPt)) {
finish(job, WTO_NAV_PATH_NO_START);
return;
}
if (!snap_to_mesh(query, filter, req.snapM, g_pack->heightSpan, req.goal, &job.goalRef, job.goalPt)) {
if (!(req.goalSnapM > req.snapM) ||
!snap_to_mesh(query, filter, req.goalSnapM, g_pack->heightSpan, req.goal, &job.goalRef, job.goalPt)) {
finish(job, WTO_NAV_PATH_NO_GOAL);
return;
}
job.result.goalMoved = 1;
}
job.state = JobState::Queued;
}
int next_queued()
{
int best = -1;
for (int i = 0; i < WTO_NAV_RT_PATH_SLOTS; i++) {
if (g_jobs[i].state == JobState::Queued && (best < 0 || g_jobs[i].ticket < g_jobs[best].ticket))
best = i;
}
return best;
}
/* Turns a finished polygon corridor into straight-path corners. */
void finalize(PathJob &job, dtNavMeshQuery *query)
{
int count = 0;
dtStatus status = query->finalizeSlicedFindPath(g_poly_path, &count, kMaxPathPolys);
if (dtStatusFailed(status) || count == 0) {
finish(job, WTO_NAV_PATH_FAILED);
return;
}
const bool partial = dtStatusDetail(status, DT_PARTIAL_RESULT) || g_poly_path[count - 1] != job.goalRef;
float goal[3];
dtVcopy(goal, job.goalPt);
if (partial && dtStatusFailed(query->closestPointOnPoly(g_poly_path[count - 1], job.goalPt, goal, nullptr))) {
finish(job, WTO_NAV_PATH_FAILED);
return;
}
int corners = 0;
status = query->findStraightPath(job.startPt, goal, g_poly_path, count, job.corners, g_corner_flags, g_corner_refs,
&corners, WTO_NAV_RT_MAX_CORNERS, 0);
if (dtStatusFailed(status) || corners == 0) {
finish(job, WTO_NAV_PATH_FAILED);
return;
}
push_corners(job, job.corners, corners);
occupy(g_occupancy[&job - g_jobs], job, count);
float length = 0.0f;
for (int i = 1; i < corners; i++)
length += dtVdist(job.corners + (i - 1) * 3, job.corners + i * 3);
job.result.count = corners;
job.result.lengthM = length;
job.result.truncated = dtStatusDetail(status, DT_BUFFER_TOO_SMALL) ? 1 : 0;
finish(job, partial ? WTO_NAV_PATH_PARTIAL : WTO_NAV_PATH_FULL);
}
/* Starts the oldest queued search; false when nothing is left to search. */
bool start_next()
{
for (;;) {
const int slot = next_queued();
if (slot < 0)
return false;
PathJob &job = g_jobs[slot];
dtNavMeshQuery *query = g_pack->pathQueries[job.tier];
if (dtStatusFailed(query->initSlicedFindPath(job.startRef, job.goalRef, job.startPt, job.goalPt,
&g_filters[job.filter], 0))) {
finish(job, WTO_NAV_PATH_FAILED);
continue;
}
job.state = JobState::Running;
g_active = slot;
return true;
}
}
} // namespace
/* The pack is already replaced: its traffic counters start at zero, so nothing is released. */
void paths_reset_locked()
{
memset(g_jobs, 0, sizeof(g_jobs));
for (Occupancy &occ : g_occupancy) {
occ.group = -1;
occ.polys.clear();
}
g_active = -1;
}
uint32_t traffic_paths_locked()
{
uint32_t paths = 0;
for (const Occupancy &occ : g_occupancy)
paths += occ.group >= 0;
return paths;
}
uint32_t paths_pending_locked()
{
uint32_t pending = 0;
for (const PathJob &job : g_jobs)
pending += job.state == JobState::Queued || job.state == JobState::Running;
return pending;
}
} // namespace wtonav
using namespace wtonav;
extern "C" uint32_t wto_nav_path_request(uint32_t slot, const WtoNavPathRequest *request)
{
if (slot >= WTO_NAV_RT_PATH_SLOTS || request == nullptr)
return 0;
AcquireSRWLockExclusive(&g_lock);
PathJob &job = g_jobs[slot];
if (g_active == (int)slot)
g_active = -1; /* The next initSlicedFindPath discards the abandoned search */
memset(&job, 0, sizeof(job));
release(g_occupancy[slot]); /* A path never counts as traffic against its own replacement */
if (g_next_ticket == 0)
g_next_ticket = 1;
job.ticket = g_next_ticket++;
job.tier = request->tier;
job.filter = request->filter;
job.group = request->group >= 1 && request->group <= WTO_NAV_RT_TRAFFIC_GROUPS ? (int)request->group - 1 : -1;
prepare(job, *request);
const uint32_t ticket = job.ticket;
ReleaseSRWLockExclusive(&g_lock);
return ticket;
}
extern "C" void wto_nav_path_result(uint32_t slot, uint32_t ticket, float *points, int max_points, WtoNavPathResult *result)
{
memset(result, 0, sizeof(*result));
result->status = WTO_NAV_PATH_STALE;
if (slot >= WTO_NAV_RT_PATH_SLOTS || ticket == 0)
return;
AcquireSRWLockShared(&g_lock);
const PathJob &job = g_jobs[slot];
if (job.ticket == ticket) {
if (job.state == JobState::Queued || job.state == JobState::Running) {
result->status = WTO_NAV_PATH_PENDING;
} else if (job.state == JobState::Done) {
*result = job.result;
if (result->count > max_points)
result->count = max_points < 0 ? 0 : max_points;
if (points != nullptr && result->count > 0)
memcpy(points, job.corners, sizeof(float) * 3 * (size_t)result->count);
}
}
ReleaseSRWLockShared(&g_lock);
}
extern "C" void wto_nav_pump(double budget_us, float now)
{
AcquireSRWLockExclusive(&g_lock);
const double began = now_micros();
dynamic_expire_locked(now);
g_pump_serial++;
g_pump_now = now;
expire_occupancy(now);
if (g_pack == nullptr) {
for (PathJob &job : g_jobs) {
if (job.state == JobState::Queued || job.state == JobState::Running)
finish(job, WTO_NAV_PATH_FAILED);
}
g_active = -1;
ReleaseSRWLockExclusive(&g_lock);
return;
}
for (;;) {
if (g_active < 0 && !start_next())
break;
PathJob &job = g_jobs[g_active];
dtNavMeshQuery *query = g_pack->pathQueries[job.tier];
if (job.lastPump != g_pump_serial) {
job.lastPump = g_pump_serial;
job.frames++;
}
const double chunk_began = now_micros();
int done = 0;
g_cost_tier = (int)job.tier;
g_cost_group = g_tuning.trafficCostPerPath > 0.0f ? job.group : -1;
const dtStatus status = query->updateSlicedFindPath(kIterChunk, &done);
g_cost_group = -1;
job.searchMicros += now_micros() - chunk_began;
if (dtStatusFailed(status)) {
finish(job, WTO_NAV_PATH_FAILED);
g_active = -1;
} else if (!dtStatusInProgress(status)) {
finalize(job, query);
g_active = -1;
}
if (now_micros() - began >= budget_us)
break;
}
const double spent = now_micros() - began;
if (spent > g_stats.pumpMaxMicros)
g_stats.pumpMaxMicros = spent;
ReleaseSRWLockExclusive(&g_lock);
}