Skip to main content

voxel_framework/generator/
asteroid.rs

1//! Procedural asteroid generator for [`DefaultVoxel`].
2//!
3//! # Algorithm
4//!
5//! [`AsteroidGenerator`] populates chunks using a density-field approach:
6//!
7//! 1. **Asteroid placement** — at construction time, [`AsteroidConfig::asteroid_count`]
8//!    asteroid centers and radii are derived deterministically from the seed
9//!    using [`hash3`] with decorrelated per-component inputs.  No `rand` crate
10//!    is involved, which avoids version-drift and guarantees identical output
11//!    across platforms.  The first asteroid is always pinned at the world
12//!    origin so there is always a guaranteed spawn point.
13//!
14//! 2. **Surface deformation** — for each voxel candidate the distance to the
15//!    nearest asteroid center is computed.  A surface displacement is sampled
16//!    from an FBM noise field (using [`fbm`] with configurable octaves,
17//!    frequency, and amplitude) evaluated at world-space coordinates normalized
18//!    by `2 × radius`.  The density is `radius − dist + surface_displacement`;
19//!    voxels with positive density are solid.
20//!
21//! 3. **Mineral distribution** — three independent FBM passes with seed offsets
22//!    of `+100`, `+200`, and `+300` produce separate noise fields for rare
23//!    minerals, silicon crystals, and iron ore respectively.  Threshold
24//!    comparisons on those fields determine which [`DefaultVoxel`] variant is
25//!    placed (see [`MineralFrequencies`] for the default thresholds).
26//!
27//! 4. **First-asteroid-wins** — when multiple asteroids overlap, the first one
28//!    in the precomputed list claims the voxel.  This keeps the logic O(n) per
29//!    voxel and produces seamless asteroid interiors.
30
31use bevy::math::{IVec3, Vec3};
32
33use crate::chunk::CHUNK_SIZE;
34use crate::chunk::Chunk;
35use crate::noise::{fbm, hash3};
36use crate::voxel::DefaultVoxel;
37
38use super::ChunkGenerator;
39
40/// Approximate volumetric distribution frequencies for each mineral type within
41/// a solid asteroid.
42///
43/// The values are not used as direct probability weights; rather they document
44/// the intended proportions that the FBM noise thresholds in
45/// `AsteroidGenerator::determine_mineral` were tuned to produce.  Changing
46/// these fields alone has no effect — they are for documentation and future
47/// tooling that may auto-tune thresholds to match target frequencies.
48///
49/// Values represent the fraction of solid voxels expected to contain each
50/// mineral.  The sum should be approximately `1.0`.
51#[derive(Clone, Debug)]
52pub struct MineralFrequencies {
53    /// Expected fraction of solid voxels that are rare mineral nodes.
54    ///
55    /// Default: `0.05` (~5 %).  Achieved by requiring `rare_noise > 0.55`.
56    pub rare_mineral: f32,
57    /// Expected fraction of solid voxels that are silicon crystal veins.
58    ///
59    /// Default: `0.15` (~15 %).  Achieved by requiring `crystal_noise > 0.30`.
60    pub silicon_crystal: f32,
61    /// Expected fraction of solid voxels that are iron ore deposits.
62    ///
63    /// Default: `0.25` (~25 %).  Achieved by requiring `iron_noise > 0.20`.
64    pub iron_ore: f32,
65    /// Expected fraction of solid voxels that are common rock (the fallback).
66    ///
67    /// Default: `0.55` (~55 %).
68    pub rock: f32,
69}
70
71impl Default for MineralFrequencies {
72    fn default() -> Self {
73        Self {
74            rare_mineral: 0.05,
75            silicon_crystal: 0.15,
76            iron_ore: 0.25,
77            rock: 0.55,
78        }
79    }
80}
81
82/// Configuration for the [`AsteroidGenerator`].
83///
84/// Controls asteroid count, size distribution, surface noise parameters, and
85/// mineral frequencies.  All generation is fully deterministic: the same
86/// `AsteroidConfig` always produces the same world.
87///
88/// Construct via [`AsteroidConfig::default`] and override individual fields:
89///
90/// ```rust,no_run
91/// use voxel_framework::generator::asteroid::AsteroidConfig;
92///
93/// let config = AsteroidConfig {
94///     seed: 42,
95///     asteroid_count: 12,
96///     min_radius: 15.0,
97///     max_radius: 80.0,
98///     ..AsteroidConfig::default()
99/// };
100/// ```
101#[derive(Clone, Debug)]
102pub struct AsteroidConfig {
103    /// Seed for the hash-based pseudo-random number generator.
104    ///
105    /// Changing the seed produces a completely different asteroid field.
106    pub seed: u32,
107
108    /// Number of asteroids to pre-compute and place in the world.
109    ///
110    /// The first asteroid is always at the origin.  Valid range: `1..`.
111    pub asteroid_count: usize,
112
113    /// Minimum asteroid radius in world units.
114    ///
115    /// Must satisfy `min_radius ≤ max_radius`.  Valid range: `> 0.0`.
116    pub min_radius: f32,
117
118    /// Maximum asteroid radius in world units.
119    ///
120    /// Must satisfy `max_radius ≥ min_radius`.
121    pub max_radius: f32,
122
123    /// Number of FBM octaves used for surface deformation.
124    ///
125    /// More octaves add finer surface detail at the cost of more noise
126    /// evaluations per voxel.  Typical range: `2..=6`.  Default: `4`.
127    pub noise_octaves: u32,
128
129    /// Base sampling frequency for the surface FBM field.
130    ///
131    /// Higher values produce a rougher, more pitted surface.  The field is
132    /// sampled at world coordinates divided by `2 × radius`, so the actual
133    /// spatial frequency scales with asteroid size.  Default: `2.5`.
134    pub noise_frequency: f32,
135
136    /// Surface displacement amplitude as a fraction of the asteroid radius.
137    ///
138    /// A value of `0.34` means the surface can deviate by up to ±34 % of the
139    /// radius.  Valid range: `0.0..=1.0`.  Default: `0.34`.
140    pub noise_amplitude: f32,
141
142    /// Intended mineral distribution frequencies (documentation only).
143    ///
144    /// See [`MineralFrequencies`] for details.
145    pub mineral_frequencies: MineralFrequencies,
146}
147
148impl Default for AsteroidConfig {
149    fn default() -> Self {
150        Self {
151            seed: 12345,
152            asteroid_count: 8,
153            min_radius: 20.0,
154            max_radius: 60.0,
155            noise_octaves: 4,
156            noise_frequency: 2.5,
157            noise_amplitude: 0.34,
158            mineral_frequencies: MineralFrequencies::default(),
159        }
160    }
161}
162
163/// Pre-computed asteroid with center position and radius.
164#[derive(Clone, Debug)]
165struct Asteroid {
166    center: Vec3,
167    radius: f32,
168    /// Per-asteroid seed derived from global seed + index.
169    seed: u32,
170    /// Y-axis flattening factor in [0.5, 1.0]. 0.5 = flat disk, 1.0 = sphere.
171    flatten_y: f32,
172}
173
174/// Procedural generator that fills the world with asteroid-shaped voxel
175/// formations, implementing [`ChunkGenerator<DefaultVoxel>`].
176///
177/// See the [module-level documentation](self) for a full description of the
178/// generation algorithm.  Asteroid positions and radii are computed once at
179/// construction time via [`AsteroidGenerator::new`]; subsequent calls to
180/// [`ChunkGenerator::generate`] are read-only and safe to call concurrently
181/// from multiple worker threads.
182///
183/// # Examples
184///
185/// ```rust,no_run
186/// use std::sync::Arc;
187/// use voxel_framework::generator::GeneratorResource;
188/// use voxel_framework::generator::asteroid::{AsteroidConfig, AsteroidGenerator};
189/// use voxel_framework::voxel::DefaultVoxel;
190///
191/// let config = AsteroidConfig { seed: 99, asteroid_count: 5, ..AsteroidConfig::default() };
192/// let generator = Arc::new(AsteroidGenerator::new(config));
193///
194/// // Insert into Bevy as a resource:
195/// // app.insert_resource(GeneratorResource::<DefaultVoxel> { generator });
196/// ```
197pub struct AsteroidGenerator {
198    config: AsteroidConfig,
199    asteroids: Vec<Asteroid>,
200}
201
202impl AsteroidGenerator {
203    /// Creates an [`AsteroidGenerator`] from the given [`AsteroidConfig`].
204    ///
205    /// All `config.asteroid_count` asteroid centers and radii are computed
206    /// immediately using [`hash3`]-based pseudo-random generation.  Construction
207    /// is O(n) in `asteroid_count` and allocates a single `Vec`; it is fast
208    /// enough to run on the main thread at app startup.
209    pub fn new(config: AsteroidConfig) -> Self {
210        let asteroids = Self::build_asteroids(&config);
211        Self { config, asteroids }
212    }
213
214    /// Returns a reference to the generator's configuration.
215    pub fn config(&self) -> &AsteroidConfig {
216        &self.config
217    }
218
219    /// Returns the number of pre-computed asteroids.
220    pub fn asteroid_count(&self) -> usize {
221        self.asteroids.len()
222    }
223
224    /// Deterministically generates asteroid positions and radii from the seed.
225    fn build_asteroids(config: &AsteroidConfig) -> Vec<Asteroid> {
226        let mut asteroids = Vec::with_capacity(config.asteroid_count);
227
228        for i in 0..config.asteroid_count {
229            let per_seed = config.seed.wrapping_add(i as u32 * 97 + 1);
230
231            let (center, radius, flatten_y) = if i == 0 {
232                // First asteroid always at origin (guaranteed spawn reference point).
233                let r = (config.min_radius + config.max_radius) * 0.5;
234                (Vec3::ZERO, r, 1.0)
235            } else {
236                // Hash the seed + index for each component.
237                // Use different z-values to decorrelate x, y, z, radius, flatten.
238                let hx = hash3(i as i32, 0, 0, per_seed);
239                let hy = hash3(i as i32, 1, 0, per_seed);
240                let hz = hash3(i as i32, 2, 0, per_seed);
241                let hr = hash3(i as i32, 3, 0, per_seed);
242
243                let spread_xz = config.max_radius * 10.0;
244                let spread_y = config.max_radius * 5.0;
245
246                let x = (hx * 2.0 - 1.0) * spread_xz;
247                let y = (hy * 2.0 - 1.0) * spread_y;
248                let z = (hz * 2.0 - 1.0) * spread_xz;
249
250                let r = config.min_radius + hr * (config.max_radius - config.min_radius);
251
252                (Vec3::new(x, y, z), r, 1.0_f32)
253            };
254
255            asteroids.push(Asteroid {
256                center,
257                radius,
258                seed: per_seed,
259                flatten_y,
260            });
261        }
262
263        asteroids
264    }
265
266    /// Determines the mineral type for a solid voxel based on noise at the
267    /// given world position.
268    ///
269    /// Uses three independent FBM noise passes with different seeds to create
270    /// natural-looking mineral veins. The thresholds are based on the
271    /// architecture specification.
272    #[inline]
273    fn determine_mineral(world_pos: Vec3, asteroid_seed: u32) -> DefaultVoxel {
274        // Mineral vein FBM parameters (from ARCHITECTURE.md):
275        // 3 octaves, frequency 5.0, lacunarity 2.0, gain 0.5
276        let mineral_octaves = 3;
277        let mineral_freq = 5.0;
278        let lacunarity = 2.0;
279        let gain = 0.5;
280
281        // Three independent noise passes with different seeds
282        let rare_noise = fbm(
283            world_pos.x,
284            world_pos.y,
285            world_pos.z,
286            asteroid_seed.wrapping_add(100),
287            mineral_octaves,
288            mineral_freq,
289            lacunarity,
290            gain,
291        );
292        let crystal_noise = fbm(
293            world_pos.x,
294            world_pos.y,
295            world_pos.z,
296            asteroid_seed.wrapping_add(200),
297            mineral_octaves,
298            mineral_freq,
299            lacunarity,
300            gain,
301        );
302        let iron_noise = fbm(
303            world_pos.x,
304            world_pos.y,
305            world_pos.z,
306            asteroid_seed.wrapping_add(300),
307            mineral_octaves,
308            mineral_freq,
309            lacunarity,
310            gain,
311        );
312
313        // FBM returns [-1, 1]; thresholds from ARCHITECTURE.md:
314        // rare_noise > 0.55 => RareMineral (~5%)
315        // crystal_noise > 0.30 => SiliconCrystal (~15%)
316        // iron_noise > 0.20 => IronOre (~25%)
317        // default => Rock (~55%)
318        if rare_noise > 0.55 {
319            DefaultVoxel::RareMineral
320        } else if crystal_noise > 0.30 {
321            DefaultVoxel::SiliconCrystal
322        } else if iron_noise > 0.20 {
323            DefaultVoxel::IronOre
324        } else {
325            DefaultVoxel::Rock
326        }
327    }
328}
329
330impl ChunkGenerator<DefaultVoxel> for AsteroidGenerator {
331    fn generate(&self, coord: IVec3, chunk: &mut Chunk<DefaultVoxel>) {
332        let chunk_world = coord.as_vec3() * CHUNK_SIZE as f32;
333
334        for lx in 0..CHUNK_SIZE {
335            for ly in 0..CHUNK_SIZE {
336                for lz in 0..CHUNK_SIZE {
337                    let world_pos =
338                        chunk_world + Vec3::new(lx as f32 + 0.5, ly as f32 + 0.5, lz as f32 + 0.5);
339
340                    for asteroid in &self.asteroids {
341                        let dx = world_pos.x - asteroid.center.x;
342                        let dy = (world_pos.y - asteroid.center.y) / asteroid.flatten_y;
343                        let dz = world_pos.z - asteroid.center.z;
344                        let dist = (dx * dx + dy * dy + dz * dz).sqrt();
345
346                        // Quick reject: if too far, skip noise calculation.
347                        // Max surface extent is radius + radius * amplitude.
348                        let max_extent =
349                            asteroid.radius + asteroid.radius * self.config.noise_amplitude;
350                        if dist > max_extent + 1.0 {
351                            continue;
352                        }
353
354                        // Voxels deep inside the asteroid (farther than noise can
355                        // ever displace the surface inward) are always solid.
356                        // This prevents FBM from carving internal cavities that
357                        // look like transparent holes from the outside.
358                        let inner_solid_radius =
359                            asteroid.radius * (1.0 - self.config.noise_amplitude);
360                        if dist < inner_solid_radius {
361                            let voxel = Self::determine_mineral(world_pos, asteroid.seed);
362                            chunk.set(lx, ly, lz, voxel);
363                            break;
364                        }
365
366                        // Surface band: apply FBM displacement to decide solid vs air.
367                        // Normalized coordinates for FBM sampling
368                        let norm = world_pos / (asteroid.radius * 2.0);
369
370                        let surface_noise = fbm(
371                            norm.x,
372                            norm.y,
373                            norm.z,
374                            asteroid.seed,
375                            self.config.noise_octaves,
376                            self.config.noise_frequency,
377                            2.0, // lacunarity
378                            0.5, // gain
379                        ) * asteroid.radius
380                            * self.config.noise_amplitude;
381
382                        let density = asteroid.radius - dist + surface_noise;
383
384                        if density > 0.0 {
385                            let voxel = Self::determine_mineral(world_pos, asteroid.seed);
386                            chunk.set(lx, ly, lz, voxel);
387                            // First asteroid wins for this voxel position
388                            break;
389                        }
390                    }
391                }
392            }
393        }
394    }
395}
396
397#[cfg(test)]
398mod tests {
399    use super::*;
400
401    #[test]
402    fn deterministic_generation() {
403        let config = AsteroidConfig::default();
404        let generator = AsteroidGenerator::new(config.clone());
405
406        let coord = IVec3::new(0, 0, 0);
407
408        let mut chunk_a = Chunk::<DefaultVoxel>::new();
409        generator.generate(coord, &mut chunk_a);
410
411        let mut chunk_b = Chunk::<DefaultVoxel>::new();
412        generator.generate(coord, &mut chunk_b);
413
414        for x in 0..CHUNK_SIZE {
415            for y in 0..CHUNK_SIZE {
416                for z in 0..CHUNK_SIZE {
417                    assert_eq!(
418                        chunk_a.get(x, y, z),
419                        chunk_b.get(x, y, z),
420                        "Voxel mismatch at ({x}, {y}, {z}): generation must be deterministic"
421                    );
422                }
423            }
424        }
425    }
426
427    #[test]
428    fn empty_space_produces_air() {
429        let config = AsteroidConfig {
430            asteroid_count: 1,
431            min_radius: 10.0,
432            max_radius: 10.0,
433            ..AsteroidConfig::default()
434        };
435        let generator = AsteroidGenerator::new(config);
436
437        // Chunk very far from the origin asteroid (which is at Vec3::ZERO)
438        let coord = IVec3::new(1000, 1000, 1000);
439        let mut chunk = Chunk::<DefaultVoxel>::new();
440        generator.generate(coord, &mut chunk);
441
442        assert!(
443            chunk.is_empty(),
444            "Chunk far from any asteroid should be entirely air"
445        );
446    }
447
448    #[test]
449    fn asteroid_interior_has_solid_voxels() {
450        let config = AsteroidConfig {
451            asteroid_count: 1,
452            min_radius: 30.0,
453            max_radius: 30.0,
454            ..AsteroidConfig::default()
455        };
456        let generator = AsteroidGenerator::new(config);
457
458        // Chunk at origin — center of the first asteroid
459        let coord = IVec3::new(0, 0, 0);
460        let mut chunk = Chunk::<DefaultVoxel>::new();
461        generator.generate(coord, &mut chunk);
462
463        let solid_count = (0..CHUNK_SIZE)
464            .flat_map(|x| {
465                (0..CHUNK_SIZE).flat_map(move |y| (0..CHUNK_SIZE).map(move |z| (x, y, z)))
466            })
467            .filter(|&(x, y, z)| chunk.is_solid_at(x, y, z))
468            .count();
469
470        assert!(
471            solid_count > 0,
472            "Chunk at asteroid center should contain solid voxels, but found none"
473        );
474        // The center of a radius-30 asteroid should have many solid voxels
475        assert!(
476            solid_count > CHUNK_SIZE * CHUNK_SIZE,
477            "Expected substantial solid voxels at asteroid center, got only {solid_count}"
478        );
479    }
480
481    #[test]
482    fn mineral_distribution_has_variety() {
483        let config = AsteroidConfig {
484            asteroid_count: 1,
485            min_radius: 40.0,
486            max_radius: 40.0,
487            ..AsteroidConfig::default()
488        };
489        let generator = AsteroidGenerator::new(config);
490
491        // Generate several chunks around the asteroid center to get a good sample
492        let mut has_rock = false;
493        let mut has_iron = false;
494        let mut has_silicon = false;
495        let mut has_rare = false;
496
497        for cx in -1..=1 {
498            for cy in -1..=1 {
499                for cz in -1..=1 {
500                    let coord = IVec3::new(cx, cy, cz);
501                    let mut chunk = Chunk::<DefaultVoxel>::new();
502                    generator.generate(coord, &mut chunk);
503
504                    for x in 0..CHUNK_SIZE {
505                        for y in 0..CHUNK_SIZE {
506                            for z in 0..CHUNK_SIZE {
507                                match chunk.get(x, y, z) {
508                                    DefaultVoxel::Rock => has_rock = true,
509                                    DefaultVoxel::IronOre => has_iron = true,
510                                    DefaultVoxel::SiliconCrystal => has_silicon = true,
511                                    DefaultVoxel::RareMineral => has_rare = true,
512                                    DefaultVoxel::Air => {}
513                                }
514                            }
515                        }
516                    }
517                }
518            }
519        }
520
521        assert!(has_rock, "Should contain Rock voxels");
522        assert!(has_iron, "Should contain IronOre voxels");
523        assert!(has_silicon, "Should contain SiliconCrystal voxels");
524        assert!(has_rare, "Should contain RareMineral voxels");
525    }
526}