use bevy::light::GlobalAmbientLight;
use bevy::prelude::*;
use crate::MapStateResource;
#[derive(Component)]
pub struct RustialDirectionalLight;
pub fn sync_lights(
mut commands: Commands,
map: Res<MapStateResource>,
mut ambient: ResMut<GlobalAmbientLight>,
mut q_light: Query<
(Entity, &mut DirectionalLight, &mut Transform),
With<RustialDirectionalLight>,
>,
) {
let lighting = map.0.computed_lighting();
ambient.color = Color::linear_rgb(
lighting.ambient_color[0],
lighting.ambient_color[1],
lighting.ambient_color[2],
);
ambient.brightness = 80.0;
let dir = lighting.directional_dir;
let color = Color::linear_rgb(
lighting.directional_color[0],
lighting.directional_color[1],
lighting.directional_color[2],
);
let incoming = Vec3::new(-dir[0], -dir[1], -dir[2]);
let rotation = if incoming.length_squared() > 1e-6 {
Transform::default().looking_to(incoming, Vec3::Z).rotation
} else {
Quat::IDENTITY
};
let shadows_on = lighting.shadows_enabled;
if let Ok((_entity, mut dl, mut transform)) = q_light.single_mut() {
dl.color = color;
dl.illuminance = if lighting.lighting_enabled > 0.5 {
10_000.0
} else {
0.0
};
dl.shadows_enabled = shadows_on;
transform.rotation = rotation;
} else {
commands.spawn((
DirectionalLight {
color,
illuminance: if lighting.lighting_enabled > 0.5 {
10_000.0
} else {
0.0
},
shadows_enabled: shadows_on,
..Default::default()
},
Transform::from_rotation(rotation),
RustialDirectionalLight,
));
}
}