iphonexcodeopengl-esxcode-templatestretched

iPhone OpenGL Template is cheating?


XCode's OpenGL template seems to be cheating to solve this "stretched" viewport problem I've been trying to understand for the last 3 hours.

In the iphone "OpenGL ES Application" template, the colorful square that bounces up and down on the screen is not really a square at all!

ES1Renderer.m (the ES2 file as well)

static const GLfloat squareVertices[] = {
    -0.5f,  -0.33f,
     0.5f,  -0.33f,
    -0.5f,   0.33f,
     0.5f,   0.33f,
};

But it comes out looking square on the device/simulator due to the stretching/squashing effect of a non-square viewport. I tried to fix it by fiddling with glFrustumf() but that doesn't seem to change the aspect ratio.

I was able to get things looking good (not-stretched) when I fed glViewport() with a 1:1 widht:height.. But this doesn't seem like the answer because it offsets the viewport placement.

What's the right way to correct for this stretching and why doesn't XCode do it that way?


Solution

  • I think the answer is:

    XCode is cheating like this to avoid confusing us with the extra code required to setup a frustum.

    Here's the code I'm using to set one up, and it fixed the squashing/stretching I was getting:

    const GLfloat zNear = 0.0001, zFar = 1000.0, fieldOfView = 45.0; 
    GLfloat size;
    
    size = zNear * tanf(DEGREES_TO_RADIANS(fieldOfView) / 2.0);
    
    aspectRatio = (GLfloat) backingWidth / backingHeight;
    
    
    glFrustumf(-size,//left
               size,//right
               (GLfloat)-size / aspectRatio,//bottom 
               (GLfloat)size / aspectRatio,//top 
               zNear,//zNear 
               zFar);//zFar     
    
    glViewport(0, 0, backingWidth, backingHeight); 
    

    Hope that helps someone.