hiraku-engine 0.1.0

Hiraku visual-novel engine
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
use std::{collections::BTreeMap, path::Path};

use bevy::{math::Vec2, prelude::Resource};
use hiraku_script::hson;
use serde::{Deserialize, de::DeserializeOwned};
use thiserror::Error;

use crate::{
    texture::{TextureCatalog, TextureCatalogError, load_texture_catalog},
    vfs::{HdpVfs, VfsError},
};

#[derive(Clone, Debug, Default, Resource)]
pub struct CharacterCatalog {
    pub directory: Option<String>,
    pub characters: BTreeMap<String, CharacterDefinition>,
}

#[derive(Clone, Debug)]
pub struct CharacterDefinition {
    pub name: String,
    pub directory: String,
    pub config_path: String,
    /// Named slots are assigned in declaration order so authored state changes
    /// have stable internal identities instead of relying on part names.
    pub slots: BTreeMap<String, usize>,
    pub parts: Vec<CharacterPartDefinition>,
    pub expressions: BTreeMap<String, CharacterExpressionDefinition>,
    pub basis: Vec<String>,
    pub default_expression: Option<String>,
}

#[derive(Clone, Debug)]
pub struct CharacterPartDefinition {
    pub id: String,
    pub slot: Option<usize>,
    pub path: String,
    /// Catalog rectangle in `[left, top, width, height]` form, retained so
    /// rendering can select the generated/declared atlas section.
    pub atlas_rect: Option<[f32; 4]>,
    pub offset: Vec2,
    pub layer: f32,
    pub rect: Option<[f32; 4]>,
    pub mask: Option<CharacterMaskDefinition>,
    pub blend: CharacterBlendMode,
    pub color: [u8; 4],
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub enum CharacterMaskKind {
    Read,
    Write,
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq)]
pub struct CharacterMaskDefinition {
    pub kind: CharacterMaskKind,
    #[serde(rename = "ref")]
    pub reference: u8,
}

#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub enum CharacterBlendMode {
    #[default]
    Normal,
    Multiply,
}

#[derive(Clone, Debug)]
pub struct CharacterExpressionDefinition {
    pub slot: Option<usize>,
    pub parts: Vec<String>,
    pub expressions: Vec<String>,
}

impl CharacterDefinition {
    pub fn parts_for_expressions(
        &self,
        expressions: &[String],
    ) -> Result<Vec<CharacterPartDefinition>, String> {
        let mut selected = BTreeMap::<SelectionKey, Vec<String>>::new();
        let basis = if self.basis.is_empty() {
            self.default_expression.iter().cloned().collect::<Vec<_>>()
        } else {
            self.basis.clone()
        };
        if basis.is_empty() && expressions.is_empty() {
            return Ok(self.parts.clone());
        }

        for expression in basis.iter().chain(expressions) {
            self.apply_expression(expression, &mut selected, &mut Vec::new())?;
        }

        let selected_ids = selected
            .into_iter()
            .flat_map(|(slot, ids)| ids.into_iter().map(move |id| (slot.clone(), id)))
            .collect::<Vec<_>>();
        Ok(self
            .parts
            .iter()
            .filter_map(|part| {
                let slot = selected_ids
                    .iter()
                    .find_map(|(slot, id)| (id == &part.id).then_some(slot))?;
                let mut part = part.clone();
                if let SelectionKey::Slot(index) = slot {
                    part.slot = Some(*index);
                }
                Some(part)
            })
            .collect())
    }

    fn apply_expression(
        &self,
        name: &str,
        selected: &mut BTreeMap<SelectionKey, Vec<String>>,
        resolving: &mut Vec<String>,
    ) -> Result<(), String> {
        if resolving.iter().any(|expression| expression == name) {
            return Err(format!(
                "character `{}` has a circular expression reference at `{name}`",
                self.name
            ));
        }
        let Some(expression) = self.expressions.get(name) else {
            if let Some(part) = self.parts.iter().find(|part| part.id == name) {
                let key = part
                    .slot
                    .map(SelectionKey::Slot)
                    .unwrap_or_else(|| SelectionKey::Expression(name.to_string()));
                selected.insert(key, vec![name.to_string()]);
                return Ok(());
            }
            return Err(format!(
                "character `{}` has no expression or part named `{name}`",
                self.name
            ));
        };
        resolving.push(name.to_string());
        for nested in &expression.expressions {
            self.apply_expression(nested, selected, resolving)?;
        }
        resolving.pop();

        if let Some(slot) = expression.slot {
            // An explicitly slotted expression with no parts clears that slot.
            // This is required by presets such as `Pale1-Off`.
            selected.insert(SelectionKey::Slot(slot), expression.parts.clone());
        } else {
            // Parts are the source of truth for slot ownership. Grouping is
            // important because one expression may intentionally contain
            // several layers in the same slot (for example an arm and shadow).
            let mut grouped = BTreeMap::<SelectionKey, Vec<String>>::new();
            for part_id in &expression.parts {
                let part = self.parts.iter().find(|part| &part.id == part_id).ok_or_else(|| {
                    format!(
                        "character `{}` expression `{name}` references missing part `{part_id}`",
                        self.name
                    )
                })?;
                let key = part
                    .slot
                    .map(SelectionKey::Slot)
                    .unwrap_or_else(|| SelectionKey::Expression(part_id.clone()));
                grouped.entry(key).or_default().push(part_id.clone());
            }
            selected.extend(grouped);
        }
        Ok(())
    }
}

#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
enum SelectionKey {
    Slot(usize),
    Expression(String),
}

#[derive(Debug, Error)]
pub enum CharacterCatalogError {
    #[error("failed to read character data: {0}")]
    Read(#[from] VfsError),
    #[error("failed to load texture data: {0}")]
    Texture(#[from] TextureCatalogError),
    #[error("failed to load character data `{path}`: {message}")]
    Data { path: String, message: String },
}

#[derive(Debug, Deserialize, Default)]
struct CharacterCatalogFile {
    #[serde(default)]
    characters: Vec<CharacterCatalogEntryFile>,
}

#[derive(Debug, Deserialize)]
struct CharacterCatalogEntryFile {
    name: String,
    dir: String,
    #[serde(default)]
    config: Option<String>,
}

#[derive(Debug, Deserialize, Default)]
struct CharacterConfigFile {
    #[serde(default)]
    slots: Vec<String>,
    #[serde(default)]
    parts: BTreeMap<String, CharacterPartFile>,
    #[serde(default)]
    expressions: BTreeMap<String, CharacterExpressionFile>,
    #[serde(default)]
    basis: Vec<String>,
    #[serde(default)]
    default_expression: Option<String>,
}

#[derive(Debug, Deserialize)]
struct CharacterDataFile {
    name: String,
    #[serde(flatten)]
    config: CharacterConfigFile,
}

#[derive(Debug, Deserialize)]
struct CharacterPartFile {
    #[serde(default)]
    slot: Option<String>,
    #[serde(default)]
    path: Option<String>,
    #[serde(default)]
    texture: Option<String>,
    #[serde(default)]
    offset: Option<[f64; 2]>,
    #[serde(default)]
    layer: Option<f64>,
    #[serde(default)]
    rect: Option<[f64; 4]>,
    #[serde(default)]
    mask: Option<CharacterMaskDefinition>,
    #[serde(default)]
    blend: CharacterBlendMode,
    #[serde(default = "default_part_color")]
    color: [u8; 4],
}

const fn default_part_color() -> [u8; 4] {
    [255, 255, 255, 255]
}

#[derive(Debug, Deserialize)]
#[serde(untagged)]
enum CharacterExpressionFile {
    Parts(Vec<String>),
    Definition {
        #[serde(default)]
        slot: Option<String>,
        #[serde(default)]
        parts: Vec<String>,
        #[serde(default)]
        expressions: Vec<String>,
    },
}

pub fn load_character_catalog(vfs: &HdpVfs) -> Result<CharacterCatalog, CharacterCatalogError> {
    let Some(directory) = vfs.load_characters_dir_path()? else {
        return Ok(CharacterCatalog::default());
    };

    let textures = load_texture_catalog(vfs)?;
    let catalog_path = vfs.resolve_path(
        Some(vfs.settings_path()),
        &format!("{directory}/characters.hson"),
    );
    let catalog_text = match vfs.read_text(&catalog_path) {
        Ok(catalog_text) => catalog_text,
        Err(VfsError::NotFound(_)) => {
            return load_character_data_files(vfs, &textures, directory);
        }
        Err(error) => return Err(error.into()),
    };
    let file: CharacterCatalogFile = parse_hks_data(&catalog_path, &catalog_text)?;

    let mut characters = BTreeMap::new();
    for entry in file.characters {
        let character_directory = vfs.resolve_path(Some(&catalog_path), &entry.dir);
        let config_relative = entry.config.unwrap_or_else(|| "character.hson".to_string());
        let config_path = vfs.resolve_path(
            Some(&format!("{character_directory}/__dir__")),
            &config_relative,
        );
        let config_text = vfs.read_text(&config_path)?;
        let config: CharacterConfigFile = parse_hks_data(&config_path, &config_text)?;

        let definition = character_definition_from_config(
            vfs,
            &textures,
            entry.name.clone(),
            character_directory,
            config_path,
            config,
        )?;
        characters.insert(entry.name, definition);
    }

    Ok(CharacterCatalog {
        directory: Some(directory),
        characters,
    })
}

fn load_character_data_files(
    vfs: &HdpVfs,
    textures: &TextureCatalog,
    directory: String,
) -> Result<CharacterCatalog, CharacterCatalogError> {
    let mut paths = match vfs.list_files_recursive(&directory) {
        Ok(paths) => paths,
        Err(VfsError::NotFound(_)) => {
            return Ok(CharacterCatalog {
                directory: Some(directory),
                characters: BTreeMap::new(),
            });
        }
        Err(error) => return Err(error.into()),
    };
    paths.retain(|path| path.ends_with(".char.hson"));
    paths.sort();

    let mut characters = BTreeMap::new();
    for path in paths {
        let source = vfs.read_text(&path)?;
        let data: CharacterDataFile = parse_hks_data(&path, &source)?;
        let directory_path = Path::new(&path)
            .parent()
            .and_then(|path| path.to_str())
            .unwrap_or_default();
        let definition = character_definition_from_config(
            vfs,
            textures,
            data.name.clone(),
            directory_path.to_string(),
            path,
            data.config,
        )?;
        if characters.insert(data.name.clone(), definition).is_some() {
            return Err(CharacterCatalogError::Data {
                path: data.name,
                message: "character is defined more than once".to_string(),
            });
        }
    }

    Ok(CharacterCatalog {
        directory: Some(directory),
        characters,
    })
}

fn character_definition_from_config(
    vfs: &HdpVfs,
    textures: &TextureCatalog,
    name: String,
    directory: String,
    config_path: String,
    config: CharacterConfigFile,
) -> Result<CharacterDefinition, CharacterCatalogError> {
    let slots = build_slot_indices(&config, &config_path)?;
    let mut parts = config
        .parts
        .into_iter()
        .map(|(id, part)| {
            let (path, texture_rect) = if let Some(texture_name) = part.texture.as_deref() {
                let texture =
                    textures
                        .resolve(texture_name)
                        .ok_or_else(|| CharacterCatalogError::Data {
                            path: config_path.clone(),
                            message: format!(
                                "part `{id}` references undefined texture `{texture_name}`"
                            ),
                        })?;
                (texture.path.clone(), texture.rect)
            } else {
                let path = part
                    .path
                    .as_deref()
                    .ok_or_else(|| CharacterCatalogError::Data {
                        path: config_path.clone(),
                        message: format!("part `{id}` requires `texture` or `path`"),
                    })?;
                (vfs.resolve_path(Some(&config_path), path), None)
            };
            let rect = part
                .rect
                .map(|rect| {
                    let left = rect[0] as f32;
                    let top = rect[1] as f32;
                    [left, top, left + rect[2] as f32, top + rect[3] as f32]
                })
                .or_else(|| {
                    texture_rect
                        .map(|rect| [rect[0], rect[1], rect[0] + rect[2], rect[1] + rect[3]])
                });
            if part.mask.is_some_and(|mask| mask.kind == CharacterMaskKind::Read)
                && part.blend == CharacterBlendMode::Multiply
            {
                return Err(CharacterCatalogError::Data {
                    path: config_path.clone(),
                    message: format!(
                        "part `{id}` cannot combine `mask: \"read\"` with `blend: \"multiply\"`; use separate parts"
                    ),
                });
            }
            Ok(CharacterPartDefinition {
                id,
                slot: part
                    .slot
                    .as_deref()
                    .and_then(|name| slots.get(name).copied()),
                path,
                atlas_rect: texture_rect,
                offset: part
                    .offset
                    .map(|offset| Vec2::new(offset[0] as f32, offset[1] as f32))
                    .unwrap_or(Vec2::ZERO),
                layer: part.layer.unwrap_or(0.0) as f32,
                rect,
                mask: part.mask,
                blend: part.blend,
                color: part.color,
            })
        })
        .collect::<Result<Vec<_>, CharacterCatalogError>>()?;
    parts.sort_by(|left, right| {
        left.layer
            .partial_cmp(&right.layer)
            .unwrap_or(std::cmp::Ordering::Equal)
            .then_with(|| left.id.cmp(&right.id))
    });
    let expressions = config
        .expressions
        .into_iter()
        .map(|(name, expression)| {
            let expression = match expression {
                CharacterExpressionFile::Parts(parts) => CharacterExpressionDefinition {
                    slot: None,
                    parts,
                    expressions: Vec::new(),
                },
                CharacterExpressionFile::Definition {
                    slot,
                    parts,
                    expressions,
                } => CharacterExpressionDefinition {
                    slot: slot.as_deref().and_then(|name| slots.get(name).copied()),
                    parts,
                    expressions,
                },
            };
            (name, expression)
        })
        .collect::<BTreeMap<_, _>>();
    validate_expressions(
        &expressions,
        &config.basis,
        config.default_expression.as_deref(),
        &parts,
        &config_path,
    )?;

    Ok(CharacterDefinition {
        name,
        directory,
        config_path,
        slots,
        parts,
        expressions,
        basis: config.basis,
        default_expression: config.default_expression,
    })
}

fn build_slot_indices(
    config: &CharacterConfigFile,
    path: &str,
) -> Result<BTreeMap<String, usize>, CharacterCatalogError> {
    let mut slots = BTreeMap::new();
    for name in &config.slots {
        let index = slots.len();
        if slots.insert(name.clone(), index).is_some() {
            return Err(CharacterCatalogError::Data {
                path: path.to_string(),
                message: format!("slot `{name}` is declared more than once"),
            });
        }
    }

    // Older files only name slots inside parts/expressions. Keep accepting
    // those files while assigning their extra slots deterministically.
    let mut implicit = config
        .parts
        .values()
        .filter_map(|part| part.slot.clone())
        .chain(
            config
                .expressions
                .values()
                .filter_map(|expression| match expression {
                    CharacterExpressionFile::Parts(_) => None,
                    CharacterExpressionFile::Definition { slot, .. } => slot.clone(),
                }),
        )
        .collect::<Vec<_>>();
    implicit.sort();
    implicit.dedup();
    for name in implicit {
        if !slots.contains_key(&name) {
            let index = slots.len();
            slots.insert(name, index);
        }
    }
    Ok(slots)
}

fn validate_expressions(
    expressions: &BTreeMap<String, CharacterExpressionDefinition>,
    basis: &[String],
    default_expression: Option<&str>,
    parts: &[CharacterPartDefinition],
    path: &str,
) -> Result<(), CharacterCatalogError> {
    let has_reference =
        |name: &str| expressions.contains_key(name) || parts.iter().any(|part| part.id == name);
    if let Some(default_expression) = default_expression
        && !has_reference(default_expression)
    {
        return Err(CharacterCatalogError::Data {
            path: path.to_string(),
            message: format!("default_expression `{default_expression}` is not defined"),
        });
    }

    for expression in basis {
        if !has_reference(expression) {
            return Err(CharacterCatalogError::Data {
                path: path.to_string(),
                message: format!("basis references undefined expression `{expression}`"),
            });
        }
    }

    for (expression, definition) in expressions {
        for part_id in &definition.parts {
            if !parts.iter().any(|part| &part.id == part_id) {
                return Err(CharacterCatalogError::Data {
                    path: path.to_string(),
                    message: format!(
                        "expression `{expression}` references missing part `{part_id}`"
                    ),
                });
            }
        }
        for nested in &definition.expressions {
            if !has_reference(nested) {
                return Err(CharacterCatalogError::Data {
                    path: path.to_string(),
                    message: format!(
                        "expression `{expression}` references undefined expression `{nested}`"
                    ),
                });
            }
        }
    }

    Ok(())
}

fn parse_hks_data<T>(path: &str, source: &str) -> Result<T, CharacterCatalogError>
where
    T: DeserializeOwned,
{
    hson::from_str(source).map_err(|error| CharacterCatalogError::Data {
        path: path.to_string(),
        message: error.render_with_options(path, source, hiraku_script::RenderOptions::terminal()),
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn loads_hks_character_catalog_and_parts() {
        let root =
            std::env::temp_dir().join(format!("hiraku-character-test-{}", std::process::id()));
        let characters = root.join("characters/alice");
        std::fs::create_dir_all(&characters).unwrap();
        std::fs::write(
            root.join("settings.hson"),
            ".{ charactersDir: \"characters\" }",
        )
        .unwrap();
        std::fs::write(
            root.join("characters/characters.hson"),
            ".{ characters: [.{ name: \"alice\", dir: \"alice\" }] }",
        )
        .unwrap();
        std::fs::write(
            characters.join("character.hson"),
            ".{ slots: [\"body\", \"face\", \"shade\"], parts: .{ body: .{ path: \"body.png\", slot: \"body\", offset: (12.5, -3.0), layer: -1.0, mask: .{ kind: \"write\", ref: 1 } }, face: .{ path: \"face.png\", slot: \"face\", layer: 2.0, mask: .{ kind: \"read\", ref: 1 }, color: [255, 128, 64, 96] }, shade: .{ path: \"shade.png\", slot: \"shade\", layer: 3.0, blend: \"multiply\" } }, expressions: .{ happy: [\"body\", \"face\", \"shade\"] }, default_expression: \"happy\" }",
        )
        .unwrap();

        let vfs = HdpVfs::new_with_config(&root, "settings.hson", "startup.hks");
        let catalog = load_character_catalog(&vfs).unwrap();
        let alice = &catalog.characters["alice"];

        assert_eq!(alice.parts.len(), 3);
        assert_eq!(alice.parts[0].id, "body");
        assert_eq!(alice.parts[0].offset, Vec2::new(12.5, -3.0));
        assert_eq!(alice.parts[1].id, "face");
        assert_eq!(
            alice.parts[0].mask,
            Some(CharacterMaskDefinition {
                kind: CharacterMaskKind::Write,
                reference: 1,
            })
        );
        assert_eq!(
            alice.parts[1].mask,
            Some(CharacterMaskDefinition {
                kind: CharacterMaskKind::Read,
                reference: 1,
            })
        );
        assert_eq!(alice.parts[1].blend, CharacterBlendMode::Normal);
        assert_eq!(alice.parts[1].color, [255, 128, 64, 96]);
        assert_eq!(alice.parts[2].blend, CharacterBlendMode::Multiply);
        assert_eq!(alice.slots["body"], 0);
        assert_eq!(alice.slots["face"], 1);
        assert_eq!(
            alice
                .parts_for_expressions(&["happy".to_string()])
                .unwrap()
                .len(),
            3
        );

        let _ = std::fs::remove_dir_all(root);
    }

    #[test]
    fn slot_expressions_preserve_the_other_basis_slots() {
        let definition = CharacterDefinition {
            name: "alice".to_string(),
            directory: String::new(),
            config_path: String::new(),
            slots: BTreeMap::from([("mouth".to_string(), 0), ("face".to_string(), 1)]),
            parts: [
                "body",
                "mouth_closed",
                "mouth_open",
                "face_neutral",
                "face_happy",
            ]
            .into_iter()
            .map(|id| CharacterPartDefinition {
                id: id.to_string(),
                slot: (id == "face_happy").then_some(1),
                path: format!("{id}.png"),
                atlas_rect: None,
                offset: Vec2::ZERO,
                layer: 0.0,
                rect: None,
                mask: None,
                blend: CharacterBlendMode::Normal,
                color: default_part_color(),
            })
            .collect(),
            expressions: BTreeMap::from([
                (
                    "basis".to_string(),
                    CharacterExpressionDefinition {
                        slot: None,
                        parts: vec!["body".to_string()],
                        expressions: vec!["mouth_closed".to_string(), "face_neutral".to_string()],
                    },
                ),
                (
                    "mouth_closed".to_string(),
                    CharacterExpressionDefinition {
                        slot: Some(0),
                        parts: vec!["mouth_closed".to_string()],
                        expressions: Vec::new(),
                    },
                ),
                (
                    "mouth_open".to_string(),
                    CharacterExpressionDefinition {
                        slot: Some(0),
                        parts: vec!["mouth_open".to_string()],
                        expressions: Vec::new(),
                    },
                ),
                (
                    "face_neutral".to_string(),
                    CharacterExpressionDefinition {
                        slot: Some(1),
                        parts: vec!["face_neutral".to_string()],
                        expressions: Vec::new(),
                    },
                ),
                (
                    "face_off".to_string(),
                    CharacterExpressionDefinition {
                        slot: Some(1),
                        parts: Vec::new(),
                        expressions: Vec::new(),
                    },
                ),
            ]),
            basis: vec!["basis".to_string()],
            default_expression: None,
        };

        let parts = definition
            .parts_for_expressions(&["mouth_open".to_string(), "face_happy".to_string()])
            .unwrap();
        let ids = parts.into_iter().map(|part| part.id).collect::<Vec<_>>();
        assert_eq!(ids, ["body", "mouth_open", "face_happy"]);

        let parts = definition
            .parts_for_expressions(&["face_off".to_string()])
            .expect("an empty slotted expression must clear its slot");
        let ids = parts.into_iter().map(|part| part.id).collect::<Vec<_>>();
        assert_eq!(ids, ["body", "mouth_closed"]);
    }
}