Introduction
In Minecraft coding, there's a time where you might want to have a list of objects related to chunks coordinates, and somehow, you might need to iterate through it.
But iterating can become really, really slow with a lot of elements in a Collection, especially when done each ticks or all at once.
The solution
Instead of iterating for every single object in the list, what we can achieve is splitting the list into multiples: one for each chunk.
This way, you'll be able to iterate only for the objects you want/in the loaded chunks (most of the times, related to the Player).
This method can be extended not only to Minecraft, but any game with a chunk system, and in any language.
How it is divided
1. Global Entry Point (GlobalBlockContainer)
At the top level, the GlobalBlockContainer acts as a registry for all worlds. It uses a Map<UUID, WorldBlockContainer> to ensure that when you look for data in a specific world, you don't even look at the data from others.
2. World-Level Management (WorldBlockContainer)
Each world is split into a grid of chunks. This container maps ChunkKey objects (representing X and Z coordinates) to their respective ChunkBlockContainer. This allows for instant access to any chunk's data without searching through the entire world.
3. Vertical Granularity (ChunkBlockContainer & ChunkSectionBlockContainer)
Since Minecraft worlds are tall, this divide each 16x16 chunk into vertical Sections (16x16x16 blocks).
- The Chunk container manages these sections.
- The Section container holds the actual data using a
DynamicSectionContainer.
This 3D grid approach ensures that retrieving an object at specific coordinates is done in constant time, regardless that thousands of objects can be tracked.
4. The Data Holder
The Holder<T, K> is the wrapper. It stores the actual object (T) alongside its precise coordinates. By implementing the Tracked interface, the objects become aware of their lifecycle, allowing the system to automatically trigger an onUnload() logic when a chunk is removed from memory.
The code
You can find and browse the full, generic code from one of my libraries, Arcana.