summaryrefslogtreecommitdiff
path: root/src/mesh.c
blob: 6b2951b76d57d6ae9ac5e7ecbedea4aa8ccb69b8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include <GL/glew.h>

#include "mesh.h"

void mesh_init(Mesh *mesh, int vertex_count)
{
	glGenVertexArrays(1, &mesh->vao);
	mesh->vbos_count = 0;
	mesh->vertex_count = vertex_count;
	glBindVertexArray(mesh->vao);
}

static void mesh_store(Mesh *mesh, void *data, int data_len, int dimensions, GLenum type)
{
	GLuint vbo;
	GLint index = mesh->vbos_count;
	glGenBuffers(1, &vbo);
	glBindBuffer(GL_ARRAY_BUFFER, vbo);
	glBufferData(GL_ARRAY_BUFFER, data_len, data, GL_STATIC_DRAW);
	glEnableVertexAttribArray(index);
	if (type == GL_FLOAT)
		glVertexAttribPointer(index, dimensions, type, GL_FALSE, 0, 0);
	else
		glVertexAttribIPointer(index, dimensions, type, 0, 0);
	mesh->vbos[mesh->vbos_count++] = vbo;
}

void mesh_storef(Mesh *mesh, float *data, int data_len, int dimensions)
{
	mesh_store(mesh, data, data_len * sizeof(float), dimensions, GL_FLOAT);
}

void mesh_storei(Mesh *mesh, int *data, int data_len, int dimensions)
{
	mesh_store(mesh, data, data_len * sizeof(int), dimensions, GL_INT);
}

void mesh_storeu(Mesh *mesh, unsigned int *data, int data_len, int dimensions)
{
	mesh_store(mesh, data, data_len * sizeof(unsigned int), dimensions,
		   GL_UNSIGNED_INT);
}

void mesh_storeb(Mesh *mesh, unsigned char *data, int data_len, int dimensions)
{
	mesh_store(mesh, data, data_len * sizeof(unsigned char), dimensions,
		   GL_UNSIGNED_BYTE);
}

void mesh_finish(void)
{
	glBindVertexArray(0);
}

void mesh_bind(Mesh *mesh)
{
	glBindVertexArray(mesh->vao);
	for (int i = 0; i < mesh->vbos_count; i++)
		glEnableVertexAttribArray(i);
}

void mesh_unbind(Mesh *mesh)
{
	for (int i = 0; i < mesh->vbos_count; i++)
		glDisableVertexAttribArray(i);
	glBindVertexArray(0);
}

void mesh_draw(Mesh *mesh)
{
	glDrawArrays(GL_TRIANGLES, 0, mesh->vertex_count);
}

void mesh_free(Mesh *mesh)
{
	glDeleteBuffers(mesh->vbos_count, mesh->vbos);
	glDeleteVertexArrays(1, &mesh->vao);
}