]> git.lizzy.rs Git - dragonblocks_alpha.git/blob - src/mesh.c
Append .zip to ZIP files generated by release script
[dragonblocks_alpha.git] / src / mesh.c
1 #include <stdlib.h>
2 #include <stddef.h>
3 #include "mesh.h"
4
5 Mesh *mesh_create(Vertex *vertices, GLsizei count)
6 {
7         Mesh *mesh = malloc(sizeof(Mesh));
8         mesh->pos = (v3f) {0.0f, 0.0f, 0.0f};
9         mesh->rot = (v3f) {0.0f, 0.0f, 0.0f};
10         mesh->scale = (v3f) {1.0f, 1.0f, 1.0f};
11         mesh_transform(mesh);
12         mesh->angle = 0.0f;
13         mesh->VAO = 0;
14         mesh->VBO = 0;
15         mesh->remove = false;
16         mesh->vertices = vertices;
17         mesh->count = count;
18         return mesh;
19 }
20
21 #pragma GCC diagnostic push
22 #pragma GCC diagnostic ignored "-Wpedantic"
23
24 void mesh_transform(Mesh *mesh)
25 {
26         mat4x4_translate(mesh->transform, mesh->pos.x, mesh->pos.y, mesh->pos.z);
27         mat4x4_rotate(mesh->transform, mesh->transform, mesh->rot.x, mesh->rot.y, mesh->rot.z, mesh->angle);
28         mat4x4_scale_aniso(mesh->transform, mesh->transform, mesh->scale.x, mesh->scale.y, mesh->scale.z);
29 }
30
31 #pragma GCC diagnostic pop
32
33 void mesh_delete(Mesh *mesh)
34 {
35         if (mesh->vertices)
36                 free(mesh->vertices);
37         if (mesh->VAO)
38                 glDeleteVertexArrays(1, &mesh->VAO);
39         if (mesh->VBO)
40                 glDeleteBuffers(1, &mesh->VAO);
41         free(mesh);
42 }
43
44 static void mesh_configure(Mesh *mesh)
45 {
46         glGenVertexArrays(1, &mesh->VAO);
47         glGenBuffers(1, &mesh->VBO);
48
49         glBindVertexArray(mesh->VAO);
50         glBindBuffer(GL_ARRAY_BUFFER, mesh->VBO);
51
52         glBufferData(GL_ARRAY_BUFFER, mesh->count * sizeof(Vertex), mesh->vertices, GL_STATIC_DRAW);
53
54         glVertexAttribPointer(0, 3, GL_FLOAT, false, sizeof(Vertex), (GLvoid *) offsetof(Vertex, x));
55         glEnableVertexAttribArray(0);
56         glVertexAttribPointer(1, 3, GL_FLOAT, false, sizeof(Vertex), (GLvoid *) offsetof(Vertex, r));
57         glEnableVertexAttribArray(1);
58
59         glBindBuffer(GL_ARRAY_BUFFER, 0);
60         glBindVertexArray(0);
61
62         free(mesh->vertices);
63         mesh->vertices = NULL;
64 }
65
66 void mesh_render(Mesh *mesh, ShaderProgram *prog)
67 {
68         if (mesh->vertices)
69                 mesh_configure(mesh);
70
71         glUniformMatrix4fv(prog->loc_model, 1, GL_FALSE, mesh->transform[0]);
72
73         glBindVertexArray(mesh->VAO);
74         glDrawArrays(GL_TRIANGLES, 0, mesh->count);
75         glBindVertexArray(0);
76 }