voxel_framework/world/daycycle.rs
1//! Procedural day/night cycle plugin for voxel worlds.
2//!
3//! [`DayCyclePlugin`] manages a single directional "sun" light whose
4//! illuminance and angle are updated every frame based on the current
5//! time of day. Ambient light brightness also tracks the sun elevation
6//! so the world darkens naturally at night.
7//!
8//! # Integration
9//!
10//! ```no_run
11//! use bevy::prelude::*;
12//! use voxel_framework::world::daycycle::{DayCycleConfig, DayCyclePlugin};
13//!
14//! App::new()
15//! .add_plugins(DefaultPlugins)
16//! .insert_resource(DayCycleConfig {
17//! day_length_secs: 300.0, // 5-minute days
18//! ..Default::default()
19//! })
20//! .add_plugins(DayCyclePlugin);
21//! ```
22
23use std::f32::consts::{FRAC_PI_2, TAU};
24
25use bevy::prelude::*;
26
27// ─── Resource ─────────────────────────────────────────────────────────────────
28
29/// Configuration and runtime state for the day/night cycle.
30///
31/// Insert this resource before adding [`DayCyclePlugin`] to override the
32/// defaults, or mutate it at runtime to skip time, set a starting hour, etc.
33///
34/// `time_of_day` advances automatically: `0.0` = midnight, `0.25` = dawn,
35/// `0.5` = noon, `0.75` = dusk, `1.0` wraps back to midnight.
36#[derive(Resource, Debug, Clone)]
37pub struct DayCycleConfig {
38 /// Length of one full day/night cycle in seconds.
39 ///
40 /// **Default: `600.0`** (10 minutes per day).
41 pub day_length_secs: f32,
42 /// Current time of day in the range `[0.0, 1.0)`.
43 ///
44 /// `0.0` = midnight, `0.5` = noon. Wraps at `1.0`.
45 /// **Default: `0.25`** (starts at dawn for a good first impression).
46 pub time_of_day: f32,
47 /// Maximum sun illuminance in lux, reached at solar noon.
48 ///
49 /// **Default: `100_000.0`.**
50 pub max_illuminance: f32,
51 /// Ambient light brightness during full daylight (sun at zenith).
52 ///
53 /// **Default: `800.0`.**
54 pub day_ambient: f32,
55 /// Ambient light brightness at night (no direct sun).
56 ///
57 /// **Default: `200.0`.**
58 pub night_ambient: f32,
59}
60
61impl Default for DayCycleConfig {
62 fn default() -> Self {
63 Self {
64 day_length_secs: 600.0,
65 time_of_day: 0.35, // start mid-morning — sun is visible and lit
66 max_illuminance: 100_000.0,
67 day_ambient: 800.0,
68 night_ambient: 200.0,
69 }
70 }
71}
72
73// ─── Marker ───────────────────────────────────────────────────────────────────
74
75/// Marker component placed on the directional light managed by [`DayCyclePlugin`].
76#[derive(Component)]
77pub struct SunLight;
78
79// ─── Systems ──────────────────────────────────────────────────────────────────
80
81fn spawn_sun(mut commands: Commands) {
82 commands.spawn((
83 SunLight,
84 DirectionalLight {
85 illuminance: 80_000.0,
86 shadows_enabled: true,
87 ..default()
88 },
89 Transform::from_rotation(Quat::from_euler(EulerRot::YXZ, 0.3, -1.0, 0.0)),
90 ));
91}
92
93fn advance_day_cycle(
94 time: Res<Time>,
95 mut config: ResMut<DayCycleConfig>,
96 mut sun_q: Query<(&mut DirectionalLight, &mut Transform), With<SunLight>>,
97 mut clear_color: ResMut<ClearColor>,
98) {
99 // Advance time.
100 config.time_of_day += time.delta_secs() / config.day_length_secs;
101 config.time_of_day %= 1.0;
102
103 // Map time_of_day to a sun elevation angle.
104 // sin(TAU * t - PI/2): -1 at midnight (t=0), +1 at noon (t=0.5).
105 let elevation = (TAU * config.time_of_day - FRAC_PI_2).sin();
106
107 // t_day: 0 at horizon, 1 at zenith. Add a soft floor so dawn/dusk is
108 // never pitch-black — night_ambient / max_illuminance gives a moonlight
109 // equivalent expressed as a fraction of full sun.
110 let night_fraction = config.night_ambient / config.max_illuminance;
111 let t_day = elevation.max(-night_fraction).max(0.0) + night_fraction;
112 let illuminance = t_day * config.max_illuminance;
113
114 // Sky/background color: dark blue at night → light blue at day.
115 let t_sky = ((elevation + 1.0) * 0.5).clamp(0.0, 1.0);
116 let sky_r = 0.05 + t_sky * 0.48;
117 let sky_g = 0.05 + t_sky * 0.68;
118 let sky_b = 0.15 + t_sky * 0.75;
119 clear_color.0 = Color::srgb(sky_r, sky_g, sky_b);
120
121 // Sun pitch: overhead at noon, below horizon at night.
122 let sun_yaw = std::f32::consts::FRAC_PI_4;
123 let sun_pitch = -(elevation * FRAC_PI_2 * 0.9);
124
125 for (mut light, mut transform) in sun_q.iter_mut() {
126 light.illuminance = illuminance;
127 transform.rotation = Quat::from_euler(EulerRot::YXZ, sun_yaw, sun_pitch, 0.0);
128 }
129}
130
131// ─── Plugin ───────────────────────────────────────────────────────────────────
132
133/// Plugin that adds a procedural day/night cycle.
134///
135/// On startup, spawns a [`DirectionalLight`] tagged [`SunLight`] and advances
136/// its illuminance and angle every frame according to [`DayCycleConfig`].
137/// The sun illuminance uses a soft floor (`night_ambient / max_illuminance`)
138/// so the scene is never completely dark even when the sun is below the horizon.
139///
140/// Configure via [`DayCycleConfig`] inserted before this plugin. The
141/// `time_of_day` field advances automatically and wraps at `1.0`.
142///
143/// # Example
144///
145/// ```no_run
146/// use bevy::prelude::*;
147/// use voxel_framework::world::daycycle::{DayCycleConfig, DayCyclePlugin};
148///
149/// App::new()
150/// .add_plugins(DefaultPlugins)
151/// .insert_resource(DayCycleConfig {
152/// day_length_secs: 120.0, // 2-minute days
153/// time_of_day: 0.3, // start mid-morning
154/// ..Default::default()
155/// })
156/// .add_plugins(DayCyclePlugin);
157/// ```
158pub struct DayCyclePlugin;
159
160impl Plugin for DayCyclePlugin {
161 fn build(&self, app: &mut App) {
162 app.init_resource::<DayCycleConfig>();
163 app.add_systems(Startup, spawn_sun);
164 app.add_systems(Update, advance_day_cycle);
165 }
166}