Add Mesh transformation (#11454)

# Objective

It can sometimes be useful to transform actual `Mesh` data without
needing to change the `Transform` of an entity. For example, one might
want to spawn a circle mesh facing up instead of facing Z, or to spawn a
mesh slightly offset without needing child entities.

## Solution

Add `transform_by` and `transformed_by` methods to `Mesh`. They take a
`Transform` and apply the translation, rotation, and scale to vertex
positions, and the rotation to normals and tangents.

In the `load_gltf` example, with this system:

```rust
fn transform(time: Res<Time>, mut q: Query<&mut Handle<Mesh>>, mut meshes: ResMut<Assets<Mesh>>) {
    let sin = 0.0025 * time.elapsed_seconds().sin();

    for mesh_handle in &mut q {
        if let Some(mesh) = meshes.get_mut(mesh_handle.clone_weak()) {
            let transform =
                Transform::from_rotation(Quat::from_rotation_y(0.75 * time.delta_seconds()))
                    .with_scale(Vec3::splat(1.0 + sin));
            mesh.transform_by(transform);
        }
    }
}
```

it looks like this:


https://github.com/bevyengine/bevy/assets/57632562/60432456-6d28-4d06-9c94-2f4148f5acd5
This commit is contained in:
Joona Aalto 2024-01-29 18:34:19 +02:00 committed by GitHub
parent 92567490a9
commit 70f7d9598a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -1,5 +1,6 @@
mod conversions; mod conversions;
pub mod skinning; pub mod skinning;
use bevy_transform::components::Transform;
pub use wgpu::PrimitiveTopology; pub use wgpu::PrimitiveTopology;
use crate::{ use crate::{
@ -561,6 +562,60 @@ impl Mesh {
Ok(self) Ok(self)
} }
/// Transforms the vertex positions, normals, and tangents of the mesh by the given [`Transform`].
pub fn transformed_by(mut self, transform: Transform) -> Self {
self.transform_by(transform);
self
}
/// Transforms the vertex positions, normals, and tangents of the mesh in place by the given [`Transform`].
pub fn transform_by(&mut self, transform: Transform) {
// Needed when transforming normals and tangents
let covector_scale = transform.scale.yzx() * transform.scale.zxy();
debug_assert!(
covector_scale != Vec3::ZERO,
"mesh transform scale cannot be zero on more than one axis"
);
if let Some(VertexAttributeValues::Float32x3(ref mut positions)) =
self.attribute_mut(Mesh::ATTRIBUTE_POSITION)
{
// Apply scale, rotation, and translation to vertex positions
positions
.iter_mut()
.for_each(|pos| *pos = transform.transform_point(Vec3::from_slice(pos)).to_array());
}
// No need to transform normals or tangents if rotation is near identity and scale is uniform
if transform.rotation.is_near_identity()
&& transform.scale.x == transform.scale.y
&& transform.scale.y == transform.scale.z
{
return;
}
if let Some(VertexAttributeValues::Float32x3(ref mut normals)) =
self.attribute_mut(Mesh::ATTRIBUTE_NORMAL)
{
// Transform normals, taking into account non-uniform scaling and rotation
normals.iter_mut().for_each(|normal| {
let scaled_normal = Vec3::from_slice(normal) * covector_scale;
*normal = (transform.rotation * scaled_normal.normalize_or_zero()).to_array();
});
}
if let Some(VertexAttributeValues::Float32x3(ref mut tangents)) =
self.attribute_mut(Mesh::ATTRIBUTE_TANGENT)
{
// Transform tangents, taking into account non-uniform scaling and rotation
tangents.iter_mut().for_each(|tangent| {
let scaled_tangent = Vec3::from_slice(tangent) * covector_scale;
*tangent = (transform.rotation * scaled_tangent.normalize_or_zero()).to_array();
});
}
}
/// Compute the Axis-Aligned Bounding Box of the mesh vertices in model space /// Compute the Axis-Aligned Bounding Box of the mesh vertices in model space
/// ///
/// Returns `None` if `self` doesn't have [`Mesh::ATTRIBUTE_POSITION`] of /// Returns `None` if `self` doesn't have [`Mesh::ATTRIBUTE_POSITION`] of
@ -646,6 +701,14 @@ impl Mesh {
} }
} }
impl core::ops::Mul<Mesh> for Transform {
type Output = Mesh;
fn mul(self, rhs: Mesh) -> Self::Output {
rhs.transformed_by(self)
}
}
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct MeshVertexAttribute { pub struct MeshVertexAttribute {
/// The friendly name of the vertex attribute /// The friendly name of the vertex attribute