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

433 lines
15 KiB
C++

/*
* In-game navigation engine (wto_nav_runtime.h): loads one `.wtonav` pack written by
* tools/navgen/bake into upstream Detour meshes, optionally on a background thread while the
* battle is still loading. Path searches live in wto_nav_paths.cpp, point queries and dynamic
* costs in wto_nav_queries.cpp.
*/
#include "wto_nav_internal.h"
#include "DetourAlloc.h"
#include <stdio.h>
#include <string.h>
#include <string>
namespace wtonav {
SRWLOCK g_lock = SRWLOCK_INIT;
Pack *g_pack;
QueryFilter g_filters[WTO_NAV_RT_FILTER_COUNT];
WtoNavStats g_stats;
namespace {
constexpr size_t kMaxPackBytes = 512u * 1024u * 1024u;
constexpr size_t kMaxEverBytes = 64u * 1024u;
constexpr int kMaxLevelBlocks = 4096;
bool g_filters_ready;
/* A pack read on a background thread, waiting for wto_nav_load. Guarded by g_stage_lock. */
struct Staged {
std::wstring packPath;
std::wstring levelPath;
HANDLE thread = nullptr;
Pack *pack = nullptr;
WtoNavLoadInfo info = {};
};
SRWLOCK g_stage_lock = SRWLOCK_INIT;
Staged *g_staged;
void init_filters_locked()
{
if (g_filters_ready)
return;
for (QueryFilter &filter : g_filters) {
filter.setIncludeFlags(WTO_FLAG_WALK);
filter.setExcludeFlags(WTO_FLAG_DEEP_WATER | WTO_FLAG_BLOCKED);
}
g_filters_ready = true;
}
void free_pack(Pack *pack)
{
if (pack == nullptr)
return;
for (uint32_t t = 0; t < WTO_NAV_TIER_COUNT; t++) {
dtFreeNavMeshQuery(pack->pathQueries[t]);
dtFreeNavMeshQuery(pack->pointQueries[t]);
dtFreeNavMesh(pack->meshes[t]);
}
delete pack;
}
bool read_file(const wchar_t *path, std::vector<uint8_t> &out, WtoNavLoadInfo *info)
{
FILE *file = nullptr;
if (_wfopen_s(&file, path, L"rb") != 0 || file == nullptr) {
info->result = GetFileAttributesW(path) == INVALID_FILE_ATTRIBUTES ? WTO_NAV_LOAD_MISSING : WTO_NAV_LOAD_UNREADABLE;
snprintf(info->detail, sizeof(info->detail), "%s", info->result == WTO_NAV_LOAD_MISSING ? "no pack file" : "cannot open pack");
return false;
}
bool ok = _fseeki64(file, 0, SEEK_END) == 0;
long long size = ok ? _ftelli64(file) : -1;
ok = ok && size > 0 && (unsigned long long)size <= kMaxPackBytes && _fseeki64(file, 0, SEEK_SET) == 0;
if (ok) {
out.resize((size_t)size);
ok = fread(out.data(), 1, out.size(), file) == out.size();
}
fclose(file);
if (!ok) {
info->result = WTO_NAV_LOAD_UNREADABLE;
snprintf(info->detail, sizeof(info->detail), "cannot read pack (%lld bytes)", size);
}
return ok;
}
bool fits(const std::vector<uint8_t> &data, uint64_t offset, uint64_t size)
{
return offset <= data.size() && size <= data.size() - offset;
}
bool init_queries(Pack *pack, uint32_t tier)
{
pack->pathQueries[tier] = dtAllocNavMeshQuery();
pack->pointQueries[tier] = dtAllocNavMeshQuery();
return pack->pathQueries[tier] != nullptr && pack->pointQueries[tier] != nullptr &&
dtStatusSucceed(pack->pathQueries[tier]->init(pack->meshes[tier], kPathSearchNodes)) &&
dtStatusSucceed(pack->pointQueries[tier]->init(pack->meshes[tier], kPointSearchNodes));
}
bool load_tier(const std::vector<uint8_t> &data, const WtoNavHeader &hdr, uint32_t tier, Pack *pack, uint32_t *polys, char *detail, size_t detail_size)
{
uint64_t at = hdr.tierOffsets[tier];
const uint64_t end = at + hdr.tierSizes[tier];
dtNavMeshParams params;
uint32_t tile_count = 0;
if (!fits(data, at, hdr.tierSizes[tier]) || hdr.tierSizes[tier] < sizeof(params) + sizeof(tile_count)) {
snprintf(detail, detail_size, "tier %u outside the file", tier);
return false;
}
memcpy(&params, data.data() + at, sizeof(params));
at += sizeof(params);
memcpy(&tile_count, data.data() + at, sizeof(tile_count));
at += sizeof(tile_count);
pack->meshes[tier] = dtAllocNavMesh();
if (pack->meshes[tier] == nullptr || dtStatusFailed(pack->meshes[tier]->init(&params))) {
snprintf(detail, detail_size, "tier %u mesh parameters rejected", tier);
return false;
}
for (uint32_t i = 0; i < tile_count; i++) {
uint32_t size = 0;
if (at + sizeof(size) > end) {
snprintf(detail, detail_size, "tier %u tile %u header truncated", tier, i);
return false;
}
memcpy(&size, data.data() + at, sizeof(size));
at += sizeof(size);
if (size == 0 || at + size > end) {
snprintf(detail, detail_size, "tier %u tile %u truncated", tier, i);
return false;
}
unsigned char *tile = (unsigned char *)dtAlloc(size, DT_ALLOC_PERM);
if (tile == nullptr) {
snprintf(detail, detail_size, "out of memory for tier %u", tier);
return false;
}
memcpy(tile, data.data() + at, size);
at += size;
if (dtStatusFailed(pack->meshes[tier]->addTile(tile, (int)size, DT_TILE_FREE_DATA, 0, nullptr))) {
dtFree(tile);
snprintf(detail, detail_size, "tier %u tile %u rejected by Detour", tier, i);
return false;
}
*polys += (uint32_t)((const dtMeshHeader *)tile)->polyCount;
}
if (!init_queries(pack, tier)) {
snprintf(detail, detail_size, "tier %u query init failed", tier);
return false;
}
return true;
}
Pack *parse_pack(const std::vector<uint8_t> &data, WtoNavLoadInfo *info)
{
WtoNavHeader hdr;
if (data.size() < sizeof(hdr)) {
snprintf(info->detail, sizeof(info->detail), "file shorter than the header");
return nullptr;
}
memcpy(&hdr, data.data(), sizeof(hdr));
if (memcmp(hdr.magic, WTO_NAV_MAGIC, sizeof(hdr.magic)) != 0 || hdr.version != WTO_NAV_VERSION ||
hdr.tierCount != WTO_NAV_TIER_COUNT) {
snprintf(info->detail, sizeof(info->detail), "not a version %u pack", WTO_NAV_VERSION);
return nullptr;
}
const uint64_t cover_bytes = (uint64_t)hdr.coverCount * sizeof(WtoCoverPoint);
const uint64_t tac_bytes = (uint64_t)hdr.tacCols * hdr.tacRows * sizeof(WtoTacticalCell);
if (!fits(data, hdr.coverOffset, cover_bytes) || !fits(data, hdr.tacOffset, tac_bytes)) {
snprintf(info->detail, sizeof(info->detail), "cover or tactical grid outside the file");
return nullptr;
}
memcpy(info->packSha1, hdr.everSha1, sizeof(info->packSha1));
Pack *pack = new Pack();
pack->heightSpan = hdr.bmax[1] - hdr.bmin[1];
for (uint32_t t = 0; t < WTO_NAV_TIER_COUNT; t++) {
if (!load_tier(data, hdr, t, pack, &info->polys[t], info->detail, sizeof(info->detail))) {
free_pack(pack);
return nullptr;
}
}
pack->covers.resize(hdr.coverCount);
if (cover_bytes != 0)
memcpy(pack->covers.data(), data.data() + hdr.coverOffset, (size_t)cover_bytes);
pack->tactical.resize((size_t)hdr.tacCols * hdr.tacRows);
if (tac_bytes != 0)
memcpy(pack->tactical.data(), data.data() + hdr.tacOffset, (size_t)tac_bytes);
info->tiers = WTO_NAV_TIER_COUNT;
info->covers = hdr.coverCount;
return pack;
}
/* Reads and parses a pack plus the level fingerprint; runs on any thread, touches no globals. */
Pack *read_pack(const wchar_t *pack_path, const wchar_t *level_path, WtoNavLoadInfo *info)
{
const double began = now_micros();
std::vector<uint8_t> data;
Pack *pack = nullptr;
memset(info, 0, sizeof(*info));
if (level_path != nullptr && level_path[0] != L'\0')
info->fingerprintKnown = wto_nav_read_level_fingerprint(level_path, info->levelSha1);
if (read_file(pack_path, data, info)) {
pack = parse_pack(data, info);
info->result = pack != nullptr ? WTO_NAV_LOAD_OK : WTO_NAV_LOAD_CORRUPT;
}
if (pack != nullptr && info->fingerprintKnown)
info->fingerprintMatch = memcmp(info->packSha1, info->levelSha1, sizeof(info->packSha1)) == 0;
info->readMs = (now_micros() - began) / 1000.0;
return pack;
}
DWORD WINAPI prefetch_main(void *arg)
{
Staged *staged = (Staged *)arg;
staged->pack = read_pack(staged->packPath.c_str(), staged->levelPath.c_str(), &staged->info);
return 0;
}
/* Waits for the background read of `staged` and frees what it produced. */
void discard_staged(Staged *staged)
{
if (staged == nullptr)
return;
if (staged->thread != nullptr) {
WaitForSingleObject(staged->thread, INFINITE);
CloseHandle(staged->thread);
}
free_pack(staged->pack);
delete staged;
}
/* Takes the staged pack if it is `pack_path`; the caller then owns (and joins) it. */
Staged *take_staged(const wchar_t *pack_path)
{
AcquireSRWLockExclusive(&g_stage_lock);
Staged *staged = g_staged;
if (staged != nullptr && staged->packPath == pack_path)
g_staged = nullptr;
else
staged = nullptr;
ReleaseSRWLockExclusive(&g_stage_lock);
return staged;
}
void replace_pack(Pack *pack)
{
AcquireSRWLockExclusive(&g_lock);
init_filters_locked();
free_pack(g_pack);
g_pack = pack;
paths_reset_locked();
dynamic_reset_locked();
memset(&g_stats, 0, sizeof(g_stats));
g_stats.loaded = pack != nullptr;
ReleaseSRWLockExclusive(&g_lock);
}
} // namespace
float QueryFilter::getCost(const float *pa, const float *pb,
const dtPolyRef, const dtMeshTile *, const dtPoly *,
const dtPolyRef, const dtMeshTile *, const dtPoly *curPoly,
const dtPolyRef, const dtMeshTile *, const dtPoly *) const
{
float cost = dtVdist(pa, pb) * getAreaCost(curPoly->getArea());
if (curPoly->flags & WTO_FLAG_CHOKEPOINT)
cost *= chokepointMul;
if (g_dynamic_count != 0) {
const float mx = (pa[0] + pb[0]) * 0.5f, mz = (pa[2] + pb[2]) * 0.5f;
float mul = 1.0f;
for (uint32_t i = 0; i < g_dynamic_count; i++) {
const DynamicCost &d = g_dynamic[i];
const float dx = mx - d.pos[0], dz = mz - d.pos[2];
if (dx * dx + dz * dz < d.radius * d.radius && d.mul > mul)
mul = d.mul;
}
cost *= mul;
}
return cost;
}
bool snap_to_mesh(const dtNavMeshQuery *query, const dtQueryFilter &filter, float snap, float height_span,
const float point[3], dtPolyRef *ref, float nearest[3])
{
const float near_extents[3] = { snap, snap, snap };
if (dtStatusSucceed(query->findNearestPoly(point, near_extents, &filter, ref, nearest)) && *ref != 0)
return true;
const float column_extents[3] = { snap, height_span > snap ? height_span : snap, snap };
return dtStatusSucceed(query->findNearestPoly(point, column_extents, &filter, ref, nearest)) && *ref != 0;
}
double now_micros()
{
static LARGE_INTEGER frequency;
LARGE_INTEGER counter;
if (frequency.QuadPart == 0)
QueryPerformanceFrequency(&frequency);
QueryPerformanceCounter(&counter);
return (double)counter.QuadPart * 1e6 / (double)frequency.QuadPart;
}
} // namespace wtonav
using namespace wtonav;
extern "C" int wto_nav_read_level_fingerprint(const wchar_t *level_path, uint8_t sha1[20])
{
FILE *file = nullptr;
uint8_t header[12];
int found = 0;
if (level_path == nullptr || _wfopen_s(&file, level_path, L"rb") != 0 || file == nullptr)
return 0;
if (fread(header, 1, sizeof(header), file) != sizeof(header) || memcmp(header, "DBLD3x64", 8) != 0) {
fclose(file);
return 0;
}
/* Tagged top-level blocks: u32 length (low 30 bits, tag included), 4-byte NUL-padded tag. */
for (int block = 0; block < kMaxLevelBlocks && !found; block++) {
uint32_t len_flags = 0;
char tag[4];
if (fread(&len_flags, 1, 4, file) != 4 || fread(tag, 1, 4, file) != 4)
break;
const uint32_t len = len_flags & 0x3FFFFFFFu;
if (len < 4)
break;
if (memcmp(tag, "\0END", 4) == 0)
break;
if (memcmp(tag, "eVER", 4) != 0) {
if (_fseeki64(file, (long long)len - 4, SEEK_CUR) != 0)
break;
continue;
}
/* Exporter version string (u32 length, bytes padded to 4), section count, level SHA-1. */
std::vector<uint8_t> body(len - 4 <= kMaxEverBytes ? len - 4 : 0);
if (body.empty() || fread(body.data(), 1, body.size(), file) != body.size())
break;
uint32_t text_len = 0;
memcpy(&text_len, body.data(), body.size() >= 4 ? 4 : 0);
const size_t at = 4 + (((size_t)text_len + 3u) & ~(size_t)3u);
if (body.size() >= 4 && at + 4 + 20 <= body.size()) {
memcpy(sha1, body.data() + at + 4, 20);
found = 1;
}
break;
}
fclose(file);
return found;
}
extern "C" void wto_nav_prefetch(const wchar_t *pack_path, const wchar_t *level_path)
{
if (pack_path == nullptr || pack_path[0] == L'\0')
return;
AcquireSRWLockExclusive(&g_stage_lock);
if (g_staged != nullptr && g_staged->packPath == pack_path) {
ReleaseSRWLockExclusive(&g_stage_lock);
return;
}
Staged *previous = g_staged;
Staged *staged = new Staged();
staged->packPath = pack_path;
staged->levelPath = level_path != nullptr ? level_path : L"";
staged->thread = CreateThread(nullptr, 0, prefetch_main, staged, 0, nullptr);
if (staged->thread == nullptr) {
delete staged;
staged = nullptr;
}
g_staged = staged;
ReleaseSRWLockExclusive(&g_stage_lock);
discard_staged(previous);
}
extern "C" void wto_nav_load(const wchar_t *pack_path, const wchar_t *level_path, WtoNavLoadInfo *info)
{
const double began = now_micros();
Staged *staged = take_staged(pack_path);
Pack *pack;
if (staged != nullptr) {
WaitForSingleObject(staged->thread, INFINITE);
CloseHandle(staged->thread);
staged->thread = nullptr;
pack = staged->pack;
staged->pack = nullptr;
*info = staged->info;
info->prefetched = 1;
discard_staged(staged);
} else {
pack = read_pack(pack_path, level_path, info);
}
info->waitMs = (now_micros() - began) / 1000.0;
replace_pack(pack);
}
extern "C" void wto_nav_unload(void)
{
replace_pack(nullptr);
}
extern "C" int wto_nav_is_loaded(void)
{
AcquireSRWLockShared(&g_lock);
const int loaded = g_pack != nullptr;
ReleaseSRWLockShared(&g_lock);
return loaded;
}
extern "C" void wto_nav_set_costs(uint32_t filter, const WtoNavCosts *costs)
{
if (filter >= WTO_NAV_RT_FILTER_COUNT || costs == nullptr)
return;
AcquireSRWLockExclusive(&g_lock);
init_filters_locked();
for (int area = 0; area < WTO_NAV_RT_AREA_COUNT; area++)
g_filters[filter].setAreaCost(area, costs->area[area]);
g_filters[filter].chokepointMul = costs->chokepointMul;
ReleaseSRWLockExclusive(&g_lock);
}
extern "C" void wto_nav_get_stats(WtoNavStats *stats)
{
AcquireSRWLockExclusive(&g_lock);
g_stats.pending = paths_pending_locked();
g_stats.dynamic = g_dynamic_count;
*stats = g_stats;
ReleaseSRWLockExclusive(&g_lock);
}