diff options
| author | Schark <jordan@schark.online> | 2026-09-29 21:02:22 -0400 |
|---|---|---|
| committer | Schark <jordan@schark.online> | 2026-09-29 21:02:22 -0400 |
| commit | 21404c26d3907cefa524878fb031e7a2022fb3d7 (patch) | |
| tree | 38b2bb26d6d0c05447213edca4911ccc3887f474 | |
| parent | 5f04f3ae87fb307e055d39e81f7c0c841e8a9af8 (diff) | |
| download | gamedev-21404c26d3907cefa524878fb031e7a2022fb3d7.tar.gz gamedev-21404c26d3907cefa524878fb031e7a2022fb3d7.zip | |
Game world test with updated movement
Diffstat (limited to '')
| -rw-r--r-- | platformer/README.md | 15 | ||||
| -rw-r--r-- | platformer/game_feel.md | 118 | ||||
| -rw-r--r-- | platformer/src/config.h | 20 | ||||
| -rw-r--r-- | platformer/src/level.c | 884 | ||||
| -rw-r--r-- | platformer/src/level.h | 82 | ||||
| -rw-r--r-- | platformer/src/main.c | 4 | ||||
| -rw-r--r-- | platformer/src/physics.c | 106 | ||||
| -rw-r--r-- | platformer/src/physics.h | 20 | ||||
| -rw-r--r-- | platformer/src/player.c | 241 | ||||
| -rw-r--r-- | platformer/src/player.h | 34 | ||||
| -rw-r--r-- | platformer/src/render.c | 33 | ||||
| -rw-r--r-- | platformer/src/world.c | 168 | ||||
| -rw-r--r-- | platformer/src/world.h | 59 |
13 files changed, 1603 insertions, 181 deletions
diff --git a/platformer/README.md b/platformer/README.md index 5a91052..570a105 100644 --- a/platformer/README.md +++ b/platformer/README.md @@ -2,7 +2,8 @@ A small 3D platformer written from scratch in C. The only libraries are GLFW, GLEW and OpenGL. -**Current scope:** a flat test world scattered with box platforms, one character (a box with a drop +**Current scope:** a flat test world scattered with box platforms, a small wall course, and a 55 m cliff +parkour course (behind spawn: generated, branching, with moving platforms), one character (a box with a drop shadow), a third-person camera, and a gamepad. That's everything. The only goal right now is to **dial in character movement**: running, turning, jumping and falling should feel good before anything else gets built. @@ -40,7 +41,7 @@ plus plain box platforms to jump on) *is* the game until the controls feel great the lower input latency noticeable, and the per-tick math stays the same either way. - **An explicit player state machine.** SM64 has Mario "actions" (idle, walking, jumping, and so on). We started with four states (`IDLE`, `RUN`, `JUMP`, `FALL`) and add more only when a move requires it - (so far `SKID`). + (so far `SKID` and `WALL_HANG`). - **Analog-magnitude movement.** How far you push the stick sets how fast you move. A radial deadzone keeps the full 0..1 range usable. - **Camera-relative controls.** "Up" on the stick means "away from the camera". The player orbits @@ -94,6 +95,7 @@ The game is designed for a gamepad (Xbox-style layout names; GLFW maps other pad | Right stick click | recenter: swing the camera behind the player, centered | | A (south button) | jump (hold longer to jump higher); press again within 0.2 s of landing for a second jump 1.75× as high | | Left stick pulled back at full run | skid; press A during the skid for a retreat jump (2× height, toward the stick; landing it also opens the second-jump window) | +| Jump into a violet wall (second jump, retreat jump) | wall hang: cling for 0.5 s sliding slowly down; A jumps off, mirrored away from the wall | | Back / Select | reset player to spawn | | Start | quit | @@ -115,7 +117,8 @@ arrow keys = camera, C = recenter camera, Space = jump, R = reset, Esc = quit. | `src/math3d.h` | Tiny header-only vector/matrix math (`Vec2`, `Vec3`, `Mat4`). | | `src/window.c/.h` | The window and OpenGL context (GLFW + GLEW), the clock, and swapping buffers. | | `src/controls.c/.h` | Reads the gamepad (or keyboard fallback) into one abstract `Input` struct. | -| `src/world.c/.h` | The test level: ground, seeded random box platforms, geometry queries and boundaries. | +| `src/level.c/.h` | What's in the test level: seeded random platforms, the wall course, the generated cliff course, and how moving platforms move. | +| `src/world.c/.h` | The level while the game runs: stores the boxes, moves the moving ones each tick, answers geometry queries and boundaries. | | `src/physics.c/.h` | Gravity, velocity integration, and floor/wall/ceiling collision for a generic `Body`. | | `src/player.c/.h` | The player's state machine. Turns `Input` into running, turning and jumping. | | `src/camera.c/.h` | Third-person orbit camera that frames the player inside a screen-space zone. | @@ -128,6 +131,7 @@ main ──► window, controls, world, player, camera, render controls ──► window (keyboard fallback needs the window handle) player ──► physics, world, controls (Input struct only) physics ──► world +world ──► level (level.c only uses world.h's Box type; it never calls world) camera ──► controls (Input struct only) render ──► player, camera, world (reads only, never modifies) everything ──► config.h, math3d.h @@ -138,6 +142,7 @@ everything ──► config.h, math3d.h ``` window_poll_events() while (enough time has built up for a tick): // fixed 60 Hz + world_update() (moving platforms move first, so the player rides them) controls_poll() -> Input player_update() (uses Input + the camera's yaw) camera_update() (re-frames the player's new position) @@ -190,8 +195,8 @@ Suggested fill-in order (each step can be compiled before moving on): - Richer level geometry: slopes, moving platforms, step-up onto small ledges, hand-built or loaded levels - Camera collision (the camera can currently pass through tall platforms) - Loading levels -- SM64-style extra moves: triple jump, long jump, wall kick, ground pound (the second jump and the - skid's retreat jump exist) +- SM64-style extra moves: triple jump, long jump, ground pound (the second jump, the skid's retreat + jump and the wall hang/wall jump exist) - Character model and animation - Audio - On-screen text/HUD beyond the FPS counter in the top-right corner diff --git a/platformer/game_feel.md b/platformer/game_feel.md index 6fc4a2e..616e649 100644 --- a/platformer/game_feel.md +++ b/platformer/game_feel.md @@ -114,14 +114,46 @@ and eased, not snappier. (19.66 m/s): a full retreat jump reaches **4.67 m** (2.00× the first jump, the highest jump), with 59 ticks of airtime and about 3.9 m of travel; a tap gives about 1.4 m. `retreating_movement` stays on through the jump and turns off on landing. Landing it **does** open the second-jump window - (`heightened_movement`, 0.2 s), so skid → retreat jump → second jump chains. + (`heightened_movement`, 0.2 s), so skid → retreat jump → second jump chains. `heightened_movement` is + also on for the whole retreat jump, so it can grab a wall. +- **`heightened_movement` rules, all in one place.** It turns on when landing a normal or retreat jump + (a 0.2 s window that only counts down while not in a jump), and during a second jump, retreat + jump, wall hang, or **any** wall jump (early or late). It turns off when the window runs out, when + landing a second jump or plain fall, or when a wall hang runs out. On the ground it means "A + gives the second jump"; in the air it means "can wall hang". +- **The wall hang (`WALL_HANG`).** Grabbing a wall needs all of these: `heightened_movement` is on, + the player is in the air (JUMP or FALL), they hit the side of a box with `allows_wall_hang`, and + they came in within 45° of head-on (`PLAYER_WALL_HANG_ANGLE_DEG`). A 50° hit slides along the wall + as usual. On grabbing, the player **turns to face where the wall jump will launch** (the + mirrored direction below, so the nose previews the jump), stops, and slides down with gravity off: + `vel.y = −min(3 m/s² × t, 2 m/s)` (`PLAYER_WALL_SLIDE_ACCEL`, `PLAYER_WALL_SLIDE_MAX_SPEED`). That's + 0.45 / 0.90 / 1.35 / 1.50 m/s at 0.15 / 0.30 / 0.45 / 0.50 s, and about 0.4 m of slide over the + whole hang. (The 2 m/s cap is only reached if the hang lasts past 0.67 s.) After + `PLAYER_WALL_HANG_DURATION` (0.5 s, 30 ticks) the player lets go: they drop + straight down at normal gravity, with `heightened_movement` off so they can't grab again before + landing. Sliding onto a floor is an ordinary landing, and sliding past the wall's bottom or end + lets go early. +- **The wall jump.** A during the hang jumps along the approach direction **mirrored off the wall**: + the part along the wall is kept and the part into it flips, so coming in 5° from the left leaves 5° + to the right (measured: 175° in → 5° out, 210° in → −30° out). In the first 0.1 s of the hang + (`PLAYER_WALL_JUMP_EARLY_TIME`, 6 ticks) it's a **second jump**: 4.08 m up, launched at 5 m/s. + After that it's a **normal jump**: 2.33 m up, launched at 6 m/s, and landing it opens the usual + 0.2 s window. **Both keep `heightened_movement` on for the whole jump**, so any wall jump can grab + the next wall. (At first the late one turned it off, and players found wall jumps that + wouldn't grab the next wall.) Each + takes on everything about its jump kind (top speed in the air, the variable-height cut, what + landing does). **One wall can't be grabbed twice in a row:** the wall *surface* you jumped off (same + facing, same face position) is locked out until you land, so holding toward it can't climb it + forever. Comparing surfaces rather than boxes matters on the cliff, which is built from side-by-side + strips: zigzagging along one face can't climb it. Two walls facing each + other can still be chained: in the chimney, each early wall jump gains 3.3 m and crosses in 39 ticks. - **`heightened_movement` and `retreating_movement` are named player states on purpose.** They're - fields on `Player`, separate from the IDLE/RUN/SKID/JUMP/FALL action, because later moves are meant + fields on `Player`, separate from the IDLE/RUN/SKID/JUMP/FALL/WALL_HANG action, because later moves are meant to key off them. Which jump the player is in is `jump_kind` (`JUMP_NORMAL`, `JUMP_SECOND`, `JUMP_RETREAT`); the jumps share the `JUMP` action. The title bar shows `| heightened` / `| retreating` while they're on (the title refreshes every 0.25 s, so the 0.2 s window may blink briefly or not show at all; the jumps themselves always show - it). The skid also shows as `SKID` in the state slot. + it). The skid and wall hang also show as `SKID` / `WALL_HANG` in the state slot. - **SM64-style circling is intentional.** Controls stay purely camera-relative even while the camera swings on its own, so holding the stick sideways during a camera swing makes the player run a wide arc (about 12 m radius, 24 m across, at 6 m/s). The user explicitly chose this over locking the stick direction. @@ -210,6 +242,72 @@ New automatic camera behaviors should follow the same approach: slow, eased, and - **The level is a test space**, like SM64's pre-level sandbox: flat ground plus 40 seeded-random box platforms (`WORLD_SEED`, so every run is the same layout). Spawn is kept clear (4 m). +- **Wall hanging is opt-in per box.** `Box.allows_wall_hang` is false by default. The level marks + **big terrain surfaces** (cliffs, rock pillars, the wall course's walls) and never small platforms, so + ordinary platforming never gets sticky. Hangable walls are drawn **violet** (`COLOR_WALL_HANG`), and + hangable rock is **violet-tinted rock** (`COLOR_CLIFF_HANG`), so you can tell at a glance. +- **Level content lives in `level.c`; `world.c` only stores it, moves it, and answers queries.** +- **The wall course** (`WALL_COURSE` in `level.c`) is straight ahead of the starting camera, 33–48 m + toward −Z and clear of the random platforms. It has a 12 × 8 m main wall (hangable, facing spawn), a + chimney (two 10 m hangable walls with a 4 m gap, entered from the end facing spawn), a 1.5 m step + block in front of the main wall, a ledge on the main wall at 4–4.5 m (x −2..1), a slab at 5.5–6 m + off the wall's left end, and an 8 m terracotta pillar that is *not* hangable, for comparison. The + layout is a first guess for tuning. Note the ledge: jumping into the main wall right under it hits + the ledge's side first, which isn't hangable. +- **The cliff course** (`level.c`, seeded from `CLIFF_COURSE_SEED`) is **behind** spawn (+Z, so turn + around). It's meant for **expression, not a skill check**: a scatter of platforms you read and + choose a way through, some moving, some leading nowhere, some that look possible and aren't. + - **The cliff** is a right triangle, 55 m tall. The south face (z = 40, facing spawn, x −30..20) and + the east face (x = 20, z 40..90) meet at the south-east corner. The third side faces north-west, + built as 10 strips stepping down the diagonal. **The cliff is hangable** (violet-tinted rock), and + so are 7 tall rock pillars 3.5–5 m out from the faces, which form random chimneys with it. The rule + is that big terrain surfaces are hangable and small platforms aren't. + - **How it's generated:** a band wraps the cliff (along the south face, around the corner, up the + east face). Each row out from the face turns the corner at its own spot, so distance along the + band is continuous. On it: + 1. One hidden **route** from the ground to one hop below the top, made of **big platforms (3–4.5 + m)**, because the player's weight makes small ledges skid-offs. Each step is a comfortable + normal-jump rise (0.9–1.7 m) or second-jump rise (2–2.9 m), with the path between the two + platforms checked clear (no pillar or platform in the way). About a third of the steps are + **switchbacks**, hopping out to the next row or back in instead of along, so the route climbs + without running off the end of the face. Hops in toward the hangable face are always normal + jumps, because a second jump's overshoot would grab the face instead of landing. The route + stays beside the faces and drifts in for its last hop. When boxed in, it tries easier hops, + then a scan of nearby spots. + 2. A **scatter** of 5 more platforms (mostly moving) for branches and dead ends. + 3. **The crossing:** a route on the line from the top's north-west corner over the river to the + far cliff (60 m, hangable, the finish), plus 2 extras. + + In total that's **about 37 platforms** (the user asked for 30–40, down from ~135), 8 of them moving. + - **Moving platforms:** each slides back and forth along the band, bobs up and down, or loops a + flat or upright circle, with its own 3.5–7 s period and phase (`BoxMotion` in `level.h`). Every + motion passes through its placed position each cycle, and no two moving route platforms are in a + row, so waiting always works. They keep 1.0 m from rock (more than the player is wide, so they + can't pin you) and stay 1 m above the ground. The finish **needs** at least one of them. + - **Placement rules:** nothing overlaps. Platforms nearly over one another (within 0.3 m sideways) + are 4.3 m apart vertically, so none blocks a jump from another. + - **Verified by a headless course test** (outside the repo). It builds a reachability graph with a + conservative jump model, sampling the moving platforms over 60 s. The bot then plays every + plausible upward hop between still platforms and drops the ones that fail (35 played, 1 failed). + The top and the finish are reachable. With one route and ~37 platforms, most route platforms are + the only way past their spot in the graph. The graph doesn't count wall hangs, though, and the + hangable cliff and pillar chimneys offer other ways up. **The user asked for ambiguity:** jumps + that fail or dead ends are fine, as long as the course as a whole can be finished. Don't tighten + it into a clean, obvious path. + - **A snag to know about:** a *second* jump straight at the hangable cliff from a ledge just below + the lip grabs the face instead of clearing the top, because `heightened_movement` is on. Topping + out works with a normal jump (wait out the 0.2 s window). The generator's hops in toward the face + are normal jumps for the same reason. A ledge-climb or "clear the lip" rule is a candidate for later. + - **The river** is 13 overlapping water tiles (`BOX_STYLE_WATER`, a solid 5 cm sheet, no swimming) + along the diagonal, parallel to the third side. + - **Known rough edges:** there's no camera collision, so the camera passes into the cliff and + through platforms (it's even more noticeable here). A fall from the top is a 55 m drop with no + damage, and Back resets. Jumping off a moving platform doesn't keep its momentum (SM64 mostly + doesn't either). Changing the seed gives a new climb; re-run the course test if you do, or after + changing movement numbers. +- **Box styles** (`Box.style`: `BOX_STYLE_PLATFORM` by default, `CLIFF`, `WATER`) only change color + in `render.c`; collision ignores them. Every box literal spells out all four fields, since the + build warns on missing initializers. - **Heights are sized to the jump:** ground blocks top out at 2.0 m (below the 2.33 m jump); floating slabs sit at 2.6–4.2 m, reached by jumping from a block. The 4.08 m second jump can reach 14 of the 16 slabs straight from the ground; the two with tops at 4.11 m and 4.17 m still need a block. Only 9 of 16 floating slabs have a block close @@ -222,6 +320,13 @@ New automatic camera behaviors should follow the same approach: slow, eased, and - The floor check uses the height *before* the move, so even a terminal-velocity fall can't tunnel through a 0.5 m slab. - Jumping into an underside bonks. + - Every push out of a box's side sets `Body.hit_wall`, the side's `wall_normal` and its `wall` box. + That's how the wall hang knows what it touched. `Body.gravity_scale` (normally 1) lets the + player switch gravity off while it drives its own wall slide. + - **Moving platforms carry you.** `main.c` calls `world_update` before the player each tick. Physics + first moves a body by however far its `ground_box` moved (so you ride up, down, sideways and round + loops: 0 fall-offs and 4 cm of drift over 16 s on every moving platform). Then it steps the body out + of any box that moved into it, along the shortest way. Still boxes never trigger the step-out. - **Readability is part of feel.** With no lighting, a one-color box is a flat silhouette and jumps become guesswork. Platforms use a **fixed brightness per face** (tops brightest). The **drop shadow** sits on whatever surface you'd land on and is the main depth cue, as in SM64. Keep both if you @@ -275,6 +380,13 @@ New automatic camera behaviors should follow the same approach: slow, eased, and | Second jump window | 0.5 s → 0.3 s → 0.2 s after landing | 0.2 s | | Second jump from | normal jump landings → also retreat jump landings | both | | Normal jump top speed | 6 m/s (run speed) → 7 m/s, built at 1.5 m/s², eased back at 2 m/s² after landing | 7 m/s | +| Retreat jump | + `heightened_movement` for the whole jump (it can wall hang) | on | +| Wall hang | added: 45° grab, 0.75 s, slide 3 m/s² capped at 2 m/s, mirrored wall jump (second-jump-like for 0.1 s, then normal) | — | +| Wall hang duration | 0.75 s → 0.5 s (early wall jump window kept at 0.1 s) | 0.5 s | +| Cliff course | hand-placed single path → generated (2 routes + ~135 platforms) → 1 route + extras, ~37 big platforms (3–4.5 m), hangable rock, moving platforms | seed 20260930 | +| Wall lockout | per box → per wall surface (the cliff is several boxes) | surface | +| Late wall jump heightened | off → on (late wall jumps couldn't grab the next wall) | on | +| Facing while wall hanging | into the wall → the wall jump's launch direction (a visual preview) | launch dir | | Second jump top speed | 6 m/s (same as running) → 4 → 5 m/s until it lands (4 felt a tad harsh) | 5 m/s | | Second jump slowdown | air accel 9 m/s² (0.25 s, "wall of syrup") → own rate 3.5 m/s² (0.60 s) | 3.5 m/s² | | Skid | none (full-speed U-turn) → 18 m/s² even braking, turn at the end (0.33 s) → face the stick at once, glide-then-plant curve (power 2) | 0.5 s | diff --git a/platformer/src/config.h b/platformer/src/config.h index 23d85ec..35feb4c 100644 --- a/platformer/src/config.h +++ b/platformer/src/config.h @@ -79,6 +79,15 @@ * PLAYER_RETREAT_JUMP_SPEED 4.0f m/s launched toward the stick, and the top * speed until that jump lands * + * Player: wall hang + * PLAYER_WALL_HANG_ANGLE_DEG 45.0f degrees; how far off head-on the player may + * hit a hangable wall and still hang + * PLAYER_WALL_HANG_DURATION 0.5f s the hang lasts before the player lets go + * PLAYER_WALL_SLIDE_ACCEL 3.0f m/s^2 how slowly the hang slides downward + * PLAYER_WALL_SLIDE_MAX_SPEED 2.0f m/s fastest slide down the wall + * PLAYER_WALL_JUMP_EARLY_TIME 0.1f s into the hang that a wall jump is still + * the high, second-jump-like one + * * Physics * GRAVITY 40.0f m/s^2 (stronger than real 9.8 on purpose: * platformers feel floaty with real gravity) @@ -128,6 +137,9 @@ * GRID_MAJOR_EVERY 10 every Nth line drawn brighter * WORLD_SEED 20260924u seed for the platform layout; change it * for a different (but repeatable) level + * CLIFF_COURSE_SEED 20260930u seed for the cliff course's generated + * platforms (see level.c); change it for + * a different climb * WORLD_PLATFORM_COUNT 40 how many platforms to scatter * WORLD_PLATFORM_AREA 25.0f m; platforms land within this distance of * spawn in x and z (smaller = denser) @@ -191,6 +203,13 @@ #define PLAYER_RETREAT_JUMP_VELOCITY 19.66f /* m/s upward for the jump out of a skid; tuned to 2x the first jump's height (4.67 m at 60 Hz) */ #define PLAYER_RETREAT_JUMP_SPEED 4.0f /* m/s launched toward the stick, and the top speed until landing; higher = travels farther */ +/* ---- Player: wall hang -------------------------------------------------- */ +#define PLAYER_WALL_HANG_ANGLE_DEG 45.0f /* degrees off head-on that still grabs a hangable wall; higher = grabs from shallower angles */ +#define PLAYER_WALL_HANG_DURATION 0.5f /* s clinging before letting go and falling normally; higher = longer linger */ +#define PLAYER_WALL_SLIDE_ACCEL 3.0f /* m/s^2 the cling slides down the wall; lower = stickier */ +#define PLAYER_WALL_SLIDE_MAX_SPEED 2.0f /* m/s fastest slide down the wall while clinging */ +#define PLAYER_WALL_JUMP_EARLY_TIME 0.1f /* s into the hang that A still gives the high (second-jump-like) wall jump; later = normal-jump-like */ + /* ---- 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 */ @@ -229,6 +248,7 @@ #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 */ #define WORLD_SEED 20260924u /* platform layout seed; change for a different (repeatable) level */ +#define CLIFF_COURSE_SEED 20260930u /* cliff course layout seed (level.c); change for a different (repeatable) climb */ #define WORLD_PLATFORM_COUNT 40 /* platforms scattered around spawn; more = busier level */ #define WORLD_PLATFORM_AREA 25.0f /* m from spawn (x and z) platforms can land; smaller = denser */ diff --git a/platformer/src/level.c b/platformer/src/level.c new file mode 100644 index 0000000..2e3b862 --- /dev/null +++ b/platformer/src/level.c @@ -0,0 +1,884 @@ +/* + * ============================================================ + * FILE: level.c + * + * PURPOSE: What's in the test world: the boxes it's made of and how the + * moving ones move. It's still a test space, like the one SM64's + * team tuned Mario in, just with a lot more to jump on now. + * + * FITS IN: Implements level.h. world.c calls level_build() once and + * level_motion_offset() every tick. Uses only config.h, math3d.h + * and the types in world.h; it never calls world.c. + * + * IMPLEMENT: + * - A tiny xorshift32 random generator. WHY our own instead of rand(): + * rand() differs between C libraries, so the "same" seed could give a + * different level on another machine. + * + * - level_build() adds, in this order (each check below looks at all boxes + * added before it): + * 1. Random platforms (seeded from WORLD_SEED): WORLD_PLATFORM_COUNT boxes + * within WORLD_PLATFORM_AREA of spawn, re-rolled if they come within + * SPAWN_CLEAR_RADIUS of it. Two kinds: + * block stands on the ground, top low enough to jump onto (a + * full jump lifts the feet ~2.3 m) + * floating a thin slab higher up, reached by jumping from a block + * They may overlap each other; that's fine for collision and drawing. + * 2. WALL_COURSE: hand-placed boxes for tuning the wall hang, straight + * ahead of the starting view (it looks toward -Z). Its walls allow the + * wall hang; its platforms and the comparison pillar don't. + * 3. The cliff course, behind spawn (+Z; turn around), seeded from + * CLIFF_COURSE_SEED so it doesn't change when the random platforms do: + * Triangle cliff a right triangle, CLIFF_TOP (55 m) tall. Its SOUTH + * face (z = 40, facing spawn) and EAST face (x = 20) + * meet at the south-east corner. The third side faces + * north-west and can't be axis-aligned, so the cliff + * is CLIFF_STRIP_COUNT strips whose north ends step + * down that diagonal. Rock, and HANGABLE: big terrain + * surfaces allow the wall hang; small platforms don't. + * Rock pillars PILLAR_COUNT tall hangable pillars a few meters out + * from the faces, so they form chimneys with the cliff. + * The climb a band that wraps the cliff: along the south face + * west to east, around the corner, north along the + * east face. Distance along it is `s`; distance out + * from the face is `out`. On it: + * - one ROUTE: big platforms (ROUTE_MIN_SIZE..MAX) placed + * one hop after another (a normal jump or a second + * jump, with the path between them clear) from the + * ground to one hop below the top. It guarantees the + * climb is possible but isn't marked: it wanders in + * and out and takes switchbacks (hopping out to the + * next row or back in instead of along). Hops in + * toward the hangable face are normal jumps, so an + * overshoot can't grab the face. Each row turns the + * corner at its own spot (corner_s) so `s` is + * continuous round the turn. The route paces itself + * to arrive by ROUTE_ARRIVE_BY, stays beside the faces, + * drifts in for its last hop, and when boxed in tries + * easier hops, a scan of nearby spots, then (once) a + * wider strip. + * - the SCATTER: a few more platforms (SCATTER_COUNT) at + * random spots and heights around the route: other ways up, + * shortcuts, dead ends, and jumps that look possible + * but aren't. That ambiguity is WANTED: the player + * should have to judge which paths are feasible. + * The river overlapping water tiles along the diagonal, parallel + * to the cliff's third side. + * The crossing the same idea (a route plus a couple of extras) on + * the straight line from the + * top's north-west corner over the river to the far + * cliff (60 m, hangable), the finish. + * Some platforms move (ROUTE_MOVING_SHARE / SCATTER_MOVING_SHARE): they + * slide back and forth along the band, bob up and down, or loop round a + * flat or upright circle, each with its own period and phase. A moving + * route platform is never next to another moving one, and passes through + * its placed position every cycle, so waiting on the previous platform + * always works. Moving platforms stay MOVING_MIN_BOTTOM above the ground. + * Placement rules (is_clear): nothing overlaps; platforms (nearly) over + * one another (footprints within CLEAR_SIDE_GAP) are at least + * CLEAR_HEADROOM apart vertically, so none blocks a jump from another; + * a platform over a rock's top keeps that headroom too; moving platforms keep + * MOVING_ROCK_GAP from rock so they can't pin the player against it. + * WHY a guaranteed route under a scatter: the scatter makes the climb a + * choice ("how do I get up there?") instead of one correct jump after + * another, and the route makes sure a way up always exists. + * + * - level_motion_offset(m, time): see level.h. + * - level_spawn_point(): (0, 0, 0). + * + * CONVENTIONS: Y up, boxes axis-aligned, the ground surface is y = 0. Every + * Box literal spells out all its fields (the build warns on + * missing ones); false / BOX_STYLE_PLATFORM are the defaults. + * + * NOT IN SCOPE: Level files, hand-authoring tools, moving walls. + * + * DONE WHEN: The same seeds always build the same level, spawn is clear, the + * wall course is ahead of the starting view, and the cliff course + * behind it can be climbed and crossed with the moves in player.c, + * using about 30-40 platforms in all. + * ============================================================ + */ + +#include <math.h> +#include <stdint.h> + +#include "config.h" +#include "level.h" + +/* ---- Random numbers ---------------------------------------------------- */ + +static uint32_t s_rng_state; + +/* xorshift32: three shifts and XORs give a decent, fully repeatable sequence. */ +static uint32_t next_random(void) +{ + s_rng_state ^= s_rng_state << 13; + s_rng_state ^= s_rng_state >> 17; + s_rng_state ^= s_rng_state << 5; + return s_rng_state; +} + +static void seed_random(uint32_t seed) +{ + s_rng_state = seed ? seed : 1u; /* xorshift must not start at 0 */ +} + +/* A float in [lo, hi]. */ +static float random_range(float lo, float hi) +{ + return lo + (hi - lo) * ((float)next_random() / 4294967295.0f); +} + +static bool random_chance(float share) +{ + return random_range(0.0f, 1.0f) < share; +} + +/* ---- The box list being built ------------------------------------------ */ + +static LevelBox *s_out; +static int s_count, s_capacity; +/* The space each box can ever occupy (its whole path, if it moves), for the + * placement rules. */ +static Box s_reach[LEVEL_MAX_BOXES]; + +static BoxMotion no_motion(void) +{ + BoxMotion m = { MOTION_NONE, { 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f }, 1.0f, 0.0f }; + return m; +} + +static Box shift_box(Box b, Vec3 by) +{ + b.min = vec3_add(b.min, by); + b.max = vec3_add(b.max, by); + return b; +} + +/* Everywhere a box goes over one cycle: its bounds sampled round the cycle. */ +static Box reach_of(Box b, BoxMotion m) +{ + if (m.kind == MOTION_NONE) + return b; + Box reach = b; + for (int i = 0; i < 32; i++) { + Box at = shift_box(b, level_motion_offset(m, m.period * (float)i / 32.0f)); + reach.min.x = fminf(reach.min.x, at.min.x); reach.max.x = fmaxf(reach.max.x, at.max.x); + reach.min.y = fminf(reach.min.y, at.min.y); reach.max.y = fmaxf(reach.max.y, at.max.y); + reach.min.z = fminf(reach.min.z, at.min.z); reach.max.z = fmaxf(reach.max.z, at.max.z); + } + return reach; +} + +static void add_box(Box b, BoxMotion m) +{ + if (s_count >= s_capacity) + return; /* full: LEVEL_MAX_BOXES is sized with room to spare */ + s_out[s_count].box = b; + s_out[s_count].motion = m; + s_reach[s_count] = reach_of(b, m); + s_count++; +} + +/* ---- 1. Random platforms ----------------------------------------------- */ + +#define PLATFORM_MIN_SIZE 2.0f /* m, shortest footprint side */ +#define PLATFORM_MAX_SIZE 6.0f /* m, longest footprint side */ +#define BLOCK_MIN_TOP 0.6f /* m, lowest ground block */ +#define BLOCK_MAX_TOP 2.0f /* m, highest ground block (full jump reaches ~2.3) */ +#define FLOATING_MIN_TOP 2.6f /* m, lowest floating slab top */ +#define FLOATING_MAX_TOP 4.2f /* m, highest floating slab top (reachable from a block) */ +#define FLOATING_THICKNESS 0.5f /* m, floating slab thickness */ +#define FLOATING_CHANCE 0.35f /* fraction of platforms that float */ +#define SPAWN_CLEAR_RADIUS 4.0f /* m around spawn kept free of platforms */ +#define MAX_PLACEMENT_TRIES 50 /* re-rolls before giving up on a platform */ + +/* True if the footprint comes within SPAWN_CLEAR_RADIUS of spawn. Uses the + * closest point of the footprint to spawn, so big platforms can't sneak in. */ +static bool too_close_to_spawn(Box b) +{ + Vec3 spawn = level_spawn_point(); + float dx = clampf(spawn.x, b.min.x, b.max.x) - spawn.x; + float dz = clampf(spawn.z, b.min.z, b.max.z) - spawn.z; + return dx * dx + dz * dz < SPAWN_CLEAR_RADIUS * SPAWN_CLEAR_RADIUS; +} + +/* One platform with a random size and height, centered on the origin. */ +static Box random_platform_shape(void) +{ + float half_x = 0.5f * random_range(PLATFORM_MIN_SIZE, PLATFORM_MAX_SIZE); + float half_z = 0.5f * random_range(PLATFORM_MIN_SIZE, PLATFORM_MAX_SIZE); + float bottom, top; + if (random_chance(FLOATING_CHANCE)) { + top = random_range(FLOATING_MIN_TOP, FLOATING_MAX_TOP); + bottom = top - FLOATING_THICKNESS; + } else { + top = random_range(BLOCK_MIN_TOP, BLOCK_MAX_TOP); + bottom = 0.0f; + } + Box b = { { -half_x, bottom, -half_z }, { half_x, top, half_z }, + false, BOX_STYLE_PLATFORM }; /* no wall hang, palette color */ + return b; +} + +static void add_random_platforms(void) +{ + seed_random(WORLD_SEED); + for (int i = 0; i < WORLD_PLATFORM_COUNT; i++) { + Box shape = random_platform_shape(); + for (int tries = 0; tries < MAX_PLACEMENT_TRIES; tries++) { + Vec3 spot = vec3_make(random_range(-WORLD_PLATFORM_AREA, WORLD_PLATFORM_AREA), 0.0f, + random_range(-WORLD_PLATFORM_AREA, WORLD_PLATFORM_AREA)); + Box placed = shift_box(shape, spot); + if (!too_close_to_spawn(placed)) { + add_box(placed, no_motion()); + break; + } + } + } +} + +/* ---- 2. The wall course ------------------------------------------------ */ + +/* Min corner, max corner, wall hang, style. */ +static const Box WALL_COURSE[] = { + /* The main wall: 12 m wide and 8 m tall, its hangable face toward spawn. */ + { { -10.0f, 0.0f, -40.5f }, { 2.0f, 8.0f, -40.0f }, true, BOX_STYLE_PLATFORM }, + /* A chimney: two 10 m walls with a 4 m gap, for wall-to-wall jumps. + * Enter from the open end facing spawn. */ + { { 6.0f, 0.0f, -48.0f }, { 6.5f, 10.0f, -36.0f }, true, BOX_STYLE_PLATFORM }, + { { 10.5f, 0.0f, -48.0f }, { 11.0f, 10.0f, -36.0f }, true, BOX_STYLE_PLATFORM }, + /* A step block in front of the main wall. */ + { { -6.0f, 0.0f, -36.5f }, { -3.0f, 1.5f, -33.5f }, false, BOX_STYLE_PLATFORM }, + /* A ledge on the main wall's face, to land on from a wall jump. */ + { { -2.0f, 4.0f, -40.0f }, { 1.0f, 4.5f, -38.0f }, false, BOX_STYLE_PLATFORM }, + /* A high slab off the main wall's left end, reached with a wall jump. */ + { { -13.0f, 5.5f, -39.0f }, { -10.5f, 6.0f, -36.0f }, false, BOX_STYLE_PLATFORM }, + /* A pillar as tall as the main wall but NOT hangable, for comparison. */ + { { -18.0f, 0.0f, -41.0f }, { -16.0f, 8.0f, -39.0f }, false, BOX_STYLE_PLATFORM }, +}; +#define WALL_COURSE_COUNT ((int)(sizeof WALL_COURSE / sizeof WALL_COURSE[0])) + +/* ---- 3. The cliff course: fixed terrain -------------------------------- */ + +#define CLIFF_TOP 55.0f /* m, the triangle cliff's flat top */ +#define CLIFF_WEST_X -30.0f /* m, west end of the south face */ +#define CLIFF_SOUTH_Z 40.0f /* m, the south face */ +#define CLIFF_STRIP_WIDTH 5.0f /* m, width of each strip = step size along the diagonal */ +#define CLIFF_STRIP_COUNT 10 /* strips west to east; the east face is the last one's side */ +#define CLIFF_EAST_X (CLIFF_WEST_X + CLIFF_STRIP_WIDTH * CLIFF_STRIP_COUNT) /* 20 m */ +#define RIVER_START_X -80.0f /* m, south-west corner of the first river tile */ +#define RIVER_START_Z 12.0f +#define RIVER_TILE_SIZE 12.0f /* m, each square tile's side */ +#define RIVER_TILE_STEP 6.0f /* m, each tile is this far along x AND z from the last */ +#define RIVER_TILE_COUNT 13 +#define RIVER_DEPTH 0.05f /* m, the water is a thin sheet on the ground */ + +/* The far cliff: the finish, 60 m up, across the river. */ +static const Box FAR_CLIFF = { { -70.0f, 0.0f, 80.0f }, { -32.0f, 60.0f, 98.0f }, true, BOX_STYLE_CLIFF }; + +/* The triangle cliff: strips side by side along the south face, each + * reaching one step further north than the last. Their row of north ends is + * the diagonal third side; the last strip's east side is the east face. */ +static void add_triangle_cliff(void) +{ + for (int i = 0; i < CLIFF_STRIP_COUNT; i++) { + float west = CLIFF_WEST_X + CLIFF_STRIP_WIDTH * (float)i; + Box strip = { { west, 0.0f, CLIFF_SOUTH_Z }, + { west + CLIFF_STRIP_WIDTH, CLIFF_TOP, + CLIFF_SOUTH_Z + CLIFF_STRIP_WIDTH * (float)(i + 1) }, + true, BOX_STYLE_CLIFF }; + add_box(strip, no_motion()); + } +} + +/* The river: square water tiles, each one step further along x AND z, so + * they overlap into a band running diagonally, parallel to the cliff's third + * side. */ +static void add_river(void) +{ + for (int i = 0; i < RIVER_TILE_COUNT; i++) { + float x = RIVER_START_X + RIVER_TILE_STEP * (float)i; + float z = RIVER_START_Z + RIVER_TILE_STEP * (float)i; + Box tile = { { x, 0.0f, z }, { x + RIVER_TILE_SIZE, RIVER_DEPTH, z + RIVER_TILE_SIZE }, + false, BOX_STYLE_WATER }; + add_box(tile, no_motion()); + } +} + +/* ---- 3. The cliff course: placement rules ------------------------------ */ + +#define CLEAR_SIDE_GAP 0.3f /* m; platforms (nearly) over one another must be far apart vertically... */ +#define CLEAR_HEADROOM 4.3f /* m; ...by this much, so a jump from the lower can't hit the upper */ +#define MOVING_ROCK_GAP 1.0f /* m a moving platform keeps from rock: more than the player is wide, so it can't pin them */ +#define MOVING_MIN_BOTTOM 1.0f /* m; a moving platform's underside never goes lower than this */ + +static bool is_rock(Box b) +{ + return b.style == BOX_STYLE_CLIFF; +} + +/* Horizontal distance between two footprints (0 if they touch or overlap). */ +static float footprint_gap(Box a, Box b) +{ + float dx = fmaxf(0.0f, fmaxf(a.min.x - b.max.x, b.min.x - a.max.x)); + float dz = fmaxf(0.0f, fmaxf(a.min.z - b.max.z, b.min.z - a.max.z)); + return sqrtf(dx * dx + dz * dz); +} + +static bool footprints_overlap(Box a, Box b) +{ + return a.min.x < b.max.x && a.max.x > b.min.x && a.min.z < b.max.z && a.max.z > b.min.z; +} + +/* Vertical space between two boxes (negative if their height ranges overlap). */ +static float vertical_gap(Box a, Box b) +{ + return fmaxf(a.min.y - b.max.y, b.min.y - a.max.y); +} + +/* Can a platform that sweeps through `reach` go here? See the placement + * rules in the prompt above. */ +static bool is_clear(Box reach, bool moving) +{ + if (moving && reach.min.y < MOVING_MIN_BOTTOM) + return false; /* it would dip into (or skim) the ground */ + for (int i = 0; i < s_count; i++) { + Box other = s_reach[i]; + if (footprints_overlap(reach, other) && vertical_gap(reach, other) < 0.0f) + return false; /* they'd overlap */ + + if (is_rock(other)) { + if (moving && footprint_gap(reach, other) < MOVING_ROCK_GAP) + return false; + if (footprints_overlap(reach, other) && vertical_gap(reach, other) < CLEAR_HEADROOM) + return false; /* hovering too low over a rock top */ + } else if (footprint_gap(reach, other) < CLEAR_SIDE_GAP && + vertical_gap(reach, other) < CLEAR_HEADROOM) { + return false; + } + } + return true; +} + +/* ---- 3. The cliff course: the band round the cliff --------------------- */ + +/* The band runs east along the south face from BAND_START_X, turns the + * corner, and runs north along the east face. Each row (a distance `out` from + * the faces) turns the corner at its own spot, so s, the distance along that + * row, is continuous round the turn whether the row hugs the face or not. */ +#define BAND_START_X -34.0f /* m; the climb starts west of the south face */ +#define BAND_LENGTH 110.0f /* m along a row about 3 m out; rows further out run a bit longer */ +#define PLATFORM_THICKNESS 0.5f /* m, every generated platform is a slab this thick */ + +/* Where a row `out` from the faces (platforms `depth` deep) turns the corner. */ +static float corner_s(float out, float depth) +{ + return CLIFF_EAST_X + out + 0.5f * depth - BAND_START_X; +} + +/* The direction along the band, and the direction away from the face, for + * a platform at s in that row. */ +static Vec3 band_along(float s, float out, float depth) +{ + return s < corner_s(out, depth) ? vec3_make(1.0f, 0.0f, 0.0f) : vec3_make(0.0f, 0.0f, 1.0f); +} + +static Vec3 band_out(float s, float out, float depth) +{ + return s < corner_s(out, depth) ? vec3_make(0.0f, 0.0f, -1.0f) : vec3_make(1.0f, 0.0f, 0.0f); +} + +/* A box on the band: centered at s along its row, its face-side edge `out` + * meters from the cliff face, `along` long and `depth` deep, from `bottom` to + * `top`. At the corner a row's last south box and first east box meet. */ +static Box band_box(float s, float out, float along, float depth, float bottom, float top) +{ + Box b; + float turn = corner_s(out, depth); + b.allows_wall_hang = false; + b.style = BOX_STYLE_PLATFORM; + b.min.y = bottom; + b.max.y = top; + if (s < turn) { + float x = BAND_START_X + s; + b.min.x = x - 0.5f * along; b.max.x = x + 0.5f * along; + b.min.z = CLIFF_SOUTH_Z - out - depth; b.max.z = CLIFF_SOUTH_Z - out; + } else { + float z = CLIFF_SOUTH_Z - out - 0.5f * depth + (s - turn); + b.min.x = CLIFF_EAST_X + out; b.max.x = CLIFF_EAST_X + out + depth; + b.min.z = z - 0.5f * along; b.max.z = z + 0.5f * along; + } + return b; +} + +/* ---- 3. The cliff course: moving platforms ----------------------------- */ + +#define MOTION_MIN_PERIOD 3.5f /* s, quickest cycle */ +#define MOTION_MAX_PERIOD 7.0f /* s, slowest cycle */ +#define MOTION_TRIES 6 /* motions tried for a moving platform before it stays still */ + +/* A random looping motion: slide along the band, bob up and down, or loop + * round a flat or upright circle. `along` and `out` orient it. */ +static BoxMotion random_motion(Vec3 along, Vec3 out) +{ + Vec3 up = vec3_make(0.0f, 1.0f, 0.0f); + BoxMotion m = no_motion(); + m.period = random_range(MOTION_MIN_PERIOD, MOTION_MAX_PERIOD); + m.phase = random_range(0.0f, 1.0f); + switch (next_random() % 4) { + case 0: /* back and forth along the way */ + m.kind = MOTION_SLIDE; + m.a = vec3_scale(along, random_range(1.5f, 3.0f)); + break; + case 1: /* up and down */ + m.kind = MOTION_SLIDE; + m.a = vec3_scale(up, random_range(1.2f, 2.5f)); + break; + case 2: { /* round a flat circle */ + float r = random_range(1.2f, 2.0f); + m.kind = MOTION_LOOP; + m.a = vec3_scale(along, r); + m.b = vec3_scale(out, r); + break; + } + default: { /* round an upright circle, like a ferris wheel seat */ + float r = random_range(1.2f, 2.0f); + m.kind = MOTION_LOOP; + m.a = vec3_scale(up, r); + m.b = vec3_scale(along, r); + break; + } + } + return m; +} + +/* Tries to add a platform, moving if `want_moving` and a random motion fits, + * otherwise still. Returns whether it was added, and whether it moves. */ +static bool try_add_platform(Box b, bool want_moving, Vec3 along, Vec3 out, bool *moved) +{ + *moved = false; + for (int attempt = 0; want_moving && attempt < MOTION_TRIES; attempt++) { + BoxMotion m = random_motion(along, out); + if (is_clear(reach_of(b, m), true)) { + add_box(b, m); + *moved = true; + return true; + } + } + if (!is_clear(b, false)) + return false; + add_box(b, no_motion()); + return true; +} + +/* ---- 3. The cliff course: the route (one guaranteed way) --------------- */ + +/* How far apart two platforms may be for the route: a gap and a rise that a + * normal jump (or a second jump) makes comfortably. Checked by the headless + * course test with margin; these are deliberately cautious. */ +#define ROUTE_NORMAL_MAX_RISE 1.7f /* m; a full jump lifts the feet 2.33 */ +#define ROUTE_SECOND_MIN_RISE 2.0f /* m; second-jump steps rise at least this... */ +#define ROUTE_SECOND_MAX_RISE 2.9f /* m ...and at most this (it lifts the feet 4.08) */ +#define ROUTE_SECOND_MAX_GAP 1.3f /* m; a second jump from standing covers less ground */ +#define ROUTE_MOVING_SHARE 0.4f /* chance a route platform moves (never two in a row) */ +#define ROUTE_TRIES 60 /* candidates per step before trying easier hops */ +#define ROUTE_MAX 64 +#define ROUTE_WIDEST_OUT 9.0f /* m; how far out a boxed-in route may wander */ +#define ROUTE_MIN_SIZE 3.0f /* m; generated platforms are this big or bigger... */ +#define ROUTE_MAX_SIZE 4.5f /* m ...up to this: room to land and skid with the player's weight */ +#define ROUTE_SIDESTEP_SHARE 0.35f /* chance a route step switches rows (out/in) instead of going along */ +#define HOP_HALF_WIDTH 0.45f /* m; the player's half width, plus a little, for the clear-path check */ +#define HOP_CLEARANCE 2.2f /* m above the higher platform the hop's path must be open (body + arc) */ +#define ROUTE_ARRIVE_BY 80.0f /* m along the band the route aims to reach the top by (the face ends ~104) */ +#define ROUTE_PULL_IN_HEIGHT 12.0f /* m below the top where the route starts drifting in to the face */ +#define CLIMB_TOP (CLIFF_TOP - 1.2f) /* the route's last platform: a hop below the top */ + +/* How far a normal jump comfortably clears for a given rise. */ +static float normal_max_gap(float rise) +{ + return 2.4f - 0.5f * fmaxf(rise, 0.0f); +} + +/* The route's height at each s, for placing the scatter around it. */ +static float s_route_s[ROUTE_MAX], s_route_top[ROUTE_MAX]; +static int s_route_count; + +static float route_height_at(float s) +{ + if (s_route_count == 0 || s <= s_route_s[0]) + return 0.0f; + for (int i = 1; i < s_route_count; i++) { + if (s <= s_route_s[i]) { + float t = (s - s_route_s[i - 1]) / (s_route_s[i] - s_route_s[i - 1]); + return s_route_top[i - 1] + t * (s_route_top[i] - s_route_top[i - 1]); + } + } + return s_route_top[s_route_count - 1]; +} + +static void remember_route_point(float s, float top) +{ + if (s_route_count < ROUTE_MAX) { + s_route_s[s_route_count] = s; + s_route_top[s_route_count] = top; + s_route_count++; + } +} + +/* Has the band run past the north end of the east face? The route stays + * beside the faces, so its last hop is always onto the top. */ +static bool past_the_faces(Box b) +{ + return b.max.z > CLIFF_SOUTH_Z + CLIFF_STRIP_WIDTH * CLIFF_STRIP_COUNT; +} + +/* Does `outer` (a box, or everywhere a moving box goes) hold all of `inner`? */ +static bool contains(Box outer, Box inner) +{ + return outer.min.x <= inner.min.x && outer.min.y <= inner.min.y && outer.min.z <= inner.min.z && + outer.max.x >= inner.max.x && outer.max.y >= inner.max.y && outer.max.z >= inner.max.z; +} + +/* Is the way from `prev` to `next` open? Sweeps the player's box along the + * straight line between their centers, over the height the hop passes + * through, and checks nothing else (a pillar, the cliff, another platform) + * is in the way. A hangable rock in the way would even grab a heightened + * jump out of the air. */ +static bool hop_path_clear(Box prev, Box next) +{ + float low = fminf(prev.max.y, next.max.y); + float high = fmaxf(prev.max.y, next.max.y) + HOP_CLEARANCE; + for (int step = 0; step <= 10; step++) { + float t = (float)step / 10.0f; + float x = prev.min.x + 0.5f * (prev.max.x - prev.min.x) + + t * (0.5f * (next.min.x + next.max.x) - 0.5f * (prev.min.x + prev.max.x)); + float z = prev.min.z + 0.5f * (prev.max.z - prev.min.z) + + t * (0.5f * (next.min.z + next.max.z) - 0.5f * (prev.min.z + prev.max.z)); + Box body = { { x - HOP_HALF_WIDTH, low, z - HOP_HALF_WIDTH }, + { x + HOP_HALF_WIDTH, high, z + HOP_HALF_WIDTH }, false, BOX_STYLE_PLATFORM }; + for (int i = 0; i < s_count; i++) { + Box other = s_reach[i]; + bool is_end = contains(other, prev) || contains(other, next); /* the hop's own platforms */ + if (!is_end && footprints_overlap(body, other) && vertical_gap(body, other) < 0.0f) + return false; + } + } + return true; +} + +/* Is `next` one comfortable hop from `prev`? */ +static bool route_hop_ok(Box prev, Box next, bool second) +{ + float gap = footprint_gap(prev, next); + float rise = next.max.y - prev.max.y; + if (second ? gap > ROUTE_SECOND_MAX_GAP : gap > normal_max_gap(rise)) + return false; + return hop_path_clear(prev, next); +} + +/* The route being walked: where it's got to, and its last platform. */ +typedef struct { + float s, top, out, along; /* position along the band, height, distance out, last platform's length */ + float depth; /* last platform's depth (out from the face) */ + Box last; /* the last platform placed */ + bool last_moving; + float out_min, out_max; /* the strip of the band this route wanders in */ + bool remember; /* record its heights for placing the scatter */ +} RouteWalk; + +/* Tries one random next platform for the route. `easy` asks for a short, + * low hop close to the last platform: the fallback when normal picks keep + * failing (at the corner, or next to a pillar). */ +static bool try_route_step(RouteWalk *w, float second_share, bool easy, float skip) +{ + bool second = w->top > 0.0f && !easy && random_chance(second_share); + float rise = second ? random_range(ROUTE_SECOND_MIN_RISE, ROUTE_SECOND_MAX_RISE) + : easy ? random_range(0.2f, 1.0f) + : random_range(0.9f, ROUTE_NORMAL_MAX_RISE); + rise = fminf(rise, CLIMB_TOP - w->top); + bool last = w->top + rise >= CLIMB_TOP - 0.01f; + float gap = easy ? random_range(0.3f, 0.9f) + : second ? random_range(0.6f, ROUTE_SECOND_MAX_GAP) + : random_range(0.6f, normal_max_gap(rise)); + float along = random_range(ROUTE_MIN_SIZE, ROUTE_MAX_SIZE); + float depth = random_range(ROUTE_MIN_SIZE, ROUTE_MAX_SIZE); + float out, s; + bool pulling_in = CLIMB_TOP - w->top < ROUTE_PULL_IN_HEIGHT; + if (!last && !easy && random_chance(pulling_in ? 0.6f : ROUTE_SIDESTEP_SHARE)) { + /* A switchback: hop out to the next row (or back in) instead of along, + * which climbs without using up the band. Near the top, always in. */ + bool outward = !pulling_in && + (w->out < 1.0f || (w->out + w->depth + gap + depth < w->out_max && random_chance(0.5f))); + out = outward ? w->out + w->depth + gap : w->out - gap - depth; + s = w->s + random_range(-1.0f, 1.0f); + if (out < 0.0f || out > ROUTE_WIDEST_OUT) + return false; + /* Hopping in toward the (hangable) face is a normal jump: a second + * jump keeps heightened_movement on, so an overshoot would grab the + * face instead of landing. */ + if (!outward && second) + return false; + } else { + /* Along the band, wandering in and out; the last platform hugs the face + * so the top is a hop away. */ + out = last ? random_range(0.0f, 0.6f) + : clampf(w->out + random_range(easy ? -1.0f : -2.5f, easy ? 1.0f : 2.5f), w->out_min, w->out_max); + s = w->s + 0.5f * w->along + gap + 0.5f * along + skip; + } + float top = w->top + rise; + Box b = band_box(s, out, along, depth, top - PLATFORM_THICKNESS, top); + + if (past_the_faces(b) || (w->top > 0.0f && !route_hop_ok(w->last, b, second))) + return false; + bool moving; + bool want_moving = !w->last_moving && !last && !easy && random_chance(ROUTE_MOVING_SHARE); + if (!try_add_platform(b, want_moving, band_along(s, out, depth), band_out(s, out, depth), &moving)) + return false; + w->s = s; w->top = top; w->out = out; w->along = along; w->depth = depth; + w->last = b; w->last_moving = moving; + if (w->remember) + remember_route_point(s, top); + return true; +} + +/* The last resort when random picks keep failing: scan nearby spots in order + * (every row out from the face, a range of distances along the band, a few + * rises) and take the first that is a comfortable hop and fits. */ +static bool rescue_route_step(RouteWalk *w) +{ + static const float RISES[] = { 1.4f, 1.0f, 0.6f, 0.3f }; + float size = 0.5f * (ROUTE_MIN_SIZE + ROUTE_MAX_SIZE); + for (int r = 0; r < 4; r++) { + float rise = fminf(RISES[r], CLIMB_TOP - w->top); + bool last = w->top + rise >= CLIMB_TOP - 0.01f; + for (float ds = -3.0f; ds <= 7.0f; ds += 1.0f) { + for (float out = 0.0f; out <= (last ? 0.6f : ROUTE_WIDEST_OUT); out += (last ? 0.3f : 1.0f)) { + float s = w->s + ds, top = w->top + rise; + Box b = band_box(s, out, size, size, top - PLATFORM_THICKNESS, top); + bool moving; + if (past_the_faces(b) || !route_hop_ok(w->last, b, false) || + !try_add_platform(b, false, band_along(s, out, size), band_out(s, out, size), &moving)) + continue; + w->s = s; w->top = top; w->out = out; w->along = size; w->depth = size; + w->last = b; w->last_moving = false; + if (w->remember) + remember_route_point(s, top); + return true; + } + } + } + return false; +} + +/* Walks the band from the ground to one hop below the top, placing one + * platform per hop, wandering between out_min and out_max from the face. + * Steps are mostly normal-jump rises, with second-jump rises mixed in as + * often as the remaining height needs. When a step can't be placed, easier + * hops are tried, then easy hops a little further along, then a scan of + * nearby spots; the route never leaves a gap it can't cross. */ +static void add_climb_route(float out_min, float out_max, bool remember) +{ + RouteWalk w = { 0.0f, 0.0f, out_min, 0.0f, 0.0f, band_box(0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f), false, + out_min, out_max, remember }; + bool widened = false; + if (remember) { + s_route_count = 0; + remember_route_point(0.0f, 0.0f); + } + + while (w.top < CLIMB_TOP - 0.01f) { + /* Mix in more second jumps when there's a lot of height left per meter, + * aiming to arrive well before the east face ends. */ + float needed = (CLIMB_TOP - w.top) / fmaxf(ROUTE_ARRIVE_BY - w.s, 4.0f) * 3.8f; + /* Near the top, drift in toward the face: the last hop is onto the top. */ + if (CLIMB_TOP - w.top < ROUTE_PULL_IN_HEIGHT) { + w.out_min = 0.0f; + w.out_max = fmaxf(0.6f, w.out_max - 2.0f); + w.out = fminf(w.out, w.out_max); + } + float second_share = clampf((needed - 1.2f) / 1.3f, 0.15f, 0.9f); + bool placed = false; + for (int tries = 0; tries < ROUTE_TRIES && !placed; tries++) + placed = try_route_step(&w, second_share, false, 0.0f); + for (int tries = 0; tries < ROUTE_TRIES && !placed; tries++) + placed = try_route_step(&w, second_share, true, 0.0f); + for (float skip = 0.5f; skip <= 3.0f && !placed; skip += 0.5f) + for (int tries = 0; tries < ROUTE_TRIES && !placed; tries++) + placed = try_route_step(&w, second_share, true, skip); + if (!placed) + placed = rescue_route_step(&w); + if (!placed && !widened) { + /* Boxed in (by pillars or the other route): wander wider from here + * on (once; near the top the pull-in narrows it again). */ + widened = true; + w.out_min = 0.0f; + w.out_max = ROUTE_WIDEST_OUT; + continue; + } + if (!placed) + return; /* truly stuck: the course test reports the top as unreachable */ + } +} + +/* ---- 3. The cliff course: pillars and scatter -------------------------- */ + +#define PILLAR_COUNT 7 +#define SCATTER_COUNT 5 +#define SCATTER_MOVING_SHARE 0.8f +#define SCATTER_TRIES 6000 + +/* Tall hangable rock pillars a few meters out from the face: each makes a + * chimney with the cliff for wall jumps, and its top is a place to stand. */ +static void add_rock_pillars(void) +{ + for (int i = 0, tries = 0; i < PILLAR_COUNT && tries < 200; tries++) { + float s = random_range(8.0f, BAND_LENGTH - 8.0f); + float top = CLIFF_TOP * s / BAND_LENGTH + random_range(0.0f, 4.0f); + Box b = band_box(s, random_range(3.5f, 5.0f), random_range(2.0f, 3.5f), + random_range(2.0f, 3.0f), 0.0f, top); + b.allows_wall_hang = true; + b.style = BOX_STYLE_CLIFF; + if (is_clear(b, false)) { + add_box(b, no_motion()); + i++; + } + } +} + +/* Extra platforms at random spots and heights around the route: other ways + * up, shortcuts, and dead ends. */ +static void add_scatter(void) +{ + for (int i = 0, tries = 0; i < SCATTER_COUNT && tries < SCATTER_TRIES; tries++) { + float s = random_range(0.0f, BAND_LENGTH); + float top = clampf(route_height_at(s) + random_range(-3.0f, 2.5f), 0.8f, CLIFF_TOP - 0.5f); + float out = random_range(0.0f, 10.0f); + float depth = random_range(ROUTE_MIN_SIZE, ROUTE_MAX_SIZE); + Box b = band_box(s, out, random_range(ROUTE_MIN_SIZE, ROUTE_MAX_SIZE), depth, + top - PLATFORM_THICKNESS, top); + bool moving; + if (try_add_platform(b, random_chance(SCATTER_MOVING_SHARE), band_along(s, out, depth), + band_out(s, out, depth), &moving)) + i++; + } +} + +/* ---- 3. The cliff course: the crossing --------------------------------- */ + +#define CROSS_START_X -15.0f /* m, the top's north-west corner... */ +#define CROSS_START_Z 60.0f +#define CROSS_END_X -32.0f /* m ...to the far cliff's nearest corner */ +#define CROSS_END_Z 80.0f +#define CROSS_SCATTER 2 +#define CROSS_MOVING_SHARE 0.6f + +/* A square platform centered at (x, z) with the given top. */ +static Box square_platform(float x, float z, float size, float top) +{ + Box b = { { x - 0.5f * size, top - PLATFORM_THICKNESS, z - 0.5f * size }, + { x + 0.5f * size, top, z + 0.5f * size }, false, BOX_STYLE_PLATFORM }; + return b; +} + +/* One guaranteed way across: hop by hop along the crossing line, keeping + * between side_min and side_max of it, until the far cliff is one hop away. + * Like the climb, it falls back to shorter hops rather than leaving a gap. */ +static void add_crossing_route(Vec3 start, Vec3 along, Vec3 side, float side_min, float side_max) +{ + Box prev = square_platform(CROSS_START_X + 2.5f, CROSS_START_Z - 2.5f, 5.0f, CLIFF_TOP); /* the corner of the top */ + float t = 0.0f; + bool prev_moving = false; + + for (int step = 0; step < 20; step++) { + if (footprint_gap(prev, FAR_CLIFF) <= normal_max_gap(FAR_CLIFF.max.y - prev.max.y)) + return; + bool placed = false; + for (int tries = 0; tries < 2 * ROUTE_TRIES && !placed; tries++) { + bool easy = tries >= ROUTE_TRIES; /* second half: short, low hops */ + bool second = !easy && random_chance(0.3f); + float rise = second ? random_range(ROUTE_SECOND_MIN_RISE, 2.6f) + : easy ? random_range(-0.5f, 0.8f) : random_range(-1.0f, 1.2f); + float top = clampf(prev.max.y + rise, CLIFF_TOP, FAR_CLIFF.max.y - 0.5f); + float size = random_range(ROUTE_MIN_SIZE + 0.2f, ROUTE_MAX_SIZE); + float next_t = t + (easy ? random_range(2.5f, 4.0f) : random_range(4.0f, 5.5f)); + Vec3 c = vec3_add(vec3_add(start, vec3_scale(along, next_t)), + vec3_scale(side, random_range(side_min, side_max))); + Box b = square_platform(c.x, c.z, size, top); + if (!route_hop_ok(prev, b, second && top - prev.max.y >= ROUTE_SECOND_MIN_RISE)) + continue; + bool moving; + bool want_moving = !prev_moving && !easy && random_chance(CROSS_MOVING_SHARE); + if (!try_add_platform(b, want_moving, along, side, &moving)) + continue; + t = next_t; prev = b; prev_moving = moving; + placed = true; + } + if (!placed) + return; /* stuck: the course test reports the finish as unreachable */ + } +} + +/* The same idea as the climb on the straight line from the top's corner to + * the far cliff: a guaranteed way across, plus a couple of extras. */ +static void add_crossing(void) +{ + Vec3 start = vec3_make(CROSS_START_X, 0.0f, CROSS_START_Z); + Vec3 line = vec3_sub(vec3_make(CROSS_END_X, 0.0f, CROSS_END_Z), start); + float length = vec3_length(line); + Vec3 along = vec3_scale(line, 1.0f / length); + Vec3 side = vec3_make(-along.z, 0.0f, along.x); + + add_crossing_route(start, along, side, -3.0f, 3.0f); + + /* The scatter: more platforms either side of the line. */ + for (int i = 0, tries = 0; i < CROSS_SCATTER && tries < 300; tries++) { + Vec3 c = vec3_add(vec3_add(start, vec3_scale(along, random_range(2.0f, length))), + vec3_scale(side, random_range(-7.0f, 7.0f))); + Box b = square_platform(c.x, c.z, random_range(ROUTE_MIN_SIZE, ROUTE_MAX_SIZE), random_range(54.5f, 61.0f)); + bool moving; + if (try_add_platform(b, random_chance(CROSS_MOVING_SHARE), along, side, &moving)) + i++; + } +} + +/* ---- Public interface -------------------------------------------------- */ + +int level_build(LevelBox *out, int capacity) +{ + s_out = out; + s_capacity = capacity < LEVEL_MAX_BOXES ? capacity : LEVEL_MAX_BOXES; + s_count = 0; + + add_random_platforms(); + for (int i = 0; i < WALL_COURSE_COUNT; i++) + add_box(WALL_COURSE[i], no_motion()); + + seed_random(CLIFF_COURSE_SEED); + add_triangle_cliff(); + add_box(FAR_CLIFF, no_motion()); + add_river(); + add_rock_pillars(); + add_climb_route(0.0f, ROUTE_WIDEST_OUT, true); + add_scatter(); + add_crossing(); + return s_count; +} + +Vec3 level_motion_offset(BoxMotion m, float time) +{ + float angle = 2.0f * M3D_PI * (time / m.period + m.phase); + switch (m.kind) { + case MOTION_SLIDE: + return vec3_scale(m.a, sinf(angle)); + case MOTION_LOOP: + return vec3_add(vec3_scale(m.a, cosf(angle) - 1.0f), vec3_scale(m.b, sinf(angle))); + default: + return vec3_make(0.0f, 0.0f, 0.0f); + } +} + +Vec3 level_spawn_point(void) +{ + return vec3_make(0.0f, 0.0f, 0.0f); +} diff --git a/platformer/src/level.h b/platformer/src/level.h new file mode 100644 index 0000000..ca706a1 --- /dev/null +++ b/platformer/src/level.h @@ -0,0 +1,82 @@ +/* + * ============================================================ + * FILE: level.h + * + * PURPOSE: Public interface for "what's in the level": the list of boxes + * the test world is made of, and how the moving ones move. + * level.c only DECIDES the content; world.c stores it, moves it + * each tick and answers geometry questions about it. + * + * FITS IN: world.c calls level_build() once from world_init(), and + * level_motion_offset() every tick for each moving box. level.h + * uses the Box type from world.h (types only: level.c never + * calls world.c, so there is no cycle). + * + * INTERFACE: Use these exact names: + * + * typedef enum MotionKind { + * MOTION_NONE, stays put + * MOTION_SLIDE, back and forth: offset = a * sin(angle) + * MOTION_LOOP round a circle through its start: + * offset = a * (cos(angle) - 1) + b * sin(angle) + * } MotionKind; + * typedef struct BoxMotion { + * MotionKind kind; + * Vec3 a, b; the motion's axes, meters (see above; b unused by SLIDE) + * float period; s for one full cycle + * float phase; 0..1, how far into its cycle the box is at time 0 + * } BoxMotion; + * angle = 2 * PI * (time / period + phase). Both kinds pass through + * offset 0 (the box's built position) once or twice every cycle. + * + * typedef struct LevelBox { Box box; BoxMotion motion; } LevelBox; + * box is where the box sits at offset 0. + * + * #define LEVEL_MAX_BOXES 256 + * int level_build(LevelBox *out, int capacity); + * Fills out[] with every box in the level and returns how many. + * The same seeds always build the same level. + * Vec3 level_motion_offset(BoxMotion m, float time); + * How far a moving box is from its built position at `time`. + * Vec3 level_spawn_point(void); + * Where the player starts; the level keeps it clear. + * + * Include "world.h" (for Box). + * + * CONVENTIONS: Include guard: LEVEL_H. + * + * NOT IN SCOPE: Loading levels from files, triggers, anything but boxes. + * + * DONE WHEN: world.c can build and animate the whole level through this. + * ============================================================ + */ +#ifndef LEVEL_H +#define LEVEL_H + +#include "world.h" + +typedef enum MotionKind { + MOTION_NONE, /* stays put */ + MOTION_SLIDE, /* back and forth: offset = a * sin(angle) */ + MOTION_LOOP /* round a circle through its start: offset = a * (cos(angle) - 1) + b * sin(angle) */ +} MotionKind; + +typedef struct BoxMotion { + MotionKind kind; + Vec3 a, b; /* the motion's axes, meters; b is unused by MOTION_SLIDE */ + float period; /* s for one full cycle */ + float phase; /* 0..1, how far into its cycle the box is at time 0 */ +} BoxMotion; + +typedef struct LevelBox { + Box box; /* where it sits at offset 0 */ + BoxMotion motion; +} LevelBox; + +#define LEVEL_MAX_BOXES 256 + +int level_build(LevelBox *out, int capacity); +Vec3 level_motion_offset(BoxMotion m, float time); +Vec3 level_spawn_point(void); + +#endif /* LEVEL_H */ diff --git a/platformer/src/main.c b/platformer/src/main.c index ce02b85..23f06d2 100644 --- a/platformer/src/main.c +++ b/platformer/src/main.c @@ -30,6 +30,8 @@ * window_poll_events(); * * while accumulator >= TICK_DT: // 0, 1 or several ticks + * world_update(TICK_DT); // moving platforms first, + * // so the player rides them * controls_poll(&input); * if input.quit_pressed: window_request_close(); * if input.reset_pressed: @@ -156,6 +158,8 @@ int main(void) window_poll_events(); while (accumulator >= TICK_DT) { + /* Moving platforms move first, so the player rides where they are now. */ + world_update(TICK_DT); controls_poll(&input); if (input.quit_pressed) window_request_close(); diff --git a/platformer/src/physics.c b/platformer/src/physics.c index 423550d..4e842f6 100644 --- a/platformer/src/physics.c +++ b/platformer/src/physics.c @@ -8,26 +8,39 @@ * * FITS IN: Implements physics.h. Called by player.c inside player_update(), * AFTER the player has chosen its velocity for this tick. Uses - * world_floor_below(), world_ceiling_above(), world_find_overlap() - * and world_clamp_to_bounds() from world.h. + * world_floor_below(), world_ceiling_above(), world_find_overlap(), + * world_box_moved() and world_clamp_to_bounds() from world.h. + * main.c moves the moving boxes (world_update) BEFORE this runs. * * IMPLEMENT physics_step(b, dt), in this order: - * 1. Gravity ALWAYS pulls: vel.y -= GRAVITY * dt, clamped to no lower than + * 0. hit_wall = false; steps 2-3 set it again if a side is touched. + * Ride: if on_ground on a box (ground_box >= 0), move by + * world_box_moved(ground_box) first, so a moving platform carries whatever + * stands on it, up, down and sideways. + * Step out: a moving box can move INTO a body that isn't moving. If the + * body overlaps a box now, push it out the shortest way (up onto it, down + * under it, or out a side), a few passes. Still boxes never cause this, + * because the steps below never leave a body inside one. + * 1. Gravity ALWAYS pulls: vel.y -= GRAVITY * gravity_scale * dt (the scale + * is 1 except while the owner drives vertical motion), clamped to no lower than * -TERMINAL_VELOCITY. Standing still, the floor check in step 4 pushes * right back. WHY always: that's what makes walking off a ledge fall on its * own, with no special "is there still floor under me?" case. * 2. Move X: pos.x += vel.x * dt. If the body now overlaps a box * (world_find_overlap), push it back out on the side it came from and * zero vel.x. Repeat a few times in case the push lands in another box. + * Each push records hit_wall = true, the side's outward normal (moving + * +x into a box means its -x side, normal (-1, 0, 0)) and the box, so the + * owner can react to walls (the player's wall hang). * 3. Move Z: the same, for z. Resolving one axis at a time is what makes * running diagonally into a wall SLIDE along it instead of stopping dead. * 4. Move Y: remember prev_y, then pos.y += vel.y * dt (semi-implicit Euler: * velocity was updated first; add a comment on why that's stable for a * fixed timestep). - * Floor: floor = world_floor_below((x, prev_y, z), half_width), the - * highest surface the feet were above at the START of the move. If - * pos.y <= floor: land (pos.y = floor, vel.y = 0 if falling, - * on_ground = true). Using prev_y means a fast fall can never skip + * Floor: floor = world_floor_below((x, prev_y, z), half_width, &box), + * the highest surface the feet were above at the START of the move. + * If pos.y <= floor: land (pos.y = floor, vel.y = 0 if falling, + * on_ground = true, ground_box = box). Otherwise ground_box = -1. Using prev_y means a fast fall can never skip * through a thin platform between two ticks. * Otherwise on_ground = false, and check the ceiling the same way from * the previous head height: if the head crossed a box bottom, stop at @@ -45,7 +58,8 @@ * y = 0 with on_ground = true, and stays there. It lands on * platform tops (even at terminal velocity), can't walk through a * platform's sides, slides along them when running diagonally, - * falls when it walks off an edge, and bonks on undersides. + * falls when it walks off an edge, and bonks on undersides. Pushing + * into a box's side sets hit_wall with that side's normal and box. * ============================================================ */ @@ -56,6 +70,50 @@ #define PUSH_SKIN 1e-3f /* m, extra gap left after a push-out so edges only touch */ #define MAX_PUSH_PASSES 4 /* push-outs per axis per tick (boxes can overlap) */ +/* Step 0: stand on a moving box and it carries you. */ +static void ride_ground_box(Body *b) +{ + if (b->on_ground && b->ground_box >= 0) + b->pos = vec3_add(b->pos, world_box_moved(b->ground_box)); +} + +/* Step 0: a moving box moved into the body. Push the body out along + * whichever of the six directions is shortest: usually up onto a platform + * that rose into the feet, or out of the way of one sliding sideways. */ +static void step_out_of_boxes(Body *b) +{ + for (int pass = 0; pass < MAX_PUSH_PASSES; pass++) { + Box hit; + if (!world_find_overlap(b->pos, b->half_width, b->height, &hit)) + return; + float up = hit.max.y - b->pos.y; + float down = b->pos.y + b->height - hit.min.y; + float east = hit.max.x - (b->pos.x - b->half_width); + float west = b->pos.x + b->half_width - hit.min.x; + float north = hit.max.z - (b->pos.z - b->half_width); + float south = b->pos.z + b->half_width - hit.min.z; + float least = fminf(fminf(up, down), fminf(fminf(east, west), fminf(north, south))); + + if (least == up) { + b->pos.y = hit.max.y; + if (b->vel.y < 0.0f) + b->vel.y = 0.0f; + } else if (least == down) { + b->pos.y = hit.min.y - b->height - PUSH_SKIN; + if (b->vel.y > 0.0f) + b->vel.y = 0.0f; + } else if (least == east) { + b->pos.x += east + PUSH_SKIN; + } else if (least == west) { + b->pos.x -= west + PUSH_SKIN; + } else if (least == north) { + b->pos.z += north + PUSH_SKIN; + } else { + b->pos.z -= south + PUSH_SKIN; + } + } +} + /* Pushes the body out of any box it overlaps along ONE horizontal axis, * back toward where it came from. pos_axis/vel_axis point at the x or z * members of the body, so the same code handles both axes. */ @@ -67,13 +125,22 @@ static void resolve_axis(Body *b, float *pos_axis, float *vel_axis, bool axis_is return; float box_min = axis_is_x ? hit.min.x : hit.min.z; float box_max = axis_is_x ? hit.max.x : hit.max.z; - if (*vel_axis > 0.0f) + float side; /* which way the touched side faces along this axis */ + if (*vel_axis > 0.0f) { *pos_axis = box_min - b->half_width - PUSH_SKIN; /* was moving +: back off to the min side */ - else if (*vel_axis < 0.0f) + side = -1.0f; + } else if (*vel_axis < 0.0f) { *pos_axis = box_max + b->half_width + PUSH_SKIN; /* was moving -: back off to the max side */ - else + side = 1.0f; + } else { return; /* not moving on this axis, so this axis didn't cause it */ + } *vel_axis = 0.0f; + + /* Tell the owner which wall it touched and which way that wall faces. */ + b->hit_wall = true; + b->wall_normal = axis_is_x ? vec3_make(side, 0.0f, 0.0f) : vec3_make(0.0f, 0.0f, side); + b->wall = hit; } } @@ -91,15 +158,18 @@ static void move_vertically(Body *b, float dt) /* The highest surface the feet were above BEFORE moving. Any top between * the old and new height is at or below prev_y, so the fall lands on the * first one it crossed, no matter how fast it was going. */ - float floor_y = world_floor_below(vec3_make(b->pos.x, prev_y, b->pos.z), b->half_width); + int floor_box; + float floor_y = world_floor_below(vec3_make(b->pos.x, prev_y, b->pos.z), b->half_width, &floor_box); if (b->pos.y <= floor_y) { b->pos.y = floor_y; if (b->vel.y < 0.0f) b->vel.y = 0.0f; - b->on_ground = true; + b->on_ground = true; + b->ground_box = floor_box; /* remembered so a moving box can carry us next tick */ return; } - b->on_ground = false; + b->on_ground = false; + b->ground_box = -1; /* Same idea upward: stop the head at the first underside it crossed. */ float ceiling_y = world_ceiling_above(vec3_make(b->pos.x, prev_y + b->height, b->pos.z), @@ -113,8 +183,14 @@ static void move_vertically(Body *b, float dt) void physics_step(Body *b, float dt) { + /* 0. Walls are reported fresh every step. Ride whatever we stand on, and + * step out of anything that moved into us. */ + b->hit_wall = false; + ride_ground_box(b); + step_out_of_boxes(b); + /* 1. Gravity always pulls; the floor pushes back in step 4. */ - b->vel.y -= GRAVITY * dt; + b->vel.y -= GRAVITY * b->gravity_scale * dt; if (b->vel.y < -TERMINAL_VELOCITY) b->vel.y = -TERMINAL_VELOCITY; diff --git a/platformer/src/physics.h b/platformer/src/physics.h index f626c65..9da41ac 100644 --- a/platformer/src/physics.h +++ b/platformer/src/physics.h @@ -20,17 +20,27 @@ * something (the ground or a platform top) * float half_width; collision box half-size in x and z, meters * float height; collision box height above the feet, meters + * float gravity_scale; multiplier on GRAVITY (1 = normal). The owner can + * set 0 to take over vertical motion itself (the + * player does while clinging to a wall). + * bool hit_wall; true if the last step pushed the body out of a box's + * SIDE (not a top or bottom) + * Vec3 wall_normal; that side's outward normal (+-x or +-z, y = 0); + * only meaningful if hit_wall + * Box wall; the box that side belongs to; only meaningful if hit_wall + * int ground_box; index (world_box) of the box the body stands on, or -1 + * for the ground / in the air. Used to ride moving boxes. * } Body; * * void physics_step(Body *b, float dt); * - * Include <stdbool.h> and "math3d.h". + * Include <stdbool.h>, "math3d.h" and "world.h" (for Box). * * CONVENTIONS: Include guard: PHYSICS_H. The collision shape is an axis-aligned * box that does not rotate (a spinning box would snag on walls). * * NOT IN SCOPE: Rigid bodies, rotation, mass, forces/impulses API, collision - * between bodies. + * between bodies, keeping a moving box's momentum after leaving it. * * DONE WHEN: player.c can move, land, and collide using only Body + physics_step. * ============================================================ @@ -41,6 +51,7 @@ #include <stdbool.h> #include "math3d.h" +#include "world.h" typedef struct Body { Vec3 pos; /* position of the body's FEET (bottom center), meters */ @@ -48,6 +59,11 @@ typedef struct Body { bool on_ground; /* true if the body ended the last step standing on something */ float half_width; /* collision box half-size in x and z, meters */ float height; /* collision box height above the feet, meters */ + float gravity_scale; /* multiplier on GRAVITY; 1 = normal, 0 = the owner drives vel.y itself */ + bool hit_wall; /* the last step pushed the body out of a box's side */ + Vec3 wall_normal; /* that side's outward normal (+-x or +-z); only if hit_wall */ + Box wall; /* the box that side belongs to; only if hit_wall */ + int ground_box; /* world_box index stood on (-1 = ground or airborne); for riding moving boxes */ } Body; void physics_step(Body *b, float dt); diff --git a/platformer/src/player.c b/platformer/src/player.c index 7fe0d76..737a4c9 100644 --- a/platformer/src/player.c +++ b/platformer/src/player.c @@ -17,10 +17,13 @@ * facing_yaw = 0, forward_speed = 0, state = PLAYER_IDLE, * heightened_movement = false, heightened_timer = 0, * retreating_movement = false, jump_kind = JUMP_NONE, skid_time = 0, - * skid_speed = 0, skid_yaw = 0. + * skid_speed = 0, skid_yaw = 0, wall_time = 0, wall_jump_yaw = 0, + * has_last_wall = false, body.gravity_scale = 1, body.hit_wall = false, + * body.ground_box = -1. * * - player_update(p, in, camera_yaw, dt). Use one static helper per state - * (update_ground for IDLE + RUN / update_skid / update_jump / update_fall), dispatched by a + * (update_ground for IDLE + RUN / update_skid / update_jump / update_fall / + * update_wall_hang), dispatched by a * `switch (p->state)`. Keep each helper short. Shared steps: * * A. Stick -> world direction (camera-relative). Using camera.h's convention: @@ -77,7 +80,8 @@ * already faces the stick (or where it last pointed), forward_speed = * PLAYER_RETREAT_JUMP_SPEED, body.vel.y = PLAYER_RETREAT_JUMP_VELOCITY * (2x the height, the highest jump); jump_kind = JUMP_RETREAT. - * retreating_movement stays on until it lands. + * retreating_movement AND heightened_movement are on until it + * lands (so it can grab a wall; see F). * - heightened_movement on: the SECOND jump, SM64's double jump. * body.vel.y = PLAYER_SECOND_JUMP_VELOCITY (1.75x the height); * jump_kind = JUMP_SECOND. heightened_movement stays on for the @@ -91,8 +95,10 @@ * can lead into the second jump. Landing any other way (from the * second jump, or after walking off an edge) turns it off. Every * landing turns retreating_movement off and resets jump_kind to - * JUMP_NONE. Every tick, unless the player is in the second jump, the - * heightened timer counts down and it turns off at 0. WHY named + * JUMP_NONE, and clears has_last_wall. The heightened timer counts + * down (turning it off at 0) only while jump_kind == JUMP_NONE and + * not wall hanging: a jump or hang that carries heightened_movement + * keeps it until it ends. WHY named * states rather than private "can double jump" flags: later moves * will key off them too. * @@ -128,10 +134,45 @@ * - If the player is on the ground state-wise but body.on_ground is false * (walked off a platform edge) -> FALL. * - * E. Apply: move_yaw = skid_yaw while in SKID, else facing_yaw. - * body.vel.x = sin(move_yaw) * forward_speed - * body.vel.z = cos(move_yaw) * forward_speed - * then physics_step(&p->body, dt). + * F. Wall hang (WALL_HANG). From JUMP or FALL, enter it when ALL hold: + * heightened_movement is on; the last physics step hit a wall + * (body.hit_wall) whose box allows_wall_hang; that wall's SURFACE isn't + * the one last jumped off (same facing and same face position, so a + * cliff built from side-by-side boxes counts as one wall; cleared on + * landing); and the + * player was moving into it within PLAYER_WALL_HANG_ANGLE_DEG of head-on + * (facing_yaw vs. -wall_normal). On entry: wall_jump_yaw = the approach + * direction MIRRORED off the wall (the part along the wall is kept, the + * part into it flips: 5 degrees in from the left leaves 5 degrees to the + * right); facing_yaw = wall_jump_yaw, so the nose shows exactly where a + * wall jump will launch; forward_speed = 0; vel.y = 0; wall_time = 0. + * While hanging: + * - heightened_movement stays on for the whole hang. + * - Gravity is off (body.gravity_scale = 0) and the player slides down + * at vel.y = -min(PLAYER_WALL_SLIDE_ACCEL * wall_time, + * PLAYER_WALL_SLIDE_MAX_SPEED): a slow slide that builds gently. + * - The body presses into the wall at a tiny speed (WALL_PRESS_SPEED) + * so physics keeps reporting it; no contact means the player slid + * past the wall's bottom or end. + * - A: the wall jump, along wall_jump_yaw. Within + * PLAYER_WALL_JUMP_EARLY_TIME of grabbing it's a second jump + * (PLAYER_SECOND_JUMP_VELOCITY, launched at PLAYER_SECOND_JUMP_MAX_SPEED, + * JUMP_SECOND); later it's a normal jump (PLAYER_JUMP_VELOCITY, + * launched at PLAYER_MAX_SPEED, JUMP_NORMAL). Either way + * heightened_movement stays on for the whole jump (so any wall jump + * can grab the next wall) and this wall's surface is remembered. + * - After PLAYER_WALL_HANG_DURATION, or losing contact: let go. FALL + * at normal gravity with forward_speed = 0, jump_kind = JUMP_NONE and + * heightened_movement off (so no grabbing again before landing). + * - Reaching the floor is a normal landing. + * + * E. Apply: move_yaw = skid_yaw while in SKID, straight into the wall + * (-body.wall_normal) while in WALL_HANG, else facing_yaw; speed = + * WALL_PRESS_SPEED while in WALL_HANG, else forward_speed. + * body.vel.x = sin(move_yaw) * speed + * body.vel.z = cos(move_yaw) * speed + * body.gravity_scale = 0 in WALL_HANG, else 1. + * Then physics_step(&p->body, dt). * * - player_state_name: a switch that returns string literals. * @@ -156,13 +197,19 @@ * and A during that slide launches a 2x-height jump toward the * stick at 4 m/s; landing it opens the second-jump window too. A * full jump at full run builds gently to ~7 m/s, and that extra - * speed eases back to 6 m/s after landing. The player lands cleanly back in IDLE/RUN. + * speed eases back to 6 m/s after landing. With heightened_movement + * on, hitting a violet (hangable) wall near head-on clings for + * 0.5 s, sliding slowly down, and A jumps off it mirrored. The player lands cleanly back in IDLE/RUN. * ============================================================ */ #include "config.h" #include "player.h" +/* How hard a wall-hanging player presses into the wall, m/s. Not a feel + * tunable: just enough for physics to keep reporting the contact each tick. */ +#define WALL_PRESS_SPEED 0.5f + /* What the stick is asking for this tick, in world space. */ typedef struct { float mag; /* 0..1, how far the stick is pushed */ @@ -172,6 +219,7 @@ typedef struct { static void update_ground(Player *p, const Input *in, Wish wish, float dt); static void update_skid(Player *p, const Input *in, Wish wish, float dt); static void update_fall(Player *p, const Input *in, Wish wish, float dt); +static void update_wall_hang(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 @@ -259,7 +307,8 @@ static void start_jump(Player *p) * until it lands. */ static void start_retreat_jump(Player *p) { - p->forward_speed = PLAYER_RETREAT_JUMP_SPEED; + p->forward_speed = PLAYER_RETREAT_JUMP_SPEED; + p->heightened_movement = true; /* a heightened move: it can grab a wall */ leave_ground(p, PLAYER_RETREAT_JUMP_VELOCITY, JUMP_RETREAT); } @@ -277,13 +326,15 @@ static void land(Player *p) } p->retreating_movement = false; p->jump_kind = JUMP_NONE; + p->has_last_wall = false; /* any wall can be grabbed again */ } -/* C2. The window after landing runs out on its own. It doesn't during the - * second jump: heightened_movement lasts as long as that jump does. */ +/* C2. The window after landing runs out on its own. It doesn't during a jump + * or wall hang that carries heightened_movement (second, retreat, early + * wall jump): there it lasts as long as that move does. */ static void count_down_heightened(Player *p, float dt) { - if (!p->heightened_movement || p->jump_kind == JUMP_SECOND) + if (!p->heightened_movement || p->jump_kind != JUMP_NONE || p->state == PLAYER_WALL_HANG) return; p->heightened_timer -= dt; if (p->heightened_timer <= 0.0f) @@ -382,6 +433,126 @@ static void update_skid(Player *p, const Input *in, Wish wish, float dt) } } +/* ---- F. Wall hang ----------------------------------------------------- */ + +/* Where a wall's face lies along its normal: the x of an east- or + * west-facing side, the z of a north- or south-facing one. */ +static float wall_plane(Box wall, Vec3 normal) +{ + if (normal.x > 0.5f) return wall.max.x; + if (normal.x < -0.5f) return wall.min.x; + if (normal.z > 0.5f) return wall.max.z; + return wall.min.z; +} + +/* Is the wall just hit the same SURFACE as the one last jumped off? Same + * facing and same face position: a cliff built from side-by-side boxes is + * still one wall, so zigzagging along it can't climb it forever. */ +static bool same_wall_as_last(const Player *p) +{ + const Body *b = &p->body; + return p->has_last_wall && + vec3_dot(b->wall_normal, p->last_wall_normal) > 0.99f && + fabsf(wall_plane(b->wall, b->wall_normal) - p->last_wall_plane) < 0.01f; +} + +/* F. Can the player grab the wall they just hit? Only in a heightened move, + * only on walls the level marks as hangable, not the wall they just jumped + * off, and only when running into it close to head-on (a glancing hit + * slides along it as usual). */ +static bool wants_wall_hang(const Player *p) +{ + const Body *b = &p->body; + if (!p->heightened_movement || !b->hit_wall || !b->wall.allows_wall_hang || + p->forward_speed <= 0.0f) + return false; + if (same_wall_as_last(p)) + return false; + + float head_on_yaw = atan2f(-b->wall_normal.x, -b->wall_normal.z); /* straight into the wall */ + float off_head_on = fabsf(wrap_angle(p->facing_yaw - head_on_yaw)); + return off_head_on < deg_to_rad(PLAYER_WALL_HANG_ANGLE_DEG); +} + +/* F. Grab the wall. The wall jump's direction is decided now, from how the + * player came in: mirror it off the wall, keeping the part along the wall + * and flipping the part into it. Coming in 5 degrees from the left leaves + * 5 degrees to the right. */ +static void start_wall_hang(Player *p) +{ + Vec3 n = p->body.wall_normal; + Vec3 in = vec3_make(sinf(p->facing_yaw), 0.0f, cosf(p->facing_yaw)); + Vec3 out = vec3_sub(in, vec3_scale(n, 2.0f * vec3_dot(in, n))); + p->wall_jump_yaw = atan2f(out.x, out.z); + + p->facing_yaw = p->wall_jump_yaw; /* face where the wall jump will go */ + p->forward_speed = 0.0f; + p->body.vel.y = 0.0f; /* catch on the wall; the slide builds from here */ + p->wall_time = 0.0f; + p->state = PLAYER_WALL_HANG; + p->heightened_movement = true; /* stays on for the whole hang */ +} + +/* F. The hang is over: drop straight down at normal gravity as a plain fall. + * heightened_movement ends, so the player can't grab on again before landing. */ +static void let_go_of_wall(Player *p) +{ + p->heightened_movement = false; + p->jump_kind = JUMP_NONE; + p->forward_speed = 0.0f; + p->state = PLAYER_FALL; +} + +/* F. Jump off the wall along wall_jump_yaw. Right after grabbing it's the + * high one, a second jump; later it's a normal jump at run speed. Each takes + * on its jump kind's height, top speed in the air and landing rules. Either + * way heightened_movement stays on for the whole jump, so ANY wall jump can + * grab the next wall. */ +static void start_wall_jump(Player *p) +{ + p->has_last_wall = true; + p->last_wall_normal = p->body.wall_normal; + p->last_wall_plane = wall_plane(p->body.wall, p->body.wall_normal); + p->facing_yaw = p->wall_jump_yaw; + p->heightened_movement = true; + + if (p->wall_time < PLAYER_WALL_JUMP_EARLY_TIME) { + p->forward_speed = PLAYER_SECOND_JUMP_MAX_SPEED; + leave_ground(p, PLAYER_SECOND_JUMP_VELOCITY, JUMP_SECOND); + } else { + p->forward_speed = PLAYER_MAX_SPEED; + leave_ground(p, PLAYER_JUMP_VELOCITY, JUMP_NORMAL); + } +} + +/* F. WALL_HANG: cling for a moment, sliding slowly down, and jump off. */ +static void update_wall_hang(Player *p, const Input *in, Wish wish, float dt) +{ + /* Slid all the way down to a floor: that's an ordinary landing. */ + if (p->body.on_ground) { + p->state = PLAYER_FALL; + update_fall(p, in, wish, dt); + return; + } + + if (in->jump_pressed) { + start_wall_jump(p); + return; + } + + /* Time's up, or we slid past the wall's bottom or end: let go. */ + p->wall_time += dt; + if (p->wall_time >= PLAYER_WALL_HANG_DURATION || !p->body.hit_wall || + !p->body.wall.allows_wall_hang) { + let_go_of_wall(p); + return; + } + + /* Gravity is off while hanging (see E); slide down slowly instead, building + * gently up to a capped speed. */ + p->body.vel.y = -fminf(PLAYER_WALL_SLIDE_ACCEL * p->wall_time, PLAYER_WALL_SLIDE_MAX_SPEED); +} + /* 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) @@ -424,12 +595,21 @@ static void update_fall(Player *p, const Input *in, Wish wish, float dt) update_ground(p, in, wish, dt); return; } + if (wants_wall_hang(p)) { + start_wall_hang(p); + 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) { + if (wants_wall_hang(p)) { + start_wall_hang(p); + return; + } + /* Past the apex (or landed already): it's a fall now. */ if (p->body.vel.y <= 0.0f) { p->state = PLAYER_FALL; @@ -466,6 +646,16 @@ void player_init(Player *p, Vec3 spawn) p->skid_time = 0.0f; p->skid_speed = 0.0f; p->skid_yaw = 0.0f; + p->wall_time = 0.0f; + p->wall_jump_yaw = 0.0f; + p->has_last_wall = false; + p->last_wall_normal = vec3_make(0.0f, 0.0f, 0.0f); + p->last_wall_plane = 0.0f; + p->body.gravity_scale = 1.0f; + p->body.ground_box = -1; + p->body.hit_wall = false; + p->body.wall_normal = vec3_make(0.0f, 0.0f, 0.0f); + p->body.wall = (Box){ { 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f }, false, BOX_STYLE_PLATFORM }; } void player_reset(Player *p, Vec3 spawn) @@ -483,16 +673,28 @@ void player_update(Player *p, const Input *in, float camera_yaw, float dt) case PLAYER_IDLE: case PLAYER_RUN: update_ground(p, in, wish, dt); break; case PLAYER_SKID: update_skid(p, in, wish, dt); break; + case PLAYER_WALL_HANG: update_wall_hang(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 into a velocity, then let physics move us. The player - * moves where they face, except in a skid: they've already turned to - * the stick but keep sliding the way they were running. */ - float move_yaw = p->state == PLAYER_SKID ? p->skid_yaw : p->facing_yaw; - p->body.vel.x = sinf(move_yaw) * p->forward_speed; - p->body.vel.z = cosf(move_yaw) * p->forward_speed; + * moves where they face, except in a skid (they've already turned to + * the stick but keep sliding the way they were running) and a wall hang + * (they face where the wall jump will go, but press gently straight + * into the wall so physics keeps reporting it; physics has just + * reported that wall, so wall_normal is current). The hang drives its + * own slide, so gravity is switched off for it. */ + bool hanging = p->state == PLAYER_WALL_HANG; + float move_yaw = p->facing_yaw; + if (p->state == PLAYER_SKID) + move_yaw = p->skid_yaw; + else if (hanging) + move_yaw = atan2f(-p->body.wall_normal.x, -p->body.wall_normal.z); + float move_speed = hanging ? WALL_PRESS_SPEED : p->forward_speed; + p->body.vel.x = sinf(move_yaw) * move_speed; + p->body.vel.z = cosf(move_yaw) * move_speed; + p->body.gravity_scale = hanging ? 0.0f : 1.0f; physics_step(&p->body, dt); } @@ -504,6 +706,7 @@ const char *player_state_name(PlayerState s) case PLAYER_JUMP: return "JUMP"; case PLAYER_FALL: return "FALL"; case PLAYER_SKID: return "SKID"; + case PLAYER_WALL_HANG: return "WALL_HANG"; } return "?"; } diff --git a/platformer/src/player.h b/platformer/src/player.h index 4d8fdc6..e6fd033 100644 --- a/platformer/src/player.h +++ b/platformer/src/player.h @@ -16,8 +16,9 @@ * 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) - * PLAYER_SKID on ground, braking after pulling the stick back at + * PLAYER_SKID, on ground, braking after pulling the stick back at * full run; retreating_movement is on + * PLAYER_WALL_HANG in air, clinging to a hangable wall and sliding down * } PlayerState; * * typedef enum JumpKind { which jump the player is in the air from @@ -35,9 +36,10 @@ * float forward_speed; ground speed along facing_yaw, m/s (>= 0) * PlayerState state; * bool heightened_movement; on for PLAYER_SECOND_JUMP_WINDOW s after - * landing a normal or retreat jump, and for the whole - * second jump. While on, A gives the second - * jump. Later moves will read it too. + * landing a normal or retreat jump, and for the + * whole second jump, retreat jump, wall hang + * and every wall jump. On the ground, A gives the second + * jump; in the air, it lets the player wall hang. * float heightened_timer; s left before heightened_movement ends * (not counted down during the second jump) * bool retreating_movement; on for the whole skid (PLAYER_SKID) and @@ -49,6 +51,15 @@ * float skid_speed; forward_speed when the skid began * float skid_yaw; direction the skid slides (the old run * direction; the player already faces the stick) + * float wall_time; s since the current wall hang began + * float wall_jump_yaw; where a wall jump from this hang launches: the + * approach direction mirrored off the wall + * bool has_last_wall; a wall was jumped off since the last landing + * Vec3 last_wall_normal; that wall's surface: which way it faces... + * float last_wall_plane; ...and where its face lies along that + * direction. That surface can't be hung on + * again until the player lands (no climbing + * one wall, even one built from several boxes) * } Player; * * void player_init(Player *p, Vec3 spawn); @@ -61,8 +72,8 @@ * * CONVENTIONS: Include guard: PLAYER_H. * - * NOT IN SCOPE: Health, animation, extra moves beyond the second jump and the - * skid's retreat jump (see the README roadmap). + * NOT IN SCOPE: Health, animation, extra moves beyond the second jump, the + * skid's retreat jump and the wall hang (see the README roadmap). * * DONE WHEN: main.c and render.c compile against this header alone. * ============================================================ @@ -77,13 +88,15 @@ /* SM64-style "actions". Add states here only when a new move needs one; * see the README roadmap (triple jump, long jump, wall kick, ...). The second * and retreat jumps didn't need one: they're a JUMP with a different launch - * (see JumpKind). The skid did, because it follows its own ground rules. */ + * (see JumpKind). The skid and wall hang did, because each follows its own + * movement rules. */ 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) */ - PLAYER_SKID /* on ground, braking after pulling back at full run */ + PLAYER_SKID, /* on ground, braking after pulling back at full run */ + PLAYER_WALL_HANG /* in air, clinging to a hangable wall and sliding down */ } PlayerState; /* Which jump the player is in the air from. It decides the top speed in the @@ -107,6 +120,11 @@ typedef struct Player { float skid_time; /* s since the current skid began */ float skid_speed; /* forward_speed when the skid began */ float skid_yaw; /* direction the skid slides; facing_yaw already points at the stick */ + float wall_time; /* s since the current wall hang began */ + float wall_jump_yaw; /* a wall jump's launch direction: the approach mirrored off the wall */ + bool has_last_wall; /* a wall was jumped off since the last landing... */ + Vec3 last_wall_normal; /* ...facing this way... */ + float last_wall_plane; /* ...with its face here along that direction; no regrab until landing */ } Player; void player_init(Player *p, Vec3 spawn); diff --git a/platformer/src/render.c b/platformer/src/render.c index 127806b..782c653 100644 --- a/platformer/src/render.c +++ b/platformer/src/render.c @@ -43,7 +43,11 @@ * 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 + * 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. @@ -53,7 +57,7 @@ * 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 + * 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(body.pos) * rotate_y(facing_yaw) @@ -124,6 +128,10 @@ 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_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 }; @@ -402,10 +410,25 @@ static void draw_platform(Mat4 vp, Box box, const float rgb[3]) } } +/* 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++) - draw_platform(vp, world_box(i), PLATFORM_PALETTE[i % PLATFORM_PALETTE_SIZE]); + 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 @@ -415,7 +438,7 @@ static void draw_platforms(Mat4 vp) 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 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))); diff --git a/platformer/src/world.c b/platformer/src/world.c index fb7a840..7bbde8e 100644 --- a/platformer/src/world.c +++ b/platformer/src/world.c @@ -2,149 +2,94 @@ * ============================================================ * FILE: world.c * - * PURPOSE: The test world: a flat square of ground with a scatter of box - * platforms to run around and jump on. It's still a test space, - * like the one SM64's team tuned Mario in, just with things to - * jump onto now. + * PURPOSE: Where the level lives while the game runs: it stores the boxes + * level.c builds, moves the moving ones every tick, and answers + * geometry questions about them (floors, ceilings, overlaps). * - * FITS IN: Implements world.h. Has no dependencies besides config.h and - * math3d.h. physics.c is its main caller; render.c draws its boxes. + * FITS IN: Implements world.h. Calls level_build() once and + * level_motion_offset() every tick (level.h). physics.c is its + * main caller; render.c draws its boxes; main.c calls + * world_update() once per tick. * * IMPLEMENT: - * - Level data: a static array of WORLD_PLATFORM_COUNT boxes, filled by - * world_init(). - * - * - world_init(): generate the platforms with a tiny xorshift32 random - * generator seeded from WORLD_SEED. WHY our own instead of rand(): rand() - * differs between C libraries, so the "same" seed could give a different - * level on another machine. Two kinds of platform (ranges are named - * constants at the top of this file): - * block stands on the ground (bottom 0), top low enough to jump onto - * from the ground (a full jump lifts the feet ~2.3 m) - * floating a thin slab higher up, reached by jumping from a block - * Each gets a random footprint and a random spot within WORLD_PLATFORM_AREA - * of spawn (x and z). Re-roll the spot if the footprint comes within - * SPAWN_CLEAR_RADIUS of spawn, so the player never starts inside a platform. - * Platforms may overlap each other; that's fine for both collision and - * drawing. + * - Storage: the built LevelBox list (each box at offset 0 plus its motion), + * the boxes where they are NOW, and how far each moved last tick. + * - world_init(): level_build(), then place every box at its time-0 spot. + * - world_update(dt): advance the clock; move each moving box to its built + * position + level_motion_offset(motion, time), remembering how far it + * moved (world_box_moved) so physics can carry whatever stands on it. * * - Queries, all over the body's FOOTPRINT (a square of +-half_width, the * same shape as the player's box), with edges that only touch NOT counting: * world_floor_below: the highest top <= feet.y + SURFACE_EPSILON among * boxes whose footprint overlaps, or 0 (the ground). The epsilon lets - * a body standing exactly on a top still find it. + * a body standing exactly on a top still find it. Also reports WHICH + * box that is (-1 for the ground), for riding moving platforms. * world_ceiling_above: the lowest bottom >= head.y - SURFACE_EPSILON, or * WORLD_NO_CEILING. * world_find_overlap: the first box that overlaps the body's full volume * (footprint AND height range). - * - world_clamp_to_bounds, world_spawn_point, world_half_extent: as before. + * - world_clamp_to_bounds, world_spawn_point (level_spawn_point()), + * world_half_extent. * * CONVENTIONS: Y up. Boxes are axis-aligned. The ground surface is y = 0. * - * NOT IN SCOPE: Level files, guaranteeing every platform is reachable, slopes, - * moving platforms. + * NOT IN SCOPE: Deciding what's in the level (level.c), rotating boxes, + * spatial partitioning (a few hundred boxes is fine to loop over). * - * DONE WHEN: It compiles warning-free, the same seed always builds the same - * level, spawn is clear, and the player can't leave the square. + * DONE WHEN: physics.c and render.c see every box where it is this tick, and + * moving boxes report how far they moved. * ============================================================ */ -#include <stdint.h> - #include "config.h" +#include "level.h" #include "world.h" -/* Platform generation ranges (level design, not movement feel). */ -#define PLATFORM_MIN_SIZE 2.0f /* m, shortest footprint side */ -#define PLATFORM_MAX_SIZE 6.0f /* m, longest footprint side */ -#define BLOCK_MIN_TOP 0.6f /* m, lowest ground block */ -#define BLOCK_MAX_TOP 2.0f /* m, highest ground block (full jump reaches ~2.3) */ -#define FLOATING_MIN_TOP 2.6f /* m, lowest floating slab top */ -#define FLOATING_MAX_TOP 4.2f /* m, highest floating slab top (reachable from a block) */ -#define FLOATING_THICKNESS 0.5f /* m, floating slab thickness */ -#define FLOATING_CHANCE 0.35f /* fraction of platforms that float */ -#define SPAWN_CLEAR_RADIUS 4.0f /* m around spawn kept free of platforms */ -#define MAX_PLACEMENT_TRIES 50 /* re-rolls before giving up on a platform */ - #define SURFACE_EPSILON 0.01f /* m, "standing exactly on it" tolerance */ #define OVERLAP_EPSILON 1e-4f /* m, edges closer than this only touch */ -static Box s_boxes[WORLD_PLATFORM_COUNT]; +static LevelBox s_level[LEVEL_MAX_BOXES]; /* as built: each box at offset 0, and how it moves */ +static Box s_boxes[LEVEL_MAX_BOXES]; /* where each box is now */ +static Vec3 s_moved[LEVEL_MAX_BOXES]; /* how far each box moved in the last world_update */ static int s_box_count; -static uint32_t s_rng_state; - -/* ---- Random numbers ---------------------------------------------------- */ - -/* xorshift32: three shifts and XORs give a decent, fully repeatable sequence. */ -static uint32_t next_random(void) -{ - s_rng_state ^= s_rng_state << 13; - s_rng_state ^= s_rng_state >> 17; - s_rng_state ^= s_rng_state << 5; - return s_rng_state; -} +static float s_time; /* s since world_init */ -/* A float in [lo, hi]. */ -static float random_range(float lo, float hi) +/* Where box i is at the current time. */ +static Box box_now(int i) { - return lo + (hi - lo) * ((float)next_random() / 4294967295.0f); -} - -/* ---- Level generation -------------------------------------------------- */ - -/* True if the footprint comes within SPAWN_CLEAR_RADIUS of spawn. Uses the - * closest point of the footprint to spawn, so big platforms can't sneak in. */ -static bool too_close_to_spawn(Box b) -{ - Vec3 spawn = world_spawn_point(); - float dx = clampf(spawn.x, b.min.x, b.max.x) - spawn.x; - float dz = clampf(spawn.z, b.min.z, b.max.z) - spawn.z; - return dx * dx + dz * dz < SPAWN_CLEAR_RADIUS * SPAWN_CLEAR_RADIUS; + Vec3 offset = level_motion_offset(s_level[i].motion, s_time); + Box b = s_level[i].box; + b.min = vec3_add(b.min, offset); + b.max = vec3_add(b.max, offset); + return b; } -/* One platform with a random size and height (but no position yet). */ -static Box random_platform_shape(void) +void world_init(void) { - float half_x = 0.5f * random_range(PLATFORM_MIN_SIZE, PLATFORM_MAX_SIZE); - float half_z = 0.5f * random_range(PLATFORM_MIN_SIZE, PLATFORM_MAX_SIZE); - float bottom, top; - if (random_range(0.0f, 1.0f) < FLOATING_CHANCE) { - top = random_range(FLOATING_MIN_TOP, FLOATING_MAX_TOP); - bottom = top - FLOATING_THICKNESS; - } else { - top = random_range(BLOCK_MIN_TOP, BLOCK_MAX_TOP); - bottom = 0.0f; + s_box_count = level_build(s_level, LEVEL_MAX_BOXES); + s_time = 0.0f; + for (int i = 0; i < s_box_count; i++) { + s_boxes[i] = box_now(i); + s_moved[i] = vec3_make(0.0f, 0.0f, 0.0f); } - Box b = { { -half_x, bottom, -half_z }, { half_x, top, half_z } }; - return b; } -/* Moves a box so its footprint is centered on (x, z). */ -static Box place_box(Box b, float x, float z) +void world_update(float dt) { - Vec3 offset = vec3_make(x, 0.0f, z); - b.min = vec3_add(b.min, offset); - b.max = vec3_add(b.max, offset); - return b; + s_time += dt; + for (int i = 0; i < s_box_count; i++) { + if (s_level[i].motion.kind == MOTION_NONE) + continue; /* s_moved stays 0 */ + Box now = box_now(i); + s_moved[i] = vec3_sub(now.min, s_boxes[i].min); + s_boxes[i] = now; + } } -void world_init(void) +Vec3 world_box_moved(int i) { - s_rng_state = WORLD_SEED ? WORLD_SEED : 1u; /* xorshift must not start at 0 */ - s_box_count = 0; - - for (int i = 0; i < WORLD_PLATFORM_COUNT; i++) { - Box shape = random_platform_shape(); - for (int tries = 0; tries < MAX_PLACEMENT_TRIES; tries++) { - Box placed = place_box(shape, - random_range(-WORLD_PLATFORM_AREA, WORLD_PLATFORM_AREA), - random_range(-WORLD_PLATFORM_AREA, WORLD_PLATFORM_AREA)); - if (!too_close_to_spawn(placed)) { - s_boxes[s_box_count++] = placed; - break; - } - } - } + return s_moved[i]; } int world_box_count(void) @@ -169,15 +114,20 @@ static bool footprint_overlaps(Box b, float x, float z, float half_width) z - half_width < b.max.z - OVERLAP_EPSILON; } -float world_floor_below(Vec3 feet, float half_width) +float world_floor_below(Vec3 feet, float half_width, int *box) { float floor_y = 0.0f; /* the ground */ + int floor_box = -1; for (int i = 0; i < s_box_count; i++) { Box b = s_boxes[i]; if (footprint_overlaps(b, feet.x, feet.z, half_width) && - b.max.y <= feet.y + SURFACE_EPSILON && b.max.y > floor_y) - floor_y = b.max.y; + b.max.y <= feet.y + SURFACE_EPSILON && b.max.y > floor_y) { + floor_y = b.max.y; + floor_box = i; + } } + if (box) + *box = floor_box; return floor_y; } @@ -217,7 +167,7 @@ Vec3 world_clamp_to_bounds(Vec3 p) Vec3 world_spawn_point(void) { - return vec3_make(0.0f, 0.0f, 0.0f); + return level_spawn_point(); } float world_half_extent(void) diff --git a/platformer/src/world.h b/platformer/src/world.h index 9da16c1..6cd1ce0 100644 --- a/platformer/src/world.h +++ b/platformer/src/world.h @@ -2,34 +2,52 @@ * ============================================================ * FILE: world.h * - * PURPOSE: Public interface for "the level": a flat square of ground with - * a scatter of box-shaped platforms on it. This API is how other - * modules ask questions about the level's geometry. + * PURPOSE: Public interface for "the level" while the game runs: a flat + * square of ground with box-shaped platforms and terrain on it + * (some of them moving). This API is how other modules ask + * questions about the level's geometry. + * What's IN the level is decided by level.c (level.h). * * FITS IN: physics.c asks what's under the feet, what's above the head, * and what box a body overlaps. render.c asks for the extent and * the boxes so it can draw them, and for the floor under the - * player for the shadow. main.c asks for the spawn point. + * player for the shadow. main.c asks for the spawn point and calls + * world_update() once per tick to move the moving boxes. * * INTERFACE: Use these exact names: * + * typedef enum BoxStyle { how render.c colors a box (nothing else reads it) + * BOX_STYLE_PLATFORM, the default: a color from the platform palette + * BOX_STYLE_CLIFF, rock: big terrain masses like the cliffs + * BOX_STYLE_WATER the river (still solid underfoot) + * } BoxStyle; + * * typedef struct Box { - * Vec3 min, max; axis-aligned corners, meters (min.y = bottom, max.y = top) + * Vec3 min, max; axis-aligned corners, meters (min.y = bottom, max.y = top) + * bool allows_wall_hang; its sides can be wall-hung (see player.c). FALSE + * by default: only boxes a level marks count. + * BoxStyle style; how it's drawn; BOX_STYLE_PLATFORM (0) by default * } Box; * * void world_init(void); - * Builds the level. Platforms are placed "randomly" from - * WORLD_SEED, so the same seed always gives the same layout. + * Builds the level (level_build() in level.c). + * void world_update(float dt); + * Once per tick, BEFORE the player moves: moves every moving box + * along its loop. + * Vec3 world_box_moved(int i); + * How far box i moved in the last world_update (0 for still ones). + * physics.c uses it to carry a body standing on a moving box. * int world_box_count(void); - * Box world_box(int i); 0 <= i < world_box_count() + * Box world_box(int i); 0 <= i < world_box_count(); where it is now * * A "footprint" below is the square [x +- half_width] x [z +- half_width] * around a body's center. Touching edges don't count as overlapping. * - * float world_floor_below(Vec3 feet, float half_width); + * float world_floor_below(Vec3 feet, float half_width, int *box); * The highest surface under the footprint whose top is at or just * below feet.y (a box top, or the ground at 0). This is what the - * feet land on, and where the shadow goes. + * feet land on, and where the shadow goes. If box isn't NULL, *box + * = that box's index, or -1 for the ground. * float world_ceiling_above(Vec3 head, float half_width); * The lowest box bottom over the footprint that is at or just above * head.y, or WORLD_NO_CEILING if there's none. @@ -40,8 +58,8 @@ * Returns p with x and z clamped to [-WORLD_HALF_EXTENT, * +WORLD_HALF_EXTENT]. y is untouched. * Vec3 world_spawn_point(void); - * Where the player starts / resets to: (0, 0, 0). The area around - * it is kept clear of platforms. + * Where the player starts / resets to (level_spawn_point()). The + * area around it is kept clear of platforms. * float world_half_extent(void); * Returns WORLD_HALF_EXTENT (so render.c doesn't need config * knowledge of the world's shape). @@ -52,7 +70,7 @@ * * CONVENTIONS: Include guard: WORLD_H. * - * NOT IN SCOPE: Level files, slopes, moving platforms, non-box shapes. + * NOT IN SCOPE: Level files, slopes, rotating boxes, non-box shapes. * * DONE WHEN: physics.c and render.c can be written using only this header. * ============================================================ @@ -66,14 +84,25 @@ #define WORLD_NO_CEILING 1e9f /* returned when nothing is overhead */ +/* How render.c colors a box. Purely visual: collision ignores it. */ +typedef enum BoxStyle { + BOX_STYLE_PLATFORM, /* the default: a color from the platform palette */ + BOX_STYLE_CLIFF, /* rock: big terrain masses like the cliffs */ + BOX_STYLE_WATER /* the river (still solid underfoot; there's no swimming) */ +} BoxStyle; + typedef struct Box { - Vec3 min, max; /* axis-aligned corners, meters (min.y = bottom, max.y = top) */ + Vec3 min, max; /* axis-aligned corners, meters (min.y = bottom, max.y = top) */ + bool allows_wall_hang; /* its sides can be wall-hung; false unless the level marks it */ + BoxStyle style; /* how it's drawn; BOX_STYLE_PLATFORM unless the level says otherwise */ } Box; void world_init(void); +void world_update(float dt); +Vec3 world_box_moved(int i); int world_box_count(void); Box world_box(int i); -float world_floor_below(Vec3 feet, float half_width); +float world_floor_below(Vec3 feet, float half_width, int *box); float world_ceiling_above(Vec3 head, float half_width); bool world_find_overlap(Vec3 feet, float half_width, float height, Box *hit); Vec3 world_clamp_to_bounds(Vec3 p); |
