From a0726299786b5a56e8270f77c92fd3136ccfe9ca Mon Sep 17 00:00:00 2001 From: Lars Date: Sun, 15 Jun 2025 15:00:01 -0700 Subject: [PATCH] Add single block cache --- src/map.cpp | 20 ++++++++++++++++++-- src/map.h | 5 +++++ 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/src/map.cpp b/src/map.cpp index 7a12286f3..91873d45f 100644 --- a/src/map.cpp +++ b/src/map.cpp @@ -78,12 +78,15 @@ void Map::deleteBlockImmediate(MapBlock *block) std::unique_ptr Map::detachBlock(MapBlock *block) { + v3s16 p = block->getPos(); // Remove from container - auto it = m_blocks.find(block->getPos()); + auto it = m_blocks.find(p); assert(it != m_blocks.end()); std::unique_ptr ret = std::move(it->second); assert(ret.get() == block); m_blocks.erase(it); + if (m_block_cache_p == p) + m_block_cache = nullptr; // Mark as removed block->makeOrphan(); @@ -106,8 +109,19 @@ void Map::insertBlock(std::unique_ptr block) MapBlock *Map::getBlockNoCreateNoEx(v3s16 p3d) { + if(m_block_cache && p3d == m_block_cache_p){ + return m_block_cache; + } + auto it = m_blocks.find(p3d); - return it != m_blocks.end() ? it->second.get() : nullptr; + if (it == m_blocks.end()) + return nullptr; + + MapBlock *block = it->second.get(); + m_block_cache = block; + m_block_cache_p = p3d; + + return block; } MapBlock *Map::getBlockNoCreate(v3s16 p3d) @@ -329,6 +343,8 @@ void Map::timerUpdate(float dtime, float unload_timeout, s32 max_loaded_blocks, // Delete directly from container it = m_blocks.erase(it); + if (m_block_cache_p == p) + m_block_cache = nullptr; if (unloaded_blocks) unloaded_blocks->push_back(p); diff --git a/src/map.h b/src/map.h index 54e35430b..e3af0bec7 100644 --- a/src/map.h +++ b/src/map.h @@ -276,6 +276,11 @@ protected: std::unordered_map> m_blocks; + // Last-used block is cached here for quicker access. + // Be sure to set this to nullptr when the cached block is deleted + MapBlock *m_block_cache = nullptr; + v3s16 m_block_cache_p; + // This stores the properties of the nodes on the map. const NodeDefManager *m_nodedef;