Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add checked methods to add vertex attributes to mesh only if values is not empty #17690

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions crates/bevy_mesh/src/mesh.rs
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,35 @@ impl Mesh {
.insert(attribute.id, MeshAttributeData { attribute, values });
}

/// Sets the data for a vertex attribute (position, normal, etc.) if not empty.
/// The name will often be one of the associated constants such
/// as [`Mesh::ATTRIBUTE_POSITION`].
///
/// `Aabb` of entities with modified mesh are not updated automatically.
///
/// # Panics
/// Panics when the format of the values does not match the attribute's format.
#[inline]
pub fn insert_attribute_if_not_empty(
&mut self,
attribute: MeshVertexAttribute,
values: impl Into<VertexAttributeValues>,
) {
let values = values.into();
if !values.is_empty() {
let values_format = VertexFormat::from(&values);
if values_format != attribute.format {
panic!(
"Failed to insert attribute. Invalid attribute format for {}. Given format is {values_format:?} but expected {:?}",
attribute.name, attribute.format
);
}

self.attributes
.insert(attribute.id, MeshAttributeData { attribute, values });
}
}

/// Consumes the mesh and returns a mesh with data set for a vertex attribute (position, normal, etc.).
/// The name will often be one of the associated constants such as [`Mesh::ATTRIBUTE_POSITION`].
///
Expand All @@ -257,6 +286,27 @@ impl Mesh {
self
}

/// Consumes the mesh and returns a mesh with data set for a vertex attribute (position, normal, etc.)
/// if it is not empty.
/// The name will often be one of the associated constants such as [`Mesh::ATTRIBUTE_POSITION`].
///
/// (Alternatively, you can use [`Mesh::insert_attribute`] to mutate an existing mesh in-place)
///
/// `Aabb` of entities with modified mesh are not updated automatically.
///
/// # Panics
/// Panics when the format of the values does not match the attribute's format.
#[must_use]
#[inline]
pub fn with_inserted_attribute_if_not_empty(
mut self,
attribute: MeshVertexAttribute,
values: impl Into<VertexAttributeValues>,
) -> Self {
self.insert_attribute_if_not_empty(attribute, values);
self
}

/// Removes the data for a vertex attribute
pub fn remove_attribute(
&mut self,
Expand Down