Struct bevy::render::mesh::Mesh

pub struct Mesh { /* private fields */ }

Implementations§

§

impl Mesh

Contains geometry in the form of a mesh.

Often meshes are automatically generated by bevy’s asset loaders or primitives, such as shape::Cube or shape::Box, but you can also construct one yourself.

Example of constructing a mesh (to be rendered with a StandardMaterial):

fn create_simple_parallelogram() -> Mesh {
    // Create a new mesh, add 4 vertices, each with its own position attribute (coordinate in
    // 3D space), for each of the corners of the parallelogram.
    let mut mesh = Mesh::new(PrimitiveTopology::TriangleList);
    mesh.insert_attribute(
        Mesh::ATTRIBUTE_POSITION,
        vec![[0.0, 0.0, 0.0], [1.0, 2.0, 0.0], [2.0, 2.0, 0.0], [1.0, 0.0, 0.0]]
    );
    // Assign a UV coordinate to each vertex.
    mesh.insert_attribute(
        Mesh::ATTRIBUTE_UV_0,
        vec![[0.0, 1.0], [0.5, 0.0], [1.0, 0.0], [0.5, 1.0]]
    );
    // Assign normals (everything points outwards)
    mesh.insert_attribute(
       Mesh::ATTRIBUTE_NORMAL,
       vec![[0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0]]
    );
    // After defining all the vertices and their attributes, build each triangle using the
    // indices of the vertices that make it up in a counter-clockwise order.
    mesh.set_indices(Some(Indices::U32(vec![
        // First triangle
        0, 3, 1,
        // Second triangle
        1, 3, 2
    ])));
    mesh
    // For further visualization, explanation, and examples see the built-in Bevy examples
    // and the implementation of the built-in shapes.
}

Common points of confusion:

  • UV maps in Bevy are “flipped”, (0.0, 0.0) = Top-Left (not Bot-Left like OpenGL)
  • It is normal for multiple vertices to have the same position attribute - it’s a common technique in 3D modelling for complex UV mapping or other calculations.

To render correctly with StandardMaterial a mesh needs to have properly defined:

  • UVs: Bevy needs to know how to map a texture onto the mesh.
  • Normals: Bevy needs to know how light interacts with your mesh. ([0.0, 0.0, 1.0] is very common for simple meshes because simple meshes are smooth, and they don’t require complex light calculations.)
  • Vertex winding order - the default behavior is with StandardMaterial.cull_mode = Some(Face::Front) which means that by default Bevy would only render the front of each triangle, and the front is the side of the triangle in which the vertices appear in a counter-clockwise order.

pub const ATTRIBUTE_POSITION: MeshVertexAttribute = MeshVertexAttribute::new("Vertex_Position", 0, VertexFormat::Float32x3)

Where the vertex is located in space. Use in conjunction with Mesh::insert_attribute

pub const ATTRIBUTE_NORMAL: MeshVertexAttribute = MeshVertexAttribute::new("Vertex_Normal", 1, VertexFormat::Float32x3)

The direction the vertex normal is facing in. Use in conjunction with Mesh::insert_attribute

pub const ATTRIBUTE_UV_0: MeshVertexAttribute = MeshVertexAttribute::new("Vertex_Uv", 2, VertexFormat::Float32x2)

Texture coordinates for the vertex. Use in conjunction with Mesh::insert_attribute

pub const ATTRIBUTE_TANGENT: MeshVertexAttribute = MeshVertexAttribute::new("Vertex_Tangent", 3, VertexFormat::Float32x4)

The direction of the vertex tangent. Used for normal mapping

pub const ATTRIBUTE_COLOR: MeshVertexAttribute = MeshVertexAttribute::new("Vertex_Color", 4, VertexFormat::Float32x4)

Per vertex coloring. Use in conjunction with Mesh::insert_attribute

pub const ATTRIBUTE_JOINT_WEIGHT: MeshVertexAttribute = MeshVertexAttribute::new("Vertex_JointWeight", 5, VertexFormat::Float32x4)

Per vertex joint transform matrix weight. Use in conjunction with Mesh::insert_attribute

pub const ATTRIBUTE_JOINT_INDEX: MeshVertexAttribute = MeshVertexAttribute::new("Vertex_JointIndex", 6, VertexFormat::Uint16x4)

Per vertex joint transform matrix index. Use in conjunction with Mesh::insert_attribute

pub fn new(primitive_topology: PrimitiveTopology) -> Mesh

Construct a new mesh. You need to provide a PrimitiveTopology so that the renderer knows how to treat the vertex data. Most of the time this will be PrimitiveTopology::TriangleList.

pub fn primitive_topology(&self) -> PrimitiveTopology

Returns the topology of the mesh.

pub fn insert_attribute( &mut self, attribute: MeshVertexAttribute, values: impl Into<VertexAttributeValues> )

Sets the data for a vertex attribute (position, normal etc.). The name will often be one of the associated constants such as Mesh::ATTRIBUTE_POSITION.

Panics

Panics when the format of the values does not match the attribute’s format.

pub fn remove_attribute( &mut self, attribute: impl Into<MeshVertexAttributeId> ) -> Option<VertexAttributeValues>

Removes the data for a vertex attribute

pub fn contains_attribute(&self, id: impl Into<MeshVertexAttributeId>) -> bool

pub fn attribute( &self, id: impl Into<MeshVertexAttributeId> ) -> Option<&VertexAttributeValues>

Retrieves the data currently set to the vertex attribute with the specified name.

pub fn attribute_mut( &mut self, id: impl Into<MeshVertexAttributeId> ) -> Option<&mut VertexAttributeValues>

Retrieves the data currently set to the vertex attribute with the specified name mutably.

pub fn attributes( &self ) -> impl Iterator<Item = (MeshVertexAttributeId, &VertexAttributeValues)>

Returns an iterator that yields references to the data of each vertex attribute.

pub fn attributes_mut( &mut self ) -> impl Iterator<Item = (MeshVertexAttributeId, &mut VertexAttributeValues)>

Returns an iterator that yields mutable references to the data of each vertex attribute.

pub fn set_indices(&mut self, indices: Option<Indices>)

Sets the vertex indices of the mesh. They describe how triangles are constructed out of the vertex attributes and are therefore only useful for the PrimitiveTopology variants that use triangles.

pub fn indices(&self) -> Option<&Indices>

Retrieves the vertex indices of the mesh.

pub fn indices_mut(&mut self) -> Option<&mut Indices>

Retrieves the vertex indices of the mesh mutably.

pub fn get_index_buffer_bytes(&self) -> Option<&[u8]>

Computes and returns the index data of the mesh as bytes. This is used to transform the index data into a GPU friendly format.

pub fn get_mesh_vertex_buffer_layout( &self ) -> Hashed<InnerMeshVertexBufferLayout, FixedState>

Get this Mesh’s MeshVertexBufferLayout, used in SpecializedMeshPipeline.

pub fn count_vertices(&self) -> usize

Counts all vertices of the mesh.

Panics

Panics if the attributes have different vertex counts.

pub fn get_vertex_buffer_data(&self) -> Vec<u8, Global>

Computes and returns the vertex data of the mesh as bytes. Therefore the attributes are located in the order of their MeshVertexAttribute::id. This is used to transform the vertex data into a GPU friendly format.

Panics

Panics if the attributes have different vertex counts.

pub fn duplicate_vertices(&mut self)

Duplicates the vertex attributes so that no vertices are shared.

This can dramatically increase the vertex count, so make sure this is what you want. Does nothing if no Indices are set.

pub fn compute_flat_normals(&mut self)

Calculates the Mesh::ATTRIBUTE_NORMAL of a mesh.

Panics

Panics if Indices are set or Mesh::ATTRIBUTE_POSITION is not of type float3 or if the mesh has any other topology than PrimitiveTopology::TriangleList. Consider calling Mesh::duplicate_vertices or export your mesh with normal attributes.

pub fn generate_tangents(&mut self) -> Result<(), GenerateTangentsError>

Generate tangents for the mesh using the mikktspace algorithm.

Sets the Mesh::ATTRIBUTE_TANGENT attribute if successful. Requires a PrimitiveTopology::TriangleList topology and the Mesh::ATTRIBUTE_POSITION, Mesh::ATTRIBUTE_NORMAL and Mesh::ATTRIBUTE_UV_0 attributes set.

pub fn compute_aabb(&self) -> Option<Aabb>

Compute the Axis-Aligned Bounding Box of the mesh vertices in model space

pub fn has_morph_targets(&self) -> bool

Whether this mesh has morph targets.

pub fn set_morph_targets(&mut self, morph_targets: Handle<Image>)

Set morph targets image for this mesh. This requires a “morph target image”. See MorphTargetImage for info.

pub fn set_morph_target_names(&mut self, names: Vec<String, Global>)

Sets the names of each morph target. This should correspond to the order of the morph targets in set_morph_targets.

pub fn morph_target_names(&self) -> Option<&[String]>

Gets a list of all morph target names, if they exist.

Trait Implementations§

§

impl Clone for Mesh

§

fn clone(&self) -> Mesh

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
§

impl Debug for Mesh

§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
§

impl From<Box> for Mesh

§

fn from(sp: Box) -> Mesh

Converts to this type from the input type.
§

impl From<Capsule> for Mesh

§

fn from(capsule: Capsule) -> Mesh

Converts to this type from the input type.
§

impl From<Circle> for Mesh

§

fn from(circle: Circle) -> Mesh

Converts to this type from the input type.
§

impl From<Cube> for Mesh

§

fn from(cube: Cube) -> Mesh

Converts to this type from the input type.
§

impl From<Cylinder> for Mesh

§

fn from(c: Cylinder) -> Mesh

Converts to this type from the input type.
§

impl From<Plane> for Mesh

§

fn from(plane: Plane) -> Mesh

Converts to this type from the input type.
§

impl From<Quad> for Mesh

§

fn from(quad: Quad) -> Mesh

Converts to this type from the input type.
§

impl From<RegularPolygon> for Mesh

§

fn from(polygon: RegularPolygon) -> Mesh

Converts to this type from the input type.
§

impl From<Torus> for Mesh

§

fn from(torus: Torus) -> Mesh

Converts to this type from the input type.
§

impl From<UVSphere> for Mesh

§

fn from(sphere: UVSphere) -> Mesh

Converts to this type from the input type.
§

impl RenderAsset for Mesh

§

fn extract_asset(&self) -> <Mesh as RenderAsset>::ExtractedAsset

Clones the mesh.

§

fn prepare_asset( mesh: <Mesh as RenderAsset>::ExtractedAsset, _: &mut <<Mesh as RenderAsset>::Param as SystemParam>::Item<'_, '_> ) -> Result<<Mesh as RenderAsset>::PreparedAsset, PrepareAssetError<<Mesh as RenderAsset>::ExtractedAsset>>

Converts the extracted mesh a into GpuMesh.

§

type ExtractedAsset = Mesh

The representation of the asset in the “render world”.
§

type PreparedAsset = GpuMesh

The GPU-representation of the asset.
§

type Param = (Res<'static, RenderDevice>, Res<'static, RenderAssets<Image>>)

Specifies all ECS data required by RenderAsset::prepare_asset. For convenience use the lifetimeless SystemParam.
§

impl TryFrom<Icosphere> for Mesh

§

type Error = FromIcosphereError

The type returned in the event of a conversion error.
§

fn try_from( sphere: Icosphere ) -> Result<Mesh, <Mesh as TryFrom<Icosphere>>::Error>

Performs the conversion.
§

impl TypePath for Mesh

§

fn type_path() -> &'static str

Returns the fully qualified path of the underlying type. Read more
§

fn short_type_path() -> &'static str

Returns a short, pretty-print enabled path to the type. Read more
§

fn type_ident() -> Option<&'static str>

Returns the name of the type, or None if it is anonymous. Read more
§

fn crate_name() -> Option<&'static str>

Returns the name of the crate the type is in, or None if it is anonymous. Read more
§

fn module_path() -> Option<&'static str>

Returns the path to the moudle the type is in, or None if it is anonymous. Read more
§

impl TypeUuid for Mesh

§

const TYPE_UUID: Uuid = bevy_reflect::Uuid::from_bytes([142, 203, 172, 15, 245, 69, 68, 115, 173, 67, 225, 244, 36, 58, 245, 30])

Auto Trait Implementations§

§

impl RefUnwindSafe for Mesh

§

impl Send for Mesh

§

impl Sync for Mesh

§

impl Unpin for Mesh

§

impl UnwindSafe for Mesh

Blanket Implementations§

source§

impl<T> Any for Twhere T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T, U> AsBindGroupShaderType<U> for Twhere U: ShaderType, &'a T: for<'a> Into<U>,

§

fn as_bind_group_shader_type(&self, _images: &RenderAssets<Image>) -> U

Return the T ShaderType for self. When used in AsBindGroup derives, it is safe to assume that all images in self exist.
source§

impl<T> Borrow<T> for Twhere T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> Downcast<T> for T

§

fn downcast(&self) -> &T

§

impl<T> Downcast for Twhere T: Any,

§

fn into_any(self: Box<T, Global>) -> Box<dyn Any, Global>

Convert Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>. Box<dyn Any> can then be further downcast into Box<ConcreteType> where ConcreteType implements Trait.
§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Convert Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
§

fn as_any(&self) -> &(dyn Any + 'static)

Convert &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Convert &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
§

impl<T> DowncastSync for Twhere T: Any + Send + Sync,

§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Send + Sync>

Convert Arc<Trait> (where Trait: Downcast) to Arc<Any>. Arc<Any> can then be further downcast into Arc<ConcreteType> where ConcreteType implements Trait.
§

impl<T> DynamicTypePath for Twhere T: TypePath,

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<S> FromSample<S> for S

§

fn from_sample_(s: S) -> S

source§

impl<T> Instrument for T

source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for Twhere U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> ToOwned for Twhere T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
§

impl<T, U> ToSample<U> for Twhere U: FromSample<T>,

§

fn to_sample_(self) -> U

source§

impl<T, U> TryFrom<U> for Twhere U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for Twhere U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<T> TypeData for Twhere T: 'static + Send + Sync + Clone,

§

impl<T> TypeUuidDynamic for Twhere T: TypeUuid,

§

fn type_uuid(&self) -> Uuid

Returns the UUID associated with this value’s type.

§

fn type_name(&self) -> &'static str

Returns the type name of this value’s type.

§

impl<T> Upcast<T> for T

§

fn upcast(&self) -> Option<&T>

source§

impl<T> WithSubscriber for T

source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
§

impl<T> Asset for Twhere T: TypeUuid + TypePath + AssetDynamic + TypeUuidDynamic,

§

impl<T> AssetDynamic for Twhere T: Send + Sync + 'static + TypeUuidDynamic,

§

impl<S, T> Duplex<S> for Twhere T: FromSample<S> + ToSample<S>,