66 lines
1.7 KiB
C++
66 lines
1.7 KiB
C++
#pragma once
|
|
|
|
#include <exception>
|
|
#include <vector>
|
|
#include <glad/glad.h>
|
|
|
|
struct Vertex {
|
|
float x, y, z; // position
|
|
float r, g, b; // color
|
|
float u, v; // texcoord
|
|
// = 8 floats = 32 bytes
|
|
};
|
|
|
|
class Mesh
|
|
{
|
|
public:
|
|
unsigned int VBO, VAO, EBO;
|
|
std::size_t indexCount = 0;
|
|
|
|
Mesh(const std::vector<Vertex>& vertices, const std::vector<unsigned int>& indices) : indexCount(indices.size())
|
|
{
|
|
if (vertices.empty() || indices.empty()) {
|
|
throw std::runtime_error("Mesh created with empty vertices or indices");
|
|
}
|
|
|
|
try
|
|
{
|
|
glGenVertexArrays(1, &VAO);
|
|
glGenBuffers(1, &VBO);
|
|
glGenBuffers(1, &EBO);
|
|
|
|
std::cout << VAO << std::endl;
|
|
std::cout << VBO << std::endl;
|
|
std::cout << EBO << std::endl;
|
|
|
|
glBindVertexArray(VAO);
|
|
|
|
glBindBuffer(GL_ARRAY_BUFFER, VBO);
|
|
glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(Vertex), vertices.data(), GL_STATIC_DRAW);
|
|
|
|
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
|
|
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned int), indices.data(), GL_STATIC_DRAW);
|
|
|
|
// position attribute
|
|
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, x));
|
|
glEnableVertexAttribArray(0);
|
|
// color attribute
|
|
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, r));
|
|
glEnableVertexAttribArray(1);
|
|
// texture coord attribute
|
|
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, u));
|
|
glEnableVertexAttribArray(2);
|
|
}
|
|
catch (...)
|
|
{
|
|
std::cout << "Failed to load mesh" << std::endl;
|
|
}
|
|
}
|
|
|
|
void Draw() const
|
|
{
|
|
glBindVertexArray(VAO);
|
|
glDrawElements(GL_TRIANGLES, static_cast<GLsizei>(indexCount),
|
|
GL_UNSIGNED_INT, nullptr);
|
|
}
|
|
};
|