VertexBuffer混合顶点

时间:2019-05-18 18:02:01

标签: c++ opengl

我正在尝试从简单的2D渲染器更改为批处理渲染器,它几乎可以正常工作,除了似乎第二次调用使顶点混合的事实。我尝试更改所有内容,从缓冲区数据和AttribPointer到VertexCount和顶点本身,仍然在代码中给定位置(0,0)和大小(1,1)的红色正方形,但在第二个红色正方形上应该在第一个得到红色三角形的位置上绘制,然后在第三个得到相同的红色正方形的位置上绘制,第四个得到三角形的位置,依此类推...

着色器仅获得位置0 vec2,并且gl_Position设置为该位置。

#define RENDERER_MAX_SPRITES 10000
#define RENDERER_SPRITE_SIZE (sizeof(float) * 2)
#define RENDERER_BUFFER_SIZE (RENDERER_SPRITE_SIZE * 6 * RENDERER_MAX_SPRITES)

void BatchRenderer::Initialize() {
    glGenVertexArrays(1, &VAO);
    glBindVertexArray(VAO);

    glGenBuffers(1, &VBO);
    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBufferData(GL_ARRAY_BUFFER, RENDERER_BUFFER_SIZE, nullptr, GL_DYNAMIC_DRAW);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, RENDERER_SPRITE_SIZE, (void*)0);
    glBindVertexArray(0);
}

void BatchRenderer::Add(iVec2 position, iVec2 size, Color& color, Texture& texture) {
    glBindVertexArray(VAO);
    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    float vertices[12] = {
        position.x,          position.y,         
        position.x,          position.y + size.y,
        position.x + size.x, position.y + size.y,
        position.x + size.x, position.y + size.y,
        position.x + size.x, position.y,         
        position.x,          position.y      
    };

    glBufferSubData(GL_ARRAY_BUFFER, VertexSum, sizeof(vertices), &vertices);
    VertexSum += 12;
    VertexCount += 6;
    glBindVertexArray(0);
}

void BatchRenderer::Flush() {
    shader.Use();
    glBindVertexArray(VAO);
    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glDrawArrays(GL_TRIANGLES, 0, VertexCount);
    glBindVertexArray(0);
    VertexCount = 0;
    VertexSum = 0;
}

1 个答案:

答案 0 :(得分:3)

对于第二个参数,glBufferSubData期望偏移量以字节为单位。这意味着对于您的Add每六个顶点,偏移量应提前6*2*sizeof(float)或等效地sizeof(vertices)

glBufferSubData(GL_ARRAY_BUFFER, VertexSum, sizeof(vertices), &vertices);
VertexSum += sizeof(vertices);
VertexCount += 6;