Skip to main content

AvatarAsset

Struct AvatarAsset 

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

A loaded VRM 1.0 avatar: the parsed VRM data (meta, humanoid, expressions, look-at, first-person, spring bones, constraints) plus the renderable glTF assets (nodes, primitives, materials, skins, images).

Load it with AvatarAsset::from_bytes / AvatarAsset::load, or compose it programmatically with crate::AvatarAssetBuilder. Drive a frame with crate::AvatarRuntime.

Implementations§

Source§

impl AvatarAsset

Source

pub fn meta(&self) -> &AvatarMeta

Returns a reference to the AvatarMeta.

Examples found in repository?
examples/basic.rs (line 13)
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}
Source

pub fn humanoid(&self) -> &Humanoid

Returns a reference to the Humanoid.

Source

pub fn expressions(&self) -> &Expressions

Returns a reference to the Expressions.

Source

pub fn primitives(&self) -> &[RenderPrimitive]

Returns the list of RenderPrimitives parsed from the model.

Examples found in repository?
examples/basic.rs (line 14)
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}
Source

pub fn primitive(&self, id: PrimitiveId) -> Option<&RenderPrimitive>

Resolves a type-safe primitive identifier.

Source

pub fn look_at(&self) -> Option<&LookAt>

Returns the LookAt configuration, if present.

Source

pub fn images(&self) -> &[AvatarImage]

Returns the list of AvatarImages parsed from the model.

Source

pub fn image(&self, id: ImageId) -> Option<&AvatarImage>

Resolves a type-safe image identifier.

Source

pub fn materials(&self) -> &[Material]

Returns common glTF materials with optional MToon parameters.

Source

pub fn material(&self, id: MaterialId) -> Option<&Material>

Resolves a type-safe material identifier.

Source

pub fn textures(&self) -> &[AvatarTexture]

Returns the glTF texture objects, kept separate from image data.

Source

pub fn texture(&self, id: TextureId) -> Option<&AvatarTexture>

Resolves a type-safe texture identifier.

Source

pub fn base_color( &self, material_index: u32, color_type: MaterialColorType, ) -> [f32; 4]

Returns the initial (base) color for the given material attribute.

Returns white [1, 1, 1, 1] when the material index is out of range or the material does not support color_type.

Source

pub fn instantiate(&self) -> AvatarInstance

Creates a mutable runtime state (expression weights, bone rotations, look-at target) detached from this avatar.

Source

pub fn skins(&self) -> &[Skin]

Returns the list of Skins.

Source

pub fn skin(&self, id: SkinId) -> Option<&Skin>

Resolves a type-safe skin identifier.

Source

pub fn node_constraints(&self) -> &[NodeConstraint]

Returns the list of NodeConstraints.

Source

pub fn spring_bone(&self) -> &SpringBone

Returns the SpringBone configuration.

Source

pub fn first_person(&self) -> &FirstPerson

Returns the FirstPerson configuration.

Source

pub fn nodes(&self) -> &[AvatarNode]

Returns the parsed node tree.

Source

pub fn node(&self, id: NodeId) -> Option<&AvatarNode>

Resolves a type-safe node identifier.

Source

pub fn compute_world_matrices(&self, bone_updates: &[BoneUpdate]) -> Vec<Mat4>

Computes the world transform matrix of every node, applying the given bone rotations.

Source

pub fn compute_joint_matrices( &self, skin: &Skin, bone_updates: &[BoneUpdate], ) -> Vec<Mat4>

Computes the joint matrices for skin, applying the given bone rotations.

Source

pub fn vrmc_vrm(&self) -> Option<&VRMCVrmSchema>

Returns the raw VRMCVrmSchema this avatar was parsed from.

Source

pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self, LoadError>

Loads and parses a VRM avatar from a file path.

Relative buffer and image URIs are resolved against the file’s parent directory, including percent-encoded image paths.

Source

pub fn from_bytes(bytes: &[u8]) -> Result<Self, LoadError>

Parses a VRM avatar from an in-memory byte slice.

Images must be embedded in buffer views or PNG/JPEG data URIs. Use Self::from_file when the document contains external references.

Source

pub fn from_file_with_options<P: AsRef<Path>>( path: P, options: LoadOptions, ) -> Result<LoadOutcome, LoadError>

Loads an avatar and returns any diagnostics produced by the selected validation mode. Relative buffer and image URIs are resolved against the file’s parent directory.

Source

pub fn from_bytes_with_options( bytes: &[u8], options: LoadOptions, ) -> Result<LoadOutcome, LoadError>

Parses an avatar and returns diagnostics for recoverable violations. Unresolved external buffer and image references are rejected.

Source

pub fn load<P: AsRef<Path>>(path: P) -> Result<Self, LoadError>

Loads a VRM 1.0 asset from a file using strict validation.

Relative external buffers and images are resolved against the file’s parent directory. Use Self::load_with_options to collect diagnostics from permissive validation.

§Errors

Returns crate::LoadError when the file cannot be read, its glTF or VRM data is invalid, an image cannot be decoded, or it requires an unsupported extension.

§Examples
use vrm_runtime::AvatarAsset;

let avatar = AvatarAsset::load("avatar.vrm")?;
println!("{}", avatar.meta().name());
Examples found in repository?
examples/basic.rs (line 11)
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 17)
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 load_with_options<P: AsRef<Path>>( path: P, options: LoadOptions, ) -> Result<LoadOutcome, LoadError>

Loads a VRM asset from a file with explicit validation options.

Source

pub const fn capabilities() -> Capabilities

Returns the feature set implemented by this crate version.

Trait Implementations§

Source§

impl Clone for AvatarAsset

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for AvatarAsset

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. 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> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
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.