physics_2d/
lib.rs

1//! Interactive original 2D physics sandbox. No imported textures, fonts, or scene assets.
2//!
3//! The lab starts running immediately. Space pauses, Enter drops the selected
4//! shape, and N advances one 120 Hz tick while paused. Reset preserves the
5//! selected shape and pause state, but clears simulation time and cooldowns.
6//! I inspects a body under the cursor without waking it. Canvas hints follow
7//! remapped controls; reduced motion/flash only affect the cosmetic pulse ring.
8//!
9//! Launch the native renderer with the existing entry point:
10//! ```no_run
11//! physics_2d::run();
12//! ```
13use ferravex_core::FrameStep;
14use ferravex_core::session::GameSession;
15use ferravex_physics::d2::{
16    self, ColliderBuilder, JointBuilder, PhysicsWorld, QueryOptions, QueryReport, RayHit,
17    RigidBodyBuilder, RigidBodyHandle,
18};
19use ferravex_physics::{ContactEvent, JointHandle};
20use ferravex_render::audio::{Cue, GameAudio, Surface};
21use ferravex_render::input::{ActionKind, Binding, InputCode, PlayerInput, Preset};
22use ferravex_render::{preferences, prelude::*, ui};
23
24#[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
25mod capture;
26mod hud;
27mod juice;
28mod look;
29mod presentation;
30mod quips;
31mod scene;
32mod toys;
33
34use toys::{Fun, Scenario};
35
36const MAX_BODIES: usize = 240;
37const TICK_HZ: f64 = 120.0;
38
39#[derive(Clone, Copy, Debug)]
40enum Shape {
41    Ball(f32),
42    Box(Vec2),
43    Dumbbell,
44    /// A domino: a tall thin box drawn with pips.
45    Plank(Vec2),
46}
47
48struct Body {
49    handle: RigidBodyHandle,
50    shape: Shape,
51    color: Color,
52    previous_position: Vec2,
53    previous_angle: f32,
54}
55
56struct Sandbox {
57    physics: PhysicsWorld,
58    bodies: Vec<Body>,
59    platforms: Vec<(Vec2, Vec2)>,
60    links: Vec<JointHandle>,
61    impact: Option<(f32, Surface)>,
62    pulse_time: f32,
63    pulse_center: Vec2,
64}
65
66impl Sandbox {
67    fn new() -> Self {
68        let mut world = Self::shell();
69        for row in 0..6 {
70            for column in 0..(6 - row) {
71                world.spawn(
72                    vec2(
73                        -4.0 + column as f32 * 1.06 + row as f32 * 0.53,
74                        0.51 + row as f32 * 1.03,
75                    ),
76                    false,
77                );
78            }
79        }
80        for index in 0..9 {
81            world.spawn(
82                vec2(
83                    5.8 + (index % 3) as f32 * 1.05,
84                    5.0 + (index / 3) as f32 * 1.1,
85                ),
86                true,
87            );
88        }
89        world.mechanisms();
90        world
91    }
92
93    /// Floor, walls and platforms shared by every scenario.
94    fn shell() -> Self {
95        let mut world = Self {
96            physics: PhysicsWorld::new([0.0, -9.81]),
97            bodies: Vec::new(),
98            platforms: vec![],
99            links: Vec::new(),
100            impact: None,
101            pulse_time: 0.,
102            pulse_center: Vec2::ZERO,
103        };
104        world.record_impacts();
105        for (position, half) in [
106            (vec2(0.0, -0.5), vec2(12.0, 0.5)),
107            (vec2(-12.25, 6.0), vec2(0.25, 6.5)),
108            (vec2(12.25, 6.0), vec2(0.25, 6.5)),
109            (vec2(-8.0, 0.8), vec2(2.0, 0.8)),
110            (vec2(8.0, 0.8), vec2(2.0, 0.8)),
111        ] {
112            world
113                .physics
114                .add_box(position.to_array(), half.to_array(), false);
115            world.platforms.push((position, half));
116        }
117        world
118    }
119
120    fn mechanisms(&mut self) {
121        let anchor = self
122            .physics
123            .insert_body(RigidBodyBuilder::fixed().translation(vec2(-9., 11.)))
124            .unwrap();
125        let position = vec2(-8.5, 10.);
126        let (rod, _) = self.physics.insert(
127            RigidBodyBuilder::dynamic().translation(position),
128            ColliderBuilder::cuboid(0.18, 1.),
129        );
130        self.bodies.push(Body {
131            handle: rod,
132            shape: Shape::Box(vec2(0.18, 1.)),
133            color: ui::CYAN,
134            previous_position: position,
135            previous_angle: 0.,
136        });
137        self.links.push(
138            self.physics
139                .insert_joint(
140                    anchor,
141                    rod,
142                    JointBuilder::hinge()
143                        .local_anchor2(vec2(-0.5, 1.))
144                        .limits(-1.2, 1.2),
145                )
146                .unwrap(),
147        );
148        let position = vec2(-8.5, 8.4);
149        let (tip, _) = self.physics.insert(
150            RigidBodyBuilder::dynamic().translation(position),
151            ColliderBuilder::cuboid(0.4, 0.6),
152        );
153        self.bodies.push(Body {
154            handle: tip,
155            shape: Shape::Box(vec2(0.4, 0.6)),
156            color: ui::AMBER,
157            previous_position: position,
158            previous_angle: 0.,
159        });
160        self.links.push(
161            self.physics
162                .insert_joint(
163                    rod,
164                    tip,
165                    JointBuilder::fixed()
166                        .local_anchor1(vec2(0., -1.))
167                        .local_anchor2(vec2(0., 0.6)),
168                )
169                .unwrap(),
170        );
171        let anchor = self
172            .physics
173            .insert_body(RigidBodyBuilder::fixed().translation(vec2(-5.8, 11.)))
174            .unwrap();
175        self.spawn(vec2(-5., 9.), true);
176        let bob = self.bodies.last().unwrap().handle;
177        self.links.push(
178            self.physics
179                .insert_joint(
180                    anchor,
181                    bob,
182                    JointBuilder::distance((0.8_f32 * 0.8 + 4.).sqrt()),
183                )
184                .unwrap(),
185        );
186        let anchor = self
187            .physics
188            .insert_body(RigidBodyBuilder::fixed().translation(vec2(8.2, 12.)))
189            .unwrap();
190        let position = vec2(8.2, 10.);
191        let bob = self
192            .physics
193            .insert_compound(
194                RigidBodyBuilder::dynamic().translation(position),
195                [
196                    ColliderBuilder::cuboid(0.75, 0.1),
197                    ColliderBuilder::ball(0.28).translation(vec2(-0.75, 0.)),
198                    ColliderBuilder::ball(0.28).translation(vec2(0.75, 0.)),
199                ],
200            )
201            .unwrap();
202        self.bodies.push(Body {
203            handle: bob,
204            shape: Shape::Dumbbell,
205            color: ui::CYAN,
206            previous_position: position,
207            previous_angle: 0.,
208        });
209        self.links.push(
210            self.physics
211                .insert_joint(anchor, bob, JointBuilder::spring(2., 20., 3.))
212                .unwrap(),
213        );
214    }
215
216    fn spawn(&mut self, position: Vec2, ball: bool) -> bool {
217        if self.bodies.len() >= MAX_BODIES || !position.is_finite() {
218            return false;
219        }
220        let (handle, shape, color) = if ball {
221            (
222                self.physics.add_ball(position.to_array(), 0.44, true),
223                Shape::Ball(0.44),
224                ui::CYAN,
225            )
226        } else {
227            (
228                self.physics
229                    .add_box(position.to_array(), [0.48, 0.48], true),
230                Shape::Box(vec2(0.48, 0.48)),
231                ui::AMBER,
232            )
233        };
234        let collider = self.physics.bodies[handle].colliders()[0];
235        self.physics.colliders[collider].set_restitution(if ball { 0.42 } else { 0.08 });
236        self.physics.bodies[handle].enable_ccd(true);
237        self.bodies.push(Body {
238            handle,
239            shape,
240            color,
241            previous_position: position,
242            previous_angle: 0.0,
243        });
244        true
245    }
246
247    fn pulse(&mut self, center: Vec2) -> bool {
248        if self.pulse_time > 0. || !center.is_finite() {
249            return false;
250        }
251        self.pulse_time = 0.65;
252        self.pulse_center = center;
253        for body in &self.bodies {
254            let rigid = &mut self.physics.bodies[body.handle];
255            let position = rigid.translation();
256            if let Some(mut kick) = ferravex_play::motion::radial_velocity(
257                center.extend(0.),
258                position.extend(0.),
259                8.,
260                11.,
261            ) {
262                kick.y = kick.y.max(0.) + kick.length() * 0.55;
263                rigid.apply_impulse(kick.truncate() * rigid.mass(), true);
264            }
265        }
266        true
267    }
268
269    fn step(&mut self, dt: f32) {
270        self.pulse_time = (self.pulse_time - dt).max(0.);
271        let mut velocities = [Vec2::ZERO; MAX_BODIES];
272        for (i, body) in self.bodies.iter_mut().enumerate() {
273            velocities[i] = Vec2::from_array(self.physics.bodies[body.handle].linvel().to_array());
274            let rigid_body = &self.physics.bodies[body.handle];
275            body.previous_position = Vec2::from_array(rigid_body.translation().to_array());
276            let axis = *rigid_body.rotation() * d2::Vector::X;
277            body.previous_angle = axis.y.atan2(axis.x);
278        }
279        self.physics.step(dt);
280        self.impact = None;
281        for (body, before) in self.bodies.iter().zip(velocities) {
282            // Joint corrections and gravity alone are not collision feedback.
283            // Only an accepted solid contact start can produce an impact cue.
284            let started = self.physics.contact_events().iter().any(|event| {
285                let ContactEvent::Started(a, b) = *event else {
286                    return false;
287                };
288                self.physics
289                    .contact_pair(a, b)
290                    .is_some_and(|pair| !pair.sensor)
291                    && [a, b]
292                        .iter()
293                        .any(|id| self.physics.colliders[*id].parent() == Some(body.handle))
294            });
295            if !started {
296                continue;
297            }
298            let after = Vec2::from_array(self.physics.bodies[body.handle].linvel().to_array());
299            let change = (after - before).length();
300            if before.length() > 1.
301                && change > 1.2
302                && self.impact.is_none_or(|(strength, _)| change > strength)
303            {
304                self.impact = Some((
305                    change,
306                    if matches!(body.shape, Shape::Dumbbell) {
307                        Surface::Metal
308                    } else if matches!(body.shape, Shape::Ball(_)) {
309                        Surface::Stone
310                    } else {
311                        Surface::Wood
312                    },
313                ));
314            }
315        }
316    }
317}
318
319#[derive(Default)]
320struct LabInput {
321    reset: bool,
322    toggle_pause: bool,
323    single_step: bool,
324    ball: Option<bool>,
325    // A secondary click overrides the selected shape for this drop only.
326    drop: Option<(Vec2, bool)>,
327    pulse: Option<Vec2>,
328}
329
330/// Render-frame toy commands. CHAOS queues for the next actual tick (or places
331/// immediately while paused, like a drop); a scene toggle rebuilds like RESET.
332#[derive(Clone, Copy, Debug, Default)]
333struct ToyInput {
334    chaos: bool,
335    scene: bool,
336}
337
338struct Lab {
339    sandbox: Sandbox,
340    fun: Fun,
341    session: GameSession,
342    ball: bool,
343    impact_cooldown: f32,
344    impact: Option<(f32, Surface)>,
345    pulsed: bool,
346    /// The latest accepted or refused command, for presentation only. The HUD
347    /// shows refusals as a red wobble and a short popup on the tool involved.
348    notice: Notice,
349    /// Increments with every notice, so presentation reacts exactly once.
350    notice_serial: u32,
351    pending: LabCommands,
352    selected: Option<RigidBodyHandle>,
353}
354
355/// What the lab last did with a command. Presentation maps these to icons,
356/// key caps and one- or two-word popups instead of sentences.
357#[derive(Clone, Copy, Debug, PartialEq, Eq)]
358enum Notice {
359    /// Freshly opened lab.
360    Ready,
361    /// RESET or a scene swap rebuilt the scene.
362    Rebuilt,
363    Paused,
364    Resumed,
365    /// One manual tick while paused.
366    Stepped,
367    /// STEP pressed while running.
368    StepWhileRunning,
369    Dropped,
370    /// A drop at a non-finite position.
371    DropRejected,
372    /// A drop refused by the body cap.
373    DropFull,
374    Chaos,
375    /// CHAOS refused by the body cap.
376    ChaosFull,
377    Pulsed,
378    /// A pulse requested while paused.
379    PulsePaused,
380    PulseRecharging,
381    /// A pulse at a non-finite position.
382    PulseRejected,
383    /// Inspection pinned a body.
384    Selected,
385    /// Inspection found nothing and cleared the selection.
386    Missed,
387}
388
389/// How the solver currently treats a body.
390#[derive(Clone, Copy, Debug, PartialEq, Eq)]
391enum Rest {
392    Awake,
393    Waking,
394    Asleep,
395}
396
397/// Read-only diagnostics for the inspected body, drawn as an icon tag.
398#[derive(Clone, Copy, Debug)]
399struct Selection {
400    /// One-based scene number.
401    number: usize,
402    shape: Shape,
403    rest: Rest,
404    speed: f32,
405    /// Last-tick solid contact pairs.
406    contacts: usize,
407    position: Vec2,
408}
409
410/// At most one pending UI drop and pulse; repeated zero-tick requests coalesce.
411#[derive(Default)]
412struct LabCommands {
413    drop: Option<(Vec2, bool)>,
414    pulse: Option<Vec2>,
415}
416
417struct Inspection {
418    hits: [Option<RayHit>; 8],
419    report: QueryReport,
420}
421
422impl Sandbox {
423    fn inspect(&self, point: Vec2) -> Result<Inspection, d2::QueryError> {
424        let mut hits = [None; 8];
425        // Zero travel inspects actual collider geometry at the current pose,
426        // including compound children. No simulation step or refresh is needed.
427        let report = self.physics.spherecast_into(
428            point.to_array(),
429            [1., 0.],
430            0.04,
431            QueryOptions::new(0.),
432            &mut hits,
433        )?;
434        Ok(Inspection { hits, report })
435    }
436}
437
438impl Inspection {
439    fn body(&self, sandbox: &Sandbox) -> Option<RigidBodyHandle> {
440        self.hits
441            .iter()
442            .take(self.report.written)
443            .flatten()
444            .filter_map(|hit| hit.body)
445            .find(|handle| sandbox.bodies.iter().any(|body| body.handle == *handle))
446    }
447}
448
449/// Cosmetic time is independent of the simulation's pulse cooldown.
450#[derive(Default)]
451struct PulseVisual {
452    ring: Option<(Vec2, f32)>,
453    enabled: bool,
454    intensity: f32,
455}
456
457impl PulseVisual {
458    fn begin_frame(&mut self, elapsed: f32) {
459        let policy = preferences::feedback_policy();
460        self.enabled =
461            !policy.reduced_motion() && !policy.reduced_flash() && policy.intensity() > 0.;
462        self.intensity = policy.intensity();
463        if !self.enabled {
464            self.ring = None;
465        } else if let Some((_, age)) = &mut self.ring {
466            if elapsed.is_finite() {
467                *age += elapsed.clamp(0., 0.1);
468            }
469            if *age >= 0.65 {
470                self.ring = None;
471            }
472        }
473    }
474
475    fn accepted_pulse(&mut self, center: Vec2) {
476        if self.enabled {
477            self.ring = Some((center, 0.));
478        }
479    }
480}
481
482impl Lab {
483    fn new() -> Self {
484        let sandbox = Sandbox::new();
485        let mut fun = Fun::default();
486        fun.on_rebuild(&sandbox);
487        Self {
488            sandbox,
489            fun,
490            // A sandbox has no start screen or terminal state.
491            session: GameSession::try_new(TICK_HZ, 8, true).expect("valid lab fixed clock"),
492            ball: true,
493            impact_cooldown: 0.,
494            impact: None,
495            pulsed: false,
496            notice: Notice::Ready,
497            notice_serial: 0,
498            pending: LabCommands::default(),
499            selected: None,
500        }
501    }
502
503    fn notice(&mut self, notice: Notice) {
504        self.notice = notice;
505        self.notice_serial = self.notice_serial.wrapping_add(1);
506    }
507
508    fn reset(&mut self) {
509        let paused = self.session.is_paused();
510        self.sandbox = Sandbox::with_scenario(self.fun.scenario);
511        self.fun.on_rebuild(&self.sandbox);
512        self.session.restart();
513        self.session.set_paused(paused);
514        self.impact_cooldown = 0.;
515        self.impact = None;
516        self.pulsed = false;
517        self.pending = LabCommands::default();
518        self.selected = None;
519        self.notice(Notice::Rebuilt);
520    }
521
522    /// One deterministic CHAOS burst, bounded by the body cap.
523    fn chaos(&mut self) {
524        let count = self.sandbox.chaos(self.fun.chaos_serial);
525        if count == 0 {
526            self.notice(Notice::ChaosFull);
527            return;
528        }
529        self.fun.touch();
530        self.fun.chaos_serial = self.fun.chaos_serial.wrapping_add(1);
531        self.fun.stats.chaos += 1;
532        self.fun.events.chaos += count;
533        self.notice(Notice::Chaos);
534    }
535
536    fn drop_position(position: Vec2) -> Vec2 {
537        vec2(position.x.clamp(-11.2, 11.2), position.y.clamp(0.6, 12.4))
538    }
539
540    fn button_enabled(&self, index: usize) -> bool {
541        match index {
542            2 | 7 => self.sandbox.bodies.len() < MAX_BODIES,
543            3 => self.session.is_playing() && self.sandbox.pulse_time == 0.,
544            5 => self.session.is_paused(),
545            _ => true,
546        }
547    }
548
549    fn select_body(&mut self, inspection: Option<&Inspection>) {
550        self.selected = inspection.and_then(|query| query.body(&self.sandbox));
551        self.notice(if self.selected.is_some() {
552            Notice::Selected
553        } else {
554            Notice::Missed
555        });
556    }
557
558    /// Read-only diagnostics for the selected body, or `None` when nothing is
559    /// selected or the selected body no longer exists.
560    fn selection(&self) -> Option<Selection> {
561        let handle = self.selected?;
562        let (index, body) = self
563            .sandbox
564            .bodies
565            .iter()
566            .enumerate()
567            .find(|(_, body)| body.handle == handle)?;
568        let sleep = self.sandbox.physics.sleep_state(handle)?;
569        let rigid = &self.sandbox.physics.bodies[handle];
570        let contacts = self
571            .sandbox
572            .physics
573            .contacts()
574            .filter(|pair| {
575                !pair.sensor
576                    && [pair.collider1, pair.collider2]
577                        .iter()
578                        .any(|id| self.sandbox.physics.colliders[*id].parent() == Some(handle))
579            })
580            .count();
581        Some(Selection {
582            number: index + 1,
583            shape: body.shape,
584            rest: if sleep.sleeping {
585                Rest::Asleep
586            } else if sleep.wake_requested {
587                Rest::Waking
588            } else {
589                Rest::Awake
590            },
591            speed: rigid.linvel().length(),
592            contacts,
593            position: rigid.translation(),
594        })
595    }
596
597    #[cfg(test)]
598    fn update(&mut self, elapsed_seconds: f64, input: LabInput) -> FrameStep {
599        self.update_with_actions(elapsed_seconds, input, LabCommands::default)
600    }
601
602    #[cfg(test)]
603    fn update_toys(&mut self, elapsed_seconds: f64, input: LabInput, toys: ToyInput) -> FrameStep {
604        self.update_toys_with_actions(elapsed_seconds, input, toys, || {
605            (LabCommands::default(), false)
606        })
607    }
608
609    #[cfg(test)]
610    fn update_with_actions(
611        &mut self,
612        elapsed_seconds: f64,
613        input: LabInput,
614        mut actions: impl FnMut() -> LabCommands,
615    ) -> FrameStep {
616        self.update_toys_with_actions(elapsed_seconds, input, ToyInput::default(), || {
617            (actions(), false)
618        })
619    }
620
621    /// The full controller. `actions` is read once per actual tick (or once on
622    /// a paused zero-tick editor frame) and returns that tick's gameplay
623    /// commands plus whether its CHAOS edge was pressed.
624    fn update_toys_with_actions(
625        &mut self,
626        elapsed_seconds: f64,
627        input: LabInput,
628        toys: ToyInput,
629        mut actions: impl FnMut() -> (LabCommands, bool),
630    ) -> FrameStep {
631        self.impact = None;
632        self.pulsed = false;
633        self.fun.begin_frame();
634        // Reset (or a scene toggle, which is a rebuild) wins over every edge
635        // from this frame, including pending drops and CHAOS.
636        if input.reset || toys.scene {
637            if toys.scene {
638                self.fun.scenario = match self.fun.scenario {
639                    Scenario::Workshop => Scenario::Dominoes,
640                    Scenario::Dominoes => Scenario::Workshop,
641                };
642            }
643            self.reset();
644            return self.session.advance(0.);
645        }
646        if input.toggle_pause {
647            self.fun.pending_chaos = false;
648            self.pending = LabCommands::default();
649            self.session.toggle_pause();
650            self.notice(if self.session.is_paused() {
651                Notice::Paused
652            } else {
653                Notice::Resumed
654            });
655        }
656        if let Some(ball) = input.ball {
657            self.ball = ball;
658        }
659        if self.pending.drop.is_none() {
660            self.pending.drop = input.drop;
661        }
662        if self.pending.pulse.is_none() {
663            self.pending.pulse = input.pulse;
664        }
665        self.fun.pending_chaos |= toys.chaos;
666
667        let frame = if input.single_step && self.session.is_paused() {
668            let frame = self.session.step_paused().expect("paused lab step");
669            self.notice(Notice::Stepped);
670            frame
671        } else {
672            if input.single_step {
673                self.notice(Notice::StepWhileRunning);
674            }
675            self.session.advance(if input.toggle_pause {
676                0.
677            } else {
678                elapsed_seconds
679            })
680        };
681        // Paused placement is an editor operation, deliberately available
682        // without a tick. Running gameplay edges stay in PlayerInput until here.
683        if self.session.is_paused() && frame.steps == 0 {
684            let (commands, chaos) = actions();
685            self.apply_commands(commands, chaos);
686        }
687        for _ in 0..frame.steps {
688            let (commands, chaos) = actions();
689            self.apply_commands(commands, chaos);
690            self.impact_cooldown = (self.impact_cooldown - frame.dt).max(0.);
691            self.sandbox.step(frame.dt);
692            self.fun.after_tick(&mut self.sandbox, frame.dt);
693            if self.impact_cooldown == 0.
694                && let Some(impact) = self.sandbox.impact
695            {
696                self.impact = Some(impact);
697                self.impact_cooldown = 0.055;
698            }
699        }
700        frame
701    }
702
703    fn apply_commands(&mut self, actions: LabCommands, chaos: bool) {
704        let pending = std::mem::take(&mut self.pending);
705        if let Some((position, force_crate)) = pending.drop.or(actions.drop) {
706            let ball = self.ball && !force_crate;
707            if !position.is_finite() {
708                self.notice(Notice::DropRejected);
709            } else if self.sandbox.spawn(Self::drop_position(position), ball) {
710                self.fun.stats.drops += 1;
711                self.selected = self.sandbox.bodies.last().map(|body| body.handle);
712                self.notice(Notice::Dropped);
713            } else {
714                self.notice(Notice::DropFull);
715            }
716        }
717        if let Some(center) = pending.pulse.or(actions.pulse) {
718            if self.session.is_paused() {
719                self.notice(Notice::PulsePaused);
720            } else if center.is_finite() && self.sandbox.pulse(center) {
721                self.pulsed = true;
722                self.fun.stats.pulses += 1;
723                self.notice(Notice::Pulsed);
724            } else if !center.is_finite() {
725                self.notice(Notice::PulseRejected);
726            } else {
727                self.notice(Notice::PulseRecharging);
728            }
729        }
730        if std::mem::take(&mut self.fun.pending_chaos) | chaos {
731            self.chaos();
732        }
733    }
734}
735
736fn window_conf() -> Conf {
737    #[allow(unused_mut)]
738    let mut conf = ferravex_render::window_conf("Ferravex / 2D physics laboratory");
739    #[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
740    capture::window(&mut conf);
741    conf
742}
743
744#[cfg(test)]
745fn action_hint(input: &PlayerInput, action: &str) -> String {
746    let mut buffer = [0; 512];
747    input
748        .format_hint(action, &mut buffer)
749        .unwrap_or("Controls")
750        .into()
751}
752
753fn register_lab_actions(input: &mut PlayerInput) {
754    for (name, label, key, pad) in [
755        ("drop", "Drop selected shape", KeyCode::Enter, 7),
756        ("step", "Single step while paused", KeyCode::N, 5),
757        ("inspect", "Inspect body at cursor", KeyCode::I, 6),
758        (
759            "chaos",
760            "CHAOS: throw in fourteen shapes",
761            KeyCode::Key3,
762            10,
763        ),
764        ("domino", "Toggle the domino run", KeyCode::Key4, 11),
765    ] {
766        input
767            .action(
768                name,
769                label,
770                ActionKind::Button,
771                vec![
772                    Binding::digital(InputCode::Key(key as u16)),
773                    Binding::digital(InputCode::PadButton(pad)),
774                ],
775            )
776            .expect("valid lab input binding");
777    }
778    input
779        .action(
780            "stats",
781            "Show engine stats",
782            ActionKind::Button,
783            vec![Binding::digital(InputCode::Key(KeyCode::G as u16))],
784        )
785        .expect("valid lab input binding");
786}
787
788ferravex_render::game!(window_conf, game);
789async fn game() {
790    let mut demo = ferravex_render::demo::Demo::new();
791    let mut lab = Lab::new();
792    let mut sound = GameAudio::new();
793    let mut pulse_visual = PulseVisual::default();
794    let mut juice = juice::Juice::new();
795    juice.rebuild(lab.sandbox.bodies.len());
796    let mut hud = hud::Hud::default();
797    let mut grading = look::Grading::default();
798    let mut ambient = 0.;
799    // Personal bests are optional; autoplay demos never claim one.
800    #[allow(unused_mut)]
801    let mut bests = hud::Bests::load(!demo.autoplay);
802    #[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
803    let mut capture = capture::Capture::from_env();
804    let mut player_input = PlayerInput::preset("physics-2d", Preset::Lab2);
805    register_lab_actions(&mut player_input);
806    loop {
807        ui::warm_up_font();
808        // Editing and manual stepping remain available while the session pauses.
809        // Controls/Details and focus still suspend all sandbox input and time.
810        player_input.sample(true);
811        // Debug captures may keep an unfocused review window running.
812        #[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
813        let forced = capture.forced();
814        #[cfg(not(all(debug_assertions, not(target_arch = "wasm32"))))]
815        let forced = false;
816        let active = player_input.gameplay_active() || forced;
817        let dt = demo.dt();
818        let simulation_dt = if forced {
819            dt.clamp(0., 0.1)
820        } else {
821            player_input.simulation_dt(dt)
822        };
823        // Always reconcile policy before accepted feedback and presentation,
824        // including controls/focus suspension, paused and zero-tick frames.
825        pulse_visual.begin_frame(dt);
826        juice.apply_policy(preferences::feedback_policy());
827        if !active {
828            lab.pending = LabCommands::default();
829            lab.fun.pending_chaos = false;
830        }
831        let layout = presentation::LabLayout::compact(screen_width(), screen_height());
832        // Shake and the collapse beat move the camera, never the simulation.
833        let (focus, beat) = juice.beat().unwrap_or((Vec2::ZERO, 0.));
834        let view = layout.zoomed(focus, 1. + 0.08 * beat, juice.shake());
835
836        let pointer = player_input.cursor(dt, 600.);
837        let pointer_in_scene = active && layout.contains_scene(pointer) && hud.card.is_none();
838        let spawn_position = Lab::drop_position(view.to_world(pointer));
839        let mouse = Vec2::from(mouse_position());
840        let clicked_mouse = is_mouse_button_pressed(MouseButton::Left);
841        // Off-scene primary activates menus. Scene placement remains a fixed-
842        // tick action (or a paused editor action) below.
843        let primary = !pointer_in_scene && player_input.pressed("primary");
844        let card_closed = active && (clicked_mouse || primary) && hud.dismiss_card();
845        let mut input = LabInput {
846            reset: player_input.pressed("restart"),
847            toggle_pause: player_input.pressed("pause"),
848            single_step: player_input.pressed("step"),
849            ..LabInput::default()
850        };
851        let mut toys = ToyInput {
852            scene: player_input.pressed("domino"),
853            ..ToyInput::default()
854        };
855        if player_input.pressed("stats") {
856            hud.stats = !hud.stats;
857        }
858        if player_input.pressed("select_one") {
859            input.ball = Some(true);
860        }
861        if player_input.pressed("select_two") {
862            input.ball = Some(false);
863        }
864        let inspect = player_input.pressed("inspect");
865
866        clear_background(ui::BACKGROUND);
867        let mut clicked = [false; presentation::BUTTONS];
868        // Presses on a disabled tool get refusal feedback instead of nothing.
869        let mut refused = [false; presentation::BUTTONS];
870        let mut hovered = None;
871        for (i, click) in clicked.iter_mut().enumerate() {
872            let rect = layout.button(i);
873            let over = rect.contains(mouse)
874                || (player_input.cursor_is_virtual() && rect.contains(pointer));
875            if active && over {
876                hovered = Some(i);
877            }
878            let mouse_clicked = rect.contains(mouse) && clicked_mouse;
879            let pressed = active
880                && !card_closed
881                && (mouse_clicked
882                    || (primary && player_input.cursor_is_virtual() && rect.contains(pointer)));
883            *click = pressed && lab.button_enabled(i);
884            refused[i] = pressed && !lab.button_enabled(i);
885        }
886        if clicked[0] {
887            input.ball = Some(true);
888        }
889        if clicked[1] {
890            input.ball = Some(false);
891        }
892        if clicked[2] {
893            input.drop = Some((vec2(0., 11.5), false));
894        }
895        if clicked[3] {
896            input.pulse = Some(vec2(0., 1.));
897        }
898        input.toggle_pause |= clicked[4];
899        input.single_step |= clicked[5];
900        input.reset |= clicked[6];
901        toys.chaos |= clicked[7];
902        toys.scene |= clicked[8];
903        #[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
904        capture.inject(&mut lab, &mut input, &mut toys, &mut hud);
905        let reset = input.reset || toys.scene;
906        if reset || input.toggle_pause {
907            // Lifecycle transitions discard stale gameplay requests.
908            player_input.take_tick(["primary", "secondary", "drop", "pulse", "chaos"]);
909        }
910        let frame = lab.update_toys_with_actions(simulation_dt as f64, input, toys, || {
911            if !active || card_closed {
912                return (LabCommands::default(), false);
913            }
914            let [primary, secondary, drop, pulse, chaos] =
915                player_input.take_tick(["primary", "secondary", "drop", "pulse", "chaos"]);
916            let commands = LabCommands {
917                drop: (drop.pressed
918                    || (pointer_in_scene && (primary.pressed || secondary.pressed)))
919                    .then_some((
920                        if pointer_in_scene {
921                            spawn_position
922                        } else {
923                            vec2(0., 11.5)
924                        },
925                        pointer_in_scene && secondary.pressed,
926                    )),
927                pulse: pulse.pressed.then_some(if pointer_in_scene {
928                    spawn_position
929                } else {
930                    vec2(0., 1.)
931                }),
932            };
933            (commands, chaos.pressed)
934        });
935        if reset {
936            pulse_visual.ring = None;
937        }
938        // Feedback follows accepted lab events only.
939        let added = lab.sandbox.bodies.len() > juice.known();
940        juice.on_frame(&lab, reset);
941        juice.advance_sim(frame.steps as f32 * frame.dt);
942        juice.advance_render(dt);
943        let tools = std::array::from_fn(|i| look::ToolState {
944            hovered: hovered == Some(i),
945            pressed: hovered == Some(i) && is_mouse_button_down(MouseButton::Left),
946            selected: match i {
947                0 => lab.ball,
948                1 => !lab.ball,
949                3 => lab.sandbox.pulse_time > 0.,
950                4 => lab.session.is_paused(),
951                8 => lab.fun.scenario == Scenario::Dominoes,
952                _ => false,
953            },
954            enabled: active && lab.button_enabled(i),
955        });
956        let motion = ferravex_play::tween::Motion::from_reduced(
957            preferences::feedback_policy().reduced_motion(),
958        );
959        hud.advance(
960            &lab,
961            active,
962            dt,
963            motion,
964            &tools,
965            reset,
966            clicked_mouse || primary || clicked.iter().any(|c| *c),
967        );
968        for (i, clicked) in clicked.iter().enumerate() {
969            if *clicked {
970                hud.tool_kick(i);
971            }
972            if refused[i] {
973                hud.refuse(&lab, i);
974                sound.cue(Cue::Failure, 0.3);
975            }
976        }
977        if active && !lab.session.is_paused() && !motion.is_reduced() {
978            ambient += dt.clamp(0., 0.1);
979        }
980        grading.apply(if lab.session.is_paused() {
981            look::Grade::Paused
982        } else if lab.fun.scenario == Scenario::Dominoes {
983            look::Grade::Dominoes
984        } else {
985            look::Grade::Workshop
986        });
987        if lab.pulsed {
988            pulse_visual.accepted_pulse(lab.sandbox.pulse_center);
989            sound.cue(Cue::Impact(Surface::Metal), 0.5);
990        }
991        if let Some((strength, surface)) = lab.impact {
992            sound.cue(Cue::Impact(surface), (strength * 0.09).clamp(0.15, 0.7));
993        }
994        let events = &lab.fun.events;
995        if added && !reset {
996            sound.cue(Cue::Click, if events.chaos > 0 { 0.45 } else { 0.25 });
997        }
998        if events.collapse.is_some() {
999            sound.cue(Cue::Impact(Surface::Stone), 0.8);
1000        }
1001        if !events.goals.is_empty() || events.secret {
1002            sound.cue(Cue::Success, 0.7);
1003        }
1004        if events.returned > 0 {
1005            sound.cue(Cue::Pickup, 0.4);
1006        }
1007        if let Some(down) = events.dominoes_down
1008            && down == lab.fun.domino_count()
1009            && down > 0
1010            && events.goals.is_empty()
1011        {
1012            sound.cue(Cue::Success, 0.5);
1013        }
1014        if let Some(best) = bests.update(&lab.fun) {
1015            juice.toast(
1016                "New best!",
1017                Some(look::Glyph::Pict(ferravex_render::icons::Icon::Trophy)),
1018                Some((best.glyph, best.value)),
1019                juice::GOLD,
1020                2.6,
1021                juice::Priority::Alert,
1022            );
1023            sound.cue(Cue::Success, 0.6);
1024        }
1025        let alpha = if lab.session.is_paused() || !active {
1026            1.
1027        } else {
1028            frame.alpha
1029        };
1030        let inspection = pointer_in_scene.then(|| lab.sandbox.inspect(view.to_world(pointer)));
1031        if inspect && !reset {
1032            lab.select_body(inspection.as_ref().and_then(|result| result.as_ref().ok()));
1033        }
1034        ferravex_render::set_world_colors(true);
1035        scene::draw(&scene::World {
1036            lab: &lab,
1037            view,
1038            juice: &juice,
1039            ring: pulse_visual.ring,
1040            ring_intensity: pulse_visual.intensity,
1041            alpha,
1042            preview: (pointer_in_scene && lab.sandbox.bodies.len() < MAX_BODIES)
1043                .then_some((spawn_position, lab.ball)),
1044            time: ambient,
1045            motion,
1046        });
1047        ferravex_render::set_world_colors(false);
1048        let inspection = inspection.as_ref().and_then(|query| query.as_ref().ok());
1049        let hud_frame = hud::Frame {
1050            lab: &lab,
1051            layout: &layout,
1052            view: &view,
1053            juice: &juice,
1054            bests: &bests,
1055            input: &player_input,
1056            inspection,
1057            pointer: pointer_in_scene.then_some(pointer),
1058            active,
1059            tools,
1060        };
1061        hud.draw_world_overlay(&hud_frame, beat);
1062        hud.draw(&hud_frame);
1063        if player_input.gameplay_active() && player_input.cursor_is_virtual() {
1064            draw_circle_lines(pointer.x, pointer.y, 5., 1.3, WHITE);
1065        }
1066        player_input.draw_controls();
1067        #[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
1068        capture.end_frame();
1069        if demo.finish_frame() {
1070            break;
1071        }
1072        next_frame().await;
1073    }
1074}
1075
1076#[cfg(test)]
1077mod journey200_tests;
1078
1079#[cfg(test)]
1080mod tests {
1081    use super::*;
1082
1083    fn poses(sandbox: &Sandbox) -> Vec<(Vec2, Vec2, f32)> {
1084        sandbox
1085            .bodies
1086            .iter()
1087            .map(|body| {
1088                let rigid = &sandbox.physics.bodies[body.handle];
1089                (
1090                    rigid.translation(),
1091                    rigid.linvel(),
1092                    rigid.rotation().angle(),
1093                )
1094            })
1095            .collect()
1096    }
1097
1098    #[test]
1099    fn pause_freezes_poses_and_cooldowns_without_resume_catchup() {
1100        let mut lab = Lab::new();
1101        lab.update(
1102            1. / TICK_HZ,
1103            LabInput {
1104                pulse: Some(vec2(0., 1.)),
1105                ..LabInput::default()
1106            },
1107        );
1108        lab.update(
1109            0.,
1110            LabInput {
1111                toggle_pause: true,
1112                ..LabInput::default()
1113            },
1114        );
1115        let before = poses(&lab.sandbox);
1116        let pulse_time = lab.sandbox.pulse_time;
1117        let impact_cooldown = lab.impact_cooldown;
1118        let tick = lab.session.tick();
1119        for _ in 0..3 {
1120            assert_eq!(lab.update(60., LabInput::default()).steps, 0);
1121        }
1122        assert_eq!(poses(&lab.sandbox), before);
1123        assert_eq!(lab.sandbox.pulse_time, pulse_time);
1124        assert_eq!(lab.impact_cooldown, impact_cooldown);
1125        assert_eq!(lab.session.tick(), tick);
1126        assert_eq!(
1127            lab.update(
1128                60.,
1129                LabInput {
1130                    toggle_pause: true,
1131                    ..LabInput::default()
1132                }
1133            )
1134            .steps,
1135            0
1136        );
1137        assert_eq!(lab.update(1. / TICK_HZ, LabInput::default()).steps, 1);
1138        assert_eq!(lab.session.tick(), tick + 1);
1139    }
1140
1141    #[test]
1142    fn manual_step_advances_exactly_one_tick_and_stays_paused() {
1143        let mut lab = Lab::new();
1144        let mut reference = Lab::new();
1145        // Keep a partial tick to prove that stepping neither loses it nor
1146        // admits wall time supplied while paused.
1147        lab.update(0.5 / TICK_HZ, LabInput::default());
1148        reference.update(0.5 / TICK_HZ, LabInput::default());
1149        lab.update(
1150            0.,
1151            LabInput {
1152                toggle_pause: true,
1153                ..LabInput::default()
1154            },
1155        );
1156        for tick in 1..=10 {
1157            let frame = lab.update(
1158                20.,
1159                LabInput {
1160                    single_step: true,
1161                    ..LabInput::default()
1162                },
1163            );
1164            reference.update(1. / TICK_HZ, LabInput::default());
1165            assert_eq!(frame.steps, 1);
1166            assert_eq!(frame.dt, 1_f32 / 120.);
1167            assert_eq!(frame.alpha, 1., "manual steps present the current pose");
1168            assert!(lab.session.is_paused());
1169            assert_eq!(lab.session.tick(), tick);
1170            assert_eq!(poses(&lab.sandbox), poses(&reference.sandbox));
1171            assert_eq!(lab.update(100., LabInput::default()).steps, 0);
1172        }
1173        // A step edge while running never adds an extra simulation interval.
1174        reference.update(
1175            0.,
1176            LabInput {
1177                single_step: true,
1178                ..LabInput::default()
1179            },
1180        );
1181        assert_eq!(reference.session.tick(), 10);
1182        lab.session.set_paused(false);
1183        assert_eq!(lab.update(0.5 / TICK_HZ, LabInput::default()).steps, 1);
1184        reference.update(0.5 / TICK_HZ, LabInput::default());
1185        assert_eq!(poses(&lab.sandbox), poses(&reference.sandbox));
1186    }
1187
1188    #[test]
1189    fn reset_preserves_pause_and_shape_but_clears_world_time_and_stale_edges() {
1190        for paused in [false, true] {
1191            let mut lab = Lab::new();
1192            lab.update(
1193                2.5 / TICK_HZ,
1194                LabInput {
1195                    ball: Some(false),
1196                    drop: Some((vec2(0., 9.), false)),
1197                    pulse: Some(vec2(0., 1.)),
1198                    ..LabInput::default()
1199                },
1200            );
1201            lab.session.set_paused(paused);
1202            lab.impact_cooldown = 0.04;
1203            let frame = lab.update(
1204                10.,
1205                LabInput {
1206                    reset: true,
1207                    toggle_pause: true,
1208                    single_step: true,
1209                    ball: Some(true),
1210                    drop: Some((vec2(0., 12.), false)),
1211                    pulse: Some(vec2(0., 1.)),
1212                },
1213            );
1214            assert_eq!(frame.steps, 0);
1215            assert_eq!(lab.session.tick(), 0);
1216            assert_eq!(lab.session.is_paused(), paused);
1217            assert!(!lab.ball);
1218            assert_eq!(poses(&lab.sandbox), poses(&Sandbox::new()));
1219            assert_eq!(lab.sandbox.bodies.len(), 34);
1220            assert_eq!(lab.sandbox.physics.bodies.len(), 42);
1221            assert_eq!(lab.sandbox.links.len(), 4);
1222            assert_eq!(lab.sandbox.pulse_time, 0.);
1223            assert_eq!(lab.impact_cooldown, 0.);
1224            assert!(lab.impact.is_none());
1225            assert!(!lab.pulsed);
1226            assert_eq!(lab.notice, Notice::Rebuilt);
1227            lab.session.set_paused(false);
1228            assert_eq!(lab.update(0.5 / TICK_HZ, LabInput::default()).steps, 0);
1229        }
1230    }
1231
1232    #[test]
1233    fn paused_drops_use_selection_and_clamped_preview_without_moving() {
1234        let mut lab = Lab::new();
1235        lab.session.set_paused(true);
1236        let before = poses(&lab.sandbox);
1237        lab.update(
1238            1.,
1239            LabInput {
1240                ball: Some(false),
1241                drop: Some((vec2(90., -10.), false)),
1242                ..LabInput::default()
1243            },
1244        );
1245        let body = lab.sandbox.bodies.last().unwrap();
1246        assert!(matches!(body.shape, Shape::Box(_)));
1247        assert_eq!(body.previous_position, vec2(11.2, 0.6));
1248        assert_eq!(
1249            lab.sandbox.physics.bodies[body.handle].translation(),
1250            body.previous_position
1251        );
1252        assert_eq!(lab.sandbox.physics.bodies[body.handle].linvel(), Vec2::ZERO);
1253        assert_eq!(&poses(&lab.sandbox)[..before.len()], &before);
1254        assert_eq!(lab.session.tick(), 0);
1255
1256        lab.update(
1257            0.,
1258            LabInput {
1259                ball: Some(true),
1260                drop: Some((vec2(0., 100.), true)),
1261                ..LabInput::default()
1262            },
1263        );
1264        assert!(lab.ball, "secondary click does not change selection");
1265        assert!(matches!(
1266            lab.sandbox.bodies.last().unwrap().shape,
1267            Shape::Box(_)
1268        ));
1269        assert_eq!(lab.sandbox.bodies.last().unwrap().previous_position.y, 12.4);
1270        lab.update(
1271            0.,
1272            LabInput {
1273                drop: Some((vec2(0., 10.), false)),
1274                ..LabInput::default()
1275            },
1276        );
1277        assert!(matches!(
1278            lab.sandbox.bodies.last().unwrap().shape,
1279            Shape::Ball(_)
1280        ));
1281    }
1282
1283    #[test]
1284    fn drop_is_once_per_frame_and_reports_capacity_and_invalid_positions() {
1285        let mut lab = Lab::new();
1286        let initial_count = lab.sandbox.bodies.len();
1287        let frame = lab.update(
1288            1.,
1289            LabInput {
1290                drop: Some((vec2(0., 10.), false)),
1291                ..LabInput::default()
1292            },
1293        );
1294        assert_eq!(frame.steps, 8);
1295        assert_eq!(lab.sandbox.bodies.len(), initial_count + 1);
1296        lab.session.set_paused(true);
1297        lab.update(
1298            0.,
1299            LabInput {
1300                drop: Some((vec2(f32::NAN, 10.), false)),
1301                ..LabInput::default()
1302            },
1303        );
1304        assert_eq!(lab.sandbox.bodies.len(), initial_count + 1);
1305        assert_eq!(lab.notice, Notice::DropRejected);
1306        for _ in 0..MAX_BODIES {
1307            lab.update(
1308                0.,
1309                LabInput {
1310                    drop: Some((vec2(0., 10.), false)),
1311                    ..LabInput::default()
1312                },
1313            );
1314        }
1315        assert_eq!(lab.sandbox.bodies.len(), MAX_BODIES);
1316        assert_eq!(lab.sandbox.physics.bodies.len(), MAX_BODIES + 8);
1317        assert_eq!(lab.notice, Notice::DropFull);
1318    }
1319
1320    #[test]
1321    fn paused_pulse_is_rejected_and_manual_steps_consume_cooldown() {
1322        let mut lab = Lab::new();
1323        lab.session.set_paused(true);
1324        let before = poses(&lab.sandbox);
1325        lab.update(
1326            1.,
1327            LabInput {
1328                pulse: Some(vec2(0., 1.)),
1329                ..LabInput::default()
1330            },
1331        );
1332        assert_eq!(poses(&lab.sandbox), before);
1333        assert!(!lab.pulsed);
1334        assert_eq!(lab.sandbox.pulse_time, 0.);
1335        lab.session.set_paused(false);
1336        lab.update(
1337            0.,
1338            LabInput {
1339                pulse: Some(vec2(0., 1.)),
1340                ..LabInput::default()
1341            },
1342        );
1343        assert!(!lab.pulsed, "a zero-tick frame cannot apply an impulse");
1344        assert_eq!(lab.update(1. / TICK_HZ, LabInput::default()).steps, 1);
1345        assert!(lab.pulsed);
1346        lab.session.set_paused(true);
1347        lab.update(
1348            10.,
1349            LabInput {
1350                single_step: true,
1351                ..LabInput::default()
1352            },
1353        );
1354        assert!((lab.sandbox.pulse_time - (0.65 - 2. / 120.)).abs() < 1e-6);
1355    }
1356
1357    #[test]
1358    fn autoplay_settling_is_identical_across_render_rates() {
1359        let mut expected = Lab::new();
1360        for _ in 0..240 {
1361            expected.update(1. / TICK_HZ, LabInput::default());
1362        }
1363        for fps in [30, 60, 144] {
1364            let mut lab = Lab::new();
1365            for _ in 0..fps * 2 {
1366                lab.update(1. / fps as f64, LabInput::default());
1367            }
1368            assert_eq!(lab.session.tick(), 240);
1369            assert_eq!(poses(&lab.sandbox), poses(&expected.sandbox));
1370            assert_eq!(lab.impact_cooldown, expected.impact_cooldown);
1371        }
1372    }
1373
1374    #[test]
1375    fn pulse_wakes_and_lifts_props_and_cannot_be_spammed() {
1376        let mut sandbox = Sandbox::new();
1377        assert!(sandbox.pulse(vec2(0., 0.5)));
1378        assert!(
1379            sandbox
1380                .bodies
1381                .iter()
1382                .any(|body| sandbox.physics.bodies[body.handle].linvel().y > 0.1)
1383        );
1384        let velocities: Vec<_> = sandbox
1385            .bodies
1386            .iter()
1387            .map(|body| sandbox.physics.bodies[body.handle].linvel())
1388            .collect();
1389        assert!(!sandbox.pulse(vec2(0., 0.5)));
1390        for (body, velocity) in sandbox.bodies.iter().zip(velocities) {
1391            assert_eq!(sandbox.physics.bodies[body.handle].linvel(), velocity);
1392        }
1393        for _ in 0..80 {
1394            sandbox.step(1. / 120.);
1395        }
1396        assert!(sandbox.pulse(vec2(0., 0.5)));
1397    }
1398
1399    #[test]
1400    fn falling_bodies_produce_bounded_impact_hints() {
1401        let mut sandbox = Sandbox::new();
1402        let mut found = false;
1403        for _ in 0..360 {
1404            sandbox.step(1. / 120.);
1405            if let Some((strength, _)) = sandbox.impact {
1406                assert!(strength.is_finite() && strength > 1.2);
1407                found = true;
1408            }
1409        }
1410        assert!(found);
1411    }
1412    #[test]
1413    fn jointed_mechanisms_keep_their_constraints_under_load() {
1414        let mut sandbox = Sandbox::new();
1415        for _ in 0..1200 {
1416            sandbox.step(1. / 120.);
1417        }
1418        assert_eq!(sandbox.links.len(), 4);
1419        for &id in &sandbox.links {
1420            let joint = &sandbox.physics.joints[id];
1421            let [a, b] = sandbox.physics.joint_anchors(id).unwrap();
1422            match joint.description().kind {
1423                ferravex_physics::JointKind::Distance { length } => {
1424                    assert!((a.distance(b) - length).abs() < 0.005)
1425                }
1426                ferravex_physics::JointKind::Spring {
1427                    length, stiffness, ..
1428                } => {
1429                    let body = joint.bodies()[1];
1430                    let extension = sandbox.physics.bodies[body].mass() * 9.81 / stiffness;
1431                    assert!((a.distance(b) - length - extension).abs() < 0.025);
1432                }
1433                _ => assert!(a.distance(b) < 0.005),
1434            }
1435        }
1436    }
1437
1438    #[test]
1439    fn recovered_sandbox_settles_with_finite_rotating_bodies() {
1440        let mut sandbox = Sandbox::new();
1441        let mut rotation_seen = false;
1442        for _ in 0..720 {
1443            sandbox.step(1.0 / 120.0);
1444            for body in &sandbox.bodies {
1445                let rigid = &sandbox.physics.bodies[body.handle];
1446                assert!(rigid.translation().is_finite());
1447                assert!(rigid.linvel().is_finite());
1448                rotation_seen |= rigid.rotation().angle().abs() > 0.05;
1449            }
1450        }
1451        assert!(rotation_seen, "contacts should rotate the falling bodies");
1452        assert!(sandbox.bodies.iter().all(|body| {
1453            let p = sandbox.physics.bodies[body.handle].translation();
1454            p.y > 0.3 && p.x.abs() < 12.0
1455        }));
1456    }
1457
1458    #[test]
1459    fn spawning_is_bounded_and_rebuild_replaces_the_world() {
1460        let mut sandbox = Sandbox::new();
1461        for i in 0..MAX_BODIES + 10 {
1462            sandbox.spawn(vec2((i % 10) as f32 - 5.0, 12.0 + (i / 10) as f32), true);
1463        }
1464        assert_eq!(sandbox.bodies.len(), MAX_BODIES);
1465        assert_eq!(
1466            sandbox.physics.bodies.len(),
1467            MAX_BODIES + sandbox.platforms.len() + 3
1468        );
1469        sandbox = Sandbox::new();
1470        assert_eq!(sandbox.bodies.len(), 34);
1471        assert_eq!(sandbox.physics.bodies.len(), 42);
1472    }
1473
1474    #[test]
1475    fn running_commands_wait_for_a_tick_and_edges_are_taken_only_on_ticks() {
1476        let mut lab = Lab::new();
1477        let before = poses(&lab.sandbox);
1478        let mut commands = LabCommands {
1479            drop: Some((vec2(0., 10.), false)),
1480            pulse: Some(vec2(0., 1.)),
1481        };
1482        let mut reads = 0;
1483        let mut actions = || {
1484            reads += 1;
1485            std::mem::take(&mut commands)
1486        };
1487        assert_eq!(
1488            lab.update_with_actions(0.5 / TICK_HZ, LabInput::default(), &mut actions)
1489                .steps,
1490            0
1491        );
1492        assert_eq!(poses(&lab.sandbox), before);
1493        assert_eq!(lab.sandbox.pulse_time, 0.);
1494        assert_eq!(
1495            lab.update_with_actions(3.5 / TICK_HZ, LabInput::default(), &mut actions)
1496                .steps,
1497            4
1498        );
1499        assert_eq!(reads, 4);
1500        assert_eq!(lab.sandbox.bodies.len(), before.len() + 1);
1501        assert!(lab.pulsed);
1502        assert_eq!(
1503            lab.selected,
1504            Some(lab.sandbox.bodies.last().unwrap().handle)
1505        );
1506        assert!((lab.sandbox.pulse_time - (0.65 - 4. / 120.)).abs() < 1e-6);
1507    }
1508
1509    #[test]
1510    fn pending_ui_commands_coalesce_and_reset_discards_them() {
1511        let mut lab = Lab::new();
1512        for x in [0., 1., 2.] {
1513            lab.update(
1514                0.,
1515                LabInput {
1516                    drop: Some((vec2(x, 10.), false)),
1517                    pulse: Some(vec2(x, 1.)),
1518                    ..Default::default()
1519                },
1520            );
1521        }
1522        assert_eq!(lab.sandbox.bodies.len(), 34);
1523        assert_eq!(lab.pending.drop.unwrap().0, vec2(0., 10.));
1524        lab.update(1. / TICK_HZ, LabInput::default());
1525        assert_eq!(lab.sandbox.bodies.len(), 35);
1526        assert!(lab.pending.drop.is_none() && lab.pending.pulse.is_none());
1527        lab.update(
1528            0.,
1529            LabInput {
1530                drop: Some((vec2(0., 12.), false)),
1531                ..Default::default()
1532            },
1533        );
1534        lab.update_with_actions(
1535            30.,
1536            LabInput {
1537                reset: true,
1538                ..Default::default()
1539            },
1540            || {
1541                panic!("reset must not consume gameplay actions");
1542            },
1543        );
1544        assert!(lab.selected.is_none());
1545        lab.update(1. / TICK_HZ, LabInput::default());
1546        assert_eq!(lab.sandbox.bodies.len(), 34);
1547        assert_eq!(lab.sandbox.pulse_time, 0.);
1548    }
1549
1550    #[test]
1551    fn queries_inspect_compound_current_poses_without_waking_or_ticking() {
1552        let mut lab = Lab::new();
1553        lab.session.set_paused(true);
1554        let handle = lab.sandbox.bodies.last().unwrap().handle;
1555        let before = poses(&lab.sandbox);
1556        let sleep = lab.sandbox.physics.sleep_state(handle).unwrap();
1557        let query = lab.sandbox.inspect(vec2(8.95, 10.)).unwrap();
1558        assert_eq!(query.body(&lab.sandbox), Some(handle));
1559        assert!(query.report.total > 0);
1560        lab.select_body(Some(&query));
1561        assert_eq!(lab.selected, Some(handle));
1562        assert_eq!(lab.notice, Notice::Selected);
1563        let selection = lab.selection().unwrap();
1564        assert!(matches!(selection.shape, Shape::Dumbbell));
1565        assert_eq!(selection.number, lab.sandbox.bodies.len());
1566        assert_eq!(selection.position, vec2(8.2, 10.));
1567        assert_eq!(lab.sandbox.physics.sleep_state(handle), Some(sleep));
1568        assert_eq!(poses(&lab.sandbox), before);
1569        assert_eq!(lab.session.tick(), 0);
1570        lab.sandbox.physics.bodies[handle].set_translation(vec2(0., 10.), true);
1571        assert_eq!(
1572            lab.sandbox
1573                .inspect(vec2(0.75, 10.))
1574                .unwrap()
1575                .body(&lab.sandbox),
1576            Some(handle)
1577        );
1578        assert_ne!(
1579            lab.sandbox
1580                .inspect(vec2(8.95, 10.))
1581                .unwrap()
1582                .body(&lab.sandbox),
1583            Some(handle)
1584        );
1585        lab.sandbox.physics.remove_body(handle);
1586        assert!(
1587            lab.selected.is_some() && lab.selection().is_none(),
1588            "stale selection"
1589        );
1590        lab.reset();
1591        assert!(lab.selected.is_none());
1592        let miss = lab.sandbox.inspect(vec2(0., 12.)).unwrap();
1593        lab.select_body(Some(&miss));
1594        assert!(lab.selected.is_none());
1595        assert_eq!(lab.notice, Notice::Missed);
1596    }
1597
1598    #[test]
1599    fn inspection_reports_bounded_hits_and_invalid_points() {
1600        let mut sandbox = Sandbox::new();
1601        for _ in 0..12 {
1602            assert!(sandbox.spawn(vec2(0., 10.), true));
1603        }
1604        let query = sandbox.inspect(vec2(0., 10.)).unwrap();
1605        assert_eq!(query.report.written, 8);
1606        assert_eq!(query.report.total, 12);
1607        assert!(query.report.is_truncated());
1608        assert_eq!(
1609            query.body(&sandbox),
1610            Some(sandbox.bodies.last().unwrap().handle)
1611        );
1612        assert!(sandbox.inspect(vec2(f32::NAN, 10.)).is_err());
1613        assert!(sandbox.inspect(vec2(f32::INFINITY, 10.)).is_err());
1614        let miss = sandbox.inspect(vec2(0., 12.)).unwrap();
1615        assert_eq!(miss.report.total, 0);
1616        assert!(miss.hits.iter().all(Option::is_none));
1617    }
1618
1619    #[test]
1620    fn collision_feedback_requires_a_real_solid_contact_start() {
1621        let mut sandbox = Sandbox {
1622            physics: PhysicsWorld::new([0., -180.]),
1623            bodies: Vec::new(),
1624            platforms: Vec::new(),
1625            links: Vec::new(),
1626            impact: None,
1627            pulse_time: 0.,
1628            pulse_center: Vec2::ZERO,
1629        };
1630        sandbox.spawn(vec2(0., 10.), true);
1631        let handle = sandbox.bodies[0].handle;
1632        sandbox.physics.bodies[handle].set_linvel(vec2(0., -3.), true);
1633        sandbox.step(1. / 120.);
1634        assert!(sandbox.physics.contact_events().is_empty());
1635        assert!(
1636            sandbox.impact.is_none(),
1637            "large gravity velocity changes are silent"
1638        );
1639        let (_, floor) = sandbox.physics.insert(
1640            RigidBodyBuilder::fixed(),
1641            ColliderBuilder::cuboid(5., 0.5).sensor(true),
1642        );
1643        sandbox.physics.bodies[handle].set_translation(vec2(0., 0.7), true);
1644        sandbox.step(1. / 120.);
1645        assert!(!sandbox.physics.contact_events().is_empty());
1646        assert!(sandbox.impact.is_none(), "sensor starts are silent");
1647        sandbox.physics.colliders[floor].set_sensor(false);
1648        sandbox.physics.bodies[handle].set_translation(vec2(0., 3.), true);
1649        sandbox.step(1. / 120.);
1650        sandbox.physics.bodies[handle].set_translation(vec2(0., 0.95), true);
1651        sandbox.physics.bodies[handle].set_linvel(vec2(0., -10.), true);
1652        sandbox.step(1. / 120.);
1653        assert!(
1654            sandbox.impact.is_some(),
1655            "a new solid impact produces feedback"
1656        );
1657    }
1658
1659    #[test]
1660    fn presentation_policy_clears_existing_rings_without_changing_simulation() {
1661        use ferravex_play::feedback::FeedbackPolicy;
1662        let original = preferences::feedback_policy();
1663        for (motion, flash) in [(true, false), (false, true), (true, true)] {
1664            preferences::set_feedback_policy(FeedbackPolicy::default());
1665            let mut visual = PulseVisual::default();
1666            let mut lab = Lab::new();
1667            visual.begin_frame(0.);
1668            lab.update(
1669                1. / TICK_HZ,
1670                LabInput {
1671                    pulse: Some(vec2(0., 1.)),
1672                    ..Default::default()
1673                },
1674            );
1675            assert!(lab.pulsed);
1676            visual.accepted_pulse(lab.sandbox.pulse_center);
1677            assert!(visual.ring.is_some());
1678            lab.session.set_paused(true);
1679            let before = poses(&lab.sandbox);
1680            let cooldown = lab.sandbox.pulse_time;
1681            preferences::set_feedback_policy(FeedbackPolicy::new(motion, flash, 1.).unwrap());
1682            visual.begin_frame(0.); // menus/paused/zero-tick policy changes still apply
1683            assert!(visual.ring.is_none());
1684            visual.accepted_pulse(vec2(0., 1.));
1685            assert!(visual.ring.is_none());
1686            assert_eq!(poses(&lab.sandbox), before);
1687            assert_eq!(lab.sandbox.pulse_time, cooldown);
1688            assert_eq!(lab.session.tick(), 1);
1689            preferences::set_feedback_policy(FeedbackPolicy::default());
1690            visual.begin_frame(0.);
1691            assert!(
1692                visual.ring.is_none(),
1693                "re-enabling must not revive old effects"
1694            );
1695            visual.accepted_pulse(vec2(0., 1.));
1696            assert!(visual.ring.is_some());
1697            for _ in 0..7 {
1698                visual.begin_frame(0.1);
1699            }
1700            assert!(visual.ring.is_none());
1701            assert_eq!(
1702                lab.sandbox.pulse_time, cooldown,
1703                "cosmetic time does not recharge physics"
1704            );
1705        }
1706        preferences::set_feedback_policy(original);
1707    }
1708
1709    #[test]
1710    fn all_presentation_policies_preserve_running_impulses_and_ticks() {
1711        use ferravex_play::feedback::FeedbackPolicy;
1712        let original = preferences::feedback_policy();
1713        let mut expected = Lab::new();
1714        for frame in 0..20 {
1715            expected.update(
1716                1. / 60.,
1717                LabInput {
1718                    pulse: (frame == 0).then_some(vec2(0., 1.)),
1719                    ..Default::default()
1720                },
1721            );
1722        }
1723        for (motion, flash, intensity) in [
1724            (false, false, 1.),
1725            (true, false, 1.),
1726            (false, true, 1.),
1727            (true, true, 1.),
1728            (false, false, 0.),
1729        ] {
1730            preferences::set_feedback_policy(
1731                FeedbackPolicy::new(motion, flash, intensity).unwrap(),
1732            );
1733            let mut lab = Lab::new();
1734            let mut visual = PulseVisual::default();
1735            for frame in 0..20 {
1736                visual.begin_frame(1. / 60.);
1737                lab.update(
1738                    1. / 60.,
1739                    LabInput {
1740                        pulse: (frame == 0).then_some(vec2(0., 1.)),
1741                        ..Default::default()
1742                    },
1743                );
1744                if lab.pulsed {
1745                    visual.accepted_pulse(lab.sandbox.pulse_center);
1746                }
1747            }
1748            assert_eq!(lab.session.tick(), 40);
1749            assert_eq!(poses(&lab.sandbox), poses(&expected.sandbox));
1750            assert_eq!(lab.sandbox.pulse_time, expected.sandbox.pulse_time);
1751            assert_eq!(visual.ring.is_none(), motion || flash || intensity == 0.);
1752        }
1753        preferences::set_feedback_policy(original);
1754    }
1755
1756    #[test]
1757    fn lab_hints_follow_rebinding_and_unbound_actions() {
1758        let mut input = PlayerInput::transient("journey200-142-hints");
1759        register_lab_actions(&mut input);
1760        assert_eq!(action_hint(&input, "step"), "N");
1761        assert_eq!(action_hint(&input, "drop"), "Enter");
1762        assert_eq!(action_hint(&input, "inspect"), "I");
1763        input
1764            .rebind(
1765                "step",
1766                vec![Binding::digital(InputCode::Key(KeyCode::J as u16))],
1767            )
1768            .unwrap();
1769        assert_eq!(action_hint(&input, "step"), "J");
1770        input.rebind("inspect", vec![]).unwrap();
1771        assert_eq!(action_hint(&input, "inspect"), "Unbound");
1772    }
1773
1774    #[test]
1775    fn button_availability_matches_pause_cooldown_and_capacity() {
1776        let mut lab = Lab::new();
1777        assert!(!lab.button_enabled(5));
1778        assert!(lab.button_enabled(3));
1779        lab.update(
1780            1. / TICK_HZ,
1781            LabInput {
1782                pulse: Some(vec2(0., 1.)),
1783                ..Default::default()
1784            },
1785        );
1786        assert!(!lab.button_enabled(3));
1787        lab.session.set_paused(true);
1788        assert!(lab.button_enabled(5));
1789        assert!(!lab.button_enabled(3));
1790        while lab.sandbox.spawn(vec2(0., 10.), true) {}
1791        assert!(!lab.button_enabled(2));
1792        lab.reset();
1793        assert!(lab.button_enabled(2));
1794        assert!(lab.button_enabled(5));
1795    }
1796}