use bevy_transform::components::Transform;
pub use wgpu_types::PrimitiveTopology;
use super::{
skinning::{SkinnedMeshBounds, SkinnedMeshBoundsError},
triangle_area_normal, triangle_normal, FourIterators, Indices, MeshAttributeData,
MeshTrianglesError, MeshVertexAttribute, MeshVertexAttributeId, MeshVertexBufferLayout,
MeshVertexBufferLayoutRef, MeshVertexBufferLayouts, MeshWindingInvertError,
VertexAttributeValues, VertexBufferLayout,
};
#[cfg(feature = "morph")]
use crate::morph::MorphAttributes;
#[cfg(feature = "serialize")]
use crate::SerializedMeshAttributeData;
use alloc::collections::BTreeMap;
use bevy_asset::{Asset, RenderAssetUsages};
use bevy_math::{bounding::Aabb3d, primitives::Triangle3d, *};
use bevy_platform::collections::{hash_map, HashMap};
use bevy_reflect::{std_traits::ReflectDefault, Reflect};
use bytemuck::cast_slice;
use core::hash::{Hash, Hasher};
use core::ptr;
#[cfg(feature = "serialize")]
use serde::{Deserialize, Serialize};
use thiserror::Error;
use tracing::warn;
use wgpu_types::{VertexAttribute, VertexFormat, VertexStepMode, WriteOnly};
pub const INDEX_BUFFER_ASSET_INDEX: u64 = 0;
pub const VERTEX_ATTRIBUTE_BUFFER_ID: u64 = 10;
#[derive(Error, Debug, Clone)]
pub enum MeshAccessError {
#[error("The mesh vertex/index data has been extracted to the RenderWorld (via `Mesh::asset_usage`)")]
ExtractedToRenderWorld,
#[error("The requested mesh data wasn't found in this mesh")]
NotFound,
}
const MESH_EXTRACTED_ERROR: &str = "Mesh has been extracted to RenderWorld. To access vertex attributes, the mesh `asset_usage` must include `MAIN_WORLD`";
#[derive(Debug, Clone, PartialEq, Reflect, Default)]
enum MeshExtractableData<T> {
Data(T),
#[default]
NoData,
ExtractedToRenderWorld,
}
impl<T> MeshExtractableData<T> {
fn as_ref(&self) -> Result<&T, MeshAccessError> {
match self {
MeshExtractableData::Data(data) => Ok(data),
MeshExtractableData::NoData => Err(MeshAccessError::NotFound),
MeshExtractableData::ExtractedToRenderWorld => {
Err(MeshAccessError::ExtractedToRenderWorld)
}
}
}
fn as_ref_option(&self) -> Result<Option<&T>, MeshAccessError> {
match self {
MeshExtractableData::Data(data) => Ok(Some(data)),
MeshExtractableData::NoData => Ok(None),
MeshExtractableData::ExtractedToRenderWorld => {
Err(MeshAccessError::ExtractedToRenderWorld)
}
}
}
fn as_mut(&mut self) -> Result<&mut T, MeshAccessError> {
match self {
MeshExtractableData::Data(data) => Ok(data),
MeshExtractableData::NoData => Err(MeshAccessError::NotFound),
MeshExtractableData::ExtractedToRenderWorld => {
Err(MeshAccessError::ExtractedToRenderWorld)
}
}
}
fn as_mut_option(&mut self) -> Result<Option<&mut T>, MeshAccessError> {
match self {
MeshExtractableData::Data(data) => Ok(Some(data)),
MeshExtractableData::NoData => Ok(None),
MeshExtractableData::ExtractedToRenderWorld => {
Err(MeshAccessError::ExtractedToRenderWorld)
}
}
}
fn extract(&mut self) -> Result<MeshExtractableData<T>, MeshAccessError> {
match core::mem::replace(self, MeshExtractableData::ExtractedToRenderWorld) {
MeshExtractableData::ExtractedToRenderWorld => {
Err(MeshAccessError::ExtractedToRenderWorld)
}
not_extracted => Ok(not_extracted),
}
}
fn replace(
&mut self,
data: impl Into<MeshExtractableData<T>>,
) -> Result<Option<T>, MeshAccessError> {
match core::mem::replace(self, data.into()) {
MeshExtractableData::ExtractedToRenderWorld => {
*self = MeshExtractableData::ExtractedToRenderWorld;
Err(MeshAccessError::ExtractedToRenderWorld)
}
MeshExtractableData::Data(t) => Ok(Some(t)),
MeshExtractableData::NoData => Ok(None),
}
}
}
impl<T> From<Option<T>> for MeshExtractableData<T> {
fn from(value: Option<T>) -> Self {
match value {
Some(data) => MeshExtractableData::Data(data),
None => MeshExtractableData::NoData,
}
}
}
#[derive(Asset, Debug, Clone, Reflect, PartialEq)]
#[reflect(Clone)]
pub struct Mesh {
#[reflect(ignore, clone)]
primitive_topology: PrimitiveTopology,
#[reflect(ignore, clone)]
attributes: MeshExtractableData<BTreeMap<MeshVertexAttributeId, MeshAttributeData>>,
indices: MeshExtractableData<Indices>,
#[cfg(feature = "morph")]
morph_targets: MeshExtractableData<Vec<MorphAttributes>>,
#[cfg(feature = "morph")]
morph_target_names: MeshExtractableData<Vec<String>>,
pub asset_usage: RenderAssetUsages,
pub enable_raytracing: bool,
pub final_aabb: Option<Aabb3d>,
skinned_mesh_bounds: Option<SkinnedMeshBounds>,
}
impl Mesh {
pub const ATTRIBUTE_POSITION: MeshVertexAttribute =
MeshVertexAttribute::new("Vertex_Position", 0, VertexFormat::Float32x3);
pub const ATTRIBUTE_NORMAL: MeshVertexAttribute =
MeshVertexAttribute::new("Vertex_Normal", 1, VertexFormat::Float32x3);
pub const ATTRIBUTE_UV_0: MeshVertexAttribute =
MeshVertexAttribute::new("Vertex_Uv", 2, VertexFormat::Float32x2);
pub const ATTRIBUTE_UV_1: MeshVertexAttribute =
MeshVertexAttribute::new("Vertex_Uv_1", 3, VertexFormat::Float32x2);
pub const ATTRIBUTE_TANGENT: MeshVertexAttribute =
MeshVertexAttribute::new("Vertex_Tangent", 4, VertexFormat::Float32x4);
pub const ATTRIBUTE_COLOR: MeshVertexAttribute =
MeshVertexAttribute::new("Vertex_Color", 5, VertexFormat::Float32x4);
pub const ATTRIBUTE_JOINT_WEIGHT: MeshVertexAttribute =
MeshVertexAttribute::new("Vertex_JointWeight", 6, VertexFormat::Float32x4);
pub const ATTRIBUTE_JOINT_INDEX: MeshVertexAttribute =
MeshVertexAttribute::new("Vertex_JointIndex", 7, VertexFormat::Uint16x4);
pub const FIRST_AVAILABLE_CUSTOM_ATTRIBUTE: u64 = 8;
pub fn new(primitive_topology: PrimitiveTopology, asset_usage: RenderAssetUsages) -> Self {
Mesh {
primitive_topology,
attributes: MeshExtractableData::Data(Default::default()),
indices: MeshExtractableData::NoData,
#[cfg(feature = "morph")]
morph_targets: MeshExtractableData::NoData,
#[cfg(feature = "morph")]
morph_target_names: MeshExtractableData::NoData,
asset_usage,
enable_raytracing: true,
final_aabb: None,
skinned_mesh_bounds: None,
}
}
pub fn primitive_topology(&self) -> PrimitiveTopology {
self.primitive_topology
}
#[inline]
pub fn insert_attribute(
&mut self,
attribute: MeshVertexAttribute,
values: impl Into<VertexAttributeValues>,
) {
self.try_insert_attribute(attribute, values)
.expect(MESH_EXTRACTED_ERROR);
}
#[inline]
pub fn try_insert_attribute(
&mut self,
attribute: MeshVertexAttribute,
values: impl Into<VertexAttributeValues>,
) -> Result<(), MeshAccessError> {
let values = values.into();
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
.as_mut()?
.insert(attribute.id, MeshAttributeData { attribute, values });
Ok(())
}
#[must_use]
#[inline]
pub fn with_inserted_attribute(
mut self,
attribute: MeshVertexAttribute,
values: impl Into<VertexAttributeValues>,
) -> Self {
self.insert_attribute(attribute, values);
self
}
#[inline]
pub fn try_with_inserted_attribute(
mut self,
attribute: MeshVertexAttribute,
values: impl Into<VertexAttributeValues>,
) -> Result<Self, MeshAccessError> {
self.try_insert_attribute(attribute, values)?;
Ok(self)
}
pub fn remove_attribute(
&mut self,
attribute: impl Into<MeshVertexAttributeId>,
) -> Option<VertexAttributeValues> {
self.attributes
.as_mut()
.expect(MESH_EXTRACTED_ERROR)
.remove(&attribute.into())
.map(|data| data.values)
}
pub fn try_remove_attribute(
&mut self,
attribute: impl Into<MeshVertexAttributeId>,
) -> Result<VertexAttributeValues, MeshAccessError> {
Ok(self
.attributes
.as_mut()?
.remove(&attribute.into())
.ok_or(MeshAccessError::NotFound)?
.values)
}
#[must_use]
pub fn with_removed_attribute(mut self, attribute: impl Into<MeshVertexAttributeId>) -> Self {
self.remove_attribute(attribute);
self
}
pub fn try_with_removed_attribute(
mut self,
attribute: impl Into<MeshVertexAttributeId>,
) -> Result<Self, MeshAccessError> {
self.try_remove_attribute(attribute)?;
Ok(self)
}
#[inline]
pub fn contains_attribute(&self, id: impl Into<MeshVertexAttributeId>) -> bool {
self.attributes
.as_ref()
.expect(MESH_EXTRACTED_ERROR)
.contains_key(&id.into())
}
#[inline]
pub fn try_contains_attribute(
&self,
id: impl Into<MeshVertexAttributeId>,
) -> Result<bool, MeshAccessError> {
Ok(self.attributes.as_ref()?.contains_key(&id.into()))
}
#[inline]
pub fn attribute(
&self,
id: impl Into<MeshVertexAttributeId>,
) -> Option<&VertexAttributeValues> {
self.try_attribute_option(id).expect(MESH_EXTRACTED_ERROR)
}
#[inline]
pub fn try_attribute(
&self,
id: impl Into<MeshVertexAttributeId>,
) -> Result<&VertexAttributeValues, MeshAccessError> {
self.try_attribute_option(id)?
.ok_or(MeshAccessError::NotFound)
}
#[inline]
pub fn try_attribute_option(
&self,
id: impl Into<MeshVertexAttributeId>,
) -> Result<Option<&VertexAttributeValues>, MeshAccessError> {
Ok(self
.attributes
.as_ref()?
.get(&id.into())
.map(|data| &data.values))
}
#[inline]
pub(crate) fn try_attribute_data(
&self,
id: impl Into<MeshVertexAttributeId>,
) -> Result<Option<&MeshAttributeData>, MeshAccessError> {
Ok(self.attributes.as_ref()?.get(&id.into()))
}
#[inline]
pub fn attribute_mut(
&mut self,
id: impl Into<MeshVertexAttributeId>,
) -> Option<&mut VertexAttributeValues> {
self.try_attribute_mut_option(id)
.expect(MESH_EXTRACTED_ERROR)
}
#[inline]
pub fn try_attribute_mut(
&mut self,
id: impl Into<MeshVertexAttributeId>,
) -> Result<&mut VertexAttributeValues, MeshAccessError> {
self.try_attribute_mut_option(id)?
.ok_or(MeshAccessError::NotFound)
}
#[inline]
pub fn try_attribute_mut_option(
&mut self,
id: impl Into<MeshVertexAttributeId>,
) -> Result<Option<&mut VertexAttributeValues>, MeshAccessError> {
Ok(self
.attributes
.as_mut()?
.get_mut(&id.into())
.map(|data| &mut data.values))
}
pub fn attributes(
&self,
) -> impl Iterator<Item = (&MeshVertexAttribute, &VertexAttributeValues)> {
self.try_attributes().expect(MESH_EXTRACTED_ERROR)
}
pub fn try_attributes(
&self,
) -> Result<impl Iterator<Item = (&MeshVertexAttribute, &VertexAttributeValues)>, MeshAccessError>
{
Ok(self
.attributes
.as_ref()?
.values()
.map(|data| (&data.attribute, &data.values)))
}
pub fn attributes_mut(
&mut self,
) -> impl Iterator<Item = (&MeshVertexAttribute, &mut VertexAttributeValues)> {
self.try_attributes_mut().expect(MESH_EXTRACTED_ERROR)
}
pub fn try_attributes_mut(
&mut self,
) -> Result<
impl Iterator<Item = (&MeshVertexAttribute, &mut VertexAttributeValues)>,
MeshAccessError,
> {
Ok(self
.attributes
.as_mut()?
.values_mut()
.map(|data| (&data.attribute, &mut data.values)))
}
#[inline]
pub fn insert_indices(&mut self, indices: Indices) {
self.indices
.replace(Some(indices))
.expect(MESH_EXTRACTED_ERROR);
}
#[inline]
pub fn try_insert_indices(&mut self, indices: Indices) -> Result<(), MeshAccessError> {
self.indices.replace(Some(indices))?;
Ok(())
}
#[must_use]
#[inline]
pub fn with_inserted_indices(mut self, indices: Indices) -> Self {
self.insert_indices(indices);
self
}
#[inline]
pub fn try_with_inserted_indices(mut self, indices: Indices) -> Result<Self, MeshAccessError> {
self.try_insert_indices(indices)?;
Ok(self)
}
#[inline]
pub fn indices(&self) -> Option<&Indices> {
self.indices.as_ref_option().expect(MESH_EXTRACTED_ERROR)
}
#[inline]
pub fn try_indices(&self) -> Result<&Indices, MeshAccessError> {
self.indices.as_ref()
}
#[inline]
pub fn try_indices_option(&self) -> Result<Option<&Indices>, MeshAccessError> {
self.indices.as_ref_option()
}
#[inline]
pub fn indices_mut(&mut self) -> Option<&mut Indices> {
self.try_indices_mut_option().expect(MESH_EXTRACTED_ERROR)
}
#[inline]
pub fn try_indices_mut(&mut self) -> Result<&mut Indices, MeshAccessError> {
self.indices.as_mut()
}
#[inline]
pub fn try_indices_mut_option(&mut self) -> Result<Option<&mut Indices>, MeshAccessError> {
self.indices.as_mut_option()
}
#[inline]
pub fn remove_indices(&mut self) -> Option<Indices> {
self.try_remove_indices().expect(MESH_EXTRACTED_ERROR)
}
#[inline]
pub fn try_remove_indices(&mut self) -> Result<Option<Indices>, MeshAccessError> {
self.indices.replace(None)
}
#[must_use]
pub fn with_removed_indices(mut self) -> Self {
self.remove_indices();
self
}
pub fn try_with_removed_indices(mut self) -> Result<Self, MeshAccessError> {
self.try_remove_indices()?;
Ok(self)
}
pub fn get_vertex_size(&self) -> u64 {
self.attributes
.as_ref()
.expect(MESH_EXTRACTED_ERROR)
.values()
.map(|data| data.attribute.format.size())
.sum()
}
pub fn get_vertex_buffer_size(&self) -> usize {
let vertex_size = self.get_vertex_size() as usize;
let vertex_count = self.count_vertices();
vertex_count * vertex_size
}
pub fn get_index_buffer_bytes(&self) -> Option<&[u8]> {
let mesh_indices = self.indices.as_ref_option().expect(MESH_EXTRACTED_ERROR);
mesh_indices.as_ref().map(|indices| match &indices {
Indices::U16(indices) => cast_slice(&indices[..]),
Indices::U32(indices) => cast_slice(&indices[..]),
})
}
#[cfg(feature = "morph")]
pub fn get_morph_targets(&self) -> Option<&[MorphAttributes]> {
self.morph_targets
.as_ref_option()
.expect(MESH_EXTRACTED_ERROR)
.map(|morph_attributes| &morph_attributes[..])
}
pub fn get_mesh_vertex_buffer_layout(
&self,
mesh_vertex_buffer_layouts: &mut MeshVertexBufferLayouts,
) -> MeshVertexBufferLayoutRef {
let mesh_attributes = self.attributes.as_ref().expect(MESH_EXTRACTED_ERROR);
let mut attributes = Vec::with_capacity(mesh_attributes.len());
let mut attribute_ids = Vec::with_capacity(mesh_attributes.len());
let mut accumulated_offset = 0;
for (index, data) in mesh_attributes.values().enumerate() {
attribute_ids.push(data.attribute.id);
attributes.push(VertexAttribute {
offset: accumulated_offset,
format: data.attribute.format,
shader_location: index as u32,
});
accumulated_offset += data.attribute.format.size();
}
let layout = MeshVertexBufferLayout {
layout: VertexBufferLayout {
array_stride: accumulated_offset,
step_mode: VertexStepMode::Vertex,
attributes,
},
attribute_ids,
};
mesh_vertex_buffer_layouts.insert(layout)
}
pub fn count_vertices(&self) -> usize {
let mut vertex_count: Option<usize> = None;
let mesh_attributes = self.attributes.as_ref().expect(MESH_EXTRACTED_ERROR);
for (attribute_id, attribute_data) in mesh_attributes {
let attribute_len = attribute_data.values.len();
if let Some(previous_vertex_count) = vertex_count {
if previous_vertex_count != attribute_len {
let name = mesh_attributes
.get(attribute_id)
.map(|data| data.attribute.name.to_string())
.unwrap_or_else(|| format!("{attribute_id:?}"));
warn!("{name} has a different vertex count ({attribute_len}) than other attributes ({previous_vertex_count}) in this mesh, \
all attributes will be truncated to match the smallest.");
vertex_count = Some(core::cmp::min(previous_vertex_count, attribute_len));
}
} else {
vertex_count = Some(attribute_len);
}
}
vertex_count.unwrap_or(0)
}
pub fn create_packed_vertex_buffer_data(&self) -> Vec<u8> {
let mut attributes_interleaved_buffer = vec![0; self.get_vertex_buffer_size()];
self.write_packed_vertex_buffer_data(WriteOnly::from_mut(
&mut attributes_interleaved_buffer,
));
attributes_interleaved_buffer
}
pub fn write_packed_vertex_buffer_data(&self, mut slice: WriteOnly<'_, [u8]>) {
let mesh_attributes = self.attributes.as_ref().expect(MESH_EXTRACTED_ERROR);
let vertex_size = self.get_vertex_size() as usize;
let vertex_count = self.count_vertices();
let mut attribute_offset = 0;
for attribute_data in mesh_attributes.values() {
let attribute_size = attribute_data.attribute.format.size() as usize;
let attributes_bytes = attribute_data.values.get_bytes();
for (vertex_index, attribute_bytes) in attributes_bytes
.chunks_exact(attribute_size)
.take(vertex_count)
.enumerate()
{
let offset = vertex_index * vertex_size + attribute_offset;
slice
.slice(offset..offset + attribute_size)
.copy_from_slice(attribute_bytes);
}
attribute_offset += attribute_size;
}
}
pub fn duplicate_vertices(&mut self) {
self.try_duplicate_vertices().expect(MESH_EXTRACTED_ERROR);
}
pub fn try_duplicate_vertices(&mut self) -> Result<(), MeshAccessError> {
fn duplicate<T: Copy>(values: &[T], indices: impl Iterator<Item = usize>) -> Vec<T> {
indices.map(|i| values[i]).collect()
}
let Some(indices) = self.indices.replace(None)? else {
return Ok(());
};
let mesh_attributes = self.attributes.as_mut()?;
for attributes in mesh_attributes.values_mut() {
let indices = indices.iter();
#[expect(
clippy::match_same_arms,
reason = "Although the `vec` binding on some match arms may have different types, each variant has different semantics; thus it's not guaranteed that they will use the same type forever."
)]
match &mut attributes.values {
VertexAttributeValues::Float32(vec) => *vec = duplicate(vec, indices),
VertexAttributeValues::Sint32(vec) => *vec = duplicate(vec, indices),
VertexAttributeValues::Uint32(vec) => *vec = duplicate(vec, indices),
VertexAttributeValues::Float32x2(vec) => *vec = duplicate(vec, indices),
VertexAttributeValues::Sint32x2(vec) => *vec = duplicate(vec, indices),
VertexAttributeValues::Uint32x2(vec) => *vec = duplicate(vec, indices),
VertexAttributeValues::Float32x3(vec) => *vec = duplicate(vec, indices),
VertexAttributeValues::Sint32x3(vec) => *vec = duplicate(vec, indices),
VertexAttributeValues::Uint32x3(vec) => *vec = duplicate(vec, indices),
VertexAttributeValues::Sint32x4(vec) => *vec = duplicate(vec, indices),
VertexAttributeValues::Uint32x4(vec) => *vec = duplicate(vec, indices),
VertexAttributeValues::Float32x4(vec) => *vec = duplicate(vec, indices),
VertexAttributeValues::Sint16x2(vec) => *vec = duplicate(vec, indices),
VertexAttributeValues::Snorm16x2(vec) => *vec = duplicate(vec, indices),
VertexAttributeValues::Uint16x2(vec) => *vec = duplicate(vec, indices),
VertexAttributeValues::Unorm16x2(vec) => *vec = duplicate(vec, indices),
VertexAttributeValues::Sint16x4(vec) => *vec = duplicate(vec, indices),
VertexAttributeValues::Snorm16x4(vec) => *vec = duplicate(vec, indices),
VertexAttributeValues::Uint16x4(vec) => *vec = duplicate(vec, indices),
VertexAttributeValues::Unorm16x4(vec) => *vec = duplicate(vec, indices),
VertexAttributeValues::Sint8x2(vec) => *vec = duplicate(vec, indices),
VertexAttributeValues::Snorm8x2(vec) => *vec = duplicate(vec, indices),
VertexAttributeValues::Uint8x2(vec) => *vec = duplicate(vec, indices),
VertexAttributeValues::Unorm8x2(vec) => *vec = duplicate(vec, indices),
VertexAttributeValues::Sint8x4(vec) => *vec = duplicate(vec, indices),
VertexAttributeValues::Snorm8x4(vec) => *vec = duplicate(vec, indices),
VertexAttributeValues::Uint8x4(vec) => *vec = duplicate(vec, indices),
VertexAttributeValues::Unorm8x4(vec) => *vec = duplicate(vec, indices),
VertexAttributeValues::Uint8(vec) => *vec = duplicate(vec, indices),
VertexAttributeValues::Sint8(vec) => *vec = duplicate(vec, indices),
VertexAttributeValues::Unorm8(vec) => *vec = duplicate(vec, indices),
VertexAttributeValues::Snorm8(vec) => *vec = duplicate(vec, indices),
VertexAttributeValues::Uint16(vec) => *vec = duplicate(vec, indices),
VertexAttributeValues::Sint16(vec) => *vec = duplicate(vec, indices),
VertexAttributeValues::Unorm16(vec) => *vec = duplicate(vec, indices),
VertexAttributeValues::Snorm16(vec) => *vec = duplicate(vec, indices),
VertexAttributeValues::Float16(vec) => *vec = duplicate(vec, indices),
VertexAttributeValues::Float16x2(vec) => *vec = duplicate(vec, indices),
VertexAttributeValues::Float16x4(vec) => *vec = duplicate(vec, indices),
VertexAttributeValues::Float64(vec) => *vec = duplicate(vec, indices),
VertexAttributeValues::Float64x2(vec) => *vec = duplicate(vec, indices),
VertexAttributeValues::Float64x3(vec) => *vec = duplicate(vec, indices),
VertexAttributeValues::Float64x4(vec) => *vec = duplicate(vec, indices),
VertexAttributeValues::Unorm10_10_10_2(vec) => *vec = duplicate(vec, indices),
VertexAttributeValues::Unorm8x4Bgra(vec) => *vec = duplicate(vec, indices),
}
}
Ok(())
}
#[must_use]
pub fn with_duplicated_vertices(mut self) -> Self {
self.duplicate_vertices();
self
}
pub fn try_with_duplicated_vertices(mut self) -> Result<Self, MeshAccessError> {
self.try_duplicate_vertices()?;
Ok(self)
}
pub fn merge_duplicate_vertices(&mut self) -> Result<(), MeshMergeDuplicateVerticesError> {
match self.try_indices() {
Ok(_) => return Err(MeshMergeDuplicateVerticesError::IndicesAlreadySet),
Err(err) => match err {
MeshAccessError::ExtractedToRenderWorld => return Err(err.into()),
MeshAccessError::NotFound => (),
},
}
#[derive(Copy, Clone)]
struct VertexRef<'a> {
mesh_attributes: &'a BTreeMap<MeshVertexAttributeId, MeshAttributeData>,
i: usize,
}
impl<'a> VertexRef<'a> {
fn push_to(&self, target: &mut BTreeMap<MeshVertexAttributeId, MeshAttributeData>) {
for (key, this_attribute_data) in self.mesh_attributes.iter() {
let target_attribute_data = target.get_mut(key).unwrap(); target_attribute_data
.values
.push_from(&this_attribute_data.values, self.i);
}
}
}
impl<'a> PartialEq for VertexRef<'a> {
fn eq(&self, other: &Self) -> bool {
assert!(ptr::eq(self.mesh_attributes, other.mesh_attributes));
for values in self.mesh_attributes.values() {
if values.values.get_bytes_at(self.i) != values.values.get_bytes_at(other.i) {
return false;
}
}
true
}
}
impl<'a> Eq for VertexRef<'a> {}
impl<'a> Hash for VertexRef<'a> {
fn hash<H: Hasher>(&self, state: &mut H) {
for values in self.mesh_attributes.values() {
values.values.get_bytes_at(self.i).hash(state);
}
}
}
let old_attributes = self.attributes.as_ref()?;
let mut new_attributes: BTreeMap<MeshVertexAttributeId, MeshAttributeData> = self
.attributes
.as_ref()?
.iter()
.map(|(k, v)| {
(
*k,
MeshAttributeData {
attribute: v.attribute,
values: VertexAttributeValues::new(VertexFormat::from(&v.values)),
},
)
})
.collect();
let mut vertex_to_new_index: HashMap<VertexRef, u32> = HashMap::new();
let mut indices = Vec::with_capacity(self.count_vertices());
for i in 0..self.count_vertices() {
let len: u32 = vertex_to_new_index
.len()
.try_into()
.expect("The number of vertices exceeds u32::MAX");
let vertex_ref = VertexRef {
mesh_attributes: old_attributes,
i,
};
let j = match vertex_to_new_index.entry(vertex_ref) {
hash_map::Entry::Occupied(e) => *e.get(),
hash_map::Entry::Vacant(e) => {
e.insert(len);
vertex_ref.push_to(&mut new_attributes);
len
}
};
indices.push(j);
}
drop(vertex_to_new_index);
for v in new_attributes.values_mut() {
v.values.shrink_to_fit();
}
self.attributes = MeshExtractableData::Data(new_attributes);
self.indices = MeshExtractableData::Data(Indices::U32(indices));
Ok(())
}
pub fn with_merge_duplicate_vertices(
mut self,
) -> Result<Self, MeshMergeDuplicateVerticesError> {
self.merge_duplicate_vertices()?;
Ok(self)
}
pub fn invert_winding(&mut self) -> Result<(), MeshWindingInvertError> {
fn invert<I>(
indices: &mut [I],
topology: PrimitiveTopology,
) -> Result<(), MeshWindingInvertError> {
match topology {
PrimitiveTopology::TriangleList => {
let (chunks, []) = indices.as_chunks_mut() else {
return Err(MeshWindingInvertError::AbruptIndicesEnd);
};
for [_, b, c] in chunks {
core::mem::swap(b, c);
}
Ok(())
}
PrimitiveTopology::LineList => {
if !indices.len().is_multiple_of(2) {
return Err(MeshWindingInvertError::AbruptIndicesEnd);
}
indices.reverse();
Ok(())
}
PrimitiveTopology::TriangleStrip | PrimitiveTopology::LineStrip => {
indices.reverse();
Ok(())
}
_ => Err(MeshWindingInvertError::WrongTopology),
}
}
let mesh_indices = self.indices.as_mut_option()?;
match mesh_indices {
Some(Indices::U16(vec)) => invert(vec, self.primitive_topology),
Some(Indices::U32(vec)) => invert(vec, self.primitive_topology),
None => Ok(()),
}
}
pub fn with_inverted_winding(mut self) -> Result<Self, MeshWindingInvertError> {
self.invert_winding().map(|_| self)
}
pub fn compute_normals(&mut self) {
self.try_compute_normals().expect(MESH_EXTRACTED_ERROR);
}
pub fn try_compute_normals(&mut self) -> Result<(), MeshAccessError> {
assert!(
matches!(self.primitive_topology, PrimitiveTopology::TriangleList),
"`compute_normals` can only work on `TriangleList`s"
);
if self.try_indices_option()?.is_none() {
self.try_compute_flat_normals()
} else {
self.try_compute_smooth_normals()
}
}
pub fn compute_flat_normals(&mut self) {
self.try_compute_flat_normals().expect(MESH_EXTRACTED_ERROR);
}
pub fn try_compute_flat_normals(&mut self) -> Result<(), MeshAccessError> {
assert!(
self.try_indices_option()?.is_none(),
"`compute_flat_normals` can't work on indexed geometry. Consider calling either `Mesh::compute_smooth_normals` or `Mesh::duplicate_vertices` followed by `Mesh::compute_flat_normals`."
);
assert!(
matches!(self.primitive_topology, PrimitiveTopology::TriangleList),
"`compute_flat_normals` can only work on `TriangleList`s"
);
let positions = self
.try_attribute(Mesh::ATTRIBUTE_POSITION)?
.as_float3()
.expect("`Mesh::ATTRIBUTE_POSITION` vertex attributes should be of type `float3`");
let normals: Vec<_> = positions
.as_chunks()
.0
.iter()
.flat_map(|&[a, b, c]| [triangle_normal(a, b, c); 3])
.collect();
self.try_insert_attribute(Mesh::ATTRIBUTE_NORMAL, normals)
}
pub fn compute_smooth_normals(&mut self) {
self.try_compute_smooth_normals()
.expect(MESH_EXTRACTED_ERROR);
}
pub fn try_compute_smooth_normals(&mut self) -> Result<(), MeshAccessError> {
self.try_compute_custom_smooth_normals(|[a, b, c], positions, normals| {
let pa = Vec3::from(positions[a]);
let pb = Vec3::from(positions[b]);
let pc = Vec3::from(positions[c]);
let ab = pb - pa;
let ba = pa - pb;
let bc = pc - pb;
let cb = pb - pc;
let ca = pa - pc;
let ac = pc - pa;
const EPS: f32 = f32::EPSILON;
let weight_a = if ab.length_squared() * ac.length_squared() > EPS {
ab.angle_between(ac)
} else {
0.0
};
let weight_b = if ba.length_squared() * bc.length_squared() > EPS {
ba.angle_between(bc)
} else {
0.0
};
let weight_c = if ca.length_squared() * cb.length_squared() > EPS {
ca.angle_between(cb)
} else {
0.0
};
let normal = Vec3::from(triangle_normal(positions[a], positions[b], positions[c]));
normals[a] += normal * weight_a;
normals[b] += normal * weight_b;
normals[c] += normal * weight_c;
})
}
pub fn compute_area_weighted_normals(&mut self) {
self.try_compute_area_weighted_normals()
.expect(MESH_EXTRACTED_ERROR);
}
pub fn try_compute_area_weighted_normals(&mut self) -> Result<(), MeshAccessError> {
self.try_compute_custom_smooth_normals(|[a, b, c], positions, normals| {
let normal = Vec3::from(triangle_area_normal(
positions[a],
positions[b],
positions[c],
));
[a, b, c].into_iter().for_each(|pos| {
normals[pos] += normal;
});
})
}
pub fn compute_custom_smooth_normals(
&mut self,
per_triangle: impl FnMut([usize; 3], &[[f32; 3]], &mut [Vec3]),
) {
self.try_compute_custom_smooth_normals(per_triangle)
.expect(MESH_EXTRACTED_ERROR);
}
pub fn try_compute_custom_smooth_normals(
&mut self,
mut per_triangle: impl FnMut([usize; 3], &[[f32; 3]], &mut [Vec3]),
) -> Result<(), MeshAccessError> {
assert!(
matches!(self.primitive_topology, PrimitiveTopology::TriangleList),
"smooth normals can only be computed on `TriangleList`s"
);
assert!(
self.try_indices_option()?.is_some(),
"smooth normals can only be computed on indexed meshes"
);
let positions = self
.try_attribute(Mesh::ATTRIBUTE_POSITION)?
.as_float3()
.expect("`Mesh::ATTRIBUTE_POSITION` vertex attributes should be of type `float3`");
let mut normals = vec![Vec3::ZERO; positions.len()];
match self.try_indices()? {
Indices::U16(vec) => vec.as_chunks().0.iter().for_each(|&chunk| {
per_triangle(chunk.map(|i| i as usize), positions, &mut normals);
}),
Indices::U32(vec) => vec.as_chunks().0.iter().for_each(|&chunk| {
per_triangle(chunk.map(|i| i as usize), positions, &mut normals);
}),
}
for normal in &mut normals {
*normal = normal.try_normalize().unwrap_or(Vec3::ZERO);
}
self.try_insert_attribute(Mesh::ATTRIBUTE_NORMAL, normals)
}
#[must_use]
pub fn with_computed_normals(self) -> Self {
self.try_with_computed_normals()
.expect(MESH_EXTRACTED_ERROR)
}
pub fn try_with_computed_normals(mut self) -> Result<Self, MeshAccessError> {
self.try_compute_normals()?;
Ok(self)
}
pub fn with_computed_flat_normals(mut self) -> Self {
self.compute_flat_normals();
self
}
pub fn try_with_computed_flat_normals(mut self) -> Result<Self, MeshAccessError> {
self.try_compute_flat_normals()?;
Ok(self)
}
pub fn with_computed_smooth_normals(mut self) -> Self {
self.compute_smooth_normals();
self
}
pub fn try_with_computed_smooth_normals(mut self) -> Result<Self, MeshAccessError> {
self.try_compute_smooth_normals()?;
Ok(self)
}
pub fn with_computed_area_weighted_normals(mut self) -> Self {
self.compute_area_weighted_normals();
self
}
pub fn try_with_computed_area_weighted_normals(mut self) -> Result<Self, MeshAccessError> {
self.try_compute_area_weighted_normals()?;
Ok(self)
}
#[cfg(feature = "bevy_mikktspace")]
pub fn generate_tangents(&mut self) -> Result<(), super::GenerateTangentsError> {
let tangents = super::generate_tangents_for_mesh(self)?;
self.try_insert_attribute(Mesh::ATTRIBUTE_TANGENT, tangents)?;
Ok(())
}
#[cfg(feature = "bevy_mikktspace")]
pub fn with_generated_tangents(mut self) -> Result<Mesh, super::GenerateTangentsError> {
self.generate_tangents()?;
Ok(self)
}
pub fn merge(&mut self, other: &Mesh) -> Result<(), MeshMergeError> {
use VertexAttributeValues::*;
if self.primitive_topology != other.primitive_topology {
return Err(MeshMergeError::IncompatiblePrimitiveTopology {
self_primitive_topology: self.primitive_topology,
other_primitive_topology: other.primitive_topology,
});
}
let index_offset = self.count_vertices();
for (attribute, values) in self.try_attributes_mut()? {
if let Some(other_values) = other.try_attribute_option(attribute.id)? {
#[expect(
clippy::match_same_arms,
reason = "Although the bindings on some match arms may have different types, each variant has different semantics; thus it's not guaranteed that they will use the same type forever."
)]
match (values, other_values) {
(Float32(vec1), Float32(vec2)) => vec1.extend(vec2),
(Sint32(vec1), Sint32(vec2)) => vec1.extend(vec2),
(Uint32(vec1), Uint32(vec2)) => vec1.extend(vec2),
(Float32x2(vec1), Float32x2(vec2)) => vec1.extend(vec2),
(Sint32x2(vec1), Sint32x2(vec2)) => vec1.extend(vec2),
(Uint32x2(vec1), Uint32x2(vec2)) => vec1.extend(vec2),
(Float32x3(vec1), Float32x3(vec2)) => vec1.extend(vec2),
(Sint32x3(vec1), Sint32x3(vec2)) => vec1.extend(vec2),
(Uint32x3(vec1), Uint32x3(vec2)) => vec1.extend(vec2),
(Sint32x4(vec1), Sint32x4(vec2)) => vec1.extend(vec2),
(Uint32x4(vec1), Uint32x4(vec2)) => vec1.extend(vec2),
(Float32x4(vec1), Float32x4(vec2)) => vec1.extend(vec2),
(Sint16x2(vec1), Sint16x2(vec2)) => vec1.extend(vec2),
(Snorm16x2(vec1), Snorm16x2(vec2)) => vec1.extend(vec2),
(Uint16x2(vec1), Uint16x2(vec2)) => vec1.extend(vec2),
(Unorm16x2(vec1), Unorm16x2(vec2)) => vec1.extend(vec2),
(Sint16x4(vec1), Sint16x4(vec2)) => vec1.extend(vec2),
(Snorm16x4(vec1), Snorm16x4(vec2)) => vec1.extend(vec2),
(Uint16x4(vec1), Uint16x4(vec2)) => vec1.extend(vec2),
(Unorm16x4(vec1), Unorm16x4(vec2)) => vec1.extend(vec2),
(Sint8x2(vec1), Sint8x2(vec2)) => vec1.extend(vec2),
(Snorm8x2(vec1), Snorm8x2(vec2)) => vec1.extend(vec2),
(Uint8x2(vec1), Uint8x2(vec2)) => vec1.extend(vec2),
(Unorm8x2(vec1), Unorm8x2(vec2)) => vec1.extend(vec2),
(Sint8x4(vec1), Sint8x4(vec2)) => vec1.extend(vec2),
(Snorm8x4(vec1), Snorm8x4(vec2)) => vec1.extend(vec2),
(Uint8x4(vec1), Uint8x4(vec2)) => vec1.extend(vec2),
(Unorm8x4(vec1), Unorm8x4(vec2)) => vec1.extend(vec2),
_ => {
return Err(MeshMergeError::IncompatibleVertexAttributes {
self_attribute: *attribute,
other_attribute: other
.try_attribute_data(attribute.id)?
.map(|data| data.attribute),
})
}
}
}
}
if let (Some(indices), Some(other_indices)) =
(self.try_indices_mut_option()?, other.try_indices_option()?)
{
indices.extend(other_indices.iter().map(|i| (i + index_offset) as u32));
}
Ok(())
}
pub fn transformed_by(mut self, transform: Transform) -> Self {
self.transform_by(transform);
self
}
pub fn try_transformed_by(mut self, transform: Transform) -> Result<Self, MeshAccessError> {
self.try_transform_by(transform)?;
Ok(self)
}
pub fn transform_by(&mut self, transform: Transform) {
self.try_transform_by(transform)
.expect(MESH_EXTRACTED_ERROR);
}
pub fn try_transform_by(&mut self, transform: Transform) -> Result<(), MeshAccessError> {
let scale_recip = 1. / transform.scale;
debug_assert!(
transform.scale.yzx() * transform.scale.zxy() != Vec3::ZERO,
"mesh transform scale cannot be zero on more than one axis"
);
if let Some(VertexAttributeValues::Float32x3(positions)) =
self.try_attribute_mut_option(Mesh::ATTRIBUTE_POSITION)?
{
positions
.iter_mut()
.for_each(|pos| *pos = transform.transform_point(Vec3::from_slice(pos)).to_array());
}
if transform.rotation.is_near_identity()
&& transform.scale.x == transform.scale.y
&& transform.scale.y == transform.scale.z
{
return Ok(());
}
if let Some(VertexAttributeValues::Float32x3(normals)) =
self.try_attribute_mut_option(Mesh::ATTRIBUTE_NORMAL)?
{
normals.iter_mut().for_each(|normal| {
*normal = (transform.rotation
* scale_normal(Vec3::from_array(*normal), scale_recip))
.to_array();
});
}
if let Some(VertexAttributeValues::Float32x4(tangents)) =
self.try_attribute_mut_option(Mesh::ATTRIBUTE_TANGENT)?
{
tangents.iter_mut().for_each(|tangent| {
let handedness = tangent[3];
let scaled_tangent = Vec3::from_slice(tangent) * transform.scale;
*tangent = (transform.rotation * scaled_tangent.normalize_or_zero())
.extend(handedness)
.to_array();
});
}
Ok(())
}
pub fn translated_by(mut self, translation: Vec3) -> Self {
self.translate_by(translation);
self
}
pub fn try_translated_by(mut self, translation: Vec3) -> Result<Self, MeshAccessError> {
self.try_translate_by(translation)?;
Ok(self)
}
pub fn translate_by(&mut self, translation: Vec3) {
self.try_translate_by(translation)
.expect(MESH_EXTRACTED_ERROR);
}
pub fn try_translate_by(&mut self, translation: Vec3) -> Result<(), MeshAccessError> {
if translation == Vec3::ZERO {
return Ok(());
}
if let Some(VertexAttributeValues::Float32x3(positions)) =
self.try_attribute_mut_option(Mesh::ATTRIBUTE_POSITION)?
{
positions
.iter_mut()
.for_each(|pos| *pos = (Vec3::from_slice(pos) + translation).to_array());
}
Ok(())
}
pub fn rotated_by(mut self, rotation: Quat) -> Self {
self.try_rotate_by(rotation).expect(MESH_EXTRACTED_ERROR);
self
}
pub fn try_rotated_by(mut self, rotation: Quat) -> Result<Self, MeshAccessError> {
self.try_rotate_by(rotation)?;
Ok(self)
}
pub fn rotate_by(&mut self, rotation: Quat) {
self.try_rotate_by(rotation).expect(MESH_EXTRACTED_ERROR);
}
pub fn try_rotate_by(&mut self, rotation: Quat) -> Result<(), MeshAccessError> {
if let Some(VertexAttributeValues::Float32x3(positions)) =
self.try_attribute_mut_option(Mesh::ATTRIBUTE_POSITION)?
{
positions
.iter_mut()
.for_each(|pos| *pos = (rotation * Vec3::from_slice(pos)).to_array());
}
if rotation.is_near_identity() {
return Ok(());
}
if let Some(VertexAttributeValues::Float32x3(normals)) =
self.try_attribute_mut_option(Mesh::ATTRIBUTE_NORMAL)?
{
normals.iter_mut().for_each(|normal| {
*normal = (rotation * Vec3::from_slice(normal).normalize_or_zero()).to_array();
});
}
if let Some(VertexAttributeValues::Float32x4(tangents)) =
self.try_attribute_mut_option(Mesh::ATTRIBUTE_TANGENT)?
{
tangents.iter_mut().for_each(|tangent| {
let handedness = tangent[3];
*tangent = (rotation * Vec3::from_slice(tangent).normalize_or_zero())
.extend(handedness)
.to_array();
});
}
Ok(())
}
pub fn scaled_by(mut self, scale: Vec3) -> Self {
self.scale_by(scale);
self
}
pub fn try_scaled_by(mut self, scale: Vec3) -> Result<Self, MeshAccessError> {
self.try_scale_by(scale)?;
Ok(self)
}
pub fn scale_by(&mut self, scale: Vec3) {
self.try_scale_by(scale).expect(MESH_EXTRACTED_ERROR);
}
pub fn try_scale_by(&mut self, scale: Vec3) -> Result<(), MeshAccessError> {
let scale_recip = 1. / scale;
debug_assert!(
scale.yzx() * scale.zxy() != Vec3::ZERO,
"mesh transform scale cannot be zero on more than one axis"
);
if let Some(VertexAttributeValues::Float32x3(positions)) =
self.try_attribute_mut_option(Mesh::ATTRIBUTE_POSITION)?
{
positions
.iter_mut()
.for_each(|pos| *pos = (scale * Vec3::from_slice(pos)).to_array());
}
if scale.x == scale.y && scale.y == scale.z {
return Ok(());
}
if let Some(VertexAttributeValues::Float32x3(normals)) =
self.try_attribute_mut_option(Mesh::ATTRIBUTE_NORMAL)?
{
normals.iter_mut().for_each(|normal| {
*normal = scale_normal(Vec3::from_array(*normal), scale_recip).to_array();
});
}
if let Some(VertexAttributeValues::Float32x4(tangents)) =
self.try_attribute_mut_option(Mesh::ATTRIBUTE_TANGENT)?
{
tangents.iter_mut().for_each(|tangent| {
let handedness = tangent[3];
let scaled_tangent = Vec3::from_slice(tangent) * scale;
*tangent = scaled_tangent
.normalize_or_zero()
.extend(handedness)
.to_array();
});
}
Ok(())
}
pub fn normalize_joint_weights(&mut self) {
self.try_normalize_joint_weights()
.expect(MESH_EXTRACTED_ERROR);
}
pub fn try_normalize_joint_weights(&mut self) -> Result<(), MeshAccessError> {
if let Some(VertexAttributeValues::Float32x4(joints)) =
self.try_attribute_mut_option(Self::ATTRIBUTE_JOINT_WEIGHT)?
{
for weights in joints.iter_mut() {
weights.iter_mut().for_each(|w| *w = w.max(0.0));
let sum: f32 = weights.iter().sum();
if sum == 0.0 {
weights[0] = 1.0;
} else {
let recip = sum.recip();
for weight in weights.iter_mut() {
*weight *= recip;
}
}
}
}
Ok(())
}
pub fn triangles(&self) -> Result<impl Iterator<Item = Triangle3d> + '_, MeshTrianglesError> {
fn indices_to_triangle<T: TryInto<usize> + Copy>(
vertices: &[[f32; 3]],
indices: &[T; 3],
) -> Option<Triangle3d> {
let vert0 = Vec3::from(*vertices.get(indices[0].try_into().ok()?)?);
let vert1 = Vec3::from(*vertices.get(indices[1].try_into().ok()?)?);
let vert2 = Vec3::from(*vertices.get(indices[2].try_into().ok()?)?);
Some(Triangle3d {
vertices: [vert0, vert1, vert2],
})
}
let position_data = self.try_attribute(Mesh::ATTRIBUTE_POSITION)?;
let Some(vertices) = position_data.as_float3() else {
return Err(MeshTrianglesError::PositionsFormat);
};
let indices = self.try_indices()?;
match self.primitive_topology {
PrimitiveTopology::TriangleList => {
let iterator = match indices {
Indices::U16(vec) => FourIterators::First(
vec.as_chunks()
.0
.iter()
.flat_map(|indices| indices_to_triangle(vertices, indices)),
),
Indices::U32(vec) => FourIterators::Second(
vec.as_chunks()
.0
.iter()
.flat_map(|indices| indices_to_triangle(vertices, indices)),
),
};
Ok(iterator)
}
PrimitiveTopology::TriangleStrip => {
let iterator = match indices {
Indices::U16(vec) => {
FourIterators::Third(vec.array_windows().enumerate().flat_map(
|(i, indices @ &[idx0, idx1, idx2])| {
if i % 2 == 0 {
indices_to_triangle(vertices, indices)
} else {
indices_to_triangle(vertices, &[idx1, idx0, idx2])
}
},
))
}
Indices::U32(vec) => {
FourIterators::Fourth(vec.array_windows().enumerate().flat_map(
|(i, indices @ &[idx0, idx1, idx2])| {
if i % 2 == 0 {
indices_to_triangle(vertices, indices)
} else {
indices_to_triangle(vertices, &[idx1, idx0, idx2])
}
},
))
}
};
Ok(iterator)
}
_ => Err(MeshTrianglesError::WrongTopology),
}
}
pub fn take_gpu_data(&mut self) -> Result<Self, MeshAccessError> {
let attributes = self.attributes.extract()?;
let indices = self.indices.extract()?;
#[cfg(feature = "morph")]
let morph_targets = self.morph_targets.extract()?;
#[cfg(feature = "morph")]
let morph_target_names = self.morph_target_names.extract()?;
if let Some(MeshAttributeData {
values: VertexAttributeValues::Float32x3(position_values),
..
}) = attributes
.as_ref_option()?
.and_then(|attrs| attrs.get(&Self::ATTRIBUTE_POSITION.id))
&& !position_values.is_empty()
{
let mut iter = position_values.iter().map(|p| Vec3::from_slice(p));
let mut min = iter.next().unwrap();
let mut max = min;
for v in iter {
min = Vec3::min(min, v);
max = Vec3::max(max, v);
}
self.final_aabb = Some(Aabb3d::from_min_max(min, max));
}
Ok(Self {
attributes,
indices,
#[cfg(feature = "morph")]
morph_targets,
#[cfg(feature = "morph")]
morph_target_names,
..self.clone()
})
}
pub fn skinned_mesh_bounds(&self) -> Option<&SkinnedMeshBounds> {
self.skinned_mesh_bounds.as_ref()
}
pub fn set_skinned_mesh_bounds(&mut self, skinned_mesh_bounds: Option<SkinnedMeshBounds>) {
self.skinned_mesh_bounds = skinned_mesh_bounds;
}
pub fn with_skinned_mesh_bounds(
mut self,
skinned_mesh_bounds: Option<SkinnedMeshBounds>,
) -> Self {
self.set_skinned_mesh_bounds(skinned_mesh_bounds);
self
}
pub fn generate_skinned_mesh_bounds(&mut self) -> Result<(), SkinnedMeshBoundsError> {
self.skinned_mesh_bounds = Some(SkinnedMeshBounds::from_mesh(self)?);
Ok(())
}
pub fn with_generated_skinned_mesh_bounds(mut self) -> Result<Self, SkinnedMeshBoundsError> {
self.generate_skinned_mesh_bounds()?;
Ok(self)
}
}
#[cfg(feature = "morph")]
impl Mesh {
pub fn has_morph_targets(&self) -> bool {
self.try_has_morph_targets().expect(MESH_EXTRACTED_ERROR)
}
pub fn try_has_morph_targets(&self) -> Result<bool, MeshAccessError> {
Ok(self.morph_targets.as_ref_option()?.is_some())
}
#[cfg(feature = "morph")]
pub fn set_morph_targets(&mut self, morph_targets: Vec<MorphAttributes>) {
self.try_set_morph_targets(morph_targets)
.expect(MESH_EXTRACTED_ERROR);
}
#[cfg(feature = "morph")]
pub fn try_set_morph_targets(
&mut self,
morph_targets: Vec<MorphAttributes>,
) -> Result<(), MeshAccessError> {
self.morph_targets.replace(Some(morph_targets))?;
Ok(())
}
#[cfg(feature = "morph")]
pub fn morph_targets(&self) -> Option<&Vec<MorphAttributes>> {
self.morph_targets
.as_ref_option()
.expect(MESH_EXTRACTED_ERROR)
}
#[cfg(feature = "morph")]
pub fn try_morph_targets(&self) -> Result<&Vec<MorphAttributes>, MeshAccessError> {
self.morph_targets.as_ref()
}
#[must_use]
#[cfg(feature = "morph")]
pub fn with_morph_targets(mut self, morph_targets: Vec<MorphAttributes>) -> Self {
self.set_morph_targets(morph_targets);
self
}
#[cfg(feature = "morph")]
pub fn try_with_morph_targets(
mut self,
morph_targets: Vec<MorphAttributes>,
) -> Result<Self, MeshAccessError> {
self.try_set_morph_targets(morph_targets)?;
Ok(self)
}
pub fn set_morph_target_names(&mut self, names: Vec<String>) {
self.try_set_morph_target_names(names)
.expect(MESH_EXTRACTED_ERROR);
}
pub fn try_set_morph_target_names(
&mut self,
names: Vec<String>,
) -> Result<(), MeshAccessError> {
self.morph_target_names.replace(Some(names))?;
Ok(())
}
#[must_use]
pub fn with_morph_target_names(self, names: Vec<String>) -> Self {
self.try_with_morph_target_names(names)
.expect(MESH_EXTRACTED_ERROR)
}
pub fn try_with_morph_target_names(
mut self,
names: Vec<String>,
) -> Result<Self, MeshAccessError> {
self.try_set_morph_target_names(names)?;
Ok(self)
}
pub fn morph_target_names(&self) -> Option<&[String]> {
self.try_morph_target_names().expect(MESH_EXTRACTED_ERROR)
}
pub fn try_morph_target_names(&self) -> Result<Option<&[String]>, MeshAccessError> {
Ok(self
.morph_target_names
.as_ref_option()?
.map(core::ops::Deref::deref))
}
}
#[derive(Reflect, Default, Debug, Clone, PartialEq, Eq)]
#[reflect(Default, Debug, Clone, PartialEq)]
pub enum UvChannel {
#[default]
Uv0,
Uv1,
}
pub(crate) fn scale_normal(normal: Vec3, scale_recip: Vec3) -> Vec3 {
let n = Vec3::select(normal.cmpeq(Vec3::ZERO), Vec3::ZERO, normal * scale_recip);
if n.is_finite() {
n.normalize_or_zero()
} else {
Vec3::select(n.abs().cmpeq(Vec3::INFINITY), n.signum(), Vec3::ZERO).normalize()
}
}
impl core::ops::Mul<Mesh> for Transform {
type Output = Mesh;
fn mul(self, rhs: Mesh) -> Self::Output {
rhs.transformed_by(self)
}
}
#[cfg(feature = "serialize")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SerializedMesh {
primitive_topology: PrimitiveTopology,
attributes: Vec<(MeshVertexAttributeId, SerializedMeshAttributeData)>,
indices: Option<Indices>,
}
#[cfg(feature = "serialize")]
impl SerializedMesh {
pub fn from_mesh(mut mesh: Mesh) -> Self {
Self {
primitive_topology: mesh.primitive_topology,
attributes: mesh
.attributes
.replace(None)
.expect(MESH_EXTRACTED_ERROR)
.unwrap()
.into_iter()
.map(|(id, data)| {
(
id,
SerializedMeshAttributeData::from_mesh_attribute_data(data),
)
})
.collect(),
indices: mesh.indices.replace(None).expect(MESH_EXTRACTED_ERROR),
}
}
pub fn into_mesh(self) -> Mesh {
MeshDeserializer::default().deserialize(self)
}
}
#[cfg(feature = "serialize")]
pub struct MeshDeserializer {
custom_vertex_attributes: HashMap<Box<str>, MeshVertexAttribute>,
}
#[cfg(feature = "serialize")]
impl Default for MeshDeserializer {
fn default() -> Self {
const BUILTINS: [MeshVertexAttribute; Mesh::FIRST_AVAILABLE_CUSTOM_ATTRIBUTE as usize] = [
Mesh::ATTRIBUTE_POSITION,
Mesh::ATTRIBUTE_NORMAL,
Mesh::ATTRIBUTE_UV_0,
Mesh::ATTRIBUTE_UV_1,
Mesh::ATTRIBUTE_TANGENT,
Mesh::ATTRIBUTE_COLOR,
Mesh::ATTRIBUTE_JOINT_WEIGHT,
Mesh::ATTRIBUTE_JOINT_INDEX,
];
Self {
custom_vertex_attributes: BUILTINS
.into_iter()
.map(|attribute| (attribute.name.into(), attribute))
.collect(),
}
}
}
#[cfg(feature = "serialize")]
impl MeshDeserializer {
pub fn new() -> Self {
Self::default()
}
pub fn add_custom_vertex_attribute(
&mut self,
name: &str,
attribute: MeshVertexAttribute,
) -> &mut Self {
self.custom_vertex_attributes.insert(name.into(), attribute);
self
}
pub fn deserialize(&self, serialized_mesh: SerializedMesh) -> Mesh {
Mesh {
attributes: MeshExtractableData::Data(
serialized_mesh
.attributes
.into_iter()
.filter_map(|(id, data)| {
let attribute = data.attribute.clone();
let Some(data) =
data.try_into_mesh_attribute_data(&self.custom_vertex_attributes)
else {
warn!(
"Deserialized mesh contains custom vertex attribute {attribute:?} that \
was not specified with `MeshDeserializer::add_custom_vertex_attribute`. Ignoring."
);
return None;
};
Some((id, data))
})
.collect()),
indices: serialized_mesh.indices.into(),
..Mesh::new(serialized_mesh.primitive_topology, RenderAssetUsages::default())
}
}
}
#[derive(Error, Debug, Clone)]
pub enum MeshMergeDuplicateVerticesError {
#[error("Index attribute already set.")]
IndicesAlreadySet,
#[error("Mesh access error: {0}")]
MeshAccessError(#[from] MeshAccessError),
}
#[derive(Error, Debug, Clone)]
pub enum MeshMergeError {
#[error("Incompatible vertex attribute types: {} and {}", self_attribute.name, other_attribute.map(|a| a.name).unwrap_or("None"))]
IncompatibleVertexAttributes {
self_attribute: MeshVertexAttribute,
other_attribute: Option<MeshVertexAttribute>,
},
#[error(
"Incompatible primitive topologies: {:?} and {:?}",
self_primitive_topology,
other_primitive_topology
)]
IncompatiblePrimitiveTopology {
self_primitive_topology: PrimitiveTopology,
other_primitive_topology: PrimitiveTopology,
},
#[error("Mesh access error: {0}")]
MeshAccessError(#[from] MeshAccessError),
}
#[cfg(test)]
mod tests {
use super::Mesh;
#[cfg(feature = "serialize")]
use super::SerializedMesh;
use crate::mesh::{Indices, MeshWindingInvertError, VertexAttributeValues};
use crate::PrimitiveTopology;
use bevy_asset::RenderAssetUsages;
use bevy_math::bounding::Aabb3d;
use bevy_math::primitives::Triangle3d;
use bevy_math::Vec3;
use bevy_transform::components::Transform;
#[test]
#[should_panic]
fn panic_invalid_format() {
let _mesh = Mesh::new(
PrimitiveTopology::TriangleList,
RenderAssetUsages::default(),
)
.with_inserted_attribute(Mesh::ATTRIBUTE_UV_0, vec![[0.0, 0.0, 0.0]]);
}
#[test]
fn transform_mesh() {
let mesh = Mesh::new(
PrimitiveTopology::TriangleList,
RenderAssetUsages::default(),
)
.with_inserted_attribute(
Mesh::ATTRIBUTE_POSITION,
vec![[-1., -1., 2.], [1., -1., 2.], [0., 1., 2.]],
)
.with_inserted_attribute(
Mesh::ATTRIBUTE_NORMAL,
vec![
Vec3::new(-1., -1., 1.).normalize().to_array(),
Vec3::new(1., -1., 1.).normalize().to_array(),
[0., 0., 1.],
],
)
.with_inserted_attribute(Mesh::ATTRIBUTE_UV_0, vec![[0., 0.], [1., 0.], [0.5, 1.]]);
let mesh = mesh.transformed_by(
Transform::from_translation(Vec3::splat(-2.)).with_scale(Vec3::new(2., 0., -1.)),
);
if let Some(VertexAttributeValues::Float32x3(positions)) =
mesh.attribute(Mesh::ATTRIBUTE_POSITION)
{
assert_eq!(
positions,
&vec![[-4.0, -2.0, -4.0], [0.0, -2.0, -4.0], [-2.0, -2.0, -4.0]]
);
} else {
panic!("Mesh does not have a position attribute");
}
if let Some(VertexAttributeValues::Float32x3(normals)) =
mesh.attribute(Mesh::ATTRIBUTE_NORMAL)
{
assert_eq!(normals, &vec![[0., -1., 0.], [0., -1., 0.], [0., 0., -1.]]);
} else {
panic!("Mesh does not have a normal attribute");
}
if let Some(VertexAttributeValues::Float32x2(uvs)) = mesh.attribute(Mesh::ATTRIBUTE_UV_0) {
assert_eq!(uvs, &vec![[0., 0.], [1., 0.], [0.5, 1.]]);
} else {
panic!("Mesh does not have a uv attribute");
}
}
#[test]
fn point_list_mesh_invert_winding() {
let mesh = Mesh::new(PrimitiveTopology::PointList, RenderAssetUsages::default())
.with_inserted_indices(Indices::U32(vec![]));
assert!(matches!(
mesh.with_inverted_winding(),
Err(MeshWindingInvertError::WrongTopology)
));
}
#[test]
fn line_list_mesh_invert_winding() {
let mesh = Mesh::new(PrimitiveTopology::LineList, RenderAssetUsages::default())
.with_inserted_indices(Indices::U32(vec![0, 1, 1, 2, 2, 3]));
let mesh = mesh.with_inverted_winding().unwrap();
assert_eq!(
mesh.indices().unwrap().iter().collect::<Vec<usize>>(),
vec![3, 2, 2, 1, 1, 0]
);
}
#[test]
fn line_list_mesh_invert_winding_fail() {
let mesh = Mesh::new(PrimitiveTopology::LineList, RenderAssetUsages::default())
.with_inserted_indices(Indices::U32(vec![0, 1, 1]));
assert!(matches!(
mesh.with_inverted_winding(),
Err(MeshWindingInvertError::AbruptIndicesEnd)
));
}
#[test]
fn line_strip_mesh_invert_winding() {
let mesh = Mesh::new(PrimitiveTopology::LineStrip, RenderAssetUsages::default())
.with_inserted_indices(Indices::U32(vec![0, 1, 2, 3]));
let mesh = mesh.with_inverted_winding().unwrap();
assert_eq!(
mesh.indices().unwrap().iter().collect::<Vec<usize>>(),
vec![3, 2, 1, 0]
);
}
#[test]
fn triangle_list_mesh_invert_winding() {
let mesh = Mesh::new(
PrimitiveTopology::TriangleList,
RenderAssetUsages::default(),
)
.with_inserted_indices(Indices::U32(vec![
0, 3, 1, 1, 3, 2, ]));
let mesh = mesh.with_inverted_winding().unwrap();
assert_eq!(
mesh.indices().unwrap().iter().collect::<Vec<usize>>(),
vec![
0, 1, 3, 1, 2, 3, ]
);
}
#[test]
fn triangle_list_mesh_invert_winding_fail() {
let mesh = Mesh::new(
PrimitiveTopology::TriangleList,
RenderAssetUsages::default(),
)
.with_inserted_indices(Indices::U32(vec![0, 3, 1, 2]));
assert!(matches!(
mesh.with_inverted_winding(),
Err(MeshWindingInvertError::AbruptIndicesEnd)
));
}
#[test]
fn triangle_strip_mesh_invert_winding() {
let mesh = Mesh::new(
PrimitiveTopology::TriangleStrip,
RenderAssetUsages::default(),
)
.with_inserted_indices(Indices::U32(vec![0, 1, 2, 3]));
let mesh = mesh.with_inverted_winding().unwrap();
assert_eq!(
mesh.indices().unwrap().iter().collect::<Vec<usize>>(),
vec![3, 2, 1, 0]
);
}
#[test]
fn compute_area_weighted_normals() {
let mut mesh = Mesh::new(
PrimitiveTopology::TriangleList,
RenderAssetUsages::default(),
);
mesh.insert_attribute(
Mesh::ATTRIBUTE_POSITION,
vec![[0., 0., 0.], [1., 0., 0.], [0., 1., 0.], [0., 0., 1.]],
);
mesh.insert_indices(Indices::U16(vec![0, 1, 2, 0, 2, 3]));
mesh.compute_area_weighted_normals();
let normals = mesh
.attribute(Mesh::ATTRIBUTE_NORMAL)
.unwrap()
.as_float3()
.unwrap();
assert_eq!(4, normals.len());
assert_eq!(Vec3::new(1., 0., 1.).normalize().to_array(), normals[0]);
assert_eq!([0., 0., 1.], normals[1]);
assert_eq!(Vec3::new(1., 0., 1.).normalize().to_array(), normals[2]);
assert_eq!([1., 0., 0.], normals[3]);
}
#[test]
fn compute_area_weighted_normals_proportionate() {
let mut mesh = Mesh::new(
PrimitiveTopology::TriangleList,
RenderAssetUsages::default(),
);
mesh.insert_attribute(
Mesh::ATTRIBUTE_POSITION,
vec![[0., 0., 0.], [2., 0., 0.], [0., 1., 0.], [0., 0., 1.]],
);
mesh.insert_indices(Indices::U16(vec![0, 1, 2, 0, 2, 3]));
mesh.compute_area_weighted_normals();
let normals = mesh
.attribute(Mesh::ATTRIBUTE_NORMAL)
.unwrap()
.as_float3()
.unwrap();
assert_eq!(4, normals.len());
assert_eq!(Vec3::new(1., 0., 2.).normalize().to_array(), normals[0]);
assert_eq!([0., 0., 1.], normals[1]);
assert_eq!(Vec3::new(1., 0., 2.).normalize().to_array(), normals[2]);
assert_eq!([1., 0., 0.], normals[3]);
}
#[test]
fn compute_angle_weighted_normals() {
let verts = vec![
[1.0, 1.0, 1.0],
[-1.0, 1.0, 1.0],
[-1.0, -1.0, 1.0],
[1.0, -1.0, 1.0],
[1.0, 1.0, -1.0],
[-1.0, 1.0, -1.0],
[-1.0, -1.0, -1.0],
[1.0, -1.0, -1.0],
];
let indices = Indices::U16(vec![
0, 1, 2, 2, 3, 0, 5, 4, 7, 7, 6, 5, 1, 5, 6, 6, 2, 1, 4, 0, 3, 3, 7, 4, 4, 5, 1, 1, 0, 4, 3, 2, 6, 6, 7, 3, ]);
let mut mesh = Mesh::new(
PrimitiveTopology::TriangleList,
RenderAssetUsages::default(),
);
mesh.insert_attribute(Mesh::ATTRIBUTE_POSITION, verts);
mesh.insert_indices(indices);
mesh.compute_smooth_normals();
let normals = mesh
.attribute(Mesh::ATTRIBUTE_NORMAL)
.unwrap()
.as_float3()
.unwrap();
for new in normals.iter().copied().flatten() {
const FRAC_1_SQRT_3: f32 = 0.57735026;
const MIN: f32 = FRAC_1_SQRT_3 - f32::EPSILON;
const MAX: f32 = FRAC_1_SQRT_3 + f32::EPSILON;
assert!(new.abs() >= MIN, "{new} < {MIN}");
assert!(new.abs() <= MAX, "{new} > {MAX}");
}
}
#[test]
fn triangles_from_triangle_list() {
let mut mesh = Mesh::new(
PrimitiveTopology::TriangleList,
RenderAssetUsages::default(),
);
mesh.insert_attribute(
Mesh::ATTRIBUTE_POSITION,
vec![[0., 0., 0.], [1., 0., 0.], [1., 1., 0.], [0., 1., 0.]],
);
mesh.insert_indices(Indices::U32(vec![0, 1, 2, 2, 3, 0]));
assert_eq!(
vec![
Triangle3d {
vertices: [
Vec3::new(0., 0., 0.),
Vec3::new(1., 0., 0.),
Vec3::new(1., 1., 0.),
]
},
Triangle3d {
vertices: [
Vec3::new(1., 1., 0.),
Vec3::new(0., 1., 0.),
Vec3::new(0., 0., 0.),
]
}
],
mesh.triangles().unwrap().collect::<Vec<Triangle3d>>()
);
}
#[test]
fn triangles_from_triangle_strip() {
let mut mesh = Mesh::new(
PrimitiveTopology::TriangleStrip,
RenderAssetUsages::default(),
);
let positions: Vec<Vec3> = [
[0., 0., 0.],
[1., 0., 0.],
[0., 1., 0.],
[1., 1., 0.],
[0., 2., 0.],
[1., 2., 0.],
]
.into_iter()
.map(Vec3::from_array)
.collect();
mesh.insert_attribute(Mesh::ATTRIBUTE_POSITION, positions.clone());
mesh.insert_indices(Indices::U32(vec![0, 1, 2, 3, 4, 5]));
assert_eq!(
vec![
Triangle3d {
vertices: [positions[0], positions[1], positions[2]]
},
Triangle3d {
vertices: [positions[2], positions[1], positions[3]]
},
Triangle3d {
vertices: [positions[2], positions[3], positions[4]]
},
Triangle3d {
vertices: [positions[4], positions[3], positions[5]]
},
],
mesh.triangles().unwrap().collect::<Vec<Triangle3d>>()
);
}
#[test]
fn take_gpu_data_calculates_aabb() {
let mut mesh = Mesh::new(
PrimitiveTopology::TriangleList,
RenderAssetUsages::default(),
);
mesh.insert_attribute(
Mesh::ATTRIBUTE_POSITION,
vec![
[-0.5, 0., 0.],
[-1., 0., 0.],
[-1., -1., 0.],
[-0.5, -1., 0.],
],
);
mesh.insert_indices(Indices::U32(vec![0, 1, 2, 2, 3, 0]));
mesh = mesh.take_gpu_data().unwrap();
assert_eq!(
mesh.final_aabb,
Some(Aabb3d::from_min_max([-1., -1., 0.], [-0.5, 0., 0.]))
);
}
#[cfg(feature = "serialize")]
#[test]
fn serialize_deserialize_mesh() {
let mut mesh = Mesh::new(
PrimitiveTopology::TriangleList,
RenderAssetUsages::default(),
);
mesh.insert_attribute(
Mesh::ATTRIBUTE_POSITION,
vec![[0., 0., 0.], [2., 0., 0.], [0., 1., 0.], [0., 0., 1.]],
);
mesh.insert_indices(Indices::U16(vec![0, 1, 2, 0, 2, 3]));
let serialized_mesh = SerializedMesh::from_mesh(mesh.clone());
let serialized_string = serde_json::to_string(&serialized_mesh).unwrap();
let serialized_mesh_from_string: SerializedMesh =
serde_json::from_str(&serialized_string).unwrap();
let deserialized_mesh = serialized_mesh_from_string.into_mesh();
assert_eq!(mesh, deserialized_mesh);
}
#[test]
fn merge_duplicate_vertices() {
let mut mesh = Mesh::new(
PrimitiveTopology::TriangleList,
RenderAssetUsages::default(),
);
let positions = vec![
[0.0, 0.0, 0.0],
[1.0, 0.0, 0.0],
[1.0, 1.0, 0.0],
[1.0, 1.0, 0.0],
[0.0, 1.0, 0.0],
[0.0, 0.0, 0.0],
];
let uvs = vec![
[0.0, 0.0],
[1.0, 0.0],
[1.0, 1.0],
[1.0, 1.0],
[0.0, 1.0],
[0.0, 0.5],
];
mesh.insert_attribute(
Mesh::ATTRIBUTE_POSITION,
VertexAttributeValues::Float32x3(positions.clone()),
);
mesh.insert_attribute(
Mesh::ATTRIBUTE_UV_0,
VertexAttributeValues::Float32x2(uvs.clone()),
);
let res = mesh.merge_duplicate_vertices();
assert!(res.is_ok());
assert_eq!(6, mesh.indices().unwrap().len());
assert_eq!(5, mesh.attribute(Mesh::ATTRIBUTE_POSITION).unwrap().len());
assert_eq!(5, mesh.attribute(Mesh::ATTRIBUTE_UV_0).unwrap().len());
mesh.duplicate_vertices();
assert!(mesh.indices().is_none());
let VertexAttributeValues::Float32x3(new_positions) =
mesh.attribute(Mesh::ATTRIBUTE_POSITION).unwrap()
else {
panic!("Unexpected attribute type")
};
let VertexAttributeValues::Float32x2(new_uvs) =
mesh.attribute(Mesh::ATTRIBUTE_UV_0).unwrap()
else {
panic!("Unexpected attribute type")
};
assert_eq!(&positions, new_positions);
assert_eq!(&uvs, new_uvs);
}
}