emberline/
lib.rs

1//! A small precision platformer: no assets, a fixed simulation, and forgiving jumps.
2//!
3//! The native entry point opens the interactive renderer. The browser retains the
4//! exports generated by `ferravex_render::game!`.
5//!
6//! ```no_run
7//! emberline::run();
8//! ```
9//!
10//! The private simulation and its tests use the same session as the host: Ready
11//! waits for confirmation, Paused freezes the trial, and Won freezes the result.
12//! Fixed-tick input is consumed only when `GameSession::advance` schedules work.
13mod animation;
14#[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
15mod capture;
16mod compact;
17mod hud;
18#[cfg(test)]
19mod journey200_tests;
20mod juice;
21mod presentation;
22mod quips;
23mod style;
24use animation::EmberAnimation;
25use ferravex_core::session::{GameSession, SessionState};
26use ferravex_physics::character::{
27    Character, CharacterInput, CharacterSettings, CharacterShape, Obstacle, QueryBounds, Terrain,
28};
29use ferravex_play::camera::{Follow2, Follow2Settings, Limits2};
30use ferravex_play::feedback::FeedbackPolicy;
31use ferravex_play::gameplay::checkpoint::CheckpointActivation;
32use ferravex_render::audio::{Cue, GameAudio, Surface};
33use ferravex_render::input::{
34    HintDevice, PlayerInput, Preset,
35    touch::{Control, Output, Region},
36};
37use ferravex_render::{demo::Demo, prelude::*};
38use juice::Juice;
39use presentation::{
40    apply_policy, motion_scale, sync_audio, sync_preferences, touch_button_matches,
41};
42use quips::DeathCause;
43
44const WIDTH: f32 = 1280.0;
45const HEIGHT: f32 = 720.0;
46const WORLD_END: f32 = 2700.0;
47const PLAYER: Vec2 = Vec2::new(24.0, 40.0);
48const SPEED: f32 = 280.0;
49const GRAVITY: f32 = 1600.0;
50const JUMP: f32 = 660.0;
51const COYOTE: f32 = 0.10;
52const BUFFER: f32 = 0.12;
53const ORANGE: Color = Color::new(1.0, 0.54, 0.25, 1.0);
54const CREAM: Color = Color::new(0.96, 0.88, 0.72, 1.0);
55const GREEN: Color = Color::new(0.48, 0.68, 0.48, 1.0);
56/// Gold/silver/bronze trial targets in seconds.
57const MEDALS: [f32; 3] = [12., 18., 30.];
58/// The secret moth hovers above the Furnace spring: reachable only with a
59/// spring or full jump plus the earned air jump.
60const MOTH_AT: Vec2 = Vec2::new(2070., 160.);
61const MOTH_POINTS: u32 = 500;
62/// Feet within this many units above spikes, then a safe landing, is a close call.
63const CLOSE_CALL: f32 = 26.;
64const LIFT_X: f32 = 2590.;
65/// Section names; the HUD draws the section number beside them.
66const ZONES: [&str; 3] = ["THE TREELINE", "THE OLD MILL", "THE FURNACE"];
67
68/// Where each numbered lantern is drawn, beside (not under) its spring platform.
69fn lantern_position(index: usize) -> Vec2 {
70    vec2(if index <= 1 { 1494. } else { 2152. }, 474.)
71}
72
73/// Spikes are triangles: their outer corners and very tips do not hurt.
74fn hazard_hitbox(h: &Rect) -> Rect {
75    Rect::new(h.x + 4., h.y + 6., h.w - 8., h.h - 6.)
76}
77
78#[derive(Default, Clone, Copy)]
79struct Input {
80    direction: f32,
81    // An already consumed press edge, not the physical held state.
82    jump: bool,
83    jump_held: bool,
84}
85
86#[derive(Default, Clone, Copy)]
87struct Feedback {
88    jumped: bool,
89    landed: bool,
90    pickup: bool,
91    checkpoint: bool,
92    respawned: bool,
93    won: bool,
94    /// The jump this tick was the earned mid-air jump.
95    air_jumped: bool,
96    /// Points actually awarded this tick by embers or the moth.
97    pickup_points: u64,
98    pickup_at: Vec2,
99    /// The chain multiplier rose to this value this tick.
100    chain_up: Option<u32>,
101    air_jump_unlocked: bool,
102    close_call: bool,
103    secret: bool,
104    /// Index of a mid-course split recorded this tick (0 = mill, 1 = furnace).
105    split: Option<usize>,
106}
107
108struct Game {
109    session: GameSession,
110    motor: Character,
111    platforms: Vec<Rect>,
112    hazards: Vec<Rect>,
113    embers: Vec<(Vec2, bool)>,
114    checkpoints: ferravex_play::gameplay::checkpoint::Checkpoints<Vec2, 3>,
115    deaths: u32,
116    score: ferravex_play::gameplay::combo::ScoreChain,
117    jumps: u32,
118    ember_inventory: ferravex_play::gameplay::inventory::Inventory<1>,
119    air_jump_used: bool,
120    springs: [ferravex_play::gameplay::platforms::LaunchPad; 3],
121    spring_flight: bool,
122    crumbles: [ferravex_play::gameplay::platforms::CrumblePlatform; 2],
123    elapsed: f32,
124    trial: ferravex_play::gameplay::trial::Trial<3>,
125    respawn_notice: f32,
126    feedback: Feedback,
127    jump_feedback: f32,
128    landing_feedback: f32,
129    landing_at: Vec2,
130    landing_strength: f32,
131    checkpoint_notice: f32,
132    death_cause: DeathCause,
133    death_at: Vec2,
134    /// Falls since the latest lantern (or the trailhead); drives quips.
135    deaths_here: u32,
136    close_calls: u32,
137    /// Airborne feet skimmed spikes this arc; a safe landing makes it a close call.
138    skim: bool,
139    secret: bool,
140}
141
142impl Game {
143    fn new(autoplay: bool) -> Self {
144        Self {
145            session: GameSession::new(120.0, 12, autoplay),
146            motor: Character::new(feet(vec2(90.0, 520.0))),
147            platforms: vec![
148                Rect::new(-100.0, 560.0, 680.0, 250.0),
149                Rect::new(700.0, 560.0, 500.0, 250.0),
150                Rect::new(1320.0, 560.0, 500.0, 250.0),
151                Rect::new(1940.0, 560.0, 850.0, 250.0),
152                Rect::new(140.0, 445.0, 80.0, 18.0),
153                Rect::new(770.0, 435.0, 130.0, 18.0),
154                Rect::new(1350.0, 430.0, 120.0, 18.0),
155                Rect::new(2010.0, 430.0, 120.0, 18.0),
156                Rect::new(380., 330., 110., 18.),
157                Rect::new(1640., 315., 110., 18.),
158            ],
159            hazards: vec![
160                Rect::new(350.0, 542.0, 44.0, 18.0),
161                Rect::new(1040.0, 542.0, 56.0, 18.0),
162                Rect::new(1600.0, 542.0, 52.0, 18.0),
163                Rect::new(2230.0, 542.0, 56.0, 18.0),
164            ],
165            embers: [
166                (180.0, 406.0),
167                (375.0, 455.0),
168                (640.0, 470.0),
169                (835.0, 395.0),
170                (1070.0, 455.0),
171                (1260.0, 470.0),
172                (1410.0, 390.0),
173                (1880.0, 470.0),
174                (2070.0, 390.0),
175                (2430.0, 520.0),
176                (425., 300.),
177                (1695., 285.),
178            ]
179            .into_iter()
180            .map(|(x, y)| (vec2(x, y), false))
181            .collect(),
182            checkpoints: ferravex_play::gameplay::checkpoint::Checkpoints::new(
183                0x454d4232,
184                [vec2(90., 520.), vec2(1410., 520.), vec2(2050., 520.)],
185            )
186            .unwrap(),
187            deaths: 0,
188            score: ferravex_play::gameplay::combo::ScoreChain::new(5., 2, 4).unwrap(),
189            jumps: 0,
190            ember_inventory: ferravex_play::gameplay::inventory::Inventory::new().unwrap(),
191            air_jump_used: false,
192            springs: [ferravex_play::gameplay::platforms::LaunchPad::new(780., 0.25).unwrap(); 3],
193            spring_flight: false,
194            crumbles: [ferravex_play::gameplay::platforms::CrumblePlatform::new(0.65, 3.).unwrap();
195                2],
196            elapsed: 0.0,
197            trial: {
198                let mut t = ferravex_play::gameplay::trial::Trial::new(MEDALS).unwrap();
199                t.start();
200                t
201            },
202            respawn_notice: 0.0,
203            feedback: Feedback::default(),
204            jump_feedback: 0.,
205            landing_feedback: 0.,
206            landing_at: Vec2::ZERO,
207            landing_strength: 0.,
208            checkpoint_notice: 0.,
209            death_cause: DeathCause::default(),
210            death_at: Vec2::ZERO,
211            deaths_here: 0,
212            close_calls: 0,
213            skim: false,
214            secret: false,
215        }
216    }
217
218    fn won(&self) -> bool {
219        self.session.state() == SessionState::Won
220    }
221
222    fn restart(&mut self) {
223        *self = Self::new(false);
224        self.session.restart();
225    }
226
227    // Menu edges are handled once per render frame, before fixed simulation.
228    // Returning true tells presentation to discard camera/audio/animation history.
229    fn menu(&mut self, restart: bool, confirm: bool, pause: bool) -> bool {
230        if restart
231            || confirm && matches!(self.session.state(), SessionState::Won | SessionState::Lost)
232        {
233            self.restart();
234            return true;
235        }
236        if confirm && self.session.state() == SessionState::Ready {
237            self.session.start();
238        } else if (confirm && self.session.is_paused() || pause) && self.session.toggle_pause() {
239            // A buffered jump must not fire after a menu visit.
240            self.cancel_jump();
241        }
242        false
243    }
244
245    fn cancel_jump(&mut self) {
246        self.motor.jump.buffer = 0.;
247        self.motor.jump.held = false;
248    }
249
250    fn gate_input(&mut self, active: bool) {
251        if !active {
252            self.cancel_jump();
253        }
254    }
255
256    fn advance(
257        &mut self,
258        elapsed_seconds: f64,
259        mut input: impl FnMut(&Self) -> Input,
260        mut after_tick: impl FnMut(&mut Self, f32),
261    ) -> f32 {
262        let frame = self.session.advance(elapsed_seconds);
263        let mut simulated = 0.;
264        for _ in 0..frame.steps {
265            if !self.session.is_playing() {
266                break;
267            }
268            self.update(input(self), frame.dt);
269            simulated += frame.dt;
270            after_tick(self, frame.dt);
271        }
272        simulated
273    }
274
275    fn position(&self) -> Vec2 {
276        vec2(
277            self.motor.position.x - PLAYER.x * 0.5,
278            -self.motor.position.y - PLAYER.y,
279        )
280    }
281    fn velocity(&self) -> Vec2 {
282        vec2(self.motor.velocity.x, -self.motor.velocity.y)
283    }
284    fn body(&self) -> Rect {
285        Rect::new(self.position().x, self.position().y, PLAYER.x, PLAYER.y)
286    }
287
288    fn respawn(&mut self) {
289        self.motor = Character::new(feet(self.checkpoints.recovery().current.anchor));
290        for platform in &mut self.crumbles {
291            platform.reset();
292        }
293        self.air_jump_used = false;
294        self.spring_flight = false;
295        self.skim = false;
296        self.deaths += 1;
297        self.deaths_here += 1;
298        self.score.break_chain();
299        self.respawn_notice = 0.6;
300        self.jump_feedback = 0.;
301        self.landing_feedback = 0.;
302        self.feedback = Feedback {
303            respawned: true,
304            ..Feedback::default()
305        };
306    }
307
308    fn update(&mut self, input: Input, dt: f32) {
309        self.feedback = Feedback::default();
310        if !self.session.is_playing() {
311            return;
312        }
313        let grounded = self.motor.grounded;
314        let landing_speed = self.velocity().y.max(0.);
315        let jumps = self.jumps;
316        self.elapsed += dt;
317        self.trial.advance(dt).unwrap();
318        self.score.advance(dt).unwrap();
319        self.respawn_notice = (self.respawn_notice - dt).max(0.0);
320        self.jump_feedback = (self.jump_feedback - dt).max(0.);
321        self.landing_feedback = (self.landing_feedback - dt).max(0.);
322        self.checkpoint_notice = (self.checkpoint_notice - dt).max(0.);
323        for (mechanism, surface) in self.crumbles.iter_mut().zip(&self.platforms[8..10]) {
324            let contact = self.motor.grounded
325                && (-self.motor.position.y - surface.y).abs() < 1.
326                && (self.motor.position.x - surface.center().x).abs() < surface.w * 0.5;
327            mechanism.step(dt, contact).unwrap();
328        }
329        // A side platform moves before the motor, so standing passengers inherit its pose.
330        self.platforms[5].x = 770.0 + (self.elapsed * 1.2).sin() * 28.0;
331        // PlayerInput already detects presses. Two fresh presses can arrive on
332        // adjacent ticks; do not run held-button edge detection a second time.
333        self.motor.jump.held = false;
334        let result = self
335            .motor
336            .step(
337                &EmberTerrain(&self.platforms, self.crumbles.map(|c| !c.solid())),
338                CharacterShape::Box2 { half: PLAYER * 0.5 },
339                CharacterSettings {
340                    speed: SPEED,
341                    gravity: GRAVITY,
342                    jump_speed: JUMP,
343                    terminal_speed: 1000.,
344                    ground_acceleration: 2400.,
345                    air_acceleration: 1600.,
346                    coyote_time: COYOTE,
347                    jump_buffer: BUFFER,
348                    ground_snap: 0.1,
349                    step_height: 0.,
350                    max_recovery: 24.,
351                    ..Default::default()
352                },
353                CharacterInput {
354                    direction: vec3(input.direction, 0., 0.),
355                    jump: input.jump,
356                },
357                dt,
358            )
359            .expect("authored Emberline character terrain");
360        self.jumps += u32::from(result.jumped);
361        self.feedback.landed = !grounded && self.motor.grounded && landing_speed > 50.;
362        if self.motor.grounded {
363            self.air_jump_used = false;
364        }
365        if input.jump
366            && !result.jumped
367            && !self.motor.grounded
368            && self.motor.jump.coyote == 0.
369            && !self.air_jump_used
370            && self.ember_inventory.count(1) >= 3
371        {
372            self.motor.velocity.y = JUMP * 0.85;
373            self.motor.jump.buffer = 0.;
374            self.air_jump_used = true;
375            self.jumps += 1;
376            self.feedback.air_jumped = true;
377        }
378        if self.motor.grounded {
379            self.spring_flight = false;
380        }
381        for (pad, platform) in self.springs.iter_mut().zip([4, 6, 7]) {
382            let surface = self.platforms[platform];
383            let contact = self.motor.grounded
384                && self.motor.velocity.y <= 0.
385                && (self.motor.position.x - surface.center().x).abs() < 25.
386                && (-self.motor.position.y - surface.y).abs() < 1.;
387            if let Some(speed) = pad.step(dt, contact).unwrap() {
388                self.motor.velocity.y = speed;
389                self.motor.grounded = false;
390                self.motor.jump.coyote = 0.;
391                self.motor.jump.buffer = 0.;
392                self.spring_flight = true;
393                self.feedback.jumped = true;
394            }
395        }
396        // Release makes a short hop; holding keeps the full gap-clearing arc.
397        // Cutting velocity once avoids applying a frame-rate-dependent force.
398        if !self.spring_flight
399            && !result.jumped
400            && !input.jump_held
401            && !input.jump
402            && self.motor.velocity.y > JUMP * 0.45
403        {
404            self.motor.velocity.y = JUMP * 0.45;
405        }
406        self.motor.position.x = self
407            .motor
408            .position
409            .x
410            .clamp(PLAYER.x * 0.5, WORLD_END - PLAYER.x * 0.5);
411        let body = self.body();
412        let spiked = self
413            .hazards
414            .iter()
415            .any(|h| body.overlaps(&hazard_hitbox(h)));
416        if self.position().y > 780.0 || spiked {
417            self.death_cause = if spiked {
418                DeathCause::Spikes
419            } else {
420                DeathCause::Fissure
421            };
422            self.death_at = self.position();
423            self.respawn();
424            return;
425        }
426        // Skimming the spike tips in the air, then landing safely, is a close call.
427        if !self.motor.grounded {
428            let feet = body.bottom();
429            self.skim |= self.hazards.iter().any(|h| {
430                body.right() > h.x
431                    && body.x < h.right()
432                    && feet > h.y - CLOSE_CALL
433                    && feet <= h.y + 6.
434            });
435        } else if !grounded && self.skim {
436            self.skim = false;
437            self.close_calls += 1;
438            self.feedback.close_call = true;
439        }
440        self.feedback.jumped |= self.jumps > jumps;
441        if self.feedback.jumped {
442            self.jump_feedback = 0.18;
443        }
444        if self.feedback.landed {
445            self.landing_feedback = 0.24;
446            self.landing_at = self.position() + vec2(PLAYER.x * 0.5, PLAYER.y);
447            self.landing_strength = (landing_speed / 700.).clamp(0.25, 1.);
448        }
449        let unlocked_before = self.ember_inventory.count(1) >= 3;
450        for (position, collected) in &mut self.embers {
451            if !*collected
452                && body.overlaps(&Rect::new(position.x - 12.0, position.y - 12.0, 24.0, 24.0))
453            {
454                *collected = true;
455                self.feedback.pickup = true;
456                award(&mut self.score, &mut self.feedback, 100, *position);
457                self.ember_inventory
458                    .add(ferravex_play::gameplay::inventory::Stack {
459                        item: 1,
460                        amount: 1,
461                        limit: 32,
462                    })
463                    .unwrap();
464            }
465        }
466        if !unlocked_before && self.ember_inventory.count(1) >= 3 {
467            self.feedback.air_jump_unlocked = true;
468        }
469        if !self.secret && body.overlaps(&Rect::new(MOTH_AT.x - 12., MOTH_AT.y - 12., 24., 24.)) {
470            self.secret = true;
471            self.feedback.secret = true;
472            self.feedback.pickup = true;
473            award(&mut self.score, &mut self.feedback, MOTH_POINTS, MOTH_AT);
474        }
475        if self.position().x > 1380.0 && self.position().x < 1490.0 && self.motor.grounded {
476            self.feedback.checkpoint |= matches!(
477                self.checkpoints.activate_with_outcome(1).unwrap(),
478                CheckpointActivation::Activated { .. }
479            );
480        }
481        if self.checkpoints.index() == 1
482            && self.position().x > 2020.
483            && self.position().x < 2140.
484            && self.motor.grounded
485        {
486            self.feedback.checkpoint |= matches!(
487                self.checkpoints.activate_with_outcome(2).unwrap(),
488                CheckpointActivation::Activated { .. }
489            );
490        }
491        if self.feedback.checkpoint {
492            self.checkpoint_notice = 2.5;
493            self.deaths_here = 0;
494        }
495        for (split, x) in [(0, 900.), (1, 1800.)] {
496            if self.position().x >= x && self.trial.splits()[split].is_none() {
497                self.trial.split(split).unwrap();
498                self.feedback.split = Some(split);
499            }
500        }
501        if self.position().x > 2560.0 && self.motor.grounded {
502            self.trial.split(2).unwrap();
503            self.feedback.won = self.session.finish(true);
504        }
505    }
506
507    fn autoplay(&self) -> Input {
508        let front = self.position().x + PLAYER.x;
509        let hazard = self
510            .hazards
511            .iter()
512            .any(|h| h.x >= front - 2.0 && h.x - front < 74.0);
513        let gap = self
514            .platforms
515            .iter()
516            .filter(|p| p.y == 560.0)
517            .any(|p| front > p.x && front <= p.right() && p.right() - front < 58.0);
518        Input {
519            direction: 1.0,
520            jump: self.motor.grounded && (hazard || gap),
521            jump_held: true,
522        }
523    }
524}
525
526/// Award through the shared chain and describe the accepted result for feedback.
527fn award(
528    score: &mut ferravex_play::gameplay::combo::ScoreChain,
529    feedback: &mut Feedback,
530    base: u32,
531    at: Vec2,
532) {
533    let before = if score.chain() == 0 {
534        1
535    } else {
536        score.multiplier()
537    };
538    if let Some(receipt) = score.award_with_receipt(base) {
539        feedback.pickup_points += receipt.total_change;
540        feedback.pickup_at = at;
541        if receipt.multiplier > before {
542            feedback.chain_up = Some(receipt.multiplier);
543        }
544    }
545}
546
547fn feet(position: Vec2) -> Vec3 {
548    vec3(position.x + PLAYER.x * 0.5, -position.y - PLAYER.y, 0.)
549}
550struct EmberTerrain<'a>(&'a [Rect], [bool; 2]);
551impl EmberTerrain<'_> {
552    fn obstacle_at(&self, i: usize) -> Obstacle {
553        let p = self.0[i];
554        let mut obstacle = Obstacle::cuboid(
555            i as u64,
556            vec3(p.x + p.w * 0.5, -p.y - p.h * 0.5, 0.),
557            vec3(p.w * 0.5, p.h * 0.5, 1.),
558        );
559        obstacle.sensor = (8..10).contains(&i) && self.1[i - 8];
560        obstacle
561    }
562}
563impl Terrain for EmberTerrain<'_> {
564    fn visit(&self, bounds: QueryBounds, visitor: &mut dyn FnMut(Obstacle)) {
565        for i in 0..self.0.len() {
566            let o = self.obstacle_at(i);
567            if bounds.intersects(o.bounds()) {
568                visitor(o);
569            }
570        }
571    }
572    fn obstacle(&self, id: u64) -> Option<Obstacle> {
573        ((id as usize) < self.0.len()).then(|| self.obstacle_at(id as usize))
574    }
575}
576
577fn diamond(position: Vec2, radius: f32, color: Color) {
578    draw_triangle(
579        position + vec2(0.0, -radius),
580        position + vec2(radius * 0.65, 0.0),
581        position + vec2(0.0, radius),
582        color,
583    );
584    draw_triangle(
585        position + vec2(0.0, -radius),
586        position + vec2(0.0, radius),
587        position - vec2(radius * 0.65, 0.0),
588        Color::new(color.r * 0.7, color.g * 0.7, color.b * 0.7, color.a),
589    );
590}
591
592fn tree(x: f32, y: f32, size: f32, color: Color) {
593    draw_rectangle(
594        x - size * 0.04,
595        y - size * 0.45,
596        size * 0.08,
597        size * 0.45,
598        color,
599    );
600    draw_triangle(
601        vec2(x, y - size),
602        vec2(x - size * 0.35, y - size * 0.2),
603        vec2(x + size * 0.3, y - size * 0.2),
604        color,
605    );
606    draw_triangle(
607        vec2(x, y - size * 1.2),
608        vec2(x - size * 0.25, y - size * 0.5),
609        vec2(x + size * 0.25, y - size * 0.5),
610        color,
611    );
612}
613
614fn world(
615    game: &Game,
616    camera: f32,
617    time: f32,
618    motion: &EmberAnimation,
619    policy: FeedbackPolicy,
620    juice: &Juice,
621) {
622    let movement = motion_scale(policy);
623    let scenery_camera = camera * movement;
624    clear_background(Color::from_hex(0x242c2b));
625    draw_circle(
626        1040.0 - scenery_camera * 0.12,
627        160.0,
628        86.0,
629        Color::from_hex(0xa97043),
630    );
631    for i in 0..12 {
632        let x = i as f32 * 330.0 - scenery_camera * 0.22 - 140.0;
633        draw_triangle(
634            vec2(x, 510.0),
635            vec2(x + 210.0, 175.0 + (i % 3) as f32 * 50.0),
636            vec2(x + 450.0, 510.0),
637            Color::from_hex(0x34413b),
638        );
639    }
640    for i in 0..32 {
641        tree(
642            i as f32 * 130.0 - scenery_camera * 0.52,
643            570.0,
644            140.0 + (i % 4) as f32 * 40.0,
645            Color::from_hex(0x28352f),
646        );
647    }
648    for i in 0..8 {
649        let x = 800.0 + i as f32 * 290.0 - scenery_camera * 0.8;
650        draw_rectangle(x, 260.0, 12.0, 300.0, Color::from_hex(0x1e2926));
651        draw_line(x, 268.0, x + 280.0, 290.0, 4.0, Color::from_hex(0x1e2926));
652        draw_line(
653            x + 100.0,
654            275.0,
655            x + 100.0,
656            325.0,
657            2.0,
658            Color::from_hex(0x1e2926),
659        );
660        draw_circle(x + 100.0, 328.0, 4.0, ORANGE);
661    }
662    // Deep hot fissures provide an unmistakable landing boundary.
663    draw_rectangle(0.0, 645.0, WIDTH, 75.0, Color::from_hex(0x8c452c));
664    for i in 0..if movement > 0. { 40 } else { 0 } {
665        let x = (i as f32 * 119.0 + time * 12.0).rem_euclid(WIDTH);
666        let y = 675.0 - ((time * 25.0 + i as f32 * 39.0) % 180.0);
667        draw_circle(x, y, 1.5, Color::new(1.0, 0.52, 0.22, 0.45 * movement));
668    }
669    for (index, p) in game.platforms.iter().enumerate() {
670        if index >= 8 && !game.crumbles[index - 8].solid() {
671            continue;
672        }
673        let x = p.x - camera;
674        if index >= 8 {
675            let warning = game.crumbles[index - 8].phase()
676                == ferravex_play::gameplay::platforms::PlatformPhase::Warning;
677            draw_rectangle_lines(
678                x - 2.,
679                p.y - 2.,
680                p.w + 4.,
681                p.h + 4.,
682                2.,
683                if warning { ORANGE } else { GREEN },
684            );
685        }
686        draw_rectangle(x, p.y, p.w, p.h, Color::from_hex(0x383c32));
687        draw_rectangle(x, p.y, p.w, 7.0, Color::from_hex(0x8d8962));
688        draw_rectangle(x, p.y + 7.0, p.w, 8.0, Color::from_hex(0x545942));
689        if p.h > 100.0 {
690            for i in 0..(p.w / 64.0) as usize {
691                let rx = x + i as f32 * 64.0;
692                draw_triangle(
693                    vec2(rx, 598.0),
694                    vec2(rx + 50.0, 585.0),
695                    vec2(rx + 33.0, 684.0),
696                    Color::from_hex(0x30372f),
697                );
698            }
699        } else {
700            draw_line(
701                x + 8.0,
702                p.y + p.h,
703                x + 8.0,
704                560.0,
705                3.0,
706                Color::from_hex(0x62634d),
707            );
708            draw_line(
709                x + p.w - 8.0,
710                p.y + p.h,
711                x + p.w - 8.0,
712                560.0,
713                3.0,
714                Color::from_hex(0x62634d),
715            );
716        }
717    }
718    for index in [4, 6, 7] {
719        let p = game.platforms[index];
720        draw_rectangle(p.center().x - 25. - camera, p.y - 5., 50., 5., GREEN);
721        // A rising chevron says "launch" without a word.
722        let lift = (time * 3. + index as f32).sin().max(0.) * 2. * movement;
723        let x = p.center().x - camera;
724        ferravex_render::shapes::polyline(
725            &[
726                vec2(x - 7., p.y - 9. - lift),
727                vec2(x, p.y - 16. - lift),
728                vec2(x + 7., p.y - 9. - lift),
729            ],
730            ferravex_render::shapes::Stroke::new(3., GREEN)
731                .cap(ferravex_render::shapes::Cap::Round)
732                .join(ferravex_render::shapes::Join::Round),
733        );
734    }
735    for h in &game.hazards {
736        for i in 0..4 {
737            let x = h.x - camera + i as f32 * h.w / 4.0;
738            draw_triangle(
739                vec2(x, h.bottom()),
740                vec2(x + h.w / 8.0, h.y),
741                vec2(x + h.w / 4.0, h.bottom()),
742                ORANGE,
743            );
744        }
745    }
746    for (position, collected) in &game.embers {
747        if !collected {
748            let at = *position - vec2(camera, 0.0)
749                + vec2(0.0, (time * 3.0 + position.x).sin() * 3.0 * movement);
750            diamond(at, 10.0, ORANGE);
751        }
752    }
753    if !game.secret {
754        moth(MOTH_AT - vec2(camera, 0.), time, movement);
755    }
756    // A filled flame (not color alone) marks lit lanterns; the number plate
757    // and HUD pips identify them. Only the next lantern carries a short hint.
758    for index in 1..=2 {
759        let at = lantern_position(index) - vec2(camera, 0.);
760        let lit = game.checkpoints.index() >= index;
761        let flare = juice.flare[index - 1];
762        if lit {
763            let pulse = 1. + (time * 2.6 + index as f32).sin() * 0.06 * movement;
764            draw_circle(at.x, at.y, 52. * pulse, Color::new(1., 0.62, 0.28, 0.08));
765            draw_circle(at.x, at.y, 30. * pulse, Color::new(1., 0.68, 0.32, 0.14));
766        }
767        if flare > 0. {
768            // A brief warm bloom as the wick catches; cleared under reduced flash.
769            draw_circle(
770                at.x,
771                at.y,
772                26. + 22. * (1. - flare),
773                Color::new(1., 0.78, 0.36, 0.45 * flare),
774            );
775        }
776        draw_rectangle(
777            at.x - 3.,
778            at.y + 15.,
779            6.,
780            560. - at.y - 15.,
781            Color::from_hex(0x70715a),
782        );
783        let frame = if lit {
784            juice::GOLD
785        } else {
786            Color::from_hex(0xb9b49a)
787        };
788        draw_triangle(
789            vec2(at.x - 17., at.y - 15.),
790            vec2(at.x + 17., at.y - 15.),
791            vec2(at.x, at.y - 27.),
792            frame,
793        );
794        draw_rectangle(at.x - 14., at.y - 15., 28., 30., Color::from_hex(0x1a2420));
795        draw_rectangle_lines(at.x - 14., at.y - 15., 28., 30., 3., frame);
796        if lit {
797            let flicker = 1. + (time * 11. + index as f32 * 2.).sin() * 0.12 * movement;
798            diamond(vec2(at.x, at.y + 1.), 9. * flicker, ORANGE);
799            diamond(vec2(at.x, at.y + 3.), 4. * flicker, juice::GOLD);
800        }
801        draw_rectangle(at.x - 10., at.y + 30., 20., 20., Color::from_hex(0x1a2420));
802        centered_label(&index.to_string(), at.x + 1., at.y + 46., 16., frame);
803        if !lit && game.checkpoints.index() + 1 == index && (40. ..WIDTH - 40.).contains(&at.x) {
804            save_marker(
805                at,
806                time,
807                movement,
808                hud::coach(game) == Some(hud::Coach::Lantern),
809            );
810        }
811    }
812    // The exit lift: a car inside a green frame, with a beacon. It rises on a win.
813    let exit = LIFT_X - camera;
814    let rise = if game.won() {
815        (juice.celebrate * 140.).min(150.) * juice.motion().min(1.)
816    } else {
817        0.
818    };
819    // A shaft of rails climbs out of the night, so the car has somewhere to go.
820    let rail = Color::from_hex(0x1e2a26);
821    draw_rectangle(
822        exit - 33.,
823        -200.,
824        66.,
825        650.,
826        Color::new(0.07, 0.11, 0.10, 0.55),
827    );
828    for side in [-31., 27.] {
829        draw_rectangle(exit + side, -200., 4., 650., rail);
830    }
831    for rung in 0..8 {
832        let y = 430. - rung as f32 * 64.;
833        draw_line(exit - 29., y, exit + 29., y - 18., 2., rail);
834    }
835    draw_rectangle(exit - 35.0, 450.0, 70.0, 110.0, Color::from_hex(0x1a2925));
836    let blink = if movement > 0. {
837        0.55 + 0.45 * (time * 5.).sin().max(0.)
838    } else {
839        1.
840    };
841    draw_circle(exit, 416., 6., Color::new(GREEN.r, GREEN.g, GREEN.b, blink));
842    draw_circle(
843        exit,
844        416.,
845        14.,
846        Color::new(GREEN.r, GREEN.g, GREEN.b, 0.15 * blink),
847    );
848    // The finish flag matches the one at the end of the HUD course track.
849    ferravex_render::icons::draw_styled(
850        ferravex_render::icons::Icon::Flag,
851        vec2(exit + 2., 386. + (time * 2.).sin() * 2. * movement),
852        24.,
853        ferravex_render::icons::IconStyle::new(Color::new(
854            GREEN.r,
855            GREEN.g,
856            GREEN.b,
857            0.6 + 0.4 * blink,
858        ))
859        .shadow(Color::new(0.02, 0.03, 0.03, 0.6)),
860    );
861    draw_rectangle(exit - 27., 456. - rise, 54., 98., Color::from_hex(0x2d3f36));
862    draw_rectangle_lines(
863        exit - 27.,
864        456. - rise,
865        54.,
866        98.,
867        2.,
868        Color::from_hex(0x5d7d62),
869    );
870    draw_rectangle(exit - 27., 452. - rise, 54., 4., Color::from_hex(0x5d7d62));
871    draw_rectangle_lines(exit - 35.0, 450.0, 70.0, 110.0, 5.0, GREEN);
872    draw_triangle(
873        vec2(exit - 8.0, 495.0 - rise),
874        vec2(exit + 9.0, 505.0 - rise),
875        vec2(exit - 8.0, 515.0 - rise),
876        GREEN,
877    );
878    if game.landing_feedback > 0. {
879        let progress = 1. - game.landing_feedback / 0.24;
880        let spread = 8. + progress * (18. + game.landing_strength * 20.);
881        let p = game.landing_at - vec2(camera, 0.);
882        for direction in [-1., 1.] {
883            draw_circle(
884                p.x + direction * spread,
885                p.y - 2. - progress * 7.,
886                2. + (1. - progress) * 3.,
887                Color::new(CREAM.r, CREAM.g, CREAM.b, (1. - progress) * 0.6 * movement),
888            );
889        }
890    }
891    let p = game.position() - vec2(camera, rise);
892    if game.jump_feedback > 0. {
893        draw_ellipse(
894            p.x + PLAYER.x * 0.5,
895            p.y + PLAYER.y + 3.,
896            12. + (1. - game.jump_feedback / 0.18) * 8.,
897            3.,
898            0.,
899            Color::new(
900                ORANGE.r,
901                ORANGE.g,
902                ORANGE.b,
903                game.jump_feedback * 2. * policy.intensity(),
904            ),
905        );
906    }
907    let (left, right, body) = match motion.frame() {
908        1 => (0., 0., 1.),
909        2 => (-3., 3., 0.),
910        3 | 5 => (0., 0., -1.),
911        4 => (3., -3., 0.),
912        8 => (-3., -1., 0.),
913        9 => (1., 2., 0.),
914        10 => (-3., -3., 3.),
915        11 => (-1., -1., 1.),
916        _ => (0., 0., 0.),
917    };
918    let pose_scale = if matches!(motion.frame(), 8 | 9) {
919        1.
920    } else {
921        movement
922    };
923    let (left, right, body) = (left * pose_scale, right * pose_scale, body * pose_scale);
924    draw_ellipse(
925        p.x + 12.0,
926        p.y + 42.0 + rise,
927        15.0,
928        3.0,
929        0.0,
930        Color::new(0.0, 0.0, 0.0, 0.20),
931    );
932    // Squash/stretch scales the authored shapes around the feet.
933    let scale = juice.player_scale();
934    let anchor = p + vec2(PLAYER.x * 0.5, PLAYER.y);
935    let at =
936        |x: f32, y: f32| anchor + vec2((x - PLAYER.x * 0.5) * scale.x, (y - PLAYER.y) * scale.y);
937    let rect = |x: f32, y: f32, w: f32, h: f32, color: Color| {
938        let corner = at(x, y);
939        draw_rectangle(corner.x, corner.y, w * scale.x, h * scale.y, color);
940    };
941    draw_triangle(
942        at(5.0, 18.0),
943        at(
944            12.0 - motion.facing() * 25.0 + juice.cape().x,
945            22.0 + left * 0.4 + body + juice.cape().y,
946        ),
947        at(5.0, 26.0),
948        Color::from_hex(0x9e5033),
949    );
950    rect(3.0, 15.0 + body, 18.0, 19.0, ORANGE);
951    rect(4.0, 32.0, 6.0, 8.0 + left, Color::from_hex(0x1b2524));
952    rect(15.0, 32.0, 6.0, 8.0 + right, Color::from_hex(0x1b2524));
953    rect(4.0, 1.0 + body, 17.0, 15.0, CREAM);
954    rect(1.0, body, 24.0, 6.0, Color::from_hex(0xc79d57));
955    // Eyes: a slow blink, and wide "uh-oh" eyes during a fast fall.
956    let face = if motion.facing() < 0. { 5.0 } else { 14.0 };
957    let worried = game.velocity().y > 420. && !game.motor.grounded;
958    let blink = movement > 0. && (time * 0.9).fract() < 0.035;
959    let eye = if worried {
960        5.
961    } else if blink {
962        1.
963    } else {
964        3.
965    };
966    rect(
967        face,
968        9.5 + body - eye * 0.5,
969        5.0,
970        eye,
971        Color::from_hex(0x26312b),
972    );
973}
974
975/// The next unlit lantern's save marker: a breathing gold halo and a bobbing
976/// arrow, drawn without words. While a first-time player is learning to save,
977/// the halo is larger and brighter.
978fn save_marker(at: Vec2, time: f32, movement: f32, teaching: bool) {
979    use ferravex_render::shapes;
980    let breathe = 0.5 + 0.5 * (time * 3.).sin() * movement.min(1.);
981    let boost = if teaching { 1.35 } else { 1. };
982    shapes::glow_disc(
983        at,
984        (40. + 8. * breathe) * boost,
985        Color::new(1., 0.8, 0.4, (0.10 + 0.08 * breathe) * boost),
986    );
987    shapes::glow_ring(
988        at,
989        (26. + 6. * breathe) * boost,
990        3.,
991        Color::new(1., 0.8, 0.4, 0.35 + 0.25 * breathe),
992    );
993    let bob = (time * 4.).sin() * 4. * movement;
994    let tip = vec2(at.x, at.y - 34. + bob);
995    shapes::glow_disc(tip - vec2(0., 8.), 16., Color::new(1., 0.75, 0.3, 0.3));
996    ferravex_render::icons::draw_styled(
997        ferravex_render::icons::Icon::ArrowDown,
998        tip - vec2(0., 8.),
999        22.,
1000        ferravex_render::icons::IconStyle::new(juice::GOLD)
1001            .shadow(Color::new(0.02, 0.03, 0.03, 0.7)),
1002    );
1003}
1004
1005/// The secret: a little moth that is visible early and reachable only with skill.
1006fn moth(at: Vec2, time: f32, movement: f32) {
1007    let flap = (time * 16.).sin() * movement;
1008    let hover = (time * 2.).sin() * 4. * movement;
1009    let at = at + vec2(0., hover);
1010    draw_circle(at.x, at.y, 9., Color::new(0.86, 0.80, 1.0, 0.12));
1011    let wing = juice::MOTH;
1012    for side in [-1., 1.] {
1013        draw_triangle(
1014            at,
1015            at + vec2(side * (10. + 3. * flap), -8.),
1016            at + vec2(side * (9. + 2. * flap), 4.),
1017            wing,
1018        );
1019    }
1020    draw_ellipse(at.x, at.y, 2., 5., 0., Color::from_hex(0x5a4f6e));
1021}
1022
1023fn label(text: &str, x: f32, y: f32, size: f32, color: Color) {
1024    // The drop shadow fades with the text so toasts never leave a ghost.
1025    draw_text(
1026        text,
1027        x + 1.0,
1028        y + 2.0,
1029        size,
1030        Color::new(0.08, 0.12, 0.10, 0.8 * color.a),
1031    );
1032    draw_text(text, x, y, size, color);
1033}
1034
1035fn text_width(text: &str, size: f32) -> f32 {
1036    get_default_font()
1037        .try_metrics(8, size / 8.)
1038        .and_then(|metrics| metrics.measure_line(text))
1039        .expect("finite authored label")
1040        .width
1041}
1042
1043fn centered_label(text: &str, x: f32, y: f32, size: f32, color: Color) {
1044    label(text, x - text_width(text, size) * 0.5, y, size, color);
1045}
1046
1047fn fitted_centered_label(text: &str, x: f32, y: f32, width: f32, size: f32, color: Color) {
1048    let measured = text_width(text, size);
1049    centered_label(text, x, y, size * (width / measured.max(1.)).min(1.), color);
1050}
1051
1052fn config() -> Conf {
1053    #[allow(unused_mut)]
1054    let mut conf = ferravex_render::window_conf("EMBERLINE | Ferravex");
1055    #[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
1056    capture::window(&mut conf);
1057    conf
1058}
1059
1060/// Records context for this course layout and medal rules.
1061const RECORD_RULES: u64 = 0x454d_424c_0001;
1062const RECORD_ID: &str = "course";
1063
1064fn best_clear(records: Option<&ferravex_render::storage::Records>) -> Option<f64> {
1065    records?
1066        .get(RECORD_ID, RECORD_RULES)?
1067        .fastest_us
1068        .map(|us| us as f64 / 1_000_000.)
1069}
1070
1071ferravex_render::game!(config, game);
1072async fn game() {
1073    let mut demo = Demo::new();
1074    let mut sound = GameAudio::new();
1075    let mut game = Game::new(demo.autoplay);
1076    let mut motion = EmberAnimation::new();
1077    let mut juice = Juice::new();
1078    let mut overlay = hud::Overlay::new(game.session.state());
1079    let mut particles = ferravex_render::effects::ParticleRenderer::new(384)
1080        .expect("bounded presentation particles");
1081    // Personal bests are optional: a storage failure still leaves a playable game.
1082    let mut records = ferravex_render::storage::Records::new("emberline").ok();
1083    let mut results = hud::Results::default();
1084    #[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
1085    let mut capture = capture::Capture::from_env();
1086    let mut player_input = PlayerInput::preset("emberline", Preset::Platformer);
1087    let mut camera = Follow2::new(Follow2Settings {
1088        offset: vec2(WIDTH * 0.15, 0.),
1089        dead_zone: vec2(28., 0.),
1090        half_life: std::f32::consts::LN_2 / 9.,
1091        look_ahead_time: 0.05,
1092        max_look_ahead: 28.,
1093        teleport_distance: Some(600.),
1094        limits: Some(Limits2 {
1095            min: vec2(WIDTH * 0.5, HEIGHT * 0.5),
1096            max: vec2(WORLD_END - WIDTH * 0.5, HEIGHT * 0.5),
1097        }),
1098    })
1099    .unwrap();
1100    camera
1101        .set_look_ahead_dead_zone(vec2(12., 0.))
1102        .expect("authored look-ahead velocity threshold");
1103    loop {
1104        let compact = compact::CompactHud::for_screen(vec2(screen_width(), screen_height()));
1105        let canvas = ferravex_render::canvas::Canvas2D::fit(
1106            vec2(WIDTH, HEIGHT),
1107            vec2(screen_width(), screen_height()),
1108        );
1109        let corner = hud::WideLayout::new(canvas, vec2(screen_width(), screen_height()));
1110        let button = |rect: Rect, code| Control {
1111            region: Region::Rect(Rect::new(
1112                canvas.project(vec2(rect.x, rect.y)).x,
1113                canvas.project(vec2(rect.x, rect.y)).y,
1114                rect.w * canvas.scale,
1115                rect.h * canvas.scale,
1116            )),
1117            output: Output::Button(code),
1118        };
1119        let layout = compact.map_or_else(
1120            || {
1121                [
1122                    button(Rect::new(0., 590., 120., HEIGHT - 590.), 12),
1123                    button(Rect::new(120., 590., 130., HEIGHT - 590.), 13),
1124                    button(Rect::new(1080., 590., WIDTH - 1080., HEIGHT - 590.), 3),
1125                    button(corner.pause, 11),
1126                    button(hud::card_rect(game.session.state()), 10),
1127                ]
1128            },
1129            |hud| hud.touch_layout(),
1130        );
1131        player_input
1132            .set_touch_layout(&layout[..if game.session.is_playing() { 4 } else { 5 }])
1133            .unwrap();
1134        player_input.sample(game.session.is_playing());
1135        let touch_mode = player_input.current_device() == HintDevice::Touch;
1136        let state = game.session.state();
1137        #[allow(unused_mut)]
1138        let mut pause = player_input.pressed("pause");
1139        #[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
1140        {
1141            pause |= capture.pause_now(&game);
1142        }
1143        let restarted = game.menu(
1144            player_input.pressed("restart"),
1145            player_input.pressed("confirm"),
1146            pause,
1147        );
1148        if restarted {
1149            sound.reset();
1150            motion.reset();
1151            camera.cut();
1152            juice.reset();
1153            results = hud::Results::default();
1154        }
1155        if restarted || state != game.session.state() {
1156            // Disable once even for Playing -> Playing restarts, so held and
1157            // pending gameplay actions cannot leak through a menu edge.
1158            player_input.sample(false);
1159            player_input.sample(game.session.is_playing());
1160        }
1161        let gameplay_active = demo.autoplay || player_input.gameplay_active();
1162        // Controls/focus suspend local play without changing a manual pause.
1163        game.gate_input(gameplay_active);
1164        sync_audio(&mut sound, game.session.state(), gameplay_active);
1165        let policy = sync_preferences(&mut game, &mut motion, &mut camera);
1166        juice.apply_policy(policy);
1167        let direction = player_input.movement().x;
1168        let dt = if demo.autoplay {
1169            demo.dt()
1170        } else {
1171            player_input.simulation_dt(demo.dt())
1172        };
1173        #[allow(unused_mut)]
1174        let mut autoplay: fn(&Game) -> Input = Game::autoplay;
1175        #[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
1176        if capture.stop_jumping() {
1177            autoplay = |_: &Game| Input {
1178                direction: 1.,
1179                ..Input::default()
1180            };
1181        }
1182        let mut finished = false;
1183        let simulated = game.advance(
1184            f64::from(dt),
1185            |game| {
1186                if demo.autoplay {
1187                    autoplay(game)
1188                } else {
1189                    Input {
1190                        direction,
1191                        jump: player_input.pressed("jump"),
1192                        jump_held: player_input.held("jump"),
1193                    }
1194                }
1195            },
1196            |game, dt| {
1197                if game.feedback.respawned {
1198                    motion.reset();
1199                    camera.cut();
1200                    sound.reset();
1201                }
1202                motion.update(game, dt);
1203                apply_policy(game, &mut motion, policy);
1204                juice.apply_policy(policy);
1205                juice.on_tick(game);
1206                juice.advance(dt);
1207                let surface = if game.position().x > 1800. {
1208                    Surface::Metal
1209                } else if game.position().x > 900. {
1210                    Surface::Wood
1211                } else {
1212                    Surface::Grass
1213                };
1214                let fb = game.feedback;
1215                if fb.jumped {
1216                    sound.cue(Cue::Jump, if fb.air_jumped { 0.6 } else { 0.5 });
1217                }
1218                if fb.landed {
1219                    sound.cue(Cue::Impact(surface), 0.25 + game.landing_strength * 0.25);
1220                }
1221                if fb.pickup {
1222                    sound.cue(Cue::Pickup, if fb.chain_up.is_some() { 0.7 } else { 0.55 });
1223                }
1224                if fb.won || fb.checkpoint || fb.secret || fb.air_jump_unlocked {
1225                    sound.cue(Cue::Success, 0.65);
1226                }
1227                if fb.close_call || fb.split.is_some() {
1228                    sound.cue(Cue::Click, 0.45);
1229                }
1230                if fb.respawned {
1231                    sound.cue(Cue::Failure, 0.5);
1232                }
1233                for _ in 0..motion.footsteps() {
1234                    sound.cue(Cue::Footstep(surface), 0.32);
1235                }
1236                finished |= fb.won;
1237            },
1238        );
1239        if finished {
1240            // Compare against the stored best before recording this clear.
1241            results = hud::Results {
1242                previous_best: best_clear(records.as_ref()),
1243                demo: demo.autoplay,
1244            };
1245            #[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
1246            if let Some(best) = capture.fake_best() {
1247                results = hud::Results {
1248                    previous_best: Some(best),
1249                    demo: false,
1250                };
1251            }
1252            if !demo.autoplay
1253                && let Some(records) = records.as_mut()
1254            {
1255                let _ = records.attempt(
1256                    RECORD_ID,
1257                    RECORD_RULES,
1258                    game.score.total(),
1259                    ferravex_render::storage::run_micros(game.trial.elapsed() as f32),
1260                );
1261            }
1262        }
1263        if game.won() {
1264            juice.advance_celebration(demo.dt());
1265        }
1266        overlay.frame(
1267            &game,
1268            demo.dt(),
1269            policy,
1270            restarted,
1271            game.feedback.respawned,
1272            player_input.held("confirm"),
1273        );
1274        let veteran = best_clear(records.as_ref()).is_some();
1275        overlay.prompt_frame(hud::prompt(&game, &juice, veteran), demo.dt());
1276        let camera_x = camera
1277            .update(
1278                simulated,
1279                vec2(game.position().x, HEIGHT * 0.5),
1280                vec2(game.velocity().x, 0.),
1281            )
1282            .expect("valid platformer camera")
1283            .center
1284            .x
1285            - WIDTH * 0.5;
1286        let shake = juice.camera_offset();
1287        let mut view = canvas.camera();
1288        view.target.y -= shake.y;
1289        set_camera(&view);
1290        world(
1291            &game,
1292            camera_x + shake.x,
1293            game.elapsed,
1294            &motion,
1295            policy,
1296            &juice,
1297        );
1298        view.target.x += camera_x + shake.x;
1299        set_camera(&view);
1300        particles
1301            .draw_2d(
1302                &juice.particles,
1303                ferravex_render::effects::ParticleStyle {
1304                    stretch: 0.004,
1305                    max_stretch: 2.5,
1306                    ..Default::default()
1307                },
1308            )
1309            .expect("authored particle style");
1310        set_camera(&canvas.camera());
1311        hud::world_effects(&juice, camera_x + shake.x);
1312        if juice.flash > 0. {
1313            // A soft red edge vignette, cleared entirely under reduced flash.
1314            let a = juice.flash * 0.45;
1315            let red = Color::new(0.75, 0.12, 0.08, a);
1316            for (x, y, w, h) in [
1317                (-200., -200., WIDTH + 400., 236.),
1318                (-200., HEIGHT - 36., WIDTH + 400., 236.),
1319                (-200., -200., 236., HEIGHT + 400.),
1320                (WIDTH - 36., -200., 236., HEIGHT + 400.),
1321            ] {
1322                draw_rectangle(x, y, w, h, red);
1323            }
1324        }
1325        ferravex_render::set_world_colors(false);
1326        let best = best_clear(records.as_ref());
1327        if let Some(hud) = compact {
1328            hud.draw(&game, &player_input, &juice, &overlay, &results, best);
1329        } else {
1330            let hints = hud::Hints::new(&player_input, touch_mode);
1331            match game.session.state() {
1332                SessionState::Ready => {
1333                    let best = records
1334                        .as_ref()
1335                        .and_then(|r| r.get(RECORD_ID, RECORD_RULES))
1336                        .and_then(|r| r.fastest_us)
1337                        .map(|us| {
1338                            let time = us as f64 / 1_000_000.;
1339                            (time, hud::pace(time))
1340                        });
1341                    hud::ready(&hints, best, &overlay);
1342                }
1343                SessionState::Paused => hud::paused(&game, &hints, &overlay),
1344                SessionState::Won => hud::won(&game, &hints, &juice, &overlay, &results),
1345                _ => {
1346                    hud::play(&game, &juice, &overlay, corner.right);
1347                    hud::hero_prompt(&game, &hints, &overlay, camera_x + shake.x);
1348                    if touch_mode
1349                        && !player_input.touch_customized()
1350                        && [
1351                            ("move_left", 12),
1352                            ("move_right", 13),
1353                            ("jump", 3),
1354                            ("pause", 11),
1355                        ]
1356                        .iter()
1357                        .all(|(action, channel)| {
1358                            touch_button_matches(&player_input, action, *channel)
1359                        })
1360                    {
1361                        use ferravex_render::icons::{self, Icon};
1362                        for (x, icon) in [
1363                            (68.0, Icon::ArrowLeft),
1364                            (182.0, Icon::ArrowRight),
1365                            (1184.0, Icon::ArrowUp),
1366                        ] {
1367                            draw_circle(x, 651.0, 38.0, Color::new(0.09, 0.14, 0.12, 0.65));
1368                            icons::draw(icon, vec2(x, 651.), 34., CREAM);
1369                        }
1370                        // While a jump prompt is live, the jump button breathes.
1371                        if let Some((_, alpha)) = overlay.prompt() {
1372                            let breathe =
1373                                0.5 + 0.5 * (overlay.since * 5.).sin() * juice.motion().min(1.);
1374                            ferravex_render::shapes::glow_ring(
1375                                vec2(1184., 651.),
1376                                42. + 5. * breathe,
1377                                4.,
1378                                Color::new(
1379                                    GREEN.r,
1380                                    GREEN.g,
1381                                    GREEN.b,
1382                                    alpha * (0.5 + 0.4 * breathe),
1383                                ),
1384                            );
1385                        }
1386                        let pause = corner.pause;
1387                        ferravex_render::shapes::fill_rounded_rect(
1388                            pause,
1389                            12.,
1390                            Color::new(0.09, 0.14, 0.12, 0.85),
1391                        );
1392                        icons::draw(Icon::Pause, pause.center(), 28., CREAM);
1393                    }
1394                }
1395            }
1396        }
1397        set_default_camera();
1398        overlay.draw_transition(vec2(screen_width() * 0.5, screen_height() * 0.5));
1399        player_input.draw_controls();
1400        #[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
1401        capture.end_frame();
1402        if demo.finish_frame() {
1403            break;
1404        }
1405        next_frame().await;
1406    }
1407}
1408
1409#[cfg(test)]
1410mod tests {
1411    use super::*;
1412
1413    #[test]
1414    fn tap_and_hold_produce_distinct_controlled_jump_arcs() {
1415        let apex = |held| {
1416            let mut game = Game::new(true);
1417            for _ in 0..8 {
1418                game.update(Input::default(), DT);
1419            }
1420            let mut rise = 0_f32;
1421            for tick in 0..130 {
1422                game.update(
1423                    Input {
1424                        jump: tick == 0,
1425                        jump_held: held,
1426                        direction: 0.,
1427                    },
1428                    DT,
1429                );
1430                rise = rise.max(520. - game.position().y);
1431            }
1432            assert_eq!(game.jumps, 1);
1433            assert_eq!(game.deaths, 0);
1434            assert!(game.motor.grounded);
1435            rise
1436        };
1437        let short = apex(false);
1438        let full = apex(true);
1439        assert!(
1440            short > 20. && full > short + 60.,
1441            "tap={short}, hold={full}"
1442        );
1443    }
1444
1445    const DT: f32 = 1.0 / 120.0;
1446
1447    #[test]
1448    fn floor_stops_player_without_tunneling() {
1449        let mut game = Game::new(true);
1450        game.motor.position = feet(vec2(90., 80.));
1451        game.motor.grounded = false;
1452        for _ in 0..240 {
1453            game.update(Input::default(), DT);
1454        }
1455        assert!(game.motor.grounded);
1456        assert!((game.position().y - 520.).abs() < 0.01);
1457        assert_eq!(game.deaths, 0);
1458    }
1459
1460    #[test]
1461    fn coyote_jump_and_buffered_landing_work() {
1462        let mut game = Game::new(true);
1463        game.motor.position = feet(vec2(590., 520.));
1464        game.motor.grounded = false;
1465        game.motor.jump.coyote = 0.07;
1466        game.update(
1467            Input {
1468                jump: true,
1469                ..Input::default()
1470            },
1471            DT,
1472        );
1473        assert!(game.velocity().y < -600.0);
1474        game.motor.position = feet(vec2(90., 517.));
1475        game.motor.jump.held = false;
1476        game.motor.velocity.y = -180.;
1477        game.motor.jump.coyote = 0.0;
1478        game.update(
1479            Input {
1480                jump: true,
1481                ..Input::default()
1482            },
1483            DT,
1484        );
1485        for _ in 0..4 {
1486            game.update(
1487                Input {
1488                    jump_held: true,
1489                    ..Input::default()
1490                },
1491                DT,
1492            );
1493        }
1494        assert!(game.velocity().y < -500.0);
1495        assert_eq!(game.jumps, 2);
1496    }
1497
1498    #[test]
1499    fn hazards_respawn_at_activated_checkpoint() {
1500        let mut game = Game::new(true);
1501        game.motor.position = feet(vec2(1410., 520.));
1502        game.update(Input::default(), DT);
1503        assert_eq!(game.checkpoints.index(), 1);
1504        game.motor.position = feet(vec2(1605., 520.));
1505        game.update(Input::default(), DT);
1506        assert_eq!(game.position(), game.checkpoints.recovery().current.anchor);
1507        assert_eq!(game.deaths, 1);
1508    }
1509
1510    #[test]
1511    fn moving_side_platform_carries_a_standing_player() {
1512        let mut game = Game::new(true);
1513        game.motor = Character::new(feet(vec2(815., 395.)));
1514        game.update(Input::default(), DT);
1515        let before = game.position();
1516        game.update(Input::default(), DT);
1517        assert!(game.motor.grounded);
1518        assert!(game.position().x - before.x > 0.27);
1519        assert!((game.position().y - before.y).abs() < 0.01);
1520    }
1521    #[test]
1522    fn autoplay_completes_all_sections_with_real_physics() {
1523        let mut game = Game::new(true);
1524        for _ in 0..2400 {
1525            game.update(game.autoplay(), DT);
1526            if game.won() {
1527                break;
1528            }
1529        }
1530        assert!(
1531            game.won(),
1532            "position {:?}, deaths {}",
1533            game.position(),
1534            game.deaths
1535        );
1536        assert_eq!(game.checkpoints.index(), 2);
1537        assert!(game.jumps >= 7);
1538        assert!(game.embers.iter().any(|(_, found)| *found));
1539        assert_eq!(game.deaths, 0);
1540    }
1541}
1542
1543#[cfg(test)]
1544mod collectible_score_tests {
1545    use super::*;
1546    #[test]
1547    fn each_ember_awards_once_and_falls_break_only_the_chain() {
1548        let mut g = Game::new(true);
1549        g.embers = vec![
1550            (vec2(102., 540.), false),
1551            (vec2(108., 540.), false),
1552            (vec2(114., 540.), false),
1553        ];
1554        g.update(Input::default(), 1. / 120.);
1555        assert_eq!(g.score.total(), 400);
1556        g.update(Input::default(), 1. / 120.);
1557        assert_eq!(g.score.total(), 400);
1558        g.respawn();
1559        assert_eq!(g.score.chain(), 0);
1560        assert_eq!(g.score.total(), 400);
1561    }
1562}
1563
1564#[cfg(test)]
1565mod trial_loop_tests {
1566    use super::*;
1567    #[test]
1568    fn ordinary_completion_records_all_splits_and_freezes_the_medal() {
1569        let mut g = Game::new(true);
1570        for _ in 0..2400 {
1571            g.update(g.autoplay(), 1. / 120.);
1572            if g.won() {
1573                break;
1574            }
1575        }
1576        assert!(g.trial.finished());
1577        let splits = g.trial.splits();
1578        assert!(splits[0] < splits[1] && splits[1] < splits[2]);
1579        assert!(g.trial.medal().is_some());
1580        let time = g.trial.elapsed();
1581        g.update(Input::default(), 1.);
1582        assert_eq!(g.trial.elapsed(), time);
1583        assert!(!Game::new(true).trial.finished());
1584    }
1585}
1586
1587#[cfg(test)]
1588mod earned_jump_tests {
1589    use super::*;
1590    #[test]
1591    fn three_real_pickups_unlock_one_air_jump_per_landing() {
1592        let mut g = Game::new(true);
1593        g.embers = vec![(vec2(102., 540.), false); 3];
1594        g.update(Input::default(), 1. / 120.);
1595        assert_eq!(g.ember_inventory.count(1), 3);
1596        g.update(
1597            Input {
1598                jump: true,
1599                jump_held: true,
1600                ..Input::default()
1601            },
1602            1. / 120.,
1603        );
1604        for _ in 0..20 {
1605            g.update(
1606                Input {
1607                    jump_held: true,
1608                    ..Input::default()
1609                },
1610                1. / 120.,
1611            );
1612        }
1613        g.update(
1614            Input {
1615                jump: true,
1616                jump_held: true,
1617                ..Input::default()
1618            },
1619            1. / 120.,
1620        );
1621        assert!(g.air_jump_used);
1622        assert!(g.feedback.jumped);
1623        assert!(g.motor.velocity.y > 500.);
1624        assert_eq!(g.jumps, 2);
1625        g.update(
1626            Input {
1627                jump_held: true,
1628                ..Input::default()
1629            },
1630            1. / 120.,
1631        );
1632        g.update(
1633            Input {
1634                jump: true,
1635                jump_held: true,
1636                ..Input::default()
1637            },
1638            1. / 120.,
1639        );
1640        assert_eq!(g.jumps, 2);
1641        assert!(!g.feedback.jumped);
1642        for _ in 0..240 {
1643            g.update(Input::default(), 1. / 120.);
1644        }
1645        assert!(g.motor.grounded);
1646        assert!(!g.air_jump_used);
1647    }
1648}
1649
1650#[cfg(test)]
1651mod spring_route_tests {
1652    use super::*;
1653    #[test]
1654    fn bonus_route_springboards_launch_from_actual_platform_contact() {
1655        let mut g = Game::new(true);
1656        g.motor = Character::new(feet(vec2(168., 405.)));
1657        g.update(Input::default(), 1. / 120.);
1658        assert!(g.spring_flight);
1659        assert!(g.feedback.jumped);
1660        assert!(!g.motor.grounded);
1661        assert!(g.motor.velocity.y > 750.);
1662        g.update(Input::default(), 1. / 120.);
1663        assert!(g.motor.velocity.y > 700.);
1664        assert!(!g.feedback.jumped);
1665    }
1666}
1667
1668#[cfg(test)]
1669mod crumble_route_tests {
1670    use super::*;
1671    #[test]
1672    fn bonus_platforms_really_stop_supporting_the_player_then_regrow() {
1673        let mut g = Game::new(true);
1674        g.motor = Character::new(feet(vec2(410., 290.)));
1675        g.update(Input::default(), 1. / 120.);
1676        assert!(g.motor.grounded);
1677        for _ in 0..90 {
1678            g.update(
1679                Input {
1680                    jump_held: true,
1681                    ..Input::default()
1682                },
1683                1. / 120.,
1684            );
1685        }
1686        assert!(!g.crumbles[0].solid());
1687        assert!(g.position().y > 290.);
1688        for _ in 0..400 {
1689            g.update(Input::default(), 1. / 120.);
1690        }
1691        assert!(g.crumbles[0].solid());
1692    }
1693}
1694
1695#[cfg(test)]
1696mod checkpoint_route_tests {
1697    use super::*;
1698    #[test]
1699    fn later_lantern_updates_respawn_without_losing_earned_inventory() {
1700        let mut g = Game::new(true);
1701        g.motor = Character::new(feet(vec2(1410., 520.)));
1702        g.update(Input::default(), 1. / 120.);
1703        assert_eq!(g.checkpoints.index(), 1);
1704        g.motor = Character::new(feet(vec2(2050., 520.)));
1705        g.update(Input::default(), 1. / 120.);
1706        assert_eq!(g.checkpoints.index(), 2);
1707        let saved = g.checkpoints.snapshot();
1708        g.crumbles[0].step(1., true).unwrap();
1709        g.motor = Character::new(feet(vec2(2235., 520.)));
1710        g.update(Input::default(), 1. / 120.);
1711        assert_eq!(g.position(), vec2(2050., 520.));
1712        assert!(g.crumbles[0].solid());
1713        g.motor = Character::new(feet(vec2(1410., 520.)));
1714        g.update(Input::default(), 1. / 120.);
1715        assert_eq!(g.checkpoints.snapshot(), saved);
1716    }
1717}
1718
1719#[cfg(test)]
1720mod session_tests {
1721    use super::*;
1722
1723    const STEP: f64 = 1. / 120.;
1724
1725    fn idle(game: &mut Game, elapsed: f64) -> f32 {
1726        game.advance(elapsed, |_| Input::default(), |_, _| {})
1727    }
1728
1729    #[test]
1730    fn ready_waits_for_confirm_and_does_not_bank_startup_time() {
1731        let mut game = Game::new(false);
1732        let start = game.position();
1733        assert_eq!(game.session.state(), SessionState::Ready);
1734        assert_eq!(idle(&mut game, 60.), 0.);
1735        game.update(
1736            Input {
1737                direction: 1.,
1738                jump: true,
1739                jump_held: true,
1740            },
1741            STEP as f32,
1742        );
1743        assert_eq!(game.position(), start);
1744        assert_eq!(game.trial.elapsed(), 0.);
1745        assert_eq!(game.session.tick(), 0);
1746        game.menu(false, false, true);
1747        assert_eq!(game.session.state(), SessionState::Ready);
1748        assert!(!game.menu(false, true, false));
1749        assert!(game.session.is_playing());
1750        assert_eq!(idle(&mut game, 0.), 0.);
1751        idle(&mut game, STEP);
1752        assert_eq!(game.session.tick(), 1);
1753        assert_eq!(game.elapsed, STEP as f32);
1754    }
1755
1756    #[test]
1757    fn zero_tick_frames_retain_jump_input_and_catchup_accepts_it_once() {
1758        let mut game = Game::new(true);
1759        idle(&mut game, STEP);
1760        let mut pending_jump = true;
1761        let mut sampled = 0;
1762        let mut input = |_: &Game| {
1763            sampled += 1;
1764            Input {
1765                jump: std::mem::take(&mut pending_jump),
1766                jump_held: true,
1767                direction: 0.,
1768            }
1769        };
1770        assert_eq!(game.advance(STEP * 0.25, &mut input, |_, _| {}), 0.);
1771        let mut takeoffs = 0;
1772        game.advance(STEP * 11.75, &mut input, |game, _| {
1773            takeoffs += usize::from(game.feedback.jumped);
1774        });
1775        assert_eq!(sampled, 12);
1776        assert!(!pending_jump);
1777        assert_eq!(takeoffs, 1);
1778        assert_eq!(game.jumps, 1);
1779        assert!(!game.motor.grounded);
1780    }
1781
1782    #[test]
1783    fn pause_freezes_airborne_motion_trial_platforms_and_feedback_without_catchup() {
1784        let mut game = Game::new(true);
1785        idle(&mut game, STEP);
1786        game.advance(
1787            STEP,
1788            |_| Input {
1789                jump: true,
1790                jump_held: true,
1791                direction: 1.,
1792            },
1793            |_, _| {},
1794        );
1795        assert!(game.feedback.jumped);
1796        let before = (
1797            game.position(),
1798            game.velocity(),
1799            game.trial.elapsed(),
1800            game.platforms[5].x,
1801            game.jump_feedback,
1802            game.session.tick(),
1803        );
1804        game.menu(false, false, true);
1805        assert!(game.session.is_paused());
1806        assert_eq!(idle(&mut game, 120.), 0.);
1807        assert_eq!(
1808            (
1809                game.position(),
1810                game.velocity(),
1811                game.trial.elapsed(),
1812                game.platforms[5].x,
1813                game.jump_feedback,
1814                game.session.tick()
1815            ),
1816            before,
1817        );
1818        // Direct simulation calls respect the same pause gate.
1819        game.update(Input::default(), 0.1);
1820        assert_eq!(game.position(), before.0);
1821        assert_eq!(game.trial.elapsed(), before.2);
1822        game.menu(false, true, false);
1823        assert!(game.session.is_playing());
1824        assert_eq!(idle(&mut game, 0.), 0.);
1825        idle(&mut game, STEP);
1826        assert_eq!(game.session.tick(), before.5 + 1);
1827        assert!(game.trial.elapsed() > before.2);
1828        assert!(game.jump_feedback < before.4);
1829        assert_eq!(game.jumps, 1);
1830    }
1831
1832    #[test]
1833    fn pause_discards_buffered_jump_and_restart_clears_the_entire_run() {
1834        let mut game = Game::new(true);
1835        game.motor = Character::new(feet(vec2(90., 510.)));
1836        game.advance(
1837            STEP,
1838            |_| Input {
1839                jump: true,
1840                ..Input::default()
1841            },
1842            |_, _| {},
1843        );
1844        assert!(game.motor.jump.buffer > 0.);
1845        game.menu(false, false, true);
1846        assert_eq!(game.motor.jump.buffer, 0.);
1847        game.menu(false, false, true);
1848        for _ in 0..60 {
1849            idle(&mut game, STEP);
1850        }
1851        assert_eq!(game.jumps, 0, "pause must cancel a pending landing jump");
1852        assert!(game.motor.grounded);
1853
1854        game.embers = vec![(vec2(102., 540.), false); 3];
1855        idle(&mut game, STEP);
1856        assert_eq!(game.ember_inventory.count(1), 3);
1857        assert!(game.score.total() > 0);
1858        game.motor = Character::new(feet(vec2(1410., 520.)));
1859        idle(&mut game, STEP);
1860        assert_eq!(game.checkpoints.index(), 1);
1861        game.crumbles[0].step(1., true).unwrap();
1862        assert!(!game.crumbles[0].solid());
1863        game.respawn();
1864        assert_eq!(game.deaths, 1);
1865        idle(&mut game, STEP * 0.5);
1866        game.menu(false, false, true);
1867        assert!(game.menu(true, false, false));
1868        assert!(game.session.is_playing());
1869        assert_eq!(game.session.tick(), 0);
1870        assert_eq!(game.position(), vec2(90., 520.));
1871        assert_eq!(game.velocity(), Vec2::ZERO);
1872        assert_eq!(game.checkpoints.index(), 0);
1873        assert_eq!(game.ember_inventory.count(1), 0);
1874        assert_eq!(game.embers.len(), 12);
1875        assert!(game.embers.iter().all(|(_, collected)| !collected));
1876        assert_eq!(game.score.total(), 0);
1877        assert_eq!(game.deaths, 0);
1878        assert_eq!(game.jumps, 0);
1879        assert_eq!(game.trial.elapsed(), 0.);
1880        assert!(game.trial.splits().iter().all(Option::is_none));
1881        assert!(game.crumbles.iter().all(|platform| platform.solid()));
1882        assert_eq!(game.respawn_notice, 0.);
1883        assert_eq!(game.checkpoint_notice, 0.);
1884        assert_eq!(game.jump_feedback, 0.);
1885        assert_eq!(game.landing_feedback, 0.);
1886        assert!(!game.feedback.respawned);
1887        assert_eq!(
1888            idle(&mut game, STEP * 0.5),
1889            0.,
1890            "restart clears fractional clock debt"
1891        );
1892    }
1893
1894    #[test]
1895    fn autoplay_completion_freezes_everything_and_confirm_starts_a_fresh_run() {
1896        let mut game = Game::new(true);
1897        let mut victories = 0;
1898        for _ in 0..600 {
1899            game.advance(1. / 30., Game::autoplay, |game, _| {
1900                assert_eq!(victories, 0, "no further tick runs after reaching the lift");
1901                victories += usize::from(game.feedback.won);
1902            });
1903            if game.won() {
1904                break;
1905            }
1906        }
1907        assert!(game.won());
1908        assert_eq!(game.deaths, 0);
1909        assert_eq!(victories, 1);
1910        assert_eq!(game.checkpoints.index(), 2);
1911        let before = (
1912            game.position(),
1913            game.trial.elapsed(),
1914            game.score.total(),
1915            game.session.tick(),
1916        );
1917        game.menu(false, false, true);
1918        assert!(game.won(), "pause cannot reopen the completed run");
1919        game.advance(
1920            60.,
1921            |_| panic!("terminal session must not sample gameplay"),
1922            |_, _| panic!("terminal session must not tick"),
1923        );
1924        game.update(Input::default(), 1.);
1925        assert_eq!(
1926            (
1927                game.position(),
1928                game.trial.elapsed(),
1929                game.score.total(),
1930                game.session.tick()
1931            ),
1932            before
1933        );
1934        assert!(game.menu(false, true, false));
1935        assert!(game.session.is_playing());
1936        assert!(!game.trial.finished());
1937        assert_eq!(game.score.total(), 0);
1938        assert_eq!(game.session.tick(), 0);
1939    }
1940
1941    #[test]
1942    fn landing_and_checkpoint_feedback_fire_on_edges_and_do_not_repeat_while_standing() {
1943        let mut game = Game::new(true);
1944        game.motor = Character::new(feet(vec2(1410., 490.)));
1945        game.motor.velocity.y = -400.;
1946        let mut landings = 0;
1947        let mut checkpoints = 0;
1948        for _ in 0..120 {
1949            game.advance(
1950                STEP,
1951                |_| Input::default(),
1952                |game, _| {
1953                    landings += usize::from(game.feedback.landed);
1954                    checkpoints += usize::from(game.feedback.checkpoint);
1955                },
1956            );
1957        }
1958        assert_eq!(landings, 1);
1959        assert_eq!(checkpoints, 1);
1960        assert!(game.landing_strength > 0.5);
1961        assert!((game.landing_at.y - 560.).abs() < 0.01);
1962        assert_eq!(game.landing_feedback, 0.);
1963        assert!(game.checkpoint_notice > 0.);
1964        for _ in 0..240 {
1965            idle(&mut game, STEP);
1966        }
1967        assert_eq!(
1968            game.checkpoint_notice, 0.,
1969            "standing at a lantern does not retrigger its notice"
1970        );
1971    }
1972}
1973
1974#[cfg(test)]
1975mod journey200_131 {
1976    use super::*;
1977
1978    const DT: f32 = 1. / 120.;
1979
1980    #[test]
1981    fn consecutive_fresh_presses_accept_the_earned_air_jump_once() {
1982        let mut game = Game::new(true);
1983        game.embers = vec![(vec2(102., 540.), false); 3];
1984        game.update(Input::default(), DT);
1985        assert_eq!(game.ember_inventory.count(1), 3);
1986        let press = Input {
1987            jump: true,
1988            jump_held: true,
1989            ..Input::default()
1990        };
1991        game.update(press, DT);
1992        assert_eq!(game.jumps, 1);
1993        game.update(press, DT); // A release/repress sampled between adjacent ticks.
1994        assert_eq!(game.jumps, 2);
1995        assert!(game.air_jump_used);
1996        assert!(game.feedback.jumped);
1997        assert!(game.motor.velocity.y > 500.);
1998        game.update(press, DT);
1999        assert_eq!(game.jumps, 2, "an unavailable air jump emits no takeoff");
2000        assert!(!game.feedback.jumped);
2001        for _ in 0..200 {
2002            game.update(
2003                Input {
2004                    jump_held: true,
2005                    ..Input::default()
2006                },
2007                DT,
2008            );
2009        }
2010        assert!(game.motor.grounded);
2011        assert_eq!(game.jumps, 2, "holding alone must never buffer a new jump");
2012        assert!(!game.air_jump_used);
2013    }
2014
2015    #[test]
2016    fn controls_gate_cancels_a_buffered_landing_jump_without_overriding_manual_pause() {
2017        let mut game = Game::new(true);
2018        let mut input = PlayerInput::transient("emberline-controls-gate");
2019        game.motor = Character::new(feet(vec2(90., 510.)));
2020        game.update(
2021            Input {
2022                jump: true,
2023                ..Input::default()
2024            },
2025            DT,
2026        );
2027        assert!(game.motor.jump.buffer > 0.);
2028        input.sample(true);
2029        input.set_controls_open(true);
2030        game.gate_input(input.gameplay_active());
2031        assert_eq!(game.motor.jump.buffer, 0.);
2032        assert!(game.session.is_playing());
2033        let before = (game.position(), game.trial.elapsed(), game.session.tick());
2034        game.advance(
2035            f64::from(input.simulation_dt(60.)),
2036            |_| panic!("controls gate"),
2037            |_, _| {},
2038        );
2039        assert_eq!(
2040            before,
2041            (game.position(), game.trial.elapsed(), game.session.tick())
2042        );
2043        input.set_controls_open(false);
2044        input.sample(true);
2045        for _ in 0..60 {
2046            game.advance(f64::from(DT), |_| Input::default(), |_, _| {});
2047        }
2048        assert!(game.motor.grounded);
2049        assert_eq!(game.jumps, 0);
2050        game.menu(false, false, true);
2051        input.set_controls_open(true);
2052        input.sample(false);
2053        game.gate_input(input.gameplay_active());
2054        input.set_controls_open(false);
2055        assert!(game.session.is_paused());
2056    }
2057
2058    #[test]
2059    fn coyote_and_landing_buffers_expire_without_ghost_jumps() {
2060        let mut game = Game::new(true);
2061        game.motor = Character::new(feet(vec2(600., 490.)));
2062        game.motor.jump.coyote = DT * 0.5;
2063        game.update(
2064            Input {
2065                jump: true,
2066                ..Input::default()
2067            },
2068            DT,
2069        );
2070        assert_eq!(game.jumps, 0);
2071        assert!(!game.feedback.jumped);
2072        game.motor = Character::new(feet(vec2(90., 120.)));
2073        game.update(
2074            Input {
2075                jump: true,
2076                ..Input::default()
2077            },
2078            DT,
2079        );
2080        assert!(game.motor.jump.buffer > 0.);
2081        for _ in 0..150 {
2082            game.update(Input::default(), DT);
2083        }
2084        assert!(game.motor.grounded);
2085        assert_eq!(game.jumps, 0);
2086        assert_eq!(game.motor.jump.buffer, 0.);
2087    }
2088
2089    #[test]
2090    fn autoplay_rules_and_accepted_events_are_identical_under_every_visual_policy() {
2091        for policy in [
2092            FeedbackPolicy::new(true, false, 1.).unwrap(),
2093            FeedbackPolicy::new(false, true, 1.).unwrap(),
2094            FeedbackPolicy::new(true, true, 1.).unwrap(),
2095            FeedbackPolicy::new(false, false, 0.).unwrap(),
2096            FeedbackPolicy::new(false, false, 0.3).unwrap(),
2097        ] {
2098            let mut baseline = Game::new(true);
2099            let mut reduced = Game::new(true);
2100            let mut motion = EmberAnimation::new();
2101            let mut takeoffs = 0;
2102            let mut landings = 0;
2103            let mut checkpoints = 0;
2104            for frame in 0..1800 {
2105                let dt = [1. / 30., 0., 1. / 144., 1. / 60.][frame % 4];
2106                baseline.advance(dt, Game::autoplay, |_, _| {});
2107                apply_policy(&mut reduced, &mut motion, policy);
2108                reduced.advance(dt, Game::autoplay, |game, dt| {
2109                    motion.update(game, dt);
2110                    apply_policy(game, &mut motion, policy);
2111                    takeoffs += usize::from(game.feedback.jumped);
2112                    landings += usize::from(game.feedback.landed);
2113                    checkpoints += usize::from(game.feedback.checkpoint);
2114                });
2115                assert_eq!(baseline.position(), reduced.position());
2116                assert_eq!(baseline.velocity(), reduced.velocity());
2117                assert_eq!(baseline.session.state(), reduced.session.state());
2118                assert_eq!(baseline.session.tick(), reduced.session.tick());
2119                assert_eq!(baseline.trial.elapsed(), reduced.trial.elapsed());
2120                assert_eq!(baseline.score.total(), reduced.score.total());
2121                assert_eq!(
2122                    baseline.checkpoints.recovery(),
2123                    reduced.checkpoints.recovery()
2124                );
2125                assert_eq!(baseline.embers, reduced.embers);
2126                assert_eq!(baseline.platforms, reduced.platforms);
2127                assert_eq!(baseline.feedback.jumped, reduced.feedback.jumped);
2128                assert_eq!(baseline.feedback.landed, reduced.feedback.landed);
2129                assert_eq!(baseline.feedback.checkpoint, reduced.feedback.checkpoint);
2130                if reduced.won() {
2131                    break;
2132                }
2133            }
2134            assert!(reduced.won());
2135            assert_eq!(reduced.deaths, 0);
2136            assert!(takeoffs >= 7);
2137            assert!(landings >= 7);
2138            assert_eq!(checkpoints, 2);
2139            assert_eq!(reduced.checkpoints.recovery().current.index, 2);
2140            assert!(reduced.checkpoints.recovery().next.is_none());
2141            assert!(reduced.trial.splits().iter().all(Option::is_some));
2142        }
2143    }
2144}
2145
2146/// Polish pass: forgiving spikes, fall causes, close calls, the moth secret,
2147/// chain/unlock receipts and section splits, all from real fixed ticks.
2148#[cfg(test)]
2149mod polish_tests {
2150    use super::*;
2151
2152    const DT: f32 = 1. / 120.;
2153    const RIGHT: Input = Input {
2154        direction: 1.,
2155        jump: false,
2156        jump_held: false,
2157    };
2158
2159    #[test]
2160    fn spike_corners_forgive_but_spike_centers_still_hurt() {
2161        let mut game = Game::new(true);
2162        // Overlap only the first 3 units of the first spike strip (x=350).
2163        game.motor = Character::new(feet(vec2(329., 520.)));
2164        game.update(Input::default(), DT);
2165        assert_eq!(game.deaths, 0, "a triangle's outer corner does not hurt");
2166        game.motor = Character::new(feet(vec2(340., 520.)));
2167        game.update(Input::default(), DT);
2168        assert_eq!(game.deaths, 1);
2169        assert!(game.feedback.respawned);
2170        assert_eq!(game.death_cause, DeathCause::Spikes);
2171        assert_eq!(game.death_at, vec2(340., 520.));
2172    }
2173
2174    #[test]
2175    fn fissure_falls_name_their_cause_and_lanterns_reset_the_local_fall_count() {
2176        let mut game = Game::new(true);
2177        for expected in 1..=2 {
2178            game.motor = Character::new(feet(vec2(600., 600.)));
2179            for _ in 0..120 {
2180                game.update(Input::default(), DT);
2181                if game.feedback.respawned {
2182                    break;
2183                }
2184            }
2185            assert_eq!(game.death_cause, DeathCause::Fissure);
2186            assert_eq!((game.deaths, game.deaths_here), (expected, expected));
2187        }
2188        game.motor = Character::new(feet(vec2(1410., 520.)));
2189        game.update(Input::default(), DT);
2190        assert!(game.feedback.checkpoint);
2191        assert_eq!((game.deaths, game.deaths_here), (2, 0));
2192    }
2193
2194    #[test]
2195    fn skimming_spike_tips_then_landing_safely_is_exactly_one_close_call() {
2196        let mut game = Game::new(true);
2197        game.motor = Character::new(feet(vec2(370., 494.)));
2198        game.motor.grounded = false;
2199        game.motor.velocity.x = SPEED;
2200        let mut calls = 0;
2201        for _ in 0..60 {
2202            game.update(RIGHT, DT);
2203            calls += usize::from(game.feedback.close_call);
2204            if game.motor.grounded {
2205                break;
2206            }
2207        }
2208        assert_eq!(game.deaths, 0);
2209        assert!(game.motor.grounded);
2210        assert_eq!((calls, game.close_calls), (1, 1));
2211        assert!(!game.skim);
2212
2213        // A full-height autoplay course clears spikes with room to spare.
2214        let mut tidy = Game::new(true);
2215        for _ in 0..2400 {
2216            tidy.update(tidy.autoplay(), DT);
2217            if tidy.won() {
2218                break;
2219            }
2220        }
2221        assert!(tidy.won());
2222        assert_eq!(tidy.close_calls, 0);
2223
2224        // A fall cancels a pending skim, and restart clears the count.
2225        let mut fallen = Game::new(true);
2226        fallen.motor = Character::new(feet(vec2(360., 500.)));
2227        fallen.motor.grounded = false;
2228        fallen.update(Input::default(), DT);
2229        assert!(fallen.skim);
2230        fallen.respawn();
2231        assert!(!fallen.skim);
2232        game.restart();
2233        assert_eq!(
2234            (game.close_calls, game.secret, game.deaths_here),
2235            (0, false, 0)
2236        );
2237    }
2238
2239    fn launch_from_furnace_spring(embers: bool) -> Game {
2240        let mut game = Game::new(true);
2241        game.embers = if embers {
2242            vec![(vec2(2070., 410.), false); 3]
2243        } else {
2244            Vec::new()
2245        };
2246        game.motor = Character::new(feet(vec2(2058., 390.)));
2247        game.update(Input::default(), DT);
2248        assert!(game.spring_flight, "the spring really launches");
2249        game
2250    }
2251
2252    #[test]
2253    fn the_moth_needs_the_earned_air_jump_and_pays_out_once() {
2254        let mut plain = launch_from_furnace_spring(false);
2255        for _ in 0..240 {
2256            plain.update(
2257                Input {
2258                    jump: plain.motor.velocity.y.abs() < 40.,
2259                    jump_held: true,
2260                    ..Input::default()
2261                },
2262                DT,
2263            );
2264        }
2265        assert!(!plain.secret, "a spring alone cannot reach the moth");
2266
2267        let mut game = launch_from_furnace_spring(true);
2268        assert!(game.feedback.air_jump_unlocked);
2269        let before = game.score.total();
2270        let mut found = 0;
2271        let mut pressed = false;
2272        for _ in 0..240 {
2273            let apex = !pressed && game.motor.velocity.y < 40.;
2274            pressed |= apex;
2275            game.update(
2276                Input {
2277                    jump: apex,
2278                    jump_held: true,
2279                    ..Input::default()
2280                },
2281                DT,
2282            );
2283            found += usize::from(game.feedback.secret);
2284        }
2285        assert!(pressed && game.secret);
2286        assert_eq!(found, 1);
2287        assert!(game.score.total() >= before + u64::from(MOTH_POINTS));
2288        assert_eq!(game.deaths, 0);
2289    }
2290
2291    #[test]
2292    fn pickups_report_accepted_points_chain_rises_and_one_unlock() {
2293        let mut game = Game::new(true);
2294        game.embers = vec![(vec2(102., 540.), false); 3];
2295        game.update(Input::default(), DT);
2296        let fb = game.feedback;
2297        assert!(fb.pickup && fb.air_jump_unlocked);
2298        assert_eq!(fb.pickup_points, 400);
2299        assert_eq!(fb.chain_up, Some(2));
2300        assert_eq!(fb.pickup_at, vec2(102., 540.));
2301        game.update(Input::default(), DT);
2302        assert!(!game.feedback.air_jump_unlocked && game.feedback.pickup_points == 0);
2303    }
2304
2305    #[test]
2306    fn section_splits_announce_once_each_in_order() {
2307        let mut game = Game::new(true);
2308        let mut splits = Vec::new();
2309        for _ in 0..2400 {
2310            game.update(game.autoplay(), DT);
2311            splits.extend(game.feedback.split);
2312            if game.won() {
2313                break;
2314            }
2315        }
2316        assert_eq!(splits, [0, 1]);
2317    }
2318}