use std::f32::consts::{FRAC_PI_2, TAU};
use bevy::prelude::*;
#[derive(Resource, Debug, Clone)]
pub struct DayCycleConfig {
pub day_length_secs: f32,
pub time_of_day: f32,
pub max_illuminance: f32,
pub day_ambient: f32,
pub night_ambient: f32,
}
impl Default for DayCycleConfig {
fn default() -> Self {
Self {
day_length_secs: 600.0,
time_of_day: 0.35, max_illuminance: 100_000.0,
day_ambient: 800.0,
night_ambient: 200.0,
}
}
}
#[derive(Component)]
pub struct SunLight;
fn spawn_sun(mut commands: Commands) {
commands.spawn((
SunLight,
DirectionalLight {
illuminance: 80_000.0,
shadows_enabled: true,
..default()
},
Transform::from_rotation(Quat::from_euler(EulerRot::YXZ, 0.3, -1.0, 0.0)),
));
}
fn advance_day_cycle(
time: Res<Time>,
mut config: ResMut<DayCycleConfig>,
mut sun_q: Query<(&mut DirectionalLight, &mut Transform), With<SunLight>>,
mut clear_color: ResMut<ClearColor>,
) {
config.time_of_day += time.delta_secs() / config.day_length_secs;
config.time_of_day %= 1.0;
let elevation = (TAU * config.time_of_day - FRAC_PI_2).sin();
let night_fraction = config.night_ambient / config.max_illuminance;
let t_day = elevation.max(-night_fraction).max(0.0) + night_fraction;
let illuminance = t_day * config.max_illuminance;
let t_sky = ((elevation + 1.0) * 0.5).clamp(0.0, 1.0);
let sky_r = 0.05 + t_sky * 0.48;
let sky_g = 0.05 + t_sky * 0.68;
let sky_b = 0.15 + t_sky * 0.75;
clear_color.0 = Color::srgb(sky_r, sky_g, sky_b);
let sun_yaw = std::f32::consts::FRAC_PI_4;
let sun_pitch = -(elevation * FRAC_PI_2 * 0.9);
for (mut light, mut transform) in sun_q.iter_mut() {
light.illuminance = illuminance;
transform.rotation = Quat::from_euler(EulerRot::YXZ, sun_yaw, sun_pitch, 0.0);
}
}
pub struct DayCyclePlugin;
impl Plugin for DayCyclePlugin {
fn build(&self, app: &mut App) {
app.init_resource::<DayCycleConfig>();
app.add_systems(Startup, spawn_sun);
app.add_systems(Update, advance_day_cycle);
}
}