I'm making a Minecraft clone as my very first OpenGL project and am stuck at the box selection part. What would be the best method to make a reliable box selection?
I've been going through some AABB algorithms, but none of them explain well enough what they exactly do (especially the super tweaked ones) and I don't want to use stuff I don't understand.
Since the world is composed of cubes I used octrees to remove some strain on ray cast calculations, basically the only thing I need is this function:
float cube_intersect(Vector ray, Vector origin, Vector min, Vector max)
{
//???
}
The ray and origin are easily obtained with
Vector ray, origin, point_far;
double mx, my, mz;
gluUnProject(viewport[2]/2, viewport[3]/2, 1.0, (double*)modelview, (double*)projection, viewport, &mx, &my, &mz);
point_far = Vector(mx, my, mz);
gluUnProject(viewport[2]/2, viewport[3]/2, 0.0, (double*)modelview, (double*)projection, viewport, &mx, &my, &mz);
origin = Vector(mx, my, mz);
ray = point_far-origin;
min and max are the opposite corners of a cube.
I'm not even sure this is the right way to do this, considering the number of cubes I'd have to check, even with octrees.
I've also tried gluProject
, it works, but is very unreliable and doesn't give me the selected face of the cube.
EDIT
So this is what I've done: calculate a position in space with the ray:
float t = 0;
for(int i=0; i<10; i++)
{
Vector p = ray*t+origin;
while(visible octree)
{
if(p inside octree)
{
// then call recursive function until a cube is found
break;
}
octree = octree->next;
}
if(found a cube)
{
break;
}
t += .5;
}
It's actually surprisingly fast and stops after the first found cube.
As you can see the ray has to go trough multiple octrees before it finds a cube (actually a position in space) - there is a crosshair in the middle of the screen. The lower the increment step the more precise the selection, but also slower.