/* * 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 #include #include namespace wtonav { SRWLOCK g_lock = SRWLOCK_INIT; Pack *g_pack; QueryFilter g_filters[WTO_NAV_RT_FILTER_COUNT]; WtoNavStats g_stats; WtoNavTuning g_tuning; int g_cost_tier = -1; int g_cost_group = -1; 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 &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 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)); } /* Traffic counters: one per polygon and group, addressed through each tile slot's first index. */ void init_traffic(Pack *pack, uint32_t tier) { const dtNavMesh *mesh = pack->meshes[tier]; const int max_tiles = mesh->getMaxTiles(); uint32_t total = 0; pack->tileBase[tier].assign((size_t)max_tiles, 0); for (int i = 0; i < max_tiles; i++) { pack->tileBase[tier][(size_t)i] = total; const dtMeshTile *tile = mesh->getTile(i); if (tile != nullptr && tile->header != nullptr) total += (uint32_t)tile->header->polyCount; } for (std::vector &counts : pack->traffic[tier]) counts.assign(total, 0); } 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; } init_traffic(pack, tier); 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 &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 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 curRef, 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_cost_group >= 0 && g_pack != nullptr) { const int at = poly_index(*g_pack, (uint32_t)g_cost_tier, curRef); const uint16_t paths = at >= 0 ? g_pack->traffic[g_cost_tier][g_cost_group][(size_t)at] : 0; if (paths != 0) { const float mul = 1.0f + g_tuning.trafficCostPerPath * (float)paths; cost *= mul < g_tuning.trafficCostMaxMul ? mul : g_tuning.trafficCostMaxMul; } } 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; } int poly_index(const Pack &pack, uint32_t tier, dtPolyRef ref) { if (tier >= WTO_NAV_TIER_COUNT || pack.meshes[tier] == nullptr || ref == 0) return -1; unsigned int salt = 0, tile = 0, poly = 0; pack.meshes[tier]->decodePolyId(ref, salt, tile, poly); const std::vector &base = pack.tileBase[tier]; if (tile >= base.size()) return -1; const size_t at = (size_t)base[tile] + poly; return at < pack.traffic[tier][0].size() ? (int)at : -1; } 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 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_set_tuning(const WtoNavTuning *tuning) { if (tuning == nullptr) return; AcquireSRWLockExclusive(&g_lock); g_tuning = *tuning; if (!(g_tuning.trafficCostPerPath > 0.0f)) g_tuning.trafficCostPerPath = 0.0f; if (!(g_tuning.trafficCostMaxMul >= 1.0f)) g_tuning.trafficCostMaxMul = 1.0f; if (!(g_tuning.trafficHoldSec > 0.0f)) g_tuning.trafficHoldSec = 0.0f; if (!(g_tuning.cornerOffsetM > 0.0f)) g_tuning.cornerOffsetM = 0.0f; ReleaseSRWLockExclusive(&g_lock); } extern "C" void wto_nav_get_stats(WtoNavStats *stats) { AcquireSRWLockExclusive(&g_lock); g_stats.pending = paths_pending_locked(); g_stats.trafficPaths = traffic_paths_locked(); g_stats.dynamic = g_dynamic_count; *stats = g_stats; ReleaseSRWLockExclusive(&g_lock); }