clairlune_sprites/
character.rs1use crate::embedded::SHEETS;
5use crate::sheet::{Animation, Frame, MAX_CHARACTER_COLORS, ORIGIN, SpriteSheet};
6use clairlune_scene::Rgb;
7use clairlune_scene::activity::Catalog;
8use clairlune_scene::anim::DEFAULT_ONE_SHOT_MS;
9use clairlune_scene::placeholder::CLAWD_PLACEHOLDER;
10use std::collections::BTreeMap;
11use std::sync::OnceLock;
12
13pub const BASE_SHEET: &str = "_base";
15
16pub trait Character {
18 fn animation(&self, activity: &str, state: &str) -> Option<&Animation>;
20
21 fn one_shot_ms(&self, activity: &str, state: &str) -> u64 {
23 self.animation(activity, state)
24 .map(Animation::duration_ms)
25 .filter(|&d| d > 0)
26 .unwrap_or(DEFAULT_ONE_SHOT_MS)
27 }
28}
29
30#[derive(Clone, Debug)]
32pub struct Placeholder {
33 anim: Animation,
34}
35
36impl Default for Placeholder {
37 fn default() -> Self {
38 Self::new()
39 }
40}
41
42impl Placeholder {
43 pub fn new() -> Self {
44 let m = &CLAWD_PLACEHOLDER;
45 let pixels = (0..m.height)
46 .flat_map(|y| (0..m.width).map(move |x| m.pixel(x, y)))
47 .collect();
48 let mut anchors = BTreeMap::new();
49 anchors.insert(
51 ORIGIN.to_string(),
52 ((m.width / 2) as i32, m.height as i32 - 1),
53 );
54 let frame = Frame {
55 width: m.width,
56 height: m.height,
57 pixels,
58 duration_ms: DEFAULT_ONE_SHOT_MS as u32,
59 anchors,
60 };
61 Self {
62 anim: Animation {
63 name: "placeholder".into(),
64 frames: vec![frame],
65 },
66 }
67 }
68}
69
70impl Character for Placeholder {
71 fn animation(&self, _activity: &str, _state: &str) -> Option<&Animation> {
72 Some(&self.anim)
73 }
74}
75
76#[derive(Clone, Debug)]
80pub struct SheetCharacter {
81 sheets: BTreeMap<String, SpriteSheet>,
82 placeholder: Placeholder,
83}
84
85impl SheetCharacter {
86 pub fn builtin() -> Result<Self, Vec<String>> {
88 Self::from_sources(SHEETS)
89 }
90
91 pub fn from_sources(sources: &[(&str, &str, &[u8])]) -> Result<Self, Vec<String>> {
93 let mut errors = Vec::new();
94 let mut sheets = BTreeMap::new();
95 let mut colors = Vec::new();
96 for (name, json, png) in sources {
97 match SpriteSheet::parse(json, png) {
98 Ok(sheet) => {
99 for c in &sheet.colors {
100 if !colors.contains(c) {
101 colors.push(*c);
102 }
103 }
104 sheets.insert(name.to_string(), sheet);
105 }
106 Err(e) => errors.push(format!("{name}: {e}")),
107 }
108 }
109 if colors.len() > MAX_CHARACTER_COLORS {
110 errors.push(format!(
111 "all sheets together use {} colours; the character may use at most {MAX_CHARACTER_COLORS}",
112 colors.len()
113 ));
114 }
115 if errors.is_empty() {
116 Ok(Self {
117 sheets,
118 placeholder: Placeholder::new(),
119 })
120 } else {
121 Err(errors)
122 }
123 }
124
125 pub fn colors(&self) -> Vec<Rgb> {
127 let mut out: Vec<Rgb> = Vec::new();
128 for sheet in self.sheets.values() {
129 for c in &sheet.colors {
130 if !out.contains(c) {
131 out.push(*c);
132 }
133 }
134 }
135 out
136 }
137
138 pub fn has_sheet(&self, activity: &str) -> bool {
139 self.sheets.contains_key(activity)
140 }
141
142 pub fn missing_art<'c>(&self, catalog: &'c Catalog) -> Vec<&'c str> {
144 catalog
145 .activities
146 .iter()
147 .map(|a| a.id.as_str())
148 .filter(|id| !self.has_sheet(id))
149 .collect()
150 }
151
152 pub fn validate(&self, catalog: &Catalog) -> Vec<String> {
155 let mut errors = Vec::new();
156 for a in &catalog.activities {
157 let Some(sheet) = self.sheets.get(&a.id) else {
158 continue;
159 };
160 for state in a.animation.states.keys() {
161 let in_base = self
162 .sheets
163 .get(BASE_SHEET)
164 .is_some_and(|b| b.animations.contains_key(state));
165 if !sheet.animations.contains_key(state) && !in_base {
166 errors.push(format!(
167 "{}: state `{state}` has no tag in {}.aseprite or {BASE_SHEET}.aseprite",
168 a.id, a.id
169 ));
170 }
171 }
172 }
173 errors
174 }
175}
176
177impl Character for SheetCharacter {
178 fn animation(&self, activity: &str, state: &str) -> Option<&Animation> {
179 self.sheets
180 .get(activity)
181 .and_then(|s| s.animations.get(state))
182 .or_else(|| {
183 self.sheets
184 .get(BASE_SHEET)
185 .and_then(|s| s.animations.get(state))
186 })
187 .or_else(|| self.placeholder.animation(activity, state))
188 }
189}
190
191pub fn builtin_character() -> &'static SheetCharacter {
193 static CHARACTER: OnceLock<SheetCharacter> = OnceLock::new();
194 CHARACTER.get_or_init(|| SheetCharacter::builtin().expect("embedded sheets are valid"))
195}
196
197#[cfg(test)]
198mod tests {
199 use super::*;
200 use crate::sheet::tests::fixture;
201 use clairlune_scene::activity::builtin_catalog;
202
203 #[test]
204 fn placeholder_matches_the_pixel_map() {
205 let p = Placeholder::new();
206 let a = p.animation("anything", "any").unwrap();
207 let f = &a.frames[0];
208 assert_eq!((f.width, f.height), (15, 9));
209 assert_eq!(f.origin(), (7, 8));
210 assert_eq!(p.one_shot_ms("x", "y"), DEFAULT_ONE_SHOT_MS);
211 }
212
213 #[test]
214 fn builtin_sheets_are_valid_and_complete() {
215 let c = SheetCharacter::builtin().expect("embedded sheets parse");
216 let errors = c.validate(builtin_catalog());
217 assert!(errors.is_empty(), "{}", errors.join("\n"));
218 for a in &builtin_catalog().activities {
220 for s in a.animation.states.keys() {
221 assert!(c.animation(&a.id, s).is_some());
222 }
223 }
224 }
225
226 #[test]
227 fn validation_reports_states_without_tags() {
228 let (json, png) = fixture(2, 0, 0);
229 let c = SheetCharacter::from_sources(&[("warm_hands", &json, &png)]).unwrap();
230 let errors = c.validate(builtin_catalog()).join("\n");
231 assert!(errors.contains("state `warm` has no tag"), "{errors}");
232 assert!(
233 errors.contains("state `look_around` has no tag"),
234 "{errors}"
235 );
236 assert!(!errors.contains("`idle`"));
238 assert_eq!(c.animation("warm_hands", "idle").unwrap().name, "idle");
239 assert_eq!(
241 c.animation("warm_hands", "warm").unwrap().name,
242 "placeholder"
243 );
244 assert!(c.missing_art(builtin_catalog()).contains(&"stroll"));
245 }
246}