1use 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
13const CAMERA_INITIAL_POSITION: Vec3 = vec3(-0.4, 0.0, 0.0);
15
16#[derive(Resource)]
18struct AppStatus {
19 light_mode: LightMode,
21 anisotropy_enabled: bool,
23 visible_scene: Scene,
25}
26
27#[derive(Clone, Copy, PartialEq, Default)]
30enum LightMode {
31 #[default]
33 Directional,
34 Point,
36 EnvironmentMap,
38}
39
40#[derive(Component)]
47struct MaterialVariants {
48 anisotropic: Handle<StandardMaterial>,
50 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
80fn 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
99fn 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
135fn 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
148fn 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
179fn 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
191fn 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
211fn 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 keyboard.just_pressed(KeyCode::Space) {
224 match app_status.light_mode {
225 LightMode::Directional => {
226 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 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 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 keyboard.just_pressed(KeyCode::Enter) {
264 app_status.anisotropy_enabled = !app_status.anisotropy_enabled;
265
266 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
289fn 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
296fn 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
317fn spawn_directional_light(commands: &mut Commands) {
319 commands.spawn(DirectionalLight {
320 color: WHITE.into(),
321 illuminance: 3000.0,
322 ..default()
323 });
324}
325
326fn 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 fn create_help_text(&self) -> Text {
338 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 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 let mesh_help_text = format!("Press Q to change to {}", self.visible_scene.next());
354
355 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}