Search code examples
c++openglgccfreeglut

GLUT: blank window


I successfully compiled this code using latest freeglut but I'm constantly getting a blank window filled with the color specified in glClearColor function. This simple program is from a Interactive Computer Graphics textbook provided by my college. I copied it word for word and it still doesn't work. It should render 2 squares rotating.

I use gcc on windows 7 machine:

$ gcc -Iinlude -Llib -o sample.exe sample.cpp -lfreeglut -lopengl32

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <GL/glut.h>

void rashape(int width, int height);
void display();
void renderScene();
void animate(int value);
void drawSquare();
int angle = 0;

int main(int argc, char **argv) {
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE);
    glutInitWindowSize(600, 300);
    glutInitWindowPosition(0, 0);
    glutCreateWindow("Primjer animacije");
    glutDisplayFunc(display);
    glutTimerFunc(20, animate, 0);
    glutMainLoop();
}

void animate(int value) {
    angle++;
    if(angle >= 360) kut = 0;
    glutPostRedisplay();
    glutTimerFunc(20, animate, 0);
}

void display() {
    glClearColor(1.0f, 0.2f, 1.0f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);
    glLoadIdentity();
    renderScene();
    glutSwapBuffers();
}

void reshape(int width, int height) {
    glDisable(GL_DEPTH_TEST);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(0, width-1, 0, height-1, 0, 1);
    glViewport(0, 0, (GLsizei)width, (GLsizei)height);
    glMatrixMode(GL_MODELVIEW);
}

void drawSquare() {
    glBegin(GL_QUADS);
    glVertex2f(  0.0f,   0.0f);
    glVertex2f(100.0f,   0.0f);
    glVertex2f(100.0f, 100.0f);
    glVertex2f(  0.0f, 100.0f);
    glEnd();
}

void renderScene() {
    glPointSize(6);
    glColor3f(0.3f, 1.0f, 0.3f);

    glPushMatrix();
    glTranslatef( 150.0f, 160.0f, 0.0f);
    glScalef(1.5f, 1.5f, 1.0f);
    glRotatef((float)kut, 0.0f, 0.0f, 1.0f);
    glTranslatef(-50.0f, -50.0f, 0.0f);
    drawSquare();
    glPopMatrix();

    glPushMatrix();
    glTranslatef( 400.0f, 160.0f, 0.0f);
    glScalef(1.5f, 1.5f, 1.0f);
    glRotatef(-(float)kut, 0.0f, 0.0f, 1.0f);
    glTranslatef(-50.0f, -50.0f, 0.0f);
    drawSquare();
    glPopMatrix();
}

Solution

  • You never call reshape(). Thus, the default projection matrix is used, which puts (0,0) at the center of the screen and has a view 'radius' of 1. As a result, your squares are being rendered far off screen.

    Calling reshape() with appropriate parameters before trying to render anything should work. What you would really want to do, though, is set it as a glutReshapeFunc() so that the projection matrix adjusts automatically to resizing. This is easy to do:

    int main(int argc, char ** argv)
    {
        // ... stuff ...
        glutReshapeFunc(reshape);
        // ... more stuff ...
    }
    

    The viewport should now automatically adjust to window resizing.