summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--platformer/README.md4
-rw-r--r--platformer/src/camera.c66
-rw-r--r--platformer/src/camera.h17
-rw-r--r--platformer/src/config.h54
-rw-r--r--platformer/src/controls.c202
-rw-r--r--platformer/src/controls.h17
-rw-r--r--platformer/src/main.c95
-rw-r--r--platformer/src/math3d.h196
-rw-r--r--platformer/src/physics.c42
-rw-r--r--platformer/src/physics.h12
-rw-r--r--platformer/src/player.c152
-rw-r--r--platformer/src/player.h25
-rw-r--r--platformer/src/render.c315
-rw-r--r--platformer/src/render.h9
-rw-r--r--platformer/src/window.c131
-rw-r--r--platformer/src/window.h17
-rw-r--r--platformer/src/world.c35
-rw-r--r--platformer/src/world.h8
18 files changed, 1396 insertions, 1 deletions
diff --git a/platformer/README.md b/platformer/README.md
index cea08bd..a83487b 100644
--- a/platformer/README.md
+++ b/platformer/README.md
@@ -81,6 +81,10 @@ The game is designed for a gamepad (Xbox-style layout names; GLFW maps other pad
| Back / Select | reset player to spawn |
| Start | quit |
+If a connected pad is ignored, the console prints `"<name>" (GUID ...) has no gamepad mapping`. Add a
+mapping line for that GUID to `EXTRA_GAMEPAD_MAPPINGS` in `src/controls.c` (the Xbox Elite Series 2 over
+USB is already there).
+
**Keyboard fallback** (only active when no gamepad is connected, for testing): WASD = move,
arrow keys = camera, Space = jump, R = reset, Esc = quit.
diff --git a/platformer/src/camera.c b/platformer/src/camera.c
index 00f8d4a..531d58c 100644
--- a/platformer/src/camera.c
+++ b/platformer/src/camera.c
@@ -49,3 +49,69 @@
* player slightly without jitter.
* ============================================================
*/
+
+#include "camera.h"
+#include "config.h"
+
+/* The point the camera wants to look at: a bit above the player's feet. */
+static Vec3 desired_target(Vec3 follow_point)
+{
+ return vec3_add(follow_point, vec3_make(0.0f, CAMERA_TARGET_HEIGHT, 0.0f));
+}
+
+/* The YAW CONVENTION from camera.h. player.c depends on this exact formula. */
+static void recompute_position(Camera *c)
+{
+ Vec3 offset = vec3_make(sinf(c->yaw) * cosf(c->pitch),
+ sinf(c->pitch),
+ cosf(c->yaw) * cosf(c->pitch));
+ c->position = vec3_add(c->target, vec3_scale(offset, c->distance));
+}
+
+void camera_init(Camera *c, Vec3 follow_point)
+{
+ c->target = desired_target(follow_point); /* snap, no smoothing */
+ c->yaw = 0.0f; /* on +Z, looking toward -Z */
+ c->pitch = CAMERA_PITCH_DEFAULT;
+ c->distance = CAMERA_DISTANCE;
+ recompute_position(c);
+}
+
+void camera_update(Camera *c, const Input *in, Vec3 follow_point, float dt)
+{
+ /* 1. Orbit. The yaw sign is flipped (-=): pushing the stick RIGHT should
+ * turn the VIEW right, which means the camera swings LEFT around the
+ * player. The camera's forward is (-sin(yaw), 0, -cos(yaw)), so turning it
+ * toward the camera's right (+X at yaw 0) needs yaw to DECREASE. */
+ c->yaw -= in->look.x * CAMERA_YAW_SPEED * dt;
+ c->pitch += in->look.y * CAMERA_PITCH_SPEED * dt;
+ c->pitch = clampf(c->pitch, CAMERA_PITCH_MIN, CAMERA_PITCH_MAX);
+ c->yaw = wrap_angle(c->yaw);
+
+ /* 2. Follow with exponential smoothing. A camera that snaps rigidly to the
+ * player looks jittery, and a little lag lets you see the motion. Using
+ * 1 - e^(-rate*dt) instead of a fixed lerp factor keeps the catch-up speed
+ * the same regardless of the tick rate. */
+ float t = 1.0f - expf(-CAMERA_FOLLOW_RATE * dt);
+ c->target = vec3_lerp(c->target, desired_target(follow_point), t);
+
+ /* 3. Place the eye on the orbit sphere around the new target. */
+ recompute_position(c);
+}
+
+float camera_yaw(const Camera *c)
+{
+ return c->yaw;
+}
+
+Mat4 camera_view(const Camera *c)
+{
+ return mat4_look_at(c->position, c->target, vec3_make(0.0f, 1.0f, 0.0f));
+}
+
+Mat4 camera_projection(const Camera *c, float aspect)
+{
+ (void)c; /* every camera shares the same lens for now */
+ float fovy_rad = CAMERA_FOV_DEG * (M3D_PI / 180.0f);
+ return mat4_perspective(fovy_rad, aspect, CAMERA_NEAR, CAMERA_FAR);
+}
diff --git a/platformer/src/camera.h b/platformer/src/camera.h
index ead4bc9..cdceaec 100644
--- a/platformer/src/camera.h
+++ b/platformer/src/camera.h
@@ -49,4 +49,21 @@
#ifndef CAMERA_H
#define CAMERA_H
+#include "controls.h"
+#include "math3d.h"
+
+typedef struct Camera {
+ Vec3 target; /* the smoothed point we look at (near the player) */
+ float yaw; /* orbit angle around the target, radians */
+ float pitch; /* angle above horizontal, radians */
+ float distance; /* meters from target */
+ Vec3 position; /* derived eye position (recomputed in camera_update) */
+} Camera;
+
+void camera_init(Camera *c, Vec3 follow_point);
+void camera_update(Camera *c, const Input *in, Vec3 follow_point, float dt);
+float camera_yaw(const Camera *c);
+Mat4 camera_view(const Camera *c);
+Mat4 camera_projection(const Camera *c, float aspect);
+
#endif /* CAMERA_H */
diff --git a/platformer/src/config.h b/platformer/src/config.h
index 1aa6447..5f1e3db 100644
--- a/platformer/src/config.h
+++ b/platformer/src/config.h
@@ -81,4 +81,58 @@
#ifndef CONFIG_H
#define CONFIG_H
+/* ---- Window ------------------------------------------------------------ */
+#define WINDOW_WIDTH 1280 /* starting window width, pixels */
+#define WINDOW_HEIGHT 720 /* starting window height, pixels */
+#define WINDOW_TITLE "platformer" /* base title; main.c appends the debug readout */
+#define SKY_COLOR_R 0.45f /* clear color: the "sky" behind everything */
+#define SKY_COLOR_G 0.65f
+#define SKY_COLOR_B 0.90f
+
+/* ---- Simulation timing ------------------------------------------------- */
+#define TICK_HZ 60 /* logic ticks per second; higher = lower input latency (SM64 used 30) */
+#define TICK_DT (1.0f / TICK_HZ) /* seconds per tick; derived, don't edit */
+#define MAX_FRAME_TIME 0.25f /* longest frame we catch up on; stops a "spiral of death" after a stall */
+
+/* ---- Input ------------------------------------------------------------- */
+#define MOVE_DEADZONE 0.20f /* left stick radius ignored; higher = less drift, less fine control */
+#define LOOK_DEADZONE 0.20f /* right stick radius ignored; higher = camera harder to nudge */
+
+/* ---- Player: ground movement ------------------------------------------- */
+#define PLAYER_MAX_SPEED 9.0f /* m/s at full stick tilt; higher = faster top run speed */
+#define PLAYER_GROUND_ACCEL 30.0f /* m/s^2 toward target speed; higher = snappier starts */
+#define PLAYER_GROUND_FRICTION 40.0f /* m/s^2 slowdown with stick released; higher = snappier stops */
+#define PLAYER_TURN_RATE 12.0f /* rad/s max facing rotation on ground; higher = tighter turns */
+
+/* ---- Player: air movement ---------------------------------------------- */
+#define PLAYER_AIR_CONTROL 0.30f /* 0..1 multiplier on accel + turn rate in air; higher = more steerable jumps */
+#define PLAYER_JUMP_VELOCITY 14.0f /* m/s upward at jump start; higher = taller jumps (~2.4 m apex at 14) */
+#define PLAYER_JUMP_CUT 0.50f /* vel.y multiplier on early A release; lower = shorter taps */
+
+/* ---- Physics ----------------------------------------------------------- */
+#define GRAVITY 40.0f /* m/s^2; stronger than real 9.8 on purpose, real gravity feels floaty */
+#define TERMINAL_VELOCITY 50.0f /* m/s max fall speed; lower = long falls feel more controlled */
+
+/* ---- Player: size (used by render, and later by collision) ------------- */
+#define PLAYER_HALF_WIDTH 0.4f /* m; half the box's width/depth */
+#define PLAYER_HEIGHT 1.6f /* m; box height (body.pos is the player's FEET) */
+
+/* ---- Camera ------------------------------------------------------------ */
+#define CAMERA_DISTANCE 10.0f /* m from target; higher = see more, player looks smaller */
+#define CAMERA_TARGET_HEIGHT 1.0f /* m above player's feet the camera looks at */
+#define CAMERA_PITCH_DEFAULT 0.35f /* rad above horizontal at start */
+#define CAMERA_PITCH_MIN 0.05f /* rad; lowest the camera can swing (just above the ground) */
+#define CAMERA_PITCH_MAX 1.20f /* rad; highest the camera can swing (near top-down) */
+#define CAMERA_YAW_SPEED 2.5f /* rad/s orbit at full right-stick tilt; higher = faster spin */
+#define CAMERA_PITCH_SPEED 1.5f /* rad/s tilt at full right-stick tilt */
+#define CAMERA_FOLLOW_RATE 8.0f /* 1/s; higher = camera catches up to the player faster */
+#define CAMERA_FOV_DEG 60.0f /* vertical field of view, degrees; higher = wider, faster-feeling view */
+#define CAMERA_NEAR 0.1f /* m; near clip plane */
+#define CAMERA_FAR 500.0f /* m; far clip plane (must reach past the world edge) */
+
+/* ---- World ------------------------------------------------------------- */
+#define WORLD_HALF_EXTENT 100.0f /* m; the ground is a square of 2x this per side */
+#define GRID_SPACING 1.0f /* m between grid lines; the grid is how you read speed */
+#define GRID_MAJOR_EVERY 10 /* every Nth line drawn brighter, for reading distances */
+
#endif /* CONFIG_H */
diff --git a/platformer/src/controls.c b/platformer/src/controls.c
index 850a1ae..f9f55c0 100644
--- a/platformer/src/controls.c
+++ b/platformer/src/controls.c
@@ -25,6 +25,21 @@
* pad connects or disconnects (glfwGetGamepadName), so it's clear
* which device is in use.
*
+ * - Extra built-in mappings: some pads aren't in GLFW's database under
+ * their exact GUID (on Linux the GUID includes the driver/firmware
+ * version), so they show up as a raw joystick with
+ * glfwJoystickIsGamepad() == false and get ignored. Keep a short list
+ * of SDL-format mapping strings for pads we actually use, and register
+ * them in controls_init() with glfwUpdateGamepadMappings(). Currently:
+ * Xbox Elite Series 2 over USB (xpad driver, GUID
+ * 030000005e040000000b000017050000). To add a pad: find its GUID with
+ * glfwGetJoystickGUID() and its button/axis order from the evdev codes
+ * (/proc/bus/input/devices), or copy its line from SDL's
+ * gamecontrollerdb.txt.
+ * At init, also print any joystick that has sticks (>= 2 axes) but no
+ * mapping, with its name and GUID, so a new pad that's silently ignored
+ * is easy to diagnose.
+ *
* - Gamepad mapping:
* move.x = GLFW_GAMEPAD_AXIS_LEFT_X
* move.y = -GLFW_GAMEPAD_AXIS_LEFT_Y (GLFW reports up as NEGATIVE,
@@ -62,7 +77,8 @@
* CONVENTIONS: `s_` prefix for statics. <GLFW/glfw3.h> is included here (not
* in controls.h).
*
- * NOT IN SCOPE: Rebinding, loading an external gamecontrollerdb.txt,
+ * NOT IN SCOPE: Rebinding, loading an external gamecontrollerdb.txt (a few
+ * embedded mapping lines are fine; a whole database is not),
* rumble, triggers/shoulder buttons (add them when a move needs
* them), input recording/replay.
*
@@ -73,3 +89,187 @@
* in switches back.
* ============================================================
*/
+
+#include <GLFW/glfw3.h>
+
+#include <stdio.h>
+#include <string.h>
+
+#include "config.h"
+#include "controls.h"
+#include "window.h"
+
+#define NO_GAMEPAD (-1)
+
+/* SDL-format mappings for pads missing from GLFW's built-in database under
+ * their exact GUID. Without a mapping, GLFW only exposes a pad as a raw
+ * joystick and we ignore it. One line per pad:
+ * GUID,name,<standard button/axis>:<raw index>,...,platform:<OS>,
+ * where bN = raw button N, aN = raw axis N, h0.M = hat 0 direction bitmask M. */
+static const char *EXTRA_GAMEPAD_MAPPINGS =
+ /* Xbox Elite Series 2 over USB (xpad driver, reports version 0x0517). */
+ "030000005e040000000b000017050000,Xbox Elite Series 2 Controller,"
+ "a:b0,b:b1,x:b2,y:b3,leftshoulder:b4,rightshoulder:b5,back:b6,start:b7,"
+ "guide:b8,leftstick:b9,rightstick:b10,leftx:a0,lefty:a1,lefttrigger:a2,"
+ "rightx:a3,righty:a4,righttrigger:a5,dpup:h0.1,dpright:h0.2,dpdown:h0.4,"
+ "dpleft:h0.8,platform:Linux,\n";
+
+/* Last tick's button states, for turning "down" into "pressed this tick". */
+static bool s_prev_jump, s_prev_reset, s_prev_quit;
+
+/* The joystick id we're reading, or NO_GAMEPAD. Only used to notice (and
+ * print) when a pad connects or disconnects. */
+static int s_active_jid = NO_GAMEPAD;
+
+/* Raw buttons for this tick, before edge detection. */
+typedef struct {
+ bool jump, reset, quit;
+} Buttons;
+
+/* Radial deadzone. WHY radial and not per-axis: a per-axis deadzone snaps
+ * diagonals to the cardinal directions and makes slow walking feel "sticky".
+ * SM64 also computes one magnitude from the whole stick and uses it for speed.
+ * The rescale makes the deadzone's edge 0 and full tilt 1, so the whole
+ * 0..1 range stays usable instead of jumping from 0 to `deadzone`. */
+static Vec2 apply_radial_deadzone(float x, float y, float deadzone)
+{
+ float len = sqrtf(x * x + y * y);
+ if (len < deadzone)
+ return vec2_make(0.0f, 0.0f);
+
+ /* Clamped because some pads report corners past 1. */
+ float new_len = clampf((len - deadzone) / (1.0f - deadzone), 0.0f, 1.0f);
+ float scale = new_len / len;
+ return vec2_make(x * scale, y * scale);
+}
+
+/* Returns the first connected gamepad, or NO_GAMEPAD. Called every poll,
+ * which is also what makes hot-plugging work. */
+static int find_gamepad(void)
+{
+ for (int jid = GLFW_JOYSTICK_1; jid <= GLFW_JOYSTICK_LAST; jid++) {
+ if (glfwJoystickIsGamepad(jid))
+ return jid;
+ }
+ return NO_GAMEPAD;
+}
+
+static void report_gamepad_change(int jid)
+{
+ if (jid == s_active_jid)
+ return;
+ if (s_active_jid != NO_GAMEPAD)
+ printf("controls: gamepad disconnected, keyboard fallback active\n");
+ if (jid != NO_GAMEPAD)
+ printf("controls: using gamepad \"%s\"\n", glfwGetGamepadName(jid));
+ fflush(stdout);
+ s_active_jid = jid;
+}
+
+static Buttons read_gamepad(int jid, Input *out)
+{
+ Buttons buttons = { false, false, false };
+ GLFWgamepadstate state;
+ if (!glfwGetGamepadState(jid, &state))
+ return buttons;
+
+ /* GLFW reports stick-up as NEGATIVE y, so flip it: up = forward = +y. */
+ out->move = apply_radial_deadzone(state.axes[GLFW_GAMEPAD_AXIS_LEFT_X],
+ -state.axes[GLFW_GAMEPAD_AXIS_LEFT_Y],
+ MOVE_DEADZONE);
+ out->look = apply_radial_deadzone(state.axes[GLFW_GAMEPAD_AXIS_RIGHT_X],
+ -state.axes[GLFW_GAMEPAD_AXIS_RIGHT_Y],
+ LOOK_DEADZONE);
+
+ buttons.jump = state.buttons[GLFW_GAMEPAD_BUTTON_A] == GLFW_PRESS;
+ buttons.reset = state.buttons[GLFW_GAMEPAD_BUTTON_BACK] == GLFW_PRESS;
+ buttons.quit = state.buttons[GLFW_GAMEPAD_BUTTON_START] == GLFW_PRESS;
+ out->using_gamepad = true;
+ return buttons;
+}
+
+static bool key_down(int key)
+{
+ return glfwGetKey(window_handle(), key) == GLFW_PRESS;
+}
+
+/* Turns two opposing keys into -1, 0 or +1. */
+static float key_axis(int negative_key, int positive_key)
+{
+ return (float)key_down(positive_key) - (float)key_down(negative_key);
+}
+
+/* Keyboard fallback for testing without a pad. Keys are all-or-nothing,
+ * so diagonals are normalized to keep |move| <= 1 (otherwise diagonal
+ * running would be ~41% faster). */
+static Buttons read_keyboard(Input *out)
+{
+ Buttons buttons;
+ Vec2 move = vec2_make(key_axis(GLFW_KEY_A, GLFW_KEY_D), key_axis(GLFW_KEY_S, GLFW_KEY_W));
+ float len = vec2_length(move);
+ if (len > 1.0f)
+ move = vec2_make(move.x / len, move.y / len);
+ out->move = move;
+
+ Vec2 look = vec2_make(key_axis(GLFW_KEY_LEFT, GLFW_KEY_RIGHT), key_axis(GLFW_KEY_DOWN, GLFW_KEY_UP));
+ len = vec2_length(look);
+ if (len > 1.0f)
+ look = vec2_make(look.x / len, look.y / len);
+ out->look = look;
+
+ buttons.jump = key_down(GLFW_KEY_SPACE);
+ buttons.reset = key_down(GLFW_KEY_R);
+ buttons.quit = false; /* Esc is handled for every device in controls_poll */
+ out->using_gamepad = false;
+ return buttons;
+}
+
+/* Lists joysticks that have sticks but no gamepad mapping. Headsets, mice and
+ * keyboards also show up as joysticks, which is why anything with fewer
+ * than 2 axes is skipped. */
+static void report_unmapped_joysticks(void)
+{
+ for (int jid = GLFW_JOYSTICK_1; jid <= GLFW_JOYSTICK_LAST; jid++) {
+ int axis_count = 0;
+ if (!glfwJoystickPresent(jid) || glfwJoystickIsGamepad(jid))
+ continue;
+ glfwGetJoystickAxes(jid, &axis_count);
+ if (axis_count >= 2)
+ printf("controls: \"%s\" (GUID %s) has no gamepad mapping, ignoring it\n",
+ glfwGetJoystickName(jid), glfwGetJoystickGUID(jid));
+ }
+}
+
+void controls_init(void)
+{
+ if (!glfwUpdateGamepadMappings(EXTRA_GAMEPAD_MAPPINGS))
+ fprintf(stderr, "controls: failed to add extra gamepad mappings\n");
+ report_unmapped_joysticks();
+
+ /* Report whichever pad is already plugged in at startup. */
+ report_gamepad_change(find_gamepad());
+}
+
+void controls_poll(Input *out)
+{
+ memset(out, 0, sizeof *out); /* no stale data from the last tick */
+
+ int jid = find_gamepad();
+ report_gamepad_change(jid);
+
+ Buttons now = (jid != NO_GAMEPAD) ? read_gamepad(jid, out) : read_keyboard(out);
+
+ /* Esc always quits, even with a pad connected, so you can always exit. */
+ if (key_down(GLFW_KEY_ESCAPE))
+ now.quit = true;
+
+ /* Edges: "pressed" is true only on the first tick the button is down. */
+ out->jump_held = now.jump;
+ out->jump_pressed = now.jump && !s_prev_jump;
+ out->reset_pressed = now.reset && !s_prev_reset;
+ out->quit_pressed = now.quit && !s_prev_quit;
+
+ s_prev_jump = now.jump;
+ s_prev_reset = now.reset;
+ s_prev_quit = now.quit;
+}
diff --git a/platformer/src/controls.h b/platformer/src/controls.h
index dbbe936..fc2ac4d 100644
--- a/platformer/src/controls.h
+++ b/platformer/src/controls.h
@@ -43,4 +43,21 @@
#ifndef CONTROLS_H
#define CONTROLS_H
+#include <stdbool.h>
+
+#include "math3d.h"
+
+typedef struct Input {
+ Vec2 move; /* left stick after deadzone, length 0..1. +x = right, +y = forward */
+ Vec2 look; /* right stick after deadzone, length 0..1. +x = orbit right, +y = tilt up */
+ bool jump_held; /* A is down this tick */
+ bool jump_pressed; /* A went down THIS tick (one tick only) */
+ bool reset_pressed; /* Back/Select went down this tick (one tick only) */
+ bool quit_pressed; /* Start (or Esc) went down this tick (one tick only) */
+ bool using_gamepad; /* true if a gamepad produced this Input (debug info) */
+} Input;
+
+void controls_init(void);
+void controls_poll(Input *out);
+
#endif /* CONTROLS_H */
diff --git a/platformer/src/main.c b/platformer/src/main.c
index 4e9e07a..5b11772 100644
--- a/platformer/src/main.c
+++ b/platformer/src/main.c
@@ -65,3 +65,98 @@
* the title bar shows live state/speed.
* ============================================================
*/
+
+#include <stdio.h>
+
+#include "camera.h"
+#include "config.h"
+#include "controls.h"
+#include "player.h"
+#include "render.h"
+#include "window.h"
+#include "world.h"
+
+#define TITLE_UPDATE_INTERVAL 0.25 /* seconds between debug title refreshes */
+
+/* Our "HUD" until text rendering exists: live state in the title bar.
+ * Updating a few times per second keeps it readable (and cheap). */
+static void update_debug_title(const Player *player, const Input *input)
+{
+ char title[128];
+ snprintf(title, sizeof title, "%s | %s | speed %.2f m/s | y %.2f | %s",
+ WINDOW_TITLE,
+ player_state_name(player->state),
+ player->forward_speed,
+ player->body.pos.y,
+ input->using_gamepad ? "pad" : "keyboard");
+ window_set_title(title);
+}
+
+int main(void)
+{
+ if (!window_init())
+ return 1;
+ controls_init();
+ world_init();
+
+ Player player;
+ player_init(&player, world_spawn_point());
+ Camera camera;
+ camera_init(&camera, player.body.pos);
+
+ if (!render_init()) {
+ window_shutdown();
+ return 1;
+ }
+
+ /* FIXED TIMESTEP with an accumulator. Real time comes in uneven chunks
+ * (one display frame at a time), but the game logic always advances in
+ * exact TICK_DT steps. Each frame adds the elapsed time to the
+ * accumulator, then runs as many whole ticks as fit (0, 1 or several);
+ * the leftover carries into the next frame. The payoff: identical jump
+ * heights and speeds no matter the monitor's refresh rate or a dropped
+ * frame, which is exactly what you need when tuning movement. SM64 ran its
+ * logic at 30 Hz; we use TICK_HZ. */
+ Input input = { 0 };
+ double previous = window_time();
+ double accumulator = 0.0;
+ double last_title_time = 0.0;
+
+ while (!window_should_close()) {
+ double now = window_time();
+ double frame_time = now - previous;
+ previous = now;
+ /* After a stall (breakpoint, window drag) don't try to simulate the
+ * whole gap at once: that would take even longer and fall further behind. */
+ if (frame_time > MAX_FRAME_TIME)
+ frame_time = MAX_FRAME_TIME;
+ accumulator += frame_time;
+
+ window_poll_events();
+
+ while (accumulator >= TICK_DT) {
+ controls_poll(&input);
+ if (input.quit_pressed)
+ window_request_close();
+ if (input.reset_pressed)
+ player_reset(&player, world_spawn_point());
+ /* Player before camera, so the camera follows where the player IS,
+ * not where it was a tick ago. SM64 updates Mario before the camera too. */
+ player_update(&player, &input, camera_yaw(&camera), TICK_DT);
+ camera_update(&camera, &input, player.body.pos, TICK_DT);
+ accumulator -= TICK_DT;
+ }
+
+ render_frame(&camera, &player, window_aspect());
+ window_swap();
+
+ if (now - last_title_time >= TITLE_UPDATE_INTERVAL) {
+ update_debug_title(&player, &input);
+ last_title_time = now;
+ }
+ }
+
+ render_shutdown();
+ window_shutdown();
+ return 0;
+}
diff --git a/platformer/src/math3d.h b/platformer/src/math3d.h
index 316e418..e0f89a5 100644
--- a/platformer/src/math3d.h
+++ b/platformer/src/math3d.h
@@ -74,4 +74,200 @@
#ifndef MATH3D_H
#define MATH3D_H
+#include <math.h>
+
+#define M3D_PI 3.14159265358979f /* C99 doesn't guarantee M_PI */
+
+typedef struct { float x, y; } Vec2;
+typedef struct { float x, y, z; } Vec3;
+typedef struct { float m[16]; } Mat4; /* column-major: (row r, col c) = m[c*4 + r] */
+
+/* ---- Scalar helpers ---------------------------------------------------- */
+
+static inline float clampf(float v, float lo, float hi)
+{
+ if (v < lo) return lo;
+ if (v > hi) return hi;
+ return v;
+}
+
+/* Moves current toward target by at most max_step, never overshooting.
+ * This is how speeds accelerate and brake at a fixed rate per tick. */
+static inline float approachf(float current, float target, float max_step)
+{
+ if (current < target) {
+ current += max_step;
+ return current > target ? target : current;
+ }
+ current -= max_step;
+ return current < target ? target : current;
+}
+
+/* Returns a in (-PI, PI]. */
+static inline float wrap_angle(float a)
+{
+ a = fmodf(a + M3D_PI, 2.0f * M3D_PI); /* now in (-2PI, 2PI) */
+ if (a <= 0.0f) a += 2.0f * M3D_PI; /* now in (0, 2PI] */
+ return a - M3D_PI;
+}
+
+/* Like approachf, but for angles: turns the SHORT way around the circle,
+ * so facing 170 deg and turning to -170 deg is a 20 deg turn, not 340. */
+static inline float approach_angle(float current, float target, float max_step)
+{
+ float diff = wrap_angle(target - current);
+ return wrap_angle(current + clampf(diff, -max_step, max_step));
+}
+
+/* ---- Vec2 -------------------------------------------------------------- */
+
+static inline Vec2 vec2_make(float x, float y)
+{
+ Vec2 v = { x, y };
+ return v;
+}
+
+static inline float vec2_length(Vec2 v)
+{
+ return sqrtf(v.x * v.x + v.y * v.y);
+}
+
+/* ---- Vec3 -------------------------------------------------------------- */
+
+static inline Vec3 vec3_make(float x, float y, float z)
+{
+ Vec3 v = { x, y, z };
+ return v;
+}
+
+static inline Vec3 vec3_add(Vec3 a, Vec3 b)
+{
+ return vec3_make(a.x + b.x, a.y + b.y, a.z + b.z);
+}
+
+static inline Vec3 vec3_sub(Vec3 a, Vec3 b)
+{
+ return vec3_make(a.x - b.x, a.y - b.y, a.z - b.z);
+}
+
+static inline Vec3 vec3_scale(Vec3 v, float s)
+{
+ return vec3_make(v.x * s, v.y * s, v.z * s);
+}
+
+static inline float vec3_dot(Vec3 a, Vec3 b)
+{
+ return a.x * b.x + a.y * b.y + a.z * b.z;
+}
+
+static inline Vec3 vec3_cross(Vec3 a, Vec3 b)
+{
+ return vec3_make(a.y * b.z - a.z * b.y,
+ a.z * b.x - a.x * b.z,
+ a.x * b.y - a.y * b.x);
+}
+
+static inline float vec3_length(Vec3 v)
+{
+ return sqrtf(vec3_dot(v, v));
+}
+
+/* Returns (0,0,0) for a zero-length input instead of dividing by zero. */
+static inline Vec3 vec3_normalize(Vec3 v)
+{
+ float len = vec3_length(v);
+ if (len <= 0.0f) return vec3_make(0.0f, 0.0f, 0.0f);
+ return vec3_scale(v, 1.0f / len);
+}
+
+/* t = 0 gives a, t = 1 gives b. */
+static inline Vec3 vec3_lerp(Vec3 a, Vec3 b, float t)
+{
+ return vec3_add(a, vec3_scale(vec3_sub(b, a), t));
+}
+
+/* ---- Mat4 -------------------------------------------------------------- */
+
+static inline Mat4 mat4_identity(void)
+{
+ Mat4 r = {{ 0 }};
+ r.m[0] = r.m[5] = r.m[10] = r.m[15] = 1.0f;
+ return r;
+}
+
+/* result = a * b, so b is applied to a point first, then a. */
+static inline Mat4 mat4_mul(Mat4 a, Mat4 b)
+{
+ Mat4 r;
+ for (int col = 0; col < 4; col++) {
+ for (int row = 0; row < 4; row++) {
+ float sum = 0.0f;
+ for (int k = 0; k < 4; k++)
+ sum += a.m[k * 4 + row] * b.m[col * 4 + k];
+ r.m[col * 4 + row] = sum;
+ }
+ }
+ return r;
+}
+
+/* The translation lives in the last column. */
+static inline Mat4 mat4_translate(Vec3 t)
+{
+ Mat4 r = mat4_identity();
+ r.m[12] = t.x;
+ r.m[13] = t.y;
+ r.m[14] = t.z;
+ return r;
+}
+
+static inline Mat4 mat4_scale(Vec3 s)
+{
+ Mat4 r = mat4_identity();
+ r.m[0] = s.x;
+ r.m[5] = s.y;
+ r.m[10] = s.z;
+ return r;
+}
+
+/* Rotates around +Y, turning +Z toward +X: (0,0,1) -> (sin a, 0, cos a).
+ * This matches the player's facing vector (sin(yaw), 0, cos(yaw)). */
+static inline Mat4 mat4_rotate_y(float angle)
+{
+ float c = cosf(angle), s = sinf(angle);
+ Mat4 r = mat4_identity();
+ r.m[0] = c; /* row 0, col 0 */
+ r.m[8] = s; /* row 0, col 2 */
+ r.m[2] = -s; /* row 2, col 0 */
+ r.m[10] = c; /* row 2, col 2 */
+ return r;
+}
+
+/* Standard OpenGL (gluPerspective) projection. Maps the view frustum to
+ * clip space, with the camera looking down -Z. */
+static inline Mat4 mat4_perspective(float fovy_rad, float aspect, float near, float far)
+{
+ float f = 1.0f / tanf(fovy_rad * 0.5f);
+ Mat4 r = {{ 0 }};
+ r.m[0] = f / aspect;
+ r.m[5] = f;
+ r.m[10] = (far + near) / (near - far);
+ r.m[11] = -1.0f; /* row 3, col 2: w = -z */
+ r.m[14] = 2.0f * far * near / (near - far);
+ return r;
+}
+
+/* Standard OpenGL (gluLookAt) view matrix: moves the world so the eye sits
+ * at the origin looking down -Z, with `up` roughly +Y on screen. */
+static inline Mat4 mat4_look_at(Vec3 eye, Vec3 target, Vec3 up)
+{
+ Vec3 f = vec3_normalize(vec3_sub(target, eye)); /* forward */
+ Vec3 s = vec3_normalize(vec3_cross(f, up)); /* right */
+ Vec3 u = vec3_cross(s, f); /* true up */
+ Mat4 r = mat4_identity();
+ r.m[0] = s.x; r.m[4] = s.y; r.m[8] = s.z; r.m[12] = -vec3_dot(s, eye);
+ r.m[1] = u.x; r.m[5] = u.y; r.m[9] = u.z; r.m[13] = -vec3_dot(u, eye);
+ r.m[2] = -f.x; r.m[6] = -f.y; r.m[10] = -f.z; r.m[14] = vec3_dot(f, eye);
+ return r;
+}
+
#endif /* MATH3D_H */
diff --git a/platformer/src/physics.c b/platformer/src/physics.c
index 3608c48..b04a78e 100644
--- a/platformer/src/physics.c
+++ b/platformer/src/physics.c
@@ -38,3 +38,45 @@
* y = 0 with on_ground = true, and stays there.
* ============================================================
*/
+
+#include "config.h"
+#include "physics.h"
+#include "world.h"
+
+void physics_step(Body *b, float dt)
+{
+ /* 1. Gravity. On the ground vel.y is left alone: a jump sets it positive
+ * before this call, and that's what lifts the body off the ground. */
+ if (!b->on_ground) {
+ b->vel.y -= GRAVITY * dt;
+ if (b->vel.y < -TERMINAL_VELOCITY)
+ b->vel.y = -TERMINAL_VELOCITY;
+ }
+
+ /* 2. Integrate with semi-implicit Euler: velocity was updated above, and
+ * position now moves with that NEW velocity. Unlike plain Euler (which
+ * uses the old velocity) this doesn't gain energy over time, and with a
+ * fixed dt the result is identical every run, so a jump always
+ * reaches the same height. */
+ b->pos = vec3_add(b->pos, vec3_scale(b->vel, dt));
+
+ /* 3. Ground. Landing snaps the feet to the surface and kills the downward
+ * speed. on_ground goes false the moment a jump lifts the body (and,
+ * once terrain exists, when walking off a ledge). */
+ float ground = world_ground_height(b->pos.x, b->pos.z);
+ if (b->pos.y <= ground) {
+ b->pos.y = ground;
+ if (b->vel.y < 0.0f)
+ b->vel.y = 0.0f;
+ b->on_ground = true;
+ } else {
+ b->on_ground = false;
+ }
+
+ /* 4. Bounds. Zero the velocity into an edge we got clamped against, so
+ * the body doesn't "stick" to it while pushing into it. */
+ Vec3 clamped = world_clamp_to_bounds(b->pos);
+ if (clamped.x != b->pos.x) b->vel.x = 0.0f;
+ if (clamped.z != b->pos.z) b->vel.z = 0.0f;
+ b->pos = clamped;
+}
diff --git a/platformer/src/physics.h b/platformer/src/physics.h
index dfbfebb..580d09b 100644
--- a/platformer/src/physics.h
+++ b/platformer/src/physics.h
@@ -33,4 +33,16 @@
#ifndef PHYSICS_H
#define PHYSICS_H
+#include <stdbool.h>
+
+#include "math3d.h"
+
+typedef struct Body {
+ Vec3 pos; /* position of the body's FEET (bottom center), meters */
+ Vec3 vel; /* velocity, meters/second */
+ bool on_ground; /* true if the body ended the last step standing on ground */
+} Body;
+
+void physics_step(Body *b, float dt);
+
#endif /* PHYSICS_H */
diff --git a/platformer/src/player.c b/platformer/src/player.c
index 1f1b94c..ed8da51 100644
--- a/platformer/src/player.c
+++ b/platformer/src/player.c
@@ -71,3 +71,155 @@
* player lands cleanly back in IDLE/RUN.
* ============================================================
*/
+
+#include "config.h"
+#include "player.h"
+
+/* What the stick is asking for this tick, in world space. */
+typedef struct {
+ float mag; /* 0..1, how far the stick is pushed */
+ float yaw; /* world direction to move in; only meaningful if mag > 0 */
+} Wish;
+
+static void update_ground(Player *p, const Input *in, Wish wish, float dt);
+static void update_fall(Player *p, const Input *in, Wish wish, float dt);
+
+/* A. Stick -> world direction. "Up" on the stick means "away from the
+ * camera", so the stick is rotated by the camera's yaw (camera.h's
+ * convention for forward/right on the ground plane). */
+static Wish compute_wish(const Input *in, float camera_yaw)
+{
+ Vec3 fwd = vec3_make(-sinf(camera_yaw), 0.0f, -cosf(camera_yaw));
+ Vec3 right = vec3_make( cosf(camera_yaw), 0.0f, -sinf(camera_yaw));
+ Vec3 dir = vec3_add(vec3_scale(fwd, in->move.y), vec3_scale(right, in->move.x));
+
+ Wish wish;
+ wish.mag = vec2_length(in->move);
+ wish.yaw = atan2f(dir.x, dir.z); /* inverse of facing = (sin(yaw), 0, cos(yaw)) */
+ return wish;
+}
+
+/* Turns toward the stick and speeds up toward a speed set by how far it's
+ * pushed. Shared by ground and air movement; the air passes smaller rates. */
+static void steer(Player *p, Wish wish, float turn_rate, float accel, float dt)
+{
+ p->facing_yaw = approach_angle(p->facing_yaw, wish.yaw, turn_rate * dt);
+ p->forward_speed = approachf(p->forward_speed, PLAYER_MAX_SPEED * wish.mag, accel * dt);
+}
+
+/* Standing still vs walking vs running is only a matter of speed. */
+static PlayerState grounded_state(const Player *p)
+{
+ return p->forward_speed > 0.0f ? PLAYER_RUN : PLAYER_IDLE;
+}
+
+/* B + C. IDLE and RUN: full control, friction when the stick is released,
+ * and the only place a jump can start. */
+static void update_ground(Player *p, const Input *in, Wish wish, float dt)
+{
+ /* Walked off an edge (once edges exist): start falling. */
+ if (!p->body.on_ground) {
+ p->state = PLAYER_FALL;
+ update_fall(p, in, wish, dt);
+ return;
+ }
+
+ if (wish.mag > 0.0f)
+ steer(p, wish, PLAYER_TURN_RATE, PLAYER_GROUND_ACCEL, dt);
+ else
+ p->forward_speed = approachf(p->forward_speed, 0.0f, PLAYER_GROUND_FRICTION * dt);
+ p->state = grounded_state(p);
+
+ if (in->jump_pressed) {
+ p->body.vel.y = PLAYER_JUMP_VELOCITY;
+ p->body.on_ground = false;
+ p->state = PLAYER_JUMP;
+ }
+}
+
+/* D. Air movement: weaker steering, and NO friction when the stick is
+ * released, so you keep your momentum like in SM64. */
+static void air_steer(Player *p, Wish wish, float dt)
+{
+ if (wish.mag > 0.0f)
+ steer(p, wish,
+ PLAYER_TURN_RATE * PLAYER_AIR_CONTROL,
+ PLAYER_GROUND_ACCEL * PLAYER_AIR_CONTROL, dt);
+}
+
+/* FALL: in the air, going down. Landing hands straight over to the ground
+ * logic on the same tick, so a jump pressed on the landing tick isn't lost. */
+static void update_fall(Player *p, const Input *in, Wish wish, float dt)
+{
+ if (p->body.on_ground) {
+ p->state = grounded_state(p);
+ update_ground(p, in, wish, dt);
+ return;
+ }
+ air_steer(p, wish, dt);
+}
+
+/* JUMP: in the air, still rising from a jump. */
+static void update_jump(Player *p, const Input *in, Wish wish, float dt)
+{
+ /* Past the apex (or landed already): it's a fall now. */
+ if (p->body.vel.y <= 0.0f) {
+ p->state = PLAYER_FALL;
+ update_fall(p, in, wish, dt);
+ return;
+ }
+
+ air_steer(p, wish, dt);
+
+ /* Variable jump height: letting go of A while rising cuts the upward speed.
+ * Tapping A gives a short hop, holding it gives the full jump. Switching to
+ * FALL right away makes sure the cut happens only once. */
+ if (!in->jump_held) {
+ p->body.vel.y *= PLAYER_JUMP_CUT;
+ p->state = PLAYER_FALL;
+ }
+}
+
+void player_init(Player *p, Vec3 spawn)
+{
+ p->body.pos = spawn;
+ p->body.vel = vec3_make(0.0f, 0.0f, 0.0f);
+ p->body.on_ground = true;
+ p->facing_yaw = 0.0f;
+ p->forward_speed = 0.0f;
+ p->state = PLAYER_IDLE;
+}
+
+void player_reset(Player *p, Vec3 spawn)
+{
+ player_init(p, spawn);
+}
+
+void player_update(Player *p, const Input *in, float camera_yaw, float dt)
+{
+ Wish wish = compute_wish(in, camera_yaw);
+
+ /* IDLE and RUN share one helper: they differ only in speed. */
+ switch (p->state) {
+ case PLAYER_IDLE:
+ case PLAYER_RUN: update_ground(p, in, wish, dt); break;
+ case PLAYER_JUMP: update_jump(p, in, wish, dt); break;
+ case PLAYER_FALL: update_fall(p, in, wish, dt); break;
+ }
+
+ /* E. Turn "speed along facing" into a velocity, then let physics move us. */
+ p->body.vel.x = sinf(p->facing_yaw) * p->forward_speed;
+ p->body.vel.z = cosf(p->facing_yaw) * p->forward_speed;
+ physics_step(&p->body, dt);
+}
+
+const char *player_state_name(PlayerState s)
+{
+ switch (s) {
+ case PLAYER_IDLE: return "IDLE";
+ case PLAYER_RUN: return "RUN";
+ case PLAYER_JUMP: return "JUMP";
+ case PLAYER_FALL: return "FALL";
+ }
+ return "?";
+}
diff --git a/platformer/src/player.h b/platformer/src/player.h
index bedfaf4..35e5b6a 100644
--- a/platformer/src/player.h
+++ b/platformer/src/player.h
@@ -45,4 +45,29 @@
#ifndef PLAYER_H
#define PLAYER_H
+#include "controls.h"
+#include "math3d.h"
+#include "physics.h"
+
+/* SM64-style "actions". Add states here only when a new move needs one;
+ * see the README roadmap (double jump, long jump, wall kick, ...). */
+typedef enum PlayerState {
+ PLAYER_IDLE, /* on ground, not moving */
+ PLAYER_RUN, /* on ground, moving (walk vs run is just speed) */
+ PLAYER_JUMP, /* in air, going up after a jump */
+ PLAYER_FALL /* in air, going down (or walked off something) */
+} PlayerState;
+
+typedef struct Player {
+ Body body; /* position / velocity / on_ground */
+ float facing_yaw; /* radians; facing vector = (sin(yaw), 0, cos(yaw)) */
+ float forward_speed; /* ground speed along facing_yaw, m/s (>= 0) */
+ PlayerState state;
+} Player;
+
+void player_init(Player *p, Vec3 spawn);
+void player_reset(Player *p, Vec3 spawn);
+void player_update(Player *p, const Input *in, float camera_yaw, float dt);
+const char *player_state_name(PlayerState s);
+
#endif /* PLAYER_H */
diff --git a/platformer/src/render.c b/platformer/src/render.c
index a326b15..a91b561 100644
--- a/platformer/src/render.c
+++ b/platformer/src/render.c
@@ -63,3 +63,318 @@
* 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);
+}
diff --git a/platformer/src/render.h b/platformer/src/render.h
index 33e518d..24dcf5e 100644
--- a/platformer/src/render.h
+++ b/platformer/src/render.h
@@ -28,4 +28,13 @@
#ifndef RENDER_H
#define RENDER_H
+#include <stdbool.h>
+
+#include "camera.h"
+#include "player.h"
+
+bool render_init(void);
+void render_frame(const Camera *cam, const Player *player, float aspect);
+void render_shutdown(void);
+
#endif /* RENDER_H */
diff --git a/platformer/src/window.c b/platformer/src/window.c
index 455b249..1f4d517 100644
--- a/platformer/src/window.c
+++ b/platformer/src/window.c
@@ -42,3 +42,134 @@
* viewport correct.
* ============================================================
*/
+
+/* GLEW must come before GLFW: it defines the GL headers GLFW would include. */
+#include <GL/glew.h>
+#include <GLFW/glfw3.h>
+
+#include <stdio.h>
+
+#include "config.h"
+#include "window.h"
+
+static GLFWwindow *s_window;
+
+static void on_glfw_error(int code, const char *description)
+{
+ fprintf(stderr, "GLFW error %d: %s\n", code, description);
+}
+
+static void on_framebuffer_resize(GLFWwindow *window, int w, int h)
+{
+ (void)window;
+ glViewport(0, 0, w, h);
+}
+
+bool window_init(void)
+{
+ glfwSetErrorCallback(on_glfw_error);
+
+ /* Also initializes GLFW's joystick/gamepad support, used by controls.c. */
+ if (!glfwInit()) {
+ fprintf(stderr, "window: glfwInit failed\n");
+ return false;
+ }
+
+ glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
+ glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
+ glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
+ glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_TRUE);
+
+ s_window = glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT, WINDOW_TITLE, NULL, NULL);
+ if (!s_window) {
+ fprintf(stderr, "window: could not create a %dx%d window with an OpenGL 3.3 core context\n",
+ WINDOW_WIDTH, WINDOW_HEIGHT);
+ glfwTerminate();
+ return false;
+ }
+ glfwMakeContextCurrent(s_window);
+
+ /* glewExperimental makes GLEW load core-profile functions it would
+ * otherwise skip because it can't find them in the extension string. */
+ glewExperimental = GL_TRUE;
+ GLenum glew_status = glewInit();
+ if (glew_status != GLEW_OK) {
+ fprintf(stderr, "window: glewInit failed: %s\n", glewGetErrorString(glew_status));
+ glfwDestroyWindow(s_window);
+ s_window = NULL;
+ glfwTerminate();
+ return false;
+ }
+ /* In a core profile, glewInit calls glGetString(GL_EXTENSIONS), which no
+ * longer exists, so it leaves a harmless GL_INVALID_ENUM behind. Clear it
+ * so it doesn't look like a bug in our own code later. */
+ glGetError();
+
+ glfwSwapInterval(1); /* vsync: no tearing, and no burning a CPU core */
+
+ glfwSetFramebufferSizeCallback(s_window, on_framebuffer_resize);
+ int w, h;
+ glfwGetFramebufferSize(s_window, &w, &h);
+ glViewport(0, 0, w, h);
+
+ glEnable(GL_DEPTH_TEST);
+ return true;
+}
+
+void window_shutdown(void)
+{
+ if (s_window) {
+ glfwDestroyWindow(s_window);
+ s_window = NULL;
+ }
+ glfwTerminate();
+}
+
+bool window_should_close(void)
+{
+ return glfwWindowShouldClose(s_window);
+}
+
+void window_request_close(void)
+{
+ glfwSetWindowShouldClose(s_window, GLFW_TRUE);
+}
+
+void window_poll_events(void)
+{
+ glfwPollEvents();
+}
+
+void window_swap(void)
+{
+ glfwSwapBuffers(s_window);
+}
+
+double window_time(void)
+{
+ return glfwGetTime();
+}
+
+/* Framebuffer size, NOT window size: they differ on HiDPI displays. */
+void window_framebuffer_size(int *w, int *h)
+{
+ glfwGetFramebufferSize(s_window, w, h);
+}
+
+float window_aspect(void)
+{
+ int w, h;
+ window_framebuffer_size(&w, &h);
+ if (h <= 0) return 1.0f; /* minimized window: avoid dividing by zero */
+ return (float)w / (float)h;
+}
+
+void window_set_title(const char *title)
+{
+ glfwSetWindowTitle(s_window, title);
+}
+
+struct GLFWwindow *window_handle(void)
+{
+ return s_window;
+}
diff --git a/platformer/src/window.h b/platformer/src/window.h
index c40dc9e..06ca163 100644
--- a/platformer/src/window.h
+++ b/platformer/src/window.h
@@ -40,4 +40,21 @@
#ifndef WINDOW_H
#define WINDOW_H
+#include <stdbool.h>
+
+/* Forward declaration, so including window.h doesn't pull in GLFW. */
+struct GLFWwindow;
+
+bool window_init(void);
+void window_shutdown(void);
+bool window_should_close(void);
+void window_request_close(void);
+void window_poll_events(void);
+void window_swap(void);
+double window_time(void);
+void window_framebuffer_size(int *w, int *h);
+float window_aspect(void);
+void window_set_title(const char *title);
+struct GLFWwindow *window_handle(void); /* ONLY controls.c may use this */
+
#endif /* WINDOW_H */
diff --git a/platformer/src/world.c b/platformer/src/world.c
index 2dffb72..4ae0d00 100644
--- a/platformer/src/world.c
+++ b/platformer/src/world.c
@@ -27,3 +27,38 @@
* DONE WHEN: It compiles warning-free, and the player can't leave the square.
* ============================================================
*/
+
+#include "config.h"
+#include "world.h"
+
+void world_init(void)
+{
+ /* Nothing to do yet. This is where level data would be loaded. */
+}
+
+float world_ground_height(float x, float z)
+{
+ /* The world is flat for now. This is where a heightmap/platform lookup
+ * will go once there's terrain to stand on. */
+ (void)x;
+ (void)z;
+ return 0.0f;
+}
+
+/* Keeps x and z on the ground square; y (height) is untouched. */
+Vec3 world_clamp_to_bounds(Vec3 p)
+{
+ p.x = clampf(p.x, -WORLD_HALF_EXTENT, WORLD_HALF_EXTENT);
+ p.z = clampf(p.z, -WORLD_HALF_EXTENT, WORLD_HALF_EXTENT);
+ return p;
+}
+
+Vec3 world_spawn_point(void)
+{
+ return vec3_make(0.0f, 0.0f, 0.0f);
+}
+
+float world_half_extent(void)
+{
+ return WORLD_HALF_EXTENT;
+}
diff --git a/platformer/src/world.h b/platformer/src/world.h
index 9553938..af60feb 100644
--- a/platformer/src/world.h
+++ b/platformer/src/world.h
@@ -37,4 +37,12 @@
#ifndef WORLD_H
#define WORLD_H
+#include "math3d.h"
+
+void world_init(void);
+float world_ground_height(float x, float z);
+Vec3 world_clamp_to_bounds(Vec3 p);
+Vec3 world_spawn_point(void);
+float world_half_extent(void);
+
#endif /* WORLD_H */