crystal_cavern/
lib.rs

1//! A small cave expedition: recover three crystals, wake two altars, find daylight.
2//!
3//! The host uses the shared session clock; the objective graph owns puzzle rules.
4//! Inactive frames never advance the expedition timer:
5//! ```
6//! use ferravex_core::session::{GameSession, SessionState};
7//! let mut session = GameSession::new(60.0, 8, false);
8//! assert_eq!(session.state(), SessionState::Ready);
9//! session.start();
10//! assert_eq!(session.advance(1.0 / 60.0).steps, 1);
11//! session.set_paused(true);
12//! assert_eq!(session.advance(30.0).steps, 0);
13//! session.restart();
14//! assert_eq!(session.tick(), 0);
15//! ```
16use ferravex_core::session::{GameSession, SessionState};
17use ferravex_physics::character::{
18    CharacterSettings, CharacterShape, Obstacle, ObstacleShape, QueryBounds, Terrain,
19    move_and_slide,
20};
21use ferravex_play::ai::{Candidate, Observer, Sight, TargetSelector, VisibilityQuery, WorkBudget};
22use ferravex_play::camera::{Input3, Mode3, NoObstructions, Rig3, Settings3, Target3};
23use ferravex_play::feedback::FeedbackPolicy;
24use ferravex_play::objective::{ObjectiveProgress, ObjectiveState};
25use ferravex_render::audio::{Cue, GameAudio, Surface};
26use ferravex_render::input::{
27    ActionKind, Binding, InputCode, PlayerInput, Preset,
28    touch::{Control, Output, Region},
29};
30type Aabb2 = ferravex_core::collision::Aabb2<Vec2>;
31use ferravex_render::{
32    demo::Demo,
33    material::{MaterialOptions, ShaderMaterial, ShaderSource},
34    mesh::Mesh3d,
35    prelude::*,
36    shaders::{LitMaterial, LitSettings},
37};
38use std::collections::VecDeque;
39
40const TILE: f32 = 2.7;
41const RADIUS: f32 = 0.29;
42const SPEED: f32 = 4.3;
43const MAP: [&str; 15] = [
44    "#############",
45    "#####...#####",
46    "#####.X.#####",
47    "######G######",
48    "###.......###",
49    "###A...B..###",
50    "###.......###",
51    "######.######",
52    "#....#.#....#",
53    "#.C.......C.#",
54    "#....#.#....#",
55    "###....C..###",
56    "#####...#####",
57    "#####.S.#####",
58    "#############",
59];
60const MINT: Color = Color::from_rgba(108, 239, 209, 255);
61/// Deep blue-teal cave air: fog and clear color, so distance cools the palette.
62const INK: Color = Color::from_rgba(11, 19, 26, 255);
63const WARM: Color = Color::from_rgba(202, 165, 107, 255);
64
65fn center(x: usize, z: usize) -> Vec2 {
66    vec2(x as f32 * TILE, z as f32 * TILE)
67}
68fn at(marker: u8) -> Vec2 {
69    for (z, row) in MAP.iter().enumerate() {
70        if let Some(x) = row.bytes().position(|c| c == marker) {
71            return center(x, z);
72        }
73    }
74    panic!("map is missing marker");
75}
76
77fn forward(yaw: f32) -> Vec2 {
78    vec2(yaw.sin(), -yaw.cos())
79}
80fn world(p: Vec2, height: f32) -> Vec3 {
81    vec3(p.x, height, p.y)
82}
83
84#[derive(Clone, Copy, Default)]
85struct Input {
86    movement: Vec2,
87    turn: f32,
88    interact: bool,
89}
90
91#[derive(Clone, Copy, Debug, PartialEq, Eq)]
92enum Interactable {
93    Crystal(usize),
94    Altar(u8),
95    Gate,
96    /// Optional bonus crystal tucked behind the spawn point. Outside the graph.
97    Shy,
98    /// The lost miner's note. Re-readable, never part of the objective graph.
99    Note,
100}
101impl Interactable {
102    fn objective(self) -> Option<usize> {
103        match self {
104            Self::Crystal(i) => Some(i),
105            Self::Altar(i) => Some(3 + usize::from(i)),
106            Self::Gate => Some(5),
107            Self::Shy | Self::Note => None,
108        }
109    }
110    fn id(self) -> u64 {
111        match self {
112            Self::Crystal(i) => i as u64 + 1,
113            Self::Altar(i) => 4 + u64::from(i),
114            Self::Gate => 6,
115            Self::Shy => 7,
116            Self::Note => 8,
117        }
118    }
119    fn from_id(id: u64) -> Option<Self> {
120        match id {
121            1..=3 => Some(Self::Crystal(id as usize - 1)),
122            4..=5 => Some(Self::Altar(id as u8 - 4)),
123            6 => Some(Self::Gate),
124            7 => Some(Self::Shy),
125            8 => Some(Self::Note),
126            _ => None,
127        }
128    }
129}
130
131/// What a locked target is waiting for, read from the objective graph.
132#[derive(Clone, Copy, Debug, PartialEq, Eq)]
133enum Blocker {
134    /// Altar I needs every crystal: (recovered, required).
135    Crystals(u16, u16),
136    /// Altar II needs altar I awake first.
137    AltarI,
138    /// The seal needs both altars; this many are awake.
139    Altars(u8),
140}
141
142/// The nearby-object prompt, drawn as a key cap and pictograms.
143#[derive(Clone, Copy, Debug, PartialEq, Eq)]
144enum Prompt {
145    /// Press interact to use this target (the note shows its next page).
146    Use(Interactable),
147    /// Locked until the blocker clears.
148    Locked(Interactable, Blocker),
149    /// The seal is open: walk through into the daylight.
150    Exit,
151}
152
153/// A transient message after a use, shown as pictograms or the note itself.
154#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
155enum Notice {
156    #[default]
157    None,
158    /// A refused use and what it is waiting for (the prompt shakes).
159    Locked(Interactable, Blocker),
160    /// A page of Wendell's note, read in passing.
161    Note(u32),
162}
163
164/// Steve, the shy bonus crystal, hides in the corner behind the spawn point.
165fn shy_position() -> Vec2 {
166    center(7, 13) + vec2(0.85, 0.85)
167}
168/// Wendell's lost note (and hat) sit in the Echoing Grotto's far corner.
169fn note_position() -> Vec2 {
170    center(1, 8) + vec2(-0.7, -0.7)
171}
172/// Index into [`quips::ZONES`] for a walkable position.
173fn zone_at(p: Vec2) -> usize {
174    let x = (p.x / TILE).round() as i32;
175    let z = (p.y / TILE).round() as i32;
176    match (x, z) {
177        (_, 12..) => 0,
178        (_, 11) => 1,
179        (..=4, 8..=10) => 3,
180        (8.., 8..=10) => 4,
181        (_, 7..=10) => 2,
182        _ => 5,
183    }
184}
185/// Seconds without objective progress before each whispered hint level.
186const HINT_AFTER: [f32; 3] = [30., 55., 85.];
187/// Crystals start humming within this many metres.
188const RESONANCE_RANGE: f32 = 11.;
189
190/// Presentation-facing facts from one simulation step. Reset every step and
191/// merged into [`Progress`]; nothing here feeds back into the rules.
192#[derive(Clone, Copy, Debug, Default, PartialEq)]
193struct Events {
194    bonk: bool,
195    rejected: Option<Interactable>,
196    shy: bool,
197    note: Option<u32>,
198    zone: Option<usize>,
199    hint: bool,
200}
201
202fn objectives() -> ferravex_play::objective::ObjectiveGraph<6> {
203    use ferravex_play::objective::*;
204    ObjectiveGraph::new(
205        1,
206        std::array::from_fn(|i| ObjectiveSpec {
207            id: i as u16 + 1,
208            all: match i {
209                3 => 7,
210                4 => 1 << 3,
211                5 => 1 << 4,
212                _ => 0,
213            },
214            any: 0,
215            exclusive_group: 0,
216            kind: ObjectiveKind::Event {
217                id: i as u16 + 1,
218                count: 1,
219            },
220        }),
221    )
222    .unwrap()
223}
224struct Game {
225    position: Vec2,
226    velocity: Vec2,
227    yaw: f32,
228    walls: Vec<Aabb2>,
229    crystals: Vec<Vec2>,
230    collected: [bool; 3],
231    objectives: ferravex_play::objective::ObjectiveGraph<6>,
232    focus: TargetSelector,
233    switches: u8,
234    gate: Aabb2,
235    won: bool,
236    elapsed: f32,
237    notice: Notice,
238    notice_time: f32,
239    shy_found: bool,
240    note_reads: u32,
241    bonks: u32,
242    bump_cooldown: f32,
243    rejected: u32,
244    zone: usize,
245    zones_seen: u8,
246    /// Expedition seconds since the last accepted objective.
247    stuck: f32,
248    hint_level: u8,
249    hints_used: u32,
250    walked: f32,
251    events: Events,
252}
253impl Game {
254    fn new() -> Self {
255        let mut walls = Vec::new();
256        let mut crystals = Vec::new();
257        for (z, row) in MAP.iter().enumerate() {
258            for (x, tile) in row.bytes().enumerate() {
259                if tile == b'#' {
260                    walls.push(Aabb2::from_min_size(
261                        center(x, z) - Vec2::splat(TILE * 0.5),
262                        Vec2::splat(TILE),
263                    ));
264                } else if tile == b'C' {
265                    crystals.push(center(x, z));
266                }
267            }
268        }
269        Self {
270            position: at(b'S'),
271            velocity: Vec2::ZERO,
272            yaw: 0.0,
273            walls,
274            crystals,
275            collected: [false; 3],
276            objectives: objectives(),
277            // A challenger must be more than 20 cm closer. Range/visibility
278            // remain mandatory, and facing never restricts nearby exploration.
279            focus: TargetSelector::new(0.2).expect("finite focus margin"),
280            switches: 0,
281            gate: Aabb2::from_min_size(at(b'G') - vec2(TILE * 0.5, 0.175), vec2(TILE, 0.35)),
282            won: false,
283            elapsed: 0.0,
284            notice: Notice::None,
285            notice_time: 0.,
286            shy_found: false,
287            note_reads: 0,
288            bonks: 0,
289            bump_cooldown: 0.,
290            rejected: 0,
291            zone: 0,
292            zones_seen: 1,
293            stuck: 0.,
294            hint_level: 0,
295            hints_used: 0,
296            walked: 0.,
297            events: Events::default(),
298        }
299    }
300    /// Index of the first incomplete objective, or 6 once complete.
301    fn stage(&self) -> usize {
302        self.objectives
303            .iter()
304            .find(|view| view.state != ObjectiveState::Complete)
305            .map_or(6, |view| view.index)
306    }
307    fn nearest_crystal(&self) -> Option<Vec2> {
308        self.crystals
309            .iter()
310            .zip(self.collected)
311            .filter(|(_, collected)| !collected)
312            .map(|(p, _)| *p)
313            .min_by(|a, b| {
314                a.distance_squared(self.position)
315                    .total_cmp(&b.distance_squared(self.position))
316            })
317    }
318    /// The crystal a hint should point at: a visible one first, then the
319    /// nearest through rock. Read-only, like every other inspection here.
320    fn hint_crystal(&self) -> Option<Vec2> {
321        self.crystals
322            .iter()
323            .zip(self.collected)
324            .filter(|(_, collected)| !collected)
325            .map(|(p, _)| (!self.visible(*p), p.distance_squared(self.position), *p))
326            .min_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)))
327            .map(|(_, _, p)| p)
328    }
329    /// Where the current objective is, for the hint marker.
330    fn hint_target(&self) -> Option<Vec2> {
331        match self.stage() {
332            0..=2 => self.hint_crystal(),
333            3 => Some(at(b'A')),
334            4 => Some(at(b'B')),
335            5 => Some(at(b'X')),
336            _ => None,
337        }
338    }
339    fn hint_text(&self) -> &'static str {
340        let zone = self.hint_crystal().map_or(0, zone_at);
341        quips::hint(self.stage(), self.hint_level, zone)
342    }
343    /// 0 far away (or done) to 1 standing on the nearest missing crystal.
344    /// Steve does not hum. Steve is shy.
345    fn resonance(&self) -> f32 {
346        self.nearest_crystal().map_or(0., |p| {
347            (1. - p.distance(self.position) / RESONANCE_RANGE).clamp(0., 1.)
348        })
349    }
350    fn count(&self) -> usize {
351        self.collected.iter().filter(|&&c| c).count()
352    }
353    fn open(&self) -> bool {
354        matches!(
355            self.objectives.state(5),
356            Some(ObjectiveState::Ready | ObjectiveState::Complete)
357        )
358    }
359    fn crystal_progress(&self) -> (u16, u16) {
360        self.objectives
361            .iter()
362            .take(3)
363            .fold((0, 0), |(done, total), view| {
364                let ObjectiveProgress::Event { count, required } = view.progress else {
365                    unreachable!("crystals are authored event objectives");
366                };
367                (done + count, total + required)
368            })
369    }
370    fn completed_mask(&self) -> u64 {
371        self.objectives
372            .iter()
373            .filter(|view| view.state == ObjectiveState::Complete)
374            .fold(0, |mask, view| mask | 1 << view.index)
375    }
376    fn obstacles(&self) -> impl Iterator<Item = &Aabb2> {
377        self.walls
378            .iter()
379            .chain((!self.open()).then_some(&self.gate))
380    }
381    fn visible(&self, p: Vec2) -> bool {
382        !self
383            .obstacles()
384            .any(|wall| wall.cast_segment(self.position, p).is_some())
385    }
386    fn near(&self, p: Vec2) -> bool {
387        self.position.distance_squared(p) < 1.7 * 1.7 && self.visible(p)
388    }
389    fn notify(&mut self, notice: Notice, seconds: f32) {
390        self.notice = notice;
391        self.notice_time = seconds;
392    }
393    fn objective_event(&mut self, index: usize) {
394        self.objectives
395            .event(index as u16 + 1, 1, self.objectives.last_event_serial() + 1)
396            .unwrap();
397        self.sync_objectives();
398        // Progress resets the whisper schedule for the next objective.
399        self.stuck = 0.;
400        self.hint_level = 0;
401    }
402    fn sync_objectives(&mut self) {
403        for (i, collected) in self.collected.iter_mut().enumerate() {
404            *collected = self.objectives.complete(i);
405        }
406        self.switches = if self.objectives.complete(4) {
407            2
408        } else if self.objectives.complete(3) {
409            1
410        } else {
411            0
412        };
413        self.won = self.objectives.complete(5);
414    }
415    fn target_position(&self, target: Interactable) -> Vec2 {
416        match target {
417            Interactable::Crystal(i) => self.crystals[i],
418            Interactable::Altar(i) => at(if i == 0 { b'A' } else { b'B' }),
419            // Query the near face, not the center of the solid closed gate.
420            Interactable::Gate => at(b'G') + vec2(0., 0.22),
421            Interactable::Shy => shy_position(),
422            Interactable::Note => note_position(),
423        }
424    }
425    fn target_ready(&self, target: Interactable) -> bool {
426        match target.objective() {
427            Some(index) => self
428                .objectives
429                .inspect(index)
430                .is_some_and(|view| view.state == ObjectiveState::Ready),
431            None => target != Interactable::Shy || !self.shy_found,
432        }
433    }
434    // The prompt, world highlight and accepted interaction share one target.
435    fn target(&self) -> Option<Interactable> {
436        self.select_focus().1
437    }
438    fn select_focus(&self) -> (TargetSelector, Option<Interactable>) {
439        let mut selector = self.focus;
440        if self.won {
441            selector.reset();
442            return (selector, None);
443        }
444        let candidates = self
445            .crystals
446            .iter()
447            .enumerate()
448            .filter(|(i, _)| !self.collected[*i])
449            .map(|(i, _)| Interactable::Crystal(i))
450            .chain((self.switches..2).map(Interactable::Altar))
451            .chain(std::iter::once(Interactable::Gate))
452            .chain((!self.shy_found).then_some(Interactable::Shy))
453            .chain(std::iter::once(Interactable::Note));
454        let candidates = candidates
455            .map(|target| Candidate {
456                id: target.id(),
457                position: world(self.target_position(target), 0.),
458                groups: 1,
459            })
460            .filter(|candidate| {
461                // Preserve the original strict interaction distance at its boundary.
462                candidate
463                    .position
464                    .distance_squared(world(self.position, 0.))
465                    < 1.7 * 1.7
466            });
467        let report = selector
468            .select_visible(
469                candidates,
470                Observer {
471                    position: world(self.position, 0.),
472                    forward: Vec3::Z,
473                },
474                Sight::new(1.7, std::f32::consts::TAU, 1).expect("cave interaction range"),
475                &mut WorkBudget::new(8, 8, 0),
476                &mut CaveVisibility(self),
477                |candidate| -candidate.position.distance(world(self.position, 0.)),
478            )
479            .expect("finite authored cave candidates");
480        debug_assert!(
481            !report.incomplete,
482            "all eight cave objects fit the focus budget"
483        );
484        (
485            selector,
486            report
487                .target
488                .and_then(|target| Interactable::from_id(target.id)),
489        )
490    }
491    fn blocker(&self, target: Interactable) -> Option<Blocker> {
492        let view = target
493            .objective()
494            .and_then(|i| self.objectives.inspect(i))?;
495        let missing = view.blockers.missing_all;
496        let (count, required) = self.crystal_progress();
497        Some(if missing & 7 != 0 {
498            Blocker::Crystals(count, required)
499        } else if missing & (1 << 3) != 0 {
500            Blocker::AltarI
501        } else {
502            Blocker::Altars(self.switches)
503        })
504    }
505    fn interact(&mut self) {
506        let (focus, target) = self.select_focus();
507        self.focus = focus;
508        let Some(target) = target else {
509            return;
510        };
511        if !self.target_ready(target) {
512            self.rejected += 1;
513            self.events.rejected = Some(target);
514            if let Some(blocker) = self.blocker(target) {
515                self.notify(Notice::Locked(target, blocker), 3.5);
516            }
517            return;
518        }
519        // Accepted uses speak through pops, sockets and the echo; a refusal
520        // still showing from earlier is replaced, not left behind.
521        self.notify(Notice::None, 0.);
522        match target {
523            Interactable::Crystal(i) => self.objective_event(i),
524            Interactable::Altar(0) => self.objective_event(3),
525            Interactable::Altar(_) => self.objective_event(4),
526            Interactable::Gate => {}
527            Interactable::Shy => {
528                self.shy_found = true;
529                self.events.shy = true;
530            }
531            Interactable::Note => {
532                self.events.note = Some(self.note_reads);
533                // Handwriting takes longer to read than a status line.
534                self.notify(Notice::Note(self.note_reads), 6.);
535                self.note_reads += 1;
536            }
537        }
538    }
539    fn prompt(&self) -> Option<Prompt> {
540        self.target().map(|target| {
541            if !self.target_ready(target)
542                && let Some(blocker) = self.blocker(target)
543            {
544                return Prompt::Locked(target, blocker);
545            }
546            match target {
547                Interactable::Gate => Prompt::Exit,
548                target => Prompt::Use(target),
549            }
550        })
551    }
552    fn step(&mut self, input: Input, dt: f32) {
553        self.events = Events::default();
554        if self.won {
555            return;
556        }
557        self.notice_time = (self.notice_time - dt).max(0.0);
558        self.elapsed += dt;
559        self.stuck += dt;
560        let level = HINT_AFTER
561            .iter()
562            .filter(|&&after| self.stuck >= after)
563            .count() as u8;
564        if level > self.hint_level {
565            self.hints_used += u32::from(level - self.hint_level);
566            self.hint_level = level;
567            self.events.hint = true;
568        }
569        self.yaw += input.turn * dt;
570        let front = forward(self.yaw);
571        let right = vec2(-front.y, front.x);
572        let movement = input.movement.clamp_length_max(1.0);
573        let desired = (front * movement.y + right * movement.x) * SPEED;
574        let weight = ferravex_play::motion::response(
575            if desired.length_squared() < 0.01 {
576                24.
577            } else {
578                18.
579            },
580            dt,
581        );
582        self.velocity = self.velocity.lerp(desired, weight);
583        let intended = self.velocity.length();
584        let delta = self.velocity * dt;
585        let motion = move_and_slide(
586            &CaveTerrain(self),
587            CharacterShape::Capsule {
588                radius: RADIUS,
589                height: 1.75,
590            },
591            CharacterSettings {
592                step_height: 0.,
593                ground_snap: 0.,
594                ..Default::default()
595            },
596            world(self.position, 0.),
597            world(delta, 0.),
598            true,
599        )
600        .expect("authored cave character terrain");
601        let next = vec2(motion.position.x, motion.position.z);
602        self.bump_cooldown = (self.bump_cooldown - dt).max(0.);
603        if dt > 0. {
604            // Wall sliding must not retain hidden velocity into a blocked wall.
605            self.velocity = (next - self.position) / dt;
606            // A brisk walk that stops dead is a bonk; glancing slides are not.
607            if intended > SPEED * 0.6
608                && self.velocity.length() < intended * 0.35
609                && movement.length_squared() > 0.25
610                && self.bump_cooldown == 0.
611            {
612                self.bonks += 1;
613                self.bump_cooldown = 0.9;
614                self.events.bonk = true;
615            }
616        }
617        self.walked += next.distance(self.position);
618        self.position = next;
619        let zone = zone_at(self.position);
620        if zone != self.zone {
621            self.zone = zone;
622            if self.zones_seen & (1 << zone) == 0 {
623                self.zones_seen |= 1 << zone;
624                self.events.zone = Some(zone);
625            }
626        }
627        self.focus = self.select_focus().0;
628        if input.interact {
629            self.interact();
630        }
631        if self.open() && self.position.distance(at(b'X')) < 1.2 {
632            self.objective_event(5);
633            self.notify(Notice::None, 0.);
634        }
635    }
636}
637
638#[derive(Default)]
639struct Progress {
640    completed: u64,
641    pickups: usize,
642    altars: u8,
643    won: bool,
644    /// Presentation facts merged from every executed step this frame.
645    bonks: u32,
646    rejected: Option<Interactable>,
647    shy: bool,
648    note: Option<u32>,
649    zone: Option<usize>,
650    hint: bool,
651}
652impl Progress {
653    fn absorb(&mut self, events: Events) {
654        self.bonks += u32::from(events.bonk);
655        self.rejected = events.rejected.or(self.rejected);
656        self.shy |= events.shy;
657        self.note = events.note.or(self.note);
658        self.zone = events.zone.or(self.zone);
659        self.hint |= events.hint;
660    }
661}
662
663// Host lifecycle stays testable without a window, audio device or renderer.
664struct Expedition {
665    game: Game,
666    session: GameSession,
667    pilot: Pilot,
668    autoplay: bool,
669    discard_frame: bool,
670    /// Expeditions restarted this session; varies a few quips between runs.
671    runs: u32,
672}
673impl Expedition {
674    fn new(autoplay: bool) -> Self {
675        Self {
676            game: Game::new(),
677            session: GameSession::new(60., 8, autoplay),
678            pilot: Pilot::default(),
679            autoplay,
680            discard_frame: false,
681            runs: 0,
682        }
683    }
684    fn start(&mut self) {
685        if self.session.start() {
686            self.discard_frame = true;
687        }
688    }
689    fn restart(&mut self) {
690        // A fresh Game: every crystal, altar, notice and whisper resets.
691        self.game = Game::new();
692        self.session.restart();
693        self.pilot = Pilot::default();
694        self.discard_frame = true;
695        self.runs = self.runs.wrapping_add(1);
696    }
697    fn set_paused(&mut self, paused: bool) {
698        if self.session.set_paused(paused) {
699            self.game.velocity = Vec2::ZERO;
700            // A browser may deliver a long frame on refocus. Discard that frame
701            // as well as all paused frames, including its stale input edges.
702            self.discard_frame = true;
703        }
704    }
705    fn advance(&mut self, elapsed: f64, sample_input: impl FnOnce() -> Input) -> Progress {
706        let mut progress = Progress::default();
707        if !self.session.is_playing() {
708            return progress;
709        }
710        if std::mem::take(&mut self.discard_frame) {
711            return progress;
712        }
713        let frame = self.session.advance(elapsed);
714        if frame.steps == 0 {
715            return progress;
716        }
717        // Leave pending edges in PlayerInput until a real tick. Its existing
718        // focus/context handling then also clears taps across host suspension.
719        let mut input = sample_input();
720        let previous_completed = self.game.completed_mask();
721        for _ in 0..frame.steps {
722            let command = if self.autoplay {
723                self.pilot.input(&self.game)
724            } else {
725                Input {
726                    // One render edge is spent on one tick, even if another
727                    // interactable becomes reachable during catch-up.
728                    interact: std::mem::take(&mut input.interact),
729                    ..input
730                }
731            };
732            let collected = self.game.count();
733            let switches = self.game.switches;
734            self.game.step(command, frame.dt);
735            progress.absorb(self.game.events);
736            progress.pickups += self.game.count() - collected;
737            progress.altars += self.game.switches - switches;
738            if self.game.won {
739                progress.won = self.session.finish(true);
740                break;
741            }
742        }
743        progress.completed = self.game.completed_mask() & !previous_completed;
744        progress
745    }
746}
747
748struct CaveVisibility<'a>(&'a Game);
749impl VisibilityQuery for CaveVisibility<'_> {
750    fn clear(&mut self, from: Vec3, to: Vec3) -> bool {
751        !self.0.obstacles().any(|wall| {
752            wall.cast_segment(vec2(from.x, from.z), vec2(to.x, to.z))
753                .is_some()
754        })
755    }
756}
757
758struct CaveTerrain<'a>(&'a Game);
759impl CaveTerrain<'_> {
760    fn box_at(&self, id: usize) -> Option<Obstacle> {
761        let wall = if id == self.0.walls.len() {
762            if self.0.open() {
763                return None;
764            }
765            self.0.gate
766        } else {
767            *self.0.walls.get(id)?
768        };
769        let center = (wall.min + wall.max) * 0.5;
770        let half = (wall.max - wall.min) * 0.5;
771        Some(Obstacle::cuboid(
772            id as u64 + 1,
773            world(center, 1.5),
774            vec3(half.x, 1.5, half.y),
775        ))
776    }
777}
778impl Terrain for CaveTerrain<'_> {
779    fn visit(&self, bounds: QueryBounds, visitor: &mut dyn FnMut(Obstacle)) {
780        visitor(Obstacle {
781            shape: ObstacleShape::Plane { normal: Vec3::Y },
782            ..Obstacle::cuboid(0, Vec3::ZERO, Vec3::ONE)
783        });
784        for i in 0..=self.0.walls.len() {
785            if let Some(o) = self.box_at(i)
786                && bounds.intersects(o.bounds())
787            {
788                visitor(o);
789            }
790        }
791    }
792    fn obstacle(&self, id: u64) -> Option<Obstacle> {
793        if id == 0 {
794            Some(Obstacle {
795                shape: ObstacleShape::Plane { normal: Vec3::Y },
796                ..Obstacle::cuboid(0, Vec3::ZERO, Vec3::ONE)
797            })
798        } else {
799            self.box_at((id - 1) as usize)
800        }
801    }
802}
803
804/// The smoke driver plans a route, then emits the same movement/turn/E inputs as a player.
805#[derive(Default)]
806struct Pilot {
807    goal: Option<Vec2>,
808    path: VecDeque<Vec2>,
809}
810impl Pilot {
811    fn input(&mut self, game: &Game) -> Input {
812        if game.won {
813            return Input::default();
814        }
815        let goal = game
816            .crystals
817            .iter()
818            .enumerate()
819            .find(|(i, _)| !game.collected[*i])
820            .map(|(_, &p)| p)
821            .unwrap_or_else(|| {
822                at(if game.switches == 0 {
823                    b'A'
824                } else if game.switches == 1 {
825                    b'B'
826                } else {
827                    b'X'
828                })
829            });
830        if self.goal != Some(goal) {
831            self.goal = Some(goal);
832            self.path = route(game, goal);
833        }
834        while self
835            .path
836            .front()
837            .is_some_and(|p| game.position.distance(*p) < 0.18)
838        {
839            self.path.pop_front();
840        }
841        let target = self.path.front().copied().unwrap_or(goal);
842        let delta = target - game.position;
843        let angle = delta.x.atan2(-delta.y);
844        let turn = (angle - game.yaw + std::f32::consts::PI).rem_euclid(std::f32::consts::TAU)
845            - std::f32::consts::PI;
846        Input {
847            movement: vec2(
848                0.0,
849                if turn.abs() < 0.15 && delta.length() > 0.06 {
850                    1.0
851                } else {
852                    0.0
853                },
854            ),
855            turn: (turn * 10.0).clamp(-3.5, 3.5),
856            interact: game.near(goal),
857        }
858    }
859}
860fn route(game: &Game, goal: Vec2) -> VecDeque<Vec2> {
861    use ferravex_play::{
862        ai::WorkBudget,
863        navigation::{NavMesh, NavTriangle},
864    };
865    let mut faces = Vec::new();
866    // Door state controls the actual traversable surface at planning time.
867    for (z, row) in MAP.iter().enumerate() {
868        for (x, tile) in row.bytes().enumerate() {
869            if tile == b'#' || (tile == b'G' && !game.open()) {
870                continue;
871            }
872            let a = world(vec2((x as f32 - 0.5) * TILE, (z as f32 - 0.5) * TILE), 0.);
873            let b = world(vec2((x as f32 + 0.5) * TILE, (z as f32 - 0.5) * TILE), 0.);
874            let c = world(vec2((x as f32 - 0.5) * TILE, (z as f32 + 0.5) * TILE), 0.);
875            let d = world(vec2((x as f32 + 0.5) * TILE, (z as f32 + 0.5) * TILE), 0.);
876            faces.push(NavTriangle([a, b, c]));
877            faces.push(NavTriangle([b, d, c]));
878        }
879    }
880    let mesh = NavMesh::welded(faces).unwrap();
881    let Ok(mut search) = mesh.search(world(game.position, 0.), world(goal, 0.)) else {
882        return VecDeque::new();
883    };
884    // This offline pilot plans only on goal changes, with a hard work allowance.
885    if search.step(&mesh, &mut WorkBudget::new(0, 0, 10000)) != Ok(true) {
886        return VecDeque::new();
887    }
888    search
889        .route(&mesh)
890        .unwrap()
891        .iter()
892        .map(|p| vec2(p.position.x, p.position.z))
893        .collect()
894}
895
896/// Small triangular rock faces, bounded to 14 cm beyond the collision slab.
897/// Flat normals and vertex colors provide material detail without texture assets.
898fn faceted_wall(color: Color, seed: usize) -> Mesh3d {
899    let mut vertices = Vec::new();
900    for (side, (normal, tangent)) in [
901        (Vec3::X, Vec3::Z),
902        (-Vec3::X, -Vec3::Z),
903        (Vec3::Z, -Vec3::X),
904        (-Vec3::Z, Vec3::X),
905    ]
906    .iter()
907    .enumerate()
908    {
909        for band in 0..3 {
910            let bottom = -2.1 + band as f32 * 1.4;
911            let top = bottom + 1.4;
912            let origin = *normal * TILE * 0.5;
913            let corners = [
914                origin - *tangent * TILE * 0.5 + Vec3::Y * bottom,
915                origin + *tangent * TILE * 0.5 + Vec3::Y * bottom,
916                origin + *tangent * TILE * 0.5 + Vec3::Y * top,
917                origin - *tangent * TILE * 0.5 + Vec3::Y * top,
918            ];
919            let middle = origin
920                + *normal * 0.14
921                + *tangent * (((seed + band + side) % 3) as f32 - 1.0) * 0.35
922                + Vec3::Y * (bottom + 0.63);
923            for face in 0..4 {
924                let points = [corners[face], corners[(face + 1) % 4], middle];
925                let mut face_normal = (points[1] - points[0])
926                    .cross(points[2] - points[0])
927                    .normalize();
928                if face_normal.dot(*normal) < 0.0 {
929                    face_normal = -face_normal;
930                }
931                let shade = 0.83 + ((seed + side * 3 + face + band * 2) % 5) as f32 * 0.045;
932                for point in points {
933                    let mut vertex = Vertex::new2(
934                        point,
935                        Vec2::ZERO,
936                        Color::new(color.r * shade, color.g * shade, color.b * shade, 1.0),
937                    );
938                    vertex.normal = face_normal.extend(0.0);
939                    vertices.push(vertex);
940                }
941            }
942        }
943    }
944    Mesh3d::from_mesh(Mesh {
945        indices: (0..vertices.len() as u16).collect(),
946        vertices,
947        texture: None,
948    })
949}
950
951struct Piece {
952    mesh: Mesh3d,
953    position: Vec3,
954    rotation: Quat,
955    wall_sides: Option<[bool; 4]>,
956}
957
958// Cosmetic phases are separate from expedition time. Suppressed time is never
959// accumulated, so resuming a preference cannot jump through hidden animation.
960// There are no transient flashes, particles, camera impulses or FeedbackController
961// in this exploration game; accepted audio remains independent of these phases.
962#[derive(Default)]
963struct Presentation {
964    motion_time: f32,
965    glow_time: f32,
966    pulse: bool,
967}
968impl Presentation {
969    fn advance(&mut self, elapsed: f32, policy: FeedbackPolicy) {
970        let dt = if elapsed.is_finite() {
971            elapsed.clamp(0., 0.25)
972        } else {
973            0.
974        };
975        if !policy.reduced_motion() {
976            self.motion_time += dt * policy.intensity();
977        }
978        self.pulse = !policy.reduced_flash() && policy.intensity() > 0.;
979        if self.pulse {
980            self.glow_time += dt * policy.intensity();
981        }
982    }
983}
984
985// Formatting is bounded and reads live bindings without consuming input. A long
986// binding list points to Controls instead of truncating into a misleading key.
987fn action_hint(input: &PlayerInput, name: &str) -> String {
988    // Leave room for the action in a 21-column, 320px overlay. Larger lists
989    // remain available in Controls rather than displacing essential guidance.
990    let mut bytes = [0; 12];
991    input
992        .format_hint(name, &mut bytes)
993        .unwrap_or("See Controls")
994        .into()
995}
996
997struct Scene {
998    pulse: ShaderMaterial,
999    #[cfg(not(target_arch = "wasm32"))]
1000    watcher: std::cell::RefCell<Option<ferravex_render::material::MaterialFileWatcher>>,
1001    stone: Vec<Piece>,
1002    crystal: Mesh3d,
1003    tip: Mesh3d,
1004    pedestal: Mesh3d,
1005    rune: Mesh3d,
1006    rune_dark: Mesh3d,
1007    gate: Mesh3d,
1008    daylight: Mesh3d,
1009    shy: Mesh3d,
1010    shy_tip: Mesh3d,
1011    paper: Mesh3d,
1012    hat: Mesh3d,
1013    brim: Mesh3d,
1014    lantern: Mesh3d,
1015    lantern_cap: Mesh3d,
1016    shard: [Mesh3d; 2],
1017    /// Faintly glowing mineral seams at wall bases: (position, rotation, violet).
1018    shards: Vec<(Vec3, Quat, usize)>,
1019}
1020
1021/// Lantern props: Base Camp, Wendell's abandoned camp and the Hall of Altars.
1022fn lantern_positions() -> [Vec2; 3] {
1023    [
1024        center(5, 12) + vec2(-0.95, -0.4),
1025        center(1, 8) + vec2(0.35, -0.95),
1026        center(9, 4) + vec2(0.95, -0.95),
1027    ]
1028}
1029impl Scene {
1030    fn new() -> Self {
1031        let mut stone = Vec::new();
1032        for (z, row) in MAP.iter().enumerate() {
1033            for (x, tile) in row.bytes().enumerate() {
1034                let p = center(x, z);
1035                let hash = (x * 17 + z * 31) % 7;
1036                if tile == b'#' {
1037                    // Same order as faceted_wall: +X, -X, +Z, -Z.
1038                    let sides = [
1039                        (x as i32 + 1, z as i32),
1040                        (x as i32 - 1, z as i32),
1041                        (x as i32, z as i32 + 1),
1042                        (x as i32, z as i32 - 1),
1043                    ]
1044                    .map(|(a, b)| {
1045                        (0..13).contains(&a)
1046                            && (0..15).contains(&b)
1047                            && MAP[b as usize].as_bytes()[a as usize] != b'#'
1048                    });
1049                    if !sides.iter().any(|&open| open) {
1050                        continue;
1051                    }
1052                    // Warm sandstone with a hint of rose; the grade cools its shadows.
1053                    let c = Color::from_rgba(
1054                        104 + hash as u8 * 5,
1055                        76 + hash as u8 * 3,
1056                        66 + hash as u8 * 3,
1057                        255,
1058                    );
1059                    stone.push(Piece {
1060                        wall_sides: Some(sides),
1061                        mesh: faceted_wall(c, hash),
1062                        position: world(p, 2.1),
1063                        rotation: Quat::IDENTITY,
1064                    });
1065                } else {
1066                    // Cool slate floor contrasts the warm walls instead of matching them.
1067                    let shade = 44 + hash as u8 * 2;
1068                    stone.push(Piece {
1069                        wall_sides: None,
1070                        mesh: Mesh3d::cuboid(
1071                            vec3(TILE, 0.22, TILE),
1072                            Color::from_rgba(shade - 6, shade - 1, shade + 4, 255),
1073                        ),
1074                        position: world(p, -0.12),
1075                        rotation: Quat::IDENTITY,
1076                    });
1077                    stone.push(Piece {
1078                        wall_sides: None,
1079                        mesh: Mesh3d::cuboid(
1080                            vec3(TILE, 0.4, TILE),
1081                            Color::from_rgba(40, 34, 38, 255),
1082                        ),
1083                        position: world(p, 4.3),
1084                        rotation: Quat::IDENTITY,
1085                    });
1086                    // Ceiling formations frame the view without blocking the walking plane.
1087                    if hash < 3 && tile == b'.' {
1088                        stone.push(Piece {
1089                            wall_sides: None,
1090                            mesh: Mesh3d::cone(
1091                                0.55,
1092                                0.8 + hash as f32 * 0.25,
1093                                Color::from_rgba(78, 62, 58, 255),
1094                                5,
1095                            ),
1096                            position: world(p + vec2(0.6, 0.7), 3.5),
1097                            rotation: Quat::from_rotation_x(std::f32::consts::PI),
1098                        });
1099                    }
1100                }
1101            }
1102        }
1103        let occlusion = ferravex_render::ao::AoScene::new(stone.iter().map(|p| {
1104            (
1105                &p.mesh.mesh,
1106                Mat4::from_rotation_translation(p.rotation, p.position),
1107            )
1108        }))
1109        .expect("cave AO scene");
1110        for p in &mut stone {
1111            occlusion
1112                .bake(
1113                    &mut p.mesh.mesh,
1114                    Mat4::from_rotation_translation(p.rotation, p.position),
1115                    ferravex_render::ao::AoSettings {
1116                        radius: 1.5,
1117                        strength: 0.3,
1118                        ..Default::default()
1119                    },
1120                )
1121                .expect("cave vertex AO");
1122            if let Some(sides) = p.wall_sides {
1123                // Bake against complete occluders first. Only the faces touching
1124                // walkable cells can be seen from the collision-bounded camera.
1125                // Three height bands × four triangles × three vertices per side.
1126                const SIDE_VERTICES: usize = 3 * 4 * 3;
1127                p.mesh
1128                    .mesh
1129                    .indices
1130                    .retain(|&i| sides[i as usize / SIDE_VERTICES]);
1131            }
1132            p.mesh.invalidate_gpu();
1133        }
1134        // Bake once, then merge nearby opaque pieces into 3x3-tile chunks.
1135        // Authored AO and normals survive; distant chunks retain useful bounds.
1136        let mut chunks = std::collections::BTreeMap::<(i32, i32), Vec<Piece>>::new();
1137        for piece in stone {
1138            let key = (
1139                (piece.position.x / (TILE * 3.)).floor() as i32,
1140                (piece.position.z / (TILE * 3.)).floor() as i32,
1141            );
1142            chunks.entry(key).or_default().push(piece);
1143        }
1144        let stone = chunks
1145            .into_values()
1146            .map(|pieces| Piece {
1147                mesh: Mesh3d::combine(pieces.iter().map(|p| {
1148                    (
1149                        &p.mesh.mesh,
1150                        Mat4::from_rotation_translation(p.rotation, p.position),
1151                    )
1152                }))
1153                .expect("bounded static cave chunk"),
1154                position: Vec3::ZERO,
1155                rotation: Quat::IDENTITY,
1156                wall_sides: None,
1157            })
1158            .collect();
1159        // Deterministic seams of tiny crystals where floor meets wall.
1160        let mut shards = Vec::new();
1161        for (z, row) in MAP.iter().enumerate() {
1162            for (x, tile) in row.bytes().enumerate() {
1163                if tile == b'#' || (x * 7 + z * 13) % 4 != 0 {
1164                    continue;
1165                }
1166                for (dx, dz) in [(1i32, 0i32), (-1, 0), (0, 1), (0, -1)] {
1167                    let (nx, nz) = (x as i32 + dx, z as i32 + dz);
1168                    if MAP[nz as usize].as_bytes()[nx as usize] != b'#' {
1169                        continue;
1170                    }
1171                    let dir = vec2(dx as f32, dz as f32);
1172                    let side = vec2(-dir.y, dir.x);
1173                    for k in 0..3 {
1174                        let offset = (k as f32 - 1.) * 0.22 + ((x + z) % 3) as f32 * 0.1;
1175                        let p = center(x, z) + dir * (TILE * 0.5 - 0.1) + side * offset;
1176                        let lean = Quat::from_rotation_z(-dir.x * 0.5 + k as f32 * 0.15)
1177                            * Quat::from_rotation_x(dir.y * 0.5);
1178                        shards.push((world(p, 0.1 + k as f32 * 0.03), lean, (x + k) % 5 / 4));
1179                    }
1180                    break;
1181                }
1182            }
1183        }
1184        let pulse = ShaderMaterial::new(
1185            ShaderSource::fragment(include_str!("../shaders/crystal.frag")),
1186            MaterialOptions {
1187                blend: ferravex_render::material::BlendMode::Opaque,
1188                ..Default::default()
1189            },
1190        )
1191        .expect("crystal material");
1192        #[cfg(not(target_arch = "wasm32"))]
1193        let watcher = std::env::var_os("FERRAVEX_CRYSTAL_SHADER").map(|path| {
1194            ferravex_render::material::MaterialFileWatcher::new(pulse.clone(), None, path.into())
1195        });
1196        Self {
1197            pulse,
1198            #[cfg(not(target_arch = "wasm32"))]
1199            watcher: std::cell::RefCell::new(watcher),
1200            stone,
1201            crystal: Mesh3d::frustum(0.32, 0.24, 0.8, MINT, 6),
1202            tip: Mesh3d::cone(0.25, 0.55, Color::from_rgba(160, 250, 235, 255), 6),
1203            pedestal: Mesh3d::cylinder(0.7, 0.65, Color::from_rgba(112, 99, 79, 255), 8),
1204            rune: Mesh3d::cuboid(vec3(0.075, 0.025, 0.4), MINT),
1205            rune_dark: Mesh3d::cuboid(vec3(0.075, 0.025, 0.4), Color::from_rgba(28, 52, 52, 255)),
1206            gate: Mesh3d::cuboid(vec3(TILE, 3.9, 0.35), Color::from_rgba(56, 102, 101, 255)),
1207            daylight: Mesh3d::cuboid(vec3(2.4, 3.5, 0.08), Color::from_rgba(225, 235, 182, 255)),
1208            shy: Mesh3d::frustum(0.15, 0.11, 0.36, Color::from_rgba(168, 120, 236, 255), 6),
1209            shy_tip: Mesh3d::cone(0.12, 0.26, Color::from_rgba(214, 180, 255, 255), 6),
1210            paper: Mesh3d::cuboid(
1211                vec3(0.34, 0.012, 0.44),
1212                Color::from_rgba(214, 204, 176, 255),
1213            ),
1214            hat: Mesh3d::cylinder(0.15, 0.16, Color::from_rgba(96, 64, 40, 255), 8),
1215            brim: Mesh3d::cylinder(0.26, 0.025, Color::from_rgba(84, 56, 36, 255), 10),
1216            lantern: Mesh3d::cuboid(vec3(0.17, 0.24, 0.17), Color::from_rgba(255, 192, 110, 255)),
1217            lantern_cap: Mesh3d::cuboid(vec3(0.22, 0.05, 0.22), Color::from_rgba(52, 46, 40, 255)),
1218            shard: [
1219                Mesh3d::cone(0.07, 0.3, Color::from_rgba(70, 150, 138, 255), 4),
1220                Mesh3d::cone(0.07, 0.3, Color::from_rgba(132, 98, 178, 255), 4),
1221            ],
1222            shards,
1223        }
1224    }
1225    fn draw(
1226        &self,
1227        game: &Game,
1228        material: &LitMaterial,
1229        eye: Vec3,
1230        presentation: &Presentation,
1231        active: bool,
1232    ) {
1233        let time = presentation.motion_time;
1234        #[cfg(not(target_arch = "wasm32"))]
1235        if let Some(watcher) = self.watcher.borrow_mut().as_mut()
1236            && let Err(error) = watcher.poll()
1237        {
1238            eprintln!("Crystal shader reload: {error}");
1239        }
1240        let mut lights = [ferravex_render::lighting::PointLight {
1241            position: Vec3::ZERO,
1242            color: MINT,
1243            radius: 4.8,
1244            intensity: 1.8,
1245        }; 3];
1246        let mut count = 0;
1247        for (i, &p) in game.crystals.iter().enumerate() {
1248            if !game.collected[i] {
1249                // Warmer/colder: each crystal brightens as the explorer approaches.
1250                let near = (1. - p.distance(game.position) / RESONANCE_RANGE).clamp(0., 1.);
1251                lights[count].position = world(p, 1.35);
1252                lights[count].intensity = 1.5 + 0.8 * near;
1253                lights[count].radius = 4.8 + 1.4 * near;
1254                count += 1;
1255            }
1256        }
1257        ferravex_render::set_point_lights(&lights[..count]).unwrap();
1258        let settings = LitSettings {
1259            camera_position: eye,
1260            light_direction: vec3(-0.3, 0.8, 0.4),
1261            fog_color: INK,
1262            fog_start: 6.0,
1263            fog_end: 26.0,
1264            ambient: 0.5,
1265        };
1266        material.begin(settings);
1267        for piece in &self.stone {
1268            piece.mesh.draw(piece.position, piece.rotation);
1269        }
1270        for marker in *b"AB" {
1271            self.pedestal.draw(world(at(marker), 0.325), Quat::IDENTITY);
1272        }
1273        if !game.open() {
1274            self.gate.draw(world(at(b'G'), 1.95), Quat::IDENTITY);
1275        }
1276        for p in lantern_positions() {
1277            self.lantern_cap.draw(world(p, 0.27), Quat::IDENTITY);
1278        }
1279        // Wendell's note and hat. The note stays; it is always worth a re-read.
1280        let note = note_position();
1281        self.paper
1282            .draw(world(note, 0.02), Quat::from_rotation_y(0.4));
1283        self.hat.draw(
1284            world(note + vec2(0.45, 0.2), 0.1),
1285            Quat::from_rotation_z(0.12),
1286        );
1287        self.brim.draw(
1288            world(note + vec2(0.45, 0.2), 0.02),
1289            Quat::from_rotation_z(0.12),
1290        );
1291        // Full ambient keeps crystal facets luminous without adding a texture or post-process.
1292        material.begin(LitSettings {
1293            ambient: 1.0,
1294            ..settings
1295        });
1296        // Bypass the authored pulse shader for reduced flash. Freezing its time
1297        // alone still pulses as bobbing changes the shader's world.y input.
1298        if presentation.pulse {
1299            self.pulse
1300                .begin([
1301                    [presentation.glow_time, 0., 0., 0.],
1302                    [0.; 4],
1303                    [0.; 4],
1304                    [0.; 4],
1305                ])
1306                .unwrap();
1307        }
1308        for (i, &p) in game.crystals.iter().enumerate() {
1309            if game.collected[i] {
1310                continue;
1311            }
1312            let height = 0.95 + (time * 1.6 + i as f32).sin() * 0.09;
1313            let rotation = Quat::from_rotation_y(time * 0.22 + i as f32);
1314            self.crystal.draw(world(p, height), rotation);
1315            self.tip.draw(world(p, height + 0.65), rotation);
1316            self.tip.draw(
1317                world(p, height - 0.65),
1318                rotation * Quat::from_rotation_x(std::f32::consts::PI),
1319            );
1320        }
1321        if presentation.pulse {
1322            self.pulse.end();
1323        }
1324        if !game.shy_found {
1325            // Steve wobbles shyly in his corner; motionless under reduced motion.
1326            let p = shy_position();
1327            let wobble = Quat::from_rotation_y(time * 0.4)
1328                * Quat::from_rotation_z((time * 2.3).sin() * 0.12);
1329            self.shy.draw(world(p, 0.2), wobble);
1330            self.shy_tip.draw(world(p, 0.5), wobble);
1331        }
1332        for p in lantern_positions() {
1333            self.lantern.draw(world(p, 0.12), Quat::IDENTITY);
1334        }
1335        for (position, rotation, kind) in &self.shards {
1336            self.shard[*kind].draw(*position, *rotation);
1337        }
1338        for (index, marker) in b"AB".iter().enumerate() {
1339            let p = at(*marker);
1340            for bar in 0..=index {
1341                self.rune.draw(
1342                    world(
1343                        p + vec2((bar as f32 - index as f32 * 0.5) * 0.19, 0.0),
1344                        0.665,
1345                    ),
1346                    Quat::IDENTITY,
1347                );
1348            }
1349            if game.switches as usize > index {
1350                self.tip
1351                    .draw(world(p, 1.2), Quat::from_rotation_y(time * 0.3));
1352            }
1353        }
1354        if !game.open() {
1355            // The seal's three sockets light as their crystals are recovered.
1356            for i in 0..3 {
1357                let rune = if game.collected[i] {
1358                    &self.rune
1359                } else {
1360                    &self.rune_dark
1361                };
1362                rune.draw(
1363                    world(at(b'G') + vec2((i as f32 - 1.0) * 0.35, 0.22), 1.65),
1364                    Quat::from_rotation_x(std::f32::consts::FRAC_PI_2),
1365                );
1366            }
1367        }
1368        self.daylight
1369            .draw(world(at(b'X') + vec2(0.0, -0.7), 1.75), Quat::IDENTITY);
1370        if active && let Some(target) = game.target() {
1371            let p = game.target_position(target);
1372            let color = if game.target_ready(target) {
1373                MINT
1374            } else {
1375                WARM
1376            };
1377            // A steady ground ring identifies the exact prompted object.
1378            // Depth-tested geometry cannot reveal targets through cave walls.
1379            for segment in 0..24 {
1380                let point = |n: u32| {
1381                    let angle = n as f32 * std::f32::consts::TAU / 24.;
1382                    world(p + vec2(angle.cos(), angle.sin()) * 0.85, 0.035)
1383                };
1384                draw_line_3d(point(segment), point(segment + 1), color);
1385            }
1386        }
1387        material.end();
1388    }
1389}
1390
1391fn window_conf() -> Conf {
1392    #[allow(unused_mut)]
1393    let mut conf = ferravex_render::window_conf("Ferravex / Crystal Cavern");
1394    #[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
1395    capture::window(&mut conf);
1396    conf
1397}
1398
1399/// Records context for this map, objective graph and secret count.
1400const RECORD_RULES: u64 = 0x4343_4156_0001;
1401const RECORD_ID: &str = "expedition";
1402
1403/// (fastest seconds, most secrets) from optional local records.
1404fn best_record(records: Option<&ferravex_render::storage::Records>) -> Option<(f32, u64)> {
1405    let record = records?.get(RECORD_ID, RECORD_RULES)?;
1406    Some((record.fastest_us? as f32 / 1_000_000., record.score))
1407}
1408
1409ferravex_render::game!(window_conf, game);
1410async fn game() {
1411    let font = get_default_font();
1412    let characters: Vec<char> = (' '..='~').collect();
1413    for size in [14, 17, 20, 22, 23, 24, 26, 30, 38] {
1414        font.populate_font_cache(&characters, size);
1415    }
1416    let mut demo = Demo::new();
1417    let mut sound = GameAudio::new();
1418    let mut score = ferravex_render::audio::AdaptiveScore::new(90, 17).unwrap();
1419    use ferravex_play::audio::{AcousticProfile, AcousticScene, AcousticZone};
1420    let acoustics = AcousticScene::new([AcousticZone {
1421        min: vec3(0., -2., 19.),
1422        max: vec3(35., 6., 40.),
1423        feather: 4.,
1424        profile: AcousticProfile {
1425            gain: 0.9,
1426            low_pass_hz: 3500.,
1427        },
1428    }])
1429    .unwrap();
1430    ferravex_render::set_quality(ferravex_render::lighting::Quality::Medium);
1431    let mut expedition = Expedition::new(demo.autoplay);
1432    let mut presentation = Presentation::default();
1433    let mut juice = Juice::new();
1434    let mut particles = ferravex_render::effects::ParticleRenderer::new(320)
1435        .expect("bounded presentation particles");
1436    // Personal bests are optional: a storage failure still leaves a playable game.
1437    let mut records = ferravex_render::storage::Records::new("crystal-cavern").ok();
1438    let mut results = hud::Results::default();
1439    let mut card_motion = hud::CardMotion::new();
1440    let mut hud_scratch = String::with_capacity(128);
1441    let mut pauses = 0_u32;
1442    let mut glow = look::Glow::new();
1443    let mut look_state = None;
1444    let mut attract = 0_f32;
1445    #[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
1446    let mut capture = capture::Capture::from_env();
1447    let mut view_rig = Rig3::new(Settings3 {
1448        position_half_life: 0.,
1449        target_half_life: 0.,
1450        fov_half_life: 0.,
1451        ..Default::default()
1452    })
1453    .unwrap();
1454    let scene = Scene::new();
1455    let material = LitMaterial::new().expect("Ferravex cave shader");
1456    let mut pitch = -0.03_f32;
1457    let mut player_input = PlayerInput::preset("crystal-cavern", Preset::Explore);
1458    player_input.set_mouse_look_button(Some(1)).unwrap();
1459    for (name, key) in [
1460        ("move_left", KeyCode::A),
1461        ("move_right", KeyCode::D),
1462        ("move_forward", KeyCode::W),
1463        ("move_back", KeyCode::S),
1464    ] {
1465        let mut bindings = player_input.bindings(name).unwrap().to_vec();
1466        bindings.retain(|b| {
1467            !matches!(b.code, InputCode::Key(_)) || b.code == InputCode::Key(key as u16)
1468        });
1469        player_input.set_default_bindings(name, bindings).unwrap();
1470    }
1471    for (name, key, scale) in [
1472        ("look_rate_x", KeyCode::Left, -0.72),
1473        ("look_rate_x", KeyCode::Right, 0.72),
1474        ("look_rate_y", KeyCode::Up, -0.5),
1475        ("look_rate_y", KeyCode::Down, 0.5),
1476    ] {
1477        player_input
1478            .add_default_binding(
1479                name,
1480                Binding {
1481                    code: InputCode::Key(key as u16),
1482                    scale,
1483                    deadzone: 0.,
1484                },
1485            )
1486            .unwrap();
1487    }
1488    player_input
1489        .global_action(
1490            "help",
1491            "Toggle help",
1492            ActionKind::Button,
1493            vec![Binding::digital(InputCode::Key(KeyCode::H as u16))],
1494        )
1495        .unwrap();
1496    let mut help = false;
1497    let mut confirm_requested = false;
1498    loop {
1499        // Read on every presentation frame, before accepted feedback and draws,
1500        // including Ready, Controls, paused and frames with no fixed update.
1501        let policy = ferravex_render::preferences::feedback_policy();
1502        juice.apply_policy(policy);
1503        ferravex_render::ui::warm_up_font_sizes(&[14, 17, 20, 22, 23, 24, 26, 30, 38]);
1504        let w = screen_width();
1505        let h = screen_height();
1506        player_input
1507            .set_touch_layout(&[
1508                Control {
1509                    region: Region::Circle {
1510                        center: vec2(w - 65., h - 90.),
1511                        radius: 48.,
1512                    },
1513                    output: Output::Button(4),
1514                },
1515                Control {
1516                    region: Region::Rect(Rect::new(0., 0., w * 0.42, h)),
1517                    output: Output::Stick {
1518                        x: 0,
1519                        y: 1,
1520                        radius: 54.,
1521                        floating: true,
1522                    },
1523                },
1524                Control {
1525                    region: Region::Rect(Rect::new(w * 0.42, 0., w * 0.58, h)),
1526                    output: Output::Look { x: 0, y: 1 },
1527                },
1528            ])
1529            .unwrap();
1530        player_input.sample_play();
1531        let clicked_confirm = std::mem::take(&mut confirm_requested);
1532        let confirm = player_input.pressed("confirm") || clicked_confirm;
1533        let activate = confirm && !expedition.session.is_playing();
1534        let restarted = player_input.pressed("restart")
1535            || expedition.session.state() == SessionState::Won && confirm;
1536        if restarted {
1537            expedition.restart();
1538            presentation = Presentation::default();
1539            juice.reset();
1540            results = hud::Results::default();
1541            sound.reset();
1542            view_rig.cut();
1543            pitch = -0.03;
1544            // Back at Base Camp: the whole expedition again, as pictograms.
1545            juice.call_marked(
1546                "BASE CAMP",
1547                quips::retry(expedition.runs),
1548                Some(juice::Mark::Icon(
1549                    ferravex_render::icons::Icon::Home,
1550                    juice::STONE,
1551                )),
1552                juice::Extra::Chain,
1553                juice::STONE,
1554                3.,
1555                juice::Priority::Event,
1556            );
1557        } else if confirm && expedition.session.state() == SessionState::Ready {
1558            expedition.start();
1559            juice.zone(0, 3.2);
1560        }
1561        if restarted || activate {
1562            // Suppress keys held across start/retry/resume, then restore the
1563            // gameplay context. PlayerInput retains the manual pause reason.
1564            player_input.set_paused(true);
1565            player_input.set_paused(false);
1566            player_input.sample(true);
1567        }
1568        #[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
1569        let force_pause = {
1570            if let Some(secrets) = capture.before_frame(&mut expedition) {
1571                juice.on_progress(&secrets, &expedition.game, expedition.runs);
1572            }
1573            capture.paused()
1574        };
1575        #[cfg(not(all(debug_assertions, not(target_arch = "wasm32"))))]
1576        let force_pause = false;
1577        let was_playing = expedition.session.is_playing();
1578        expedition.set_paused(force_pause || !demo.autoplay && !player_input.gameplay_active());
1579        if was_playing && expedition.session.state() == SessionState::Paused {
1580            pauses = pauses.wrapping_add(1);
1581        }
1582        if player_input.pressed("help") {
1583            help = !help;
1584        }
1585        let elapsed = demo.dt();
1586        let dt = if expedition.session.is_playing() && !expedition.discard_frame {
1587            elapsed
1588        } else {
1589            0.
1590        };
1591        let movement = player_input.movement();
1592        let look = player_input.look(dt);
1593        if !demo.autoplay && expedition.session.is_playing() && !expedition.discard_frame {
1594            expedition.game.yaw += look.x;
1595            pitch = (pitch - look.y).clamp(-0.8, 0.8);
1596        }
1597        #[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
1598        let staged_use = capture.use_now();
1599        #[cfg(not(all(debug_assertions, not(target_arch = "wasm32"))))]
1600        let staged_use = false;
1601        let previous_elapsed = expedition.game.elapsed;
1602        let progress = expedition.advance(elapsed as f64, || Input {
1603            movement,
1604            interact: player_input.pressed("interact") || staged_use,
1605            ..Default::default()
1606        });
1607        let played = expedition.game.elapsed - previous_elapsed;
1608        presentation.advance(played, policy);
1609        juice.on_progress(&progress, &expedition.game, expedition.runs);
1610        let pings = juice.advance(played, &expedition.game);
1611        if expedition.session.state() == SessionState::Won {
1612            juice.advance_celebration(elapsed);
1613        }
1614        for index in 0..6 {
1615            if progress.completed & (1 << index) != 0 {
1616                ferravex_render::performance::event(
1617                    ferravex_play::performance::DiagnosticKind::Objective,
1618                    index as f32,
1619                );
1620            }
1621        }
1622        if progress.pickups > 0 {
1623            sound.cue(Cue::Pickup, 0.55);
1624        }
1625        if progress.altars > 0 {
1626            sound.cue(Cue::Impact(Surface::Metal), 0.4);
1627        }
1628        if progress.completed & (1 << 4) != 0 {
1629            // The seal grinds open under the second altar's chime.
1630            sound.cue(Cue::Impact(Surface::Stone), 0.6);
1631        }
1632        if progress.won {
1633            sound.cue(Cue::Success, 0.65);
1634        }
1635        if progress.shy {
1636            sound.cue(Cue::Pickup, 0.5);
1637            sound.cue(Cue::Success, 0.3);
1638        }
1639        if progress.note.is_some() || progress.hint {
1640            sound.cue(Cue::Click, 0.3);
1641        }
1642        if progress.rejected.is_some() {
1643            sound.cue(Cue::Impact(Surface::Wood), 0.25);
1644        }
1645        if progress.bonks > 0 {
1646            sound.cue(Cue::Impact(Surface::Stone), 0.35);
1647        }
1648        if pings > 0 {
1649            sound.cue(Cue::Click, 0.05 + 0.15 * expedition.game.resonance());
1650        }
1651        if progress.won {
1652            let game = &expedition.game;
1653            // Compare against the stored best before recording this clear.
1654            results = hud::Results {
1655                summary: quips::RunSummary {
1656                    seconds: game.elapsed,
1657                    hints: game.hints_used,
1658                    bonks: game.bonks,
1659                    shy: game.shy_found,
1660                    note: game.note_reads > 0,
1661                },
1662                previous_best: best_record(records.as_ref()).map(|best| best.0),
1663                recorded: !demo.autoplay,
1664            };
1665            #[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
1666            if let Some(best) = capture.fake_best() {
1667                results.previous_best = Some(best);
1668                results.recorded = true;
1669            }
1670            if !demo.autoplay
1671                && let Some(records) = records.as_mut()
1672            {
1673                let _ = records.attempt(
1674                    RECORD_ID,
1675                    RECORD_RULES,
1676                    u64::from(game.shy_found) + u64::from(game.note_reads > 0),
1677                    ferravex_render::storage::run_micros(game.elapsed),
1678                );
1679            }
1680        }
1681        let game = &expedition.game;
1682        sound.set_acoustics(acoustics.sample(world(game.position, 0.), false).unwrap());
1683        score.update(dt.min(0.25), (game.count() as f32 / 3.).clamp(0., 1.));
1684        sound.walk(
1685            world(game.position, 0.),
1686            true,
1687            expedition.session.is_playing(),
1688            Surface::Stone,
1689            1.45,
1690        );
1691        let state = expedition.session.state();
1692        if look_state != Some(state) {
1693            // Sticky per-state grade: cave, framed menus, or daylight results.
1694            set_post_fx(look::post_for(state));
1695            look_state = Some(state);
1696        }
1697        clear_background(INK);
1698        let (shake_yaw, shake_pitch) = juice.shake();
1699        // Head bob follows accepted travel (frozen under reduced motion), and
1700        // the Ready screen slowly looks around the cave like an attract mode.
1701        let stride = (game.velocity.length() / SPEED).min(1.);
1702        let bob =
1703            (game.walked * std::f32::consts::TAU / 1.7).sin() * 0.035 * stride * juice.motion();
1704        if state == SessionState::Ready {
1705            attract += elapsed;
1706        }
1707        let sway = if state == SessionState::Ready {
1708            (attract * 0.22).sin() * 0.45 * juice.motion()
1709        } else {
1710            0.
1711        };
1712        let view = view_rig
1713            .update(
1714                dt,
1715                Input3 {
1716                    target: Target3::at(world(game.position, 0.)),
1717                    mode: Mode3::FirstPerson {
1718                        eye_offset: Vec3::Y * (1.55 + bob),
1719                        yaw: game.yaw + shake_yaw + sway,
1720                        pitch: (pitch + shake_pitch).clamp(-0.85, 0.85),
1721                    },
1722                    fov_y: (67. + juice.fov_punch()).to_radians(),
1723                },
1724                &NoObstructions,
1725            )
1726            .expect("valid cavern view")
1727            .pose;
1728        let eye = view.position;
1729        set_camera(&Camera3D {
1730            position: eye,
1731            target: view.target,
1732            up: view.up,
1733            fovy: view.fov_y,
1734            z_near: 0.06,
1735            z_far: 80.,
1736            ..Default::default()
1737        });
1738        scene.draw(
1739            game,
1740            &material,
1741            eye,
1742            &presentation,
1743            expedition.session.is_playing(),
1744        );
1745        let forward = (view.target - eye).normalize_or_zero();
1746        let right = forward.cross(view.up).normalize_or_zero();
1747        look::draw_lights(
1748            &mut glow,
1749            game,
1750            (right, view.up),
1751            if presentation.pulse {
1752                presentation.glow_time
1753            } else {
1754                0.
1755            },
1756            presentation.motion_time,
1757        );
1758        // Bursts are drawn only during play; menus keep a clean overlay stream.
1759        if expedition.session.is_playing()
1760            && !juice.particles.is_empty()
1761            && let Ok(billboard) = ferravex_render::effects::BillboardView::new(
1762                eye,
1763                (view.target - eye).cross(view.up),
1764                view.up,
1765            )
1766        {
1767            let _ = particles.draw_3d(
1768                &juice.particles,
1769                billboard,
1770                ferravex_render::effects::ParticleStyle {
1771                    draw: ferravex_render::effects::EffectStyle {
1772                        blend: ferravex_render::effects::EffectBlend::Additive,
1773                        ..Default::default()
1774                    },
1775                    ..Default::default()
1776                },
1777            );
1778        }
1779        set_default_camera();
1780        let use_hint = action_hint(&player_input, "interact");
1781        let confirm_hint = action_hint(&player_input, "confirm");
1782        let retry_hint = action_hint(&player_input, "restart");
1783        let pause_hint = action_hint(&player_input, "pause");
1784        let help_hint = action_hint(&player_input, "help");
1785        if expedition.session.is_playing() {
1786            hud::edge_glow(&juice, w, h);
1787            hud::top_bar(game, &juice, w, &mut hud_scratch);
1788            let marker = hud::hint_marker(game, game.yaw, w, &mut hud_scratch);
1789            hud::pops(&juice, w, h);
1790            let target_color = game
1791                .target()
1792                .map_or(Color::new(0.8, 0.9, 0.85, 0.6), |target| {
1793                    if game.target_ready(target) {
1794                        MINT
1795                    } else {
1796                        WARM
1797                    }
1798                });
1799            draw_circle(
1800                screen_width() * 0.5 + juice.nope_offset(),
1801                screen_height() * 0.5,
1802                if game.target().is_some() { 3. } else { 1.7 },
1803                target_color,
1804            );
1805            // The prompt pill sits below the reticle, above the note slip and
1806            // clear of the help rows.
1807            let prompt_top = (h * 0.55).min(h - 230.).max(114.);
1808            let prompt = game.prompt();
1809            if let Some(prompt) = prompt {
1810                // Any accepted use teaches the key; then the target leads.
1811                let learned =
1812                    game.count() > 0 || game.switches > 0 || game.shy_found || game.note_reads > 0;
1813                hud::prompt(
1814                    prompt_top,
1815                    w,
1816                    &use_hint,
1817                    prompt,
1818                    (game.note_reads, learned),
1819                    &juice,
1820                );
1821            }
1822            // Milestones, zone names and the cave's echo sit between the bar
1823            // and the prompt, never in the warm notice slot below.
1824            let callout_top = (if marker {
1825                hud::MARKER_Y + 42.
1826            } else {
1827                hud::BAR + 12.
1828            })
1829            .max(h * 0.13);
1830            let callout_bottom = if prompt.is_some() {
1831                prompt_top - 16.
1832            } else {
1833                // Room for a head line plus its whisper/echo on short screens.
1834                (h * 0.5 - 40.).max(callout_top + 48.)
1835            };
1836            hud::callout(
1837                &juice,
1838                w,
1839                callout_top,
1840                (callout_bottom - callout_top).clamp(0., 96.),
1841            );
1842            // Wendell's note is the one text read during play: it is the find.
1843            // A refused use speaks through the shaking prompt and the echo.
1844            if game.notice_time > 0.0
1845                && let Notice::Note(page) = game.notice
1846            {
1847                hud::note(page, w, h);
1848            }
1849            if help {
1850                hud::help([&use_hint, &pause_hint, &retry_hint, &help_hint], w, h);
1851            } else if !player_input.touch_seen() {
1852                let move_hint = ["move_forward", "move_left", "move_back", "move_right"]
1853                    .map(|name| action_hint(&player_input, name));
1854                hud::onboarding(game, move_hint.each_ref().map(String::as_str), w, h);
1855            }
1856        } else {
1857            confirm_requested |= hud::card(
1858                hud::Card {
1859                    state: expedition.session.state(),
1860                    confirm_hint: &confirm_hint,
1861                    retry_hint: &retry_hint,
1862                    results: &results,
1863                    best: best_record(records.as_ref()),
1864                    pauses,
1865                    controls_open: player_input.controls_open(),
1866                },
1867                game,
1868                &juice,
1869                &mut card_motion,
1870                elapsed,
1871                w,
1872                h,
1873            );
1874        }
1875        if player_input.touch_seen()
1876            && !player_input.touch_customized()
1877            && expedition.session.is_playing()
1878        {
1879            let (origin, delta) = player_input
1880                .touch_stick(0, 1)
1881                .unwrap_or((vec2(90., h - 105.), Vec2::ZERO));
1882            let tint = Color::new(0.8, 0.9, 0.85, 0.45);
1883            draw_circle_lines(origin.x, origin.y, 54., 2., tint);
1884            draw_circle(
1885                origin.x + delta.x * 38.,
1886                origin.y + delta.y * 38.,
1887                15.,
1888                tint,
1889            );
1890            draw_circle_lines(w - 65., h - 90., 44., 2., tint);
1891            ferravex_render::icons::draw(
1892                ferravex_render::icons::Icon::Hand,
1893                vec2(w - 65., h - 90.),
1894                34.,
1895                tint,
1896            );
1897        }
1898        player_input.draw_controls();
1899        #[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
1900        capture.end_frame();
1901        if demo.finish_frame() {
1902            break;
1903        }
1904        next_frame().await;
1905    }
1906    if demo.autoplay {
1907        let game = &expedition.game;
1908        println!(
1909            "Crystal Cavern: crystals={}, altars={}, won={}, elapsed={:.2}, hints={}, bonks={}",
1910            game.count(),
1911            game.switches,
1912            game.won,
1913            game.elapsed,
1914            game.hints_used,
1915            game.bonks
1916        );
1917    }
1918}
1919
1920#[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
1921mod capture;
1922mod hud;
1923mod juice;
1924mod look;
1925mod quips;
1926use juice::Juice;
1927
1928#[cfg(test)]
1929mod journey200_138;
1930
1931#[cfg(test)]
1932mod journey200_tests;
1933
1934#[cfg(test)]
1935mod journey200_193;
1936
1937#[cfg(test)]
1938mod polish_tests;
1939
1940#[cfg(test)]
1941mod tests {
1942    use super::*;
1943    use ferravex_play::input::{ActionMap, ContextId};
1944
1945    fn interaction_map() -> (ActionMap, usize, InputCode) {
1946        let mut map = ActionMap::default();
1947        let key = InputCode::Key(KeyCode::E as u16);
1948        let action = map
1949            .named_action(
1950                "interact",
1951                ActionKind::Button,
1952                ContextId::GLOBAL,
1953                vec![Binding::digital(key)],
1954            )
1955            .unwrap();
1956        (map, action, key)
1957    }
1958
1959    fn playing() -> Expedition {
1960        let mut expedition = Expedition::new(false);
1961        expedition.start();
1962        expedition.advance(0., Input::default);
1963        expedition
1964    }
1965
1966    #[test]
1967    fn ready_and_start_do_not_charge_menu_time_or_reuse_input() {
1968        let mut expedition = Expedition::new(false);
1969        expedition.game.position = expedition.game.crystals[0];
1970        let input = Input {
1971            interact: true,
1972            ..Default::default()
1973        };
1974        expedition.advance(90., || input);
1975        assert_eq!(expedition.session.state(), SessionState::Ready);
1976        assert_eq!(expedition.game.elapsed, 0.);
1977        assert_eq!(expedition.game.count(), 0);
1978        expedition.start();
1979        expedition.advance(90., || input);
1980        assert_eq!(expedition.session.tick(), 0);
1981        expedition.advance(1. / 60., Input::default);
1982        assert_eq!(expedition.session.tick(), 1);
1983        assert_eq!(expedition.game.count(), 0);
1984    }
1985
1986    #[test]
1987    fn interaction_tap_survives_frames_without_a_tick() {
1988        let mut expedition = playing();
1989        expedition.game.position = expedition.game.crystals[0];
1990        let (mut map, action, key) = interaction_map();
1991        map.feed(key, 1.);
1992        map.feed(key, 0.);
1993        for _ in 0..2 {
1994            expedition.advance(0.001, || Input {
1995                interact: map.consume_tick(action).pressed,
1996                ..Default::default()
1997            });
1998        }
1999        assert_eq!(expedition.game.count(), 0);
2000        assert!(map.peek(action).pressed);
2001        let progress = expedition.advance(0.015, || Input {
2002            interact: map.consume_tick(action).pressed,
2003            ..Default::default()
2004        });
2005        assert_eq!(progress.pickups, 1);
2006        assert_eq!(expedition.game.count(), 1);
2007        assert!(!map.peek(action).pressed);
2008    }
2009
2010    #[test]
2011    fn one_interaction_edge_cannot_collect_multiple_targets_during_catchup() {
2012        let mut expedition = playing();
2013        let p = expedition.game.crystals[0];
2014        expedition.game.crystals.fill(p);
2015        expedition.game.position = p;
2016        let input = Input {
2017            interact: true,
2018            ..Default::default()
2019        };
2020        let progress = expedition.advance(0.12, || input);
2021        assert!(expedition.session.tick() > 1);
2022        assert_eq!(progress.pickups, 1);
2023        assert_eq!(expedition.game.count(), 1);
2024        expedition.advance(0.1, Input::default);
2025        assert_eq!(expedition.game.count(), 1);
2026        expedition.advance(1. / 60., || input);
2027        assert_eq!(expedition.game.count(), 2);
2028    }
2029
2030    #[test]
2031    fn pause_and_refocus_clear_pending_input_without_advancing_time() {
2032        let mut expedition = playing();
2033        expedition.game.position = expedition.game.crystals[0];
2034        expedition.game.velocity = Vec2::Y * SPEED;
2035        let input = Input {
2036            interact: true,
2037            movement: Vec2::Y,
2038            ..Default::default()
2039        };
2040        expedition.advance(0.001, || input);
2041        let position = expedition.game.position;
2042        let notice_time = expedition.game.notice_time;
2043        expedition.set_paused(true);
2044        assert_eq!(expedition.game.velocity, Vec2::ZERO);
2045        expedition.advance(120., || input);
2046        assert_eq!(expedition.game.elapsed, 0.);
2047        assert_eq!(expedition.game.notice_time, notice_time);
2048        assert_eq!(expedition.game.position, position);
2049        expedition.set_paused(false);
2050        expedition.advance(120., || input);
2051        assert_eq!(expedition.session.tick(), 0);
2052        expedition.advance(1. / 60., Input::default);
2053        assert_eq!(expedition.session.tick(), 1);
2054        assert_eq!(expedition.game.count(), 0);
2055        assert_eq!(expedition.game.position, position);
2056    }
2057
2058    #[test]
2059    fn focus_loss_between_render_frames_discards_a_buffered_tap() {
2060        let mut expedition = playing();
2061        expedition.game.position = expedition.game.crystals[0];
2062        let (mut map, action, key) = interaction_map();
2063        map.feed(key, 1.);
2064        expedition.advance(0.001, || Input {
2065            interact: map.consume_tick(action).pressed,
2066            ..Default::default()
2067        });
2068        assert!(map.peek(action).pressed);
2069        // PlayerInput clears its map on a focus-epoch change even when the host
2070        // delivers no render frame while unfocused. No second latch survives.
2071        map.lose_focus();
2072        expedition.advance(1. / 60., || Input {
2073            interact: map.consume_tick(action).pressed,
2074            ..Default::default()
2075        });
2076        assert_eq!(expedition.game.count(), 0);
2077    }
2078
2079    #[test]
2080    fn nearest_visible_target_drives_prompt_and_accepted_collection() {
2081        let mut game = Game::new();
2082        let p = game.crystals[0];
2083        game.crystals[1] = p + vec2(0.8, 0.);
2084        game.position = p + vec2(0.65, 0.);
2085        assert_eq!(game.target(), Some(Interactable::Crystal(1)));
2086        assert_eq!(game.prompt(), Some(Prompt::Use(Interactable::Crystal(1))));
2087        game.interact();
2088        assert!(!game.collected[0]);
2089        assert!(game.collected[1]);
2090        // The count lives in the pickup pop and the HUD's sockets; an accepted
2091        // use leaves no sentence behind.
2092        assert_eq!(game.notice, Notice::None);
2093        let corner = center(5, 8);
2094        game.position = corner + vec2(-1.65, 1.);
2095        game.crystals[0] = corner + vec2(-1., 1.65);
2096        // Nearby floor points separated by the authored wall's corner.
2097        assert!(game.position.distance(game.crystals[0]) < 1.7);
2098        assert!(!game.visible(game.crystals[0]));
2099        assert_ne!(game.target(), Some(Interactable::Crystal(0)));
2100    }
2101
2102    #[test]
2103    fn altar_and_gate_prompts_explain_prerequisites_and_exit() {
2104        let mut game = Game::new();
2105        game.position = at(b'A');
2106        assert!(!game.target_ready(game.target().unwrap()));
2107        assert_eq!(
2108            game.prompt(),
2109            Some(Prompt::Locked(
2110                Interactable::Altar(0),
2111                Blocker::Crystals(0, 3)
2112            ))
2113        );
2114        game.interact();
2115        assert_eq!(game.switches, 0);
2116        assert_eq!(
2117            game.notice,
2118            Notice::Locked(Interactable::Altar(0), Blocker::Crystals(0, 3))
2119        );
2120        game.position = at(b'B');
2121        assert_eq!(
2122            game.prompt(),
2123            Some(Prompt::Locked(Interactable::Altar(1), Blocker::AltarI))
2124        );
2125        game.position = at(b'A');
2126        for i in 0..3 {
2127            game.objective_event(i);
2128        }
2129        assert!(game.target_ready(game.target().unwrap()));
2130        assert_eq!(game.prompt(), Some(Prompt::Use(Interactable::Altar(0))));
2131        game.position = at(b'B');
2132        assert_eq!(
2133            game.prompt(),
2134            Some(Prompt::Locked(Interactable::Altar(1), Blocker::AltarI))
2135        );
2136        game.position = at(b'A');
2137        game.interact();
2138        assert_eq!(game.target(), None);
2139        game.position = at(b'B');
2140        assert_eq!(game.prompt(), Some(Prompt::Use(Interactable::Altar(1))));
2141        game.interact();
2142        assert!(game.open());
2143        game.position = at(b'G') + vec2(0., 1.);
2144        assert_eq!(game.target(), Some(Interactable::Gate));
2145        assert_eq!(game.prompt(), Some(Prompt::Exit));
2146        assert!(
2147            !game.won,
2148            "Opening the gate does not complete the expedition"
2149        );
2150    }
2151
2152    #[test]
2153    fn completion_is_once_and_retry_resets_the_entire_expedition() {
2154        let mut expedition = playing();
2155        for i in 0..5 {
2156            expedition.game.objective_event(i);
2157        }
2158        expedition.game.position = at(b'X');
2159        let progress = expedition.advance(0.1, Input::default);
2160        assert!(progress.won);
2161        assert_eq!(expedition.session.state(), SessionState::Won);
2162        // Catch-up stops on the winning tick, not the end of the render frame.
2163        assert!((expedition.game.elapsed - 1. / 60.).abs() < 0.0001);
2164        let elapsed = expedition.game.elapsed;
2165        let notice_time = expedition.game.notice_time;
2166        expedition.set_paused(true);
2167        assert!(!expedition.advance(30., Input::default).won);
2168        assert_eq!(expedition.game.elapsed, elapsed);
2169        assert_eq!(expedition.game.notice_time, notice_time);
2170        assert_eq!(expedition.session.state(), SessionState::Won);
2171        expedition.restart();
2172        assert_eq!(expedition.session.state(), SessionState::Playing);
2173        assert_eq!(expedition.session.tick(), 0);
2174        assert_eq!(expedition.game.count(), 0);
2175        assert_eq!(expedition.game.switches, 0);
2176        assert_eq!(expedition.game.elapsed, 0.);
2177        assert_eq!(expedition.game.position, at(b'S'));
2178        assert_eq!(expedition.game.velocity, Vec2::ZERO);
2179        assert_eq!(expedition.game.yaw, 0.);
2180        assert!(!expedition.game.open());
2181        assert!(expedition.pilot.path.is_empty());
2182        assert!(expedition.pilot.goal.is_none());
2183    }
2184
2185    #[test]
2186    fn autoplay_completes_through_the_session_with_irregular_frames() {
2187        let mut expedition = Expedition::new(true);
2188        for frame in 0..12000 {
2189            expedition.advance([1. / 144., 1. / 30., 0.07][frame % 3], Input::default);
2190            if expedition.session.state() == SessionState::Won {
2191                break;
2192            }
2193        }
2194        assert_eq!(expedition.session.state(), SessionState::Won);
2195        assert_eq!(expedition.game.count(), 3);
2196        assert_eq!(expedition.game.switches, 2);
2197        assert!(expedition.game.elapsed < 120.);
2198    }
2199
2200    #[test]
2201    fn exploration_accelerates_quickly_and_release_has_a_short_stop() {
2202        let mut game = Game::new();
2203        for _ in 0..20 {
2204            game.step(
2205                Input {
2206                    movement: Vec2::Y,
2207                    ..Default::default()
2208                },
2209                1. / 120.,
2210            );
2211        }
2212        assert!(game.velocity.length() > SPEED * 0.9);
2213        let released = game.position;
2214        for _ in 0..45 {
2215            game.step(Input::default(), 1. / 120.);
2216        }
2217        assert!(game.velocity.length() < 0.01);
2218        assert!(released.distance(game.position) < 0.25);
2219    }
2220
2221    #[test]
2222    fn walls_block_even_large_steps() {
2223        let mut game = Game::new();
2224        game.step(
2225            Input {
2226                movement: vec2(1.0, 0.0),
2227                ..Input::default()
2228            },
2229            10.0,
2230        );
2231        assert!(game.position.x < center(8, 13).x - TILE * 0.5 - RADIUS);
2232        assert!(game.position.x > at(b'S').x);
2233    }
2234    #[test]
2235    fn objective_checkpoint_resumes_the_actual_altar_sequence() {
2236        use ferravex_play::{objective::ObjectiveSnapshot, persistence::SaveData};
2237        let mut game = Game::new();
2238        for p in game.crystals.clone() {
2239            game.position = p;
2240            game.interact();
2241        }
2242        game.position = at(b'A');
2243        game.interact();
2244        let bytes = game.objectives.snapshot().encode(1).unwrap();
2245        let mut restored = Game::new();
2246        restored
2247            .objectives
2248            .restore(ObjectiveSnapshot::decode(&bytes).unwrap().0)
2249            .unwrap();
2250        restored.sync_objectives();
2251        assert_eq!(restored.count(), 3);
2252        assert_eq!(restored.switches, 1);
2253        restored.position = at(b'B');
2254        restored.interact();
2255        assert!(restored.open());
2256        restored.position = at(b'X');
2257        restored.step(Input::default(), 1. / 120.);
2258        assert!(restored.won);
2259    }
2260    #[test]
2261    fn gate_requires_crystals_and_ordered_altars() {
2262        let mut game = Game::new();
2263        game.position = at(b'B');
2264        game.interact();
2265        assert_eq!(game.switches, 0);
2266        game.position = at(b'A');
2267        game.interact();
2268        assert_eq!(game.switches, 0);
2269        for p in game.crystals.clone() {
2270            game.position = p;
2271            game.interact();
2272        }
2273        assert_eq!(game.count(), 3);
2274        game.position = at(b'B');
2275        game.interact();
2276        assert!(!game.open());
2277        game.position = at(b'A');
2278        game.interact();
2279        assert_eq!(game.switches, 1);
2280        game.position = at(b'B');
2281        game.interact();
2282        assert!(game.open());
2283    }
2284    #[test]
2285    fn sealed_gate_blocks_exit_and_interaction_through_walls() {
2286        let mut game = Game::new();
2287        game.position = center(6, 4);
2288        game.step(
2289            Input {
2290                movement: Vec2::Y,
2291                ..Input::default()
2292            },
2293            2.0,
2294        );
2295        assert!(game.position.y > game.gate.max.y + RADIUS);
2296        assert!(!game.won);
2297        game.position = center(2, 7);
2298        assert!(!game.visible(game.crystals[0]));
2299    }
2300    #[test]
2301    fn autoplay_solves_with_player_inputs_and_restart_clears_state() {
2302        let mut game = Game::new();
2303        let mut pilot = Pilot::default();
2304        for _ in 0..12_000 {
2305            game.step(pilot.input(&game), 1.0 / 60.0);
2306            if game.won {
2307                break;
2308            }
2309        }
2310        assert!(
2311            game.won,
2312            "position={:?}, crystals={}, switches={}",
2313            game.position,
2314            game.count(),
2315            game.switches
2316        );
2317        assert!(game.elapsed < 120.0);
2318        game = Game::new();
2319        assert_eq!(game.count(), 0);
2320        assert_eq!(game.switches, 0);
2321        assert!(!game.won);
2322        assert_eq!(game.position, at(b'S'));
2323    }
2324}