UNPKG

@minecraft/creator-tools

Version:

Minecraft Creator Tools command line and libraries.

95 lines (94 loc) 3.13 kB
import WorldChunk from "./WorldChunk"; /** * LRU (Least Recently Used) cache for WorldChunk objects. * * Manages memory by evicting least recently used chunks when the cache * exceeds its maximum size. This enables viewing of very large worlds * without loading all chunks into memory simultaneously. * * When a chunk is evicted, its cached/parsed data is cleared but the * chunk object itself remains in the world's chunks Map. This allows * the chunk to be re-parsed on demand from its raw LevelKeyValue data. */ export default class WorldChunkCache { /** Maximum number of chunks to keep parsed data for */ private _maxChunks; /** Ordered list of chunk keys, oldest first (LRU tracking) */ private _accessOrder; /** Set of chunks currently in the cache */ private _cachedChunks; /** Callback to get a chunk by its key */ private _getChunk?; /** * Create a new chunk cache. * @param maxChunks Maximum number of chunks to keep parsed data for */ constructor(maxChunks?: number); /** Get the maximum number of cached chunks */ get maxChunks(): number; /** Set the maximum number of cached chunks */ set maxChunks(value: number); /** Get the current number of cached chunks */ get size(): number; /** * Set the callback to retrieve chunks by key. * The key format should be "dim_x_z" (e.g., "0_10_-5"). */ setChunkProvider(provider: (key: string) => WorldChunk | undefined): void; /** * Generate a cache key for a chunk. */ static makeKey(dim: number, x: number, z: number): string; /** * Parse a cache key back into coordinates. */ static parseKey(key: string): { dim: number; x: number; z: number; } | undefined; /** * Record access to a chunk, marking it as recently used. * Call this whenever a chunk is accessed for rendering or data retrieval. */ access(dim: number, x: number, z: number): void; /** * Record access to a chunk by key. */ accessByKey(key: string): void; /** * Evict least recently used chunks if over the limit. */ private _evictIfNeeded; /** * Evict a specific chunk, clearing its cached data. */ private _evictChunk; /** * Check if a chunk is in the cache (has parsed data available). */ isInCache(dim: number, x: number, z: number): boolean; /** * Clear all cached chunks. */ clear(): void; /** * Prefetch chunks in a region, loading them into the cache. * Useful for ensuring a viewport's worth of chunks are available. * * @param dim Dimension index * @param minX Minimum chunk X coordinate * @param maxX Maximum chunk X coordinate * @param minZ Minimum chunk Z coordinate * @param maxZ Maximum chunk Z coordinate */ prefetchRegion(dim: number, minX: number, maxX: number, minZ: number, maxZ: number): void; /** * Get statistics about cache usage. */ getStats(): { size: number; maxSize: number; hitRate: number; }; }