shader_material_glsl/
shader_material_glsl.rs

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