Skip to main content

AvatarRuntime

Struct AvatarRuntime 

Source
pub struct AvatarRuntime { /* private fields */ }
Expand description

A high-level VRM instance that owns controls, animation, and simulation.

Implementations§

Source§

impl AvatarRuntime

Source

pub fn new(asset: impl Into<Arc<Avatar>>) -> Self

Creates an independent runtime from an owned or shared immutable asset.

Examples found in repository?
examples/basic.rs (line 16)
9fn main() {
10    let path = std::env::args().nth(1).expect("usage: basic <avatar.vrm>");
11    let avatar = AvatarAsset::load(&path).expect("failed to load avatar");
12
13    println!("avatar: {}", avatar.meta().name());
14    println!("primitives: {}", avatar.primitives().len());
15
16    let mut runtime = AvatarRuntime::new(avatar);
17
18    // One frame with spring bones and constraints enabled by default.
19    let frame = runtime.update(1.0 / 60.0).expect("valid delta time");
20
21    // Bake fully transformed, renderer-ready CPU meshes on demand.
22    let meshes = frame.bake_cpu();
23    for mesh in &meshes {
24        println!(
25            "mesh(node {}): vertices={} indices={} topology={:?} material={:?}",
26            mesh.node_id,
27            mesh.positions.len(),
28            mesh.indices.len(),
29            mesh.topology,
30            mesh.material_id,
31        );
32    }
33}
More examples
Hide additional examples
examples/vrma.rs (line 20)
8fn main() -> Result<(), Box<dyn std::error::Error>> {
9    let mut arguments = std::env::args().skip(1);
10    let avatar_path = arguments
11        .next()
12        .expect("usage: vrma <avatar.vrm> <motion.vrma>");
13    let animation_path = arguments
14        .next()
15        .expect("usage: vrma <avatar.vrm> <motion.vrma>");
16
17    let avatar = AvatarAsset::load(avatar_path)?;
18    let animation = VrmAnimation::load(animation_path)?;
19    let duration = animation.duration();
20    let mut runtime = AvatarRuntime::new(avatar);
21
22    runtime.play(
23        animation,
24        PlaybackOptions {
25            mode: PlaybackMode::Once,
26            ..PlaybackOptions::default()
27        },
28    )?;
29
30    let delta_seconds = 1.0 / 60.0;
31    let frame_count = ((duration / delta_seconds).ceil() as usize).max(1) + 1;
32    for frame_index in 0..frame_count {
33        let (draw_count, bone_update_count) = {
34            let frame = runtime.update(delta_seconds)?;
35            (frame.gpu().draws().len(), frame.bone_updates().len())
36        };
37
38        if frame_index % 60 == 0 || !runtime.is_playing() {
39            println!(
40                "time={:.3}s draws={} bone_updates={}",
41                runtime.playback_time().unwrap_or(0.0),
42                draw_count,
43                bone_update_count,
44            );
45        }
46        if !runtime.is_playing() {
47            break;
48        }
49    }
50
51    Ok(())
52}
Source

pub fn asset(&self) -> &Avatar

Returns the immutable avatar asset evaluated by this runtime.

Source

pub fn shared_asset(&self) -> Arc<Avatar> ⓘ

Clones the shared handle to the immutable avatar asset.

Source

pub fn options(&self) -> RuntimeOptions

Returns the currently active runtime switches.

Source

pub fn set_constraints_enabled(&mut self, enabled: bool)

Enables or disables constraint evaluation for subsequent frames.

Source

pub fn set_spring_bone_enabled(&mut self, enabled: bool)

Enables or disables spring-bone simulation for subsequent frames.

Source

pub fn set_expression( &mut self, name: &str, weight: f32, ) -> Result<(), ControlError>

Sets a persistent expression weight.

Source

pub fn clear_expression(&mut self, name: &str) -> Result<(), ControlError>

Removes the persistent weight for one expression.

Source

pub fn clear_expressions(&mut self)

Removes all persistent expression weights.

Source

pub fn expression_weight(&self, name: &str) -> Result<f32, ControlError>

Returns a persistent expression weight, or zero if it was not set.

Source

pub fn set_bone_rotation( &mut self, bone: HumanBone, rotation: Quat, ) -> Result<(), ControlError>

Sets a normalized persistent local-space rotation for a humanoid bone.

Source

pub fn clear_bone_rotation( &mut self, bone: HumanBone, ) -> Result<(), ControlError>

Removes the persistent rotation override for one humanoid bone.

Source

pub fn clear_bone_rotations(&mut self)

Removes all persistent humanoid bone rotation overrides.

Source

pub fn set_bone_translation( &mut self, bone: HumanBone, translation: Vec3, ) -> Result<(), ControlError>

Sets a persistent local-space translation for a humanoid bone.

Source

pub fn clear_bone_translation( &mut self, bone: HumanBone, ) -> Result<(), ControlError>

Removes the persistent translation override for one humanoid bone.

Source

pub fn clear_bone_translations(&mut self)

Removes all persistent humanoid bone translation overrides.

Source

pub fn set_look_at_target( &mut self, target: Option<Vec3>, ) -> Result<(), ControlError>

Sets the world-space point that the avatar should look toward.

Source

pub fn clear_look_at_target(&mut self)

Removes the persistent look-at target.

Source

pub fn play( &mut self, clip: impl Into<Arc<VrmAnimation>>, options: PlaybackOptions, ) -> Result<(), ControlError>

Validates and starts a clip from time zero.

Loaded VRMA clips are retargeted from their source rest pose to this runtime’s avatar. PlaybackOptions::scale_hips_translation controls whether Hips motion is scaled by the source and target avatar heights.

§Errors

Returns ControlError::InvalidAnimation when the clip contains an invalid track or when the playback speed is negative or non-finite.

Examples found in repository?
examples/vrma.rs (lines 22-28)
8fn main() -> Result<(), Box<dyn std::error::Error>> {
9    let mut arguments = std::env::args().skip(1);
10    let avatar_path = arguments
11        .next()
12        .expect("usage: vrma <avatar.vrm> <motion.vrma>");
13    let animation_path = arguments
14        .next()
15        .expect("usage: vrma <avatar.vrm> <motion.vrma>");
16
17    let avatar = AvatarAsset::load(avatar_path)?;
18    let animation = VrmAnimation::load(animation_path)?;
19    let duration = animation.duration();
20    let mut runtime = AvatarRuntime::new(avatar);
21
22    runtime.play(
23        animation,
24        PlaybackOptions {
25            mode: PlaybackMode::Once,
26            ..PlaybackOptions::default()
27        },
28    )?;
29
30    let delta_seconds = 1.0 / 60.0;
31    let frame_count = ((duration / delta_seconds).ceil() as usize).max(1) + 1;
32    for frame_index in 0..frame_count {
33        let (draw_count, bone_update_count) = {
34            let frame = runtime.update(delta_seconds)?;
35            (frame.gpu().draws().len(), frame.bone_updates().len())
36        };
37
38        if frame_index % 60 == 0 || !runtime.is_playing() {
39            println!(
40                "time={:.3}s draws={} bone_updates={}",
41                runtime.playback_time().unwrap_or(0.0),
42                draw_count,
43                bone_update_count,
44            );
45        }
46        if !runtime.is_playing() {
47            break;
48        }
49    }
50
51    Ok(())
52}
Source

pub fn pause(&mut self)

Pauses the current clip without discarding its time.

Source

pub fn resume(&mut self)

Resumes the current clip, if one is loaded.

Source

pub fn set_playback_speed(&mut self, speed: f32) -> Result<(), ControlError>

Changes playback speed without replacing or rewinding the clip.

Source

pub fn seek(&mut self, time: f32) -> Result<(), ControlError>

Seeks the current clip to a non-negative time clamped to its duration.

Source

pub fn stop(&mut self)

Stops and discards the current animation playback state.

Source

pub fn playback_time(&self) -> Option<f32>

Returns the current clip time, or None when no clip is loaded.

Examples found in repository?
examples/vrma.rs (line 41)
8fn main() -> Result<(), Box<dyn std::error::Error>> {
9    let mut arguments = std::env::args().skip(1);
10    let avatar_path = arguments
11        .next()
12        .expect("usage: vrma <avatar.vrm> <motion.vrma>");
13    let animation_path = arguments
14        .next()
15        .expect("usage: vrma <avatar.vrm> <motion.vrma>");
16
17    let avatar = AvatarAsset::load(avatar_path)?;
18    let animation = VrmAnimation::load(animation_path)?;
19    let duration = animation.duration();
20    let mut runtime = AvatarRuntime::new(avatar);
21
22    runtime.play(
23        animation,
24        PlaybackOptions {
25            mode: PlaybackMode::Once,
26            ..PlaybackOptions::default()
27        },
28    )?;
29
30    let delta_seconds = 1.0 / 60.0;
31    let frame_count = ((duration / delta_seconds).ceil() as usize).max(1) + 1;
32    for frame_index in 0..frame_count {
33        let (draw_count, bone_update_count) = {
34            let frame = runtime.update(delta_seconds)?;
35            (frame.gpu().draws().len(), frame.bone_updates().len())
36        };
37
38        if frame_index % 60 == 0 || !runtime.is_playing() {
39            println!(
40                "time={:.3}s draws={} bone_updates={}",
41                runtime.playback_time().unwrap_or(0.0),
42                draw_count,
43                bone_update_count,
44            );
45        }
46        if !runtime.is_playing() {
47            break;
48        }
49    }
50
51    Ok(())
52}
Source

pub fn is_playing(&self) -> bool

Reports whether a loaded clip is currently advancing.

Examples found in repository?
examples/vrma.rs (line 38)
8fn main() -> Result<(), Box<dyn std::error::Error>> {
9    let mut arguments = std::env::args().skip(1);
10    let avatar_path = arguments
11        .next()
12        .expect("usage: vrma <avatar.vrm> <motion.vrma>");
13    let animation_path = arguments
14        .next()
15        .expect("usage: vrma <avatar.vrm> <motion.vrma>");
16
17    let avatar = AvatarAsset::load(avatar_path)?;
18    let animation = VrmAnimation::load(animation_path)?;
19    let duration = animation.duration();
20    let mut runtime = AvatarRuntime::new(avatar);
21
22    runtime.play(
23        animation,
24        PlaybackOptions {
25            mode: PlaybackMode::Once,
26            ..PlaybackOptions::default()
27        },
28    )?;
29
30    let delta_seconds = 1.0 / 60.0;
31    let frame_count = ((duration / delta_seconds).ceil() as usize).max(1) + 1;
32    for frame_index in 0..frame_count {
33        let (draw_count, bone_update_count) = {
34            let frame = runtime.update(delta_seconds)?;
35            (frame.gpu().draws().len(), frame.bone_updates().len())
36        };
37
38        if frame_index % 60 == 0 || !runtime.is_playing() {
39            println!(
40                "time={:.3}s draws={} bone_updates={}",
41                runtime.playback_time().unwrap_or(0.0),
42                draw_count,
43                bone_update_count,
44            );
45        }
46        if !runtime.is_playing() {
47            break;
48        }
49    }
50
51    Ok(())
52}
Source

pub fn update(&mut self, dt: f32) -> Result<FrameView<'_>, RuntimeError>

Evaluates one frame while retaining all persistent controls.

dt is elapsed time in seconds. Animation, expressions, LookAt, node constraints, SpringBone, world transforms, skinning palettes, and dynamic material values are evaluated in their runtime order.

§Errors

Returns RuntimeError::InvalidDeltaTime for a negative or non-finite delta and an overflow variant when a material or animation clock cannot advance without becoming non-finite.

Invalid time arithmetic returns an error before either clock or the cached frame is mutated.

Examples found in repository?
examples/basic.rs (line 19)
9fn main() {
10    let path = std::env::args().nth(1).expect("usage: basic <avatar.vrm>");
11    let avatar = AvatarAsset::load(&path).expect("failed to load avatar");
12
13    println!("avatar: {}", avatar.meta().name());
14    println!("primitives: {}", avatar.primitives().len());
15
16    let mut runtime = AvatarRuntime::new(avatar);
17
18    // One frame with spring bones and constraints enabled by default.
19    let frame = runtime.update(1.0 / 60.0).expect("valid delta time");
20
21    // Bake fully transformed, renderer-ready CPU meshes on demand.
22    let meshes = frame.bake_cpu();
23    for mesh in &meshes {
24        println!(
25            "mesh(node {}): vertices={} indices={} topology={:?} material={:?}",
26            mesh.node_id,
27            mesh.positions.len(),
28            mesh.indices.len(),
29            mesh.topology,
30            mesh.material_id,
31        );
32    }
33}
More examples
Hide additional examples
examples/vrma.rs (line 34)
8fn main() -> Result<(), Box<dyn std::error::Error>> {
9    let mut arguments = std::env::args().skip(1);
10    let avatar_path = arguments
11        .next()
12        .expect("usage: vrma <avatar.vrm> <motion.vrma>");
13    let animation_path = arguments
14        .next()
15        .expect("usage: vrma <avatar.vrm> <motion.vrma>");
16
17    let avatar = AvatarAsset::load(avatar_path)?;
18    let animation = VrmAnimation::load(animation_path)?;
19    let duration = animation.duration();
20    let mut runtime = AvatarRuntime::new(avatar);
21
22    runtime.play(
23        animation,
24        PlaybackOptions {
25            mode: PlaybackMode::Once,
26            ..PlaybackOptions::default()
27        },
28    )?;
29
30    let delta_seconds = 1.0 / 60.0;
31    let frame_count = ((duration / delta_seconds).ceil() as usize).max(1) + 1;
32    for frame_index in 0..frame_count {
33        let (draw_count, bone_update_count) = {
34            let frame = runtime.update(delta_seconds)?;
35            (frame.gpu().draws().len(), frame.bone_updates().len())
36        };
37
38        if frame_index % 60 == 0 || !runtime.is_playing() {
39            println!(
40                "time={:.3}s draws={} bone_updates={}",
41                runtime.playback_time().unwrap_or(0.0),
42                draw_count,
43                bone_update_count,
44            );
45        }
46        if !runtime.is_playing() {
47            break;
48        }
49    }
50
51    Ok(())
52}
Source

pub fn reset(&mut self)

Resets controls, simulation, and all cached output to the rest state.

Source

pub fn instance_mut(&mut self) -> &mut AvatarInstance

Provides mutable low-level state for custom evaluation pipelines.

Source

pub fn spring_simulator_mut(&mut self) -> &mut SpringBoneSimulator

Provides mutable access to the spring simulator for advanced use.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.