0

我正在使用 OpenGL 渲染一些立方体,我已经设法渲染了大约 10 个立方体,但是我现在想将代码抽象到类中。我从顶点数组对象开始。

我已经查看了代码并将其跟踪到着色器,以确保顶点数据到达它需要的位置。

#include "cube_vertex_array.h"

cube_vertex_array::cube_vertex_array(float* vertex_buffer, const std::string& texture_file)
{
    GLCall(glGenVertexArrays(1, &va_ID));
    GLCall(glBindVertexArray(va_ID));

GLCall(glGenBuffers(1, &vb_ID));
GLCall(glBindBuffer(GL_ARRAY_BUFFER, vb_ID));
GLCall(glBufferData(GL_ARRAY_BUFFER, sizeof(vertex_buffer), vertex_buffer, GL_STATIC_DRAW));
GLCall(glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(0 * sizeof(float))));
GLCall(glEnableVertexAttribArray(0));
GLCall(glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(3 * sizeof(float))));
GLCall(glEnableVertexAttribArray(1));

GLCall(glGenTextures(1, &texture));
GLCall(glBindTexture(GL_TEXTURE_2D, texture));
GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT));
GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT));
GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR));
GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR));
int width, height, nrChanells;
stbi_set_flip_vertically_on_load(true);
unsigned char* data = stbi_load(texture_file.c_str(), &width, &height, &nrChanells, 0);
if (data)
{
    GLCall(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data));
    GLCall(glGenerateMipmap(GL_TEXTURE_2D));
}
else { std::cout << "failed to load texture" << std::endl; }
stbi_image_free(data);

GLCall(glBindVertexArray(0));
}

void cube_vertex_array::bind()
{
    GLCall(glBindVertexArray(va_ID));
}

此外,这是使用此类的 main() 部分:

main()
{
cube_vertex_array cube_1(vertices, "resources/test.png");
cube_1.bind();
while (!glfwWindowShouldClose(window))
    {
    cube_1.bind();
    GLCall(glDrawArrays(GL_TRIANGLES, 0, 36));
    }
    GLCall(glDeleteVertexArrays(1, &cube_1.va_ID));                                                                             
GLCall(glDeleteBuffers(1, &cube_1.vb_ID));
}   

我希望看到多个立方体呈现,但这不会发生。如果我将顶点数组直接实现到主文件中,则代码会呈现立方体,但是在抽象为类时它不会呈现任何内容。这里可能是什么问题?

4

1 回答 1

1

问题是你sizeof(vertex_buffer)在这条线上“打电话”:

GLCall(glBufferData(GL_ARRAY_BUFFER, sizeof(vertex_buffer), vertex_buffer, GL_STATIC_DRAW));

vertex_buffer是指向数组的指针,因此如果您“调用”sizeof它,您将获得 a 的大小,float*而不是数组中元素的数量 times sizeof(float)

解决此问题的一种方法是将数组的大小作为参数传递。您可以做的另一件事是发送数组中的元素数量并将其乘以 sizeof(float)。

于 2019-02-14T01:12:19.907 回答