Depth buffer read causes crash

Hi all. Since I’ve been unable to locate a jogl sample for reading the depth buffer, I tried the following only to have jogl crash in native method glReadPixels

// Grab screen z value
FloatBuffer buffer = ByteBuffer.allocateDirect(viewPortWidth * viewPortHeight).asFloatBuffer();
gl.glReadPixels(x, y, viewPortWidth, viewPortHeight, GL.GL_DEPTH_COMPONENT, GL.GL_FLOAT, buffer);

depth = buffer.get();

glReadPixels work fine for reading the frame buffer with a ByteBuffer, but the depth component is float so I can’t read to a byte buffer as a byte.

Anyone?

This way works well for me :

float[] winZ = new float[1];

gl.glReadPixels ( clickX, (int)winY, 1, 1, GL.GL_DEPTH_COMPONENT, GL.GL_FLOAT, winZ );

Hmm. Can’t get it to work properly. Always gets 1.0f for z buffer pos.

Could you please check my code?

public Vector3D getWorldPosFromMouse(int x, int y) { // Some init stuff double model_view[] = new double[16]; double projection[] = new double[16]; int viewport[] = new int[4]; double x2 = x;
        float[] winZ = new float[1];
   
        gl.glReadPixels( x, y, 1, 1, GL.GL_DEPTH_COMPONENT, GL.GL_FLOAT, winZ);
        
        System.out.println("Depth hit = " + winZ[0]);
       
        
        // Get needed stuff
        gl.glGetDoublev(GL.GL_MODELVIEW_MATRIX, model_view);
        gl.glGetDoublev(GL.GL_PROJECTION_MATRIX, projection);
        gl.glGetIntegerv(GL.GL_VIEWPORT, viewport);
        
        double y2 = (double)viewport[3] - y;
       
        // Do it
        double[] ray1 = new double[1];
        double[] ray2 = new double[1];
        double[] ray3 = new double[1];

        glu.gluUnProject(x2, y2, winz[0], model_view, projection, viewport, ray1, ray2, ray3);  
        
        return new Vector3D((float)ray1[0], (float)ray2[0], (float)ray3[0]);
    }

I think you have to use y2 in glReadPixels not y.

Hi,

I’m currently having a similar problem, however my depth component is always returned as 0.

I’m also using this approach:

float[] winZ = new float[1];

gl.glReadPixels ( clickX, (int)winY, 1, 1, GL.GL_DEPTH_COMPONENT, GL.GL_FLOAT, winZ );

Any thoughts?

The problem was that I got the viewport, projection etc. stuff from OpenGL outside the JOGL rendering thread. This caused them all to be filled with zeros which in turn returned zero for the readbuffer call.

This thread issue is a major pain when usin JOGL in larger systems such as 3D editor apps etc.

Since floats uses 4 bytes should it not be “viewPortWidth * viewPortHeight * 4”?

Yes, it was in fact a thread issue. I also struggled with picking because of this, but now that I know to remember it, it shouldn’t be that big of a pain in the future… hopefully.

Thanks.