Files
WT-Offline/native/wto-nav/wto_nav_paths.cpp
T
N0VAN0M4LY ba947fe5b6 feat(ground-ai): follow baked navmesh paths with sliced searches
Native engine (native/wto-nav):
- Path searches are queued per slot and advanced with Detour's sliced
  search inside a per-frame time budget (navEngine.pathBudgetMsPerFrame),
  so a 4 km search no longer stalls a frame. The synchronous find_path
  op is gone.
- The battle's pack is read on a background thread when the mission
  finishes loading (prefetch); load_map only takes the result.
- New mesh queries: probe (surface, flags, room to the mesh edge),
  raycast, nearest walkable point, and dynamic cost circles for wrecks,
  jams and fresh obstacles that later searches route around.

Ground AI scripts:
- route picks the mesh tier by vehicle width and the cost filter by
  tracked or wheeled, plans on goal change, drift off the corridor, a
  timer or reported obstacles, and falls back to the stock road mesh
  only when the battle decided on the fallback.
- follow steers at a speed-scaled lookahead point and brakes ahead of
  sharp corners, narrow passages and the destination.
- avoid casts rays from both front hull corners that drive through
  objects the bake marks crushable, follows slower traffic, steps aside
  or yields by size priority in narrow passages.
- unstick escalates deterministically: back up along the corridor, mark
  a jam and replan, then log the spot and hand the order back.
- Flank lanes are built through the queued searches; rallies are not
  released while their lanes are still being built.
- Removed the 9-arc forward probing, 7-arc reverse probing, 145 m
  straight shortcuts, 165 m snapping and random sideways detours.

Tuning: new pathFollow section, navEngine.goalSnapRadiusM and
pathBudgetMsPerFrame, navBake.crushableMaxRiExtraHp passed to the
scripts; retired navigation.cornerBrakeAccel, stuckWindowSec,
stuckMinMoveM and unstickReverseSec. Launcher fields and en/zh-CN labels
updated.

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, offline engine
run on avg_poland (prefetch, sliced searches within budget, slot
replacement, dynamic costs), isolated game copy build. daScript
compilation and in-battle behaviour still need the in-game run.
2026-12-05 17:38:41 +08:00

247 lines
8.1 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.
*/
#include "wto_nav_internal.h"
#include <string.h>
namespace wtonav {
namespace {
constexpr int kIterChunk = 64; /* Detour node expansions between budget checks */
enum class JobState : uint8_t { Empty, Queued, Running, Done };
struct PathJob {
uint32_t ticket;
JobState state;
uint32_t tier;
uint32_t filter;
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];
};
PathJob g_jobs[WTO_NAV_RT_PATH_SLOTS];
uint32_t g_next_ticket = 1;
uint32_t g_pump_serial;
int g_active = -1; /* Slot whose search owns its tier's path query */
dtPolyRef g_poly_path[kMaxPathPolys];
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, nullptr, nullptr,
&corners, WTO_NAV_RT_MAX_CORNERS, 0);
if (dtStatusFailed(status) || corners == 0) {
finish(job, WTO_NAV_PATH_FAILED);
return;
}
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
void paths_reset_locked()
{
memset(g_jobs, 0, sizeof(g_jobs));
g_active = -1;
}
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));
if (g_next_ticket == 0)
g_next_ticket = 1;
job.ticket = g_next_ticket++;
job.tier = request->tier;
job.filter = request->filter;
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++;
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;
const dtStatus status = query->updateSlicedFindPath(kIterChunk, &done);
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);
}