From 8971ed81ce038883b3bf5b7411ed4b157fe9402c Mon Sep 17 00:00:00 2001 From: Federico Bassini Date: Thu, 22 Oct 2026 17:13:46 +0200 Subject: [PATCH 1/3] engine: composite moves blocked by solid tiles SpriteManager::move_composite_{left,right,up,down}_blocked move a composite as the limited moves do unless its Hitbox would step on a solid background tile, read with the new TileCollision::when_free. TileManager:: background_tile_index gives a background tile's ID for maps and collision sets. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 6 +- CONTEXT.md | 2 + Task.md | 4 + src/engine/mod.rs | 2 +- src/engine/sprites.rs | 327 ++++++++++++++++++++++++++++++++++- src/engine/tile_collision.rs | 192 ++++++++++++++++++-- src/engine/tiles.rs | 43 +++++ src/prelude.rs | 2 +- tests/emulator.rs | 82 +++++++++ 9 files changed, 640 insertions(+), 20 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ea50c41..93f1e95 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,10 @@ together: every breaking change of the refactoring is in this release, so a prog multiply two bytes, and divide a 16-bit value by a byte with explicit register and flag contracts. - **Tile collision checks** (`engine::TileCollision`): test screen pixels against a set of solid tile IDs using the active background map and current camera scroll. +- **Obstacles** (`SpriteManager::move_composite_{left,right,up,down}_blocked`, `engine::Hitbox`): a composite + sprite stops against solid background tiles, tested on a hitbox (e.g. a character's feet); + `TileCollision::when_free` runs code when no pixel of a list is solid, and + `TileManager::background_tile_index` gives the tile ID of background tiles for maps and collision sets. - **Cartridge SRAM control** (`stdlib::sram`): enable/disable external RAM on MBC1/MBC5 and select MBC5's 8 KiB RAM bank; persistent save management remains a follow-up. @@ -257,7 +261,7 @@ uses its module names: `gb_asm`, `gb_std`, `rust_boy::rust_boy`. APIs that were | `use rust_boy::gb_std::flow::If` (any `gb_std::` path) | `use rust_boy::stdlib::flow::If` | | `use rust_boy::rust_boy::{RustBoy, ...}` | `use rust_boy::engine::{RustBoy, ...}`, or `use rust_boy::prelude::*` | | `use rust_boy::gb_asm::Chunk` | `use rust_boy::engine::Chunk` (the game layout is the engine's: `Chunk`, `Layout`) | -| (none) | `use rust_boy::prelude::*`: `Aabb`, `RustBoy`, `RustBoyConfig`, `Error`, `SpriteSize`, `TileSource`, `TilemapArea`, `InputManager`, `AnimationType`, `Var`, `VarType`, `SpriteId`, `CompositeSpriteId`, `ANIM_DISABLED`, `BuiltinFunction`, `Chunk`, `Layout`, `Lcdc`, `Palettes`, `Window`, `MetaspritePart`, `ArrayElement`, `WramArray`, `SpritePool`, `EntityPool`, `Font`, `TextPrinter`, `NumberPrinter`, `NumberFormat`, `BackgroundAnimation`, `BackgroundAnimationConfig`, `AssetError`, `PngOptions`, `PngColorMapping`, `TileOrder`, `png_to_2bpp`, `Definition`, `MemoryRegion`, `If`, `IfA`, `IfConst`, `IfCall`, `Call`, `Routine`, `Regs`, `PadButton`, `Interrupt`, `Stat`, `Timer`, `TimerClock`, `Palette`, `PaletteFade`, `PaletteRegister`, `Shade`, `SpriteFlags`, `ObjectPalette`, `SpritePriority`, `Asm`, `Block`, `Emittable`, `LabelAllocator`, `Expr`, `Instr`, `R8`, `R16`, `Mem`, `Condition`, `Section`, and `hw` | +| (none) | `use rust_boy::prelude::*`: `Aabb`, `Hitbox`, `RustBoy`, `RustBoyConfig`, `Error`, `SpriteSize`, `TileSource`, `TilemapArea`, `InputManager`, `AnimationType`, `Var`, `VarType`, `SpriteId`, `CompositeSpriteId`, `ANIM_DISABLED`, `BuiltinFunction`, `Chunk`, `Layout`, `Lcdc`, `Palettes`, `Window`, `MetaspritePart`, `ArrayElement`, `WramArray`, `SpritePool`, `EntityPool`, `Font`, `TextPrinter`, `NumberPrinter`, `NumberFormat`, `BackgroundAnimation`, `BackgroundAnimationConfig`, `AssetError`, `PngOptions`, `PngColorMapping`, `TileOrder`, `png_to_2bpp`, `Definition`, `MemoryRegion`, `If`, `IfA`, `IfConst`, `IfCall`, `Call`, `Routine`, `Regs`, `PadButton`, `Interrupt`, `Stat`, `Timer`, `TimerClock`, `Palette`, `PaletteFade`, `PaletteRegister`, `Shade`, `SpriteFlags`, `ObjectPalette`, `SpritePriority`, `Asm`, `Block`, `Emittable`, `LabelAllocator`, `Expr`, `Instr`, `R8`, `R16`, `Mem`, `Condition`, `Section`, and `hw` | ### 2. Building a program (`engine::RustBoy`) diff --git a/CONTEXT.md b/CONTEXT.md index 119dfda..aad0c1f 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -1533,6 +1533,8 @@ Detailed list in [`Task.md`](Task.md) Phase 3. Biggest gaps: interrupt handlers, the timer and a soft reset exist since `refactor-p3-interrupts`, WRAM arrays since `refactor-p3-wram-arrays`). `engine::Aabb` provides half-open rectangle overlap checks (edges must not wrap). + Composites move unless a `Hitbox` would step on solid tiles (`SpriteManager::move_composite_*_blocked`, on + `TileCollision::when_free`); `TileManager::background_tile_index` names background tiles' IDs. Register-based function arguments use `RustBoy::call_args` / `Call::with_args`. Signed 8.8 position/velocity/gravity integration exists in `stdlib::movement`. `stdlib::flow` provides `While`, fixed-count `For` and `SwitchA`; For saves BC around its body. diff --git a/Task.md b/Task.md index a4a4d14..4b33578 100644 --- a/Task.md +++ b/Task.md @@ -375,6 +375,10 @@ the next step is Phase 3, and the `refactor` → `main` PR, whose release notes - [x] Generalised tile collision (`refactor-p3-tile-collision`): `TileCollision::at_screen_pixel` checks a configurable set of solid tile IDs using the active map and current SCX/SCY; sample multiple points for larger objects. +- [x] Blocked moves against solid tiles (found writing olive-empire, branch `olive-empire-blocked-moves`): + `SpriteManager::move_composite_{left,right,up,down}_blocked` move a composite as the limited moves do unless + its `Hitbox` would step on a `TileCollision` tile (steps of 1..=8 pixels), built on `TileCollision::when_free`; + `TileManager::background_tile_index` gives a background tile's ID for maps and collision sets. - [x] 16-bit math helpers (branch `refactor-p3-math`): unsigned 16-bit add/subtract/compare, 8×8 multiply and 16÷8 divide with documented register/flag contracts. Regression tests link all routines and cover borrow-free subtraction, greater-than comparison, asymmetric diff --git a/src/engine/mod.rs b/src/engine/mod.rs index 5c39a99..84452ec 100644 --- a/src/engine/mod.rs +++ b/src/engine/mod.rs @@ -42,7 +42,7 @@ pub use scenes::SceneManager; pub use sprites::{ ANIM_DISABLED, CompositeSpriteId, MetaspritePart, SpriteId, SpriteManager, SpriteSize, }; -pub use tile_collision::{TileCollision, TileCollisionCheck}; +pub use tile_collision::{Hitbox, TileCollision, TileCollisionCheck}; pub use tiles::{TileId, TileManager, TileSource, TilemapArea}; pub use variables::{ArrayElement, Var, VarId, VarType, VariableManager, WramArray}; diff --git a/src/engine/sprites.rs b/src/engine/sprites.rs index 4480618..3ff0cdf 100644 --- a/src/engine/sprites.rs +++ b/src/engine/sprites.rs @@ -3,9 +3,12 @@ use std::collections::BTreeMap; use super::memory::{MemoryAllocator, MemoryRegion}; +use super::tile_collision::{Hitbox, TileCollision}; use super::tiles::TileId; use crate::{ - asm::{Block, Condition, Expr, Instr, LabelAllocator, R8, R16, R16Stack, is_identifier}, + asm::{ + Block, Condition, Emittable, Expr, Instr, LabelAllocator, R8, R16, R16Stack, is_identifier, + }, engine::animations::Animation, hw, stdlib::graphics::sprites::{ @@ -1120,6 +1123,181 @@ impl SpriteManager { self.move_composite_limit(id, Axis::Y, MoveDir::Increase, "down", distance, limit) } + /// Move a composite sprite left as [`SpriteManager::move_composite_left_limit`] does, + /// unless its `hitbox` would step on one of the `solid` background tiles: then it does + /// not move + /// + /// The `hitbox` is a rectangle of the composite, from its top-left corner (the left + /// edge of its leftmost sprite, the top edge of its topmost one). Before the move, the + /// tiles left of the hitbox, 1 and `distance` pixels away, are read every 8 pixels + /// along its edge and at the edge's last pixel ([`TileCollision::when_free`]): the + /// active map with the camera scroll, so run the move while VRAM is accessible (input + /// bindings run at the start of the main loop, in VBlank). With a `distance` of 1 the + /// composite stops touching the obstacle; with more, up to `distance - 1` pixels before + /// it. A step cut short by `limit` is still checked for the whole `distance`. + /// + /// # Panics + /// If there is no composite `id`, if `distance` is not in 1..=8 (a longer step could + /// jump over a tile), or if the hitbox does not fit in the composite. + #[track_caller] + pub fn move_composite_left_blocked( + &self, + id: CompositeSpriteId, + distance: u8, + limit: u8, + solid: &TileCollision, + hitbox: Hitbox, + ) -> Vec { + let points = self.blocked_points(id, Axis::X, MoveDir::Decrease, distance, hitbox); + let moving = self.move_composite_left_limit(id, distance, limit); + solid.when_free(points, moving).emit(&self.labels) + } + + /// Move a composite sprite right as [`SpriteManager::move_composite_right_limit`] does, + /// unless its `hitbox` would step on one of the `solid` background tiles; see + /// [`SpriteManager::move_composite_left_blocked`] + #[track_caller] + pub fn move_composite_right_blocked( + &self, + id: CompositeSpriteId, + distance: u8, + limit: u8, + solid: &TileCollision, + hitbox: Hitbox, + ) -> Vec { + let points = self.blocked_points(id, Axis::X, MoveDir::Increase, distance, hitbox); + let moving = self.move_composite_right_limit(id, distance, limit); + solid.when_free(points, moving).emit(&self.labels) + } + + /// Move a composite sprite up as [`SpriteManager::move_composite_up_limit`] does, + /// unless its `hitbox` would step on one of the `solid` background tiles; see + /// [`SpriteManager::move_composite_left_blocked`] + #[track_caller] + pub fn move_composite_up_blocked( + &self, + id: CompositeSpriteId, + distance: u8, + limit: u8, + solid: &TileCollision, + hitbox: Hitbox, + ) -> Vec { + let points = self.blocked_points(id, Axis::Y, MoveDir::Decrease, distance, hitbox); + let moving = self.move_composite_up_limit(id, distance, limit); + solid.when_free(points, moving).emit(&self.labels) + } + + /// Move a composite sprite down as [`SpriteManager::move_composite_down_limit`] does, + /// unless its `hitbox` would step on one of the `solid` background tiles; see + /// [`SpriteManager::move_composite_left_blocked`] + #[track_caller] + pub fn move_composite_down_blocked( + &self, + id: CompositeSpriteId, + distance: u8, + limit: u8, + solid: &TileCollision, + hitbox: Hitbox, + ) -> Vec { + let points = self.blocked_points(id, Axis::Y, MoveDir::Increase, distance, hitbox); + let moving = self.move_composite_down_limit(id, distance, limit); + solid.when_free(points, moving).emit(&self.labels) + } + + /// The screen pixels a blocked move of the composite reads, as (x, y) snippets that + /// each leave the coordinate in `a`: the lines 1 and `distance` pixels ahead of the + /// hitbox, every 8 pixels along its edge and at the edge's last pixel. A tile is 8 + /// pixels, so with a step of at most 8 no tile between the two lines is skipped + #[track_caller] + fn blocked_points( + &self, + id: CompositeSpriteId, + axis: Axis, + dir: MoveDir, + distance: u8, + hitbox: Hitbox, + ) -> Vec<(Vec, Vec)> { + assert!( + (1..=8).contains(&distance), + "a blocked move takes a distance of 1 to 8 pixels, not {}: a longer step could \ + jump over a solid tile", + distance + ); + let composite = self.composite(id); + let members: Vec<&SpriteData> = composite + .sprites + .iter() + .map(|sprite_id| self.sprite(*sprite_id)) + .collect(); + let Some(first) = members.first().copied() else { + return Vec::new(); + }; + // The composite's box, from the positions it was created with + let sprite_height = 8 * i16::from(self.size.tiles_per_sprite()); + let left = members.iter().map(|s| s.x).min().unwrap_or(first.x); + let top = members.iter().map(|s| s.y).min().unwrap_or(first.y); + let width = members.iter().map(|s| s.x + 8).max().unwrap_or(first.x) - left; + let height = members + .iter() + .map(|s| s.y + sprite_height) + .max() + .unwrap_or(first.y) + - top; + let (hx, hy) = (i16::from(hitbox.x), i16::from(hitbox.y)); + let (hw, hh) = (i16::from(hitbox.width), i16::from(hitbox.height)); + assert!( + hx + hw <= width && hy + hh <= height, + "the hitbox {:?} does not fit in composite \"{}\", which is {}x{} pixels", + hitbox, + composite.name, + width, + height + ); + + // A coordinate from the composite's corner, at run time: `first`'s OAM coordinate, + // minus the OAM offset and `first`'s own offset from the corner, wrapping at 256 + let coord = |axis: Axis, offset: i16| -> Vec { + let (oam_offset, own) = match axis { + Axis::X => (hw::OAM_X_OFFSET, first.x - left), + Axis::Y => (hw::OAM_Y_OFFSET, first.y - top), + }; + let add = (offset - own - i16::from(oam_offset)).rem_euclid(256) as u8; + let mut code = Block::new(); + code.ld_a_addr_def(axis.oam_address(first)); + if add != 0 { + code.add(add); + } + code.into_instrs() + }; + + let distance = i16::from(distance); + let (start, len, across_start, across_len) = match axis { + Axis::X => (hx, hw, hy, hh), + Axis::Y => (hy, hh, hx, hw), + }; + let mut lines = match dir { + MoveDir::Decrease => vec![start - 1, start - distance], + MoveDir::Increase => vec![start + len, start + len - 1 + distance], + }; + lines.dedup(); + let last = across_start + across_len - 1; + let mut samples: Vec = (across_start..=last).step_by(8).collect(); + if samples.last() != Some(&last) { + samples.push(last); + } + + let mut points = Vec::new(); + for &line in &lines { + for &sample in &samples { + points.push(match axis { + Axis::X => (coord(Axis::X, line), coord(Axis::Y, sample)), + Axis::Y => (coord(Axis::X, sample), coord(Axis::Y, line)), + }); + } + } + points + } + /// Limited move of a composite (B6): the member that reaches the limit first leads, /// the others follow at the offsets they were created with fn move_composite_limit( @@ -2226,6 +2404,141 @@ mod tests { } } + /// A 16x16 player at screen (80, 72), of two 8x16 sprites + fn player_16x16() -> (RustBoy, CompositeSpriteId) { + let mut gb = RustBoy::new(); + gb.set_sprite_size(SpriteSize::Size8x16); + let player = gb.add_sprite_16x16( + "player", + TileSource::from_file("left.2bpp", 2), + TileSource::from_file("right.2bpp", 2), + 80, + 72, + 0, + ); + (gb, player) + } + + #[test] + fn test_blocked_moves_read_the_pixels_ahead_of_the_hitbox() { + let (gb, player) = player_16x16(); + let feet = Hitbox::new(0, 8, 16, 8); + // The screen pixels each snippet pair leaves in `a`, from the initial shadow OAM + let pixels = |axis: Axis, dir: MoveDir, distance: u8, hitbox: Hitbox| { + gb.sprites + .blocked_points(player, axis, dir, distance, hitbox) + .iter() + .map(|(x, y)| { + let mut cpu = cpu_with_oam(&gb.sprites); + cpu.run(x); + let x = cpu.a; + cpu.run(y); + (x, cpu.a) + }) + .collect::>() + }; + // The feet are x 80..=95, y 80..=87: one line ahead, the edge's first and last pixel + assert_eq!( + pixels(Axis::X, MoveDir::Decrease, 1, feet), + [(79, 80), (79, 87)] + ); + assert_eq!( + pixels(Axis::X, MoveDir::Increase, 1, feet), + [(96, 80), (96, 87)] + ); + // Along a 16-pixel edge: every 8 pixels, and the last one + assert_eq!( + pixels(Axis::Y, MoveDir::Decrease, 1, feet), + [(80, 79), (88, 79), (95, 79)] + ); + assert_eq!( + pixels(Axis::Y, MoveDir::Increase, 1, feet), + [(80, 88), (88, 88), (95, 88)] + ); + // A longer step reads the line 1 pixel ahead and the line `distance` pixels ahead + assert_eq!( + pixels(Axis::X, MoveDir::Decrease, 8, feet), + [(79, 80), (79, 87), (72, 80), (72, 87)] + ); + assert_eq!( + pixels(Axis::Y, MoveDir::Increase, 3, Hitbox::new(4, 0, 1, 16)), + [(84, 88), (84, 90)] + ); + // Ahead of the screen's left edge, the pixel wraps around the 256-pixel map + let (mut gb, _) = player_16x16(); + let edge = gb.add_sprite_16x16( + "edge", + TileSource::from_file("left.2bpp", 2), + TileSource::from_file("right.2bpp", 2), + 0, + 0, + 0, + ); + let points = gb + .sprites + .blocked_points(edge, Axis::X, MoveDir::Decrease, 1, feet); + let mut cpu = cpu_with_oam(&gb.sprites); + cpu.run(&points[0].0); + assert_eq!(cpu.a, 255); + } + + #[test] + fn test_blocked_moves_reject_long_steps_and_hitboxes_outside_the_composite() { + let (gb, player) = player_16x16(); + let solid = TileCollision::new([1]); + let feet = Hitbox::new(0, 8, 16, 8); + for distance in [0, 9] { + let message = panic_message(|| { + gb.sprites + .move_composite_left_blocked(player, distance, 8, &solid, feet) + }); + assert!( + message.contains(&format!("distance of 1 to 8 pixels, not {}", distance)), + "{}", + message + ); + } + for hitbox in [Hitbox::new(1, 0, 16, 16), Hitbox::new(0, 9, 16, 8)] { + let message = panic_message(|| { + gb.sprites + .move_composite_down_blocked(player, 1, 150, &solid, hitbox) + }); + assert!( + message.contains("does not fit in composite \"player\", which is 16x16"), + "{}", + message + ); + } + } + + #[test] + fn test_blocked_moves_without_solid_tiles_are_the_limited_moves() { + // No solid tile: no tile is read, the move is the limited one + let (gb, player) = player_16x16(); + let free = TileCollision::new([]); + let feet = Hitbox::new(0, 8, 16, 8); + let text = |code: Vec| -> Vec { + code.iter() + .map(|instr| instr.to_string().replace(|c: char| c.is_ascii_digit(), "#")) + .collect() + }; + assert_eq!( + text( + gb.sprites + .move_composite_up_blocked(player, 2, 8, &free, feet) + ), + text(gb.sprites.move_composite_up_limit(player, 2, 8)) + ); + let blocked = + gb.sprites + .move_composite_up_blocked(player, 2, 8, &TileCollision::new([1, 2]), feet); + let calls = blocked + .iter() + .filter(|instr| instr.to_string().contains("call GetTileByScreenPixel")) + .count(); + assert_eq!(calls, 6, "two lines of three pixels"); + } + type CompositeOp = Box; #[test] @@ -2247,6 +2560,18 @@ mod tests { "move_composite_down_limit", Box::new(|sm, id| drop(sm.move_composite_down_limit(id, 1, 8))), ), + ( + "move_composite_left_blocked", + Box::new(|sm, id| { + drop(sm.move_composite_left_blocked( + id, + 1, + 8, + &TileCollision::new([1]), + Hitbox::new(0, 0, 8, 8), + )) + }), + ), ( "add_composite_animation", Box::new(|sm, id| { diff --git a/src/engine/tile_collision.rs b/src/engine/tile_collision.rs index b8e7e8c..83ffe80 100644 --- a/src/engine/tile_collision.rs +++ b/src/engine/tile_collision.rs @@ -37,41 +37,201 @@ impl TileCollision { body: impl Emittable + 'static, ) -> TileCollisionCheck { TileCollisionCheck { - x: Box::new(x), - y: Box::new(y), + points: vec![(Box::new(x), Box::new(y))], body: Box::new(body), solid_tiles: self.solid_tiles.clone(), + when: When::Solid, } } + + /// Check the tiles under several screen pixels and run `body` only when none of them + /// is solid (for example, the pixels a sprite is about to step on). + /// + /// Each point is a pair of snippets that leave the unsigned screen `x` and `y` in `a`, + /// as for [`TileCollision::at_screen_pixel`], with the same VRAM-access rule. The + /// checks stop at the first solid pixel. With no points or no solid tiles, `body` + /// always runs and no tile is read. The check clobbers `a`, `bc`, `d`, `hl` and flags; + /// other registers are preserved except for changes made by the snippets and `body`. + pub fn when_free( + &self, + points: impl IntoIterator, + body: impl Emittable + 'static, + ) -> TileCollisionCheck + where + X: Emittable + 'static, + Y: Emittable + 'static, + { + TileCollisionCheck { + points: points + .into_iter() + .map(|(x, y)| -> (Box, Box) { + (Box::new(x), Box::new(y)) + }) + .collect(), + body: Box::new(body), + solid_tiles: self.solid_tiles.clone(), + when: When::Free, + } + } +} + +/// When a [`TileCollisionCheck`] runs its body +enum When { + /// The (single) pixel is on a solid tile + Solid, + /// No pixel is on a solid tile + Free, } /// An emitted screen-pixel background collision check. pub struct TileCollisionCheck { - x: Box, - y: Box, + points: Vec<(Box, Box)>, body: Box, solid_tiles: Vec, + when: When, } -impl Emittable for TileCollisionCheck { - fn emit(&mut self, labels: &LabelAllocator) -> Vec { - let [hit, end] = labels.locals(["solid_tile_hit", "solid_tile_end"]); - let mut code = Block::new(); - code.emit_all(self.x.emit(labels)) +impl TileCollisionCheck { + /// Look up the tile under one point: `a` = its ID, `hl` = its map address + fn lookup( + code: &mut Block, + point: &mut (Box, Box), + labels: &LabelAllocator, + ) { + code.emit_all(point.0.emit(labels)) .ld(R8::B, R8::A) .push(R16Stack::BC) - .emit_all(self.y.emit(labels)) + .emit_all(point.1.emit(labels)) .ld(R8::D, R8::A) .pop(R16Stack::BC) .ld(R8::C, R8::D) .call("GetTileByScreenPixel"); - for tile in &self.solid_tiles { - code.cp_imm(*tile).jr_cond(Condition::Z, &hit); + } +} + +/// A rectangle of a sprite, in pixels from the sprite's top-left corner: the part that +/// collides. For a top-down character, the feet: `Hitbox::new(0, 8, 16, 8)` is the lower +/// half of a 16x16 character, so its head can overlap the tiles above an obstacle. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Hitbox { + /// Left edge, from the sprite's left edge + pub x: u8, + /// Top edge, from the sprite's top edge + pub y: u8, + /// Width in pixels (at least 1) + pub width: u8, + /// Height in pixels (at least 1) + pub height: u8, +} + +impl Hitbox { + /// A `width` x `height` rectangle at (`x`, `y`) from the sprite's top-left corner. + /// + /// # Panics + /// If `width` or `height` is zero. + #[track_caller] + pub fn new(x: u8, y: u8, width: u8, height: u8) -> Self { + assert!(width > 0, "Hitbox width must be nonzero"); + assert!(height > 0, "Hitbox height must be nonzero"); + Self { + x, + y, + width, + height, + } + } +} + +impl Emittable for TileCollisionCheck { + fn emit(&mut self, labels: &LabelAllocator) -> Vec { + let mut code = Block::new(); + match self.when { + When::Solid => { + let [hit, end] = labels.locals(["solid_tile_hit", "solid_tile_end"]); + for point in &mut self.points { + Self::lookup(&mut code, point, labels); + } + for tile in &self.solid_tiles { + code.cp_imm(*tile).jr_cond(Condition::Z, &hit); + } + code.jp(&end) + .label(&hit) + .emit_all(self.body.emit(labels)) + .label(&end); + } + When::Free => { + if self.solid_tiles.is_empty() || self.points.is_empty() { + code.emit_all(self.body.emit(labels)); + return code.into_instrs(); + } + let [blocked] = labels.locals(["solid_tile_blocked"]); + for point in &mut self.points { + Self::lookup(&mut code, point, labels); + for tile in &self.solid_tiles { + code.cp_imm(*tile).jp_cond(Condition::Z, &blocked); + } + } + code.emit_all(self.body.emit(labels)).label(&blocked); + } } - code.jp(&end) - .label(&hit) - .emit_all(self.body.emit(labels)) - .label(&end); code.into_instrs() } } + +#[cfg(test)] +mod tests { + use super::*; + + fn text(mut check: TileCollisionCheck) -> Vec { + check + .emit(&LabelAllocator::new()) + .iter() + .map(ToString::to_string) + .collect() + } + + fn at(value: u8) -> Vec { + let mut code = Block::new(); + code.ld_a(value); + code.into_instrs() + } + + #[test] + fn when_free_reads_every_point_and_skips_the_body_on_a_solid_tile() { + let lines = text( + TileCollision::new([3, 4]) + .when_free([(at(1), at(2)), (at(5), at(6))], vec![Instr::Ret]), + ); + let calls: Vec = lines + .iter() + .enumerate() + .filter(|(_, line)| line.contains("call GetTileByScreenPixel")) + .map(|(index, _)| index) + .collect(); + assert_eq!(calls.len(), 2, "{lines:#?}"); + // After each lookup, every solid tile jumps past the body + for call in calls { + assert!(lines[call + 1].contains("cp") && lines[call + 1].contains('3')); + assert!(lines[call + 2].starts_with("jp z, .solid_tile_blocked")); + assert!(lines[call + 3].contains("cp") && lines[call + 3].contains('4')); + assert!(lines[call + 4].starts_with("jp z, .solid_tile_blocked")); + } + let body = lines + .iter() + .position(|line| line == "ret") + .expect("the body"); + assert!(lines[body + 1].starts_with(".solid_tile_blocked")); + assert_eq!(body + 2, lines.len()); + } + + #[test] + fn when_free_without_points_or_solid_tiles_is_the_body() { + for check in [ + TileCollision::new([]).when_free([(at(1), at(2))], vec![Instr::Ret]), + TileCollision::new([7]) + .when_free(Vec::<(Vec, Vec)>::new(), vec![Instr::Ret]), + ] { + assert_eq!(text(check), ["ret"]); + } + } +} diff --git a/src/engine/tiles.rs b/src/engine/tiles.rs index c58ed96..2f4a9aa 100644 --- a/src/engine/tiles.rs +++ b/src/engine/tiles.rs @@ -401,6 +401,24 @@ impl TileManager { cp_in_memory(&tile.name, Expr::hex(area.address())) } + /// The tile index of the first tile of the background tiles `id`, as a tilemap or a + /// [`TileCollision`](super::TileCollision) names it: the engine's background tiles are + /// at `$9000` (LCDC bit 4 off), where tile 0 is, so their indices are 0 to 127. The + /// next tiles of `id` have the next indices. + /// + /// # Panics + /// If `id` is not background tiles of this manager. + #[track_caller] + pub fn background_tile_index(&self, id: TileId) -> u8 { + let tile = self + .tiles + .get(&id) + .filter(|tile| !tile.is_sprite && !tile.is_tilemap) + .unwrap_or_else(|| panic!("tiles {:?} are not background tiles of this program", id)); + u8::try_from((tile.vram_address - hw::VRAM_BG_TILES) / hw::TILE_SIZE) + .expect("background tiles are allocated in the 128 background tiles") + } + /// Get the label name for a tile pub fn get_label(&self, id: TileId) -> Option<&str> { self.tiles.get(&id).map(|t| t.name.as_str()) @@ -529,6 +547,31 @@ impl TileManager { mod tests { use super::*; + #[test] + fn background_tile_index_counts_from_9000_and_rejects_other_tiles() { + let mut tiles = TileManager::new(); + let grass = tiles.add_background("Grass", TileSource::from_raw(&[["$00"; 8]])); + let sprite = tiles.add_sprite("Hero", TileSource::from_raw(&[["$ff"; 8]; 2])); + let tree = tiles.add_background("Tree", TileSource::from_raw(&[["$ff"; 8]; 4])); + let rock = tiles.add_background("Rock", TileSource::from_raw(&[["$ff"; 8]])); + let map = tiles.add_tilemap("Map", &[[0; 32]]); + assert_eq!( + [grass, tree, rock].map(|id| tiles.background_tile_index(id)), + [0, 1, 5] + ); + for id in [sprite, map] { + let message = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + tiles.background_tile_index(id) + })) + .expect_err("not background tiles"); + let message = message + .downcast_ref::() + .cloned() + .unwrap_or_default(); + assert!(message.contains("are not background tiles"), "{message}"); + } + } + #[test] fn rom_maps_do_not_reserve_or_initialize_vram() { let mut tiles = TileManager::new(); diff --git a/src/prelude.rs b/src/prelude.rs index 90ab3a0..3afe23b 100644 --- a/src/prelude.rs +++ b/src/prelude.rs @@ -41,7 +41,7 @@ pub use crate::asm::{ pub use crate::engine::{ ANIM_DISABLED, Aabb, AnimationType, ArrayElement, AssetError, BackgroundAnimation, BackgroundAnimationConfig, BuiltinFunction, Chunk, CompositeSpriteId, Definition, EntityPool, - Error, Font, InputManager, Layout, Lcdc, MemoryRegion, MetaspritePart, NumberFormat, + Error, Font, Hitbox, InputManager, Layout, Lcdc, MemoryRegion, MetaspritePart, NumberFormat, NumberPrinter, Palettes, PngColorMapping, PngOptions, RustBoy, RustBoyConfig, SceneManager, SpriteId, SpriteSize, TextPrinter, TileCollision, TileCollisionCheck, TileOrder, TileSource, TilemapArea, Var, VarType, Window, WramArray, png_to_2bpp, diff --git a/tests/emulator.rs b/tests/emulator.rs index 42150d7..b331131 100644 --- a/tests/emulator.rs +++ b/tests/emulator.rs @@ -4680,3 +4680,85 @@ fn aabb_collision_reads_live_sprite_coordinates() { gb.run_frames(2); assert_eq!(gb.read_symbol("wSpriteRectHit"), 1); } + +#[test] +fn blocked_composite_moves_stop_the_hitbox_against_solid_tiles() { + if !rgbds_enabled() { + return; + } + // A 16x16 player at screen (80, 72), whose hitbox is its feet: the lower 8 rows + let mut game = RustBoy::with_config(RustBoyConfig::default().sprite_size(SpriteSize::Size8x16)); + let tiles = || TileSource::from_raw(&[["$ff"; 8]; 2]); + let player = game.add_sprite_16x16("Player", tiles(), tiles(), 80, 72, 0); + let blank = game + .tiles + .add_background("Blank", TileSource::from_raw(&[["$00"; 8]])); + let rock = game + .tiles + .add_background("Rock", TileSource::from_raw(&[["$ff"; 8]])); + let rock_tile = game.tiles.background_tile_index(rock); + assert_eq!((game.tiles.background_tile_index(blank), rock_tile), (0, 1)); + // One rock on each side of the walk below (map row, column; 8 pixels each) + let mut map = [[0u8; 32]; 32]; + for (row, column) in [(10, 8), (10, 13), (7, 12), (13, 11)] { + map[row][column] = rock_tile; + } + game.tiles.add_tilemap("Map", &map); + + let solid = TileCollision::new([rock_tile]); + let feet = Hitbox::new(0, 8, 16, 8); + let sprites = &game.sprites; + let mut inputs = InputManager::new(); + inputs + .on_press( + PadButton::Left, + sprites.move_composite_left_blocked(player, 1, 8, &solid, feet), + ) + .on_press( + PadButton::Right, + sprites.move_composite_right_blocked(player, 1, 160, &solid, feet), + ) + .on_press( + PadButton::Up, + sprites.move_composite_up_blocked(player, 1, 1, &solid, feet), + ) + .on_press( + PadButton::Down, + sprites.move_composite_down_blocked(player, 1, 150, &solid, feet), + ); + game.add_inputs(inputs); + + let mut gb = engine_rom(&game).boot(); + gb.run_frames(3); + let position = |gb: &GameBoy| { + let (left, right) = (gb.oam_entry(0), gb.oam_entry(1)); + assert_eq!( + (right[0], right[1]), + (left[0], left[1] + 8), + "the halves move together" + ); + // Screen coordinates of the player's top-left corner + (left[1] - 8, left[0] - 16) + }; + assert_eq!(position(&gb), (80, 72)); + // The rock at column 8 ends at x 71: the feet stop touching it + gb.run_script(&[(30, &[Button::Left])]); + assert_eq!(position(&gb), (72, 72), "stopped by the rock on the left"); + // The rock at column 13 starts at x 104 + gb.run_script(&[(40, &[Button::Right])]); + assert_eq!(position(&gb), (88, 72), "stopped by the rock on the right"); + // The rock at row 7 ends at y 63: the feet stop at 64, the head overlaps its row + gb.run_script(&[(40, &[Button::Up])]); + assert_eq!(position(&gb), (88, 56), "stopped by the rock above"); + // The rock at row 13 starts at y 104 + gb.run_script(&[(60, &[Button::Down])]); + assert_eq!(position(&gb), (88, 88), "stopped by the rock below"); + // Free again on the left: the walk goes on to the rock-free screen edge + gb.run_script(&[(100, &[Button::Left])]); + assert_eq!( + position(&gb), + (0, 88), + "no rock on row 12 to the left: the left limit, OAM X 8" + ); + assert_sprites_shown_by_dma_in_vblank(&gb); +} From 818e855c91ba27f047da4517e5a67c4f301b880a Mon Sep 17 00:00:00 2001 From: Federico Bassini Date: Thu, 29 Oct 2026 19:11:46 +0100 Subject: [PATCH 2/3] engine: Var::increment, when_composite_touches, queue_tile_block_write Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 6 +++ Task.md | 4 ++ src/engine/rustboy.rs | 100 ++++++++++++++++++++++++++++++++++- src/engine/sprites.rs | 69 ++++++++++++++++++++++++ src/engine/tile_collision.rs | 89 +++++++++++++++++++++++++++++-- src/engine/variables.rs | 58 ++++++++++++++++++++ 6 files changed, 321 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 93f1e95..4b62ec7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -30,6 +30,12 @@ together: every breaking change of the refactoring is in this release, so a prog sprite stops against solid background tiles, tested on a hitbox (e.g. a character's feet); `TileCollision::when_free` runs code when no pixel of a list is solid, and `TileManager::background_tile_index` gives the tile ID of background tiles for maps and collision sets. +- **Acting on what a sprite touches** (`SpriteManager::when_composite_touches`): runs code once when a + composite's hitbox touches a solid tile on any side, with the tile ID in `a` and its map address in `hl`; built + on `TileCollision::at_first_solid` (the first solid pixel of a list). +- **Map blocks at run time** (`RustBoy::queue_tile_block_write`): queues a block of map tiles (e.g. a 2x2 + metatile) from the map address in `hl`, one VRAM-queue entry a tile. +- **`Var::increment`**: adds 1 to an 8- or 16-bit variable, wrapping, and leaves the new value in `a` / `hl`. - **Cartridge SRAM control** (`stdlib::sram`): enable/disable external RAM on MBC1/MBC5 and select MBC5's 8 KiB RAM bank; persistent save management remains a follow-up. diff --git a/Task.md b/Task.md index 4b33578..9aa3d22 100644 --- a/Task.md +++ b/Task.md @@ -379,6 +379,10 @@ the next step is Phase 3, and the `refactor` → `main` PR, whose release notes `SpriteManager::move_composite_{left,right,up,down}_blocked` move a composite as the limited moves do unless its `Hitbox` would step on a `TileCollision` tile (steps of 1..=8 pixels), built on `TileCollision::when_free`; `TileManager::background_tile_index` gives a background tile's ID for maps and collision sets. +- [x] Harvest in olive-empire (found writing it, branch `olive-empire-harvest`): `Var::increment` (8/16-bit, wraps); + `SpriteManager::when_composite_touches` runs code once for the first solid tile 1 px around a hitbox, on + `TileCollision::at_first_solid` (`When::Solid` now compares after each lookup; one point emits the same code); + `RustBoy::queue_tile_block_write` queues a WxH block of map tiles from `hl` through the VRAM queue. - [x] 16-bit math helpers (branch `refactor-p3-math`): unsigned 16-bit add/subtract/compare, 8×8 multiply and 16÷8 divide with documented register/flag contracts. Regression tests link all routines and cover borrow-free subtraction, greater-than comparison, asymmetric diff --git a/src/engine/rustboy.rs b/src/engine/rustboy.rs index 5e72e3e..71d97a6 100644 --- a/src/engine/rustboy.rs +++ b/src/engine/rustboy.rs @@ -3,7 +3,9 @@ use std::collections::{BTreeMap, BTreeSet}; use crate::asm::labels::{DefinitionEvent, DefinitionScanner, defines}; -use crate::asm::{Block, Expr, Instr, JumpTarget, LabelAllocator, R8, R16, is_identifier}; +use crate::asm::{ + Block, Expr, Instr, JumpTarget, LabelAllocator, R8, R16, R16Stack, is_identifier, +}; use crate::hw; use crate::stdlib::flow::Emittable; use crate::stdlib::graphics::oam::{self, OamTarget}; @@ -1855,6 +1857,55 @@ impl RustBoy { enqueue } + /// Queue a block of map tiles, `width` tiles a row and `tiles` row by row, with its + /// top-left cell at the map address in `hl`: for example, a 2x2 metatile found at run + /// time with [`super::TileCollision::at_first_solid`] + /// + /// One queue entry a tile, written as [`RustBoy::queue_vram_write_from_registers`] does + /// (same single-producer contract); the rows are 32 cells apart, as in a tilemap. + /// Changes all registers and flags. The queue holds + /// [`crate::stdlib::graphics::vram_queue::CAPACITY`] entries until the next VBlank flush: + /// a tile that does not fit is dropped, so queue a block before other writes of the frame. + /// + /// # Panics + /// If `width` is 0, `tiles` is empty, its length is not a multiple of `width`, or the + /// block has more tiles than the queue holds. + #[track_caller] + pub fn queue_tile_block_write(&mut self, width: u8, tiles: &[u8]) -> Vec { + let capacity = usize::from(vram_queue::CAPACITY); + assert!(width > 0, "queue_tile_block_write: width must be nonzero"); + assert!( + !tiles.is_empty() && tiles.len() % usize::from(width) == 0, + "queue_tile_block_write: {} tiles do not make rows of {width}", + tiles.len() + ); + assert!( + tiles.len() <= capacity, + "queue_tile_block_write: {} tiles do not fit in the {capacity}-entry VRAM queue", + tiles.len() + ); + let enqueue = self.queue_vram_write_from_registers(); + let width = usize::from(width); + let mut code = Block::new(); + for (index, tile) in tiles.iter().enumerate() { + // QueueVramWrite changes every register: keep the cell address + code.push(R16Stack::HL) + .ld(R8::A, *tile) + .emit_all(enqueue.clone()) + .pop(R16Stack::HL); + if index + 1 == tiles.len() { + break; + } + if (index + 1) % width == 0 { + // From the row's last cell to the next row's first one + code.ld(R16::BC, (32 - (width - 1)) as i32).add_hl(R16::BC); + } else { + code.inc(R16::HL); + } + } + code.into_instrs() + } + /// Add a sprite with its tile in one call /// Returns the sprite ID for later reference /// @@ -4341,6 +4392,53 @@ mod tests { } } + #[test] + fn test_tile_block_write_queues_each_cell_row_by_row() { + let mut gb = RustBoy::new(); + let mut code = Block::new(); + code.ld(R16::HL, 0x9C21); + code.emit_all(gb.queue_tile_block_write(2, &[10, 11, 12, 13])); + // A stub queue: the tile at its cell, and every register clobbered + code.jp("BlockEnd") + .label("QueueVramWrite") + .ld(R8::AtHl, R8::A) + .ld(R16::HL, 0) + .ld(R16::BC, 0) + .ret() + .label("BlockEnd"); + let mut cpu = TestCpu::default(); + cpu.run(&code.into_instrs()); + let writes: Vec<_> = cpu + .trace + .iter() + .filter_map(|event| match event { + Event::Write(cell, tile) => Some((cell.clone(), *tile)), + _ => None, + }) + .collect(); + assert_eq!( + writes, + [ + ("$9C21".to_string(), 10), + ("$9C22".to_string(), 11), + ("$9C41".to_string(), 12), + ("$9C42".to_string(), 13), + ] + ); + for (width, tiles) in [ + (0, &[1][..]), + (2, &[1, 2, 3][..]), + (1, &[][..]), + (1, &[0; 13][..]), + ] { + assert!( + panic_message(|| RustBoy::new().queue_tile_block_write(width, tiles)) + .contains("queue_tile_block_write"), + "{width} {tiles:?}" + ); + } + } + #[test] fn test_vram_queue_api_checks_constants_and_routine_conflicts() { for address in [ diff --git a/src/engine/sprites.rs b/src/engine/sprites.rs index 3ff0cdf..b5c458c 100644 --- a/src/engine/sprites.rs +++ b/src/engine/sprites.rs @@ -1204,6 +1204,38 @@ impl SpriteManager { solid.when_free(points, moving).emit(&self.labels) } + /// Run `body` once when the composite's `hitbox` touches one of the `solid` background + /// tiles: a tile on the line of pixels just outside the hitbox, on any side (the pixels a + /// 1-pixel blocked move would read, left, right, up, then down) + /// + /// For an action on an obstacle next to a character, like using a door or a tree. When + /// `body` runs, `a` is the touched tile's ID and `hl` its map address (see + /// [`TileCollision::at_first_solid`]); with several tiles touched, the first in that + /// order. It reads the map, so it has the VRAM-access rule of the blocked moves: put it + /// in an input binding (they run at the start of the main loop, in VBlank). + /// + /// # Panics + /// If there is no composite `id`, or if the hitbox does not fit in the composite. + #[track_caller] + pub fn when_composite_touches( + &self, + id: CompositeSpriteId, + hitbox: Hitbox, + solid: &TileCollision, + body: impl crate::asm::Emittable + 'static, + ) -> Vec { + let points: Vec<_> = [ + (Axis::X, MoveDir::Decrease), + (Axis::X, MoveDir::Increase), + (Axis::Y, MoveDir::Decrease), + (Axis::Y, MoveDir::Increase), + ] + .into_iter() + .flat_map(|(axis, dir)| self.blocked_points(id, axis, dir, 1, hitbox)) + .collect(); + solid.at_first_solid(points, body).emit(&self.labels) + } + /// The screen pixels a blocked move of the composite reads, as (x, y) snippets that /// each leave the coordinate in `a`: the lines 1 and `distance` pixels ahead of the /// hitbox, every 8 pixels along its edge and at the edge's last pixel. A tile is 8 @@ -2482,6 +2514,43 @@ mod tests { assert_eq!(cpu.a, 255); } + #[test] + fn test_touching_reads_the_line_around_the_hitbox_and_runs_the_body_once() { + let (gb, player) = player_16x16(); + let feet = Hitbox::new(0, 8, 16, 8); + let lines: Vec = gb + .sprites + .when_composite_touches(player, feet, &TileCollision::new([5]), vec![Instr::Ret]) + .iter() + .map(ToString::to_string) + .collect(); + // The 1-pixel blocked-move points: 2 left, 2 right, 3 up, 3 down + let lookups = lines + .iter() + .filter(|line| line.contains("call GetTileByScreenPixel")) + .count(); + assert_eq!(lookups, 2 + 2 + 3 + 3, "{lines:#?}"); + assert_eq!( + lines + .iter() + .filter(|line| line.starts_with("jp z, .solid_tile_hit")) + .count(), + lookups, + "a jump to the body after each lookup" + ); + assert_eq!(lines.iter().filter(|line| *line == "ret").count(), 1); + // The hitbox must fit, as for the blocked moves + assert!( + !panic_message(|| gb.sprites.when_composite_touches( + player, + Hitbox::new(0, 8, 17, 8), + &TileCollision::new([5]), + vec![Instr::Ret] + )) + .is_empty() + ); + } + #[test] fn test_blocked_moves_reject_long_steps_and_hitboxes_outside_the_composite() { let (gb, player) = player_16x16(); diff --git a/src/engine/tile_collision.rs b/src/engine/tile_collision.rs index 83ffe80..87b187b 100644 --- a/src/engine/tile_collision.rs +++ b/src/engine/tile_collision.rs @@ -44,6 +44,37 @@ impl TileCollision { } } + /// Check the tiles under several screen pixels, in order, and run `body` once for the + /// first one on a solid tile (for example, an obstacle next to a sprite to act on). + /// + /// Each point is a pair of snippets that leave the unsigned screen `x` and `y` in `a`, + /// as for [`TileCollision::at_screen_pixel`], with the same VRAM-access rule. The checks + /// stop at the first solid pixel; when `body` runs, `a` is its tile ID and `hl` its map + /// address. With no points or no solid tiles, `body` never runs. The check clobbers `a`, + /// `bc`, `d`, `hl` and flags; other registers are preserved except for changes made by + /// the snippets and `body`. + pub fn at_first_solid( + &self, + points: impl IntoIterator, + body: impl Emittable + 'static, + ) -> TileCollisionCheck + where + X: Emittable + 'static, + Y: Emittable + 'static, + { + TileCollisionCheck { + points: points + .into_iter() + .map(|(x, y)| -> (Box, Box) { + (Box::new(x), Box::new(y)) + }) + .collect(), + body: Box::new(body), + solid_tiles: self.solid_tiles.clone(), + when: When::Solid, + } + } + /// Check the tiles under several screen pixels and run `body` only when none of them /// is solid (for example, the pixels a sprite is about to step on). /// @@ -77,7 +108,7 @@ impl TileCollision { /// When a [`TileCollisionCheck`] runs its body enum When { - /// The (single) pixel is on a solid tile + /// The first pixel on a solid tile, in order (one pixel for `at_screen_pixel`) Solid, /// No pixel is on a solid tile Free, @@ -148,11 +179,19 @@ impl Emittable for TileCollisionCheck { match self.when { When::Solid => { let [hit, end] = labels.locals(["solid_tile_hit", "solid_tile_end"]); + // One point (`at_screen_pixel`) is near its body: `jr`. Several + // (`at_first_solid`) can be farther than `jr` reaches + let near = self.points.len() == 1; for point in &mut self.points { Self::lookup(&mut code, point, labels); - } - for tile in &self.solid_tiles { - code.cp_imm(*tile).jr_cond(Condition::Z, &hit); + for tile in &self.solid_tiles { + code.cp_imm(*tile); + if near { + code.jr_cond(Condition::Z, &hit); + } else { + code.jp_cond(Condition::Z, &hit); + } + } } code.jp(&end) .label(&hit) @@ -224,6 +263,48 @@ mod tests { assert_eq!(body + 2, lines.len()); } + #[test] + fn at_first_solid_compares_after_each_lookup_and_runs_the_body_once() { + let lines = text( + TileCollision::new([3, 4]) + .at_first_solid([(at(1), at(2)), (at(5), at(6))], vec![Instr::Ret]), + ); + let calls: Vec = lines + .iter() + .enumerate() + .filter(|(_, line)| line.contains("call GetTileByScreenPixel")) + .map(|(index, _)| index) + .collect(); + assert_eq!(calls.len(), 2, "{lines:#?}"); + // Right after each lookup, while a and hl are that point's: jump to the body + for call in calls { + assert!(lines[call + 1].contains("cp") && lines[call + 1].contains('3')); + assert!(lines[call + 2].starts_with("jp z, .solid_tile_hit")); + assert!(lines[call + 3].contains("cp") && lines[call + 3].contains('4')); + assert!(lines[call + 4].starts_with("jp z, .solid_tile_hit")); + } + assert_eq!( + lines.iter().filter(|line| *line == "ret").count(), + 1, + "one body: {lines:#?}" + ); + let body = lines.iter().position(|line| line == "ret").unwrap(); + assert!(lines[body - 2].starts_with("jp .solid_tile_end")); + assert!(lines[body - 1].starts_with(".solid_tile_hit")); + assert!(lines[body + 1].starts_with(".solid_tile_end")); + } + + #[test] + fn at_screen_pixel_keeps_its_short_jumps() { + let lines = text(TileCollision::new([3]).at_screen_pixel(at(1), at(2), vec![Instr::Ret])); + assert!( + lines + .iter() + .any(|line| line.starts_with("jr z, .solid_tile_hit")) + ); + assert!(!lines.iter().any(|line| line.starts_with("jp z"))); + } + #[test] fn when_free_without_points_or_solid_tiles_is_the_body() { for check in [ diff --git a/src/engine/variables.rs b/src/engine/variables.rs index afdadd4..090ca20 100644 --- a/src/engine/variables.rs +++ b/src/engine/variables.rs @@ -265,6 +265,33 @@ impl Var { asm.into_instrs() } + /// The code that adds 1 to the variable, wrapping (255 + 1 = 0 for a `U8`, 65535 + 1 = 0 + /// for a `U16`), and leaves the new value where [`Var::get`] does + /// + /// - 8-bit: `inc a` between a load and a store; the new value is in `a`. + /// - 16-bit: `inc hl` between a [`Var::get`] and a store of both bytes; the new value is in + /// `hl` and `a` holds its high byte. + /// + /// Changes the flags too (`inc` sets Z when an 8-bit value wraps to 0). + /// + /// # Panics + /// If the variable is an array: use its [`WramArray`] handle. + #[track_caller] + pub fn increment(&self) -> Vec { + let mut asm = Block::new(); + asm.emit_all(self.get()); + if self.var_type.size() == 2 { + asm.inc(R16::HL).ld(R8::A, R8::L); + store_a(&mut asm, Expr::sym(&self.name), self.region); + asm.ld(R8::A, R8::H); + store_a(&mut asm, Expr::sym(&self.name) + 1, self.region); + } else { + asm.inc(R8::A); + store_a(&mut asm, Expr::sym(&self.name), self.region); + } + asm.into_instrs() + } + /// Get the variable name/label pub fn name(&self) -> &str { &self.name @@ -1098,6 +1125,37 @@ mod tests { assert!(cpu.trace.is_empty(), "get writes nothing: {:?}", cpu.trace); } + #[test] + fn test_increment_adds_one_and_wraps() { + let mut vm = VariableManager::new(); + let olives = vm.create_u16("wOlives", 0x00FF); + let lives = vm.create_u8("wLives", 254); + let fast = vm.create_hram_u8("hFast", 0); + let mut cpu = cpu_after_init(&vm); + cpu.run(&olives.increment()); + assert_eq!( + word(&cpu, "wOlives"), + 0x0100, + "the carry reaches the high byte" + ); + assert_eq!( + u16::from_be_bytes([cpu.h, cpu.l]), + 0x0100, + "the new value in hl" + ); + cpu.run(&olives.set(0xFFFF)); + cpu.run(&olives.increment()); + assert_eq!(word(&cpu, "wOlives"), 0); + cpu.run(&lives.increment()); + assert_eq!((cpu.mem["wLives"], cpu.a), (255, 255)); + cpu.run(&lives.increment()); + assert_eq!(cpu.mem["wLives"], 0, "255 + 1 wraps to 0"); + assert_eq!( + lines(fast.increment()), + ["ldh a, [hFast]", "inc a", "ldh [hFast], a"] + ); + } + #[test] fn test_set_and_get_an_8_bit_variable() { let mut vm = VariableManager::new(); From be404f3af8c341329e92bfbb80cfaa4f1fd24fc4 Mon Sep 17 00:00:00 2001 From: Federico Bassini Date: Fri, 30 Oct 2026 23:38:24 +0100 Subject: [PATCH 3/3] engine: when_composite_free and Direction Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 + Task.md | 2 + src/engine/mod.rs | 3 +- src/engine/sprites.rs | 138 ++++++++++++++++++++++++++++++++++++++---- src/prelude.rs | 10 +-- 5 files changed, 137 insertions(+), 19 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4b62ec7..76d6085 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -36,6 +36,9 @@ together: every breaking change of the refactoring is in this release, so a prog - **Map blocks at run time** (`RustBoy::queue_tile_block_write`): queues a block of map tiles (e.g. a 2x2 metatile) from the map address in `hl`, one VRAM-queue entry a tile. - **`Var::increment`**: adds 1 to an 8- or 16-bit variable, wrapping, and leaves the new value in `a` / `hl`. +- **Free-step checks** (`SpriteManager::when_composite_free`, `engine::Direction`): runs any code when a composite's + hitbox can step towards a direction without touching a solid tile (the check of the blocked moves, which now use it), + e.g. to scroll the background instead of moving the character. - **Cartridge SRAM control** (`stdlib::sram`): enable/disable external RAM on MBC1/MBC5 and select MBC5's 8 KiB RAM bank; persistent save management remains a follow-up. diff --git a/Task.md b/Task.md index 9aa3d22..233d9c3 100644 --- a/Task.md +++ b/Task.md @@ -383,6 +383,8 @@ the next step is Phase 3, and the `refactor` → `main` PR, whose release notes `SpriteManager::when_composite_touches` runs code once for the first solid tile 1 px around a hitbox, on `TileCollision::at_first_solid` (`When::Solid` now compares after each lookup; one point emits the same code); `RustBoy::queue_tile_block_write` queues a WxH block of map tiles from `hl` through the VRAM queue. +- [x] Push-scroll in olive-empire (branch `olive-empire-scroll`): `SpriteManager::when_composite_free(id, Direction, …, + body)` runs `body` when a step is free; the `move_composite_*_blocked` moves are built on it (same asm). - [x] 16-bit math helpers (branch `refactor-p3-math`): unsigned 16-bit add/subtract/compare, 8×8 multiply and 16÷8 divide with documented register/flag contracts. Regression tests link all routines and cover borrow-free subtraction, greater-than comparison, asymmetric diff --git a/src/engine/mod.rs b/src/engine/mod.rs index 84452ec..32ba18c 100644 --- a/src/engine/mod.rs +++ b/src/engine/mod.rs @@ -40,7 +40,8 @@ pub use memory::{HRAM_VARIABLES_END, MemoryRegion}; pub use rustboy::{MusicClock, RustBoy}; pub use scenes::SceneManager; pub use sprites::{ - ANIM_DISABLED, CompositeSpriteId, MetaspritePart, SpriteId, SpriteManager, SpriteSize, + ANIM_DISABLED, CompositeSpriteId, Direction, MetaspritePart, SpriteId, SpriteManager, + SpriteSize, }; pub use tile_collision::{Hitbox, TileCollision, TileCollisionCheck}; pub use tiles::{TileId, TileManager, TileSource, TilemapArea}; diff --git a/src/engine/sprites.rs b/src/engine/sprites.rs index b5c458c..5564de8 100644 --- a/src/engine/sprites.rs +++ b/src/engine/sprites.rs @@ -251,6 +251,31 @@ fn unknown_composite(id: CompositeSpriteId) -> ! { ); } +/// A way a sprite moves on the screen +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Direction { + /// Screen X decreases + Left, + /// Screen X increases + Right, + /// Screen Y decreases + Up, + /// Screen Y increases + Down, +} + +impl Direction { + /// The axis and the way the coordinate changes + fn axis_dir(self) -> (Axis, MoveDir) { + match self { + Direction::Left => (Axis::X, MoveDir::Decrease), + Direction::Right => (Axis::X, MoveDir::Increase), + Direction::Up => (Axis::Y, MoveDir::Decrease), + Direction::Down => (Axis::Y, MoveDir::Increase), + } + } +} + /// The axis a sprite moves along #[derive(Debug, Clone, Copy)] enum Axis { @@ -1148,9 +1173,8 @@ impl SpriteManager { solid: &TileCollision, hitbox: Hitbox, ) -> Vec { - let points = self.blocked_points(id, Axis::X, MoveDir::Decrease, distance, hitbox); let moving = self.move_composite_left_limit(id, distance, limit); - solid.when_free(points, moving).emit(&self.labels) + self.when_composite_free(id, Direction::Left, distance, hitbox, solid, moving) } /// Move a composite sprite right as [`SpriteManager::move_composite_right_limit`] does, @@ -1165,9 +1189,8 @@ impl SpriteManager { solid: &TileCollision, hitbox: Hitbox, ) -> Vec { - let points = self.blocked_points(id, Axis::X, MoveDir::Increase, distance, hitbox); let moving = self.move_composite_right_limit(id, distance, limit); - solid.when_free(points, moving).emit(&self.labels) + self.when_composite_free(id, Direction::Right, distance, hitbox, solid, moving) } /// Move a composite sprite up as [`SpriteManager::move_composite_up_limit`] does, @@ -1182,9 +1205,8 @@ impl SpriteManager { solid: &TileCollision, hitbox: Hitbox, ) -> Vec { - let points = self.blocked_points(id, Axis::Y, MoveDir::Decrease, distance, hitbox); let moving = self.move_composite_up_limit(id, distance, limit); - solid.when_free(points, moving).emit(&self.labels) + self.when_composite_free(id, Direction::Up, distance, hitbox, solid, moving) } /// Move a composite sprite down as [`SpriteManager::move_composite_down_limit`] does, @@ -1199,9 +1221,35 @@ impl SpriteManager { solid: &TileCollision, hitbox: Hitbox, ) -> Vec { - let points = self.blocked_points(id, Axis::Y, MoveDir::Increase, distance, hitbox); let moving = self.move_composite_down_limit(id, distance, limit); - solid.when_free(points, moving).emit(&self.labels) + self.when_composite_free(id, Direction::Down, distance, hitbox, solid, moving) + } + + /// Run `body` when a step of `distance` pixels towards `direction` is free: when the + /// composite's `hitbox` would not step on one of the `solid` background tiles + /// + /// The check of the blocked moves (`move_composite_left_blocked` is this with a limited + /// move as `body`), for a step that does something else: scroll the background instead + /// of moving the character, play a sound, … It reads the same pixels, with the same + /// VRAM-access rule: put it in an input binding (they run at the start of the main loop, + /// in VBlank). + /// + /// # Panics + /// If there is no composite `id`, if `distance` is not in 1..=8 (a longer step could + /// jump over a tile), or if the hitbox does not fit in the composite. + #[track_caller] + pub fn when_composite_free( + &self, + id: CompositeSpriteId, + direction: Direction, + distance: u8, + hitbox: Hitbox, + solid: &TileCollision, + body: impl crate::asm::Emittable + 'static, + ) -> Vec { + let (axis, dir) = direction.axis_dir(); + let points = self.blocked_points(id, axis, dir, distance, hitbox); + solid.when_free(points, body).emit(&self.labels) } /// Run `body` once when the composite's `hitbox` touches one of the `solid` background @@ -1225,13 +1273,16 @@ impl SpriteManager { body: impl crate::asm::Emittable + 'static, ) -> Vec { let points: Vec<_> = [ - (Axis::X, MoveDir::Decrease), - (Axis::X, MoveDir::Increase), - (Axis::Y, MoveDir::Decrease), - (Axis::Y, MoveDir::Increase), + Direction::Left, + Direction::Right, + Direction::Up, + Direction::Down, ] .into_iter() - .flat_map(|(axis, dir)| self.blocked_points(id, axis, dir, 1, hitbox)) + .flat_map(|direction| { + let (axis, dir) = direction.axis_dir(); + self.blocked_points(id, axis, dir, 1, hitbox) + }) .collect(); solid.at_first_solid(points, body).emit(&self.labels) } @@ -2514,6 +2565,67 @@ mod tests { assert_eq!(cpu.a, 255); } + #[test] + fn test_blocked_moves_are_when_composite_free_with_a_limited_move() { + let feet = Hitbox::new(0, 8, 16, 8); + let solid = TileCollision::new([5]); + let text = + |code: Vec| -> Vec { code.iter().map(|i| i.to_string()).collect() }; + for direction in [ + Direction::Left, + Direction::Right, + Direction::Up, + Direction::Down, + ] { + // A fresh game for each, so both get the same local labels + let (gb, player) = player_16x16(); + let blocked = match direction { + Direction::Left => gb + .sprites + .move_composite_left_blocked(player, 2, 8, &solid, feet), + Direction::Right => gb + .sprites + .move_composite_right_blocked(player, 2, 152, &solid, feet), + Direction::Up => gb + .sprites + .move_composite_up_blocked(player, 2, 16, &solid, feet), + Direction::Down => gb + .sprites + .move_composite_down_blocked(player, 2, 144, &solid, feet), + }; + let (gb, player) = player_16x16(); + let moving = match direction { + Direction::Left => gb.sprites.move_composite_left_limit(player, 2, 8), + Direction::Right => gb.sprites.move_composite_right_limit(player, 2, 152), + Direction::Up => gb.sprites.move_composite_up_limit(player, 2, 16), + Direction::Down => gb.sprites.move_composite_down_limit(player, 2, 144), + }; + let free = gb + .sprites + .when_composite_free(player, direction, 2, feet, &solid, moving); + assert_eq!(text(blocked), text(free), "{direction:?}"); + } + // Any body: here one that is not a move + let (gb, player) = player_16x16(); + let lines = text(gb.sprites.when_composite_free( + player, + Direction::Down, + 1, + feet, + &solid, + vec![Instr::Ret], + )); + assert_eq!( + lines + .iter() + .filter(|line| line.contains("call GetTileByScreenPixel")) + .count(), + 3, + "the 3 pixels under the 16-pixel-wide feet: {lines:#?}" + ); + assert!(lines.contains(&"ret".to_string())); + } + #[test] fn test_touching_reads_the_line_around_the_hitbox_and_runs_the_body_once() { let (gb, player) = player_16x16(); diff --git a/src/prelude.rs b/src/prelude.rs index 3afe23b..4ea1a79 100644 --- a/src/prelude.rs +++ b/src/prelude.rs @@ -40,11 +40,11 @@ pub use crate::asm::{ }; pub use crate::engine::{ ANIM_DISABLED, Aabb, AnimationType, ArrayElement, AssetError, BackgroundAnimation, - BackgroundAnimationConfig, BuiltinFunction, Chunk, CompositeSpriteId, Definition, EntityPool, - Error, Font, Hitbox, InputManager, Layout, Lcdc, MemoryRegion, MetaspritePart, NumberFormat, - NumberPrinter, Palettes, PngColorMapping, PngOptions, RustBoy, RustBoyConfig, SceneManager, - SpriteId, SpriteSize, TextPrinter, TileCollision, TileCollisionCheck, TileOrder, TileSource, - TilemapArea, Var, VarType, Window, WramArray, png_to_2bpp, + BackgroundAnimationConfig, BuiltinFunction, Chunk, CompositeSpriteId, Definition, Direction, + EntityPool, Error, Font, Hitbox, InputManager, Layout, Lcdc, MemoryRegion, MetaspritePart, + NumberFormat, NumberPrinter, Palettes, PngColorMapping, PngOptions, RustBoy, RustBoyConfig, + SceneManager, SpriteId, SpriteSize, TextPrinter, TileCollision, TileCollisionCheck, TileOrder, + TileSource, TilemapArea, Var, VarType, Window, WramArray, png_to_2bpp, }; pub use crate::hw; pub use crate::stdlib::flow::{Call, If, IfA, IfCall, IfConst};