Skip to main content

vrm_runtime/
evaluated_material.rs

1use crate::expressions::{MaterialColorUpdate, TextureTransformUpdate};
2use crate::{Avatar, MaterialColorType, MaterialId, TextureTransform};
3
4/// Time-dependent MToon UV animation shared by all texture slots of a material.
5///
6/// A renderer samples the optional MToon UV animation mask and applies this
7/// transform before the expression-wide and per-texture transforms.
8#[derive(Debug, Clone, Copy, PartialEq, Default)]
9pub struct UvAnimationState {
10    /// Accumulated MToon UV scroll offset.
11    pub scroll: [f32; 2],
12    /// Accumulated MToon UV rotation in radians.
13    pub rotation: f32,
14}
15
16/// Final dynamic values of one material for an evaluated frame.
17///
18/// Static texture references and render-state settings remain on [`crate::Material`].
19/// This value contains the parameters that can change because of VRM expressions
20/// or MToon UV animation, so renderers do not need to reimplement VRM blending.
21#[derive(Debug, Clone, PartialEq)]
22pub struct EvaluatedMaterial {
23    /// Stable identifier of the source [`crate::Material`].
24    pub material_id: MaterialId,
25    /// Base color after all active VRM expression binds are accumulated.
26    pub base_color_factor: [f32; 4],
27    /// Expression-adjusted emissive color with the selected HDR strength already applied.
28    pub emissive_factor: [f32; 3],
29    /// MToon shade color after active expression binds are accumulated.
30    pub shade_color_factor: [f32; 3],
31    /// MToon matcap color after active expression binds are accumulated.
32    pub matcap_factor: [f32; 3],
33    /// MToon rim color after active expression binds are accumulated.
34    pub rim_color_factor: [f32; 3],
35    /// MToon outline color after active expression binds are accumulated.
36    pub outline_color_factor: [f32; 3],
37    /// Material-wide transform produced by VRM expression binds.
38    pub texture_transform: TextureTransform,
39    /// Time-dependent MToon transform, applied before expression and texture transforms.
40    pub uv_animation: UvAnimationState,
41}
42
43pub(crate) fn evaluate_materials(
44    asset: &Avatar,
45    color_updates: &[MaterialColorUpdate],
46    texture_updates: &[TextureTransformUpdate],
47    elapsed_time: f32,
48) -> Vec<EvaluatedMaterial> {
49    let mut evaluated = asset
50        .materials()
51        .iter()
52        .enumerate()
53        .map(|(index, material)| {
54            let mtoon = material.mtoon();
55            EvaluatedMaterial {
56                material_id: MaterialId::from_index(index),
57                base_color_factor: material.base_color_factor,
58                emissive_factor: material.emissive_factor,
59                shade_color_factor: mtoon
60                    .map(|value| value.shade_color.to_array())
61                    .unwrap_or([1.0; 3]),
62                matcap_factor: mtoon
63                    .map(|value| value.matcap_factor.to_array())
64                    .unwrap_or([1.0; 3]),
65                rim_color_factor: mtoon
66                    .map(|value| value.parametric_rim_color_factor.to_array())
67                    .unwrap_or([0.0; 3]),
68                outline_color_factor: mtoon
69                    .map(|value| value.outline_color_factor.to_array())
70                    .unwrap_or([0.0; 3]),
71                texture_transform: TextureTransform::default(),
72                uv_animation: mtoon
73                    .map(|value| UvAnimationState {
74                        scroll: [
75                            value.uv_animation_scroll_x_speed_factor * elapsed_time,
76                            value.uv_animation_scroll_y_speed_factor * elapsed_time,
77                        ],
78                        rotation: value.uv_animation_rotation_speed_factor * elapsed_time,
79                    })
80                    .unwrap_or_default(),
81            }
82        })
83        .collect::<Vec<_>>();
84
85    for update in color_updates {
86        let Some(material) = evaluated.get_mut(update.material_index() as usize) else {
87            continue;
88        };
89        let base = asset.base_color(update.material_index(), update.color_type());
90        let target = update.target_value();
91        let weight = update.weight();
92        match update.color_type() {
93            MaterialColorType::Color => {
94                accumulate(&mut material.base_color_factor, base, target, weight);
95            }
96            MaterialColorType::EmissionColor => {
97                accumulate_rgb(&mut material.emissive_factor, base, target, weight);
98            }
99            MaterialColorType::ShadeColor => {
100                accumulate_rgb(&mut material.shade_color_factor, base, target, weight);
101            }
102            MaterialColorType::MatcapColor => {
103                accumulate_rgb(&mut material.matcap_factor, base, target, weight);
104            }
105            MaterialColorType::RimColor => {
106                accumulate_rgb(&mut material.rim_color_factor, base, target, weight);
107            }
108            MaterialColorType::OutlineColor => {
109                accumulate_rgb(&mut material.outline_color_factor, base, target, weight);
110            }
111        }
112    }
113
114    for update in texture_updates {
115        let Some(material) = evaluated.get_mut(update.material_index() as usize) else {
116            continue;
117        };
118        for channel in 0..2 {
119            material.texture_transform.scale[channel] +=
120                (update.scale()[channel] - 1.0) * update.weight();
121            material.texture_transform.offset[channel] +=
122                update.offset()[channel] * update.weight();
123        }
124    }
125
126    for (value, source) in evaluated.iter_mut().zip(asset.materials()) {
127        for component in &mut value.emissive_factor {
128            *component *= source.emissive_strength();
129        }
130    }
131
132    evaluated
133}
134
135fn accumulate(current: &mut [f32; 4], base: [f32; 4], target: [f32; 4], weight: f32) {
136    for channel in 0..4 {
137        current[channel] += (target[channel] - base[channel]) * weight;
138    }
139}
140
141fn accumulate_rgb(current: &mut [f32; 3], base: [f32; 4], target: [f32; 4], weight: f32) {
142    for channel in 0..3 {
143        current[channel] += (target[channel] - base[channel]) * weight;
144    }
145}