How do this viewport() and gluOrtho2d work?

Hello everyone,

I’m new to openGL, and I’m currently reading the Red book. While practicing the example in the book, I was stuck with this code:

void reshape( int w, int h ) {
	glViewport( 0, 0, w, h );
	glMatrixMode( GL_PROJECTION );
	float aspect_ratio = static_cast<float>( w )/h;
	if( w <= h ) {
		gluOrtho2D( -1.0, 1.0, -1.0 / aspect_ratio, 1.0 * aspect_ratio );
	else {
		gluOrtho2D( -1.0 * aspect_ratio, 1.0 * aspect_ratio, -1.0, 1.0 );
	glMatrixMode( GL_MODELVIEW );

The confused part is the if-else statement. I don’t understand the side affect of aspect_ratio? Does the left, right, bottom up scale base on the window width and height? Could anyone help me explain it?


Think of it this way. No matter what resolution the user stretches are window to, we want to be able to display the entire eye-space region X=-1…1, Y=-1…1 in the visible part of the window without “stretching” it (assumes square pixels).

So if the window is “wide” (w>h), then we map Y=-1…1 over the entire height of the window (the smallest dimension)

And if the window is “tall” (h>w) then we map X=-1…1 over the entire width of the window (the smallest dimension).

The aspect ratio of the remaining dimension just scaled to match the aspect ratio of the window (again, as I said, it assumes pixels are square) so that eye-space doesn’t appear to be “stretched” to map it to the window.

Hi Dark Photon,
Many thanks. I kinda see it now.