I am trying to implement object picking. I have code to render the objects as solid, unlit colors, then I read the pixels in the screen buffer. I interpret the readings from glReadPixels()
to determine which object the cursor is currently on. Finally, I re-render everything lit, textured, and colored.
gl.glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
gl.glMatrixMode(GL_MODELVIEW);
gl.glLoadIdentity();
gl.glPushMatrix();
//Picking render goes here...
gl.glPopMatrix();
//The following code reads the current pixel color at the center of the screen
FloatBuffer buffer = FloatBuffer.allocate(4);
gl.glReadBuffer(GL_FRONT);
gl.glReadPixels(drawable.getWidth() / 2, drawable.getHeight() / 2, 1, 1, GL_RGBA, GL_FLOAT, buffer);
float[] pixels = new float[3];
pixels = buffer.array();
float red = pixels[0];
float green = pixels[1];
float blue = pixels[2];
System.out.println(red + ", " + green + ", " + blue);
gl.glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
gl.glMatrixMode(GL_MODELVIEW);
gl.glLoadIdentity();
gl.glPushMatrix();
//Final render goes here...
gl.glPopMatrix();
The problem is that the call to glReadPixels()
returns me the pixel color of the FINAL render, rather than the picking render. I would appreciate an explanation of how to read the picking render pixels.
I am aware that I can use the OpenGL name stack, but frankly I find it inconvenient and ridiculous.