I have an OpenGL project where I wanted to wrap all the objects in classes. I started with the 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:
// 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:
// 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?
CodePudding user response:
Use std::vector &vertices instead of 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