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