use bevy::prelude::*; use crate::world::hash2; #[derive(Clone, Copy, Debug)] pub struct Noise { seed: u32, } impl Noise { pub fn new(seed: u32) -> Self { Self { seed } } fn gradient(&self, cell: IVec2) -> Vec2 { let h = hash2( (cell.x as u32).wrapping_add(self.seed.wrapping_mul(0x632B_E5AB)), (cell.y as u32) ^ self.seed.rotate_left(16), ); Vec2::from_angle(h as f32 / u32::MAX as f32 * std::f32::consts::TAU) } pub fn sample(&self, p: Vec2) -> f32 { let cell = p.floor(); let f = p - cell; let cell = cell.as_ivec2(); let corner = |offset: IVec2| self.gradient(cell + offset).dot(f - offset.as_vec2()); let u = f * f * f * (f * (f * 6.0 - 15.0) + 10.0); let bottom = corner(IVec2::new(0, 0)).lerp(corner(IVec2::new(1, 0)), u.x); let top = corner(IVec2::new(0, 1)).lerp(corner(IVec2::new(1, 1)), u.x); (bottom.lerp(top, u.y) * std::f32::consts::SQRT_2).clamp(-1.0, 1.0) } pub fn fbm(&self, p: Vec2, octaves: u32) -> f32 { let (mut sum, mut amplitude, mut frequency, mut total) = (0.0, 1.0, 1.0, 0.0); for octave in 0..octaves { let layer = Noise::new(self.seed.wrapping_add(octave)); sum += layer.sample(p * frequency) * amplitude; total += amplitude; amplitude *= 0.5; frequency *= 2.0; } sum / total } } #[cfg(test)] mod tests { use super::*; fn grid() -> impl Iterator { (0..40).flat_map(|y| (0..40).map(move |x| Vec2::new(x as f32 * 0.37, y as f32 * 0.29))) } #[test] fn noise_is_deterministic_per_seed() { let (a, b, c) = (Noise::new(3), Noise::new(3), Noise::new(4)); assert!(grid().all(|p| a.fbm(p, 4) == b.fbm(p, 4))); assert!(grid().any(|p| a.fbm(p, 4) != c.fbm(p, 4))); } #[test] fn noise_stays_in_range() { let noise = Noise::new(9); assert!(grid().all(|p| (-1.0..=1.0).contains(&noise.sample(p)))); assert!(grid().all(|p| (-1.0..=1.0).contains(&noise.fbm(p, 5)))); } #[test] fn noise_is_zero_on_lattice_points() { let noise = Noise::new(1); assert_eq!(noise.sample(Vec2::new(5.0, -3.0)), 0.0); } // Terrain is thresholded from noise; discontinuities would show up as speckled, noisy borders. #[test] fn noise_is_continuous() { let noise = Noise::new(5); for p in grid() { let d = (noise.sample(p) - noise.sample(p + Vec2::splat(0.001))).abs(); assert!(d < 0.01, "jump of {d} at {p}"); } } #[test] fn negative_coordinates_work() { let noise = Noise::new(2); let values: Vec = (0..20) .map(|i| noise.sample(Vec2::new(-i as f32 * 0.7 - 0.3, -2.4))) .collect(); assert!(values.iter().any(|v| *v != 0.0)); } }