Skip to main content

clairlune_scene/
activity.rs

1//! Activities: what the character is doing (PLAN.md section 4.7).
2//!
3//! One TOML file per activity in `crates/scene/activities/`, embedded at compile
4//! time. The engine never hardcodes a specific activity: adding a file (and its
5//! sprites) is how content grows. Maps are `BTreeMap` so iteration order, and
6//! therefore every seeded pick, is deterministic.
7
8use crate::archetype::{ArchetypeInfo, SURFACES, TERRAINS, WEATHERS};
9use crate::hash::StableHasher;
10use crate::recipe::TimeOfDay;
11use serde::{Deserialize, Serialize};
12use std::collections::BTreeMap;
13use std::sync::OnceLock;
14
15/// Prop ids the engine can draw.
16pub const PROPS: [&str; 25] = [
17    "campfire",
18    "log_seat",
19    "telescope",
20    "lantern",
21    "spellbook",
22    "camp_stove",
23    "coffee_mug",
24    "fallen_hat",
25    "book_closed",
26    "guitar_rest",
27    "bucket",
28    "kite_rest",
29    "stone_pile",
30    "easel",
31    "snowman",
32    "basket",
33    "picnic_basket",
34    "chess_table",
35    "practice_wall",
36    "skis_rest",
37    "flower_pots",
38    "music_stand",
39    "camera_tripod",
40    "sandcastle",
41    "yoga_mat",
42];
43/// Effect ids the engine can draw.
44pub const EFFECTS: [&str; 1] = ["embers"];
45/// Particle presets an `[[effects]]` entry can attach to an anchor.
46pub const PARTICLE_PRESETS: [&str; 6] = [
47    "sparkles",
48    "steam",
49    "notes",
50    "snow_spray",
51    "bubbles",
52    "drops",
53];
54/// Tether presets: a line from an anchor to a moving end (a float on the
55/// water, a kite in the sky).
56pub const TETHER_PRESETS: [&str; 2] = ["fishing_line", "kite_string"];
57/// Projectile presets: something thrown on its own arc, timed from the start
58/// of the effect's state.
59pub const PROJECTILE_PRESETS: [&str; 3] = ["skipping_stone", "snowball", "tennis_ball"];
60/// Which way the character faces, when it matters: `water` (the open water,
61/// on the shore) or `open` (the middle of the screen, where the sky is
62/// widest).
63pub const FACINGS: [&str; 2] = ["water", "open"];
64/// Anchor names the art exports (docs/clawd-style.md).
65pub const ANCHORS: [&str; 6] = ["origin", "feet", "head", "hand_l", "hand_r", "item_tip"];
66/// Generic prop attachment points.
67pub const ATTACH: [&str; 4] = ["path", "left_of_clawd", "right_of_clawd", "either_side"];
68
69/// Embedded activity files, sorted by file name.
70const SOURCES: [(&str, &str); 38] = [
71    (
72        "balloon_journey.toml",
73        include_str!("../activities/balloon_journey.toml"),
74    ),
75    (
76        "balloon_ride.toml",
77        include_str!("../activities/balloon_ride.toml"),
78    ),
79    (
80        "birdwatching.toml",
81        include_str!("../activities/birdwatching.toml"),
82    ),
83    (
84        "broom_flight.toml",
85        include_str!("../activities/broom_flight.toml"),
86    ),
87    (
88        "broom_journey.toml",
89        include_str!("../activities/broom_journey.toml"),
90    ),
91    ("bubbles.toml", include_str!("../activities/bubbles.toml")),
92    (
93        "catch_snowflakes.toml",
94        include_str!("../activities/catch_snowflakes.toml"),
95    ),
96    ("chess.toml", include_str!("../activities/chess.toml")),
97    ("dance.toml", include_str!("../activities/dance.toml")),
98    (
99        "desert_trek.toml",
100        include_str!("../activities/desert_trek.toml"),
101    ),
102    ("fishing.toml", include_str!("../activities/fishing.toml")),
103    ("fly_kite.toml", include_str!("../activities/fly_kite.toml")),
104    (
105        "forest_walk.toml",
106        include_str!("../activities/forest_walk.toml"),
107    ),
108    (
109        "gardening.toml",
110        include_str!("../activities/gardening.toml"),
111    ),
112    (
113        "hike_ridge.toml",
114        include_str!("../activities/hike_ridge.toml"),
115    ),
116    (
117        "hot_cocoa.toml",
118        include_str!("../activities/hot_cocoa.toml"),
119    ),
120    (
121        "make_coffee.toml",
122        include_str!("../activities/make_coffee.toml"),
123    ),
124    ("meditate.toml", include_str!("../activities/meditate.toml")),
125    (
126        "paint_easel.toml",
127        include_str!("../activities/paint_easel.toml"),
128    ),
129    (
130        "photography.toml",
131        include_str!("../activities/photography.toml"),
132    ),
133    ("picnic.toml", include_str!("../activities/picnic.toml")),
134    (
135        "play_flute.toml",
136        include_str!("../activities/play_flute.toml"),
137    ),
138    (
139        "play_guitar.toml",
140        include_str!("../activities/play_guitar.toml"),
141    ),
142    (
143        "read_lantern.toml",
144        include_str!("../activities/read_lantern.toml"),
145    ),
146    ("rowing.toml", include_str!("../activities/rowing.toml")),
147    (
148        "sandcastle.toml",
149        include_str!("../activities/sandcastle.toml"),
150    ),
151    ("ski_tour.toml", include_str!("../activities/ski_tour.toml")),
152    ("skiing.toml", include_str!("../activities/skiing.toml")),
153    (
154        "skip_stones.toml",
155        include_str!("../activities/skip_stones.toml"),
156    ),
157    ("sledding.toml", include_str!("../activities/sledding.toml")),
158    (
159        "snowballs.toml",
160        include_str!("../activities/snowballs.toml"),
161    ),
162    ("stargaze.toml", include_str!("../activities/stargaze.toml")),
163    ("stroll.toml", include_str!("../activities/stroll.toml")),
164    ("sweep.toml", include_str!("../activities/sweep.toml")),
165    ("tennis.toml", include_str!("../activities/tennis.toml")),
166    (
167        "warm_hands.toml",
168        include_str!("../activities/warm_hands.toml"),
169    ),
170    (
171        "wizard_magic.toml",
172        include_str!("../activities/wizard_magic.toml"),
173    ),
174    ("yoga.toml", include_str!("../activities/yoga.toml")),
175];
176
177#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
178#[serde(deny_unknown_fields)]
179pub struct Activity {
180    pub id: String,
181    #[serde(default = "one")]
182    pub weight: f64,
183    pub requires: Requires,
184    pub motion: Motion,
185    /// Marks left in the ground along the character's way: `ski_tracks`.
186    #[serde(default)]
187    pub trail: Option<String>,
188    #[serde(default)]
189    pub props: BTreeMap<String, PropDef>,
190    pub animation: AnimationDef,
191    #[serde(default)]
192    pub effects_by_state: BTreeMap<String, Vec<String>>,
193    pub gif: Option<GifDef>,
194    pub unattended: Unattended,
195    #[serde(default)]
196    pub character: CharacterDef,
197    /// Effects attached to the character (docs/activity-system.md section 3).
198    #[serde(default)]
199    pub effects: Vec<EffectDef>,
200}
201
202/// Per-activity character settings.
203#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Default)]
204#[serde(deny_unknown_fields)]
205pub struct CharacterDef {
206    /// Extra cleared space above the character's box, in sprite pixels
207    /// (a wizard hat, a raised wand).
208    #[serde(default)]
209    pub headroom: u32,
210}
211
212/// An effect attached to an anchor of the character's current frame.
213#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
214#[serde(deny_unknown_fields)]
215pub struct EffectDef {
216    /// `particles`, `tether` or `projectile`.
217    #[serde(rename = "type")]
218    pub kind: String,
219    /// One of [`PARTICLE_PRESETS`], [`TETHER_PRESETS`] or
220    /// [`PROJECTILE_PRESETS`], by type.
221    pub preset: String,
222    /// Anchor name, e.g. `item_tip`.
223    pub at: String,
224    /// States in which the effect runs; empty means all.
225    #[serde(default)]
226    pub states: Vec<String>,
227}
228
229impl EffectDef {
230    pub fn active_in(&self, state: &str) -> bool {
231        self.states.is_empty() || self.states.iter().any(|s| s == state)
232    }
233}
234
235fn one() -> f64 {
236    1.0
237}
238
239/// Capability requirements. An empty list means "no constraint".
240#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
241#[serde(deny_unknown_fields)]
242pub struct Requires {
243    #[serde(default)]
244    pub terrain: Vec<String>,
245    #[serde(default)]
246    pub surface: Vec<String>,
247    pub time_of_day: Vec<TimeOfDay>,
248    #[serde(default)]
249    pub weather: Vec<String>,
250    /// Needs open sky overhead (stargazing): rules out caves and interiors.
251    #[serde(default)]
252    pub sky: bool,
253}
254
255#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
256#[serde(rename_all = "snake_case")]
257pub enum MotionKind {
258    Stationary,
259    Pace,
260    Path,
261    Bob,
262    Fly,
263    /// The camera travels: the landscape scrolls past in layers while the
264    /// character walks on the nearest (docs/scrolling-scenes.md).
265    Journey,
266}
267
268#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
269#[serde(deny_unknown_fields)]
270pub struct Motion {
271    #[serde(rename = "type")]
272    pub kind: MotionKind,
273    pub path: Option<String>,
274    pub speed_cells_per_s: Option<[f64; 2]>,
275    pub at_path_end: Option<String>,
276    /// One of [`FACINGS`].
277    #[serde(default)]
278    pub face: Option<String>,
279    /// Journeys before 0.12: the loop length range in seconds. Unused now
280    /// (the pace, `speed_cells_per_s`, sets the loop); still read.
281    #[serde(default)]
282    pub loop_s: Option<[f64; 2]>,
283    /// Journeys: where the character walks, as a fraction of the width.
284    #[serde(default)]
285    pub screen_x: Option<f64>,
286    /// Journeys: fly instead of walking, the feet this far down the screen
287    /// (a fraction of the height), the land going by below.
288    #[serde(default)]
289    pub altitude: Option<f64>,
290}
291
292#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
293#[serde(deny_unknown_fields)]
294pub struct PropDef {
295    pub attach: String,
296    #[serde(default)]
297    pub effects: Vec<String>,
298    /// Extra space before the prop, in sprite pixels (a practice wall
299    /// stands back from the player).
300    #[serde(default)]
301    pub gap: u32,
302}
303
304#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
305#[serde(deny_unknown_fields)]
306pub struct AnimationDef {
307    pub start: String,
308    pub states: BTreeMap<String, StateDef>,
309}
310
311#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
312#[serde(deny_unknown_fields)]
313pub struct StateDef {
314    #[serde(default, rename = "loop")]
315    pub looping: bool,
316    pub dwell_s: Option<[f64; 2]>,
317    #[serde(default)]
318    pub next: BTreeMap<String, f64>,
319}
320
321#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
322#[serde(deny_unknown_fields)]
323pub struct GifDef {
324    pub loop_script: Vec<String>,
325}
326
327#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
328#[serde(deny_unknown_fields)]
329pub struct Unattended {
330    pub props: Vec<String>,
331}
332
333/// Integer weight for seeded picks (weights in files are decimals).
334pub fn int_weight(w: f64) -> u32 {
335    (w * 1000.0).round().max(0.0) as u32
336}
337
338/// The largest weight a file may give (picks multiply weights).
339pub const MAX_WEIGHT: f64 = 1000.0;
340
341/// A weight from a file that picks can use: at least 0.001 (it rounds to a
342/// whole thousandth) and at most `MAX_WEIGHT`.
343fn usable_weight(w: f64) -> bool {
344    w <= MAX_WEIGHT && int_weight(w) > 0
345}
346
347fn overlaps(need: &[String], offer: &[&str]) -> bool {
348    need.is_empty() || need.iter().any(|n| offer.contains(&n.as_str()))
349}
350
351impl Activity {
352    /// Whether this activity can take place in an archetype, given enabled weather.
353    pub fn fits(&self, a: &ArchetypeInfo, enabled_weather: &[String]) -> bool {
354        overlaps(&self.requires.terrain, a.terrain)
355            && overlaps(&self.requires.surface, a.surface)
356            && (!self.requires.sky || a.sky)
357            && !self.weathers_in(a, enabled_weather).is_empty()
358    }
359
360    /// Weather that the activity, the archetype and the user all allow.
361    pub fn weathers_in(&self, a: &ArchetypeInfo, enabled: &[String]) -> Vec<&'static str> {
362        a.weather
363            .iter()
364            .copied()
365            .filter(|w| {
366                self.requires.weather.is_empty() || self.requires.weather.iter().any(|r| r == w)
367            })
368            .filter(|w| enabled.iter().any(|e| e == w))
369            .collect()
370    }
371
372    /// Allowed times of day for one theme family, in canonical order.
373    pub fn times_in(&self, family: &[TimeOfDay]) -> Vec<TimeOfDay> {
374        family
375            .iter()
376            .copied()
377            .filter(|t| self.requires.time_of_day.contains(t))
378            .collect()
379    }
380
381    /// The state that follows `state` (when no `next`, back to `start`).
382    pub fn successors(&self, state: &str) -> Vec<(&str, u32)> {
383        match self.animation.states.get(state) {
384            Some(s) if !s.next.is_empty() => s
385                .next
386                .iter()
387                .map(|(k, w)| (k.as_str(), int_weight(*w)))
388                .collect(),
389            _ => vec![(self.animation.start.as_str(), 1)],
390        }
391    }
392
393    /// Whether the state machine can run: every state that goes on has a
394    /// way to go. Looser than [`validate`](Self::validate), which also holds
395    /// art and names to today's rules, for activities saved in older scenes.
396    pub fn playable(&self) -> bool {
397        self.animation.states.values().all(|s| {
398            s.next.is_empty()
399                || s.next
400                    .values()
401                    .map(|w| u64::from(int_weight(*w)))
402                    .sum::<u64>()
403                    > 0
404        })
405    }
406
407    /// Every rule from PLAN.md section 4.7 that can be checked without sprites.
408    pub fn validate(&self) -> Vec<String> {
409        let mut errs = Vec::new();
410        let id = &self.id;
411        let mut err = |m: String| errs.push(format!("{id}: {m}"));
412        if !usable_weight(self.weight) {
413            err(format!("weight must be between 0.001 and {MAX_WEIGHT}"));
414        }
415        for t in &self.requires.terrain {
416            if !TERRAINS.contains(&t.as_str()) {
417                err(format!("unknown terrain `{t}`"));
418            }
419        }
420        for s in &self.requires.surface {
421            if !SURFACES.contains(&s.as_str()) {
422                err(format!("unknown surface `{s}`"));
423            }
424        }
425        for w in &self.requires.weather {
426            if !WEATHERS.contains(&w.as_str()) {
427                err(format!("unknown weather `{w}`"));
428            }
429        }
430        if self.requires.time_of_day.is_empty() {
431            err("requires.time_of_day is empty".into());
432        }
433        let states = &self.animation.states;
434        if !states.contains_key(&self.animation.start) {
435            err(format!(
436                "start state `{}` is not defined",
437                self.animation.start
438            ));
439        }
440        for (name, s) in states {
441            for (to, w) in &s.next {
442                if !states.contains_key(to) {
443                    err(format!("state `{name}` goes to undefined state `{to}`"));
444                }
445                if !usable_weight(*w) {
446                    err(format!(
447                        "state `{name}`: weight for `{to}` must be between 0.001 and {MAX_WEIGHT}"
448                    ));
449                }
450            }
451            match (s.looping, s.dwell_s) {
452                (true, None) => err(format!("looping state `{name}` needs dwell_s")),
453                (true, Some([lo, hi])) if !(lo >= 0.2 && hi >= lo) => err(format!(
454                    "state `{name}`: dwell_s must be [lo, hi] with 0.2 <= lo <= hi"
455                )),
456                (false, Some(_)) => err(format!(
457                    "state `{name}`: dwell_s only applies to looping states"
458                )),
459                _ => {}
460            }
461        }
462        for (state, effects) in &self.effects_by_state {
463            if !states.contains_key(state) {
464                err(format!("effects_by_state names undefined state `{state}`"));
465            }
466            for e in effects {
467                if !EFFECTS.contains(&e.as_str()) {
468                    err(format!("unknown effect `{e}`"));
469                }
470            }
471        }
472        for (prop, def) in &self.props {
473            if !PROPS.contains(&prop.as_str()) {
474                err(format!("unknown prop `{prop}`"));
475            }
476            if !ATTACH.contains(&def.attach.as_str()) {
477                err(format!("prop `{prop}`: unknown attach `{}`", def.attach));
478            }
479            for e in &def.effects {
480                if !EFFECTS.contains(&e.as_str()) {
481                    err(format!("prop `{prop}`: unknown effect `{e}`"));
482                }
483            }
484        }
485        if let Some(t) = &self.trail
486            && t != "ski_tracks"
487        {
488            err(format!("unknown trail `{t}`"));
489        }
490        if self.motion.kind == MotionKind::Bob && self.requires.terrain != ["shore"] {
491            err("bob motion floats on the shore's water: requires.terrain = [\"shore\"]".into());
492        }
493        if let Some(face) = &self.motion.face {
494            if !FACINGS.contains(&face.as_str()) {
495                err(format!("unknown facing `{face}`"));
496            }
497            if face == "water" && self.requires.terrain != ["shore"] {
498                err("facing the water needs requires.terrain = [\"shore\"]".into());
499            }
500        }
501        for e in &self.effects {
502            match e.kind.as_str() {
503                "particles" if !PARTICLE_PRESETS.contains(&e.preset.as_str()) => {
504                    err(format!("unknown particle preset `{}`", e.preset));
505                }
506                "tether" if !TETHER_PRESETS.contains(&e.preset.as_str()) => {
507                    err(format!("unknown tether preset `{}`", e.preset));
508                }
509                "projectile" if !PROJECTILE_PRESETS.contains(&e.preset.as_str()) => {
510                    err(format!("unknown projectile preset `{}`", e.preset));
511                }
512                "particles" | "tether" | "projectile" => {}
513                other => err(format!(
514                    "effect type `{other}` is not implemented (`particles`, `tether`, `projectile`)"
515                )),
516            }
517            if e.preset == "tennis_ball" && !self.props.contains_key("practice_wall") {
518                err("a tennis ball needs a practice wall (props.practice_wall)".into());
519            }
520            if e.preset == "snowball" && !self.props.contains_key("snowman") {
521                err("a snowball needs a snowman to throw at (props.snowman)".into());
522            }
523            if ["fishing_line", "skipping_stone"].contains(&e.preset.as_str())
524                && self.requires.terrain != ["shore"]
525            {
526                err(format!(
527                    "`{}` needs requires.terrain = [\"shore\"]",
528                    e.preset
529                ));
530            }
531            if !ANCHORS.contains(&e.at.as_str()) {
532                err(format!("effect anchor `{}` is not a known anchor", e.at));
533            }
534            for s in &e.states {
535                if !states.contains_key(s) {
536                    err(format!("effect names undefined state `{s}`"));
537                }
538            }
539        }
540        let journey = self.motion.kind == MotionKind::Journey;
541        if journey && !self.props.is_empty() {
542            err("a journey has no props: the ground moves under them".into());
543        }
544        // A journey without the character is the landscape going by.
545        if self.unattended.props.is_empty() && !journey {
546            err("unattended.props is empty: Buddy-off scenes need a focal object".into());
547        }
548        for p in &self.unattended.props {
549            if !PROPS.contains(&p.as_str()) && !EFFECTS.contains(&p.as_str()) {
550                err(format!("unattended: unknown prop or effect `{p}`"));
551            }
552        }
553        if self.motion.altitude.is_some() && self.motion.kind != MotionKind::Journey {
554            err("altitude is for journeys".into());
555        }
556        match self.motion.kind {
557            MotionKind::Stationary => {}
558            MotionKind::Pace | MotionKind::Fly | MotionKind::Bob => {
559                match self.motion.speed_cells_per_s {
560                    Some([lo, hi]) if lo > 0.0 && hi >= lo => {}
561                    _ => err(format!(
562                        "{} motion needs speed_cells_per_s = [lo, hi] with 0 < lo <= hi",
563                        format!("{:?}", self.motion.kind).to_lowercase()
564                    )),
565                }
566            }
567            MotionKind::Journey => {
568                match self.motion.speed_cells_per_s {
569                    Some([lo, hi]) if lo >= 1.0 && hi >= lo && hi <= 20.0 => {}
570                    _ => err(
571                        "journey motion needs speed_cells_per_s = [lo, hi] within 1..=20 (the ground's pace)"
572                            .into(),
573                    ),
574                }
575                if let Some(x) = self.motion.screen_x
576                    && !(0.15..=0.85).contains(&x)
577                {
578                    err("journey screen_x must be within 0.15..=0.85".into());
579                }
580                if let Some(y) = self.motion.altitude
581                    && !(0.2..=0.6).contains(&y)
582                {
583                    err("journey altitude must be within 0.2..=0.6".into());
584                }
585            }
586            MotionKind::Path => err(format!(
587                "motion `{:?}` is not implemented yet (milestone M4)",
588                self.motion.kind
589            )),
590        }
591        if let Some(gif) = &self.gif {
592            let script = &gif.loop_script;
593            if script.first() != Some(&self.animation.start) {
594                err("gif.loop_script must start with the start state".into());
595            }
596            for pair in script.windows(2).chain(std::iter::once(
597                [
598                    script.last().cloned().unwrap_or_default(),
599                    script.first().cloned().unwrap_or_default(),
600                ]
601                .as_slice(),
602            )) {
603                let (from, to) = (&pair[0], &pair[1]);
604                if !states.contains_key(from) {
605                    err(format!("gif.loop_script names undefined state `{from}`"));
606                } else if !self.successors(from).iter().any(|(s, _)| s == to) {
607                    err(format!("gif.loop_script: `{from}` can't go to `{to}`"));
608                }
609            }
610        }
611        errs
612    }
613}
614
615/// The activity catalog.
616#[derive(Clone, Debug, PartialEq)]
617pub struct Catalog {
618    pub activities: Vec<Activity>,
619    /// Hash of the source files; part of the content context.
620    pub data_hash: u64,
621}
622
623impl Catalog {
624    /// Parses and validates the embedded activity files. Panics on invalid data,
625    /// which CI catches through the tests.
626    pub fn builtin() -> Self {
627        Self::from_sources(&SOURCES)
628            .unwrap_or_else(|e| panic!("invalid built-in activities:\n{}", e.join("\n")))
629    }
630
631    /// Parses `(file name, toml)` pairs. Returns every error at once.
632    pub fn from_sources(sources: &[(&str, &str)]) -> Result<Self, Vec<String>> {
633        let mut errors = Vec::new();
634        let mut activities = Vec::new();
635        let mut h = StableHasher::new();
636        for (name, text) in sources {
637            h.write_str(name);
638            write_text(&mut h, text);
639            match toml::from_str::<Activity>(text) {
640                Ok(a) => {
641                    if format!("{}.toml", a.id) != *name {
642                        errors.push(format!("{name}: id `{}` must match the file name", a.id));
643                    }
644                    errors.extend(a.validate());
645                    activities.push(a);
646                }
647                Err(e) => errors.push(format!("{name}: {e}")),
648            }
649        }
650        activities.sort_by(|a, b| a.id.cmp(&b.id));
651        if errors.is_empty() {
652            Ok(Self {
653                activities,
654                data_hash: h.finish(),
655            })
656        } else {
657            Err(errors)
658        }
659    }
660
661    pub fn get(&self, id: &str) -> Option<&Activity> {
662        self.activities.iter().find(|a| a.id == id)
663    }
664}
665
666/// Hashes text with CRLF normalised to LF, so a Windows checkout with
667/// `core.autocrlf` gives the same hash (and recipes) as everywhere else.
668fn write_text(h: &mut StableHasher, text: &str) {
669    h.write_str(&text.replace("\r\n", "\n"));
670}
671
672/// The built-in catalog, parsed once.
673pub fn builtin_catalog() -> &'static Catalog {
674    static CATALOG: OnceLock<Catalog> = OnceLock::new();
675    CATALOG.get_or_init(Catalog::builtin)
676}
677
678/// Hash of the built-in activity files without parsing them.
679pub fn builtin_data_hash() -> u64 {
680    let mut h = StableHasher::new();
681    for (name, text) in SOURCES {
682        h.write_str(name);
683        write_text(&mut h, text);
684    }
685    h.finish()
686}
687
688#[cfg(test)]
689mod tests {
690    use super::*;
691
692    #[test]
693    fn builtin_catalog_is_valid() {
694        let c = Catalog::builtin();
695        assert_eq!(c.activities.len(), SOURCES.len());
696        assert_eq!(c.data_hash, builtin_data_hash());
697    }
698
699    #[test]
700    fn validation_reports_bad_files() {
701        let bad = r#"
702            id = "bad"
703            [requires]
704            terrain = ["lava"]
705            time_of_day = []
706            [motion]
707            type = "pace"
708            [props.anvil]
709            attach = "on_head"
710            [animation]
711            start = "idle"
712            [animation.states.idle]
713            loop = true
714            next = { nowhere = 1.0, idle = 0.0001 }
715            [gif]
716            loop_script = ["sit"]
717            [unattended]
718            props = []
719        "#;
720        let errs = Catalog::from_sources(&[("bad.toml", bad)]).unwrap_err();
721        let all = errs.join("\n");
722        for needle in [
723            "unknown terrain `lava`",
724            "time_of_day is empty",
725            "undefined state `nowhere`",
726            "needs dwell_s",
727            "unknown prop `anvil`",
728            "unknown attach `on_head`",
729            "unattended.props is empty",
730            "pace motion needs speed",
731            "must start with the start state",
732            "weight for `idle` must be between 0.001",
733        ] {
734            assert!(all.contains(needle), "missing `{needle}` in:\n{all}");
735        }
736    }
737
738    #[test]
739    fn sources_are_sorted_by_file_name_like_a_folder_listing() {
740        // The data hash follows this order, and tools that read the folder
741        // (the preview window) sort by name, so both must agree.
742        let names: Vec<&str> = SOURCES.iter().map(|(n, _)| *n).collect();
743        let mut sorted = names.clone();
744        sorted.sort_unstable();
745        assert_eq!(names, sorted);
746    }
747
748    #[test]
749    fn data_hash_ignores_line_endings() {
750        let lf = Catalog::builtin();
751        let crlf: Vec<(String, String)> = SOURCES
752            .iter()
753            .map(|(n, t)| (n.to_string(), t.replace('\n', "\r\n")))
754            .collect();
755        let refs: Vec<(&str, &str)> = crlf.iter().map(|(n, t)| (n.as_str(), t.as_str())).collect();
756        assert_eq!(
757            Catalog::from_sources(&refs).unwrap().data_hash,
758            lf.data_hash
759        );
760    }
761
762    #[test]
763    fn unknown_fields_are_rejected() {
764        let text = "id = \"x\"\ncolour = \"red\"\n";
765        assert!(Catalog::from_sources(&[("x.toml", text)]).is_err());
766    }
767}