gluUnProject coordinates

Recommended Posts

Using gluUnProject gleamed from examples around the web and nehe. copy and paste job with some changes.
GLfloat mx, my;

void GetOGLPos(int x, int y)
{

GLint viewport[4];
GLdouble modelview[16];
GLdouble projection[16];
GLfloat winX, winY, winZ;
GLdouble posX, posY, posZ;

glGetDoublev( GL_MODELVIEW_MATRIX, modelview );
glGetDoublev( GL_PROJECTION_MATRIX, projection );
glGetIntegerv( GL_VIEWPORT, viewport );

winX = (float)x;
winY = (float)viewport[3] - (float)y;
glReadPixels( x, int(winY), 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &winZ );

gluUnProject( winX, winY, winZ, modelview, projection, viewport, &posX, &posY, &posZ);

mx = posX;
my = posY;

//	return Vector3(posX, posY, posZ);
} 
Never used vectors and it just gives me errors, that's a problem for another day. Not sure if "mx" and "my" return correct values is the problem. As obviously since posX, posY are encapsulated within this function it is obviously inacessable to another function. I needed the transformed co-ordinates so that when i click on the mouse i can draw something at those co-ordinates, say a sphere for example. i already have a sphere on screen and when I move it around the max co-ordinates of x and y are around 11 and 8. when I have this code though
if (keys[VK_SPACE])
{
GetOGLPos(winX, winY);
glRasterPos2f(0, 0);
glPrint("mouse x: %f", mx);
glRasterPos2f(0, -0.5f);
glPrint("mouse y: %f", my);
}

x is a maximum of 55 and y around 36. rather hugely different i'd say and dividing mx and my by a number isn't a solution either.

Share on other sites
I'm at work at the moment, so I'll answer your question more fully later tonight at home. I've used gluUnProject a lot; you don't need the depth buffer read at all. I've never seen one example where that was remotely useful (I can imagine scenarios where it could be, though). Basically, you need to call the function twice: once with a z value of 0.0f, and once with a z value of 1.0f. This will give you two vectors, which form a world-space ray from the mouse co-ords on the near clip plane to the mouse co-ords on the far clip plane.

Once you've got this ray, you can use some 3D math to intersect it with a plane to get a position to draw at, or intersect it with geometric objects in your scene to select them. I assume that's what you're trying to do...

Got it thanks ^^

Create an account

Register a new account

• Partner Spotlight

• Forum Statistics

• Total Topics
627636
• Total Posts
2978331

• 10
• 12
• 22
• 13
• 33