voxel_framework/skybox/mod.rs
1//! Configurable skybox system for the voxel framework.
2//!
3//! # Modes
4//!
5//! Two display modes are available through [`SkyboxMode`]:
6//!
7//! * **`Starfield`** (default) — spawns a procedural field of unlit cube-shaped
8//! stars distributed on a large sphere using a golden-angle sunflower spiral.
9//! The background clear color is set to black automatically.
10//! * **`Color`** — sets the Bevy [`ClearColor`] to a solid color and spawns no
11//! geometry. Use this for day-sky tints or minimalist environments.
12//!
13//! # Render pipeline integration
14//!
15//! The starfield is composed of standard Bevy `Mesh3d` + `MeshMaterial3d`
16//! entities marked with [`SkyboxRoot`]. All star meshes are parented to a
17//! single root entity so they move with the scene. Because the star material
18//! has `unlit: true`, the starfield is unaffected by scene lighting and remains
19//! visible even in completely dark environments.
20//!
21//! For the `Color` mode, no entities are spawned; [`ClearColor`] is simply
22//! overwritten as a resource during the `Startup` schedule.
23//!
24//! # Integration
25//!
26//! ```no_run
27//! use bevy::prelude::*;
28//! use voxel_framework::skybox::{SkyboxConfig, SkyboxMode, SkyboxPlugin, StarfieldConfig};
29//!
30//! fn main() {
31//! App::new()
32//! .insert_resource(SkyboxConfig {
33//! mode: SkyboxMode::Starfield(StarfieldConfig {
34//! count: 1200,
35//! radius: 900.0,
36//! star_size: 0.4,
37//! color: Color::WHITE,
38//! }),
39//! })
40//! .add_plugins(SkyboxPlugin)
41//! .run();
42//! }
43//! ```
44
45use bevy::prelude::*;
46
47// ─── Starfield configuration ──────────────────────────────────────────────────
48
49/// Visual parameters for the procedural starfield rendered by
50/// [`SkyboxMode::Starfield`].
51///
52/// Stars are distributed using a golden-angle sunflower spiral on a sphere of
53/// radius [`radius`](StarfieldConfig::radius). Each star is a tiny unlit cube
54/// of side length [`star_size`](StarfieldConfig::star_size).
55#[derive(Debug, Clone)]
56pub struct StarfieldConfig {
57 /// Total number of star entities spawned.
58 ///
59 /// Higher values produce a denser sky at the cost of more draw calls.
60 /// Default: `800`.
61 pub count: u32,
62 /// Radius of the sphere on which stars are placed, in world units.
63 ///
64 /// This should be large enough to always surround the camera but smaller
65 /// than the far clipping plane of the active camera. Default: `900.0`.
66 pub radius: f32,
67 /// Side length of each star cube, in world units.
68 ///
69 /// Smaller values look more point-like; larger values produce visible
70 /// polygonal stars. Default: `0.5`.
71 pub star_size: f32,
72 /// Base color applied to all star meshes via an unlit [`StandardMaterial`].
73 ///
74 /// Because the material is unlit, scene lighting has no effect on this
75 /// color. Default: [`Color::WHITE`].
76 pub color: Color,
77}
78
79impl Default for StarfieldConfig {
80 fn default() -> Self {
81 Self {
82 count: 800,
83 radius: 900.0,
84 star_size: 0.5,
85 color: Color::WHITE,
86 }
87 }
88}
89
90// ─── SkyboxMode ───────────────────────────────────────────────────────────────
91
92/// Selects how the sky background is rendered.
93///
94/// Set this inside [`SkyboxConfig`] before adding [`SkyboxPlugin`]. Changing
95/// the mode at runtime requires re-spawning the skybox manually, as the setup
96/// system only runs at `Startup`.
97#[derive(Debug, Clone)]
98pub enum SkyboxMode {
99 /// Render a procedural starfield composed of small unlit cube meshes.
100 ///
101 /// The Bevy [`ClearColor`] is set to black automatically so the space
102 /// between stars appears dark. Appearance is controlled by the inner
103 /// [`StarfieldConfig`].
104 Starfield(StarfieldConfig),
105 /// Fill the background with a solid color by setting [`ClearColor`].
106 ///
107 /// No geometry is spawned. Use this for day-sky tints, sunset gradients
108 /// baked into a single color, or any environment where star geometry is
109 /// not needed.
110 Color(Color),
111 // Note: an HDR cubemap / asset mode is intentionally omitted here because
112 // it requires the "bevy_asset" and image features which this crate does not
113 // enable by default.
114}
115
116impl Default for SkyboxMode {
117 fn default() -> Self {
118 SkyboxMode::Starfield(StarfieldConfig::default())
119 }
120}
121
122// ─── SkyboxConfig resource ────────────────────────────────────────────────────
123
124/// Top-level configuration resource for the skybox system.
125///
126/// Insert a customized instance before adding [`SkyboxPlugin`] to override the
127/// default starfield, or rely on [`Default`] to get an 800-star white
128/// starfield.
129///
130/// # Examples
131///
132/// ```no_run
133/// use bevy::prelude::*;
134/// use voxel_framework::skybox::{SkyboxConfig, SkyboxMode};
135///
136/// // Solid-color sky (no star geometry spawned).
137/// let sky = SkyboxConfig { mode: SkyboxMode::Color(Color::srgb(0.5, 0.7, 1.0)) };
138/// ```
139#[derive(Resource, Debug, Clone, Default)]
140pub struct SkyboxConfig {
141 /// The rendering mode to use. Defaults to
142 /// `SkyboxMode::Starfield(StarfieldConfig::default())`.
143 pub mode: SkyboxMode,
144}
145
146// ─── Marker component ─────────────────────────────────────────────────────────
147
148/// Marker component attached to the skybox root entity.
149///
150/// When [`SkyboxMode::Starfield`] is active, all star mesh entities are
151/// parented to a single entity carrying this component. Query for `SkyboxRoot`
152/// to locate or despawn the entire starfield in one operation.
153#[derive(Component)]
154pub struct SkyboxRoot;
155
156// ─── Setup system ─────────────────────────────────────────────────────────────
157
158/// Startup system that spawns the skybox based on [`SkyboxConfig`].
159fn setup_skybox_system(
160 mut commands: Commands,
161 mut meshes: ResMut<Assets<Mesh>>,
162 mut materials: ResMut<Assets<StandardMaterial>>,
163 config: Res<SkyboxConfig>,
164) {
165 match &config.mode {
166 SkyboxMode::Starfield(cfg) => {
167 commands.insert_resource(ClearColor(Color::BLACK));
168 spawn_starfield(&mut commands, &mut meshes, &mut materials, cfg);
169 }
170 SkyboxMode::Color(color) => {
171 commands.insert_resource(ClearColor(*color));
172 }
173 }
174}
175
176/// Spawns star entities distributed on a sphere using a golden-angle sunflower
177/// spiral. Each star is a tiny unlit cube parented to a [`SkyboxRoot`] entity.
178fn spawn_starfield(
179 commands: &mut Commands,
180 meshes: &mut ResMut<Assets<Mesh>>,
181 materials: &mut ResMut<Assets<StandardMaterial>>,
182 cfg: &StarfieldConfig,
183) {
184 let star_mesh = meshes.add(Cuboid::new(cfg.star_size, cfg.star_size, cfg.star_size));
185 let star_material = materials.add(StandardMaterial {
186 base_color: cfg.color,
187 unlit: true,
188 ..default()
189 });
190
191 let golden_angle: f32 = std::f32::consts::PI * (3.0 - 5.0_f32.sqrt());
192
193 let mut children = Vec::with_capacity(cfg.count as usize);
194
195 for i in 0..cfg.count {
196 let t = i as f32 / cfg.count as f32;
197 // Map t -> [-1, 1] for the cosine of the polar angle
198 let cos_theta = 1.0 - 2.0 * t;
199 let sin_theta = (1.0 - cos_theta * cos_theta).max(0.0).sqrt();
200 let phi = golden_angle * i as f32;
201
202 let x = cfg.radius * sin_theta * phi.cos();
203 let y = cfg.radius * cos_theta;
204 let z = cfg.radius * sin_theta * phi.sin();
205
206 let child = commands
207 .spawn((
208 Mesh3d(star_mesh.clone()),
209 MeshMaterial3d(star_material.clone()),
210 Transform::from_translation(Vec3::new(x, y, z)),
211 ))
212 .id();
213 children.push(child);
214 }
215
216 commands
217 .spawn((SkyboxRoot, Transform::default(), Visibility::default()))
218 .add_children(&children);
219}
220
221// ─── Plugin ───────────────────────────────────────────────────────────────────
222
223/// Plugin that enables the skybox system.
224///
225/// # What it registers
226///
227/// * [`SkyboxConfig`] — initialized as a default resource (starfield with 800
228/// white stars). Insert a pre-populated instance before adding this plugin
229/// to override the defaults.
230/// * A `Startup` system that reads [`SkyboxConfig`] and either spawns the
231/// procedural starfield geometry or sets [`ClearColor`], depending on
232/// [`SkyboxMode`].
233///
234/// # Examples
235///
236/// ```no_run
237/// use bevy::prelude::*;
238/// use voxel_framework::skybox::{SkyboxConfig, SkyboxMode, SkyboxPlugin, StarfieldConfig};
239///
240/// App::new()
241/// .insert_resource(SkyboxConfig {
242/// mode: SkyboxMode::Color(Color::srgb(0.1, 0.1, 0.2)),
243/// })
244/// .add_plugins(SkyboxPlugin)
245/// .run();
246/// ```
247pub struct SkyboxPlugin;
248
249impl Plugin for SkyboxPlugin {
250 fn build(&self, app: &mut App) {
251 app.init_resource::<SkyboxConfig>();
252 app.add_systems(Startup, setup_skybox_system);
253 }
254}
255
256// ─── Tests ────────────────────────────────────────────────────────────────────
257
258#[cfg(test)]
259mod tests {
260 use super::*;
261
262 #[test]
263 fn test_skybox_default_is_starfield() {
264 let config = SkyboxConfig::default();
265 assert!(
266 matches!(config.mode, SkyboxMode::Starfield(_)),
267 "default SkyboxMode should be Starfield"
268 );
269 }
270
271 #[test]
272 fn test_starfield_config_defaults() {
273 let cfg = StarfieldConfig::default();
274 assert_eq!(cfg.count, 800);
275 assert_eq!(cfg.radius, 900.0);
276 assert_eq!(cfg.star_size, 0.5);
277 }
278}