Hi guys, I’m new to OpenGL and therefore jogl. I have a simple 3D plot where xMax, yMax, zMax = 1.0 and xMin, yMin, zMin = 0. I need to determine the point in 3D space where the user clicked within my 3D plot.
I converted this code from an article on nehe.gamedev.net:
http://nehe.gamedev.net/data/articles/article.asp?article=13
Here’s my complete function:
private static DoubleBuffer modelViewBuffer = DoubleBuffer.allocate(16);
private static DoubleBuffer projectionBuffer = DoubleBuffer.allocate(16);
private static IntBuffer viewport = IntBuffer.allocate(4);
private static DoubleBuffer zValueBuff = DoubleBuffer.allocate(1);
private static DoubleBuffer coordBuff = DoubleBuffer.allocate(3);
public static Point3D get3DPointForWindowCoords(GL gl, GLU glu, int x, int y) {
gl.glGetDoublev(GL.GL_MODELVIEW_MATRIX, modelViewBuffer);
gl.glGetDoublev(GL.GL_PROJECTION_MATRIX, projectionBuffer);
gl.glGetIntegerv(GL.GL_VIEWPORT, viewport);
float winX = (float) x;
float winY = viewport.get(3) - (float) y;
gl.glReadPixels(x, (int) winY, 1, 1, GL.GL_DEPTH_COMPONENT, GL.GL_FLOAT, zValueBuff);
float winZ = (float) zValueBuff.get(0);
zValueBuff.clear();
System.out.println("z value: " + winZ);
glu.gluUnProject(winX, winY, winZ, modelViewBuffer, projectionBuffer, viewport, coordBuff);
Point3D p = new Point3D();
p.x = (float)coordBuff.get(0);
p.y = (float)coordBuff.get(1);
p.z = (float)coordBuff.get(2);
coordBuff.clear();
System.out.println("point: " + p.x + " " + p.y + " " + p.z);
return p;
}
- Am I doing anything wrong here? I just realized I’m not clearing the modelview, projection, etc buffers but nothing bad appears to be happening.
- winZ always appears to be 0
- At first I thought the coordinates it was returning were completely wrong, so I began drawing polygons at the returned coordinates. They are in fact drawn in the center of my mouse click, but they’re drawn very close to the viewing location.
Here’s two images to demonstrate what I’m referring to.
I have a simple plot. I left click once and call get3DPointForWindowCoords(gl,glu,clickpoint.x,clickpoint.y). Then I draw a polygon at those returned coordinates. Here is what I see:
Next, I zoom out and rotate around the plot. As you can see the polygon is far out on the z+ axis - no where near the “plot area”.
I’m not really sure how to fix this. Can someone point me in the right direction?
Thanks