Created
May 23, 2013 11:25
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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