I wanted to create a class to handle OpenGL buffers like vertex buffers objects or colorbuffers.
Here is the buffer.h:
#pragma once
#include <GL/glew.h>
class glBuffer
{
public:
glBuffer(GLenum target);
void setdata(const void *data, GLenum mode);
void bind(GLuint index, GLint valuePerVertex, GLenum variableType = GL_FLOAT, GLsizei stride = 0, int offset = 0);
void unbind();
GLuint getBufferID() const;
~glBuffer();
private:
bool m_active;
GLuint m_buffer;
GLuint m_index;
GLenum m_target;
};
And buffer.cpp:
#include "buffer.h"
#include <GL/glew.h>
#include <iostream>
glBuffer::glBuffer(GLenum target)
{
m_target = target;
m_active = false;
glGenBuffers(1, &m_buffer);
}
void glBuffer::setdata(const void *data, GLenum mode)
{
glBindBuffer(m_target, m_buffer);
glBufferData(m_target, sizeof(data), data, mode);
glBindBuffer(m_target, 0);
}
void glBuffer::bind(GLuint index, GLint valuePerVertex, GLenum variableType, GLsizei stride, int offset)
{
m_active = true;
m_index = index;
glEnableVertexAttribArray(m_index);
glBindBuffer(m_target, m_buffer);
glVertexAttribPointer(
m_index,
valuePerVertex,
variableType,
GL_FALSE, //normalized?
stride,
(void*)offset //buffer offset
);
}
void glBuffer::unbind()
{
m_active = false;
glBindBuffer(m_target, 0);
glDisableVertexAttribArray(m_index);
}
GLuint glBuffer::getBufferID() const
{
return m_buffer;
}
glBuffer::~glBuffer()
{
if (!m_active){
unbind();
}
glDeleteBuffers(1, &m_buffer);
}
Here is how I use it in my application, where I #include "buffer.h" :
glBuffer vbo(GL_ARRAY_BUFFER);
vbo.setdata(color_buffer_data, GL_STATIC_DRAW);
vbo.bind(0, 3);
Replaces :
GLuint vbo;
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertex_buffer_data), vertex_buffer_data, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glVertexAttribPointer(
0, // attribute 0. No particular reason for 0, but must match the layout in the shader.
3, // size
GL_FLOAT, // type
GL_FALSE, // normalized?
0, // stride
(void*)0 // array buffer offset
);
When I compile and run it, I get a black window without anything drawn.
What is happening?
PS: I'm using vs, glfw3, glew.
sizeof(data)inglBuffer::setdata()is going to be4or8on most platforms, not the length ofdatalike you seem to hope. Pass in a separatesizeargument or use a container likestd::array<>/std::vector<>. - genpfault