1use crate::archetype::{ArchetypeInfo, SURFACES, TERRAINS, WEATHERS};
9use crate::hash::StableHasher;
10use crate::recipe::TimeOfDay;
11use serde::Deserialize;
12use std::collections::BTreeMap;
13use std::sync::OnceLock;
14
15pub const PROPS: [&str; 10] = [
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];
28pub const EFFECTS: [&str; 1] = ["embers"];
30pub const PARTICLE_PRESETS: [&str; 3] = ["sparkles", "steam", "notes"];
32pub const ANCHORS: [&str; 6] = ["origin", "feet", "head", "hand_l", "hand_r", "item_tip"];
34pub const ATTACH: [&str; 4] = ["path", "left_of_clawd", "right_of_clawd", "either_side"];
36
37const SOURCES: [(&str, &str); 7] = [
39 (
40 "make_coffee.toml",
41 include_str!("../activities/make_coffee.toml"),
42 ),
43 (
44 "play_guitar.toml",
45 include_str!("../activities/play_guitar.toml"),
46 ),
47 (
48 "read_lantern.toml",
49 include_str!("../activities/read_lantern.toml"),
50 ),
51 ("stargaze.toml", include_str!("../activities/stargaze.toml")),
52 ("stroll.toml", include_str!("../activities/stroll.toml")),
53 (
54 "warm_hands.toml",
55 include_str!("../activities/warm_hands.toml"),
56 ),
57 (
58 "wizard_magic.toml",
59 include_str!("../activities/wizard_magic.toml"),
60 ),
61];
62
63#[derive(Deserialize, Clone, Debug, PartialEq)]
64#[serde(deny_unknown_fields)]
65pub struct Activity {
66 pub id: String,
67 #[serde(default = "one")]
68 pub weight: f64,
69 pub requires: Requires,
70 pub motion: Motion,
71 #[serde(default)]
72 pub props: BTreeMap<String, PropDef>,
73 pub animation: AnimationDef,
74 #[serde(default)]
75 pub effects_by_state: BTreeMap<String, Vec<String>>,
76 pub gif: Option<GifDef>,
77 pub unattended: Unattended,
78 #[serde(default)]
79 pub character: CharacterDef,
80 #[serde(default)]
82 pub effects: Vec<EffectDef>,
83}
84
85#[derive(Deserialize, Clone, Debug, PartialEq, Default)]
87#[serde(deny_unknown_fields)]
88pub struct CharacterDef {
89 #[serde(default)]
92 pub headroom: u32,
93}
94
95#[derive(Deserialize, Clone, Debug, PartialEq)]
97#[serde(deny_unknown_fields)]
98pub struct EffectDef {
99 #[serde(rename = "type")]
101 pub kind: String,
102 pub preset: String,
104 pub at: String,
106 #[serde(default)]
108 pub states: Vec<String>,
109}
110
111impl EffectDef {
112 pub fn active_in(&self, state: &str) -> bool {
113 self.states.is_empty() || self.states.iter().any(|s| s == state)
114 }
115}
116
117fn one() -> f64 {
118 1.0
119}
120
121#[derive(Deserialize, Clone, Debug, PartialEq)]
123#[serde(deny_unknown_fields)]
124pub struct Requires {
125 #[serde(default)]
126 pub terrain: Vec<String>,
127 #[serde(default)]
128 pub surface: Vec<String>,
129 pub time_of_day: Vec<TimeOfDay>,
130 #[serde(default)]
131 pub weather: Vec<String>,
132 #[serde(default)]
134 pub sky: bool,
135}
136
137#[derive(Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
138#[serde(rename_all = "snake_case")]
139pub enum MotionKind {
140 Stationary,
141 Pace,
142 Path,
143 Bob,
144 Fly,
145}
146
147#[derive(Deserialize, Clone, Debug, PartialEq)]
148#[serde(deny_unknown_fields)]
149pub struct Motion {
150 #[serde(rename = "type")]
151 pub kind: MotionKind,
152 pub path: Option<String>,
153 pub speed_cells_per_s: Option<[f64; 2]>,
154 pub at_path_end: Option<String>,
155}
156
157#[derive(Deserialize, Clone, Debug, PartialEq)]
158#[serde(deny_unknown_fields)]
159pub struct PropDef {
160 pub attach: String,
161 #[serde(default)]
162 pub effects: Vec<String>,
163}
164
165#[derive(Deserialize, Clone, Debug, PartialEq)]
166#[serde(deny_unknown_fields)]
167pub struct AnimationDef {
168 pub start: String,
169 pub states: BTreeMap<String, StateDef>,
170}
171
172#[derive(Deserialize, Clone, Debug, PartialEq)]
173#[serde(deny_unknown_fields)]
174pub struct StateDef {
175 #[serde(default, rename = "loop")]
176 pub looping: bool,
177 pub dwell_s: Option<[f64; 2]>,
178 #[serde(default)]
179 pub next: BTreeMap<String, f64>,
180}
181
182#[derive(Deserialize, Clone, Debug, PartialEq)]
183#[serde(deny_unknown_fields)]
184pub struct GifDef {
185 pub loop_script: Vec<String>,
186}
187
188#[derive(Deserialize, Clone, Debug, PartialEq)]
189#[serde(deny_unknown_fields)]
190pub struct Unattended {
191 pub props: Vec<String>,
192}
193
194pub fn int_weight(w: f64) -> u32 {
196 (w * 1000.0).round().max(0.0) as u32
197}
198
199fn overlaps(need: &[String], offer: &[&str]) -> bool {
200 need.is_empty() || need.iter().any(|n| offer.contains(&n.as_str()))
201}
202
203impl Activity {
204 pub fn fits(&self, a: &ArchetypeInfo, enabled_weather: &[String]) -> bool {
206 overlaps(&self.requires.terrain, a.terrain)
207 && overlaps(&self.requires.surface, a.surface)
208 && (!self.requires.sky || a.sky)
209 && !self.weathers_in(a, enabled_weather).is_empty()
210 }
211
212 pub fn weathers_in(&self, a: &ArchetypeInfo, enabled: &[String]) -> Vec<&'static str> {
214 a.weather
215 .iter()
216 .copied()
217 .filter(|w| {
218 self.requires.weather.is_empty() || self.requires.weather.iter().any(|r| r == w)
219 })
220 .filter(|w| enabled.iter().any(|e| e == w))
221 .collect()
222 }
223
224 pub fn times_in(&self, family: &[TimeOfDay]) -> Vec<TimeOfDay> {
226 family
227 .iter()
228 .copied()
229 .filter(|t| self.requires.time_of_day.contains(t))
230 .collect()
231 }
232
233 pub fn successors(&self, state: &str) -> Vec<(&str, u32)> {
235 match self.animation.states.get(state) {
236 Some(s) if !s.next.is_empty() => s
237 .next
238 .iter()
239 .map(|(k, w)| (k.as_str(), int_weight(*w)))
240 .collect(),
241 _ => vec![(self.animation.start.as_str(), 1)],
242 }
243 }
244
245 pub fn validate(&self) -> Vec<String> {
247 let mut errs = Vec::new();
248 let id = &self.id;
249 let mut err = |m: String| errs.push(format!("{id}: {m}"));
250 if self.weight.is_nan() || self.weight <= 0.0 {
251 err("weight must be positive".into());
252 }
253 for t in &self.requires.terrain {
254 if !TERRAINS.contains(&t.as_str()) {
255 err(format!("unknown terrain `{t}`"));
256 }
257 }
258 for s in &self.requires.surface {
259 if !SURFACES.contains(&s.as_str()) {
260 err(format!("unknown surface `{s}`"));
261 }
262 }
263 for w in &self.requires.weather {
264 if !WEATHERS.contains(&w.as_str()) {
265 err(format!("unknown weather `{w}`"));
266 }
267 }
268 if self.requires.time_of_day.is_empty() {
269 err("requires.time_of_day is empty".into());
270 }
271 let states = &self.animation.states;
272 if !states.contains_key(&self.animation.start) {
273 err(format!(
274 "start state `{}` is not defined",
275 self.animation.start
276 ));
277 }
278 for (name, s) in states {
279 for (to, w) in &s.next {
280 if !states.contains_key(to) {
281 err(format!("state `{name}` goes to undefined state `{to}`"));
282 }
283 if w.is_nan() || *w <= 0.0 {
284 err(format!(
285 "state `{name}`: weight for `{to}` must be positive"
286 ));
287 }
288 }
289 match (s.looping, s.dwell_s) {
290 (true, None) => err(format!("looping state `{name}` needs dwell_s")),
291 (true, Some([lo, hi])) if !(lo >= 0.2 && hi >= lo) => err(format!(
292 "state `{name}`: dwell_s must be [lo, hi] with 0.2 <= lo <= hi"
293 )),
294 (false, Some(_)) => err(format!(
295 "state `{name}`: dwell_s only applies to looping states"
296 )),
297 _ => {}
298 }
299 }
300 for (state, effects) in &self.effects_by_state {
301 if !states.contains_key(state) {
302 err(format!("effects_by_state names undefined state `{state}`"));
303 }
304 for e in effects {
305 if !EFFECTS.contains(&e.as_str()) {
306 err(format!("unknown effect `{e}`"));
307 }
308 }
309 }
310 for (prop, def) in &self.props {
311 if !PROPS.contains(&prop.as_str()) {
312 err(format!("unknown prop `{prop}`"));
313 }
314 if !ATTACH.contains(&def.attach.as_str()) {
315 err(format!("prop `{prop}`: unknown attach `{}`", def.attach));
316 }
317 for e in &def.effects {
318 if !EFFECTS.contains(&e.as_str()) {
319 err(format!("prop `{prop}`: unknown effect `{e}`"));
320 }
321 }
322 }
323 for e in &self.effects {
324 if e.kind != "particles" {
325 err(format!(
326 "effect type `{}` is not implemented (only `particles`)",
327 e.kind
328 ));
329 }
330 if !PARTICLE_PRESETS.contains(&e.preset.as_str()) {
331 err(format!("unknown particle preset `{}`", e.preset));
332 }
333 if !ANCHORS.contains(&e.at.as_str()) {
334 err(format!("effect anchor `{}` is not a known anchor", e.at));
335 }
336 for s in &e.states {
337 if !states.contains_key(s) {
338 err(format!("effect names undefined state `{s}`"));
339 }
340 }
341 }
342 if self.unattended.props.is_empty() {
343 err("unattended.props is empty: Buddy-off scenes need a focal object".into());
344 }
345 for p in &self.unattended.props {
346 if !PROPS.contains(&p.as_str()) && !EFFECTS.contains(&p.as_str()) {
347 err(format!("unattended: unknown prop or effect `{p}`"));
348 }
349 }
350 match self.motion.kind {
351 MotionKind::Stationary => {}
352 MotionKind::Pace => match self.motion.speed_cells_per_s {
353 Some([lo, hi]) if lo > 0.0 && hi >= lo => {}
354 _ => err("pace motion needs speed_cells_per_s = [lo, hi] with 0 < lo <= hi".into()),
355 },
356 MotionKind::Path | MotionKind::Bob | MotionKind::Fly => err(format!(
357 "motion `{:?}` is not implemented yet (milestone M4)",
358 self.motion.kind
359 )),
360 }
361 if let Some(gif) = &self.gif {
362 let script = &gif.loop_script;
363 if script.first() != Some(&self.animation.start) {
364 err("gif.loop_script must start with the start state".into());
365 }
366 for pair in script.windows(2).chain(std::iter::once(
367 [
368 script.last().cloned().unwrap_or_default(),
369 script.first().cloned().unwrap_or_default(),
370 ]
371 .as_slice(),
372 )) {
373 let (from, to) = (&pair[0], &pair[1]);
374 if !states.contains_key(from) {
375 err(format!("gif.loop_script names undefined state `{from}`"));
376 } else if !self.successors(from).iter().any(|(s, _)| s == to) {
377 err(format!("gif.loop_script: `{from}` can't go to `{to}`"));
378 }
379 }
380 }
381 errs
382 }
383}
384
385#[derive(Clone, Debug, PartialEq)]
387pub struct Catalog {
388 pub activities: Vec<Activity>,
389 pub data_hash: u64,
391}
392
393impl Catalog {
394 pub fn builtin() -> Self {
397 Self::from_sources(&SOURCES)
398 .unwrap_or_else(|e| panic!("invalid built-in activities:\n{}", e.join("\n")))
399 }
400
401 pub fn from_sources(sources: &[(&str, &str)]) -> Result<Self, Vec<String>> {
403 let mut errors = Vec::new();
404 let mut activities = Vec::new();
405 let mut h = StableHasher::new();
406 for (name, text) in sources {
407 h.write_str(name);
408 write_text(&mut h, text);
409 match toml::from_str::<Activity>(text) {
410 Ok(a) => {
411 if format!("{}.toml", a.id) != *name {
412 errors.push(format!("{name}: id `{}` must match the file name", a.id));
413 }
414 errors.extend(a.validate());
415 activities.push(a);
416 }
417 Err(e) => errors.push(format!("{name}: {e}")),
418 }
419 }
420 activities.sort_by(|a, b| a.id.cmp(&b.id));
421 if errors.is_empty() {
422 Ok(Self {
423 activities,
424 data_hash: h.finish(),
425 })
426 } else {
427 Err(errors)
428 }
429 }
430
431 pub fn get(&self, id: &str) -> Option<&Activity> {
432 self.activities.iter().find(|a| a.id == id)
433 }
434}
435
436fn write_text(h: &mut StableHasher, text: &str) {
439 h.write_str(&text.replace("\r\n", "\n"));
440}
441
442pub fn builtin_catalog() -> &'static Catalog {
444 static CATALOG: OnceLock<Catalog> = OnceLock::new();
445 CATALOG.get_or_init(Catalog::builtin)
446}
447
448pub fn builtin_data_hash() -> u64 {
450 let mut h = StableHasher::new();
451 for (name, text) in SOURCES {
452 h.write_str(name);
453 write_text(&mut h, text);
454 }
455 h.finish()
456}
457
458#[cfg(test)]
459mod tests {
460 use super::*;
461
462 #[test]
463 fn builtin_catalog_is_valid() {
464 let c = Catalog::builtin();
465 assert_eq!(c.activities.len(), SOURCES.len());
466 assert_eq!(c.data_hash, builtin_data_hash());
467 }
468
469 #[test]
470 fn validation_reports_bad_files() {
471 let bad = r#"
472 id = "bad"
473 [requires]
474 terrain = ["lava"]
475 time_of_day = []
476 [motion]
477 type = "pace"
478 [props.anvil]
479 attach = "on_head"
480 [animation]
481 start = "idle"
482 [animation.states.idle]
483 loop = true
484 next = { nowhere = 1.0 }
485 [gif]
486 loop_script = ["sit"]
487 [unattended]
488 props = []
489 "#;
490 let errs = Catalog::from_sources(&[("bad.toml", bad)]).unwrap_err();
491 let all = errs.join("\n");
492 for needle in [
493 "unknown terrain `lava`",
494 "time_of_day is empty",
495 "undefined state `nowhere`",
496 "needs dwell_s",
497 "unknown prop `anvil`",
498 "unknown attach `on_head`",
499 "unattended.props is empty",
500 "pace motion needs speed",
501 "must start with the start state",
502 ] {
503 assert!(all.contains(needle), "missing `{needle}` in:\n{all}");
504 }
505 }
506
507 #[test]
508 fn data_hash_ignores_line_endings() {
509 let lf = Catalog::builtin();
510 let crlf: Vec<(String, String)> = SOURCES
511 .iter()
512 .map(|(n, t)| (n.to_string(), t.replace('\n', "\r\n")))
513 .collect();
514 let refs: Vec<(&str, &str)> = crlf.iter().map(|(n, t)| (n.as_str(), t.as_str())).collect();
515 assert_eq!(
516 Catalog::from_sources(&refs).unwrap().data_hash,
517 lf.data_hash
518 );
519 }
520
521 #[test]
522 fn unknown_fields_are_rejected() {
523 let text = "id = \"x\"\ncolour = \"red\"\n";
524 assert!(Catalog::from_sources(&[("x.toml", text)]).is_err());
525 }
526}