Path: blob/main/examples/animation/custom_skinned_mesh.rs
6592 views
//! Skinned mesh example with mesh and joints data defined in code.1//! Example taken from <https://github.com/KhronosGroup/glTF-Tutorials/blob/master/gltfTutorial/gltfTutorial_019_SimpleSkin.md>23use std::f32::consts::*;45use bevy::{6asset::RenderAssetUsages,7math::ops,8mesh::{9skinning::{SkinnedMesh, SkinnedMeshInverseBindposes},10Indices, PrimitiveTopology, VertexAttributeValues,11},12prelude::*,13};14use rand::{Rng, SeedableRng};15use rand_chacha::ChaCha8Rng;1617fn main() {18App::new()19.add_plugins(DefaultPlugins)20.insert_resource(AmbientLight {21brightness: 3000.0,22..default()23})24.add_systems(Startup, setup)25.add_systems(Update, joint_animation)26.run();27}2829/// Used to mark a joint to be animated in the [`joint_animation`] system.30#[derive(Component)]31struct AnimatedJoint(isize);3233/// Construct a mesh and a skeleton with 2 joints for that mesh,34/// and mark the second joint to be animated.35/// It is similar to the scene defined in `models/SimpleSkin/SimpleSkin.gltf`36fn setup(37mut commands: Commands,38asset_server: Res<AssetServer>,39mut meshes: ResMut<Assets<Mesh>>,40mut materials: ResMut<Assets<StandardMaterial>>,41mut skinned_mesh_inverse_bindposes_assets: ResMut<Assets<SkinnedMeshInverseBindposes>>,42) {43// Create a camera44commands.spawn((45Camera3d::default(),46Transform::from_xyz(2.5, 2.5, 9.0).looking_at(Vec3::ZERO, Vec3::Y),47));4849// Create inverse bindpose matrices for a skeleton consists of 2 joints50let inverse_bindposes = skinned_mesh_inverse_bindposes_assets.add(vec![51Mat4::from_translation(Vec3::new(-0.5, -1.0, 0.0)),52Mat4::from_translation(Vec3::new(-0.5, -1.0, 0.0)),53]);5455// Create a mesh56let mesh = Mesh::new(57PrimitiveTopology::TriangleList,58RenderAssetUsages::RENDER_WORLD,59)60// Set mesh vertex positions61.with_inserted_attribute(62Mesh::ATTRIBUTE_POSITION,63vec![64[0.0, 0.0, 0.0],65[1.0, 0.0, 0.0],66[0.0, 0.5, 0.0],67[1.0, 0.5, 0.0],68[0.0, 1.0, 0.0],69[1.0, 1.0, 0.0],70[0.0, 1.5, 0.0],71[1.0, 1.5, 0.0],72[0.0, 2.0, 0.0],73[1.0, 2.0, 0.0],74],75)76// Add UV coordinates that map the left half of the texture since its a 1 x77// 2 rectangle.78.with_inserted_attribute(79Mesh::ATTRIBUTE_UV_0,80vec![81[0.0, 0.00],82[0.5, 0.00],83[0.0, 0.25],84[0.5, 0.25],85[0.0, 0.50],86[0.5, 0.50],87[0.0, 0.75],88[0.5, 0.75],89[0.0, 1.00],90[0.5, 1.00],91],92)93// Set mesh vertex normals94.with_inserted_attribute(Mesh::ATTRIBUTE_NORMAL, vec![[0.0, 0.0, 1.0]; 10])95// Set mesh vertex joint indices for mesh skinning.96// Each vertex gets 4 indices used to address the `JointTransforms` array in the vertex shader97// as well as `SkinnedMeshJoint` array in the `SkinnedMesh` component.98// This means that a maximum of 4 joints can affect a single vertex.99.with_inserted_attribute(100Mesh::ATTRIBUTE_JOINT_INDEX,101// Need to be explicit here as [u16; 4] could be either Uint16x4 or Unorm16x4.102VertexAttributeValues::Uint16x4(vec![103[0, 0, 0, 0],104[0, 0, 0, 0],105[0, 1, 0, 0],106[0, 1, 0, 0],107[0, 1, 0, 0],108[0, 1, 0, 0],109[0, 1, 0, 0],110[0, 1, 0, 0],111[0, 1, 0, 0],112[0, 1, 0, 0],113]),114)115// Set mesh vertex joint weights for mesh skinning.116// Each vertex gets 4 joint weights corresponding to the 4 joint indices assigned to it.117// The sum of these weights should equal to 1.118.with_inserted_attribute(119Mesh::ATTRIBUTE_JOINT_WEIGHT,120vec![121[1.00, 0.00, 0.0, 0.0],122[1.00, 0.00, 0.0, 0.0],123[0.75, 0.25, 0.0, 0.0],124[0.75, 0.25, 0.0, 0.0],125[0.50, 0.50, 0.0, 0.0],126[0.50, 0.50, 0.0, 0.0],127[0.25, 0.75, 0.0, 0.0],128[0.25, 0.75, 0.0, 0.0],129[0.00, 1.00, 0.0, 0.0],130[0.00, 1.00, 0.0, 0.0],131],132)133// Tell bevy to construct triangles from a list of vertex indices,134// where each 3 vertex indices form a triangle.135.with_inserted_indices(Indices::U16(vec![1360, 1, 3, 0, 3, 2, 2, 3, 5, 2, 5, 4, 4, 5, 7, 4, 7, 6, 6, 7, 9, 6, 9, 8,137]));138139let mesh = meshes.add(mesh);140141// We're seeding the PRNG here to make this example deterministic for testing purposes.142// This isn't strictly required in practical use unless you need your app to be deterministic.143let mut rng = ChaCha8Rng::seed_from_u64(42);144145for i in -5..5 {146// Create joint entities147let joint_0 = commands148.spawn(Transform::from_xyz(149i as f32 * 1.5,1500.0,151// Move quads back a small amount to avoid Z-fighting and not152// obscure the transform gizmos.153-(i as f32 * 0.01).abs(),154))155.id();156let joint_1 = commands.spawn((AnimatedJoint(i), Transform::IDENTITY)).id();157158// Set joint_1 as a child of joint_0.159commands.entity(joint_0).add_children(&[joint_1]);160161// Each joint in this vector corresponds to each inverse bindpose matrix in `SkinnedMeshInverseBindposes`.162let joint_entities = vec![joint_0, joint_1];163164// Create skinned mesh renderer. Note that its transform doesn't affect the position of the mesh.165commands.spawn((166Mesh3d(mesh.clone()),167MeshMaterial3d(materials.add(StandardMaterial {168base_color: Color::srgb(169rng.random_range(0.0..1.0),170rng.random_range(0.0..1.0),171rng.random_range(0.0..1.0),172),173base_color_texture: Some(asset_server.load("textures/uv_checker_bw.png")),174..default()175})),176SkinnedMesh {177inverse_bindposes: inverse_bindposes.clone(),178joints: joint_entities,179},180));181}182}183184/// Animate the joint marked with [`AnimatedJoint`] component.185fn joint_animation(186time: Res<Time>,187mut query: Query<(&mut Transform, &AnimatedJoint)>,188mut gizmos: Gizmos,189) {190for (mut transform, animated_joint) in &mut query {191match animated_joint.0 {192-5 => {193transform.rotation =194Quat::from_rotation_x(FRAC_PI_2 * ops::sin(time.elapsed_secs()));195}196-4 => {197transform.rotation =198Quat::from_rotation_y(FRAC_PI_2 * ops::sin(time.elapsed_secs()));199}200-3 => {201transform.rotation =202Quat::from_rotation_z(FRAC_PI_2 * ops::sin(time.elapsed_secs()));203}204-2 => {205transform.scale.x = ops::sin(time.elapsed_secs()) + 1.0;206}207-1 => {208transform.scale.y = ops::sin(time.elapsed_secs()) + 1.0;209}2100 => {211transform.translation.x = 0.5 * ops::sin(time.elapsed_secs());212transform.translation.y = ops::cos(time.elapsed_secs());213}2141 => {215transform.translation.y = ops::sin(time.elapsed_secs());216transform.translation.z = ops::cos(time.elapsed_secs());217}2182 => {219transform.translation.x = ops::sin(time.elapsed_secs());220}2213 => {222transform.translation.y = ops::sin(time.elapsed_secs());223transform.scale.x = ops::sin(time.elapsed_secs()) + 1.0;224}225_ => (),226}227// Show transform228let mut axis = *transform;229axis.translation.x += animated_joint.0 as f32 * 1.5;230gizmos.axes(axis, 1.0);231}232}233234235