#include <GL/glew.h>
#include "vertexBuffer.h"

namespace render{

vertexBuffer::vertexBuffer()
{
    obj = 0;
    mode = GL_ARRAY_BUFFER;
}

vertexBuffer::~vertexBuffer()
{
    free();
}

void vertexBuffer::gen()
{
    if(glIsBuffer(obj))
        return;
    _alloc();
    glGenBuffers(1, &obj);
}

void vertexBuffer::_alloc()
{
    _addToList();
}

void vertexBuffer::free()
{
    if(obj)
    {
        unbind();
        glDeleteBuffers(1, &obj);
        obj = 0;
    }
    _removeFromList();
}

void vertexBuffer::bind(int m)
{
    if(m)
        mode = m;
    if(obj)
        glBindBuffer(mode, obj);
}

void vertexBuffer::unbind()
{
    glBindBuffer(mode, 0);
}

void vertexBuffer::createEmptyBuffer(unsigned size, unsigned usage)
{
    if(!obj)
        gen();
    bind();
    glBufferData(mode, size, 0, usage);
}

void vertexBuffer::_data(unsigned size, const void *data, unsigned usage)
{
    bind();
    glBufferData(mode, size, data, usage);
}

void vertexBuffer::_subData(unsigned size, const void *data, int offset)
{
    bind();
    glBufferSubData(mode, offset, size, data);
}

}
