Path: blob/main/examples/shader_advanced/custom_vertex_attribute.rs
6849 views
//! A shader that reads a mesh's custom vertex attribute.12use bevy::{3mesh::{MeshVertexAttribute, MeshVertexBufferLayoutRef},4pbr::{MaterialPipeline, MaterialPipelineKey},5prelude::*,6reflect::TypePath,7render::render_resource::{8AsBindGroup, RenderPipelineDescriptor, SpecializedMeshPipelineError, VertexFormat,9},10shader::ShaderRef,11};1213/// This example uses a shader source file from the assets subdirectory14const SHADER_ASSET_PATH: &str = "shaders/custom_vertex_attribute.wgsl";1516fn main() {17App::new()18.add_plugins((DefaultPlugins, MaterialPlugin::<CustomMaterial>::default()))19.add_systems(Startup, setup)20.run();21}2223// A "high" random id should be used for custom attributes to ensure consistent sorting and avoid collisions with other attributes.24// See the MeshVertexAttribute docs for more info.25const ATTRIBUTE_BLEND_COLOR: MeshVertexAttribute =26MeshVertexAttribute::new("BlendColor", 988540917, VertexFormat::Float32x4);2728/// set up a simple 3D scene29fn setup(30mut commands: Commands,31mut meshes: ResMut<Assets<Mesh>>,32mut materials: ResMut<Assets<CustomMaterial>>,33) {34let mesh = Mesh::from(Cuboid::default())35// Sets the custom attribute36.with_inserted_attribute(37ATTRIBUTE_BLEND_COLOR,38// The cube mesh has 24 vertices (6 faces, 4 vertices per face), so we insert one BlendColor for each39vec![[1.0, 0.0, 0.0, 1.0]; 24],40);4142// cube43commands.spawn((44Mesh3d(meshes.add(mesh)),45MeshMaterial3d(materials.add(CustomMaterial {46color: LinearRgba::WHITE,47})),48Transform::from_xyz(0.0, 0.5, 0.0),49));5051// camera52commands.spawn((53Camera3d::default(),54Transform::from_xyz(-2.0, 2.5, 5.0).looking_at(Vec3::ZERO, Vec3::Y),55));56}5758// This is the struct that will be passed to your shader59#[derive(Asset, TypePath, AsBindGroup, Debug, Clone)]60struct CustomMaterial {61#[uniform(0)]62color: LinearRgba,63}6465impl Material for CustomMaterial {66fn vertex_shader() -> ShaderRef {67SHADER_ASSET_PATH.into()68}69fn fragment_shader() -> ShaderRef {70SHADER_ASSET_PATH.into()71}7273fn specialize(74_pipeline: &MaterialPipeline,75descriptor: &mut RenderPipelineDescriptor,76layout: &MeshVertexBufferLayoutRef,77_key: MaterialPipelineKey<Self>,78) -> Result<(), SpecializedMeshPipelineError> {79let vertex_layout = layout.0.get_layout(&[80Mesh::ATTRIBUTE_POSITION.at_shader_location(0),81ATTRIBUTE_BLEND_COLOR.at_shader_location(1),82])?;83descriptor.vertex.buffers = vec![vertex_layout];84Ok(())85}86}878889