-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbrick.c
132 lines (104 loc) · 2.49 KB
/
brick.c
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
#include <stdlib.h>
#include <stdio.h>
#include <GL/glew.h>
#include "brick.h"
#include "linmath.h"
#include "constants.h"
#include "shader.h"
#include "model.h"
#include "mesh.h"
#include "objects.h"
#include "utils.h"
static const float SCALE_FACTOR = 0.2;
static int mesh_ref_count = 0;
static struct mesh *mesh = NULL;
static struct mesh *
brick_mesh(void)
{
if (mesh != NULL) {
++mesh_ref_count;
return mesh;
}
mesh = mesh_load("resource/brick.obj");
return mesh;
}
static void
brick_mesh_free(void)
{
if (mesh == NULL)
return;
--mesh_ref_count;
if (mesh_ref_count == 0) {
mesh_free(mesh);
mesh = NULL;
}
}
struct brick *
brick_new(void)
{
struct brick *b = malloc(sizeof *b);
b->x = b->y = b->z = 0.0;
b->mesh = brick_mesh();
b->alive = GL_TRUE;
return b;
}
void
brick_free(struct brick *b)
{
free(b);
brick_mesh_free();
}
static int brick_object_type(const struct brick *b)
{
switch (b->type) {
case NORMAL:
return OBJECT_BRICK;
case HARD:
return OBJECT_HARD_BRICK;
default:
break;
}
fprintf(stderr, "Unknown brick type '%d'\n", b->type);
return OBJECT_BRICK;
}
void
brick_draw(void *object, GLuint shader_program)
{
struct brick *brick = (struct brick *) object;
shader_set_uniform_m4(shader_program, "model", brick->model_matrix);
shader_set_uniform_m4(shader_program, "normalModel", brick->normal_matrix);
shader_set_uniform_i(shader_program, "objectType",
brick_object_type(brick));
glBindVertexArray(brick->mesh->vao);
glDrawArrays(GL_TRIANGLES, 0, brick->mesh->vertex_count);
glBindVertexArray(0);
}
static void
recalculate_matrices(struct brick *b)
{
mat4x4_identity(b->model_matrix);
mat4x4_scale_aniso(b->model_matrix, b->model_matrix,
SCALE_FACTOR, SCALE_FACTOR, SCALE_FACTOR);
mat4x4_translate_in_place(b->model_matrix, b->x, b->y, b->z);
mat4x4_invert(b->normal_matrix, b->model_matrix);
mat4x4_transpose(b->normal_matrix, b->normal_matrix);
}
static void
update_bounding_box(struct brick *b)
{
b->box = b->mesh->bounding_box;
mat4x4_mul_vec3(b->box.min, b->model_matrix, b->box.min);
mat4x4_mul_vec3(b->box.max, b->model_matrix, b->box.max);
}
void
brick_update(void *object)
{
struct brick *b = (struct brick *) object;
recalculate_matrices(b);
update_bounding_box(b);
}
void
brick_set_alive(struct brick *b, GLboolean alive)
{
b->alive = alive;
}