Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions crates/core/src/character.rs
Original file line number Diff line number Diff line change
Expand Up @@ -393,6 +393,22 @@ impl Character {
})
}

/// How wide the art is on screen, in points.
///
/// The widest frame the Character declares, not the one drawing now: the
/// Engine is told this once and keeps the feet that far from a display
/// edge for the Character's whole life, so the number has to cover
/// whichever Animation it happens to be playing when it gets there.
pub fn sprite_width(&self) -> f64 {
let widest = self
.animations
.values()
.map(|animation| animation.frame_size.0)
.max()
.unwrap_or_default();
f64::from(widest) * f64::from(self.scale)
}

/// Which Animation actually draws: the one asked for, its optional
/// fallback, or — when it anchors a variant ring — whichever member the
/// elapsed time has cycled to, with the time already spent in its slot.
Expand Down Expand Up @@ -715,6 +731,18 @@ mod tests {
);
}

/// The Engine keeps the feet half a sprite clear of a display edge, so the
/// width it is told is the one on screen: art at scale 3 is three times as
/// wide as the file, and a Character measured by its file would stand a
/// third of the way off the edge.
#[test]
fn a_sprite_is_as_wide_as_its_widest_frame_blown_up_by_its_own_scale() {
let character = load_manifest(&format!("scale = 3\n{}", declaring(&REQUIRED_ANIMATIONS)))
.expect("package is valid");

assert_eq!(character.sprite_width(), 6.0, "2px of art at scale 3");
}

#[test]
fn a_loaded_character_carries_exactly_the_art_its_animations_name() {
let character = load_manifest(&declaring(&REQUIRED_ANIMATIONS)).expect("package is valid");
Expand Down
140 changes: 129 additions & 11 deletions crates/core/src/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -302,10 +302,17 @@ const GRAVITY: f64 = 3600.0;
const CEILING_CLEARANCE: f64 = 128.0;

/// How far from a horizontal display edge the feet must stay so the full
/// sprite is on-screen when standing (not climbing). The Engine does not know
/// the art's size; 64 is 16px at 4×, enough for a character of typical width.
/// sprite is on-screen when standing (not climbing), for an Engine nobody told
/// how wide its Character is. 64 is 16px at 4×, a character of typical width.
/// Climb frames assume the wall is in the middle of the frame, so this inset
/// applies only to non-climb states.
///
/// A default rather than the answer. The art is centred on the feet, so the
/// half that hangs past the outermost edge is drawn by no overlay at all —
/// there is no neighbouring display to finish it, the way there is at a seam.
/// A guess that falls short of a Character's real half-width is that Character
/// standing half off screen, which is what `Engine::with_sprite_width` exists
/// to stop.
const EDGE_CLEARANCE: f64 = 64.0;

/// Points per second squared. The yank gate is this times `YANK_WINDOW_S`:
Expand Down Expand Up @@ -448,6 +455,10 @@ pub struct Engine {
/// proposal that would move the sprite is refused; a Grab, a Throw or
/// losing the ground ends it at once. #177.
poke_cooldown_ms: u32,
/// Half the width of the art drawn over the feet, which is how far from a
/// display edge they must stay for all of it to be on screen.
/// `EDGE_CLEARANCE` until a Character says otherwise.
edge_clearance: f64,
}

impl Engine {
Expand Down Expand Up @@ -489,17 +500,38 @@ impl Engine {
rush_reported: false,
chase_ms: 0,
poke_cooldown_ms: 0,
edge_clearance: EDGE_CLEARANCE,
}
}

/// The Behaviors this Character declares. Nothing else reaches the Engine
/// from a Character Package: art is the renderer's, and a Behavior is
/// Primitives the Engine already owns.
/// The Behaviors this Character declares. The art itself is the renderer's,
/// and a Behavior is Primitives the Engine already owns.
pub fn with_behaviors(mut self, behaviors: BTreeMap<String, Behavior>) -> Self {
self.behaviors = behaviors;
self
}

/// How wide the art drawn over the feet is, in points.
///
/// The one measurement of the art the Engine needs: every edge it keeps the
/// sprite clear of — the display's and the Dock's — is a distance from the
/// feet, and how far that has to be is half a sprite. Without it the Engine
/// falls back to `EDGE_CLEARANCE`, which is a guess.
///
/// The whole frame rather than the opaque pixels in it. A Character resting
/// with its padding off screen looks right and is drawn whole; one measured
/// by its ink would need remeasuring every frame, and the mask is the
/// renderer's business.
/// A width of zero or less is no measurement, and keeps the default: it
/// would otherwise read as a sprite of no width and stand the feet on the
/// display edge itself.
pub fn with_sprite_width(mut self, width: f64) -> Self {
if width > 0.0 {
self.edge_clearance = width / 2.0;
}
self
}

/// The Character's cursor reactions (#152).
pub fn with_cursor_reactions(mut self, near: CursorReaction, rush: CursorReaction) -> Self {
self.near_reaction = near;
Expand Down Expand Up @@ -857,9 +889,11 @@ impl Engine {
&& !self.riding
&& self.coast_s == 0.0;
if stationary {
if let Some((edge_x, face_direction)) = at_horizontal_edge(self.position.x, snapshot) {
// A Perch narrower than `EDGE_CLEARANCE` would lose the sprite
// if the inset ran anyway.
if let Some((edge_x, face_direction)) =
at_horizontal_edge(self.position.x, self.edge_clearance, snapshot)
{
// A Perch narrower than the clearance would lose the sprite if
// the inset ran anyway.
let can_inset = if self.state == State::Perched {
perch_at(
Point {
Expand Down Expand Up @@ -1074,7 +1108,14 @@ impl Engine {
self.position.x += self.velocity.x * dt;

if let Some(wall) = wall_reached(self.position.x, self.velocity.x, snapshot)
.or_else(|| dock_side_reached(self.position, self.velocity.x, snapshot))
.or_else(|| {
dock_side_reached(
self.position,
self.velocity.x,
self.edge_clearance,
snapshot,
)
})
{
// Arriving at a screen edge sideways is a catch, not a stop.
// It also keeps the sprite inside the displays. The Dock's
Expand Down Expand Up @@ -1122,7 +1163,7 @@ impl Engine {
// Dock, not on it. #176.
if let Some(dock) = dock_in(snapshot) {
if self.position.y > dock.y && next_y <= dock.y {
if let Some(x) = dock_top_at(self.position.x, dock) {
if let Some(x) = dock_top_at(self.position.x, self.edge_clearance, dock) {
self.position = Point { x, y: dock.y };
return Some(Contact::Landed(Surface::Perch));
}
Expand Down Expand Up @@ -1160,7 +1201,12 @@ impl Engine {
// longer than the Dock is wide would cross it unseen; the
// snapshot assembler caps `elapsed_ms` at one poll interval,
// which is what keeps a step small.
if let Some(side) = dock_side_reached(self.position, self.velocity.x, snapshot) {
if let Some(side) = dock_side_reached(
self.position,
self.velocity.x,
self.edge_clearance,
snapshot,
) {
self.position.x = side;
self.velocity = Point::default();
return Some(Contact::Wall);
Expand Down Expand Up @@ -5819,6 +5865,41 @@ mod tests {
);
}

/// `EDGE_CLEARANCE` promises the whole sprite is on screen when standing,
/// and guesses at how wide one is. A Character wider than the guess came to
/// rest with its art hanging over the outermost edge, where there is no
/// neighbouring display to draw the rest of it — half a mech, off screen,
/// for as long as it stood there.
#[test]
fn a_sprite_wider_than_the_default_clearance_rests_fully_on_screen() {
// Timber Wolf's canvas at scale 1: a half-width of 88, well over the 64
// an Engine that was never told assumes.
const WIDTH: f64 = 176.0;
let mut engine = Engine::new(Point { x: 950.0, y: 400.0 }).with_sprite_width(WIDTH);

engine.tick(&WorldSnapshot {
cursor: Point { x: 950.0, y: 400.0 },
verbs: vec![Verb::Grab],
..snapshot(100)
});
engine.tick(&WorldSnapshot {
verbs: vec![Verb::Throw {
velocity: Point { x: 500.0, y: 0.0 },
}],
..snapshot(100)
});

let at_rest = settle(&mut engine, &snapshot(100));
let right_edge = one_display().x + one_display().width;
assert_eq!(at_rest.state, State::Grounded, "it settles: {at_rest:?}");
assert!(
at_rest.position.x + WIDTH / 2.0 <= right_edge,
"the art's right edge is off screen: feet at {} put it at {}, past {right_edge}",
at_rest.position.x,
at_rest.position.x + WIDTH / 2.0,
);
}

#[test]
fn climbing_preserves_wall_centered_frames_and_may_clip() {
let mut engine = Engine::new(Point { x: 900.0, y: 400.0 });
Expand All @@ -5842,6 +5923,43 @@ mod tests {
);
}

/// The resting inset grew with the art, and the wall did not move: a climb
/// still catches the outermost edge itself, so a frame drawn with the wall
/// running down its middle still lines up on one. Widening the inset would
/// otherwise have stranded the climb a half-sprite short of the wall, with
/// the sprite hugging nothing.
#[test]
fn a_wide_sprite_climbs_the_wall_it_rests_clear_of() {
const WIDTH: f64 = 176.0;
let mut engine = Engine::new(Point { x: 900.0, y: 400.0 }).with_sprite_width(WIDTH);
let right_edge = one_display().x + one_display().width;

engine.tick(&WorldSnapshot {
cursor: Point { x: 900.0, y: 400.0 },
verbs: vec![Verb::Grab],
..snapshot(100)
});
let climbing = engine.tick(&WorldSnapshot {
verbs: vec![Verb::Throw {
velocity: Point { x: 2000.0, y: 0.0 },
}],
..snapshot(100)
});

assert_eq!(climbing.state, State::Climbing, "it climbs: {climbing:?}");
assert_eq!(
climbing.position.x, right_edge,
"the climb holds the wall itself, whatever the art's width"
);

let at_rest = settle(&mut engine, &snapshot(100));
assert_eq!(
at_rest.position.x,
right_edge - WIDTH / 2.0,
"letting go of the wall stands it clear by its own half-width"
);
}

#[test]
fn dragging_to_the_edge_does_not_snap_position_or_facing() {
let mut engine = Engine::new(Point { x: 900.0, y: 400.0 });
Expand Down
40 changes: 21 additions & 19 deletions crates/core/src/engine/geometry.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! Spatial queries over a `WorldSnapshot`.

use super::{Point, Rect, Window, WorldSnapshot, CEILING_CLEARANCE, EDGE_CLEARANCE};
use super::{Point, Rect, Window, WorldSnapshot, CEILING_CLEARANCE};
use crate::window_source::DOCK_PERCH_ID;

/// A surface the sprite can come to rest on.
Expand Down Expand Up @@ -253,7 +253,7 @@ pub(super) fn dock_in(snapshot: &WorldSnapshot) -> Option<Rect> {
/// appear around a resting sprite when it unhides, and a dropped sprite
/// arrives from above: on a walk the two are the same side, one step away.
///
/// The wall stands `EDGE_CLEARANCE` out from the Dock's own edge — half a
/// The wall stands `clearance` out from the Dock's own edge — half a
/// sprite, the same half `at_horizontal_edge` keeps on screen — because a
/// sprite centered on the edge is already half hidden, walking and climbing.
/// Strictly inside that, so the sprite this puts on the line is beside the
Expand All @@ -273,13 +273,11 @@ pub(super) fn dock_in(snapshot: &WorldSnapshot) -> Option<Rect> {
pub(super) fn dock_side_reached(
position: Point,
velocity_x: f64,
clearance: f64,
snapshot: &WorldSnapshot,
) -> Option<f64> {
let dock = dock_in(snapshot)?;
let (left, right) = (
dock.x - EDGE_CLEARANCE,
dock.x + dock.width + EDGE_CLEARANCE,
);
let (left, right) = (dock.x - clearance, dock.x + dock.width + clearance);
if position.y <= dock.y || position.x <= left || position.x >= right {
return None;
}
Expand Down Expand Up @@ -320,17 +318,17 @@ pub(super) fn dock_side_reached(

/// Where a climb beside the Dock steps onto its top, once the feet reach it.
///
/// `EDGE_CLEARANCE` in from the side it climbed, so the whole sprite stands on
/// Half a sprite in from the side it climbed, so the whole sprite stands on
/// the Dock rather than overhanging the corner — and so it stands somewhere
/// `perch_at` agrees is the Dock, which is what keeps it there. Clamped to the
/// far side for a Dock narrower than a sprite. `None` when the climb is
/// nowhere near the Dock, which is every ordinary climb up a screen edge.
pub(super) fn dock_top_at(x: f64, dock: Rect) -> Option<f64> {
pub(super) fn dock_top_at(x: f64, clearance: f64, dock: Rect) -> Option<f64> {
let (left, right) = (dock.x, dock.x + dock.width);
if (left - EDGE_CLEARANCE..=left + EDGE_CLEARANCE).contains(&x) {
Some((left + EDGE_CLEARANCE).min(right))
} else if (right - EDGE_CLEARANCE..=right + EDGE_CLEARANCE).contains(&x) {
Some((right - EDGE_CLEARANCE).max(left))
if (left - clearance..=left + clearance).contains(&x) {
Some((left + clearance).min(right))
} else if (right - clearance..=right + clearance).contains(&x) {
Some((right - clearance).max(left))
} else if dock.spans_x(x) {
Some(x)
} else {
Expand All @@ -340,7 +338,11 @@ pub(super) fn dock_top_at(x: f64, dock: Rect) -> Option<f64> {

/// Adjusted position and facing when at a horizontal display edge, so the full
/// sprite stays on-screen and faces away from the wall.
pub(super) fn at_horizontal_edge(x: f64, snapshot: &WorldSnapshot) -> Option<(f64, f64)> {
pub(super) fn at_horizontal_edge(
x: f64,
clearance: f64,
snapshot: &WorldSnapshot,
) -> Option<(f64, f64)> {
let left = snapshot
.displays
.iter()
Expand All @@ -353,13 +355,13 @@ pub(super) fn at_horizontal_edge(x: f64, snapshot: &WorldSnapshot) -> Option<(f6
.max_by(f64::total_cmp)?;

// Only correct when very close to the boundary. Sprites that settled
// naturally within EDGE_CLEARANCE but not AT the edge should stay put.
const SNAP_THRESHOLD: f64 = EDGE_CLEARANCE / 2.0;
// naturally within a half-sprite of the edge but not AT it should stay put.
let snap_threshold = clearance / 2.0;

if x <= left + SNAP_THRESHOLD {
Some((left + EDGE_CLEARANCE, 1.0))
} else if x >= right - SNAP_THRESHOLD {
Some((right - EDGE_CLEARANCE, -1.0))
if x <= left + snap_threshold {
Some((left + clearance, 1.0))
} else if x >= right - snap_threshold {
Some((right - clearance, -1.0))
} else {
None
}
Expand Down
39 changes: 38 additions & 1 deletion crates/core/src/roster.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,8 @@ impl Roster {
let id = uuid::Uuid::new_v4().to_string();
let engine = Engine::new(position)
.with_behaviors(character.behaviors.clone())
.with_cursor_reactions(character.near_reaction, character.rush_reaction);
.with_cursor_reactions(character.near_reaction, character.rush_reaction)
.with_sprite_width(character.sprite_width());
let instance = Instance {
id: id.clone(),
name,
Expand Down Expand Up @@ -330,6 +331,42 @@ mod tests {
);
}

/// A spawned Instance measures its own Character. The Engine's fallback
/// clearance is a guess at how wide a sprite is, and a Character wider than
/// the guess came to rest with its art hanging over the outermost display
/// edge, where no overlay draws it.
#[test]
fn a_spawned_instance_keeps_its_own_width_clear_of_the_display_edge() {
let memory = MemoryManifest::new(std::env::temp_dir().join("test-wide.md"));
let mut roster = Roster::new(memory);
let mut character = test_character("Wide");
for animation in character.animations.values_mut() {
animation.frame_size = (400, 400);
}

let id = roster.spawn(
&character,
"Wide One".to_string(),
Point {
x: 1900.0,
y: 100.0,
},
);
let instance = roster.get_mut(&id).expect("the Instance was just spawned");
let at_rest = (0..120)
.map(|_| instance.tick(&test_snapshot()))
.last()
.expect("the ticks produce frames");

let right_edge = 1920.0;
assert!(
at_rest.position.x + 200.0 <= right_edge,
"the art's right edge is off screen: feet at {} put it at {}",
at_rest.position.x,
at_rest.position.x + 200.0,
);
}

#[test]
fn two_instances_of_the_same_character_play_different_behaviors_independently() {
let memory = MemoryManifest::new(std::env::temp_dir().join("test-independent.md"));
Expand Down
Loading