custom_vertex_attribute/
custom_vertex_attribute.rs1use 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
16const 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
26const ATTRIBUTE_BLEND_COLOR: MeshVertexAttribute =
29 MeshVertexAttribute::new("BlendColor", 988540917, VertexFormat::Float32x4);
30
31fn 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 .with_inserted_attribute(
40 ATTRIBUTE_BLEND_COLOR,
41 vec![[1.0, 0.0, 0.0, 1.0]; 24],
43 );
44
45 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 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#[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}