feat(ground-ai): load baked navigation packs in battle

Statically link upstream Detour into wto_ws.dll with a navigation engine
(native/wto-nav) that loads one .wtonav pack per battle, reads the level
file's eVER fingerprint and answers path queries through a cost filter
that multiplies chokepoint polygons. Start and goal points that do not
sit on the ground are retried over the mesh's height range.

The ground AI script talks to it through call_mission_action("wtoNav")
with load_map, unload_map, find_path and get_stats. Requests are string
parameters; replies use the DataBlock setters local_mp_awards already
resolves, with coordinates as centimetre ints, so no new native site is
needed. The local server writes the battle level into customBots
wtoLevel, and the build writes the pack folder as nav.dir in wto_ws.cfg
(build-game-copy.ts --map-nav).

The first load_map of a battle decides it once: loaded, fallback to the
script's own navigation, or refused when navEngine.allowFallback is off,
in which case bots do not plan or drive. A fingerprint mismatch is
logged and the pack is still used. The script proves the round trip
with one path per team at battle start and logs query statistics.

Add the navEngine, navCostsTracked and navCostsWheeled tuning sections
through the server reader, generated daScript constants and the
launcher's bot tuning page in both languages.

Verified with root and launcher type checks, MSVC builds without
warnings in project code, check-patches 14/14 on 2.61.0.58 and
2.61.0.60, native module resolution 14/14 on 2.61.0.37, .58, .60 and
.64, a scratch game copy build packing 29 ground AI modules, and an
offline run of the engine: all three maps load with matching
fingerprints and every spawn-to-capture path on every tier succeeds.
This commit is contained in:
N0VAN0M4LY committed 2026-12-05 16:39:26 +08:00
1 parent 21ab1084a6
commit e0a344708d
23 files changed
+1280 -14

No files matched your search

+399
View File
@@ -0,0 +1,399 @@
/*
* In-game navigation engine (wto_nav_runtime.h): loads one `.wtonav` pack written by
* tools/navgen/bake into upstream Detour meshes and answers path queries for the ground AI.
*/
#include "wto_nav_runtime.h"
#include "wto_nav_format.h"
#include "DetourAlloc.h"
#include "DetourCommon.h"
#include "DetourNavMesh.h"
#include "DetourNavMeshQuery.h"
#include <windows.h>
#include <stdio.h>
#include <string.h>
#include <vector>
#ifndef DT_VIRTUAL_QUERYFILTER
#error "Detour must be built with DT_VIRTUAL_QUERYFILTER for the chokepoint cost filter"
#endif
namespace {
constexpr int kMaxSearchNodes = 32768;
constexpr int kMaxPathPolys = 4096;
constexpr size_t kMaxPackBytes = 512u * 1024u * 1024u;
constexpr size_t kMaxEverBytes = 64u * 1024u;
constexpr int kMaxLevelBlocks = 4096;
/* Area costs per WtoPolyArea, times a multiplier on chokepoint polygons. */
class WtoQueryFilter : public dtQueryFilter {
public:
float chokepointMul = 1.0f;
float 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 override
{
float cost = dtVdist(pa, pb) * getAreaCost(curPoly->getArea());
if (curPoly->flags & WTO_FLAG_CHOKEPOINT)
cost *= chokepointMul;
return cost;
}
};
struct Pack {
float heightSpan = 0.0f; /* Vertical extent of the mesh bounds */
dtNavMesh *meshes[WTO_NAV_TIER_COUNT] = {};
dtNavMeshQuery *queries[WTO_NAV_TIER_COUNT] = {};
std::vector<WtoCoverPoint> covers;
std::vector<WtoTacticalCell> tactical;
};
SRWLOCK g_lock = SRWLOCK_INIT;
Pack *g_pack;
WtoQueryFilter g_filters[WTO_NAV_RT_FILTER_COUNT];
bool g_filters_ready;
WtoNavStats g_stats;
void init_filters_locked()
{
if (g_filters_ready)
return;
for (WtoQueryFilter &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->queries[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 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;
}
pack->queries[tier] = dtAllocNavMeshQuery();
if (pack->queries[tier] == nullptr || dtStatusFailed(pack->queries[tier]->init(pack->meshes[tier], kMaxSearchNodes))) {
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;
}
/*
* Nearest polygon within `snap` metres; mission points (spawn and capture zone centres) carry
* heights that are not on the ground, so a miss is retried over the mesh's whole height range,
* still within `snap` horizontally.
*/
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;
}
WtoNavPathStatus find_path_locked(uint32_t tier, uint32_t filter_index, float snap_radius_m,
const float start[3], const float goal[3],
float *points, int max_points, int *count, float *length_m)
{
if (g_pack == nullptr || tier >= WTO_NAV_TIER_COUNT || filter_index >= WTO_NAV_RT_FILTER_COUNT ||
points == nullptr || max_points < 2 || !(snap_radius_m > 0.0f))
return WTO_NAV_PATH_FAILED;
dtNavMeshQuery *query = g_pack->queries[tier];
const WtoQueryFilter &filter = g_filters[filter_index];
dtPolyRef start_ref = 0, goal_ref = 0;
float start_pt[3], goal_pt[3];
if (!snap_to_mesh(query, filter, snap_radius_m, g_pack->heightSpan, start, &start_ref, start_pt))
return WTO_NAV_PATH_NO_START;
if (!snap_to_mesh(query, filter, snap_radius_m, g_pack->heightSpan, goal, &goal_ref, goal_pt))
return WTO_NAV_PATH_NO_GOAL;
static dtPolyRef path[kMaxPathPolys];
int path_count = 0;
dtStatus status = query->findPath(start_ref, goal_ref, start_pt, goal_pt, &filter, path, &path_count, kMaxPathPolys);
if (dtStatusFailed(status) || path_count == 0)
return WTO_NAV_PATH_FAILED;
bool partial = dtStatusDetail(status, DT_PARTIAL_RESULT) || path[path_count - 1] != goal_ref;
if (partial && dtStatusFailed(query->closestPointOnPoly(path[path_count - 1], goal, goal_pt, nullptr)))
return WTO_NAV_PATH_FAILED;
int corners = 0;
status = query->findStraightPath(start_pt, goal_pt, path, path_count, points, nullptr, nullptr, &corners, max_points, 0);
if (dtStatusFailed(status) || corners == 0)
return WTO_NAV_PATH_FAILED;
float length = 0.0f;
for (int i = 1; i < corners; i++)
length += dtVdist(points + (i - 1) * 3, points + i * 3);
*count = corners;
*length_m = length;
return partial ? WTO_NAV_PATH_PARTIAL : WTO_NAV_PATH_FULL;
}
} // namespace
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_load(const wchar_t *pack_path, const uint8_t *level_sha1, WtoNavLoadInfo *info)
{
std::vector<uint8_t> data;
Pack *pack = nullptr;
memset(info, 0, sizeof(*info));
if (level_sha1 != nullptr) {
info->fingerprintKnown = 1;
memcpy(info->levelSha1, level_sha1, sizeof(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 && level_sha1 != nullptr)
info->fingerprintMatch = memcmp(info->packSha1, level_sha1, sizeof(info->packSha1)) == 0;
AcquireSRWLockExclusive(&g_lock);
init_filters_locked();
free_pack(g_pack);
g_pack = pack;
memset(&g_stats, 0, sizeof(g_stats));
g_stats.loaded = pack != nullptr;
ReleaseSRWLockExclusive(&g_lock);
}
extern "C" void wto_nav_unload(void)
{
AcquireSRWLockExclusive(&g_lock);
free_pack(g_pack);
g_pack = nullptr;
g_stats.loaded = 0;
ReleaseSRWLockExclusive(&g_lock);
}
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" WtoNavPathStatus wto_nav_find_path(uint32_t tier, uint32_t filter, float snap_radius_m,
const float start[3], const float goal[3],
float *points, int max_points, int *count, float *length_m)
{
*count = 0;
*length_m = 0.0f;
AcquireSRWLockExclusive(&g_lock);
const double began = now_micros();
const WtoNavPathStatus status = find_path_locked(tier, filter, snap_radius_m, start, goal, points, max_points, count, length_m);
const double spent = now_micros() - began;
if (g_pack != nullptr) {
g_stats.queries++;
g_stats.totalMicros += spent;
if (spent > g_stats.maxMicros)
g_stats.maxMicros = spent;
if (status != WTO_NAV_PATH_FULL)
g_stats.failures++;
}
ReleaseSRWLockExclusive(&g_lock);
return status;
}
extern "C" void wto_nav_get_stats(WtoNavStats *stats)
{
AcquireSRWLockShared(&g_lock);
*stats = g_stats;
ReleaseSRWLockShared(&g_lock);
}
+86
View File
@@ -0,0 +1,86 @@
/*
* In-game navigation engine: one baked `.wtonav` pack (tools/navgen) held for the battle in
* progress, queried through upstream Detour. The C side (wto-net local_mp_nav.c) owns the
* daScript request protocol; this interface only knows packs, levels and paths.
*
* Every function is safe to call from any thread; queries are serialized internally.
*/
#pragma once
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
#define WTO_NAV_RT_AREA_COUNT 12 /* WtoPolyArea values 0..11 */
#define WTO_NAV_RT_FILTER_COUNT 2 /* 0 tracked, 1 wheeled */
/* Detour traversal costs for one vehicle class, indexed by WtoPolyArea. */
typedef struct WtoNavCosts {
float area[WTO_NAV_RT_AREA_COUNT];
float chokepointMul; /* Multiplies the area cost on WTO_FLAG_CHOKEPOINT polygons */
} WtoNavCosts;
typedef enum WtoNavLoadResult {
WTO_NAV_LOAD_OK = 0,
WTO_NAV_LOAD_MISSING, /* No pack file for the level */
WTO_NAV_LOAD_UNREADABLE, /* The file exists but cannot be read */
WTO_NAV_LOAD_CORRUPT, /* Bad header, offsets or Detour tile data */
} WtoNavLoadResult;
typedef struct WtoNavLoadInfo {
WtoNavLoadResult result;
int fingerprintKnown; /* 1 when the level file's eVER SHA-1 was read */
int fingerprintMatch; /* 1 when it equals the pack's; meaningful only when known */
uint8_t packSha1[20];
uint8_t levelSha1[20];
uint32_t tiers;
uint32_t covers;
uint32_t polys[3];
char detail[96]; /* Why loading failed, for the log */
} WtoNavLoadInfo;
typedef enum WtoNavPathStatus {
WTO_NAV_PATH_FULL = 0,
WTO_NAV_PATH_PARTIAL, /* Ends at the reachable polygon closest to the goal */
WTO_NAV_PATH_NO_START, /* Start not within the snap radius of the mesh */
WTO_NAV_PATH_NO_GOAL,
WTO_NAV_PATH_FAILED, /* No pack loaded, bad tier or Detour failure */
} WtoNavPathStatus;
typedef struct WtoNavStats {
int loaded;
uint32_t queries;
uint32_t failures;
double totalMicros;
double maxMicros;
} WtoNavStats;
/* Reads the eVER SHA-1 of a Dagor level file (levels/<name>.bin) without loading the level. */
int wto_nav_read_level_fingerprint(const wchar_t *level_path, uint8_t sha1[20]);
/*
* Loads `pack_path`, replacing any loaded pack. `level_sha1` is the fingerprint of the level the
* game runs (NULL when unknown); a mismatch is reported but never refuses the pack.
*/
void wto_nav_load(const wchar_t *pack_path, const uint8_t *level_sha1, WtoNavLoadInfo *info);
void wto_nav_unload(void);
int wto_nav_is_loaded(void);
/* Replaces the traversal costs of one filter (0 tracked, 1 wheeled). */
void wto_nav_set_costs(uint32_t filter, const WtoNavCosts *costs);
/*
* Straight-line corners from `start` to `goal` on the mesh of `tier` (0 narrow, 1 standard,
* 2 wide). `points` receives up to `max_points` xyz triples; the first is the snapped start.
*/
WtoNavPathStatus wto_nav_find_path(uint32_t tier, uint32_t filter, float snap_radius_m,
const float start[3], const float goal[3],
float *points, int max_points, int *count, float *length_m);
void wto_nav_get_stats(WtoNavStats *stats);
#ifdef __cplusplus
}
#endif
+22 -5
View File
@@ -5,6 +5,8 @@
Output: <Out>\wto_ws.dll (default build\native). Static C runtime (/MT), so the DLL needs
nothing but the system's ws2_32.dll. MinHook comes from native\third_party\minhook (BSD-2).
The ground AI navigation engine (native\wto-nav) links upstream Detour from
native\third_party\recastnavigation (zlib), compiled separately at its own warning level.
#>
param([string]$Out = (Join-Path $PSScriptRoot '..\..\build\native'))
$ErrorActionPreference = 'Stop'
@@ -16,19 +18,34 @@ $vcvars = Join-Path $vs 'VC\Auxiliary\Build\vcvars64.bat'
$src = Join-Path $PSScriptRoot 'src'
$mh = Join-Path $PSScriptRoot '..\third_party\minhook'
$nav = Join-Path $PSScriptRoot '..\wto-nav'
$dt = Join-Path $PSScriptRoot '..\third_party\recastnavigation\Detour'
New-Item -ItemType Directory -Force $Out | Out-Null
$obj = Join-Path $Out 'obj'
New-Item -ItemType Directory -Force $obj | Out-Null
$dtObj = Join-Path $obj 'detour'
New-Item -ItemType Directory -Force $dtObj | Out-Null
$sources = @(
function Quote($paths) { $paths | ForEach-Object { '"' + (Resolve-Path $_) + '"' } }
$sources = Quote @(
"$src\dll_main.c", "$src\hook_config.c", "$src\redirect_rules.c", "$src\resolver_hooks.c", "$src\connection_hooks.c",
"$src\local_mp_core.c", "$src\local_mp_values.c", "$src\local_mp_players.c", "$src\local_mp_loadout.c", "$src\local_mp_actions.c", "$src\local_mp_awards.c", "$src\local_mp_kills.c", "$src\local_mp_events.c", "$src\local_mp_scores.c", "$src\local_mp_nuke.c", "$src\local_mp_support.c",
"$src\local_mp_damage_notifications.c", "$src\local_mp_air_events.c", "$src\local_mp_ground_ai.c", "$src\local_mp_zones.c",
"$src\local_mp_damage_notifications.c", "$src\local_mp_air_events.c", "$src\local_mp_ground_ai.c", "$src\local_mp_nav.c", "$src\local_mp_zones.c",
"$nav\wto_nav_runtime.cpp",
"$mh\src\hook.c", "$mh\src\buffer.c", "$mh\src\trampoline.c", "$mh\src\hde\hde64.c"
) | ForEach-Object { '"' + (Resolve-Path $_) + '"' }
)
$detourSources = Quote (Get-ChildItem "$dt\Source\*.cpp").FullName
$detourObjects = (Get-ChildItem "$dt\Source\*.cpp") | ForEach-Object { '"' + (Join-Path $dtObj ($_.BaseName + '.obj')) + '"' }
# Every translation unit that sees dtQueryFilter must agree on its layout (wto_nav_runtime.cpp).
$detourFlags = "/DDT_VIRTUAL_QUERYFILTER /I`"$dt\Include`""
$command = "`"$vcvars`" >nul && cl /nologo /LD /O2 /MT /W4 /wd4100 /D_CRT_SECURE_NO_WARNINGS /DWIN32_LEAN_AND_MEAN " +
"/I`"$mh\include`" /Fo`"$obj\\`" $($sources -join ' ') /Fe`"$Out\wto_ws.dll`" " +
$detour = "`"$vcvars`" >nul && cl /nologo /c /O2 /MT /EHsc /W3 $detourFlags /Fo`"$dtObj\\`" $($detourSources -join ' ')"
cmd /c $detour
if ($LASTEXITCODE -ne 0) { throw "cl (Detour) failed with $LASTEXITCODE" }
$command = "`"$vcvars`" >nul && cl /nologo /LD /O2 /MT /EHsc /W4 /wd4100 /D_CRT_SECURE_NO_WARNINGS /DWIN32_LEAN_AND_MEAN $detourFlags " +
"/I`"$mh\include`" /I`"$nav`" /Fo`"$obj\\`" $($sources -join ' ') $($detourObjects -join ' ') /Fe`"$Out\wto_ws.dll`" " +
"/link /DEF:`"$src\wto_ws.def`" ws2_32.lib"
cmd /c $command
if ($LASTEXITCODE -ne 0) { throw "cl failed with $LASTEXITCODE" }
+16 -1
View File
@@ -9,6 +9,7 @@
* exe.size_of_image=0x...
* native.<name>=<value> what the LocalMP modules need from the executable: RVAs of
* functions and globals, structure offsets (local_mp_values.c)
* nav.dir=<folder> optional, UTF-8: where the ground AI finds <level>.wtonav packs
*
* wto_ws.log: which host names were answered locally and which connections were redirected or
* refused, so a run shows every address the game tried (the audit handover 6.2 asks for).
@@ -32,6 +33,7 @@ typedef struct NativeValue {
} NativeValue;
static wchar_t g_folder[MAX_PATH];
static wchar_t g_nav_dir[MAX_PATH];
static CRITICAL_SECTION g_log_lock;
static FILE *g_log;
static int g_log_enabled = 1;
@@ -87,10 +89,16 @@ static void read_native_value(const char *line)
g_native_count++;
}
static void read_nav_dir(const char *utf8)
{
if (MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8, -1, g_nav_dir, MAX_PATH) == 0)
g_nav_dir[0] = L'\0';
}
static void read_settings(void)
{
wchar_t path[MAX_PATH];
char line[160];
char line[1024];
FILE *file;
if (_snwprintf_s(path, MAX_PATH, _TRUNCATE, L"%swto_ws.cfg", g_folder) < 0)
return;
@@ -108,10 +116,17 @@ static void read_settings(void)
parse_value(line + 18, &g_exe_size_of_image);
else if (strncmp(line, NATIVE_PREFIX, sizeof(NATIVE_PREFIX) - 1) == 0)
read_native_value(line);
else if (strncmp(line, "nav.dir=", 8) == 0)
read_nav_dir(line + 8);
}
fclose(file);
}
const wchar_t *config_nav_dir(void)
{
return g_nav_dir;
}
int config_native_value(const char *name, int64_t *value)
{
size_t i;
+2
View File
@@ -13,3 +13,5 @@ void describe_address(const struct sockaddr *name, int length, char *text, size_
int config_native_value(const char *name, int64_t *value);
/* Whether the settings were resolved for the executable this process runs (PE time stamp and size). */
int config_native_matches_executable(void);
/* Folder of the ground AI navigation packs (wto_ws.cfg "nav.dir="); empty when not configured. */
const wchar_t *config_nav_dir(void);
+8
View File
@@ -19,6 +19,7 @@
#define SCRIPT_READY_ACTION "wtoGroundAiScriptReady"
#define DRIVE_CONTROL_ACTION "wtoGroundAiDriveControl"
#define NAV_ACTION "wtoNav"
typedef void (__fastcall *MissionActionFn)(const char *name, const void *blk);
typedef uint8_t *(__fastcall *AsGroundModelFn)(uint8_t *unit);
@@ -139,6 +140,11 @@ static void __fastcall hook_mission_action(const char *name, const void *blk)
}
return;
}
if (name != NULL && strcmp(name, NAV_ACTION) == 0) {
/* The script's request block doubles as the reply (local_mp_nav.c). */
local_mp_nav_request((void *)blk);
return;
}
if (name == NULL || strcmp(name, DRIVE_CONTROL_ACTION) != 0) {
orig_mission_action(name, blk);
return;
@@ -162,6 +168,8 @@ void local_mp_ground_ai_update(float dt)
if (orig_mission_action == NULL)
return;
hosting = local_mp_is_host();
if (!hosting)
local_mp_nav_session_ended();
AcquireSRWLockExclusive(&control_lock);
for (i = 0; i < sizeof(controls) / sizeof(controls[0]); i++) {
GroundAiDriveControl *control = &controls[i];
+4
View File
@@ -112,3 +112,7 @@ void local_mp_zones_reset(void);
int install_local_mp_air_event_hooks(void);
int install_local_mp_ground_ai_hooks(void);
void local_mp_ground_ai_update(float dt);
/* "wtoNav" requests of the ground AI script and the battle's navigation pack (local_mp_nav.c). */
void local_mp_nav_request(void *blk);
void local_mp_nav_session_ended(void);
+352
View File
@@ -0,0 +1,352 @@
/*
* "wtoNav" requests of the ground AI script (call_mission_action, local_mp_ground_ai.c) and the
* battle's navigation pack (native/wto-nav). The script fills a DataBlock with the request, this
* module answers synchronously by writing into the same block:
*
* op=load_map allowFallback="0|1", tracked/wheeled costs t_<area>, w_<area>
* -> state=loaded|fallback|failed, fingerprint=match|mismatch|unknown, level,
* reason, tiers, covers
* op=unload_map -> ok
* op=find_path tier, filter (0 tracked, 1 wheeled), max, snap, sx..sz, gx..gz
* -> status=full|partial|no_start|no_goal|failed, count, lenCm,
* p<i>x/p<i>y/p<i>z in centimetres (ints)
* op=get_stats -> loaded, queries, failures, avgUs, maxUs
*
* Request values are strings: the script only uses the DataBlock string add it already relies on.
* Replies are ints and strings written with the setters local_mp_awards resolves.
*
* The level comes from the mission settings (customBots wtoLevel, written by the local server),
* the pack folder from wto_ws.cfg (nav.dir). Whether the battle uses the pack, falls back to the
* script's own navigation or refuses to drive is decided by the first load_map of the battle and
* kept until unload_map or the end of the session; it never changes in the middle of a battle.
*/
#include "hook_config.h"
#include "local_mp_internal.h"
#include "local_mp_offsets.h"
#include "local_mp_values.h"
#include "wto_nav_runtime.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NAV_MAX_POINTS 96
#define NAV_LEVEL_MAX 64
typedef void (__fastcall *BlkSetStrFn)(void *blk, const char *name, const char *value);
typedef void (__fastcall *BlkSetIntFn)(void *blk, const char *name, const int32_t *value);
typedef void (__fastcall *BlkToOwnedFn)(void *blk);
typedef enum NavDecision {
NAV_UNDECIDED = 0,
NAV_LOADED,
NAV_FALLBACK,
NAV_FAILED,
} NavDecision;
typedef struct NavBattle {
NavDecision decision;
char level[NAV_LEVEL_MAX];
char fingerprint[16];
char reason[96];
uint32_t tiers;
uint32_t covers;
} NavBattle;
/* Costs in the order of WtoPolyArea; empty names are areas the mesh never carries. */
static const char *const AREA_KEYS[WTO_NAV_RT_AREA_COUNT] = {
"", "road", "bridge", "ground", "rough", "forest", "crushable", "shallowWater", "", "exposed", "", "",
};
static NavBattle g_battle;
static SRWLOCK g_battle_lock = SRWLOCK_INIT;
static LONG g_missing_values_logged;
static int values_ready(void)
{
if (g_lmp.blk_set_str && g_lmp.blk_set_int && g_lmp.blk_to_owned &&
g_lmp_datablock_get_str && g_local_mp_mission_settings)
return 1;
if (InterlockedExchange(&g_missing_values_logged, 1) == 0)
log_line("WTO_NAV|UNAVAILABLE|reason=DataBlock setters of local_mp_awards not resolved");
return 0;
}
static void set_str(void *blk, const char *name, const char *value)
{
((BlkSetStrFn)g_lmp.blk_set_str)(blk, name, value ? value : "");
}
/* Integer setters expect an owned DataBlock (as in local_mp_awards.c). */
static void set_int(void *blk, const char *name, int32_t value)
{
if (*(int32_t *)((uint8_t *)blk + LMP_BLK_OFF_OWNED_STATE) != -1)
((BlkToOwnedFn)g_lmp.blk_to_owned)(blk);
((BlkSetIntFn)g_lmp.blk_set_int)(blk, name, &value);
}
static float get_real(const void *blk, const char *name, float def)
{
const char *text = g_lmp_datablock_get_str(blk, name, "");
char *end;
float value;
if (text == NULL || text[0] == '\0')
return def;
value = strtof(text, &end);
return (*end == '\0' && value == value) ? value : def;
}
static long get_long(const void *blk, const char *name, long def)
{
const char *text = g_lmp_datablock_get_str(blk, name, "");
char *end;
long value;
if (text == NULL || text[0] == '\0')
return def;
value = strtol(text, &end, 10);
return *end == '\0' ? value : def;
}
static int32_t to_cm(float metres)
{
const float cm = metres * 100.0f;
if (cm > 2.0e9f)
return INT32_MAX;
if (cm < -2.0e9f)
return INT32_MIN;
return (int32_t)(cm >= 0.0f ? cm + 0.5f : cm - 0.5f);
}
static void hex20(const uint8_t *sha1, char out[41])
{
static const char digits[] = "0123456789abcdef";
int i;
for (i = 0; i < 20; i++) {
out[i * 2] = digits[sha1[i] >> 4];
out[i * 2 + 1] = digits[sha1[i] & 15];
}
out[40] = '\0';
}
/* "levels/avg_berlin.bin" -> "avg_berlin"; only names the bake could have produced. */
static int battle_level(char out[NAV_LEVEL_MAX])
{
const char *path = g_lmp_datablock_get_str(g_local_mp_mission_settings + LMP_MIS_OFF_CUSTOM_BOTS, "wtoLevel", "");
const char *name, *dot;
size_t len, i;
if (path == NULL || path[0] == '\0')
return 0;
name = strrchr(path, '/');
name = name ? name + 1 : path;
dot = strrchr(name, '.');
len = dot ? (size_t)(dot - name) : strlen(name);
if (len == 0 || len >= NAV_LEVEL_MAX)
return 0;
for (i = 0; i < len; i++) {
const char c = name[i];
if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_'))
return 0;
out[i] = c;
}
out[len] = '\0';
return 1;
}
/* <game>\levels\<level>.bin, the game folder being the parent of the executable's win64 folder. */
static int level_file_path(const char *level, wchar_t *out, size_t out_count)
{
wchar_t exe[MAX_PATH];
wchar_t *slash;
DWORD length = GetModuleFileNameW(NULL, exe, MAX_PATH);
int i;
if (length == 0 || length >= MAX_PATH)
return 0;
for (i = 0; i < 2; i++) {
slash = wcsrchr(exe, L'\\');
if (slash == NULL)
return 0;
*slash = L'\0';
}
return _snwprintf_s(out, out_count, _TRUNCATE, L"%s\\levels\\%S.bin", exe, level) > 0;
}
static void read_costs(const void *blk, const char *prefix, WtoNavCosts *costs)
{
char key[48];
int area;
for (area = 0; area < WTO_NAV_RT_AREA_COUNT; area++) {
costs->area[area] = 1.0f;
if (AREA_KEYS[area][0] == '\0')
continue;
snprintf(key, sizeof(key), "%s_%s", prefix, AREA_KEYS[area]);
costs->area[area] = get_real(blk, key, 1.0f);
if (!(costs->area[area] > 0.0f))
costs->area[area] = 1.0f;
}
snprintf(key, sizeof(key), "%s_chokepoint", prefix);
costs->chokepointMul = get_real(blk, key, 1.0f);
if (!(costs->chokepointMul > 0.0f))
costs->chokepointMul = 1.0f;
}
static void decide_locked(const void *blk, int allow_fallback)
{
wchar_t pack[MAX_PATH], level_path[MAX_PATH];
const wchar_t *dir = config_nav_dir();
uint8_t level_sha1[20];
int have_level_sha1 = 0;
WtoNavLoadInfo info;
double began = (double)GetTickCount64();
WtoNavCosts costs;
memset(&info, 0, sizeof(info));
if (!battle_level(g_battle.level)) {
snprintf(g_battle.reason, sizeof(g_battle.reason), "battle level unknown (customBots wtoLevel)");
} else if (dir[0] == L'\0') {
snprintf(g_battle.reason, sizeof(g_battle.reason), "no pack folder (wto_ws.cfg nav.dir)");
} else if (_snwprintf_s(pack, MAX_PATH, _TRUNCATE, L"%s\\%S.wtonav", dir, g_battle.level) <= 0) {
snprintf(g_battle.reason, sizeof(g_battle.reason), "pack path too long");
} else {
have_level_sha1 = level_file_path(g_battle.level, level_path, MAX_PATH) &&
wto_nav_read_level_fingerprint(level_path, level_sha1);
read_costs(blk, "t", &costs);
wto_nav_set_costs(0, &costs);
read_costs(blk, "w", &costs);
wto_nav_set_costs(1, &costs);
wto_nav_load(pack, have_level_sha1 ? level_sha1 : NULL, &info);
if (info.result != WTO_NAV_LOAD_OK)
snprintf(g_battle.reason, sizeof(g_battle.reason), "%s", info.detail);
}
if (info.result == WTO_NAV_LOAD_OK && g_battle.reason[0] == '\0') {
char expected[41], actual[41];
g_battle.decision = NAV_LOADED;
g_battle.tiers = info.tiers;
g_battle.covers = info.covers;
snprintf(g_battle.fingerprint, sizeof(g_battle.fingerprint), "%s",
!info.fingerprintKnown ? "unknown" : info.fingerprintMatch ? "match" : "mismatch");
hex20(info.packSha1, expected);
hex20(info.levelSha1, actual);
if (info.fingerprintKnown && !info.fingerprintMatch)
log_line("WTO_NAV|FINGERPRINT_MISMATCH|level=%s|expected=%s|actual=%s", g_battle.level, expected, actual);
log_line("WTO_NAV|LOADED|level=%s|fingerprint=%s|tiers=%u|covers=%u|polys=%u/%u/%u|ms=%.0f",
g_battle.level, g_battle.fingerprint, info.tiers, info.covers,
info.polys[0], info.polys[1], info.polys[2], (double)GetTickCount64() - began);
return;
}
snprintf(g_battle.fingerprint, sizeof(g_battle.fingerprint), "unknown");
g_battle.decision = allow_fallback ? NAV_FALLBACK : NAV_FAILED;
if (allow_fallback)
log_line("WTO_NAV|FALLBACK_STOCK_NAV|level=%s|reason=%s", g_battle.level, g_battle.reason);
else
log_line("WTO_NAV|LOAD_FAILED_NO_FALLBACK|level=%s|reason=%s", g_battle.level, g_battle.reason);
}
static void load_map(void *blk)
{
static const char *const STATES[] = { "", "loaded", "fallback", "failed" };
const int allow_fallback = get_long(blk, "allowFallback", 1) != 0;
AcquireSRWLockExclusive(&g_battle_lock);
if (g_battle.decision == NAV_UNDECIDED)
decide_locked(blk, allow_fallback);
set_str(blk, "state", STATES[g_battle.decision]);
set_str(blk, "fingerprint", g_battle.fingerprint);
set_str(blk, "level", g_battle.level);
set_str(blk, "reason", g_battle.reason);
set_int(blk, "tiers", (int32_t)g_battle.tiers);
set_int(blk, "covers", (int32_t)g_battle.covers);
ReleaseSRWLockExclusive(&g_battle_lock);
}
static void unload_locked(const char *why)
{
if (g_battle.decision == NAV_UNDECIDED)
return;
if (wto_nav_is_loaded()) {
WtoNavStats stats;
wto_nav_get_stats(&stats);
log_line("WTO_NAV|UNLOADED|level=%s|why=%s|queries=%u|failures=%u|avgUs=%.0f|maxUs=%.0f",
g_battle.level, why, stats.queries, stats.failures,
stats.queries ? stats.totalMicros / stats.queries : 0.0, stats.maxMicros);
wto_nav_unload();
}
memset(&g_battle, 0, sizeof(g_battle));
}
static void find_path(void *blk)
{
static const char *const STATUS[] = { "full", "partial", "no_start", "no_goal", "failed" };
float points[NAV_MAX_POINTS * 3];
const float start[3] = { get_real(blk, "sx", 0.0f), get_real(blk, "sy", 0.0f), get_real(blk, "sz", 0.0f) };
const float goal[3] = { get_real(blk, "gx", 0.0f), get_real(blk, "gy", 0.0f), get_real(blk, "gz", 0.0f) };
const long tier = get_long(blk, "tier", -1), filter = get_long(blk, "filter", 0);
long max = get_long(blk, "max", NAV_MAX_POINTS);
int count = 0, i;
float length = 0.0f;
char key[16];
WtoNavPathStatus status;
if (max < 2 || max > NAV_MAX_POINTS)
max = NAV_MAX_POINTS;
status = (tier < 0 || filter < 0) ? WTO_NAV_PATH_FAILED
: wto_nav_find_path((uint32_t)tier, (uint32_t)filter, get_real(blk, "snap", 0.0f),
start, goal, points, (int)max, &count, &length);
set_str(blk, "status", STATUS[status]);
set_int(blk, "count", count);
set_int(blk, "lenCm", to_cm(length));
for (i = 0; i < count; i++) {
snprintf(key, sizeof(key), "p%dx", i);
set_int(blk, key, to_cm(points[i * 3]));
snprintf(key, sizeof(key), "p%dy", i);
set_int(blk, key, to_cm(points[i * 3 + 1]));
snprintf(key, sizeof(key), "p%dz", i);
set_int(blk, key, to_cm(points[i * 3 + 2]));
}
}
static void get_stats(void *blk)
{
WtoNavStats stats;
wto_nav_get_stats(&stats);
set_int(blk, "loaded", stats.loaded);
set_int(blk, "queries", (int32_t)stats.queries);
set_int(blk, "failures", (int32_t)stats.failures);
set_int(blk, "avgUs", stats.queries ? (int32_t)(stats.totalMicros / stats.queries) : 0);
set_int(blk, "maxUs", (int32_t)stats.maxMicros);
}
void local_mp_nav_request(void *blk)
{
const char *op;
if (blk == NULL || !values_ready())
return;
op = g_lmp_datablock_get_str(blk, "op", "");
if (op == NULL)
return;
if (strcmp(op, "find_path") == 0) {
find_path(blk);
} else if (strcmp(op, "load_map") == 0) {
load_map(blk);
} else if (strcmp(op, "unload_map") == 0) {
AcquireSRWLockExclusive(&g_battle_lock);
unload_locked("battle ended");
ReleaseSRWLockExclusive(&g_battle_lock);
set_int(blk, "ok", 1);
} else if (strcmp(op, "get_stats") == 0) {
get_stats(blk);
} else {
log_line("WTO_NAV|BAD_REQUEST|op=%s", op);
}
}
void local_mp_nav_session_ended(void)
{
if (TryAcquireSRWLockExclusive(&g_battle_lock)) {
unload_locked("session ended");
ReleaseSRWLockExclusive(&g_battle_lock);
}
}