docs/bevy/examples/3d/anisotropy.rs 11.8 K · 372 lines · raw · history

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