OpenGL: Using Geometric Primitives

Using Geometric Primitives

In this lesson, we use the geometric primitives that we covered in OpenGL lesson 2, along with the project from OpenGL lesson 1, to draw an American flag. Recall that in lesson 1, our code drew a simple window with a white diagonal line in it, like this:

Beginning with that code from lesson 1, we first take out the old drawing code, which draws the white line. This leaves us with code to create a plain black window:

Next, we resize the window to fit the dimensions of our flag. The flag has a width that is 1.9 times the height (Incidentally, the size specification for the flag can be found at usflag.org). To get the window scaled properly, we change the dimensions from (250, 250) to (950, 500) by changing arguments that are passed into glutInitWindowSize() inside the main function.

After this the window is larger and much longer. However, the window is still black because we call glClearColor() with four zero parameters. The function glClearColor() sets all pixels that do not get repainted to the color that is passed into it. Now, glClearColor() is called at the start of the Initialize() function. Since we want the background color to be the blue that is the background for the stars of the flag, we change the call to glClearColor() to glClearColor(0.0, 0.0, 102.0/255.0, 0.0). This makes the window blue.

Next, we add a function to draw the stripes from bottom to top. The first six span the entire flag and the last seven are shorter to account for the blue region with the stars in it. The stripes are drawn as reactangles using the GL_QUADS argument and the color alternates between red and white.

Finally, we draw the stars using our DrawStar() function to draw each star and calling that with our DrawStars() function, which cycles through the rows. Recall, from lesson 2, that a star is not a convex object. So, we cannot draw it by using the GL_POLYGON argument. Instead, we use GL_TRIANGLE_FAN to create a set of 10 triangles with one vertex at the center.

Adding the DrawStars() and DrawStar() functions and making the call to DrawStars() from our Draw() function, we get our complete flag.