docs/bevy/release-content/release-notes/extended_material_2d.md 2.1 K · 71 lines · raw · history

1 ---
2 title: Extended material 2D
3 authors: ["@cookie1170"]
4 pull_requests: [25183]
5 ---
6
7 Bevy now provides a 2D analog to 3D's [`ExtendedMaterial`], which can be used to extend an existing material by implementing the `MaterialExtension2d` trait:
8
9 ```rs
10 #[derive(AsBindGroup, Reflect, Clone)]
11 struct MyExtendedMaterial {
12 // Make sure to make this high enough to not collide with the base material's uniforms!
13 #[uniform(20)]
14 important_binding: Vec4,
15 }
16
17 impl MaterialExtension2d for MyExtendedMaterial {
18 fn vertex_shader() -> Option<ShaderRef> {
19 None // Return `Some` to override the base material's vertex shader
20 }
21
22 fn fragment_shader() -> Option<ShaderRef> {
23 None // Return `Some` to override the base material's fragment shader
24 }
25
26 fn depth_bias(&self) -> Option<f32> {
27 None // Return `Some` to override the base material's depth bias
28 }
29
30 fn alpha_mode(&self) -> Option<AlphaMode2d> {
31 None // Return `Some` to override the base material's alpha mode
32 }
33 }
34 ```
35
36 This material can now be used in an `ExtendedMaterial2d` struct:
37
38 ```rs
39 fn main() {
40 App::new()
41 .add_plugins((
42 DefaultPlugins,
43 // Make sure to add a plugin for the material!
44 Material2dPlugin::<ExtendedMaterial2d<ColorMaterial, MyExtendedMaterial>>::default()
45 ))
46 .add_systems(Startup, spawn_extended_material_mesh)
47 .run();
48 }
49
50 fn spawn_extended_material_mesh(
51 mut commands: Commands,
52 mut materials: ResMut<Assets<ExtendedMaterial2d<ColorMaterial, MyExtendedMaterial>>>,
53 ) {
54 // Create an extended material with a `ColorMaterial` as the base and `MyExtendedMaterial` as the extension
55 // `ColorMaterial`'s bindings will be available to `MyExtendedMaterial`'s shader
56 let material = ExtendedMaterial2d {
57 base: ColorMaterial::from_color(Color::WHITE),
58 extension: MyExtendedMaterial {
59 important_binding: Vec4::ZERO,
60 },
61 };
62
63 let handle = materials.add(material);
64 commands.spawn((
65 Mesh2d,
66 MeshMaterial2d(handle),
67 ));
68 }
69 ```
70
71 [`ExtendedMaterial`]: https://docs.rs/bevy/latest/bevy/pbr/struct.ExtendedMaterial.html