use bevy::ecs::query::QueryFilter;
use bevy::light::GlobalAmbientLight;
use bevy::prelude::*;
use super::LightingSystems;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct SunConfig {
pub color: Color,
pub illuminance: f32,
pub direction: Vec3,
pub shadows_enabled: bool,
}
impl Default for SunConfig {
fn default() -> Self {
Self {
color: Color::WHITE,
illuminance: 10_000.0,
direction: Vec3::NEG_Y,
shadows_enabled: false,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct FillLightConfig {
pub color: Color,
pub illuminance: f32,
pub direction: Option<Vec3>,
}
impl Default for FillLightConfig {
fn default() -> Self {
Self {
color: Color::WHITE,
illuminance: 1_000.0,
direction: None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct AmbientConfig {
pub color: Color,
pub brightness: f32,
}
impl Default for AmbientConfig {
fn default() -> Self {
Self {
color: Color::WHITE,
brightness: 80.0,
}
}
}
#[derive(Resource, Debug, Clone, Copy, PartialEq, Default)]
pub struct SceneLightingConfig {
pub sun: Option<SunConfig>,
pub fill: Option<FillLightConfig>,
pub ambient: Option<AmbientConfig>,
}
impl SceneLightingConfig {
pub fn sun_direction(&self) -> Option<Vec3> {
self.sun.map(|sun| normalize_or_down(sun.direction))
}
pub fn fill_direction(&self) -> Option<Vec3> {
let fill = self.fill?;
let explicit = fill.direction.and_then(Vec3::try_normalize);
Some(explicit.unwrap_or_else(|| -self.sun_direction().unwrap_or(Vec3::NEG_Y)))
}
}
fn normalize_or_down(direction: Vec3) -> Vec3 {
direction.try_normalize().unwrap_or(Vec3::NEG_Y)
}
pub fn light_rotation(direction: Vec3) -> Quat {
Quat::from_rotation_arc(Vec3::NEG_Z, normalize_or_down(direction))
}
#[derive(Component, Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct SceneSunLight;
#[derive(Component, Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct SceneFillLight;
#[derive(Clone, Copy)]
struct DirectionalSpec {
color: Color,
illuminance: f32,
shadows_enabled: bool,
rotation: Quat,
}
fn sync_directional<M: Component, F: QueryFilter>(
commands: &mut Commands,
query: &mut Query<(Entity, &mut DirectionalLight, &mut Transform), F>,
marker: M,
desired: Option<DirectionalSpec>,
) {
let mut kept = false;
for (entity, mut light, mut transform) in query.iter_mut() {
match desired {
Some(spec) if !kept => {
kept = true;
light.color = spec.color;
light.illuminance = spec.illuminance;
light.shadows_enabled = spec.shadows_enabled;
transform.rotation = spec.rotation;
}
_ => commands.entity(entity).try_despawn(),
}
}
if let (false, Some(spec)) = (kept, desired) {
commands.spawn((
marker,
DirectionalLight {
color: spec.color,
illuminance: spec.illuminance,
shadows_enabled: spec.shadows_enabled,
..default()
},
Transform::from_rotation(spec.rotation),
));
}
}
type SunQuery<'w, 's> = Query<
'w,
's,
(
Entity,
&'static mut DirectionalLight,
&'static mut Transform,
),
(With<SceneSunLight>, Without<SceneFillLight>),
>;
type FillQuery<'w, 's> = Query<
'w,
's,
(
Entity,
&'static mut DirectionalLight,
&'static mut Transform,
),
(With<SceneFillLight>, Without<SceneSunLight>),
>;
fn sync_scene_lighting(
mut commands: Commands,
config: Res<SceneLightingConfig>,
mut suns: SunQuery,
mut fills: FillQuery,
ambient: Option<ResMut<GlobalAmbientLight>>,
) {
if !config.is_changed() {
return;
}
let sun = config.sun.map(|sun| DirectionalSpec {
color: sun.color,
illuminance: sun.illuminance,
shadows_enabled: sun.shadows_enabled,
rotation: light_rotation(sun.direction),
});
sync_directional(&mut commands, &mut suns, SceneSunLight, sun);
let fill = config
.fill
.zip(config.fill_direction())
.map(|(fill, direction)| DirectionalSpec {
color: fill.color,
illuminance: fill.illuminance,
shadows_enabled: false,
rotation: light_rotation(direction),
});
sync_directional(&mut commands, &mut fills, SceneFillLight, fill);
if let Some(values) = config.ambient {
match ambient {
Some(mut ambient) => {
ambient.color = values.color;
ambient.brightness = values.brightness;
}
None => commands.insert_resource(GlobalAmbientLight {
color: values.color,
brightness: values.brightness,
..default()
}),
}
}
}
pub struct SceneLightingPlugin;
impl Plugin for SceneLightingPlugin {
fn build(&self, app: &mut App) {
app.init_resource::<SceneLightingConfig>();
app.add_systems(Update, sync_scene_lighting.in_set(LightingSystems::Scene));
}
}
#[cfg(test)]
mod tests {
use super::*;
fn app_with(config: SceneLightingConfig) -> App {
let mut app = App::new();
app.insert_resource(config);
app.add_plugins(SceneLightingPlugin);
app
}
fn suns(app: &mut App) -> Vec<(DirectionalLight, Transform)> {
let mut query = app
.world_mut()
.query_filtered::<(&DirectionalLight, &Transform), With<SceneSunLight>>();
query
.iter(app.world())
.map(|(light, transform)| (*light, *transform))
.collect()
}
fn fills(app: &mut App) -> Vec<(DirectionalLight, Transform)> {
let mut query = app
.world_mut()
.query_filtered::<(&DirectionalLight, &Transform), With<SceneFillLight>>();
query
.iter(app.world())
.map(|(light, transform)| (*light, *transform))
.collect()
}
#[test]
fn default_config_is_empty() {
let config = SceneLightingConfig::default();
assert_eq!(config.sun, None);
assert_eq!(config.fill, None);
assert_eq!(config.ambient, None);
assert_eq!(config.sun_direction(), None);
assert_eq!(config.fill_direction(), None);
}
#[test]
fn rotation_points_local_forward_along_direction() {
for direction in [
Vec3::NEG_Y,
Vec3::Y,
Vec3::X,
Vec3::Z,
Vec3::NEG_Z,
Vec3::new(-0.4, -1.0, 0.3),
] {
let forward = light_rotation(direction * 3.0) * Vec3::NEG_Z;
assert!(
forward.abs_diff_eq(direction.normalize(), 1e-5),
"{direction}: {forward}"
);
}
}
#[test]
fn invalid_direction_points_down() {
for direction in [
Vec3::ZERO,
Vec3::splat(f32::NAN),
Vec3::splat(f32::INFINITY),
] {
let forward = light_rotation(direction) * Vec3::NEG_Z;
assert!(forward.abs_diff_eq(Vec3::NEG_Y, 1e-5), "{direction}");
}
}
#[test]
fn fill_opposes_the_sun_unless_given_a_direction() {
let mut config = SceneLightingConfig {
sun: Some(SunConfig {
direction: Vec3::new(0.0, -5.0, 0.0),
..default()
}),
fill: Some(FillLightConfig::default()),
ambient: None,
};
assert!(config.fill_direction().unwrap().abs_diff_eq(Vec3::Y, 1e-6));
config.fill = Some(FillLightConfig {
direction: Some(Vec3::new(2.0, 0.0, 0.0)),
..default()
});
assert!(config.fill_direction().unwrap().abs_diff_eq(Vec3::X, 1e-6));
config.fill = Some(FillLightConfig {
direction: Some(Vec3::ZERO),
..default()
});
assert!(config.fill_direction().unwrap().abs_diff_eq(Vec3::Y, 1e-6));
config.sun = None;
assert!(config.fill_direction().unwrap().abs_diff_eq(Vec3::Y, 1e-6));
}
#[test]
fn default_config_spawns_nothing_and_leaves_ambient_alone() {
let mut app = app_with(SceneLightingConfig::default());
app.insert_resource(GlobalAmbientLight {
brightness: 123.0,
..default()
});
app.update();
app.update();
assert!(suns(&mut app).is_empty());
assert!(fills(&mut app).is_empty());
assert_eq!(
app.world().resource::<GlobalAmbientLight>().brightness,
123.0
);
}
#[test]
fn config_spawns_one_sun_and_one_fill() {
let mut app = app_with(SceneLightingConfig {
sun: Some(SunConfig {
color: Color::srgb(1.0, 0.9, 0.8),
illuminance: 5_000.0,
direction: Vec3::NEG_Y,
shadows_enabled: true,
}),
fill: Some(FillLightConfig {
color: Color::srgb(0.2, 0.3, 0.9),
illuminance: 250.0,
direction: None,
}),
ambient: None,
});
app.update();
app.update();
let suns = suns(&mut app);
assert_eq!(suns.len(), 1);
let (sun, sun_transform) = suns[0];
assert_eq!(sun.color, Color::srgb(1.0, 0.9, 0.8));
assert_eq!(sun.illuminance, 5_000.0);
assert!(sun.shadows_enabled);
assert!((sun_transform.rotation * Vec3::NEG_Z).abs_diff_eq(Vec3::NEG_Y, 1e-5));
let fills = fills(&mut app);
assert_eq!(fills.len(), 1);
let (fill, fill_transform) = fills[0];
assert_eq!(fill.color, Color::srgb(0.2, 0.3, 0.9));
assert_eq!(fill.illuminance, 250.0);
assert!(!fill.shadows_enabled);
assert!((fill_transform.rotation * Vec3::NEG_Z).abs_diff_eq(Vec3::Y, 1e-5));
}
#[test]
fn config_change_updates_the_same_light_and_none_despawns_it() {
let mut app = app_with(SceneLightingConfig {
sun: Some(SunConfig::default()),
fill: Some(FillLightConfig::default()),
ambient: None,
});
app.update();
let mut query = app
.world_mut()
.query_filtered::<Entity, With<SceneSunLight>>();
let first = query.single(app.world()).expect("one sun");
app.world_mut()
.resource_mut::<SceneLightingConfig>()
.sun
.as_mut()
.unwrap()
.illuminance = 42.0;
app.update();
let second = query.single(app.world()).expect("still one sun");
assert_eq!(first, second);
assert_eq!(suns(&mut app)[0].0.illuminance, 42.0);
*app.world_mut().resource_mut::<SceneLightingConfig>() = SceneLightingConfig::default();
app.update();
assert!(suns(&mut app).is_empty());
assert!(fills(&mut app).is_empty());
}
#[test]
fn ambient_is_written_or_inserted() {
let ambient = AmbientConfig {
color: Color::srgb(0.1, 0.2, 0.3),
brightness: 12.0,
};
let config = SceneLightingConfig {
ambient: Some(ambient),
..default()
};
let mut app = app_with(config);
app.insert_resource(GlobalAmbientLight::default());
app.update();
let res = app.world().resource::<GlobalAmbientLight>();
assert_eq!(res.color, ambient.color);
assert_eq!(res.brightness, 12.0);
let mut app = app_with(config);
app.update();
let res = app.world().resource::<GlobalAmbientLight>();
assert_eq!(res.color, ambient.color);
assert_eq!(res.brightness, 12.0);
}
#[test]
fn day_cycle_sun_is_not_touched() {
use crate::world::SunLight;
let mut app = app_with(SceneLightingConfig {
sun: Some(SunConfig {
illuminance: 7.0,
..default()
}),
..default()
});
let other = app
.world_mut()
.spawn((
SunLight,
DirectionalLight {
illuminance: 999.0,
..default()
},
))
.id();
app.update();
assert_eq!(
app.world()
.get::<DirectionalLight>(other)
.unwrap()
.illuminance,
999.0
);
assert_eq!(suns(&mut app).len(), 1);
}
}