/* * 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 #include #include #include #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 covers; std::vector 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 &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 &data, uint64_t offset, uint64_t size) { return offset <= data.size() && size <= data.size() - offset; } bool load_tier(const std::vector &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(¶ms, 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(¶ms))) { 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 &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 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 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); }