iDevGames Forums
Small error with glViewport and gluPerspective? - Printable Version

+- iDevGames Forums (
+-- Forum: Development Zone (/forum-3.html)
+--- Forum: Graphics & Audio Programming (/forum-9.html)
+--- Thread: Small error with glViewport and gluPerspective? (/thread-737.html)

Small error with glViewport and gluPerspective? - cjcaufield - Sep 19, 2009 10:54 PM

I'm working on an OpenGL app that displays a single object with perspective inside a window. When the user resizes the window, the field of view changes accordingly. For example, when the height of the window is 1024 pixels, the fovy is 60 degrees, and when the window is halved to 512 pixels, the fovy is 30 degrees, etc. Changes to the window's width work similarly.

The goal is for the object to always take up the exact same number of pixels, regardless of the window size. This works perfectly when resizing horizontally, however, when resizing vertically, the object changes size by a few percent. I can't seem to figure out why. Can anyone find my problem, or, propose an alternative solution? Thanks in advance. Here's my code:

#import "GLView.h"
#import <GLUT/glut.h>

@implementation GLView

- (id) initWithFrame:(NSRect)frame
    NSOpenGLPixelFormatAttribute attrs[] =
        NSOpenGLPFAColorSize, 24,
        NSOpenGLPFAAlphaSize, 8,
    NSOpenGLPixelFormat* pixelFormat = [[NSOpenGLPixelFormat alloc] initWithAttributes:attrs];
    self = [super initWithFrame:frame pixelFormat:pixelFormat];
    return self;

- (void) drawRect:(NSRect)bounds
    [[self openGLContext] makeCurrentContext];
    glTranslatef(0.0f, 0.0f, -3.0);
    glClearColor(0.0, 0.0, 0.0, 1.0);
    glColor3d(1.0, 1.0, 1.0);
    [[self openGLContext] flushBuffer];
    [self setNeedsDisplay:YES];

- (void) reshape
    [[self openGLContext] makeCurrentContext];
    NSSize size = [self bounds].size;
    double aspect = size.width / size.height;    
    double fovy = 60.0 * size.height / 1024.0;

    glViewport(0, 0, (int)size.width, (int)size.height);
    gluPerspective(fovy, aspect, 0.1, 10.0);


Small error with glViewport and gluPerspective? - DoG - Sep 20, 2009 01:10 AM

The problem is with
double fovy = 60.0 * size.height / 1024.0;

You won't get away without doing a bit of trigonometry to figure out what the real angle should be, instead of this linear approximation.