Sunday, April 21, 2013

GL_TRIANGLES example c/c++ java


GL_TRIANGLESDraws triangles on screen. Every three vertices specified compose a triangle.

Drawing Triangles

Triangles are composed of three vertices. For this example we are going to use the regular GL_TRIANGLES mode to draw two triangles side by side.
First we want a triangle to the left. So we need three vertices on the left side representing one triangle and three vertices on the right side of the window representing the second triangle. Note that you don’t need two glBegin() functions to draw two triangles. Since the mode GL_TRIANGLES is plural, it can handle more than one triangle in between one glBegin() and glEnd() function call:
Note that I wrote on the bottom – right corner of the diagram the coordinates of the vertices. Here is the code to draw these two triangles:
Example of GL_TRIANGLES
    glBegin(GL_TRIANGLES);//start drawing triangles
      glVertex3f(-1.0f,-0.25f,0.0f);//triangle one first vertex
      glVertex3f(-0.5f,-0.25f,0.0f);//triangle one second vertex
      glVertex3f(-0.75f,0.25f,0.0f);//triangle one third vertex
      //drawing a new triangle
      glVertex3f(0.5f,-0.25f,0.0f);//triangle two first vertex
      glVertex3f(1.0f,-0.25f,0.0f);//triangle two second vertex
      glVertex3f(0.75f,0.25f,0.0f);//triangle two third vertex
    glEnd();//end drawing of triangles
Following is the whole Render() function for this example followed by a sample output. 
void Render()
{     
    //clear color and depth buffer 
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glLoadIdentity();//load identity matrix
    
    glTranslatef(0.0f,0.0f,-4.0f);//move forward 4 units
    
    glColor3f(0.0f,0.0f,1.0f); //blue color
    
    glBegin(GL_TRIANGLES);//start drawing triangles
      glVertex3f(-1.0f,-0.25f,0.0f);//triangle one first vertex
      glVertex3f(-0.5f,-0.25f,0.0f);//triangle one second vertex
      glVertex3f(-0.75f,0.25f,0.0f);//triangle one third vertex
      //drawing a new triangle
      glVertex3f(0.5f,-0.25f,0.0f);//triangle two first vertex
      glVertex3f(1.0f,-0.25f,0.0f);//triangle two second vertex
      glVertex3f(0.75f,0.25f,0.0f);//triangle two third vertex
    glEnd();//end drawing of triangles
}