Search code examples
javanested-loopsminecraft

How to divide up the processing of a giant 3D cube?


I'm not really sure how to ask this question, so if you can edit it so it's easier to understand, that would be great.

I'm trying to process a large number of points in a 3D world in java (a 40*40*40 cube, so 64000 points in all). I want to divide up the following three dimensional for loop into maybe 10*10*10 segments, than to run it every few loops so other actions can be performed, so it isn't as slow. I tried using threads, but that constantly broke because my program was accessing two things at the same time.

Here is my code:

for (int x = 0; x < 40; x++) {
    for (int y = 0; y < 40; y++) {
        for (int z = 0; z < 40; z++) {
            //Do stuff with x, y, and z
        }
    }
}

Solution

  • It sounds like you are trying to achieve something similar to the logic in BlockBreaker.

    Basically instead of using 3 nested for loops that loop 40 times each you'll start at the center and schedule block coordinates using 3 nested for loops that loop 3 times each (one block in each direction from the current block). When your logic is called you'll also want to start a tick handler going that monitors your list of scheduled blocks and keeps searching for new blocks to process using the 3 nested loops.

    Each time you schedule a block you'll increment a counter and when the counter reaches a certain limit your tick handler returns true to allow the game loop to continue. Your logic will need to keep track of how far the current block is from the point of origin and only add blocks that are within range.

    In addition to scheduling blocks, your tick handler will also be processing them and removing them from the scheduled list. Once your list is empty your tick handler should return false to stop receiving ticks.


    It's a difficult concept to explain in a post, so feel free to contact me on the MCF forums, Twitter, (same nickname as here) or on irc.esper.net #treecapitator if you have any trouble understanding the logic in the class I linked to above.