Skip to content

Instantly share code, notes, and snippets.

@vilmosioo
Created May 23, 2013 11:25
Show Gist options
  • Save vilmosioo/5635400 to your computer and use it in GitHub Desktop.
Save vilmosioo/5635400 to your computer and use it in GitHub Desktop.
OpenGL picking in Java using the stencil buffer. This script is not meant to work directly, but rather for a simple guide on how to implement picking. it is worth mentioning that this method is just one of many. I also tried using select rendering and color picking methods, but I find this the easiest one to use.
// make sure you enable the stencil buffer when creating the canvas
GLProfile profile = GLProfile.get(GLProfile.GL2);
GLCapabilities capabilities = new GLCapabilities(profile);
capabilities.setStencilBits(8);
// when picking, enable stencil test
if (picking) {
gl.glEnable(GL2.GL_STENCIL_TEST);
gl.glStencilOp(GL2.GL_KEEP, GL2.GL_KEEP, GL2.GL_REPLACE);
} else {
gl.glDisable(GL2.GL_STENCIL_TEST);
}
// clear buffers on display
gl.glClearStencil(0);
gl.glClear(GL2.GL_COLOR_BUFFER_BIT | GL2.GL_DEPTH_BUFFER_BIT | GL2.GL_STENCIL_BUFFER_BIT);
// right before drawing an object
gl.glStencilFunc(GL2.GL_ALWAYS, <object identifier>, -1);
// the actual picking, at the end of the display method
if (picking) {
picking = false;
// get the viewport data
int[] viewport = new int[4];
gl.glGetIntegerv(GL2.GL_VIEWPORT, viewport, 0);
// read pixel data on mouse click location
IntBuffer stencil = IntBuffer.allocate(4);
gl.glReadPixels(mousex, viewport[3] - mousey, 1, 1, GL2.GL_STENCIL_INDEX, GL2.GL_UNSIGNED_INT, stencil);
int identifier = stencil.array().length > 0 ? stencil.array()[0] : -1;
// able to identify the object clicked using the identifier
...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment