Unexpected triangles rendered with OpenGL

109 views Asked by At

I want to render blender's default cube and Suzanne. I have them both exported as OBJ-files. Loading and rendering works fine, but when I attempt to render them both in the same scene, things become confusing (to me).

The "relevant" code is in lines 48 to 56.

(I) Screenshot: code + rendered scene

  1. In the beginning there was just model1 (Line 51, Suzanne or a cube or anything else) and the scene was rendered as expected.

  2. Then I added another model2 (Line 54), which happened to be the cube. The unintended triangles (see rendered scene, Screenshot (I)) where drawn ontop of the cube, which was not translated "away" at this point.

  3. Don't know my plans or thoughts of when I moved the cube into the back, but was surprised to find the garbage triangles stay where they are. Since I had no idea where they came from, I started flipping lines around to get my hands on it:

    • It is of no importance whether model1 is rendered first, or model2.
    • When I load two default_cubes instead of one suzanne, one cube is perfectly fine, and the other one just like in the first screenshot.

The result is seen in Screenshot (II). I'm constructing model2 before model1 and the garbage is now rendered differently in a different place.

(II) Screenshot: code + rendered scene

The code below shows the last part of the Model-constructor, where the VBA is configured. The render() function is the one being seen in the screenshots.

   [...]
   glGenVertexArrays( 1, &VBA );
   glBindVertexArray( VBA );

   glGenBuffers( 1, &VBO[0] );
   glBindBuffer( GL_ARRAY_BUFFER, VBO[0] );
   glBufferData( GL_ARRAY_BUFFER, sizeof(glm::vec3) * vertices.size(), vertices.data(), GL_STATIC_DRAW );
   glEnableVertexAttribArray( 0 );
   glVertexAttribPointer( 0, 3, GL_FLOAT, GL_FALSE, 0, 0 );
}


void Model::render( void )
{
  glUniformMatrix4fv( model_location, 1, GL_FALSE, &model_matrix[0][0] );
  glBindVertexArray( VBA );
  // 'vertices' is of type std::vector<glm::vec3>
  glDrawArrays( GL_TRIANGLES, 0, sizeof(glm::vec3) * vertices.size() );
}
1

There are 1 answers

1
BDL On BEST ANSWER

You pass wrong data to glDrawArrays. The third parameter has to contain the number of vertices, not the size in bytes. The correct call would be:

glDrawArrays( GL_TRIANGLES, 0, vertices.size() );