Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bevyengine
GitHub Repository: bevyengine/bevy
Path: blob/main/examples/shader/shader_material.rs
6595 views
1
//! A shader and a material that uses it.
2
3
use bevy::{
4
prelude::*, reflect::TypePath, render::render_resource::AsBindGroup, shader::ShaderRef,
5
};
6
7
/// This example uses a shader source file from the assets subdirectory
8
const SHADER_ASSET_PATH: &str = "shaders/custom_material.wgsl";
9
10
fn main() {
11
App::new()
12
.add_plugins((DefaultPlugins, MaterialPlugin::<CustomMaterial>::default()))
13
.add_systems(Startup, setup)
14
.run();
15
}
16
17
/// set up a simple 3D scene
18
fn setup(
19
mut commands: Commands,
20
mut meshes: ResMut<Assets<Mesh>>,
21
mut materials: ResMut<Assets<CustomMaterial>>,
22
asset_server: Res<AssetServer>,
23
) {
24
// cube
25
commands.spawn((
26
Mesh3d(meshes.add(Cuboid::default())),
27
MeshMaterial3d(materials.add(CustomMaterial {
28
color: LinearRgba::BLUE,
29
color_texture: Some(asset_server.load("branding/icon.png")),
30
alpha_mode: AlphaMode::Blend,
31
})),
32
Transform::from_xyz(0.0, 0.5, 0.0),
33
));
34
35
// camera
36
commands.spawn((
37
Camera3d::default(),
38
Transform::from_xyz(-2.0, 2.5, 5.0).looking_at(Vec3::ZERO, Vec3::Y),
39
));
40
}
41
42
// This struct defines the data that will be passed to your shader
43
#[derive(Asset, TypePath, AsBindGroup, Debug, Clone)]
44
struct CustomMaterial {
45
#[uniform(0)]
46
color: LinearRgba,
47
#[texture(1)]
48
#[sampler(2)]
49
color_texture: Option<Handle<Image>>,
50
alpha_mode: AlphaMode,
51
}
52
53
/// The Material trait is very configurable, but comes with sensible defaults for all methods.
54
/// You only need to implement functions for features that need non-default behavior. See the Material api docs for details!
55
impl Material for CustomMaterial {
56
fn fragment_shader() -> ShaderRef {
57
SHADER_ASSET_PATH.into()
58
}
59
60
fn alpha_mode(&self) -> AlphaMode {
61
self.alpha_mode
62
}
63
}
64
65