refactor: Optimize rendering with chunk canvas caching and performance improvements

This commit is contained in:
Kacper Kostka (aider)
2025-04-05 15:49:13 +02:00
parent d87105baad
commit bb45c9fba8
3 changed files with 170 additions and 113 deletions

View File

@@ -78,18 +78,44 @@ function simulationLoop(timestamp) {
// Update physics with timestamp for rate limiting
updatePhysics(timestamp);
// Force stone layer chunks to be rendered every frame
const visibleChunks = getVisibleChunks();
for (const { chunkX, chunkY, isVisible } of visibleChunks) {
if (isVisible && chunkY === 1) {
// Mark stone layer chunks as dirty to ensure they're always rendered
dirtyChunks.add(getChunkKey(chunkX, chunkY));
}
}
// Render
render();
// Memory management: Clean up chunk cache for chunks that are far away
if (timestamp % 5000 < 16) { // Run every ~5 seconds
cleanupChunkCache();
}
// Continue the loop
requestAnimationFrame(simulationLoop);
}
// Clean up chunk cache to prevent memory leaks
function cleanupChunkCache() {
if (!chunkCanvasCache) return;
const visibleChunks = getVisibleChunks();
const visibleKeys = new Set();
// Get all visible chunk keys
for (const { chunkX, chunkY } of visibleChunks) {
visibleKeys.add(getChunkKey(chunkX, chunkY));
}
// Remove cached canvases for chunks that are far from view
for (const key of chunkCanvasCache.keys()) {
if (!visibleKeys.has(key)) {
// Keep stone layer chunks in cache longer
if (key.split(',')[1] === '1') {
// Only remove if it's really far away
const [chunkX, chunkY] = key.split(',').map(Number);
const centerChunkX = Math.floor(worldOffsetX / CHUNK_SIZE);
if (Math.abs(chunkX - centerChunkX) > 10) {
chunkCanvasCache.delete(key);
}
} else {
chunkCanvasCache.delete(key);
}
}
}
}