How to have a separate color for each face on my object in OpenGL?

Viewed 59

Total OpenGL noob here... I am trying to color each face of a pyramid in a different color like so:

    glBegin(GL_POLYGON)
    f1 = ((1,-1,-1),(1,-1,1),(0,1,0))
    f2 = ((1,-1,1),(-1,-1,1),(0,1,0))
    f3 = ((-1,-1,-1),(-1,-1,1),(0,1,0))
    f4 = ((1,-1,-1),(-1,-1,-1),(0,1,0))
    f5 = ((1,-1,-1),(1,-1,1),(-1,-1,-1),(-1,-1,1))
    for i in f1:
        glColor3f(0,255,255)
        glVertex3fv(i)
    for i in f2:
        glColor3f(255,0,0)
        glVertex3fv(i)
    for i in f3:
        glColor3f(0,255,0)
        glVertex3fv(i)
    for i in f4:
        glColor3f(255,255,0)
        glVertex3fv(i)
    for i in f5:
        glColor3f(255,0,255)
        glVertex3fv(i)
    glEnd()

but the result is awful... what am i doing wrong? My current pyramid

1 Answers

The primitive type GL_POLYGON makes 1 large polygon out of all vertices in the glBegin/glEnd sequence. Note that OpenGL cannot guess how many points make up a single polygon. You need to draw the polygons in separated glBegin/glEnd sequences:

faces = [
    ((1,-1,-1),(1,-1,1),(0,1,0)),
    ((1,-1,1),(-1,-1,1),(0,1,0)),
    ((-1,-1,-1),(-1,-1,1),(0,1,0)),
    ((1,-1,-1),(-1,-1,-1),(0,1,0)),
    ((1,-1,-1),(1,-1,1),(-1,-1,-1),(-1,-1,1))
]
colors = [(0,255,255), (255,0,0), (0,255,0), (255,255,0), (255,0,255)]

for face, color in zip(faces, colors):
    glColor3fv(color)
    
    glBegin(GL_POLYGON)
    for vertex in face:
        glVertex3fv(vertex)
    glEnd()

Alternatively, you can draw GL_TRIANGLES and make the bottom of the pyramid by 2 triangles:

tringles = [
    ((1,-1,-1),   (1,-1,1),   (0,1,0)),
    ((1,-1,1),   (-1,-1,1),  (0,1,0)),
    ((-1,-1,-1), (-1,-1,1),  (0,1,0)),
    ((1,-1,-1),  (-1,-1,-1), (0,1,0)),
    ((1,-1,-1),  (1,-1,1),   (-1,-1,-1)),
    ((1,-1,-1),  (-1,-1,-1), (-1,-1,1))
]
colors = [
    (0,255,255), (255,0,0), (0,255,0), (255,255,0), 
    (255,0,255), (255,0,255)
]

glBegin(GL_TRINAGLES)
for tringle, color in zip(tringles, colors):
    glColor3fv(color)
    for vertex in triangle:
        glVertex3fv(vertex)
glEnd()
Related