/*
 * GLLoader.cpp
 *
 *  Created on: 4 nov. 2020
 *      Author: simon
 */


#include "render/loader/GLLoader.h"
#include "render/GL.h"

namespace GL {

VertexArray::~VertexArray() {
	if (m_ID != 0)
		glDeleteVertexArrays(1, &m_ID);
}

VertexArray::VertexArray(unsigned int vertexCount) : m_VertexCount(vertexCount) {
	glGenVertexArrays(1, &m_ID);
}

void VertexArray::bind() const {
	glBindVertexArray(m_ID);
}

void VertexArray::unbind() const {
	glBindVertexArray(0);
}

void VertexArray::bindVertexBuffer(VertexBuffer& VertexBuffer) {
	VertexBuffer.bind();
	VertexBuffer.bindVertexAttribs();
	m_VertexBuffers.push_back(std::move(VertexBuffer));
}

VertexBuffer::~VertexBuffer() {
	if (m_ID != 0)
		glDeleteBuffers(1, &m_ID);
}

VertexBuffer::VertexBuffer(const std::vector<float>& data, unsigned int stride) : m_DataStride(stride) {
	glGenBuffers(1, &m_ID);
	bind();
	glBufferData(GL_ARRAY_BUFFER, data.size() * sizeof(float), nullptr, GL_STATIC_DRAW);
	glBufferSubData(GL_ARRAY_BUFFER, 0, data.size() * sizeof(float), data.data());
	unbind();
}

void VertexBuffer::bind() const {
	glBindBuffer(GL_ARRAY_BUFFER, m_ID);
}

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

void VertexBuffer::addVertexAttribPointer(unsigned int index, unsigned int coordinateSize, unsigned int offset) {
	VertexAttribPointer pointer;
	pointer.m_Index = index;
	pointer.m_Size = coordinateSize;
	pointer.m_Offset = offset;
	m_VertexAttribs.push_back(pointer);
}

void VertexBuffer::bindVertexAttribs() const {
	for (const VertexAttribPointer& pointer : m_VertexAttribs) {
		glEnableVertexAttribArray(pointer.m_Index);
		glVertexAttribPointer(pointer.m_Index, pointer.m_Size, GL_FLOAT, false, m_DataStride * sizeof(float), (void*)(intptr_t)pointer.m_Offset);
	}
}
}