custom_vertex_attribute/
custom_vertex_attribute.rs

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