Original Post
I'm working on a little 3d editor(win + opengl), and I got this little piece of code from one of the articles on NeHe. Now, this returns 3d coords for a 2d window click. But I'm having a little bit of trouble when I think about how I'm going to be able to use this to highlight the object that was clicked on. So, how would I go about finding exactly which object is being clicked on? Note: so far I haven't gone as far as choosing a data structure to keep my objects in, so for this exact problem, I'm basically starting from the start. I pretty much have 3d coords and need to find the object they belong to, or are closest to. Got any ideas that could help?
CVector3d 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);
return CVector3d(posX, posY, posZ);
}
// The points that I'm drawing:
glVertex3f( 4.0f, 4.0f, -10.0f);
glVertex3f(-4.0f, -4.0f, -10.0f);
// coords that I recieved from function
3.99569, 4.08208, -10
-4.03888, -3.99569, -10