Search code examples
androidopengl-esglu

Android OpenGL ES 2.0 reading z-buffer for gluunproject/ or calc raycollision with near far coords


I know there is a lot of stuff even on stackoverflow about this theme/problem but i really cant get it. Im in this problem for several hours now.

public Vector select(float x, float y) 
{

int viewport[] = { 0, 0, width , height};

float realY = ((float) ( height) - y);
float near[] = { 0.0f, 0.0f, 0.0f, 0.0f };
float far[] = { 0.0f, 0.0f, 0.0f, 0.0f };

GLU.gluUnProject(x, realY, 0, mg.mModelView, 0, mg.mProjection , 0, viewport, 0, near, 0);
GLU.gluUnProject(x, realY, 1, mg.mModelView, 0, mg.mProjection, 0, viewport, 0, far, 0);

float xr = near[0] / near[3];
float yr = near[1] / near[3];
float zr = near[2] / near[3];

return new Vector(xr,yr,zr);
}

/**
GLU.gluLookAt( gl, me.position.x, me.position.y, me.position.z, me.position.x, 0, me.position.z+1, 0, 1, 0 );
**/

1) Is there a possibility yet to read the z buffer with

    glReadPixels(winX, winY, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, winZ);

The GL11Extension class implements the GL_DEPTH_COMPONENT constant for glReadPixels or what? http://developer.android.com/reference/javax/microedition/khronos/opengles/GL11ExtensionPack.html#GL_DEPTH_COMPONENT

2) Or is it possible to calculate the z-Buffer manuel with my glulookat positions ?

3) Or how to calculate the collision with the near and far position.

Thank you for reading :)


Solution

  • The z part of unProject is the z position on the near clipping plane / the 'front' of the view frustum. If you know the eye position, you have two 3D points that you can make a ray/vector from.

    You then use the ray to calculate anything it passes through. In my own game, I translate the ray into my game's own coordinate system and then re-use the collision detection algorithms I already have in place. (I.e. the "does the bullet intersect hitbox" code).

    If you don't have collision detection, it is fairly simple to calculate the bounding box or bounding sphere of every model, which you only have to do once ever (so you can just add it as a property to your model files). You can then do a quick pass for every model to find which models the user picked, do a distance-from-camera test on the model locations to find which one is in the foreground, or take the poly's from each model and calculate exactly which poly was picked

    Edit: I found a working example here: enter link description here. The explanation is in russian, but the code worked for me

    enter image description here