By default openGL maps the coordinates you draw into the window as follows
(-1,1)*--------------*(1,1)
| |
| *(0,0) |
| |
(-1,-1)*--------------*(1,-1)
Notice openGL scales everything so you do NOT think in terms of pixel coordinates. You can see this with the following minimal code that draws a rectangle just ever so slightly smaller than (±1,±1) – otherwise you wouldn’t see the rectangle right on the windows edge.
//your header paths may be different depending on your OS
#include <GL/glut.h>
#include <stdlib.h> //for exit()
void init() {
glClearColor(0.0, 0.0, 0.0, 0.0);
}
void display() {
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0,1.0,1.0);
GLfloat S = 0.95;
glBegin(GL_LINE_STRIP); {
glVertex2f(-S, -S);
glVertex2f( S, -S);
glVertex2f( S, S);
glVertex2f(-S, S);
glVertex2f(-S, -S);
}
glEnd();
glutSwapBuffers();
}
void timer(int value)
{
glutTimerFunc(33,timer,33); // come back here in 33mSeconds
glutPostRedisplay(); // ask for display callback call ASAP
}
void keyboard(unsigned char key, int x, int y)
{
switch (key) {
case 27: // escape key
exit(0);
break;
default:
break;
}
}
int main(int argc, char** argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE);
glutCreateWindow("HelloGLUT");
glutTimerFunc(0,timer,0);
glutDisplayFunc(display);
glutKeyboardFunc(keyboard);
init();
glutMainLoop();
return 0;
}
Try compiling, running, and resizing the window and watch what happens – the rectangle scales with the window automatically! No need for you to think in pixel dimensions, just the default ±1 coordinate system.
But having a coordinate system limited to ±1 is inconvenient so openGL gives you a convenience function ( gluOrtho2d) to redefine the default behavior. There are other convenience functions but this serves the purpose of explaining the answer to your question. Suppose you want a coordinate system that goes from -10 to 10 instead … you would simply change the GL_PROJECTION matrix with a gluOrtho2d call. Specifically, adding three lines to the beginning of init as follows
void init() {
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(-10.,10.,-10.,10.); // added to change Cartesian cooridinate map to screen
glClearColor(0.0, 0.0, 0.0, 0.0);
}
accomplishes the following mapping of Cartesian coordinates to the window as
(-10,10)*--------------*(10,10)
| |
| *(0,0) |
| |
(-10,-10)*--------------*(10,-10)
A good resource to understand this all in more detail is OpenGL Redbook