Search code examples
openglglut

How to simply Scale an object in openGL?


I am trying to learn how to do scaling, rotating, and translating in openGL, but I am not sure exactly how to do so. I tried following an example but it is not working. Below is my sample code, which does not draw the object. Can anyone tell me what I am doing wrong?

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

GLfloat vertices[][2] = { { -1.0,1.0 },{ -1.0,0.857 },
{ -0.857,0.857 },{ -0.857,1.0 } };

void drawObject() {

    glColor3f(0.0f, 0.0f, 0.0f);
    glBegin(GL_POLYGON);
    glVertex2fv(vertices[0]);
    glVertex2fv(vertices[1]);
    glVertex2fv(vertices[2]);
    glVertex2fv(vertices[3]);
    glEnd();
}

void display(void)
{

    glClearColor(1.0, 1.0, 1.0, 1.0);
    glClear(GL_COLOR_BUFFER_BIT);
    glMatrixMode(GL_MODELVIEW);
    glShadeModel(GL_SMOOTH);
    glColor3f(0.0f, 0.0f, 0.0f);
    glPushMatrix();
    glLoadIdentity();
    glScalef(2.0, 2.0, 0.0);
    drawObject();
    glPopMatrix();

    glFlush();
}

int main(int argc, char** argv)
{

    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
    glutInitWindowSize(1600, 800);
    glutInitWindowPosition(0, 0);
    glutCreateWindow("Window");
    glutDisplayFunc(display);
    glutMainLoop();
}

Solution

  • With your current coordiantes and transformations, your object is just off the screen.

    When setting all transformation matrices to identity, you are directly drawing in clip space. And if you do never use an input w value other than 1 (glVertex2* will always set w to 1), clip space equals normalized device space. In normalized device space, the viewing volume is defined as the cube [-1,1] along all dimensions.

    However, by applying glScale(2.0, 2.0, 0.0), you scale the object by 2, with the center beeing the origin. As a result, the visible part of the scene is everything in the range [-0.5,0.5] in object space coordinates, and your object is completely outside of that range.

    If you want to scale on a single object, you should first translate it to the center, and apply the scale afterwards. The following sequence of transformations should make your object visible:

    glScalef(2.0f, 2.0f, 1.0f);
    glTranslatef(0.9285f, -0.9285f, 0.0f);
    

    Also note that all of that is deprecated in modern GL. You are relying on the fixed function pipeline with the integrated matrix stack, immediate mode (Begin/End) rendering, GL_POLYGON primitive type, which is all removed from modern core profiles of OpenGL. If you are starting with GL nowadyays, I strongly recommend learning the new way.