diff --git a/src/common/mmaps_common/Management/MMapManager.cpp b/src/common/mmaps_common/Management/MMapManager.cpp index beeef5acbe..a9115ba460 100644 --- a/src/common/mmaps_common/Management/MMapManager.cpp +++ b/src/common/mmaps_common/Management/MMapManager.cpp @@ -24,6 +24,8 @@ #include "Memory.h" #include #include +#include +#include namespace MMAP { @@ -60,10 +62,24 @@ namespace MMAP } }; - // One query per map instance per thread, kept for the life of the thread so its node pool is allocated once. + // Tile lock: see NavMeshReadLock in the header. + std::shared_mutex g_tileLock; + thread_local uint32 t_readLockDepth = 0; + + // Bumped by every unloadMapInstance, so a thread drops the queries it kept for map instances that may be gone. + std::atomic g_instanceUnloads{ 0 }; + + // One query per map instance per thread, kept so its node pool is allocated once. dtNavMeshQuery const* GetThreadNavMeshQuery(ThreadQueryKey const& key, dtNavMesh const* navMesh) { thread_local std::unordered_map, ThreadQueryKeyHash> queries; + thread_local uint32 seenUnloads = 0; + if (uint32 const unloads = g_instanceUnloads.load(std::memory_order_relaxed); unloads != seenUnloads) + { + // ~350 KB each: a long-lived thread that visits many dungeons would otherwise keep one per instance it ever saw + seenUnloads = unloads; + std::erase_if(queries, [&](auto const& entry) { return !(entry.first == key); }); + } std::unique_ptr& query = queries[key]; if (query && query->getAttachedNavMesh() == navMesh) return query.get(); @@ -93,6 +109,30 @@ namespace MMAP { return t_threadQueries; } + + NavMeshReadLock::NavMeshReadLock() + { + if (t_readLockDepth++ == 0) + g_tileLock.lock_shared(); + } + + NavMeshReadLock::~NavMeshReadLock() + { + if (--t_readLockDepth == 0) + g_tileLock.unlock_shared(); + } + + NavMeshTileChangeLock::NavMeshTileChangeLock() + { + // a thread waiting for its own read lock to go away would wait forever + ASSERT(t_readLockDepth == 0, "navmesh tile change on a thread that holds a NavMeshReadLock"); + g_tileLock.lock(); + } + + NavMeshTileChangeLock::~NavMeshTileChangeLock() + { + g_tileLock.unlock(); + } using MMapTileSet = std::unordered_map; struct MMapMapData @@ -193,6 +233,13 @@ namespace MMAP MMapDataSet::iterator itr = loadedMMaps.find(mapId); ASSERT(itr != loadedMMaps.end(), "Invalid mapId %u passed to MMapManager after startup in thread unsafe environment", mapId); + // the usual case (every grid load asks): a plain lookup, nothing changes + if (itr->second->FindMeshData(mapId, instanceId) != itr->second->meshData.end()) + return LoadResult::AlreadyLoaded; + + // adding a mesh changes meshData, which bot logic threads read in GetNavMesh / GetNavMeshQuery + NavMeshTileChangeLock tileChange; + auto [meshItr, needsLoading] = itr->second->GetMeshData(mapId, instanceId); if (!needsLoading) return LoadResult::AlreadyLoaded; @@ -361,6 +408,9 @@ namespace MMAP dtMeshHeader* header = static_cast(data.get()); dtTileRef tileRef = 0; + // the file is read; only the tile insert itself waits for searches from other threads + NavMeshTileChangeLock tileChange; + // memory allocated for data is now managed by detour, and will be deallocated when the tile is removed if (dtStatusSucceed(meshData.navMesh.addTile(static_cast(data.release()), fileHeader.size, DT_TILE_FREE_DATA, 0, &tileRef))) { @@ -393,6 +443,8 @@ namespace MMAP return false; } + NavMeshTileChangeLock tileChange; // navMeshQueries is read by GetNavMeshQuery on bot logic threads + auto [queryItr, inserted] = mmap->navMeshQueries.try_emplace({ instanceMapId, instanceId }); if (!inserted) return true; @@ -541,6 +593,7 @@ namespace MMAP MMapData* mmap = itr->second.get(); std::lock_guard lock(mmap->loadLock); + NavMeshTileChangeLock tileChange; uint32 packedGridPos = packTileID(x, y); for (auto& [instanceId, meshData] : mmap->meshData) { @@ -581,6 +634,7 @@ namespace MMAP } std::lock_guard lock(itr->second->loadLock); + NavMeshTileChangeLock tileChange; if (!isRebuildingTilesEnabledOnMap(mapId)) { @@ -620,6 +674,8 @@ namespace MMAP MMapData* mmap = itr->second.get(); std::lock_guard lock(mmap->loadLock); + NavMeshTileChangeLock tileChange; + g_instanceUnloads.fetch_add(1, std::memory_order_relaxed); std::size_t erased = mmap->navMeshQueries.erase({ instanceMapId, instanceId }); if (!erased) TC_LOG_DEBUG("maps", "MMAP:unloadMapInstance: Asked to unload not loaded dtNavMeshQuery mapId {:04} instanceId {}", instanceMapId, instanceId); @@ -654,6 +710,10 @@ namespace MMAP if (itr == loadedMMaps.end()) return nullptr; + std::optional readLock; // another thread's map may be adding a mesh right now + if (t_threadQueries) + readLock.emplace(); + MeshDataMap::iterator meshItr = itr->second->FindMeshData(mapId, instanceId); if (meshItr == itr->second->meshData.end()) return nullptr; @@ -667,6 +727,10 @@ namespace MMAP if (itr == loadedMMaps.end()) return nullptr; + std::optional readLock; // another thread's map may be adding an instance right now + if (t_threadQueries) + readLock.emplace(); + auto queryItr = itr->second->navMeshQueries.find({ instanceMapId, instanceId }); if (queryItr == itr->second->navMeshQueries.end()) return nullptr; diff --git a/src/common/mmaps_common/Management/MMapManager.h b/src/common/mmaps_common/Management/MMapManager.h index 3826cedc9c..8d78fced84 100644 --- a/src/common/mmaps_common/Management/MMapManager.h +++ b/src/common/mmaps_common/Management/MMapManager.h @@ -89,8 +89,9 @@ namespace MMAP // While one of these is alive on a thread, GetNavMeshQuery called on that thread returns a dtNavMeshQuery that belongs to // the thread (same navmesh, same node pool size as the shared one) instead of the one query each map instance shares. - // Several threads can then search paths on the same map at the same time. The navmesh itself is still shared, so this is - // only safe while no tile of it is loaded or unloaded, i.e. outside the map updates. + // Several threads can then search paths on the same map at the same time. The navmesh itself is still shared, so a search + // must not overlap a tile load or unload: either it runs outside the map updates, or it holds a NavMeshReadLock. + // While the scope is active, GetNavMeshQuery and GetNavMesh take the NavMeshReadLock for their own lookup. class TC_MMAPS_COMMON_API ScopedThreadNavMeshQuery { public: @@ -104,6 +105,30 @@ namespace MMAP private: bool _previous; }; + + // Searches from a thread that is not a map update thread (bot logic threads) run while the map threads load and unload + // navmesh tiles. Every tile or mesh change takes the tile lock exclusively (MMapManager does it itself; code that swaps + // tiles on its own, like the dynamic tile builder, holds a NavMeshTileChangeLock). Such a search holds a NavMeshReadLock + // (the same lock, shared) for its whole length, together with a ScopedThreadNavMeshQuery. A map thread searching its own + // map needs neither: its own tile changes happen between its own searches. + // Nested read locks on one thread are counted, only the outermost one locks. + class TC_MMAPS_COMMON_API NavMeshReadLock + { + public: + NavMeshReadLock(); + ~NavMeshReadLock(); + NavMeshReadLock(NavMeshReadLock const&) = delete; + NavMeshReadLock& operator=(NavMeshReadLock const&) = delete; + }; + + class TC_MMAPS_COMMON_API NavMeshTileChangeLock + { + public: + NavMeshTileChangeLock(); + ~NavMeshTileChangeLock(); + NavMeshTileChangeLock(NavMeshTileChangeLock const&) = delete; + NavMeshTileChangeLock& operator=(NavMeshTileChangeLock const&) = delete; + }; } #endif diff --git a/src/server/game/Maps/DynamicMMapTileBuilder.cpp b/src/server/game/Maps/DynamicMMapTileBuilder.cpp index 7471c56c03..35329df6c1 100644 --- a/src/server/game/Maps/DynamicMMapTileBuilder.cpp +++ b/src/server/game/Maps/DynamicMMapTileBuilder.cpp @@ -226,6 +226,7 @@ bool InvokeAsyncCallbackIfReady(TileBuildRequest& request) { TC_LOG_INFO("maps.mmapgen", "[Map {:04}] [{:02},{:02}]: Swapping new tile", request.Id.TerrainMapId, request.Id.Y, request.Id.X); + MMAP::NavMeshTileChangeLock tileChange; // searches from bot logic threads must not see a half-swapped tile request.NavMesh->removeTile(tileRef, nullptr, nullptr); unsigned char* data = static_cast(dtAlloc(tileResult.size, DT_ALLOC_PERM)); diff --git a/src/server/game/Maps/TerrainMgr.cpp b/src/server/game/Maps/TerrainMgr.cpp index be8f47c876..16cf48656c 100644 --- a/src/server/game/Maps/TerrainMgr.cpp +++ b/src/server/game/Maps/TerrainMgr.cpp @@ -107,7 +107,11 @@ namespace for (HandcraftedRoadSegment const& s : segs) roadSegs.push_back({ s.fromX, s.fromY, s.toX, s.toY, s.width }); - std::size_t const tagged = Road::ApplyCorridorsToNavmesh(*navMesh, roadSegs); + std::size_t tagged = 0; + { + MMAP::NavMeshTileChangeLock tileChange; // retags polys that bot logic threads may be searching right now + tagged = Road::ApplyCorridorsToNavmesh(*navMesh, roadSegs); + } { std::lock_guard lock(g_handcraftedRoadAppliedMutex); g_handcraftedRoadTaggedCount[key] = tagged; @@ -221,7 +225,11 @@ namespace TerrainMgrDetail for (HandcraftedRoadSegment const& s : segs) roadSegs.push_back({ s.fromX, s.fromY, s.toX, s.toY, s.width }); - std::size_t const tagged = Road::ApplyCorridorsToNavmesh(*navMesh, roadSegs); + std::size_t tagged = 0; + { + MMAP::NavMeshTileChangeLock tileChange; // retags polys that bot logic threads may be searching right now + tagged = Road::ApplyCorridorsToNavmesh(*navMesh, roadSegs); + } TC_LOG_DEBUG("misc", "[handcrafted-road] map {}: tagged {} polys across {} segments", mapId, uint32(tagged), uint32(roadSegs.size()));