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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
|
/*
* ============================================================
* 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, the
* player's drop shadow, and an FPS counter in the top right.
*
* FITS IN: Implements render.h. Reads Camera (camera.h), Player (player.h)
* and the level (world_half_extent(), world_box_count()/world_box()
* and world_floor_below() from 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. Its faces are stored in a fixed order
* (-X, +X, -Y, +Y, -Z, +Z), 6 vertices each, so a single face can be
* drawn on its own.
* 3. Shadow disc: a GL_TRIANGLE_FAN circle of radius 1 in the XZ plane
* (~24 segments).
*
* - render_frame(cam, player, aspect, fps):
* 1. glClearColor(SKY_COLOR_R/G/B), clear color + depth.
* 2. vp = camera_projection(cam, aspect) * camera_view(cam).
* 3. Ground: the cube scaled into a flat slab whose top is y = 0, drawn
* first WITHOUT depth writes (everything else is on or above it, so it
* never hides anything, and grid lines on its surface can't z-fight it).
* 4. Grid: u_mvp = vp. Draw minor lines in a dim color, major lines brighter.
* 5. Platforms: each world_box() is the cube scaled to the box. Draw it
* face by face with a fixed brightness per face (top brightest, bottom
* darkest, sides in between and different from each other) times the
* platform's color from a small palette, or COLOR_WALL_HANG for boxes
* with allows_wall_hang, so hangable walls read at a glance. Boxes with
* a BoxStyle other than PLATFORM use COLOR_CLIFF (rock) or COLOR_WATER;
* hangable rock is COLOR_CLIFF_HANG, a violet-tinted rock, so the
* "violet grabs" rule still reads on terrain. WHY: with no lighting, a
* one-color box is a flat silhouette and you can't tell its top from its
* sides, which makes jumps impossible to judge. Per-face shading is
* the cheapest way to read shape, and it needs no lighting code.
* 6. Shadow (drawn BEFORE the player):
* model = translate(player x, floor_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.
* floor_y = world_floor_below(body.pos, body.half_width, NULL): the surface
* the player would land on, whether that's the ground or a platform.
* 7. Player box:
* model = translate(player_visual_pos()) * rotate_y(facing_yaw)
* (body.pos with stair steps smoothed out)
* * 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.
* 7b. Zones (world_zone): no fill at all (a player sees straight through),
* just short black dashes spaced sparsely over the sides and top
* (not the bottom, which would z-fight the ground), so a test zone's
* extent is visible without hiding anything. Built once in
* render_init into one mesh; zones don't move.
* 8. FPS counter (skipped while fps <= 0, i.e. not measured yet): the text
* "<fps> FPS", right-aligned in the top-right corner, white with a
* dark drop shadow so it reads over both sky and ground. Glyphs come
* from a tiny built-in 3x5 pixel font (only the digits, F, P and S,
* written as "#" strings so you can see each letter in the source).
* Each lit font pixel is a quad in a small mesh that is rebuilt ONLY
* when the number changes, so the counter costs two draw calls a
* frame. It's drawn last with the depth test off, in screen space
* measured in window heights so the font pixels stay square at any
* window shape. WHY it exists: to watch the cost of later
* optimization work at a glance.
* 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: flat colors, plus the
* fixed per-face shading on platforms.
*
* NOT IN SCOPE: Lighting, textures, models, general text/HUD (only the FPS
* counter's characters exist), font files, 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. The top-right corner shows the current FPS.
* ============================================================
*/
#include <GL/glew.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.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 */
#define ZONE_DASH_SPACING 3.0f /* m between dashes (and between rows of them) on a zone's faces */
#define ZONE_DASH_LENGTH 0.8f /* m, each dash */
#define ZONE_DASH_WIDTH 0.08f /* m, each dash's thickness */
#define HUD_PIXEL 0.006f /* size of one font pixel, as a fraction of the window height */
#define HUD_MARGIN 0.02f /* gap between the FPS text and the window corner, in window heights */
#define HUD_SHADOW_OFFSET 0.5f /* text shadow offset down and right, in font pixels */
#define HUD_MAX_CHARS 16 /* longest text the FPS counter can hold */
#define GLYPH_W 3 /* font pixels per glyph, across */
#define GLYPH_H 5 /* font pixels per glyph, down */
#define GLYPH_ADVANCE 4 /* glyph width plus a one-pixel gap */
/* 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 };
static const float COLOR_WALL_HANG[3] = { 0.58f, 0.46f, 0.78f }; /* violet: sides you can hang on */
static const float COLOR_CLIFF[3] = { 0.52f, 0.47f, 0.42f }; /* warm grey rock */
static const float COLOR_CLIFF_HANG[3] = { 0.56f, 0.48f, 0.62f }; /* violet-tinted rock: hangable terrain */
static const float COLOR_WATER[3] = { 0.22f, 0.45f, 0.72f }; /* river blue */
static const float COLOR_ZONE_DASH[4] = { 0.00f, 0.00f, 0.00f, 1.0f };
static const float COLOR_HUD_TEXT[4] = { 1.00f, 1.00f, 1.00f, 1.0f };
static const float COLOR_HUD_SHADOW[4] = { 0.00f, 0.00f, 0.00f, 1.0f };
/* Platform colors, picked per platform by index so neighbors vary. */
static const float PLATFORM_PALETTE[][3] = {
{ 0.80f, 0.72f, 0.55f }, /* sandstone */
{ 0.62f, 0.66f, 0.74f }, /* slate */
{ 0.78f, 0.55f, 0.42f }, /* terracotta */
{ 0.70f, 0.70f, 0.66f }, /* concrete */
};
#define PLATFORM_PALETTE_SIZE ((int)(sizeof PLATFORM_PALETTE / sizeof PLATFORM_PALETTE[0]))
/* Brightness per cube face, in the cube's face order (-X, +X, -Y, +Y, -Z, +Z).
* Top brightest, bottom darkest, and no two touching sides the same, so the
* box's shape reads without any lighting. */
static const float FACE_SHADE[6] = { 0.70f, 0.82f, 0.45f, 1.00f, 0.60f, 0.90f };
#define CUBE_FACE_VERTS 6
/* A tiny pixel font holding only what the FPS counter spells. Each glyph is
* GLYPH_H rows, top row first, and "#" marks a lit pixel. */
typedef struct {
char ch;
const char *rows[GLYPH_H];
} Glyph;
static const Glyph FONT[] = {
{ '0', { "###", "#.#", "#.#", "#.#", "###" } },
{ '1', { ".#.", "##.", ".#.", ".#.", "###" } },
{ '2', { "###", "..#", "###", "#..", "###" } },
{ '3', { "###", "..#", "###", "..#", "###" } },
{ '4', { "#.#", "#.#", "###", "..#", "..#" } },
{ '5', { "###", "#..", "###", "..#", "###" } },
{ '6', { "###", "#..", "###", "#.#", "###" } },
{ '7', { "###", "..#", "..#", "..#", "..#" } },
{ '8', { "###", "#.#", "###", "#.#", "###" } },
{ '9', { "###", "#.#", "###", "..#", "###" } },
{ 'F', { "###", "#..", "##.", "#..", "#.." } },
{ 'P', { "###", "#.#", "###", "#..", "#.." } },
{ 'S', { ".##", "#..", ".#.", "..#", "##." } },
};
#define FONT_SIZE ((int)(sizeof FONT / sizeof FONT[0]))
/* 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 Mesh s_zone_dashes; /* every zone's dashes, in world space */
static Mesh s_hud_text; /* the FPS text, in font pixels; rebuilt when the number changes */
static int s_hud_fps = -1; /* the number s_hud_text currently spells (-1 = none yet) */
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);
}
/* One platform, drawn face by face with FACE_SHADE so its top and sides
* read as different surfaces (see the prompt above for why). */
static void draw_platform(Mat4 vp, Box box, const float rgb[3])
{
Vec3 size = vec3_sub(box.max, box.min);
Vec3 bottom = vec3_make(0.5f * (box.min.x + box.max.x), box.min.y,
0.5f * (box.min.z + box.max.z));
Mat4 mvp = mat4_mul(vp, mat4_mul(mat4_translate(bottom), mat4_scale(size)));
glBindVertexArray(s_cube.vao);
for (int face = 0; face < 6; face++) {
float s = FACE_SHADE[face];
float color[4] = { rgb[0] * s, rgb[1] * s, rgb[2] * s, 1.0f };
set_uniforms(mvp, color);
glDrawArrays(GL_TRIANGLES, face * CUBE_FACE_VERTS, CUBE_FACE_VERTS);
}
}
/* Hangable walls get their own color, so you can tell which ones grab;
* cliffs and water get theirs; everything else cycles the palette by index. */
static const float *box_color(Box box, int index)
{
if (box.allows_wall_hang)
return box.style == BOX_STYLE_CLIFF ? COLOR_CLIFF_HANG : COLOR_WALL_HANG;
switch (box.style) {
case BOX_STYLE_CLIFF: return COLOR_CLIFF;
case BOX_STYLE_WATER: return COLOR_WATER;
default: return PLATFORM_PALETTE[index % PLATFORM_PALETTE_SIZE];
}
}
static void draw_platforms(Mat4 vp)
{
for (int i = 0; i < world_box_count(); i++) {
Box box = world_box(i);
draw_platform(vp, box, box_color(box, i));
}
}
/* 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 surface BELOW the player (the ground or a platform
* top), not at the player's height. */
static void draw_shadow(Mat4 vp, const Player *player)
{
Vec3 pos = player->body.pos;
float floor_y = world_floor_below(pos, player->body.half_width, NULL);
float r = PLAYER_HALF_WIDTH * SHADOW_RADIUS_SCALE;
Mat4 model = mat4_mul(mat4_translate(vec3_make(pos.x, floor_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)
{
/* The visual position smooths out stair steps (see player_visual_pos). */
Mat4 placed = mat4_mul(mat4_translate(player_visual_pos(player)), 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);
}
/* ---- Zones ------------------------------------------------------------- */
/* Writes (if out isn't NULL) the dashes on one rectangular face: the face
* starts at `origin` and spans u_len along `u` and v_len along `v`. Rows of
* dashes every ZONE_DASH_SPACING, every other row shifted half a spacing.
* Returns how many vertices that is (6 per dash). */
static int face_dashes(float *out, Vec3 origin, Vec3 u, float u_len, Vec3 v, float v_len)
{
int count = 0;
int row = 0;
for (float vpos = 0.5f * ZONE_DASH_SPACING; vpos < v_len; vpos += ZONE_DASH_SPACING, row++) {
float shift = (row % 2) ? 0.5f * ZONE_DASH_SPACING : 0.0f;
for (float upos = 0.25f * ZONE_DASH_SPACING + shift; upos < u_len; upos += ZONE_DASH_SPACING) {
float u1 = fminf(upos + ZONE_DASH_LENGTH, u_len);
Vec3 corners[4] = {
vec3_add(origin, vec3_add(vec3_scale(u, upos), vec3_scale(v, vpos - 0.5f * ZONE_DASH_WIDTH))),
vec3_add(origin, vec3_add(vec3_scale(u, u1), vec3_scale(v, vpos - 0.5f * ZONE_DASH_WIDTH))),
vec3_add(origin, vec3_add(vec3_scale(u, u1), vec3_scale(v, vpos + 0.5f * ZONE_DASH_WIDTH))),
vec3_add(origin, vec3_add(vec3_scale(u, upos), vec3_scale(v, vpos + 0.5f * ZONE_DASH_WIDTH))),
};
static const int ORDER[6] = { 0, 1, 2, 0, 2, 3 };
for (int k = 0; k < 6 && out; k++) {
out[(count + k) * 3 + 0] = corners[ORDER[k]].x;
out[(count + k) * 3 + 1] = corners[ORDER[k]].y;
out[(count + k) * 3 + 2] = corners[ORDER[k]].z;
}
count += 6;
}
}
return count;
}
/* All five dashed faces (four sides and the top) of one zone. */
static int zone_dashes(float *out, Box b)
{
Vec3 x = vec3_make(1.0f, 0.0f, 0.0f), y = vec3_make(0.0f, 1.0f, 0.0f), z = vec3_make(0.0f, 0.0f, 1.0f);
Vec3 size = vec3_sub(b.max, b.min);
Vec3 faces[5] = { b.min, vec3_make(b.min.x, b.min.y, b.max.z), b.min,
vec3_make(b.max.x, b.min.y, b.min.z), vec3_make(b.min.x, b.max.y, b.min.z) };
Vec3 us[5] = { x, x, z, z, x };
Vec3 vs[5] = { y, y, y, y, z };
float ul[5] = { size.x, size.x, size.z, size.z, size.x };
float vl[5] = { size.y, size.y, size.y, size.y, size.z };
int count = 0;
for (int f = 0; f < 5; f++)
count += face_dashes(out ? out + count * 3 : NULL, faces[f], us[f], ul[f], vs[f], vl[f]);
return count;
}
/* One mesh with every zone's dashes: count them, then fill them in. */
static bool build_zone_dashes(void)
{
int count = 0;
for (int i = 0; i < world_zone_count(); i++)
count += zone_dashes(NULL, world_zone(i).bounds);
float *verts = malloc((size_t)(count > 0 ? count : 1) * 3 * sizeof(float));
if (!verts) {
fprintf(stderr, "render: out of memory building zone dashes\n");
return false;
}
int filled = 0;
for (int i = 0; i < world_zone_count(); i++)
filled += zone_dashes(verts + filled * 3, world_zone(i).bounds);
s_zone_dashes = make_mesh(verts, filled);
free(verts);
return true;
}
/* ---- FPS counter ------------------------------------------------------- */
/* Returns the font's glyph for ch, or NULL (e.g. a space) to leave a gap. */
static const Glyph *find_glyph(char ch)
{
for (int i = 0; i < FONT_SIZE; i++)
if (FONT[i].ch == ch)
return &FONT[i];
return NULL;
}
/* Writes one font pixel (a unit square as two triangles, hanging down and to
* the right of its top-left corner x, y) at out[0..17]; returns the next slot. */
static float *put_pixel(float *out, float x, float y)
{
static const float CORNERS[6][2] = {
{ 0, 0 }, { 1, 0 }, { 1, -1 },
{ 0, 0 }, { 1, -1 }, { 0, -1 },
};
for (int i = 0; i < 6; i++) {
out[i * 3 + 0] = x + CORNERS[i][0];
out[i * 3 + 1] = y + CORNERS[i][1];
out[i * 3 + 2] = 0.0f;
}
return out + 18;
}
/* Rebuilds s_hud_text to spell `text`, measured in font pixels with the
* origin at the text's TOP-RIGHT corner, so it's right-aligned for free. */
static void build_hud_text(const char *text)
{
static float verts[HUD_MAX_CHARS * GLYPH_W * GLYPH_H * 6 * 3];
int len = (int)strlen(text);
float left = -(float)(len * GLYPH_ADVANCE - 1); /* no gap after the last glyph */
float *out = verts;
for (int i = 0; i < len && i < HUD_MAX_CHARS; i++) {
const Glyph *glyph = find_glyph(text[i]);
if (!glyph)
continue;
float x = left + (float)(i * GLYPH_ADVANCE);
for (int row = 0; row < GLYPH_H; row++)
for (int col = 0; col < GLYPH_W; col++)
if (glyph->rows[row][col] == '#')
out = put_pixel(out, x + (float)col, -(float)row);
}
s_hud_text.vertex_count = (GLsizei)((out - verts) / 3);
glBindBuffer(GL_ARRAY_BUFFER, s_hud_text.vbo);
glBufferData(GL_ARRAY_BUFFER, (GLsizeiptr)((size_t)(out - verts) * sizeof(float)), verts, GL_DYNAMIC_DRAW);
}
/* "<fps> FPS" in the top-right corner, for keeping an eye on performance. */
static void draw_fps(int fps, float aspect)
{
if (fps <= 0) /* not measured yet */
return;
if (fps != s_hud_fps) {
char text[HUD_MAX_CHARS + 1];
snprintf(text, sizeof text, "%d FPS", fps);
build_hud_text(text);
s_hud_fps = fps;
}
/* Screen space in window heights: x in [0, aspect], y in [0, 1] from the
* bottom left. Using the height as the unit keeps font pixels square. */
Mat4 screen = mat4_mul(mat4_translate(vec3_make(-1.0f, -1.0f, 0.0f)),
mat4_scale(vec3_make(2.0f / aspect, 2.0f, 1.0f)));
Vec3 corner = vec3_make(aspect - HUD_MARGIN, 1.0f - HUD_MARGIN, 0.0f);
Vec3 shadow = vec3_add(corner, vec3_make(HUD_SHADOW_OFFSET * HUD_PIXEL,
-HUD_SHADOW_OFFSET * HUD_PIXEL, 0.0f));
Mat4 pixel = mat4_scale(vec3_make(HUD_PIXEL, HUD_PIXEL, 1.0f));
/* Drawn last with no depth test, so the scene can never cover it. */
glDisable(GL_DEPTH_TEST);
draw_mesh(&s_hud_text, GL_TRIANGLES, mat4_mul(screen, mat4_mul(mat4_translate(shadow), pixel)),
COLOR_HUD_SHADOW);
draw_mesh(&s_hud_text, GL_TRIANGLES, mat4_mul(screen, mat4_mul(mat4_translate(corner), pixel)),
COLOR_HUD_TEXT);
glEnable(GL_DEPTH_TEST);
}
/* ---- 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();
if (!build_zone_dashes()) {
glDeleteProgram(s_program);
return false;
}
s_hud_text = make_mesh(NULL, 0); /* filled in by build_hud_text() once FPS is known */
return true;
}
void render_frame(const Camera *cam, const Player *player, float aspect, int fps)
{
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_platforms(vp);
draw_shadow(vp, player); /* before the player, so the player is drawn over it */
draw_player(vp, player);
draw_mesh(&s_zone_dashes, GL_TRIANGLES, vp, COLOR_ZONE_DASH); /* zones: dashes only, see-through */
draw_fps(fps, aspect); /* last: it sits on top of everything */
glBindVertexArray(0);
}
void render_shutdown(void)
{
delete_mesh(&s_grid);
delete_mesh(&s_cube);
delete_mesh(&s_disc);
delete_mesh(&s_zone_dashes);
delete_mesh(&s_hud_text);
glDeleteProgram(s_program);
}
|