shader_material_2d/
shader_material_2d.rs1use bevy::{
4 prelude::*,
5 reflect::TypePath,
6 render::render_resource::AsBindGroup,
7 shader::ShaderRef,
8 sprite_render::{AlphaMode2d, Material2d, Material2dPlugin},
9};
10
11const SHADER_ASSET_PATH: &str = "shaders/custom_material_2d.wgsl";
13
14fn main() {
15 App::new()
16 .add_plugins((
17 DefaultPlugins,
18 Material2dPlugin::<CustomMaterial>::default(),
19 ))
20 .add_systems(Startup, setup)
21 .run();
22}
23
24fn setup(
26 mut commands: Commands,
27 mut meshes: ResMut<Assets<Mesh>>,
28 mut materials: ResMut<Assets<CustomMaterial>>,
29 asset_server: Res<AssetServer>,
30) {
31 commands.spawn(Camera2d);
33
34 commands.spawn((
36 Mesh2d(meshes.add(Rectangle::default())),
37 MeshMaterial2d(materials.add(CustomMaterial {
38 color: LinearRgba::BLUE,
39 color_texture: Some(asset_server.load("branding/icon.png")),
40 })),
41 Transform::default().with_scale(Vec3::splat(128.)),
42 ));
43}
44
45#[derive(Asset, TypePath, AsBindGroup, Debug, Clone)]
47struct CustomMaterial {
48 #[uniform(0)]
49 color: LinearRgba,
50 #[texture(1)]
51 #[sampler(2)]
52 color_texture: Option<Handle<Image>>,
53}
54
55impl Material2d for CustomMaterial {
58 fn fragment_shader() -> ShaderRef {
59 SHADER_ASSET_PATH.into()
60 }
61
62 fn alpha_mode(&self) -> AlphaMode2d {
63 AlphaMode2d::Mask(0.5)
64 }
65}