#include #include "shape_renderer.h" #include "math/math.h" ShapeRenderer::ShapeRenderer(unsigned int screen_width, unsigned int screen_height) { math::ortho_proj(_projection, 0.0f, (float)screen_width, 0.0f, (float)screen_height, -1.0f, 1.0f); /* Load shader. */ _shape_shader = new Shader("assets/shaders/shape.vert", "assets/shaders/shape.frag"); _shape_shader->use(); _shape_shader->set_mat4("projection", _projection); /* Configure VAO/VBO. */ glGenVertexArrays(1, &_vao); glGenBuffers(1, &_vbo); glBindVertexArray(_vao); glBindBuffer(GL_ARRAY_BUFFER, _vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 6 * 2, NULL, GL_DYNAMIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), 0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); } ShapeRenderer::~ShapeRenderer(void) { delete _shape_shader; } void ShapeRenderer::draw_rect(int x, int y, int width, int height, const Color& color) { _shape_shader->use(); _shape_shader->set_vec3("objectColor", color.r, color.g, color.b); float x_f = (float)x; float y_f = (float)y; float w_f = (float)width; float h_f = (float)height; /* This is ugly :) */ float vertices[6][2] = { { x_f, y_f + h_f }, { x_f, y_f }, { x_f + w_f, y_f }, { x_f, y_f + h_f }, { x_f + w_f, y_f }, {x_f + w_f, y_f + h_f } }; glBindVertexArray(_vao); glBindBuffer(GL_ARRAY_BUFFER, _vbo); glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vertices), vertices); glDrawArrays(GL_TRIANGLES, 0, 6); glBindVertexArray(0); } void ShapeRenderer::draw_triangle(int x1, int y1, int x2, int y2, int x3, int y3, const Color& color) { _shape_shader->use(); _shape_shader->set_vec3("objectColor", color.r, color.g, color.b); float vertices[3][2] = { {(float)x1, (float)y1}, {(float)x2, (float)y2}, {(float)x3, (float)y3}, }; glBindVertexArray(_vao); glBindBuffer(GL_ARRAY_BUFFER, _vbo); /* * We're overwriting the buffer content here, this is fine for just one triangle, * but don't do it for everything ;) */ glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vertices), vertices); glDrawArrays(GL_TRIANGLES, 0, 3); glBindVertexArray(0); }