My voxel system uses a flat 3D array dynamically allocated at runtime for each chunk, however generating millions of cubes per chunk isn't feasible so I need to optimize.
The first optimization I intend to implement is of course to not generate mesh data for occluded voxels, this is a good idea on paper but I don't know how to do it.
All my attempts have ended up with hard to debug memory allocation issues and as such I have to throw the towel in and ask more knowledgeable people as I'm at loss.
My current incarnation of this is as such
int8_t x = 0, y= 0, z = 0;
const int MAX = CHUNKSIZE-1;
const int MIN = 0;
int8_t sPosX = (x - 1 < MIN) ? x : x-1;
int8_t sPosY = (y - 1 < MIN) ? y : y-1;
int8_t sPosZ = (z - 1 < MIN) ? z : z-1;
int8_t ePosX = (x + 1 > MAX) ? x : x+1;
int8_t ePosY = (y + 1 > MAX) ? y : y+1;
int8_t ePosZ = (z + 1 > MAX) ? z : z+1;
int8_t a=sPosX, b=sPosY, c=sPosZ;
int8_t add = 0;
BlockType BT = BT_grass;
scene::SMesh* mesh = new scene::SMesh();
for(x = 0; x <= MAX; x++)
{
for(y = 0; y <= MAX; y++)
{
for(z = 0; z <= MAX; z++)
{
cm = b_blocks[x][y][z].material;
//b_blocks[x][y][z].setFlags(0xFE, BT);
if( !b_blocks[x][x][z].isActive() )
{
continue;
}
else
{
if(sPosX == MIN)
{
createCube(x,y,z,c,mesh,cm);
}
else
{
if(a<=ePosX)
{
if(b<=ePosY)
{
if(c<=ePosZ)
{
printf("x %d, y %d, z %d\n", x, y, z);
if(!b_blocks[x][y][z].isActive())
{
add = 1;
}
}
}
}
if(add == 1)
{
createCube(x,y,z,c,mesh,cm);
add = 0;
}
}
}
}
}
}
The if(sPosX == MIN) is a hack I implemented to not segfault on generating the chunk (otherwise it segfaults with a memory access violation on generating block[CHUNKSIZE][CHUNKSIZE][CHUNKSIZE], which isn't very nice. This hack inadvertently makes sure that all cubes are generated however and is just as unappealing.
The concise questions here are as follows: What part of my logic is broken? (presumably all of it) and how would one properly check neighbouring blocks in a fast manner that does not cause an out of bounds error? (I tried by manually coding exceptions for every last corner case but that proved to be unmaintainable and was orders of magnitude slower and prone to segfaulting)