summaryrefslogtreecommitdiff
path: root/platformer/src/render.c
blob: a91b561c304f51699b75da64bbabc08ea3742184 (plain) (blame)
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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
/*
 * ============================================================
 * FILE:        render.c
 *
 * PURPOSE:     Draws the whole scene with modern OpenGL 3.3 core and as little
 *              code as possible: a ground grid, the player as a box, and the
 *              player's drop shadow.
 *
 * FITS IN:     Implements render.h. Reads Camera (camera.h), Player (player.h)
 *              and world_half_extent()/world_ground_height() (world.h). Uses the
 *              GL functions that window.c loaded through GLEW.
 *
 * IMPLEMENT:
 *   - ONE shader program, source written as string literals in this file
 *     (no shader files to load):
 *       vertex:   in vec3 a_pos;  uniform mat4 u_mvp;  gl_Position = u_mvp * vec4(a_pos,1)
 *       fragment: uniform vec4 u_color;  out vec4 frag;  frag = u_color
 *     Add a static helper that compiles a shader and prints the info log
 *     on failure. Look up the uniform locations once in render_init.
 *
 *   - Three meshes, each a VAO + VBO built once in render_init:
 *       1. Ground grid: GL_LINES in the XZ plane at y = 0, one line every
 *          GRID_SPACING from -world_half_extent() to +world_half_extent(), in
 *          both directions. Put "major" lines (every GRID_MAJOR_EVERY-th) in a
 *          SEPARATE draw range so they can get a brighter color. The grid is
 *          what makes motion readable in a blank world, so explain that in a comment.
 *       2. Unit cube: 36 vertices (GL_TRIANGLES), spanning x,z in [-0.5, 0.5]
 *          and y in [0, 1] so its origin is at the BOTTOM center, matching
 *          Body.pos being the feet.
 *       3. Shadow disc: a GL_TRIANGLE_FAN circle of radius 1 in the XZ plane
 *          (~24 segments).
 *
 *   - render_frame(cam, player, aspect):
 *       1. glClearColor(SKY_COLOR_R/G/B), clear color + depth.
 *       2. vp = camera_projection(cam, aspect) * camera_view(cam).
 *       3. Grid: u_mvp = vp. Draw minor lines in a dim color, major lines brighter.
 *       4. Shadow (drawn BEFORE the player):
 *            model = translate(player x, ground_y + 0.01, player z) * scale(r, 1, r)
 *            with r around PLAYER_HALF_WIDTH * 1.2. Dark color. The +0.01 lift
 *            stops z-fighting with the ground. Comment WHY the shadow exists:
 *            in SM64 the blob under Mario is the main cue for where you'll land.
 *            Without it, jumps in 3D are very hard to judge.
 *            ground_y = world_ground_height(player x, player z).
 *       5. Player box:
 *            model = translate(body.pos) * rotate_y(facing_yaw)
 *                    * scale(2*PLAYER_HALF_WIDTH, PLAYER_HEIGHT, 2*PLAYER_HALF_WIDTH)
 *            Bright color (e.g. red). Also draw a small second box as a "nose" on
 *            the front face (+Z in model space) so the facing direction is visible.
 *            That makes the turn rate tunable by eye.
 *       Everything uses the one shader, changing only u_mvp and u_color.
 *
 *   - render_shutdown: delete the VAOs, VBOs and the program.
 *
 * CONVENTIONS: `s_` statics for GL handles. Model matrices built from
 *              math3d.h helpers. There's no lighting, so flat colors are fine.
 *
 * NOT IN SCOPE: Lighting, textures, models, text/HUD, anti-aliasing,
 *              interpolating between ticks (a README roadmap item).
 *
 * DONE WHEN:   The scene shows a sky-colored background, a grid ground plane
 *              stretching to the world edge, a box with a visible nose that faces
 *              where it runs, and a shadow that stays on the ground under the
 *              box during a jump.
 * ============================================================
 */

#include <GL/glew.h>

#include <math.h>
#include <stdio.h>
#include <stdlib.h>

#include "config.h"
#include "render.h"
#include "world.h"

/* Purely visual sizes (not movement tuning, so they live here, not config.h). */
#define SHADOW_RADIUS_SCALE  1.2f    /* shadow radius relative to PLAYER_HALF_WIDTH */
#define SHADOW_LIFT          0.01f   /* m above ground, so the shadow doesn't z-fight it */
#define SHADOW_SEGMENTS      24      /* triangles in the shadow circle */
#define NOSE_SIZE            0.3f    /* m, edge length of the facing-direction "nose" box */
#define NOSE_HEIGHT          0.6f    /* nose height as a fraction of PLAYER_HEIGHT */
#define GROUND_THICKNESS     1.0f    /* m, the ground slab under the grid */

/* Flat colors, RGBA. */
static const float COLOR_GROUND[4]     = { 0.36f, 0.56f, 0.32f, 1.0f };
static const float COLOR_GRID_MINOR[4] = { 0.30f, 0.48f, 0.27f, 1.0f };
static const float COLOR_GRID_MAJOR[4] = { 0.62f, 0.82f, 0.55f, 1.0f };
static const float COLOR_SHADOW[4]     = { 0.12f, 0.16f, 0.12f, 1.0f };
static const float COLOR_PLAYER[4]     = { 0.85f, 0.15f, 0.15f, 1.0f };
static const float COLOR_NOSE[4]       = { 1.00f, 0.85f, 0.20f, 1.0f };

/* A VAO + VBO of positions only (3 floats per vertex). */
typedef struct {
    GLuint  vao, vbo;
    GLsizei vertex_count;
} Mesh;

static GLuint s_program;
static GLint  s_u_mvp, s_u_color;
static Mesh   s_grid, s_cube, s_disc;
static GLsizei s_grid_minor_count;   /* grid VBO holds minor lines first, then major */

static const char *VERTEX_SRC =
    "#version 330 core\n"
    "in vec3 a_pos;\n"
    "uniform mat4 u_mvp;\n"
    "void main() { gl_Position = u_mvp * vec4(a_pos, 1.0); }\n";

static const char *FRAGMENT_SRC =
    "#version 330 core\n"
    "uniform vec4 u_color;\n"
    "out vec4 frag;\n"
    "void main() { frag = u_color; }\n";

/* ---- Setup helpers ----------------------------------------------------- */

/* Compiles one shader stage; prints the driver's error log on failure. */
static GLuint compile_shader(GLenum type, const char *source)
{
    GLuint shader = glCreateShader(type);
    glShaderSource(shader, 1, &source, NULL);
    glCompileShader(shader);

    GLint ok;
    glGetShaderiv(shader, GL_COMPILE_STATUS, &ok);
    if (!ok) {
        char log[1024];
        glGetShaderInfoLog(shader, sizeof log, NULL, log);
        fprintf(stderr, "render: %s shader failed to compile:\n%s\n",
                type == GL_VERTEX_SHADER ? "vertex" : "fragment", log);
        glDeleteShader(shader);
        return 0;
    }
    return shader;
}

static GLuint build_program(void)
{
    GLuint vs = compile_shader(GL_VERTEX_SHADER, VERTEX_SRC);
    GLuint fs = compile_shader(GL_FRAGMENT_SHADER, FRAGMENT_SRC);
    if (!vs || !fs) {
        glDeleteShader(vs);   /* deleting 0 is a no-op */
        glDeleteShader(fs);
        return 0;
    }

    GLuint program = glCreateProgram();
    glAttachShader(program, vs);
    glAttachShader(program, fs);
    glBindAttribLocation(program, 0, "a_pos");   /* every mesh uses attribute 0 */
    glLinkProgram(program);
    glDeleteShader(vs);   /* the linked program keeps what it needs */
    glDeleteShader(fs);

    GLint ok;
    glGetProgramiv(program, GL_LINK_STATUS, &ok);
    if (!ok) {
        char log[1024];
        glGetProgramInfoLog(program, sizeof log, NULL, log);
        fprintf(stderr, "render: shader program failed to link:\n%s\n", log);
        glDeleteProgram(program);
        return 0;
    }
    return program;
}

/* Uploads xyz positions into a new VAO + VBO. */
static Mesh make_mesh(const float *xyz, int vertex_count)
{
    Mesh mesh;
    mesh.vertex_count = vertex_count;
    glGenVertexArrays(1, &mesh.vao);
    glGenBuffers(1, &mesh.vbo);
    glBindVertexArray(mesh.vao);
    glBindBuffer(GL_ARRAY_BUFFER, mesh.vbo);
    glBufferData(GL_ARRAY_BUFFER, (GLsizeiptr)(vertex_count * 3 * sizeof(float)), xyz, GL_STATIC_DRAW);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void *)0);
    glBindVertexArray(0);
    return mesh;
}

static void delete_mesh(Mesh *mesh)
{
    glDeleteVertexArrays(1, &mesh->vao);
    glDeleteBuffers(1, &mesh->vbo);
}

/* Writes a line segment (2 vertices) at out[0..5]; returns the next slot. */
static float *put_line(float *out, float x0, float z0, float x1, float z1)
{
    out[0] = x0; out[1] = 0.0f; out[2] = z0;
    out[3] = x1; out[4] = 0.0f; out[5] = z1;
    return out + 6;
}

/* The ground grid. In a blank world the grid is the ONLY thing that shows
 * motion: without it, running looks like standing still. Lines are indexed
 * from the origin, so the origin is always on a major line. Minor lines go
 * first in the buffer and major lines after, so each group can be drawn with
 * its own color. */
static bool build_grid(void)
{
    float extent = world_half_extent();
    int   half_lines = (int)(extent / GRID_SPACING);
    int   lines = (2 * half_lines + 1) * 2;          /* both directions */
    float *verts = malloc((size_t)lines * 6 * sizeof(float));
    if (!verts) {
        fprintf(stderr, "render: out of memory building the grid\n");
        return false;
    }

    float *out = verts;
    for (int pass = 0; pass < 2; pass++) {           /* pass 0 = minor, 1 = major */
        for (int k = -half_lines; k <= half_lines; k++) {
            bool major = (k % GRID_MAJOR_EVERY) == 0;
            if (major != (pass == 1))
                continue;
            float c = (float)k * GRID_SPACING;
            out = put_line(out, c, -extent, c, extent);   /* runs along Z */
            out = put_line(out, -extent, c, extent, c);   /* runs along X */
        }
        if (pass == 0)
            s_grid_minor_count = (GLsizei)((out - verts) / 3);
    }

    s_grid = make_mesh(verts, lines * 2);
    free(verts);
    return true;
}

/* Unit cube, x/z in [-0.5, 0.5] and y in [0, 1]: the origin is the BOTTOM
 * center, like Body.pos being the feet. Corner i has x = bit 0, y = bit 1,
 * z = bit 2. */
static void build_cube(void)
{
    static const int FACES[36] = {
        0, 4, 6,  0, 6, 2,   /* -X */
        1, 3, 7,  1, 7, 5,   /* +X */
        0, 1, 5,  0, 5, 4,   /* -Y */
        2, 6, 7,  2, 7, 3,   /* +Y */
        0, 2, 3,  0, 3, 1,   /* -Z */
        4, 5, 7,  4, 7, 6,   /* +Z */
    };
    float verts[36 * 3];
    for (int i = 0; i < 36; i++) {
        int corner = FACES[i];
        verts[i * 3 + 0] = (corner & 1) ? 0.5f : -0.5f;
        verts[i * 3 + 1] = (corner & 2) ? 1.0f :  0.0f;
        verts[i * 3 + 2] = (corner & 4) ? 0.5f : -0.5f;
    }
    s_cube = make_mesh(verts, 36);
}

/* Radius-1 circle in the XZ plane as a triangle fan: center, then the rim,
 * with the first rim point repeated at the end to close the circle. */
static void build_disc(void)
{
    float verts[(SHADOW_SEGMENTS + 2) * 3];
    verts[0] = verts[1] = verts[2] = 0.0f;
    for (int i = 0; i <= SHADOW_SEGMENTS; i++) {
        float a = 2.0f * M3D_PI * (float)i / (float)SHADOW_SEGMENTS;
        verts[(i + 1) * 3 + 0] = sinf(a);
        verts[(i + 1) * 3 + 1] = 0.0f;
        verts[(i + 1) * 3 + 2] = cosf(a);
    }
    s_disc = make_mesh(verts, SHADOW_SEGMENTS + 2);
}

/* ---- Drawing helpers --------------------------------------------------- */

static void set_uniforms(Mat4 mvp, const float color[4])
{
    glUniformMatrix4fv(s_u_mvp, 1, GL_FALSE, mvp.m);
    glUniform4fv(s_u_color, 1, color);
}

static void draw_mesh(const Mesh *mesh, GLenum mode, Mat4 mvp, const float color[4])
{
    set_uniforms(mvp, color);
    glBindVertexArray(mesh->vao);
    glDrawArrays(mode, 0, mesh->vertex_count);
}

/* A flat slab whose top face is the ground plane, so the world isn't just
 * grid lines floating in the sky. It is drawn first without writing depth:
 * everything else is on or above the ground, so it never hides anything,
 * and that means the grid lines lying exactly on its surface can't z-fight it. */
static void draw_ground(Mat4 vp)
{
    float size = 2.0f * world_half_extent();
    Mat4 model = mat4_mul(mat4_translate(vec3_make(0.0f, -GROUND_THICKNESS, 0.0f)),
                          mat4_scale(vec3_make(size, GROUND_THICKNESS, size)));
    glDepthMask(GL_FALSE);
    draw_mesh(&s_cube, GL_TRIANGLES, mat4_mul(vp, model), COLOR_GROUND);
    glDepthMask(GL_TRUE);
}

static void draw_grid(Mat4 vp)
{
    glBindVertexArray(s_grid.vao);
    set_uniforms(vp, COLOR_GRID_MINOR);
    glDrawArrays(GL_LINES, 0, s_grid_minor_count);
    set_uniforms(vp, COLOR_GRID_MAJOR);
    glDrawArrays(GL_LINES, s_grid_minor_count, s_grid.vertex_count - s_grid_minor_count);
}

/* The drop shadow. In SM64 the blob under Mario is the main cue for where
 * you'll land: without it, depth is very hard to judge in 3D and jumps become
 * guesswork. It sits on the GROUND below the player, not at the player's height. */
static void draw_shadow(Mat4 vp, const Player *player)
{
    Vec3  pos      = player->body.pos;
    float ground_y = world_ground_height(pos.x, pos.z);
    float r        = PLAYER_HALF_WIDTH * SHADOW_RADIUS_SCALE;
    Mat4 model = mat4_mul(mat4_translate(vec3_make(pos.x, ground_y + SHADOW_LIFT, pos.z)),
                          mat4_scale(vec3_make(r, 1.0f, r)));
    draw_mesh(&s_disc, GL_TRIANGLE_FAN, mat4_mul(vp, model), COLOR_SHADOW);
}

/* The player box, plus a small "nose" box on its front (+Z in model space)
 * so you can see which way it faces and tune the turn rate by eye. */
static void draw_player(Mat4 vp, const Player *player)
{
    Mat4 placed = mat4_mul(mat4_translate(player->body.pos), mat4_rotate_y(player->facing_yaw));

    Mat4 body = mat4_mul(placed, mat4_scale(vec3_make(2.0f * PLAYER_HALF_WIDTH,
                                                      PLAYER_HEIGHT,
                                                      2.0f * PLAYER_HALF_WIDTH)));
    draw_mesh(&s_cube, GL_TRIANGLES, mat4_mul(vp, body), COLOR_PLAYER);

    Vec3 nose_offset = vec3_make(0.0f, PLAYER_HEIGHT * NOSE_HEIGHT, PLAYER_HALF_WIDTH);
    Mat4 nose = mat4_mul(placed, mat4_mul(mat4_translate(nose_offset),
                                          mat4_scale(vec3_make(NOSE_SIZE, NOSE_SIZE, NOSE_SIZE))));
    draw_mesh(&s_cube, GL_TRIANGLES, mat4_mul(vp, nose), COLOR_NOSE);
}

/* ---- Public interface -------------------------------------------------- */

bool render_init(void)
{
    s_program = build_program();
    if (!s_program)
        return false;
    s_u_mvp   = glGetUniformLocation(s_program, "u_mvp");
    s_u_color = glGetUniformLocation(s_program, "u_color");

    if (!build_grid()) {
        glDeleteProgram(s_program);
        return false;
    }
    build_cube();
    build_disc();
    return true;
}

void render_frame(const Camera *cam, const Player *player, float aspect)
{
    glClearColor(SKY_COLOR_R, SKY_COLOR_G, SKY_COLOR_B, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glUseProgram(s_program);

    Mat4 vp = mat4_mul(camera_projection(cam, aspect), camera_view(cam));

    draw_ground(vp);
    draw_grid(vp);
    draw_shadow(vp, player);   /* before the player, so the player is drawn over it */
    draw_player(vp, player);

    glBindVertexArray(0);
}

void render_shutdown(void)
{
    delete_mesh(&s_grid);
    delete_mesh(&s_cube);
    delete_mesh(&s_disc);
    glDeleteProgram(s_program);
}