Untitled

mail@pastecode.io avatar
unknown
c_cpp
2 years ago
2.8 kB
4
Indexable
Never
#include "Renderer.hpp"
#include <gl/glew.h>
#include <glm/ext/matrix_transform.hpp>

#include "Shader.hpp"

namespace Engine
{
    struct Vertex
    {
        glm::vec3 coords;
        glm::vec3 color;
        glm::vec2 texCoords{0.0f, 0.0f};
    };


    std::vector<Vertex> vertices{};
    std::vector<unsigned int> indices{};

    void Renderer::Setup()
    {
        glGenVertexArrays(1, &vao);
    }

    void Renderer::NextBatch()
    {
        glBindVertexArray(vao);
        vertices.clear();
    }

    void Renderer::DrawQuad(glm::vec2 offset, glm::vec3 color, glm::vec3 scale, float rotation)
    {
        const float size = 0.5f;


        static float verts[] =
        {
            -size, size, 0, // top left
            -size, -size, 0, // bottom left
            size, -size, 0, // bottom right
            size, -size, 0, // bottom right
            size, size, 0, // top right
            -size, size, 0 // top left
        };

        const float textCoords[] = {
            0, 1,
            0, 0,
            1, 0,
            1, 0,
            1, 1,
            0, 1
        };


        for (int i = 0; i < sizeof(verts) / sizeof(float); i += 3)
        {
            Vertex vertex{};
            glm::vec3 coords = glm::vec3(verts[i], verts[i + 1], verts[i + 2]);

            glm::mat4 transform = glm::translate(glm::mat4(1.0), glm::vec3(offset.x, offset.y, 0));
            transform = glm::rotate(transform, glm::radians(rotation), glm::vec3(0, 0, 1));
            transform = glm::scale(transform, glm::vec3(scale.x, scale.y, 1));
            vertex.coords = transform * glm::vec4(coords, 1);

            vertex.texCoords = glm::vec2(textCoords[i], textCoords[i + 1]);

            vertex.color = color;
            vertices.push_back(vertex);
        }
    }

    void Renderer::DrawBatch()
    {
        glBindVertexArray(vao);
        glGenBuffers(1, &vbo);
        glBindBuffer(GL_ARRAY_BUFFER, vbo);
        glBufferData(GL_ARRAY_BUFFER, sizeof(Vertex) * vertices.size(), &vertices[0], GL_STATIC_DRAW);

        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)0);
        glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)(sizeof(glm::vec3)));
        glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)(sizeof(glm::vec3) * 2));
        glEnableVertexAttribArray(0);
        glEnableVertexAttribArray(1);
        glEnableVertexAttribArray(2);

        glDrawArrays(GL_TRIANGLES, 0, vertices.size());

        glDisableVertexAttribArray(0);
        glDisableVertexAttribArray(1);
        glDisableVertexAttribArray(2);

        glBindVertexArray(0);
        glDeleteBuffers(1, &vbo);
    }
}