owned_orbit/
lib.rs

1//! Orbit Breaker: original gameplay, original CPU raster, and only first-party Ferravex crates.
2mod font;
3pub mod game;
4#[cfg(any(target_arch = "wasm32", test))]
5mod interactive;
6#[cfg(test)]
7mod journey200_tests;
8mod juice;
9mod presentation;
10mod quips;
11mod raster;
12mod readable;
13use ferravex_core::session::{GameSession, SessionState};
14use ferravex_engine::input::{ActionKind, ActionMap, Binding, ContextId, InputCode};
15use game::{Game, HEIGHT, Input, WIDTH};
16use raster::Canvas;
17use std::sync::Mutex;
18
19/// A finished run awaiting the host's record keeping. See [`Orbit::take_finished_run`].
20#[derive(Clone, Copy, Debug, PartialEq)]
21pub struct FinishedRun {
22    pub won: bool,
23    pub score: u32,
24    /// Simulated run time in seconds.
25    pub seconds: f32,
26    /// Whether this score beat the personal best supplied by the host.
27    pub new_best: bool,
28}
29
30pub struct Orbit {
31    pub game: Game,
32    pub canvas: Canvas,
33    session: GameSession,
34    actions: ActionMap,
35    axis: usize,
36    launch: usize,
37    restart: usize,
38    pending_launch: bool,
39    presentation: presentation::Presentation,
40    readable_status: readable::ReadableStatus,
41    unrecorded: Option<FinishedRun>,
42}
43impl Default for Orbit {
44    fn default() -> Self {
45        Self::new()
46    }
47}
48impl Orbit {
49    pub fn new() -> Self {
50        let mut actions = ActionMap::default();
51        let axis = actions.action(vec![Binding {
52            code: InputCode::PadAxis(0),
53            scale: 1.0,
54            deadzone: 0.02,
55        }]);
56        let launch = actions
57            .named_action(
58                "launch",
59                ActionKind::Button,
60                ContextId::GLOBAL,
61                vec![Binding::digital(InputCode::Key(32))],
62            )
63            .expect("valid launch action");
64        let restart = actions
65            .named_action(
66                "restart",
67                ActionKind::Button,
68                ContextId::GLOBAL,
69                vec![Binding::digital(InputCode::Key(82))],
70            )
71            .expect("valid restart action");
72        let mut app = Self {
73            game: Game::new(),
74            canvas: Canvas::new(),
75            // The simulation's Ready phase still steers and charges the serve.
76            // Session Playing means the local simulation is allowed to advance.
77            session: GameSession::new(120.0, 12, true),
78            actions,
79            axis,
80            launch,
81            restart,
82            pending_launch: false,
83            presentation: presentation::Presentation::default(),
84            readable_status: readable::ReadableStatus::default(),
85            unrecorded: None,
86        };
87        app.render();
88        app
89    }
90    /// Advance the legacy host with held buttons (bit 0 launch, bit 1 restart).
91    /// Press/release edges are latched even when elapsed time produces no tick.
92    pub fn advance(&mut self, dt: f64, axis: f32, buttons: u32) {
93        self.actions.feed(InputCode::PadAxis(0), axis);
94        self.actions
95            .feed(InputCode::Key(32), f32::from(buttons & 1 != 0));
96        self.actions
97            .feed(InputCode::Key(82), f32::from(buttons & 2 != 0));
98        let input = Input {
99            axis: self.actions.consume_tick(self.axis).value,
100            launch: self.actions.consume_tick(self.launch).pressed,
101            restart: self.actions.consume_tick(self.restart).pressed,
102        };
103        self.advance_input(dt, input);
104    }
105
106    /// Advance with an axis level and **press edges**, sampled once per host frame.
107    /// Launch waits for the next fixed tick; catch-up ticks never repeat the edge.
108    /// Restart and terminal retry apply immediately, discard that frame's elapsed
109    /// time, and leave a fresh ball ready for a separate launch press.
110    ///
111    /// ```
112    /// use owned_orbit::{Orbit, game::{Input, Phase}};
113    /// let mut orbit = Orbit::new();
114    /// orbit.advance_input(0.0, Input { launch: true, ..Input::default() });
115    /// orbit.advance_input(1.0 / 120.0, Input::default());
116    /// assert_eq!(orbit.game.phase, Phase::Playing);
117    /// ```
118    pub fn advance_input(&mut self, dt: f64, input: Input) {
119        self.advance_session(dt, input);
120        let key = self.game.phase as u8 + if self.session.is_paused() { 8 } else { 0 };
121        let policy = ferravex_engine::render::preferences::feedback_policy();
122        self.presentation
123            .screen
124            .update(dt as f32, key, self.game.score, policy);
125    }
126
127    fn advance_session(&mut self, dt: f64, input: Input) {
128        self.presentation.begin_frame(dt);
129        self.sync_presentation();
130        if input.restart {
131            self.restart();
132            return;
133        }
134        if self.session.is_paused() {
135            self.pending_launch = false;
136            return;
137        }
138        if matches!(self.game.phase, game::Phase::Won | game::Phase::Lost) {
139            self.session.finish(self.game.phase == game::Phase::Won);
140            self.finish();
141            self.pending_launch = false;
142            if self.game.phase == game::Phase::Won {
143                self.presentation.juice.celebrate(dt as f32);
144            }
145            if input.launch {
146                self.restart();
147            }
148            return;
149        }
150        self.pending_launch |= input.launch;
151        let step = self.session.advance(dt);
152        for _ in 0..step.steps {
153            self.game.tick(
154                Input {
155                    axis: input.axis,
156                    launch: std::mem::take(&mut self.pending_launch),
157                    restart: false,
158                },
159                step.dt,
160            );
161            self.presentation.accept_tick(self.game.events.drain());
162            let juice = &mut self.presentation.juice;
163            juice.tick(step.dt);
164            if matches!(self.game.phase, game::Phase::Ready | game::Phase::Playing) {
165                juice.steered(input.axis, step.dt);
166            }
167            juice.charge_learned |= self.game.armor_piercing();
168            if matches!(self.game.phase, game::Phase::Won | game::Phase::Lost) {
169                self.session.finish(self.game.phase == game::Phase::Won);
170                self.finish();
171                break;
172            }
173        }
174    }
175
176    /// Build the results card once, from the accepted final state.
177    fn finish(&mut self) {
178        if self.presentation.results.is_some() {
179            return;
180        }
181        let g = &self.game;
182        let summary = quips::RunSummary {
183            won: g.phase == game::Phase::Won,
184            score: g.score,
185            sector: g.sector,
186            clears: g.clears,
187            lives_lost: g.lives_lost,
188            saves: g.saves,
189            satellites: g.satellites,
190        };
191        let previous_best = self.presentation.best;
192        let new_best = g.score > 0 && previous_best.is_none_or(|best| g.score > best);
193        if new_best {
194            self.presentation.best = Some(g.score);
195        }
196        self.presentation.runs = self.presentation.runs.saturating_add(1);
197        self.presentation.results = Some(presentation::Results {
198            summary,
199            rank: quips::rank(summary),
200            previous_best,
201            new_best,
202        });
203        self.unrecorded = Some(FinishedRun {
204            won: summary.won,
205            score: g.score,
206            seconds: g.time,
207            new_best,
208        });
209    }
210
211    /// Supply the stored personal best so the results card can compare.
212    /// Storage stays with the host; the simulation never reads it.
213    ///
214    /// ```
215    /// let mut orbit = owned_orbit::Orbit::new();
216    /// orbit.set_personal_best(Some(9000));
217    /// assert_eq!(orbit.personal_best(), Some(9000));
218    /// ```
219    pub fn set_personal_best(&mut self, best: Option<u32>) {
220        self.presentation.best = best;
221    }
222
223    /// The best score known to this session, including a just-finished run.
224    pub fn personal_best(&self) -> Option<u32> {
225        self.presentation.best
226    }
227
228    /// The run that just finished, returned once so a host can record it.
229    ///
230    /// ```
231    /// use owned_orbit::{Orbit, game::Phase};
232    /// let mut orbit = Orbit::new();
233    /// orbit.game.phase = Phase::Lost;
234    /// orbit.advance(0.0, 0.0, 0);
235    /// let run = orbit.take_finished_run().unwrap();
236    /// assert!(!run.won && run.score == 0 && !run.new_best);
237    /// assert_eq!(orbit.take_finished_run(), None);
238    /// ```
239    pub fn take_finished_run(&mut self) -> Option<FinishedRun> {
240        self.unrecorded.take()
241    }
242
243    /// The host lifecycle; `Playing` also permits pre-serve charging and sector transitions.
244    ///
245    /// ```
246    /// use ferravex_core::session::SessionState;
247    /// assert_eq!(owned_orbit::Orbit::new().session_state(), SessionState::Playing);
248    /// ```
249    pub fn session_state(&self) -> SessionState {
250        self.session.state()
251    }
252
253    /// Pause/resume without accumulating inactive time or retaining queued launch presses.
254    /// Terminal sessions cannot be paused. Returns whether the lifecycle changed.
255    ///
256    /// ```
257    /// let mut orbit = owned_orbit::Orbit::new();
258    /// assert!(orbit.set_paused(true));
259    /// orbit.advance(20.0, 1.0, 1);
260    /// assert_eq!(orbit.game.time, 0.0);
261    /// assert!(orbit.set_paused(false));
262    /// ```
263    pub fn set_paused(&mut self, paused: bool) -> bool {
264        let changed = self.session.set_paused(paused);
265        if changed {
266            if paused {
267                self.presentation.pauses = self.presentation.pauses.wrapping_add(1);
268            }
269            self.pending_launch = false;
270            self.actions.suppress_held();
271        }
272        changed
273    }
274
275    /// Reset the run, clock and buffered controls, then allow steering and charging.
276    /// A restart never launches the ball and also resumes a paused session.
277    ///
278    /// ```
279    /// let mut orbit = owned_orbit::Orbit::new();
280    /// orbit.game.score = 500;
281    /// orbit.set_paused(true);
282    /// orbit.restart();
283    /// assert_eq!(orbit.game.score, 0);
284    /// assert_eq!(orbit.game.phase, owned_orbit::game::Phase::Ready);
285    /// ```
286    pub fn restart(&mut self) {
287        self.game.restart();
288        self.presentation.clear();
289        self.presentation.restarts = self.presentation.restarts.wrapping_add(1);
290        self.presentation.screen.restarted();
291        self.unrecorded = None;
292        self.sync_presentation();
293        self.session.restart();
294        self.pending_launch = false;
295        self.actions.suppress_held();
296    }
297    pub fn render(&mut self) {
298        self.sync_presentation();
299        self.canvas
300            .render_session(&self.game, self.session.is_paused(), &self.presentation);
301    }
302
303    /// Refresh bounded UTF-8 status from actual gameplay and the current hints.
304    /// This human-readable v1 presentation is not a save/replay format. It does
305    /// not advance gameplay, sample input or consume feedback. At most 2048
306    /// UTF-8 bytes are returned; overlong copy produces a complete error hint.
307    /// Native hosts use the authored default hints; the interactive adapter
308    /// refreshes them from its existing `PlayerInput` before each host frame.
309    ///
310    /// ```
311    /// let mut orbit = owned_orbit::Orbit::new();
312    /// assert!(orbit.status_text_v1().contains("Panels: 35 remaining"));
313    /// assert!(orbit.status_text_v1().contains("Best precision: 0. Ball saves: 0."));
314    /// ```
315    pub fn status_text_v1(&mut self) -> &str {
316        self.readable_status
317            .refresh(&self.game, self.session.is_paused(), &self.presentation);
318        self.readable_status.as_str()
319    }
320
321    fn sync_presentation(&mut self) {
322        ferravex_engine::render::preferences::sync_feedback(&mut self.presentation.feedback);
323        let policy = ferravex_engine::render::preferences::feedback_policy();
324        self.game.apply_policy(policy);
325        self.presentation.juice.apply_policy(policy);
326    }
327}
328static APP: Mutex<Option<Orbit>> = Mutex::new(None);
329#[unsafe(no_mangle)]
330pub extern "C" fn init() {
331    *APP.lock().expect("app lock") = Some(Orbit::new());
332}
333/// buttons: bit0 launch/retry, bit1 reset. Input edges survive frames with no simulation tick.
334#[unsafe(no_mangle)]
335pub extern "C" fn step(dt: f64, axis: f32, buttons: u32) {
336    if let Some(app) = APP.lock().expect("app lock").as_mut() {
337        app.advance(dt, axis, buttons);
338        app.render();
339    }
340}
341#[unsafe(no_mangle)]
342pub extern "C" fn pixels() -> *const u8 {
343    APP.lock()
344        .expect("app lock")
345        .as_ref()
346        .map_or(std::ptr::null(), |app| {
347            app.canvas.frame.pixels().as_ptr().cast()
348        })
349}
350#[unsafe(no_mangle)]
351pub extern "C" fn width() -> u32 {
352    WIDTH
353}
354#[unsafe(no_mangle)]
355pub extern "C" fn height() -> u32 {
356    HEIGHT
357}
358#[unsafe(no_mangle)]
359pub extern "C" fn status() -> u32 {
360    APP.lock()
361        .expect("app lock")
362        .as_ref()
363        .map_or(0, |app| app.game.phase as u32)
364}
365#[unsafe(no_mangle)]
366pub extern "C" fn score() -> u32 {
367    APP.lock()
368        .expect("app lock")
369        .as_ref()
370        .map_or(0, |app| app.game.score)
371}
372#[unsafe(no_mangle)]
373pub extern "C" fn lives() -> u32 {
374    APP.lock()
375        .expect("app lock")
376        .as_ref()
377        .map_or(3, |app| app.game.lives)
378}
379#[unsafe(no_mangle)]
380pub extern "C" fn sector() -> u32 {
381    APP.lock()
382        .expect("app lock")
383        .as_ref()
384        .map_or(1, |app| app.game.sector)
385}
386#[unsafe(no_mangle)]
387pub extern "C" fn paddle() -> f32 {
388    APP.lock()
389        .expect("app lock")
390        .as_ref()
391        .map_or(320.0, |app| app.game.paddle_x)
392}
393
394/// Pointer to a refreshed human-readable v1 UTF-8 status, or null before init.
395/// Read `orbit_status_text_v1_len` immediately afterward, then copy the bytes
396/// before any other mutating game call. No terminator is included. Memory stays
397/// module-owned; the maximum length is 2048. Legacy exports are unchanged.
398///
399/// ```
400/// owned_orbit::init();
401/// let ptr = owned_orbit::orbit_status_text_v1();
402/// let len = owned_orbit::orbit_status_text_v1_len() as usize;
403/// assert!(!ptr.is_null() && len <= 2048);
404/// // Copy immediately, before another mutating game call invalidates the view.
405/// let copy = unsafe { std::slice::from_raw_parts(ptr, len) }.to_vec();
406/// assert!(std::str::from_utf8(&copy).unwrap().contains("Ready."));
407/// ```
408#[unsafe(no_mangle)]
409pub extern "C" fn orbit_status_text_v1() -> *const u8 {
410    APP.lock()
411        .expect("app lock")
412        .as_mut()
413        .map_or(std::ptr::null(), |app| app.status_text_v1().as_ptr())
414}
415
416/// Byte length of the last `orbit_status_text_v1` snapshot, zero before init.
417#[unsafe(no_mangle)]
418pub extern "C" fn orbit_status_text_v1_len() -> u32 {
419    APP.lock()
420        .expect("app lock")
421        .as_ref()
422        .map_or(0, |app| app.readable_status.as_str().len() as u32)
423}
424
425#[cfg(test)]
426mod tests {
427    use super::*;
428    use ferravex_engine::{
429        play::{audio::Cue, feedback::FeedbackPolicy},
430        render::preferences,
431    };
432    const DT: f64 = 1.0 / 120.0;
433
434    struct RestorePolicy(FeedbackPolicy);
435    impl RestorePolicy {
436        fn new() -> Self {
437            let previous = preferences::feedback_policy();
438            preferences::set_feedback_policy(FeedbackPolicy::default());
439            Self(previous)
440        }
441    }
442    impl Drop for RestorePolicy {
443        fn drop(&mut self) {
444            preferences::set_feedback_policy(self.0);
445        }
446    }
447
448    #[test]
449    fn live_policy_clears_existing_effects_on_paused_zero_tick_and_render_only_frames() {
450        let _restore = RestorePolicy::new();
451        for (motion, flash) in [(true, false), (false, true), (true, true)] {
452            preferences::set_feedback_policy(FeedbackPolicy::default());
453            let mut app = Orbit::new();
454            app.game.phase = game::Phase::Playing;
455            app.game.blocks[28].health = 2;
456            app.game.ball = [80., 380.];
457            app.game.velocity = [0., -12000.];
458            app.advance_input(2. * DT, Input::default());
459            assert!(!app.game.particles.is_empty());
460            assert!(!app.game.trail.is_empty());
461            assert!(app.game.blocks.iter().any(|b| b.flash > 0.));
462            assert!(app.presentation.feedback.impact().emphasis > 0.);
463            let state = (app.game.time, app.game.ball, app.game.score, app.game.lives);
464            app.set_paused(true);
465            preferences::set_feedback_policy(FeedbackPolicy::new(motion, flash, 1.).unwrap());
466            app.advance_input(0., Input::default());
467            app.render();
468            assert_eq!(app.game.particles.is_empty(), motion);
469            assert_eq!(app.game.trail.is_empty(), motion);
470            assert_eq!(app.presentation.feedback.impact().emphasis == 0., motion);
471            assert_eq!(app.game.blocks.iter().all(|b| b.flash == 0.), flash);
472            preferences::set_feedback_policy(FeedbackPolicy::default());
473            app.render();
474            assert_eq!(app.game.particles.is_empty(), motion);
475            assert_eq!(app.game.blocks.iter().all(|b| b.flash == 0.), flash);
476            assert_eq!(
477                (app.game.time, app.game.ball, app.game.score, app.game.lives),
478                state
479            );
480            preferences::set_feedback_policy(FeedbackPolicy::new(true, true, 1.).unwrap());
481            app.render(); // no advance call: render itself must consume live policy
482            assert_eq!(app.game.particles.len(), 0);
483            assert!(app.game.blocks.iter().all(|b| b.flash == 0.));
484        }
485    }
486
487    #[test]
488    fn muted_visuals_preserve_accepted_pickup_save_audio_and_reset_drops_pending_cues() {
489        let _restore = RestorePolicy::new();
490        for reduced in [false, true] {
491            preferences::set_feedback_policy(FeedbackPolicy::new(reduced, reduced, 1.).unwrap());
492            let mut app = Orbit::new();
493            app.advance_input(
494                0.,
495                Input {
496                    launch: true,
497                    ..Default::default()
498                },
499            );
500            assert_eq!(app.presentation.take_cues().count(), 0);
501            app.advance_input(DT, Input::default());
502            assert_eq!(
503                app.presentation.take_cues().collect::<Vec<_>>(),
504                [(Cue::Jump, 0.45)]
505            );
506            app.game.ball = [100., 676.];
507            app.game.velocity = [0., 325.];
508            app.game.drops.push(game::Drop {
509                position: [app.game.paddle_x, game::PADDLE_Y - 2.],
510                kind: game::Pickup::Wide,
511            });
512            app.advance_input(6. * DT, Input::default());
513            assert_eq!((app.game.saves, app.game.lives), (1, 3));
514            assert_eq!(app.presentation.notice, Some(("WIDE PADDLE", 50)));
515            assert_eq!(
516                app.presentation.take_cues().collect::<Vec<_>>(),
517                [(Cue::Pickup, 0.55)]
518            );
519            assert_eq!(app.game.particles.is_empty(), reduced);
520            app.advance_input(0., Input::default());
521            assert_eq!(app.presentation.take_cues().count(), 0);
522            app.game.ball = [100., 676.];
523            app.game.velocity = [0., 325.];
524            app.advance_input(DT, Input::default());
525            assert_eq!(app.game.lives, 2);
526            app.restart();
527            assert_eq!(app.presentation.take_cues().count(), 0);
528            assert_eq!(app.presentation.notice, None);
529            assert_eq!(app.presentation.feedback.impact().emphasis, 0.);
530            assert_eq!(app.game.policy.reduced_motion(), reduced);
531        }
532    }
533
534    #[test]
535    fn ready_session_keeps_steering_and_charging_at_each_host_frame_rate() {
536        for fps in [30, 60, 144] {
537            let mut app = Orbit::new();
538            for _ in 0..fps * 2 {
539                app.advance(1.0 / f64::from(fps), 1., 0);
540            }
541            assert_eq!(app.session.tick(), 240);
542            assert_eq!(app.session_state(), SessionState::Playing);
543            assert_eq!(app.game.phase, game::Phase::Ready);
544            assert_eq!(app.game.serve_charge.power(), 1.);
545            assert!(app.game.paddle_x > 500.);
546        }
547    }
548
549    #[test]
550    fn sampled_edge_survives_sub_tick_frames_and_launches_once_during_catchup() {
551        let mut app = Orbit::new();
552        app.advance_input(
553            DT / 4.,
554            Input {
555                launch: true,
556                ..Input::default()
557            },
558        );
559        app.advance_input(DT / 4., Input::default());
560        assert_eq!(app.game.phase, game::Phase::Ready);
561        app.advance_input(DT * 5.5, Input::default());
562        assert_eq!(app.game.phase, game::Phase::Playing);
563        assert!((app.game.ball_save - (2.5 - 5. / 120.)).abs() < 0.0001);
564        assert_eq!(app.session.tick(), 6);
565    }
566
567    #[test]
568    fn catchup_does_not_reuse_launch_after_a_lost_life() {
569        let mut app = Orbit::new();
570        app.game.phase = game::Phase::Playing;
571        app.game.ball = [100., 676.];
572        app.game.velocity = [0., 325.];
573        // This press happens during play and is consumed before the drain.
574        app.advance(6. * DT, 0., 1);
575        assert_eq!(app.game.lives, 2);
576        assert_eq!(app.game.phase, game::Phase::Ready);
577        assert_eq!(app.game.feedback(), Some(game::Feedback::LifeLost));
578        app.advance(6. * DT, 0., 1);
579        assert_eq!(app.game.phase, game::Phase::Ready);
580        app.advance(0., 0., 0);
581        app.advance(DT, 0., 1);
582        assert_eq!(app.game.phase, game::Phase::Playing);
583    }
584
585    #[test]
586    fn pause_discards_launch_edges_and_never_advances_gameplay_time() {
587        let mut app = Orbit::new();
588        app.advance(DT / 2., 0., 1);
589        assert!(app.set_paused(true));
590        let ball = app.game.ball;
591        for _ in 0..4 {
592            app.advance(10., 1., 1);
593        }
594        assert_eq!((app.game.ball, app.game.time), (ball, 0.));
595        assert!(app.set_paused(false));
596        app.advance(DT / 2., 0., 1);
597        assert_eq!(app.session.tick(), 1);
598        assert_eq!(app.game.phase, game::Phase::Ready);
599        app.advance(0., 0., 0);
600        app.advance(DT, 0., 1);
601        assert_eq!(app.game.phase, game::Phase::Playing);
602    }
603
604    #[test]
605    fn quick_restart_resumes_and_clears_fractional_time_and_pending_launch() {
606        let mut app = Orbit::new();
607        app.game.score = 1000;
608        app.advance(DT * 0.75, 0., 1);
609        app.set_paused(true);
610        app.advance(0., 0., 3);
611        app.advance(0., 0., 0);
612        assert_eq!(app.session_state(), SessionState::Playing);
613        assert_eq!((app.game.score, app.game.lives, app.game.sector), (0, 3, 1));
614        assert_eq!(app.game.feedback(), Some(game::Feedback::Restarted));
615        app.advance(DT / 2., 0., 0);
616        assert_eq!(app.game.time, 0.);
617        app.advance(DT / 2., 0., 0);
618        assert_eq!(app.session.tick(), 1);
619        assert_eq!(app.game.phase, game::Phase::Ready);
620    }
621
622    #[test]
623    fn retry_and_held_restart_do_not_launch_or_repeatedly_reset_during_catchup() {
624        for button in [1, 2] {
625            let mut app = Orbit::new();
626            app.game.phase = game::Phase::Lost;
627            app.game.lives = 0;
628            app.advance(1., 0., button);
629            assert_eq!(app.game.phase, game::Phase::Ready);
630            assert_eq!(app.game.time, 0.);
631            app.advance(6. * DT, 0., button);
632            assert_eq!(app.session.tick(), 6);
633            assert_eq!(app.game.phase, game::Phase::Ready);
634            assert!(app.game.serve_charge.power() > 0.);
635            app.advance(0., 0., 0);
636            app.advance(DT, 0., 1);
637            assert_eq!(app.game.phase, game::Phase::Playing);
638        }
639    }
640
641    #[test]
642    fn terminal_result_stops_remaining_catchup_and_retry_starts_a_fresh_clock() {
643        for won in [false, true] {
644            let mut app = Orbit::new();
645            app.game.phase = game::Phase::Playing;
646            if won {
647                app.game.sector = 2;
648                for block in &mut app.game.blocks {
649                    block.health = 0;
650                }
651            } else {
652                app.game.lives = 1;
653                app.game.ball = [100., 676.];
654                app.game.velocity = [0., 325.];
655            }
656            app.advance(12. * DT, 0., 0);
657            assert_eq!(
658                app.session_state(),
659                if won {
660                    SessionState::Won
661                } else {
662                    SessionState::Lost
663                }
664            );
665            assert_eq!(app.game.time, DT as f32);
666            let result = (app.game.time, app.game.ball, app.game.score, app.game.lives);
667            app.advance(30., 1., 0);
668            assert_eq!(
669                (app.game.time, app.game.ball, app.game.score, app.game.lives),
670                result
671            );
672            assert!(!app.set_paused(true));
673            app.advance(0., 0., 1);
674            app.advance(0., 0., 0);
675            assert_eq!(app.session.tick(), 0);
676            assert_eq!(app.game.phase, game::Phase::Ready);
677            assert_eq!(app.game.remaining(), 35);
678        }
679    }
680
681    #[test]
682    fn sector_countdown_freezes_on_pause_and_does_not_buffer_a_transition_launch() {
683        let mut app = Orbit::new();
684        app.game.phase = game::Phase::Playing;
685        for block in &mut app.game.blocks {
686            block.health = 0;
687        }
688        app.advance(DT, 0., 0);
689        assert_eq!(app.game.phase, game::Phase::Transition);
690        let remaining = app.game.transition_remaining();
691        let time = app.game.time;
692        app.set_paused(true);
693        app.advance(20., 1., 0);
694        assert_eq!(
695            (app.game.transition_remaining(), app.game.time),
696            (remaining, time)
697        );
698        app.set_paused(false);
699        for _ in 0..16 {
700            app.advance(12. * DT, 0., 1);
701        }
702        assert_eq!((app.game.sector, app.game.phase), (2, game::Phase::Ready));
703        assert!(app.game.serve_charge.power() > 0.);
704        app.advance(0., 0., 0);
705        app.advance(DT, 0., 1);
706        assert_eq!(app.game.phase, game::Phase::Playing);
707    }
708
709    #[test]
710    fn session_autoplay_still_wins_both_sectors() {
711        let mut app = Orbit::new();
712        for _ in 0..120 * 600 {
713            let input = app.game.autoplay();
714            app.advance_input(DT, input);
715            if matches!(app.session_state(), SessionState::Won | SessionState::Lost) {
716                break;
717            }
718        }
719        assert_eq!(app.session_state(), SessionState::Won);
720        assert_eq!(app.game.clears, 70);
721        assert!(app.game.ccd_impacts > 70);
722    }
723
724    #[test]
725    fn quick_input_tap_survives_zero_tick_and_frame_is_rgba() {
726        let mut app = Orbit::new();
727        app.advance(0.0, 0.0, 1);
728        app.advance(0.0, 0.0, 0);
729        app.advance(1.0 / 120.0, 0.0, 0);
730        assert_eq!(app.game.phase, game::Phase::Playing);
731        app.render();
732        assert_eq!(app.canvas.frame.pixels().len(), (WIDTH * HEIGHT) as usize);
733        assert!(app.canvas.frame.pixels().iter().all(|p| p[3] == 255));
734        assert!(
735            app.canvas
736                .frame
737                .pixels()
738                .iter()
739                .filter(|p| p[0] > 100)
740                .count()
741                > 5000
742        );
743    }
744
745    #[test]
746    fn results_compare_with_the_supplied_best_once_and_restart_keeps_it() {
747        for (best, new_best) in [(None, true), (Some(100), true), (Some(99_999), false)] {
748            let mut app = Orbit::new();
749            app.set_personal_best(best);
750            app.game.phase = game::Phase::Playing;
751            app.game.score = 4321;
752            app.game.lives = 1;
753            app.game.ball = [100., 676.];
754            app.game.velocity = [0., 325.];
755            app.advance(DT, 0., 0);
756            assert_eq!(app.session_state(), SessionState::Lost);
757            let results = app.presentation.results.expect("results card");
758            assert_eq!((results.previous_best, results.new_best), (best, new_best));
759            assert_eq!(results.rank.title, "SPACE TOURIST");
760            let run = app.take_finished_run().expect("one record");
761            assert_eq!((run.won, run.score, run.new_best), (false, 4321, new_best));
762            app.advance(1., 0., 0);
763            assert_eq!(
764                app.take_finished_run(),
765                None,
766                "terminal frames never re-record"
767            );
768            let expected = if new_best { Some(4321) } else { best };
769            assert_eq!(app.personal_best(), expected);
770            app.restart();
771            assert!(app.presentation.results.is_none());
772            assert_eq!(app.personal_best(), expected);
773            assert_eq!(app.take_finished_run(), None);
774        }
775    }
776
777    #[test]
778    fn juice_freezes_with_pause_and_presentation_detail_never_adds_cues() {
779        let _restore = RestorePolicy::new();
780        let mut app = Orbit::new();
781        app.game.phase = game::Phase::Playing;
782        app.game.ball = [80., 380.];
783        app.game.velocity = [0., -12000.];
784        app.advance_input(DT, Input::default());
785        assert!(app.presentation.juice.pops.iter().any(Option::is_some));
786        assert!(app.presentation.juice.chime.is_some());
787        let cues: Vec<_> = app.presentation.take_cues().collect();
788        assert!(cues.len() <= 2, "{cues:?}");
789        let time = app.presentation.juice.time;
790        app.set_paused(true);
791        app.advance_input(5., Input::default());
792        app.render();
793        assert_eq!(app.presentation.juice.time, time);
794        assert!(app.presentation.juice.pops.iter().any(Option::is_some));
795        app.set_paused(false);
796        for _ in 0..240 {
797            app.advance_input(DT, Input::default());
798        }
799        assert!(app.presentation.juice.pops.iter().all(Option::is_none));
800    }
801
802    #[test]
803    fn steering_hint_retires_after_real_steering_and_survives_restart() {
804        let mut app = Orbit::new();
805        assert!(!app.presentation.juice.steering_learned());
806        for _ in 0..120 {
807            app.advance_input(
808                DT,
809                Input {
810                    axis: 1.,
811                    ..Input::default()
812                },
813            );
814        }
815        assert!(app.presentation.juice.steering_learned());
816        app.restart();
817        assert!(app.presentation.juice.steering_learned());
818    }
819
820    #[test]
821    fn steering_key_caps_flank_the_paddle_until_the_player_has_steered() {
822        let _restore = RestorePolicy::new();
823        // Bright key-cap ink in the strip left of the paddle.
824        let lit = |app: &Orbit| {
825            let left = (app.game.paddle_x - app.game.paddle_half) as usize;
826            let mut count = 0;
827            for y in 626..648 {
828                for x in left - 70..left - 8 {
829                    let p = app.canvas.frame.pixels()[y * WIDTH as usize + x];
830                    count += usize::from(p[0] > 150 && p[1] > 150);
831                }
832            }
833            count
834        };
835        let mut app = Orbit::new();
836        app.render();
837        assert!(
838            lit(&app) > 20,
839            "steering keys shown on the first ready card"
840        );
841        app.presentation.juice.steered(1., 1.);
842        app.render();
843        assert_eq!(lit(&app), 0, "and retired once learned");
844    }
845
846    #[test]
847    fn every_screen_renders_opaque_and_reduced_motion_ignores_camera_kick() {
848        let _restore = RestorePolicy::new();
849        let mut app = Orbit::new();
850        app.set_personal_best(Some(5000));
851        app.game.phase = game::Phase::Playing;
852        app.game.extra_balls.push(game::Ball {
853            position: [200., 400.],
854            velocity: [0., -300.],
855        });
856        app.game.sticky = 2;
857        app.game.time = 15.;
858        app.render();
859        app.presentation
860            .juice
861            .accept(presentation::Spark::Drain { at: [100., 653.] });
862        let kicked = app.presentation.juice.shake();
863        assert_ne!(kicked, [0, 0]);
864        preferences::set_feedback_policy(FeedbackPolicy::new(true, true, 1.).unwrap());
865        app.render();
866        assert_eq!(app.presentation.juice.shake(), [0, 0]);
867        for phase in [game::Phase::Transition, game::Phase::Won, game::Phase::Lost] {
868            app.game.phase = phase;
869            app.advance(0., 0., 0);
870            app.render();
871            assert!(app.canvas.frame.pixels().iter().all(|p| p[3] == 255));
872        }
873        assert!(app.presentation.results.is_some());
874        app.set_paused(false);
875        app.restart();
876        app.set_paused(true);
877        app.render();
878        assert!(app.canvas.frame.pixels().iter().all(|p| p[3] == 255));
879    }
880}