Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bevyengine
GitHub Repository: bevyengine/bevy
Path: blob/main/examples/shader/shader_material_2d.rs
6595 views
1
//! A shader and a material that uses it.
2
3
use bevy::{
4
prelude::*,
5
reflect::TypePath,
6
render::render_resource::AsBindGroup,
7
shader::ShaderRef,
8
sprite_render::{AlphaMode2d, Material2d, Material2dPlugin},
9
};
10
11
/// This example uses a shader source file from the assets subdirectory
12
const SHADER_ASSET_PATH: &str = "shaders/custom_material_2d.wgsl";
13
14
fn main() {
15
App::new()
16
.add_plugins((
17
DefaultPlugins,
18
Material2dPlugin::<CustomMaterial>::default(),
19
))
20
.add_systems(Startup, setup)
21
.run();
22
}
23
24
// Setup a simple 2d scene
25
fn setup(
26
mut commands: Commands,
27
mut meshes: ResMut<Assets<Mesh>>,
28
mut materials: ResMut<Assets<CustomMaterial>>,
29
asset_server: Res<AssetServer>,
30
) {
31
// camera
32
commands.spawn(Camera2d);
33
34
// quad
35
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
// This is the struct that will be passed to your shader
46
#[derive(Asset, TypePath, AsBindGroup, Debug, Clone)]
47
struct CustomMaterial {
48
#[uniform(0)]
49
color: LinearRgba,
50
#[texture(1)]
51
#[sampler(2)]
52
color_texture: Option<Handle<Image>>,
53
}
54
55
/// The Material2d trait is very configurable, but comes with sensible defaults for all methods.
56
/// You only need to implement functions for features that need non-default behavior. See the Material2d api docs for details!
57
impl 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
}
66
67