terrain_forge/noise/
simplex.rs

1use super::NoiseSource;
2
3/// Simplex noise - faster than Perlin with fewer directional artifacts
4pub struct Simplex {
5    seed: u64,
6    frequency: f64,
7}
8
9impl Simplex {
10    const F2: f64 = 0.3660254037844386; // (sqrt(3) - 1) / 2
11    const G2: f64 = 0.21132486540518713; // (3 - sqrt(3)) / 6
12
13    pub fn new(seed: u64) -> Self {
14        Self { seed, frequency: 1.0 }
15    }
16
17    pub fn with_frequency(mut self, frequency: f64) -> Self {
18        self.frequency = frequency;
19        self
20    }
21
22    fn hash(&self, x: i32, y: i32) -> usize {
23        let h = (x as u64).wrapping_mul(374761393)
24            .wrapping_add((y as u64).wrapping_mul(668265263))
25            .wrapping_add(self.seed);
26        (h ^ (h >> 13)).wrapping_mul(1274126177) as usize % 12
27    }
28
29    fn grad(hash: usize, x: f64, y: f64) -> f64 {
30        const GRAD: [(f64, f64); 12] = [
31            (1.0, 1.0), (-1.0, 1.0), (1.0, -1.0), (-1.0, -1.0),
32            (1.0, 0.0), (-1.0, 0.0), (0.0, 1.0), (0.0, -1.0),
33            (1.0, 1.0), (-1.0, 1.0), (1.0, -1.0), (-1.0, -1.0),
34        ];
35        let (gx, gy) = GRAD[hash];
36        gx * x + gy * y
37    }
38}
39
40impl NoiseSource for Simplex {
41    fn sample(&self, x: f64, y: f64) -> f64 {
42        let x = x * self.frequency;
43        let y = y * self.frequency;
44
45        let s = (x + y) * Self::F2;
46        let i = (x + s).floor() as i32;
47        let j = (y + s).floor() as i32;
48
49        let t = (i + j) as f64 * Self::G2;
50        let x0 = x - (i as f64 - t);
51        let y0 = y - (j as f64 - t);
52
53        let (i1, j1) = if x0 > y0 { (1, 0) } else { (0, 1) };
54
55        let x1 = x0 - i1 as f64 + Self::G2;
56        let y1 = y0 - j1 as f64 + Self::G2;
57        let x2 = x0 - 1.0 + 2.0 * Self::G2;
58        let y2 = y0 - 1.0 + 2.0 * Self::G2;
59
60        let mut n = 0.0;
61        for &(dx, dy, di, dj) in &[(x0, y0, 0, 0), (x1, y1, i1, j1), (x2, y2, 1, 1)] {
62            let t = 0.5 - dx * dx - dy * dy;
63            if t > 0.0 {
64                let t2 = t * t;
65                n += t2 * t2 * Self::grad(self.hash(i + di, j + dj), dx, dy);
66            }
67        }
68        70.0 * n
69    }
70}
71
72#[cfg(test)]
73mod tests {
74    use super::*;
75
76    #[test]
77    fn simplex_deterministic() {
78        let noise = Simplex::new(12345);
79        assert_eq!(noise.sample(1.5, 2.5), noise.sample(1.5, 2.5));
80    }
81
82    #[test]
83    fn simplex_range() {
84        let noise = Simplex::new(42);
85        for i in 0..50 {
86            for j in 0..50 {
87                let v = noise.sample(i as f64 * 0.1, j as f64 * 0.1);
88                assert!(v >= -1.0 && v <= 1.0, "Value {} out of range", v);
89            }
90        }
91    }
92}