noises_and_patterns/
noise.rs

1use crate::prelude::*;
2
3pub mod value;
4pub mod voronoibasic;
5
6pub trait Noise {
7
8    fn new() -> Self;
9
10    /// 2D noise for the given position
11    fn get_2d(&self, p: (FP, FP)) -> FP;
12
13    // 2D fbm for the given position and the octaves
14    fn fbm_2d(&self, p: (FP, FP), octaves: i32) -> FP {
15        let mut x = FP2::new(p.0, p.1);
16
17        let mut f = 0.0;
18        let mut a = 0.5;
19        let shift = FP2::new(100.0, 100.0);
20
21        // Rotate to reduce axial bias
22        let rot =  Matrix2::new(1.6,  1.2, -1.2,  1.6);
23
24        for _i in 0..octaves {
25            f += a * self.get_2d((x.x, x.y));
26            x = rot * x * 2.0 + shift;
27            a *= 0.5;
28        }
29        f.clamp(0.0, 1.0)
30    }
31
32    /// 2D hash, taken from https://www.shadertoy.com/view/4djSRW
33    #[inline(always)]
34    fn hash21(&self, p: FP2) -> FP {
35        let mut p3 = glm::fract(&FP3::new(p.x * 0.1031, p.y * 0.1031, p.x * 0.1031));
36
37        let dot = glm::dot(&p3, &(FP3::new(p3.y + 33.333, p3.z + 33.333, p3.x + 33.333)));
38
39        p3.x += dot; p3.y += dot; p3.z += dot;
40        ((p3.x + p3.y) * p3.z).fract()
41    }
42
43    /// Mix for FP
44    #[inline(always)]
45    fn mix(&self, a: &FP, b: &FP, v: &FP) -> FP {
46        (1.0 - v) * a + b * v
47    }
48}