Often when working on projects, we need the ability to pick graphical objects on screen. While in OpenGL versions before OpenGL 3.0, the selection buffer was used for this purpose, this buffer is removed in the modern OpenGL 3.3 core profile. However, this leaves us with some alternate methods. We will implement a simple picking technique using the depth buffer in this recipe.
The code for this recipe is in the Chapter2/Picking_DepthBuffer
folder. Relevant source files are in the Chapter2/src
folder.
Picking using depth buffer can be implemented as follows:
Enable depth testing:
glEnable(GL_DEPTH_TEST);
In the mouse down event handler, read the depth value from the depth buffer using the
glReadPixels
function at the clicked point:glReadPixels( x, HEIGHT-y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &winZ);
Unproject the 3D point,
vec3(x,HEIGHT-y,winZ)
, to obtain the object-space point from the clicked screen-space point...