Home > Enterprise >  openGL rectangle rendering triangle instead?
openGL rectangle rendering triangle instead?

Time:05-28

So i'm trying to render a rectangle in openGL using index buffers however instead i'm getting a triangle with one vertex at the origin (even though no vertex in my rectangle is suppsoed to go at the origin).

Screenshot of the triangle in wireframe mode

void Renderer::drawRect(int x,int y,int width, int height)
{   

    //(Ignoring method arguments for debugging)
    float vertices[12] = {200.f, 300.f, 0.f,
                          200.f, 100.f, 0.f,
                          600.f, 100.f, 0.f,
                          600.f, 300.f, 0.f};

    unsigned int indices[6] = {0,1,3,1,2,3};

    glBindVertexArray(this->flat_shape_VAO);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,this->element_buffer);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER,sizeof(indices),indices,GL_DYNAMIC_DRAW);

    glBindBuffer(GL_ARRAY_BUFFER,this->render_buffer);
    glBufferData(GL_ARRAY_BUFFER,sizeof(vertices),vertices,GL_DYNAMIC_DRAW);

    glEnableVertexAttribArray(0);

    glUseProgram(this->shader_program);
    glUniformMatrix4fv(this->model_view_projection_uniform,1,GL_FALSE,glm::value_ptr(this->model_view_projection_mat));
    glUniform3f(this->color_uniform,(float) this->color.r,(float)this->color.g,(float)this->color.b);
    glDrawElements(GL_TRIANGLES,6,GL_UNSIGNED_INT,nullptr);

}

My projection matrix is working fine I can still render a triangle at the correct screen coords. I suspect maybe I did index buffering wrong? Transformation matrices also work fine, atleast on my triangles.

Edit:

The VAO's attributes are set up in the class constructor with glVertexAttribPointer();

Edit 2: I disabled shaders completely and something interesting

Here is the shader source code: (vertex shader)

    #version 330 core
    layout (location = 0) in vec3 aPos;
    uniform mat4 mvp;
    uniform vec3 aColor;
    out vec3 color;
    void main()
    {
       gl_Position = mvp * vec4(aPos, 1.0);
       color = aColor;

    }

(fragment shader)


    #version 330 core
    in vec3 color;
    out vec4 FragColor;
    void main()
    {
       FragColor = vec4(color,1.0f);
    }

My projection matrix shouldn't work with shaders disabled yet I still see a triangle rendering on the screen..??

CodePudding user response:

What is the stride argument of glVertexAttribPointer? stride specifies the byte offset between consecutive generic vertex attributes. In your case it should be 0 or 12 (3*sizeof(float)) but if you look at your images it seems to be 24 because the triangle has the 1st (200, 300) and 3rd (600, 100) vertices and one more vertex with the coordinate (0, 0).

glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), nullptr);

glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), nullptr);
  • Related