#+title: Physics System #+author: Downstroke Contributors * Overview With the default =engine-update:= hook (=default-engine-update= from =downstroke-engine=), the physics pipeline runs **automatically** every frame *before* your =update:= hook. Input is processed first, then =engine-update= integrates motion and collisions, then =update:= runs so your game logic sees resolved positions and =#:on-ground?=. Set =engine-update: #f= on =make-game= to disable the built-in pass, or pass a custom =(lambda (game dt) ...)= to drive your own order — useful for shmups, menus, or experiments. All physics functions are **functional and immutable**: per-entity steps take an entity (plist) plus the current scene and frame =dt=, and return a NEW plist. Bulk steps take the entity list only. No in-place mutation of entities. Tile collision reads solid flags from the tilemap embedded in the scene (=scene-tilemap=). ** Key Physics Functions - =step-tweens= — advance =#:tween= (see =docs/tweens.org=) - =apply-acceleration= — consume one-shot #:ay into velocity - =apply-gravity= — add gravity to falling entities - =apply-velocity-x=, =apply-velocity-y= — move entity by velocity - =resolve-tile-collisions-x=, =resolve-tile-collisions-y= — snap entity off tiles on collision - =detect-on-solid= — set =#:on-ground?= from tiles below feet and/or solid entities in the scene list - =resolve-entity-collisions= — all-pairs AABB push-apart for solid entities (=entities= only) - =sync-groups= — group follow origins (=entities= only) - =aabb-overlap?= — pure boolean collision test (for queries, not resolution) Jumping is **game logic**: set =#:ay= in =update:= (e.g. =(- *jump-force*)=) when the player jumps; there is no =apply-jump=. * Physics Pipeline The canonical order inside =default-engine-update= (and the recommended order when composing steps yourself) is: #+begin_src Frame loop (see =docs/api.org= =game-run!=): input ↓ engine-update (=default-engine-update= by default) ↓ update (your game logic: set #:vx, #:vy, #:ay, …) ↓ camera follow → render Inside =default-engine-update= (per entity, then bulk): step-tweens (advance #:tween) ↓ apply-acceleration (consume #:ay into #:vy) ↓ apply-gravity (add gravity constant to #:vy) ↓ apply-velocity-x (add #:vx to #:x) ↓ resolve-tile-collisions-x (snap off horizontal tiles, zero #:vx) ↓ apply-velocity-y (add #:vy to #:y) ↓ resolve-tile-collisions-y (snap off vertical tiles, zero #:vy) ↓ detect-on-solid (tiles and/or scene entities underfoot → #:on-ground?) ↓ resolve-entity-collisions (whole entity list) ↓ sync-groups (whole entity list) #+end_src Per-entity steps use signature =(entity scene dt)=. Bulk steps =(resolve-entity-collisions entities)= and =(sync-groups entities)= apply to the full list; use =scene-transform-entities=. **Not all steps apply to every entity** (=#:skip-pipelines=, guards like =#:gravity?=, missing tilemap). See the examples section for patterns: - **Platformer**: default =engine-update=; =update:= sets =#:vx= and =#:ay= for jumps - **Top-down**: same auto pipeline; entities without =#:gravity?= skip gravity/acceleration/ground - **Physics Sandbox**: default or custom =scene-map-entities= with the same step order - **Custom / shmup**: =engine-update: #f= and move entities in =update:= * Skipping steps (~#:skip-pipelines~) An entity may include ~#:skip-pipelines=, a list of **symbols** naming steps to **omit** for that entity only. Absent or empty means no steps are skipped. | Symbol | Skipped call | |--------+----------------| | ~acceleration~ | ~apply-acceleration~ | | ~gravity~ | ~apply-gravity~ | | ~velocity-x~ | ~apply-velocity-x~ | | ~velocity-y~ | ~apply-velocity-y~ | | ~tile-collisions-x~ | ~resolve-tile-collisions-x~ | | ~tile-collisions-y~ | ~resolve-tile-collisions-y~ | | ~on-solid~ | ~detect-on-solid~ | | ~entity-collisions~ | participation in ~resolve-entity-collisions~ / ~resolve-pair~ | | ~tweens~ | ~step-tweens~ (see ~downstroke-tween~) | **Entity–entity collisions:** if *either* entity in a pair lists ~entity-collisions~ in ~#:skip-pipelines=, that pair is not resolved (no push-apart). Use this for “ghost” actors or scripted motion that should not participate in mutual solid resolution. **Legacy ~apply-velocity~:** skips each axis independently if ~velocity-x~ or ~velocity-y~ is listed. Helper: ~(entity-skips-pipeline? entity step-symbol)~ (from ~downstroke-entity~) returns ~#t~ if ~step-symbol~ is in the entity’s skip list. ** ~define-pipeline~ (~downstroke-entity~) Physics steps are defined with ~(define-pipeline (procedure-name skip-symbol) (entity scene dt) body ...)~ from the entity module, optionally with ~guard: expr~ before ~body ...~: when the guard is false, the entity is returned unchanged before the body runs. The first formal must be the entity; ~scene~ and ~dt~ are standard for pipeline uniformity. The procedure name and skip symbol are separate (e.g. ~detect-on-solid~ vs ~on-solid~). ~apply-velocity~ is still written by hand because it consults ~velocity-x~ and ~velocity-y~ independently. The renderer and other subsystems do **not** use ~#:skip-pipelines~ today; they run after your ~update:~ hook. If you add render-phase or animation-phase skips later, reuse the same plist key and helpers from ~downstroke-entity~ and document the new symbols alongside physics. Use cases: - **Tweens / knockback:** skip ~acceleration~, ~gravity~, ~velocity-x~, ~velocity-y~ (and often ~tweens~ is *not* skipped so ~step-tweens~ still runs) while a tween drives ~#:x~ / ~#:y~, but keep tile resolution so the body does not rest inside walls. - **Top-down:** entities without ~#:gravity?~ skip gravity, acceleration, and ground detection automatically; you usually do not need ~#:skip-pipelines= unless some entities differ from others. * Pipeline Steps ** apply-acceleration #+begin_src scheme (apply-acceleration entity scene dt) #+end_src **Reads**: =#:ay= (default 0), =#:vy= (default 0), =#:gravity?= to decide whether to consume **Writes**: =#:vy= (adds #:ay to it), =#:ay= (reset to 0) **Description**: Consumes the one-shot acceleration into velocity. Used for jumps (set =#:ay= in =update:=) and other instant bursts. Only works if =#:gravity?= is true (gravity-enabled entities). =scene= and =dt= are unused but required for the pipeline signature. ** apply-gravity #+begin_src scheme (apply-gravity entity scene dt) #+end_src **Reads**: =#:gravity?= (boolean), =#:vy= (default 0) **Writes**: =#:vy= (adds 1 pixel/frame²) **Description**: Applies a constant gravitational acceleration. The gravity constant is =*gravity* = 1= pixel per frame per frame. Only applies if =#:gravity?= is true. Safe to call every frame. ** apply-velocity-x #+begin_src scheme (apply-velocity-x entity scene dt) #+end_src **Reads**: =#:vx= (default 0), =#:x= (default 0) **Writes**: =#:x= (adds #:vx to it) **Description**: Moves the entity horizontally by its velocity. Call once per frame, before =resolve-tile-collisions-x=. ** apply-velocity-y #+begin_src scheme (apply-velocity-y entity scene dt) #+end_src **Reads**: =#:vy= (default 0), =#:y= (default 0) **Writes**: =#:y= (adds #:vy to it) **Description**: Moves the entity vertically by its velocity. Call once per frame, before =resolve-tile-collisions-y=. ** resolve-tile-collisions-x #+begin_src scheme (resolve-tile-collisions-x entity scene dt) #+end_src **Reads**: =#:x=, =#:y=, =#:width=, =#:height=, =#:vx= **Writes**: =#:x= (snapped to tile edge), =#:vx= (zeroed if collision occurs) **Description**: Detects all solid tiles overlapping the entity's AABB and snaps the entity to the nearest tile edge on the X-axis. If a collision is found: - **Moving right** (vx > 0): entity's right edge is snapped to the left edge of the tile (position = tile-x - width) - **Moving left** (vx < 0): entity's left edge is snapped to the right edge of the tile (position = tile-x + tile-width) Velocity is zeroed to stop the entity from sliding. Call this immediately after =apply-velocity-x=. ** resolve-tile-collisions-y #+begin_src scheme (resolve-tile-collisions-y entity scene dt) #+end_src **Reads**: =#:x=, =#:y=, =#:width=, =#:height=, =#:vy= **Writes**: =#:y= (snapped to tile edge), =#:vy= (zeroed if collision occurs) **Description**: Detects all solid tiles overlapping the entity's AABB and snaps the entity to the nearest tile edge on the Y-axis. If a collision is found: - **Moving down** (vy > 0): entity's bottom edge is snapped to the top edge of the tile (position = tile-y - height) - **Moving up** (vy < 0): entity's top edge is snapped to the bottom edge of the tile (position = tile-y + tile-height) Velocity is zeroed. Call this immediately after =apply-velocity-y=. ** detect-on-solid #+begin_src scheme (detect-on-solid entity scene dt) #+end_src **Reads**: =#:gravity?=, =#:x=, =#:y=, =#:width=, =#:height=, =#:vy=; other entities from =(scene-entities scene)= for solid support **Writes**: =#:on-ground?= (set to =#t= if supported by a solid tile probe and/or by another solid's top surface, else =#f=) **Description**: Despite the =?=-suffix, this returns an **updated entity** (it sets =#:on-ground?=), not a boolean. Ground is **either** (1) a solid tile one pixel below the feet (probe at both lower corners of the AABB), **or** (2) resting on another solid entity's **top** from the scene list (horizontal overlap, feet within a few pixels of that entity's top, and vertical speed small enough that we treat the body as supported—so moving platforms and crates count). If =scene-tilemap= is =#f=, the tile probe is skipped; entity–entity support still applies when other solids exist in the list. Only runs when =#:gravity?= is true. Use =#:on-ground?= in =update:= to gate jump input; in =default-engine-update= this step runs **after** tile collision and **before** =resolve-entity-collisions= (see engine order). If you need ground detection to account for entity push-apart first, use a custom =engine-update= and call =detect-on-solid= after =resolve-entity-collisions=. ** resolve-entity-collisions #+begin_src scheme (resolve-entity-collisions entities) #+end_src **Input**: A list of entity plists **Reads**: For each entity: =#:solid?=, =#:x=, =#:y=, =#:width=, =#:height=, =#:vx=, =#:vy= **Writes**: For colliding pairs: =#:x=, =#:y=, =#:vx=, =#:vy= (pushed apart, velocities set to ±1) **Description**: Performs all-pairs AABB overlap detection. For each pair of entities where BOTH have =#:solid? #t=, if they overlap: if one has =#:immovable? #t=, only the other entity is displaced (its velocity on that axis is zeroed). For movable vs immovable, separation prefers **vertical** resolution when the movable’s center is still **above** the immovable’s center (typical landing on a platform), so narrow horizontal overlap does not shove the mover sideways through the edge. Otherwise the shallow overlap axis is used. If both are immovable, the pair is skipped. If neither is immovable, the two bodies are pushed apart along the smaller overlap axis and their velocities on that axis are set to ±1. Entities without =#:solid?= or with =#:solid? #f= are skipped. Returns a new entity list with collisions resolved. This is relatively expensive: O(n²) for n entities. Use only when entity count is low (< 100) or for game objects where push-apart is desired. ** Using =resolve-entity-collisions= on a scene Apply the pure list function via =scene-transform-entities= (from =downstroke-world=): #+begin_src scheme (scene-transform-entities scene resolve-entity-collisions) #+end_src Returns a new scene with the updated entity list; the original scene is not modified. ** aabb-overlap? #+begin_src scheme (aabb-overlap? x1 y1 w1 h1 x2 y2 w2 h2) #+end_src **Returns**: Boolean (#t if overlapping, #f if separated or touching) **Description**: Pure collision test for two axis-aligned bounding boxes. Does not modify any state. Useful for manual collision queries (e.g., "did bullet hit enemy?") where you want to decide the response manually rather than using push-apart. #+begin_src scheme ;; Example: check if player overlaps enemy (if (aabb-overlap? (entity-ref player #:x 0) (entity-ref player #:y 0) (entity-ref player #:width 0) (entity-ref player #:height 0) (entity-ref enemy #:x 0) (entity-ref enemy #:y 0) (entity-ref enemy #:width 0) (entity-ref enemy #:height 0)) (do-damage!)) #+end_src * Tile Collision Model Tiles come from **TMX maps** loaded by the tilemap module. The tilemap parses the XML and builds a 2D tile grid. Each cell references a tile ID from the tileset. **Solid tiles** are identified by **tile metadata** in the TSX tileset (defined in Tiled editor). The physics module checks each tile to see if it has collision metadata. Tiles with no metadata are treated as non-solid background tiles. ** How Collision Works 1. Entity's AABB (x, y, width, height) is used to compute all overlapping tile cells 2. For each cell, the physics module queries the tilemap: "does this cell have a solid tile?" 3. If yes, the entity is snapped to the edge of that tile in the axis being resolved 4. Velocity is zeroed in that axis to prevent sliding ** Why X and Y are Separate Tile collisions are resolved in two passes: #+begin_src apply-velocity-x → resolve-tile-collisions-x → apply-velocity-y → resolve-tile-collisions-y #+end_src This prevents a common platformer bug: if you moved and collided on both axes at once, you could get "corner clipped" (stuck in a diagonal corner). By separating X and Y, you guarantee the entity snaps cleanly. * Entity-Entity Collision Entity-entity collisions are for when two **game objects** overlap: a player and an enemy, two boxes stacked, etc. =resolve-entity-collisions= does all-pairs AABB checks. Any entity with =#:solid? #t= that overlaps another solid entity is pushed apart. The push-apart is along the **minimum penetration axis** (X or Y, whichever overlap is smaller). Entities are pushed in opposite directions by half the overlap distance, and their velocities are set to ±1 to prevent stacking. ** When to Use - **Physics sandbox**: multiple boxes/balls that should bounce apart - **Solid obstacles**: pushable crates that block the player - **Knockback**: enemies that push back when hit ** When NOT to Use - **Trigger zones**: enemies that should detect the player without colliding — use =aabb-overlap?= manually - **Bullets**: should pass through enemies — don't mark bullet as solid, use =aabb-overlap?= to check hits - **High entity count**: 100+ entities = O(n²) is too slow * Platformer Example A minimal platformer with a player, gravity, jumping, and tile collisions. Physics runs in =default-engine-update=; =update:= is input → intent only: #+begin_src scheme ;; Omit engine-update: or use default — physics runs automatically before this hook. update: (lambda (game dt) (let* ((input (game-input game)) (scene (game-scene game)) (player (car (scene-entities scene))) (jump? (and (input-pressed? input 'a) (entity-ref player #:on-ground? #f))) (player (entity-set player #:vx (cond ((input-held? input 'left) -3) ((input-held? input 'right) 3) (else 0))))) (when jump? (play-sound 'jump)) (let ((player (if jump? (entity-set player #:ay (- *jump-force*)) player))) (game-scene-set! game (update-scene scene entities: (list player)))))) #+end_src Import =*jump-force*= from =downstroke-physics= (or use a literal such as =-15= for =#:ay=). ** Step-by-Step 1. **Set #:vx** from input (left = -3, right = +3, idle = 0) 2. **Jump**: if A pressed and =#:on-ground?= (already updated for this frame — your =update:= runs after =engine-update=), play sound and set =#:ay= to =(- *jump-force*)= 3. **Next frame’s =engine-update=** runs =apply-acceleration= through =sync-groups= as documented above * Top-Down Example A top-down game with no gravity and free 4-way movement. Give the player =#:gravity? #f= so acceleration, gravity, and ground detection no-op inside =default-engine-update=: #+begin_src scheme update: (lambda (game dt) (let* ((input (game-input game)) (scene (game-scene game)) (player (car (scene-entities scene))) (dx (+ (if (input-held? input 'left) -3 0) (if (input-held? input 'right) 3 0))) (dy (+ (if (input-held? input 'up) -3 0) (if (input-held? input 'down) 3 0))) (player (entity-set (entity-set player #:vx dx) #:vy dy))) ;; Camera follow still runs after update: in game-run! (camera-x-set! (scene-camera scene) (max 0 (- (entity-ref player #:x 0) 300))) (game-scene-set! game (update-scene scene entities: (list player))))) #+end_src ** Step-by-Step 1. **Read input**: combine left/right into dx, up/down into dy 2. **Set velocity**: both #:vx and #:vy based on input; the next =engine-update= applies velocity and tile collision 3. **No gravity**: =#:gravity? #f= skips =apply-acceleration=, =apply-gravity=, =detect-on-solid= The built-in pipeline still runs; most steps no-op or pass through for non-gravity entities. * Physics Sandbox Example The real =demo/sandbox.scm= relies on =default-engine-update= for boxes, rafts, and tile collision; =update:= only runs per-entity AI (e.g. bots) via =scene-map-entities=. If you **replace** =engine-update= with your own procedure, a full multi-entity pass looks like this (same step order as =default-engine-update=, minus tweens/sync if you omit them): #+begin_src scheme (define (my-engine-update game dt) (let ((scene (game-scene game))) (when scene (game-scene-set! game (scene-transform-entities (scene-map-entities scene (lambda (e) (apply-gravity e scene dt)) (lambda (e) (apply-velocity-x e scene dt)) (lambda (e) (resolve-tile-collisions-x e scene dt)) (lambda (e) (apply-velocity-y e scene dt)) (lambda (e) (resolve-tile-collisions-y e scene dt)) (lambda (e) (detect-on-solid e scene dt))) resolve-entity-collisions))))) #+end_src Prefer reusing =default-engine-update= unless you need a different order (e.g. =detect-on-solid= after entity collisions). A complete custom hook should also run =step-tweens= first and =sync-groups= last, matching =engine.scm=. ** step-by-step 1. **scene-map-entities**: applies each step to all entities in order (snippet above starts at gravity for brevity) - =apply-gravity= (all entities fall) - =apply-velocity-x=, =resolve-tile-collisions-x= (move and collide on x-axis) - =apply-velocity-y=, =resolve-tile-collisions-y= (move and collide on y-axis) - =detect-on-solid= (set #:on-ground?) 2. **scene-transform-entities** with **resolve-entity-collisions**: after all entities are moved and collided with tiles, resolve entity-entity overlaps (boxes pushing apart) This pattern matches how multiple movers interact in the sandbox demo, except the demo uses the built-in =default-engine-update= instead of a hand-rolled hook. ** Capturing =scene= and =dt= =scene-map-entities= passes only each entity into the step. Per-entity physics steps take =(entity scene dt)=, so wrap them: #+begin_src scheme (lambda (e) (resolve-tile-collisions-x e scene dt)) #+end_src Use the same =dt= (milliseconds) that =game-run!= passes to your hooks. * Common Patterns ** Jumping #+begin_src scheme ;; In update: (after physics, #:on-ground? is current) (let ((jump? (and (input-pressed? input 'a) (entity-ref player #:on-ground? #f)))) (if jump? (entity-set player #:ay (- *jump-force*)) player)) #+end_src =*jump-force*= (default 15) is exported from =downstroke-physics=. =apply-acceleration= and gravity run inside =default-engine-update= on the following frame. ** No Gravity For top-down games, use =#:gravity? #f= on movers so acceleration, gravity, and ground detection no-op. For shmups or fully custom motion, use =engine-update: #f= and move entities in =update:=. ** Knockback Set #:vx or #:vy directly to push an entity: #+begin_src scheme (entity-set enemy #:vx -5) ;; Push left #+end_src Gravity will resume on the next frame if =#:gravity?= is #t. ** Trigger Zones For areas that don't collide but detect presence (spawn zones, damage zones): #+begin_src scheme ;; In update: (if (aabb-overlap? (entity-ref trigger #:x 0) (entity-ref trigger #:y 0) (entity-ref trigger #:width 0) (entity-ref trigger #:height 0) (entity-ref player #:x 0) (entity-ref player #:y 0) (entity-ref player #:width 0) (entity-ref player #:height 0)) (on-trigger-enter! player)) #+end_src Don't mark the trigger as solid; just use =aabb-overlap?= to query. ** Slopes and Ramps The current tile collision system is AABB-based and does not support slopes. All tiles are axis-aligned rectangles. To simulate slopes, you can: 1. Use small tiles to approximate a slope (many tiny tiles at angles) 2. Post-process the player's position after collision (rotate velocity vector) 3. Use a custom collision function instead of =resolve-tile-collisions-y= This is beyond the scope of the basic physics system. * Performance Notes - **Tile collision**: O(overlapping tiles) per entity. Usually 1–4 tiles per frame. - **Entity collision**: O(n²) where n = entity count. Avoid for > 100 solid entities. - **Ground detection**: O(2) tile lookups per entity (corners below feet). For large games, consider spatial partitioning (grid, quadtree) to cull entity pairs. The basic physics system is designed for small to medium games (< 100 entities). * Troubleshooting ** Entity Sinks Into Floor - Make sure =#:height= is set correctly (not 0 or too large) - Verify tileset metadata marks floor tiles as solid in Tiled editor - Check that =resolve-tile-collisions-y= is called after =apply-velocity-y= ** Double-Jump / Can't Jump - Ensure =#:on-ground?= is set: with =default-engine-update=, =detect-on-solid= runs each frame; for standing on other solids, note it runs *before* =resolve-entity-collisions= in the default order (see *detect-on-solid* above) - Gate jump in =update:= with =#:on-ground?= and =input-pressed?= (not =input-held?=) - Set =#:ay= only on the jump frame; =apply-acceleration= clears =#:ay= when it runs ** Entity Slides Through Walls - Check that #:width and #:height are set correctly - Verify tileset marks wall tiles as solid - Ensure =resolve-tile-collisions-x= is called after =apply-velocity-x= ** Entities Get Stuck Overlapping - Use =(scene-transform-entities scene resolve-entity-collisions)= after all physics steps - Verify both entities have =#:solid? #t= - Reduce =*gravity*= or max velocity if entities are moving too fast (can cause multi-frame overlap) ** Performance Drops - Profile entity count (should be < 100 for full physics pipeline) - Disable =resolve-entity-collisions= if not needed - Use =aabb-overlap?= for queries instead of marking many entities solid