PDA

View Full Version : Transform from window coordinate to OpenGL coordinate



Debugger
01-26-2007, 10:41 PM
I am trying to use gluUnProject()transform window coordinate to OpenGL coordinate, but I found that I can only get correct coordinate for x axis, the y axis is a not correct, any idear about this?

I use a cross line to trace mouse position.
code:

#include <iostream>
#include <windows.h>
#include "GL/glut.h"

using namespace std ;

//Threee variable indicate the coordiante after transformation
GLdouble objX ;
GLdouble objY ;
GLdouble objZ ;
void MotionFunc(int x, int y)
{

//Get Model matrix
GLdouble *model = new GLdouble[16] ;
glGetDoublev(GL_MODELVIEW_MATRIX,model) ;
//Get project matrix
GLdouble *proj = new GLdouble[16] ;
glGetDoublev(GL_PROJECTION_MATRIX,proj) ;
//Get viewport
GLint *view = new GLint[4] ;
glGetIntegerv(GL_VIEWPORT,view) ;
//Transform
gluUnProject( x, y, 1.0, model, proj, view, &amp;objX, &amp;objY, &amp;objZ) ;

}

void init(void)
{
glClearColor(1.0, 1.0, 1.0, 1.0) ;
}

void display(void)
{

glClear(GL_COLOR_BUFFER_BIT) ;
glColor3f(1.0, 0.0, 0.0) ;
//Draw a vertical line and a horizontal line
glBegin(GL_LINES) ;
glVertex2f((objX-4.0)<-2.0?-2.0:(objX-4.0), objY) ;
glVertex2f((objX+4.0)>2.0?2.0:(objX+4.0), objY) ;
glVertex2f(objX, (objY-3.0)<-1.5?-1.5:(objY-3.0)) ;
glVertex2f(objX, (objY+3.0)>1.5?1.5:(objY+3.0)) ;
glEnd() ;
glutSwapBuffers() ;

}

void reshape(int w, int h)
{
glViewport(0, 0, (GLsizei)w, (GLsizei)h) ;
glMatrixMode(GL_PROJECTION) ;
glLoadIdentity() ;
if(w<=h)
glOrtho(-1.5, 1.5, -1.5*(GLfloat)h/(GLfloat)w,
1.5*(GLfloat)h/(GLfloat)w, -10.0, 10.0) ;
else
glOrtho(-1.5*(GLfloat)w/(GLfloat)h,
1.5*(GLfloat)w/(GLfloat)h, -1.5, 1.5, -10.0, 10.0) ;
glMatrixMode(GL_MODELVIEW) ;
glLoadIdentity() ;
}

int main(int argc, char **argv)
{
glutInit(&amp;argc, argv) ;
glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB) ;
glutInitWindowSize(1024, 768) ;
glutInitWindowPosition(0, 0) ;
glutCreateWindow("MouseSample");
init() ;
glutPassiveMotionFunc(MotionFunc);
glutDisplayFunc(display);
glutIdleFunc(display) ;
glutReshapeFunc(reshape) ;
glutMainLoop();

return 0 ;
}

Ido_Ilan
01-27-2007, 01:10 AM
Hi,

Try this:
On windows the 0,0 is the upper left corner, but 0,0 for OpenGL is on the lower left corner.
You need to send: window heigh - y.

Ido

Debugger
01-27-2007, 07:24 PM
Thank you very much! it works now, change it like the following:


glVertex2f((objX-4.0)<-2.0?-2.0:(objX-4.0), -objY) ;
glVertex2f((objX+4.0)>2.0?2.0:(objX+4.0), -objY) ;