vrm-runtime 0.1.0

Renderer-agnostic VRM 1.0 loader, validator, animation system, and runtime
Documentation
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
use vrm_spec::vrmc_vrm_1_0::{self, ExpressionPresetName};

/// Returns the canonical JSON key for a VRM preset expression.
pub(crate) fn preset_expression_name(name: &ExpressionPresetName) -> &'static str {
    match name {
        ExpressionPresetName::Happy => "happy",
        ExpressionPresetName::Angry => "angry",
        ExpressionPresetName::Sad => "sad",
        ExpressionPresetName::Relaxed => "relaxed",
        ExpressionPresetName::Surprised => "surprised",
        ExpressionPresetName::Aa => "aa",
        ExpressionPresetName::Ih => "ih",
        ExpressionPresetName::Ou => "ou",
        ExpressionPresetName::Ee => "ee",
        ExpressionPresetName::Oh => "oh",
        ExpressionPresetName::Blink => "blink",
        ExpressionPresetName::BlinkLeft => "blinkLeft",
        ExpressionPresetName::BlinkRight => "blinkRight",
        ExpressionPresetName::Neutral => "neutral",
        ExpressionPresetName::LookUp => "lookUp",
        ExpressionPresetName::LookDown => "lookDown",
        ExpressionPresetName::LookLeft => "lookLeft",
        ExpressionPresetName::LookRight => "lookRight",
    }
}

/// Reports whether a name is reserved by the VRM preset-expression registry.
pub(crate) fn is_preset_expression_name(name: &str) -> bool {
    matches!(
        name,
        "happy"
            | "angry"
            | "sad"
            | "relaxed"
            | "surprised"
            | "aa"
            | "ih"
            | "ou"
            | "ee"
            | "oh"
            | "blink"
            | "blinkLeft"
            | "blinkRight"
            | "lookUp"
            | "lookDown"
            | "lookLeft"
            | "lookRight"
            | "neutral"
    )
}

/// A blend-shape bind: the morph target on a node that an expression drives.
#[derive(Debug, Clone)]
pub struct MorphTargetBind {
    node_index: u32,
    target_index: u32,
    weight: f32,
}

impl MorphTargetBind {
    /// Creates a bind for a node's morph target with its maximum weight.
    pub fn new(node_index: u32, target_index: u32, weight: f32) -> Self {
        Self {
            node_index,
            target_index,
            weight,
        }
    }

    /// Returns the glTF node index containing the target mesh.
    pub fn node_index(&self) -> u32 {
        self.node_index
    }

    /// Returns the morph target index within the node's mesh.
    pub fn target_index(&self) -> u32 {
        self.target_index
    }

    /// Returns the target weight reached at full expression input.
    pub fn weight(&self) -> f32 {
        self.weight
    }
}

/// A material color bind: the color attribute of a material that an
/// expression shifts toward `target_value`.
#[derive(Debug, Clone)]
pub struct MaterialColorBind {
    /// The glTF material index to modify.
    pub material_index: u32,
    /// The material color property to modify.
    pub color_type: MaterialColorType,
    /// The value reached at full expression input.
    pub target_value: [f32; 4],
}

/// A UV transform bind: the texture scale/offset of a material that an
/// expression animates.
#[derive(Debug, Clone)]
pub struct TextureTransformBind {
    /// The glTF material index whose textures are modified.
    pub material_index: u32,
    /// The UV scale reached at full expression input.
    pub scale: [f32; 2],
    /// The UV offset reached at full expression input.
    pub offset: [f32; 2],
}

/// A single accumulated morph weight (node + target index), ready to apply.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct MorphTargetUpdate {
    node_index: u32,
    target_index: u32,
    weight: f32,
}

impl MorphTargetUpdate {
    pub(crate) fn new(node_index: u32, target_index: u32, weight: f32) -> Self {
        Self {
            node_index,
            target_index,
            weight,
        }
    }

    /// Returns the glTF node index containing the updated target.
    pub fn node_index(&self) -> u32 {
        self.node_index
    }

    /// Returns the updated morph target index.
    pub fn target_index(&self) -> u32 {
        self.target_index
    }

    /// Returns the accumulated morph weight.
    pub fn weight(&self) -> f32 {
        self.weight
    }
}

/// An accumulated material color shift (delta over the base color).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct MaterialColorUpdate {
    material_index: u32,
    color_type: MaterialColorType,
    target_value: [f32; 4],
    weight: f32,
}

impl MaterialColorUpdate {
    /// Creates a weighted update for one material color property.
    pub fn new(
        material_index: u32,
        color_type: MaterialColorType,
        target_value: [f32; 4],
        weight: f32,
    ) -> Self {
        Self {
            material_index,
            color_type,
            target_value,
            weight,
        }
    }

    /// Returns the raw glTF material index to update.
    pub fn material_index(&self) -> u32 {
        self.material_index
    }

    /// Returns the material color property to update.
    pub fn color_type(&self) -> MaterialColorType {
        self.color_type
    }

    /// Returns the expression's full-weight target value.
    pub fn target_value(&self) -> [f32; 4] {
        self.target_value
    }

    /// Returns the accumulated expression influence.
    pub fn weight(&self) -> f32 {
        self.weight
    }
}

/// An accumulated UV transform shift (delta over scale 1 / offset 0).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TextureTransformUpdate {
    material_index: u32,
    scale: [f32; 2],
    offset: [f32; 2],
    weight: f32,
}

impl TextureTransformUpdate {
    /// Creates a weighted UV scale and offset update for one material.
    pub fn new(material_index: u32, scale: [f32; 2], offset: [f32; 2], weight: f32) -> Self {
        Self {
            material_index,
            scale,
            offset,
            weight,
        }
    }

    /// Returns the raw glTF material index to update.
    pub fn material_index(&self) -> u32 {
        self.material_index
    }

    /// Returns the expression's full-weight UV scale.
    pub fn scale(&self) -> [f32; 2] {
        self.scale
    }

    /// Returns the expression's full-weight UV offset.
    pub fn offset(&self) -> [f32; 2] {
        self.offset
    }

    /// Returns the accumulated expression influence.
    pub fn weight(&self) -> f32 {
        self.weight
    }
}

/// The output of evaluating one expression at a given weight: every bind
/// expanded into an update list.
#[derive(Debug, Clone, Default)]
pub struct ExpressionEvaluation {
    /// Morph target weights emitted by the expression.
    pub morph_updates: Vec<MorphTargetUpdate>,
    /// Material color updates emitted by the expression.
    pub material_color_updates: Vec<MaterialColorUpdate>,
    /// Texture transform updates emitted by the expression.
    pub texture_transform_updates: Vec<TextureTransformUpdate>,
}

/// Whether an active expression suppresses (`Block`) or scales down (`Blend`)
/// the procedural expressions of a category.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ExpressionOverrideType {
    /// Leaves procedural expressions in this category unchanged.
    #[default]
    None,
    /// Suppresses procedural expressions in this category.
    Block,
    /// Scales procedural expressions down by the active expression weight.
    Blend,
}

impl From<vrmc_vrm_1_0::ExpressionOverrideType> for ExpressionOverrideType {
    fn from(schema: vrmc_vrm_1_0::ExpressionOverrideType) -> Self {
        match schema {
            vrmc_vrm_1_0::ExpressionOverrideType::None => Self::None,
            vrmc_vrm_1_0::ExpressionOverrideType::Block => Self::Block,
            vrmc_vrm_1_0::ExpressionOverrideType::Blend => Self::Blend,
        }
    }
}

/// Enforces the VRM rule that an expression cannot override its own category.
///
/// The same validator is used before loading schema expressions and before a
/// programmatically composed asset is accepted, keeping both creation paths
/// semantically identical.
pub(crate) fn validate_override_semantics(
    name: &str,
    override_blink: ExpressionOverrideType,
    override_mouth: ExpressionOverrideType,
    override_look_at: ExpressionOverrideType,
) -> Result<(), String> {
    let invalid_override = if matches!(name, "blink" | "blinkLeft" | "blinkRight")
        && override_blink != ExpressionOverrideType::None
    {
        Some(("overrideBlink", "blink"))
    } else if matches!(name, "aa" | "ih" | "ou" | "ee" | "oh")
        && override_mouth != ExpressionOverrideType::None
    {
        Some(("overrideMouth", "mouth"))
    } else if matches!(name, "lookUp" | "lookDown" | "lookLeft" | "lookRight")
        && override_look_at != ExpressionOverrideType::None
    {
        Some(("overrideLookAt", "look-at"))
    } else {
        None
    };

    if let Some((field, category)) = invalid_override {
        return Err(format!(
            "expression `{name}` must set `{field}` to `none`; an expression cannot override its own {category} category"
        ));
    }

    Ok(())
}

/// The material attribute a color bind targets.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Ord, PartialOrd)]
pub enum MaterialColorType {
    /// The base color factor.
    Color,
    /// The emissive color factor.
    EmissionColor,
    /// The MToon shade color factor.
    ShadeColor,
    /// The MToon matcap color factor.
    MatcapColor,
    /// The MToon rim color factor.
    RimColor,
    /// The MToon outline color factor.
    OutlineColor,
}

/// A named, combinable facial/motion expression (e.g. "happy", "blink").
///
/// Holds the binds it drives and the override rules for the procedural
/// mouth / blink / gaze categories. `is_binary` expressions only ever output
/// 0 or 1.
#[derive(Debug, Clone)]
pub struct Expression {
    name: String,
    is_binary: bool,
    override_blink: ExpressionOverrideType,
    override_mouth: ExpressionOverrideType,
    override_look_at: ExpressionOverrideType,
    morph_target_binds: Vec<MorphTargetBind>,
    material_color_binds: Vec<MaterialColorBind>,
    texture_transform_binds: Vec<TextureTransformBind>,
}

impl Expression {
    /// Creates an empty, continuous expression with the given name.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            is_binary: false,
            morph_target_binds: Vec::new(),
            material_color_binds: Vec::new(),
            texture_transform_binds: Vec::new(),
            override_blink: ExpressionOverrideType::default(),
            override_mouth: ExpressionOverrideType::default(),
            override_look_at: ExpressionOverrideType::default(),
        }
    }

    /// Returns the preset or custom expression name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Replaces the morph targets driven by this expression.
    pub fn with_morph_target_binds(mut self, binds: Vec<MorphTargetBind>) -> Self {
        self.morph_target_binds = binds;
        self
    }

    /// Configures VRM binary thresholding for this expression.
    pub fn with_binary(mut self, is_binary: bool) -> Self {
        self.is_binary = is_binary;
        self
    }

    /// Sets how this expression affects procedural blink expressions.
    pub fn with_override_blink(mut self, value: ExpressionOverrideType) -> Self {
        self.override_blink = value;
        self
    }

    /// Sets how this expression affects procedural mouth expressions.
    pub fn with_override_mouth(mut self, value: ExpressionOverrideType) -> Self {
        self.override_mouth = value;
        self
    }

    /// Sets how this expression affects procedural look-at expressions.
    pub fn with_override_look_at(mut self, value: ExpressionOverrideType) -> Self {
        self.override_look_at = value;
        self
    }

    /// Replaces the material colors driven by this expression.
    pub fn with_material_color_binds(mut self, binds: Vec<MaterialColorBind>) -> Self {
        self.material_color_binds = binds;
        self
    }

    /// Replaces the texture transforms driven by this expression.
    pub fn with_texture_transform_binds(mut self, binds: Vec<TextureTransformBind>) -> Self {
        self.texture_transform_binds = binds;
        self
    }

    /// Reports whether input is thresholded to zero or one at 0.5.
    pub fn is_binary(&self) -> bool {
        self.is_binary
    }
    /// Returns the procedural blink override behavior.
    pub fn override_blink(&self) -> ExpressionOverrideType {
        self.override_blink
    }
    /// Returns the procedural mouth override behavior.
    pub fn override_mouth(&self) -> ExpressionOverrideType {
        self.override_mouth
    }
    /// Returns the procedural look-at override behavior.
    pub fn override_look_at(&self) -> ExpressionOverrideType {
        self.override_look_at
    }

    /// Returns the morph target binds in declaration order.
    pub fn morph_target_binds(&self) -> &[MorphTargetBind] {
        &self.morph_target_binds
    }

    /// Returns the material color binds in declaration order.
    pub fn material_color_binds(&self) -> &[MaterialColorBind] {
        &self.material_color_binds
    }

    /// Returns the texture transform binds in declaration order.
    pub fn texture_transform_binds(&self) -> &[TextureTransformBind] {
        &self.texture_transform_binds
    }

    fn load_expression(name: impl Into<String>, expression: &vrmc_vrm_1_0::Expression) -> Self {
        let is_binary = expression.is_binary.unwrap_or(false);

        // overrideMouth/Blink/LookAt: optional in the schema. When present, convert the
        // schema's enum to ours via From; when absent, fall back to ExpressionOverrideType::None.
        let override_blink = expression
            .override_blink
            .map(ExpressionOverrideType::from)
            .unwrap_or_default();
        let override_mouth = expression
            .override_mouth
            .map(ExpressionOverrideType::from)
            .unwrap_or_default();
        let override_look_at = expression
            .override_look_at
            .map(ExpressionOverrideType::from)
            .unwrap_or_default();

        let morph_target_binds = expression
            .morph_target_binds
            .as_deref()
            .unwrap_or_default()
            .iter()
            .map(|bind| {
                MorphTargetBind::new(
                    bind.node.value() as u32,
                    bind.index as u32,
                    bind.weight as f32,
                )
            })
            .collect();

        let material_color_binds = expression
            .material_color_binds
            .as_deref()
            .unwrap_or_default()
            .iter()
            .map(|bind| {
                let color_type = match bind.r#type {
                    vrmc_vrm_1_0::MaterialColorType::Color => MaterialColorType::Color,
                    vrmc_vrm_1_0::MaterialColorType::EmissionColor => {
                        MaterialColorType::EmissionColor
                    }
                    vrmc_vrm_1_0::MaterialColorType::ShadeColor => MaterialColorType::ShadeColor,
                    vrmc_vrm_1_0::MaterialColorType::MatcapColor => MaterialColorType::MatcapColor,
                    vrmc_vrm_1_0::MaterialColorType::RimColor => MaterialColorType::RimColor,
                    vrmc_vrm_1_0::MaterialColorType::OutlineColor => {
                        MaterialColorType::OutlineColor
                    }
                };
                let target = &bind.target_value;
                MaterialColorBind {
                    material_index: bind.material.value() as u32,
                    color_type,
                    target_value: [
                        target[0] as f32,
                        target[1] as f32,
                        target[2] as f32,
                        target[3] as f32,
                    ],
                }
            })
            .collect();

        let texture_transform_binds = expression
            .texture_transform_binds
            .as_deref()
            .unwrap_or_default()
            .iter()
            .map(|bind| {
                let scale = bind
                    .scale
                    .as_ref()
                    .map(|s| [s[0] as f32, s[1] as f32])
                    .unwrap_or([1.0, 1.0]);
                let offset = bind
                    .offset
                    .as_ref()
                    .map(|o| [o[0] as f32, o[1] as f32])
                    .unwrap_or([0.0, 0.0]);
                TextureTransformBind {
                    material_index: bind.material.value() as u32,
                    scale,
                    offset,
                }
            })
            .collect();

        Self {
            name: name.into(),
            is_binary,
            override_blink,
            override_mouth,
            override_look_at,
            morph_target_binds,
            material_color_binds,
            texture_transform_binds,
        }
    }

    /// Evaluates all binds after clamping or binary-thresholding `input_weight`.
    pub fn evaluate(&self, input_weight: f32) -> ExpressionEvaluation {
        let input_weight = if self.is_binary {
            f32::from(input_weight >= 0.5)
        } else if input_weight.is_finite() {
            input_weight.clamp(0.0, 1.0)
        } else {
            0.0
        };

        ExpressionEvaluation {
            morph_updates: self
                .morph_target_binds
                .iter()
                .map(|bind| {
                    MorphTargetUpdate::new(
                        bind.node_index(),
                        bind.target_index(),
                        bind.weight() * input_weight,
                    )
                })
                .collect(),
            material_color_updates: self
                .material_color_binds
                .iter()
                .map(|bind| {
                    MaterialColorUpdate::new(
                        bind.material_index,
                        bind.color_type,
                        bind.target_value,
                        input_weight,
                    )
                })
                .collect(),
            texture_transform_updates: self
                .texture_transform_binds
                .iter()
                .map(|bind| {
                    TextureTransformUpdate::new(
                        bind.material_index,
                        bind.scale,
                        bind.offset,
                        input_weight,
                    )
                })
                .collect(),
        }
    }
}

/// The ordered list of expressions defined by an avatar (presets and customs).
#[derive(Debug, Clone, Default)]
pub struct Expressions {
    items: Vec<Expression>,
}

impl Expressions {
    /// Creates an ordered expression collection.
    pub fn new(items: Vec<Expression>) -> Self {
        Self { items }
    }

    /// Iterates over preset and custom expressions in stored order.
    pub fn iter(&self) -> impl Iterator<Item = &Expression> {
        self.items.iter()
    }

    /// Finds an expression by its exact preset or custom name.
    pub fn get(&self, name: &str) -> Option<&Expression> {
        self.items
            .iter()
            .find(|expression| expression.name() == name)
    }

    /// Returns the number of expressions.
    pub fn len(&self) -> usize {
        self.items.len()
    }

    /// Reports whether the collection contains no expressions.
    pub fn is_empty(&self) -> bool {
        self.items.is_empty()
    }

    pub(crate) fn load_expressions(expressions: &vrmc_vrm_1_0::Expressions) -> Self {
        let mut items = Vec::new();

        if let Some(preset) = &expressions.preset {
            for (preset_name, expr) in &preset.0 {
                let name = preset_expression_name(preset_name);
                items.push(Expression::load_expression(name, expr));
            }
        }

        if let Some(custom) = &expressions.custom {
            for (custom_name, expr) in custom {
                items.push(Expression::load_expression(custom_name, expr));
            }
        }

        Self::new(items)
    }
}