0

I am creating a game with infinite terrain. Sections of the terrain are broken up into regions of fixed size for handling (similar to chunks in Minecraft). I would like to load and unload them as needed as the player moves so that every region within a visibility range is visible and the others are not. For simplicity the pattern of loaded regions can be a square instead of a circle approximation.

The naive way to do this is to have a loop that runs every game update which iterates all loaded regions, and those who have an X or Y or Z coordinate that is out of range are deleted, and then have another loop that runs and ensures that all spaces that are within the X and Y and Z coordinates are not empty.

However having 2 loops every frame does not seem very efficient. A simple improvement is to only run those loops if the player location changes. But that is still every frame while the player is moving.

I could also only run the loops if the player crosses a region boundary, but still those loops are going to go over a lot of regions that do not need to be updated. In theory, only the regions at the edge of the loaded regions area need to be iterated over, if the player crosses a region boundary.

What is the most efficient algorithm to dynamically load and unload regions as needed around a player, in a cube/square fashion?

CPlus
  • 143
  • 11
  • This looks like a loop with a fairly low "n", probably on the order of hundreds, not millions. Are you sure this is the part of your terrain system you need to spend your time optimizing? You're unlikely to spot a significant delay here in your profiling even from quite a naive loop or pair of loops. – DMGregory Nov 25 '23 at 07:05
  • 1
    If your profiling is showing this matters though, you can try something like the clipmapping approach I show in this answer. This lets you replace one column or one row of chunks when the player crosses a chunk boundary, without visiting and testing all loaded chunks. They also keep a well-defined and cache-friendly spatial layout in your lookup structure, so you can efficiently traverse regions without randomized lookups. – DMGregory Nov 25 '23 at 07:13
  • @DMGregory That looks interesting, I'll try it out. – CPlus Nov 25 '23 at 19:51
  • https://m.youtube.com/playlist?list=PLFt_AvWsXl0eBW2EiBtl_sxmDtSgZBxB3 Sebastian Lague had a very nice series on this subject. – GaleRazorwind Nov 27 '23 at 15:08

0 Answers0