morph_targets/
morph_targets.rs

1//! Controls morph targets in a loaded scene.
2//!
3//! Illustrates:
4//!
5//! - How to access and modify individual morph target weights.
6//!   See the `update_weights` system for details.
7//! - How to read morph target names in `name_morphs`.
8//! - How to play morph target animations in `setup_animations`.
9
10use bevy::prelude::*;
11use std::f32::consts::PI;
12
13fn main() {
14    App::new()
15        .add_plugins(DefaultPlugins.set(WindowPlugin {
16            primary_window: Some(Window {
17                title: "morph targets".to_string(),
18                ..default()
19            }),
20            ..default()
21        }))
22        .insert_resource(AmbientLight {
23            brightness: 150.0,
24            ..default()
25        })
26        .add_systems(Startup, setup)
27        .add_systems(Update, (name_morphs, setup_animations))
28        .run();
29}
30
31#[derive(Resource)]
32struct MorphData {
33    the_wave: Handle<AnimationClip>,
34    mesh: Handle<Mesh>,
35}
36
37fn setup(asset_server: Res<AssetServer>, mut commands: Commands) {
38    commands.insert_resource(MorphData {
39        the_wave: asset_server
40            .load(GltfAssetLabel::Animation(2).from_asset("models/animated/MorphStressTest.gltf")),
41        mesh: asset_server.load(
42            GltfAssetLabel::Primitive {
43                mesh: 0,
44                primitive: 0,
45            }
46            .from_asset("models/animated/MorphStressTest.gltf"),
47        ),
48    });
49    commands.spawn(SceneRoot(asset_server.load(
50        GltfAssetLabel::Scene(0).from_asset("models/animated/MorphStressTest.gltf"),
51    )));
52    commands.spawn((
53        DirectionalLight::default(),
54        Transform::from_rotation(Quat::from_rotation_z(PI / 2.0)),
55    ));
56    commands.spawn((
57        Camera3d::default(),
58        Transform::from_xyz(3.0, 2.1, 10.2).looking_at(Vec3::ZERO, Vec3::Y),
59    ));
60}
61
62/// Plays an [`AnimationClip`] from the loaded [`Gltf`] on the [`AnimationPlayer`] created by the spawned scene.
63fn setup_animations(
64    mut has_setup: Local<bool>,
65    mut commands: Commands,
66    mut players: Query<(Entity, &Name, &mut AnimationPlayer)>,
67    morph_data: Res<MorphData>,
68    mut graphs: ResMut<Assets<AnimationGraph>>,
69) {
70    if *has_setup {
71        return;
72    }
73    for (entity, name, mut player) in &mut players {
74        // The name of the entity in the GLTF scene containing the AnimationPlayer for our morph targets is "Main"
75        if name.as_str() != "Main" {
76            continue;
77        }
78
79        let (graph, animation) = AnimationGraph::from_clip(morph_data.the_wave.clone());
80        commands
81            .entity(entity)
82            .insert(AnimationGraphHandle(graphs.add(graph)));
83
84        player.play(animation).repeat();
85        *has_setup = true;
86    }
87}
88
89/// You can get the target names in their corresponding [`Mesh`].
90/// They are in the order of the weights.
91fn name_morphs(
92    mut has_printed: Local<bool>,
93    morph_data: Res<MorphData>,
94    meshes: Res<Assets<Mesh>>,
95) {
96    if *has_printed {
97        return;
98    }
99
100    let Some(mesh) = meshes.get(&morph_data.mesh) else {
101        return;
102    };
103    let Some(names) = mesh.morph_target_names() else {
104        return;
105    };
106
107    info!("Target names:");
108    for name in names {
109        info!("  {name}");
110    }
111    *has_printed = true;
112}