Programming and Graphics

(Kiana) #1

260 Introduction to C++ Programming and Graphics


As an example, the following function draws the solid disk shown in
Figure 8.1.1(d):


void disk()
{
int N=64;
float Dthet =2.0*3.1415926/N;
float centerx=0.0, centery=0.0;
float radius=1.0;

glClear(GLCOLORBUFFERBIT);

glBegin(GLTRIANGLEFAN);
glColor3f(0.8,0.5,0.2);
glVertex2f(centerx,centery);
for (int i=0; i<=N; i++)
{
float angle = i*Dtheta;
glVertex2f(cos(angle)*radius,sin(angle)*radius);
}
glEnd();

glFlush();
}

The disk is defined by a group ofNtriangles with one common vertex at the
disk center.


Cube


Three-dimensional graphics can be drawn in similar ways. The following
function paints the cube shown in Figure 8.1.1(e):


void cube(void)
{

glClear(GLCOLORBUFFERBIT);

/* Introduce a transformation matrix.
All vertices will be multiplied by this matrix */

glLoadIdentity(); // introduce the identity matrix

glOrtho(-8.0, 8.0, -8.0, 8.0, -8.0, 8.0); // set the axes

glTranslatef(-0.5, 0.2, 0.1); // translate the identity matrix
glRotatef(-50, 1.0, 0.0, 0.0); // rotate by 50 deg about the x axis
glRotatef(50, 0.0, 1.0, 0.0); // rotate by 50 deg about the y axis
Free download pdf