use bevy::{
camera::Exposure,
core_pipeline::{tonemapping::Tonemapping, Skybox},
pbr::generate::generate_environment_map_light,
prelude::*,
render::{render_resource::TextureUsages, view::Hdr},
};
use std::{
f32::consts::PI,
fmt::{Display, Formatter, Result as FmtResult},
};
static STOP_ROTATION_HELP_TEXT: &str = "Press Enter to stop rotation";
static START_ROTATION_HELP_TEXT: &str = "Press Enter to start rotation";
static REFLECTION_MODE_HELP_TEXT: &str = "Press Space to switch reflection mode";
const ENV_MAP_INTENSITY: f32 = 5000.0;
#[derive(Resource)]
struct AppStatus {
reflection_mode: ReflectionMode,
rotating: bool,
sphere_roughness: f32,
}
#[derive(Clone, Copy, PartialEq)]
enum ReflectionMode {
EnvironmentMap = 0,
ReflectionProbe = 1,
GeneratedEnvironmentMap = 2,
}
#[derive(Resource)]
struct Cubemaps {
diffuse_environment_map: Handle<Image>,
specular_environment_map: Handle<Image>,
specular_reflection_probe: Handle<Image>,
}
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.init_resource::<AppStatus>()
.init_resource::<Cubemaps>()
.add_systems(Startup, setup)
.add_systems(PreUpdate, add_environment_map_to_camera)
.add_systems(
Update,
change_reflection_type.before(generate_environment_map_light),
)
.add_systems(Update, toggle_rotation)
.add_systems(Update, change_sphere_roughness)
.add_systems(
Update,
rotate_camera
.after(toggle_rotation)
.after(change_reflection_type),
)
.add_systems(Update, update_text.after(rotate_camera))
.add_systems(Update, setup_environment_map_usage)
.run();
}
fn setup(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
asset_server: Res<AssetServer>,
app_status: Res<AppStatus>,
cubemaps: Res<Cubemaps>,
) {
spawn_camera(&mut commands);
spawn_sphere(&mut commands, &mut meshes, &mut materials, &app_status);
spawn_reflection_probe(&mut commands, &cubemaps);
spawn_scene(&mut commands, &asset_server);
spawn_text(&mut commands, &app_status);
}
fn spawn_scene(commands: &mut Commands, asset_server: &AssetServer) {
commands.spawn((
SceneRoot(asset_server.load(GltfAssetLabel::Scene(0).from_asset("models/cubes/Cubes.glb"))),
CubesScene,
));
}
fn spawn_camera(commands: &mut Commands) {
commands.spawn((
Camera3d::default(),
Hdr,
Exposure { ev100: 11.0 },
Tonemapping::AcesFitted,
Transform::from_xyz(-3.883, 0.325, 2.781).looking_at(Vec3::ZERO, Vec3::Y),
));
}
fn spawn_sphere(
commands: &mut Commands,
meshes: &mut Assets<Mesh>,
materials: &mut Assets<StandardMaterial>,
app_status: &AppStatus,
) {
let sphere_mesh = meshes.add(Sphere::new(1.0).mesh().ico(7).unwrap());
commands.spawn((
Mesh3d(sphere_mesh.clone()),
MeshMaterial3d(materials.add(StandardMaterial {
base_color: Srgba::hex("#ffffff").unwrap().into(),
metallic: 1.0,
perceptual_roughness: app_status.sphere_roughness,
..StandardMaterial::default()
})),
SphereMaterial,
));
}
fn spawn_reflection_probe(commands: &mut Commands, cubemaps: &Cubemaps) {
commands.spawn((
LightProbe,
EnvironmentMapLight {
diffuse_map: cubemaps.diffuse_environment_map.clone(),
specular_map: cubemaps.specular_reflection_probe.clone(),
intensity: ENV_MAP_INTENSITY,
..default()
},
Transform::from_scale(Vec3::splat(2.0)),
));
}
fn spawn_text(commands: &mut Commands, app_status: &AppStatus) {
commands.spawn((
app_status.create_text(),
Node {
position_type: PositionType::Absolute,
bottom: px(12),
left: px(12),
..default()
},
));
}
fn add_environment_map_to_camera(
mut commands: Commands,
query: Query<Entity, Added<Camera3d>>,
cubemaps: Res<Cubemaps>,
) {
for camera_entity in query.iter() {
commands
.entity(camera_entity)
.insert(create_camera_environment_map_light(&cubemaps))
.insert(Skybox {
image: cubemaps.specular_environment_map.clone(),
brightness: ENV_MAP_INTENSITY,
..default()
});
}
}
fn change_reflection_type(
mut commands: Commands,
light_probe_query: Query<Entity, With<LightProbe>>,
cubes_scene_query: Query<Entity, With<CubesScene>>,
camera_query: Query<Entity, With<Camera3d>>,
keyboard: Res<ButtonInput<KeyCode>>,
mut app_status: ResMut<AppStatus>,
cubemaps: Res<Cubemaps>,
asset_server: Res<AssetServer>,
) {
if !keyboard.just_pressed(KeyCode::Space) {
return;
}
app_status.reflection_mode =
ReflectionMode::try_from((app_status.reflection_mode as u32 + 1) % 3).unwrap();
for light_probe in light_probe_query.iter() {
commands.entity(light_probe).despawn();
}
for scene_entity in cubes_scene_query.iter() {
commands.entity(scene_entity).despawn();
}
match app_status.reflection_mode {
ReflectionMode::EnvironmentMap | ReflectionMode::GeneratedEnvironmentMap => {}
ReflectionMode::ReflectionProbe => {
spawn_reflection_probe(&mut commands, &cubemaps);
spawn_scene(&mut commands, &asset_server);
}
}
for camera in camera_query.iter() {
commands
.entity(camera)
.remove::<(EnvironmentMapLight, GeneratedEnvironmentMapLight)>();
match app_status.reflection_mode {
ReflectionMode::EnvironmentMap | ReflectionMode::ReflectionProbe => {
commands
.entity(camera)
.insert(create_camera_environment_map_light(&cubemaps));
}
ReflectionMode::GeneratedEnvironmentMap => {
commands
.entity(camera)
.insert(GeneratedEnvironmentMapLight {
environment_map: cubemaps.specular_environment_map.clone(),
intensity: ENV_MAP_INTENSITY,
..default()
});
}
}
}
}
fn toggle_rotation(keyboard: Res<ButtonInput<KeyCode>>, mut app_status: ResMut<AppStatus>) {
if keyboard.just_pressed(KeyCode::Enter) {
app_status.rotating = !app_status.rotating;
}
}
fn update_text(mut text_query: Query<&mut Text>, app_status: Res<AppStatus>) {
for mut text in text_query.iter_mut() {
*text = app_status.create_text();
}
}
impl TryFrom<u32> for ReflectionMode {
type Error = ();
fn try_from(value: u32) -> Result<Self, Self::Error> {
match value {
0 => Ok(ReflectionMode::EnvironmentMap),
1 => Ok(ReflectionMode::ReflectionProbe),
2 => Ok(ReflectionMode::GeneratedEnvironmentMap),
_ => Err(()),
}
}
}
impl Display for ReflectionMode {
fn fmt(&self, formatter: &mut Formatter<'_>) -> FmtResult {
let text = match *self {
ReflectionMode::EnvironmentMap => "Environment map",
ReflectionMode::ReflectionProbe => "Reflection probe",
ReflectionMode::GeneratedEnvironmentMap => "Generated environment map",
};
formatter.write_str(text)
}
}
impl AppStatus {
fn create_text(&self) -> Text {
let rotation_help_text = if self.rotating {
STOP_ROTATION_HELP_TEXT
} else {
START_ROTATION_HELP_TEXT
};
format!(
"{}\n{}\nRoughness: {:.2}\n{}\nUp/Down arrows to change roughness",
self.reflection_mode,
rotation_help_text,
self.sphere_roughness,
REFLECTION_MODE_HELP_TEXT
)
.into()
}
}
fn create_camera_environment_map_light(cubemaps: &Cubemaps) -> EnvironmentMapLight {
EnvironmentMapLight {
diffuse_map: cubemaps.diffuse_environment_map.clone(),
specular_map: cubemaps.specular_environment_map.clone(),
intensity: ENV_MAP_INTENSITY,
..default()
}
}
fn rotate_camera(
time: Res<Time>,
mut camera_query: Query<&mut Transform, With<Camera3d>>,
app_status: Res<AppStatus>,
) {
if !app_status.rotating {
return;
}
for mut transform in camera_query.iter_mut() {
transform.translation = Vec2::from_angle(time.delta_secs() * PI / 5.0)
.rotate(transform.translation.xz())
.extend(transform.translation.y)
.xzy();
transform.look_at(Vec3::ZERO, Vec3::Y);
}
}
impl FromWorld for Cubemaps {
fn from_world(world: &mut World) -> Self {
Cubemaps {
diffuse_environment_map: world
.load_asset("environment_maps/pisa_diffuse_rgb9e5_zstd.ktx2"),
specular_environment_map: world
.load_asset("environment_maps/pisa_specular_rgb9e5_zstd.ktx2"),
specular_reflection_probe: world
.load_asset("environment_maps/cubes_reflection_probe_specular_rgb9e5_zstd.ktx2"),
}
}
}
fn setup_environment_map_usage(cubemaps: Res<Cubemaps>, mut images: ResMut<Assets<Image>>) {
if let Some(image) = images.get_mut(&cubemaps.specular_environment_map)
&& !image
.texture_descriptor
.usage
.contains(TextureUsages::COPY_SRC)
{
image.texture_descriptor.usage |= TextureUsages::COPY_SRC;
}
}
impl Default for AppStatus {
fn default() -> Self {
Self {
reflection_mode: ReflectionMode::ReflectionProbe,
rotating: false,
sphere_roughness: 0.2,
}
}
}
#[derive(Component)]
struct SphereMaterial;
#[derive(Component)]
struct CubesScene;
fn change_sphere_roughness(
keyboard: Res<ButtonInput<KeyCode>>,
mut app_status: ResMut<AppStatus>,
mut materials: ResMut<Assets<StandardMaterial>>,
sphere_query: Query<&MeshMaterial3d<StandardMaterial>, With<SphereMaterial>>,
) {
let roughness_delta = if keyboard.pressed(KeyCode::ArrowUp) {
0.01
} else if keyboard.pressed(KeyCode::ArrowDown) {
-0.01
} else {
0.0
};
if roughness_delta != 0.0 {
app_status.sphere_roughness =
(app_status.sphere_roughness + roughness_delta).clamp(0.0, 1.0);
for material_handle in sphere_query.iter() {
if let Some(material) = materials.get_mut(&material_handle.0) {
material.perceptual_roughness = app_status.sphere_roughness;
}
}
}
}