/* * ============================================================ * 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 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): * 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. 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): the surface * the player would land on, whether that's the ground or a platform. * 7. 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: flat colors, plus the * fixed per-face shading on platforms. * * 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 #include #include #include #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 }; /* 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 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); } /* 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); } } static void draw_platforms(Mat4 vp) { for (int i = 0; i < world_box_count(); i++) draw_platform(vp, world_box(i), PLATFORM_PALETTE[i % PLATFORM_PALETTE_SIZE]); } /* 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); 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) { 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_platforms(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); }