anisotropy/
anisotropy.rs

1//! Demonstrates anisotropy with the glTF sample barn lamp model.
2
3use std::fmt::Display;
4
5use bevy::{
6    color::palettes::{self, css::WHITE},
7    core_pipeline::Skybox,
8    math::vec3,
9    prelude::*,
10    time::Stopwatch,
11};
12
13/// The initial position of the camera.
14const CAMERA_INITIAL_POSITION: Vec3 = vec3(-0.4, 0.0, 0.0);
15
16/// The current settings of the app, as chosen by the user.
17#[derive(Resource)]
18struct AppStatus {
19    /// Which type of light is in the scene.
20    light_mode: LightMode,
21    /// Whether anisotropy is enabled.
22    anisotropy_enabled: bool,
23    /// Which mesh is visible
24    visible_scene: Scene,
25}
26
27/// Which type of light we're using: a directional light, a point light, or an
28/// environment map.
29#[derive(Clone, Copy, PartialEq, Default)]
30enum LightMode {
31    /// A rotating directional light.
32    #[default]
33    Directional,
34    /// A rotating point light.
35    Point,
36    /// An environment map (image-based lighting, including skybox).
37    EnvironmentMap,
38}
39
40/// A component that stores the version of the material with anisotropy and the
41/// version of the material without it.
42///
43/// This is placed on each mesh with a material. It exists so that the
44/// appropriate system can replace the materials when the user presses Enter to
45/// turn anisotropy on and off.
46#[derive(Component)]
47struct MaterialVariants {
48    /// The version of the material in the glTF file, with anisotropy.
49    anisotropic: Handle<StandardMaterial>,
50    /// The version of the material with anisotropy removed.
51    isotropic: Handle<StandardMaterial>,
52}
53
54#[derive(Default, Clone, Copy, PartialEq, Eq, Component)]
55enum Scene {
56    #[default]
57    BarnLamp,
58    Sphere,
59}
60
61impl Scene {
62    fn next(&self) -> Self {
63        match self {
64            Self::BarnLamp => Self::Sphere,
65            Self::Sphere => Self::BarnLamp,
66        }
67    }
68}
69
70impl Display for Scene {
71    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
72        let scene_name = match self {
73            Self::BarnLamp => "Barn Lamp",
74            Self::Sphere => "Sphere",
75        };
76        write!(f, "{scene_name}")
77    }
78}
79
80/// The application entry point.
81fn main() {
82    App::new()
83        .init_resource::<AppStatus>()
84        .add_plugins(DefaultPlugins.set(WindowPlugin {
85            primary_window: Some(Window {
86                title: "Bevy Anisotropy Example".into(),
87                ..default()
88            }),
89            ..default()
90        }))
91        .add_systems(Startup, setup)
92        .add_systems(Update, create_material_variants)
93        .add_systems(Update, animate_light)
94        .add_systems(Update, rotate_camera)
95        .add_systems(Update, (handle_input, update_help_text).chain())
96        .run();
97}
98
99/// Creates the initial scene.
100fn setup(mut commands: Commands, asset_server: Res<AssetServer>, app_status: Res<AppStatus>) {
101    commands.spawn((
102        Camera3d::default(),
103        Transform::from_translation(CAMERA_INITIAL_POSITION).looking_at(Vec3::ZERO, Vec3::Y),
104    ));
105
106    spawn_directional_light(&mut commands);
107
108    commands.spawn((
109        SceneRoot(asset_server.load("models/AnisotropyBarnLamp/AnisotropyBarnLamp.gltf#Scene0")),
110        Transform::from_xyz(0.0, 0.07, -0.13),
111        Scene::BarnLamp,
112    ));
113
114    commands.spawn((
115        Mesh3d(
116            asset_server.add(
117                Mesh::from(Sphere::new(0.1))
118                    .with_generated_tangents()
119                    .unwrap(),
120            ),
121        ),
122        MeshMaterial3d(asset_server.add(StandardMaterial {
123            base_color: palettes::tailwind::GRAY_300.into(),
124            anisotropy_rotation: 0.5,
125            anisotropy_strength: 1.,
126            ..default()
127        })),
128        Scene::Sphere,
129        Visibility::Hidden,
130    ));
131
132    spawn_text(&mut commands, &app_status);
133}
134
135/// Spawns the help text.
136fn spawn_text(commands: &mut Commands, app_status: &AppStatus) {
137    commands.spawn((
138        app_status.create_help_text(),
139        Node {
140            position_type: PositionType::Absolute,
141            bottom: px(12),
142            left: px(12),
143            ..default()
144        },
145    ));
146}
147
148/// For each material, creates a version with the anisotropy removed.
149///
150/// This allows the user to press Enter to toggle anisotropy on and off.
151fn create_material_variants(
152    mut commands: Commands,
153    mut materials: ResMut<Assets<StandardMaterial>>,
154    new_meshes: Query<
155        (Entity, &MeshMaterial3d<StandardMaterial>),
156        (
157            Added<MeshMaterial3d<StandardMaterial>>,
158            Without<MaterialVariants>,
159        ),
160    >,
161) {
162    for (entity, anisotropic_material_handle) in new_meshes.iter() {
163        let Some(anisotropic_material) = materials.get(anisotropic_material_handle).cloned() else {
164            continue;
165        };
166
167        commands.entity(entity).insert(MaterialVariants {
168            anisotropic: anisotropic_material_handle.0.clone(),
169            isotropic: materials.add(StandardMaterial {
170                anisotropy_texture: None,
171                anisotropy_strength: 0.0,
172                anisotropy_rotation: 0.0,
173                ..anisotropic_material
174            }),
175        });
176    }
177}
178
179/// A system that animates the light every frame, if there is one.
180fn animate_light(
181    mut lights: Query<&mut Transform, Or<(With<DirectionalLight>, With<PointLight>)>>,
182    time: Res<Time>,
183) {
184    let now = time.elapsed_secs();
185    for mut transform in lights.iter_mut() {
186        transform.translation = vec3(ops::cos(now), 1.0, ops::sin(now)) * vec3(3.0, 4.0, 3.0);
187        transform.look_at(Vec3::ZERO, Vec3::Y);
188    }
189}
190
191/// A system that rotates the camera if the environment map is enabled.
192fn rotate_camera(
193    mut camera: Query<&mut Transform, With<Camera>>,
194    app_status: Res<AppStatus>,
195    time: Res<Time>,
196    mut stopwatch: Local<Stopwatch>,
197) {
198    if app_status.light_mode == LightMode::EnvironmentMap {
199        stopwatch.tick(time.delta());
200    }
201
202    let now = stopwatch.elapsed_secs();
203    for mut transform in camera.iter_mut() {
204        *transform = Transform::from_translation(
205            Quat::from_rotation_y(now).mul_vec3(CAMERA_INITIAL_POSITION),
206        )
207        .looking_at(Vec3::ZERO, Vec3::Y);
208    }
209}
210
211/// Handles requests from the user to change the lighting or toggle anisotropy.
212fn handle_input(
213    mut commands: Commands,
214    asset_server: Res<AssetServer>,
215    cameras: Query<Entity, With<Camera>>,
216    lights: Query<Entity, Or<(With<DirectionalLight>, With<PointLight>)>>,
217    mut meshes: Query<(&mut MeshMaterial3d<StandardMaterial>, &MaterialVariants)>,
218    mut scenes: Query<(&mut Visibility, &Scene)>,
219    keyboard: Res<ButtonInput<KeyCode>>,
220    mut app_status: ResMut<AppStatus>,
221) {
222    // If Space was pressed, change the lighting.
223    if keyboard.just_pressed(KeyCode::Space) {
224        match app_status.light_mode {
225            LightMode::Directional => {
226                // Switch to a point light. Despawn all existing lights and
227                // create the light point.
228                app_status.light_mode = LightMode::Point;
229                for light in lights.iter() {
230                    commands.entity(light).despawn();
231                }
232                spawn_point_light(&mut commands);
233            }
234
235            LightMode::Point => {
236                // Switch to the environment map. Despawn all existing lights,
237                // and create the skybox and environment map.
238                app_status.light_mode = LightMode::EnvironmentMap;
239                for light in lights.iter() {
240                    commands.entity(light).despawn();
241                }
242                for camera in cameras.iter() {
243                    add_skybox_and_environment_map(&mut commands, &asset_server, camera);
244                }
245            }
246
247            LightMode::EnvironmentMap => {
248                // Switch back to a directional light. Despawn the skybox and
249                // environment map light, and recreate the directional light.
250                app_status.light_mode = LightMode::Directional;
251                for camera in cameras.iter() {
252                    commands
253                        .entity(camera)
254                        .remove::<Skybox>()
255                        .remove::<EnvironmentMapLight>();
256                }
257                spawn_directional_light(&mut commands);
258            }
259        }
260    }
261
262    // If Enter was pressed, toggle anisotropy on and off.
263    if keyboard.just_pressed(KeyCode::Enter) {
264        app_status.anisotropy_enabled = !app_status.anisotropy_enabled;
265
266        // Go through each mesh and alter its material.
267        for (mut material_handle, material_variants) in meshes.iter_mut() {
268            material_handle.0 = if app_status.anisotropy_enabled {
269                material_variants.anisotropic.clone()
270            } else {
271                material_variants.isotropic.clone()
272            }
273        }
274    }
275
276    if keyboard.just_pressed(KeyCode::KeyQ) {
277        app_status.visible_scene = app_status.visible_scene.next();
278        for (mut visibility, scene) in scenes.iter_mut() {
279            let new_vis = if *scene == app_status.visible_scene {
280                Visibility::Inherited
281            } else {
282                Visibility::Hidden
283            };
284            *visibility = new_vis;
285        }
286    }
287}
288
289/// A system that updates the help text based on the current app status.
290fn update_help_text(mut text_query: Query<&mut Text>, app_status: Res<AppStatus>) {
291    for mut text in text_query.iter_mut() {
292        *text = app_status.create_help_text();
293    }
294}
295
296/// Adds the skybox and environment map to the scene.
297fn add_skybox_and_environment_map(
298    commands: &mut Commands,
299    asset_server: &AssetServer,
300    entity: Entity,
301) {
302    commands
303        .entity(entity)
304        .insert(Skybox {
305            brightness: 5000.0,
306            image: asset_server.load("environment_maps/pisa_specular_rgb9e5_zstd.ktx2"),
307            ..default()
308        })
309        .insert(EnvironmentMapLight {
310            diffuse_map: asset_server.load("environment_maps/pisa_diffuse_rgb9e5_zstd.ktx2"),
311            specular_map: asset_server.load("environment_maps/pisa_specular_rgb9e5_zstd.ktx2"),
312            intensity: 2500.0,
313            ..default()
314        });
315}
316
317/// Spawns a rotating directional light.
318fn spawn_directional_light(commands: &mut Commands) {
319    commands.spawn(DirectionalLight {
320        color: WHITE.into(),
321        illuminance: 3000.0,
322        ..default()
323    });
324}
325
326/// Spawns a rotating point light.
327fn spawn_point_light(commands: &mut Commands) {
328    commands.spawn(PointLight {
329        color: WHITE.into(),
330        intensity: 200000.0,
331        ..default()
332    });
333}
334
335impl AppStatus {
336    /// Creates the help text as appropriate for the current app status.
337    fn create_help_text(&self) -> Text {
338        // Choose the appropriate help text for the anisotropy toggle.
339        let material_variant_help_text = if self.anisotropy_enabled {
340            "Press Enter to disable anisotropy"
341        } else {
342            "Press Enter to enable anisotropy"
343        };
344
345        // Choose the appropriate help text for the light toggle.
346        let light_help_text = match self.light_mode {
347            LightMode::Directional => "Press Space to switch to a point light",
348            LightMode::Point => "Press Space to switch to an environment map",
349            LightMode::EnvironmentMap => "Press Space to switch to a directional light",
350        };
351
352        // Choose the appropriate help text for the scene selector.
353        let mesh_help_text = format!("Press Q to change to {}", self.visible_scene.next());
354
355        // Build the `Text` object.
356        format!("{material_variant_help_text}\n{light_help_text}\n{mesh_help_text}",).into()
357    }
358}
359
360impl Default for AppStatus {
361    fn default() -> Self {
362        Self {
363            light_mode: default(),
364            anisotropy_enabled: true,
365            visible_scene: default(),
366        }
367    }
368}