Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenGL - maintaining aspect ratio upon window resize

Tags:

c

opengl

I am drawing a polygon in a square window. When I resize the window, for instance by fullscreening, the aspect ratio is disturbed. From a reference I found one way of preserving the aspect ratio. Here is the code:

    void reshape (int width, int height) {
    float cx, halfWidth = width*0.5f;
    float aspect = (float)width/(float)height; 
    glViewport (0, 0, (GLsizei) width, (GLsizei) height);
    glMatrixMode(GL_PROJECTION); 
    glLoadIdentity(); 
    glFrustum(cx-halfWidth*aspect, cx+halfWidth*aspect, bottom, top, zNear, zFar);
    glMatrixMode (GL_MODELVIEW);
}

Here, cx is the eye space center of the zNear plane in X. I request if someone could please explain how could I calculate this. I believe this should be the average of the initial first two arguments to glFrustum(). Am I right? Any help will be greatly appreciated.

like image 408
Iceman Avatar asked Feb 20 '23 19:02

Iceman


2 Answers

It looks like what you want to do is maintain the field of view or angle of view when the aspect ratio changes. See the section titled 9.085 How can I make a call to glFrustum() that matches my call to gluPerspective()? of the OpenGL FAQ for details on how to do that. Here's the short version:

fov*0.5 = arctan ((top-bottom)*0.5 / near)
top = tan(fov*0.5) * near
bottom = -top
left = aspect * bottom
right = aspect * top

See the link for details.

like image 84
user1118321 Avatar answered Feb 28 '23 09:02

user1118321


The first two arguments are the X coordinates of the left and right clipping planes in eye space. Unless you are doing off-axis tricks (for example, to display uncentered projections across multiple monitors), left and right should have the same magnitude and opposite sign. Which would make your cx variable zero.

If you are having trouble understanding glFrustrum, you can always use gluPerspective instead, which has a somewhat simplified interface.

like image 30
Andy Ross Avatar answered Feb 28 '23 11:02

Andy Ross