shader_material_screenspace_texture/
shader_material_screenspace_texture.rs

1//! A shader that samples a texture with view-independent UV coordinates.
2
3use 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
8const SHADER_ASSET_PATH: &str = "shaders/custom_material_screenspace_texture.wgsl";
9
10fn main() {
11    App::new()
12        .add_plugins((DefaultPlugins, MaterialPlugin::<CustomMaterial>::default()))
13        .add_systems(Startup, setup)
14        .add_systems(Update, rotate_camera)
15        .run();
16}
17
18#[derive(Component)]
19struct MainCamera;
20
21fn setup(
22    mut commands: Commands,
23    asset_server: Res<AssetServer>,
24    mut meshes: ResMut<Assets<Mesh>>,
25    mut custom_materials: ResMut<Assets<CustomMaterial>>,
26    mut standard_materials: ResMut<Assets<StandardMaterial>>,
27) {
28    commands.spawn((
29        Mesh3d(meshes.add(Plane3d::default().mesh().size(5.0, 5.0))),
30        MeshMaterial3d(standard_materials.add(Color::srgb(0.3, 0.5, 0.3))),
31    ));
32    commands.spawn((PointLight::default(), Transform::from_xyz(4.0, 8.0, 4.0)));
33
34    commands.spawn((
35        Mesh3d(meshes.add(Cuboid::default())),
36        MeshMaterial3d(custom_materials.add(CustomMaterial {
37            texture: asset_server.load(
38                "models/FlightHelmet/FlightHelmet_Materials_LensesMat_OcclusionRoughMetal.png",
39            ),
40        })),
41        Transform::from_xyz(0.0, 0.5, 0.0),
42    ));
43
44    // camera
45    commands.spawn((
46        Camera3d::default(),
47        Transform::from_xyz(4.0, 2.5, 4.0).looking_at(Vec3::ZERO, Vec3::Y),
48        MainCamera,
49    ));
50}
51
52fn rotate_camera(mut cam_transform: Single<&mut Transform, With<MainCamera>>, time: Res<Time>) {
53    cam_transform.rotate_around(
54        Vec3::ZERO,
55        Quat::from_axis_angle(Vec3::Y, 45f32.to_radians() * time.delta_secs()),
56    );
57    cam_transform.look_at(Vec3::ZERO, Vec3::Y);
58}
59
60#[derive(Asset, TypePath, AsBindGroup, Debug, Clone)]
61struct CustomMaterial {
62    #[texture(0)]
63    #[sampler(1)]
64    texture: Handle<Image>,
65}
66
67impl Material for CustomMaterial {
68    fn fragment_shader() -> ShaderRef {
69        SHADER_ASSET_PATH.into()
70    }
71}