problem converting from win coordinates to object coordinates

i am trying to convert windows coordinates to object ( gl ) coordinates, i am having random values as a result. Also, opengl cooordinates start from leftbottom corner of window, but my origin is at the middle of the window, and objects are drawn in respect to origin. i am confused, somebody clarify.

following is the code…getting weird values.
void getOGLPos(int x, int y, GLdouble* glX, GLdouble* glY, GLdouble* glZ )
GLint viewport[4];
GLdouble modelview[16];
GLdouble projection[16];
GLfloat winX, winY, winZ;

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, glX, glY, glZ);

GLdouble glX=0.0,glY=0.0,glZ=0.0;
getOGLPos( 240,0,&glX,&glY,&glZ);

Values I am getting, for Windows values x=240,y=0
glX = -4.342…e-0.12
glY = 2.17…e-011

Your code looks correct, it should work. That’s of course assuming you have the correct depth buffer content. You have to call your getOGLPos function after rendering, but before SwapBuffers.

What values are you expecting? The values themselves are meaningless unless you tell us your transformation setup.

2.17e-11 is nearly zero. You’ll never get an exact result with floating point math. So if you’re expecting the outcome to be zero, the result is propably ok.

I am using the following transformation setup. I was expecting, x=240, y=0 as point closer to top-right.
<--------x=240—> . (y=0)
| .Origin

Basically i was trying to write some text ( such as frame rate data) at top-left corner. so i was experimenting with client-coordinates to gl coordinates conversion.

int width=600,height=600;
glViewport( 0, 0, width, height );

//Set the matrix
glMatrixMode( GL_PROJECTION );
glLoadIdentity();//reset projection matrix

gluLookAt( 0.0f, 0.0f, 10.0f, 0.0,0.0,0.0,0.0f,1.0f, 0.0f );

oh…it did not draw correctly…origin has to be in middle.