简体   繁体   English

OpenGL VBO 放入 class 时不显示任何内容

[英]OpenGL VBO doesn't show anything when it is put in a class

I have an OpenGL project where I wanted to wrap all the objects in classes.我有一个 OpenGL 项目,我想将所有对象包装在类中。 I started with the VBO.我从 VBO 开始。 Before wrapping, the code looked something like this:在包装之前,代码看起来像这样:

// includes
int main()
{
    // init OpenGL
    GLfloat vertices[] = {
        // vertices
    };
    GLint VBO;
    glGenBuffers(1, &VBO);
    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
    // more stuff
    // create VAO
    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    // more stuff
}

This works as intended.这按预期工作。 I made a class that looks like this:我做了一个看起来像这样的 class:

// vbo.h
#ifndef VBO_H
#define VBO_H

// includes

class VBO
{
public:
    VBO(GLfloat *, GLenum);
    ~VBO();

    void bind();
    void unbind();

    GLuint id;
};

#endif

// vbo.cpp
#include "vbo.h"

VBO::VBO(GLfloat *vertices, GLenum type)
{
    glGenBuffers(1, &id);
    glBindBuffer(GL_ARRAY_BUFFER, id);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, type);
}

VBO::~VBO()
{
    glDeleteBuffers(1, &id);
}

void VBO::bind()
{
    glBindBuffer(GL_ARRAY_BUFFER, id);
}

void VBO::unbind()
{
    glBindBuffer(GL_ARRAY_BUFFER, 0);
}

and changed main to look like this:并将 main 更改为如下所示:

// includes
#include "vbo.h"

int main()
{
    // init OpenGL
    GLfloat vertices[] = {
        // vertices
    };
    VBO vbo(vertices, GL_STATIC_DRAW);
    // more stuff
    // create VAO
    vbo.bind();
    // more stuff
}

And now it doesn't render anything.现在它不渲染任何东西。 I am using OpenGL version 3.3 core profile, what am I doing wrong?我正在使用 OpenGL 3.3 版核心配置文件,我做错了什么?

Use std::vector &vertices instead of float*使用 std::vector &vertices 而不是 float*

VBO::VBO(std::vector<float> &vertices, GLenum type)
{
    glGenBuffers(1, &id);
    glBindBuffer(GL_ARRAY_BUFFER, id);
    glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(float), &vertices[0], type);
}

Also would be a good idea to create custom Constructor and assignment operator, incase you build multiple copies all of them will share the same VAO and VBO and if one gets deleted all of them will hold invalid VAO's and VBO's创建自定义构造函数和赋值运算符也是一个好主意,以防您构建多个副本,所有副本都将共享相同的 VAO 和 VBO,如果一个被删除,所有副本都将持有无效的 VAO 和 VBO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM