summaryrefslogtreecommitdiff
path: root/src/perlin.rs
blob: 0b29f48e896ef3c1de7f4c2848aeb383834fc982 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
use std::eprintln;

use crate::vec3::{Vec3, Point3};

const POINT_COUNT: usize = 256;

// Mix-in images are necessarily monochrome, so each data entry is a pixel.
pub struct MixInImage {
    width: usize,
    height: usize,
    data: Vec<f64>,
}

impl MixInImage {
    pub fn from_bmp(bmp_data: &Vec<u8>) -> Self {
        let data_position = u32::from_le_bytes([
            bmp_data[0x0A],
            bmp_data[0x0B],
            bmp_data[0x0C],
            bmp_data[0x0D],
        ]);
        // assuming windows BITMAPINFOHEADER, these are i32
        let width = i32::from_le_bytes([
            bmp_data[0x12],
            bmp_data[0x13],
            bmp_data[0x14],
            bmp_data[0x15],
        ]) as usize;
        let height = i32::from_le_bytes([
            bmp_data[0x16],
            bmp_data[0x17],
            bmp_data[0x18],
            bmp_data[0x19],
        ]) as usize;
        // assuming 3 channels, all of which are equal
        let data = bmp_data[(data_position as usize)..bmp_data.len()].iter().skip(2).step_by(3).map(|x| *x as f64 / 255.0).collect();
        Self {
            width,
            height,
            data,
        }
    }

    pub fn get(&self, point: &Point3) -> &f64 {
        let disc_x = ((point.x * self.width as f64) % self.width as f64) as usize;
        let disc_y = ((point.y * self.height as f64) % self.height as f64) as usize;
        self.data.get((disc_y * self.width) + disc_x).unwrap()
    }
}

pub struct Perlin {
    ranvec: Vec<Vec3>,
    perm_x: Vec<usize>,
    perm_y: Vec<usize>,
    perm_z: Vec<usize>,
}

impl Perlin {
    pub fn new() -> Self {
        let mut ranvec = Vec::with_capacity(POINT_COUNT);
        for _ in 0..POINT_COUNT {
            ranvec.push(Vec3::random_in_range(-1.0, 1.0).unit_vector());
        }
        Self {
            ranvec,
            perm_x: Self::generate_perm(),
            perm_y: Self::generate_perm(),
            perm_z: Self::generate_perm(),
        }
    }

    pub fn turb(&self, point: &Point3, depth: u32) -> f64 {
        let mut accum = 0.0;
        let mut temp_point = point.clone();
        let mut weight = 1.0;

        for _ in 0..depth {
            accum += weight * self.noise(&temp_point);
            weight *= 0.5;
            temp_point *= 2.0;
        }
        accum.abs()
    }

    pub fn turb_dsw(&self, point: &Point3, depth: u32, factor: f64) -> f64 {
        let mut accum = 0.0;
        let mut temp_point = point.clone();
        let mut weight = 1.0;

        for _ in 0..depth {
            accum += weight * self.noise(&temp_point);
            temp_point *= 2.0;
            temp_point += temp_point.xy_diff(&|p: &Vec3| -> f64 {weight * self.noise(p)}) * factor;
            weight *= 0.5;
        }
        accum.abs()
    }

    
    pub fn turb_dsw_mixin(&self, point: &Point3, depth: u32, factor: f64, mixin: &MixInImage, mixin_factor: f64, mixin_strength: f64) -> f64 {
        let mut accum = 0.0;
        let mut temp_point = point.clone();
        let mut mixin_point = point.clone();
        let mut weight = 1.0;

        for _ in 0..depth {
            accum += weight * (1.0 - mixin_strength) * self.noise(&temp_point);
            temp_point *= 2.0;
            let diff = temp_point.xy_diff(&|p: &Vec3| -> f64 {weight * self.noise(p)});
            temp_point += &diff * factor;
            mixin_point += &diff * mixin_factor;
            accum += weight * mixin_strength * mixin.get(&mixin_point);
            weight *= 0.5;
        }
        accum.abs()
    }

    pub fn noise(&self, point: &Point3) -> f64 {
        let u = point.x - point.x.floor();
        let v = point.y - point.y.floor();
        let w = point.z - point.z.floor();
        let i = point.x.floor() as i32;
        let j = point.y.floor() as i32;
        let k = point.z.floor() as i32;
        let mut c: [[[Vec3; 2]; 2]; 2] = Default::default();
        for di in 0..2 {
            for dj in 0..2 {
                for dk in 0..2 {
                    c[di][dj][dk] = self
                        .ranvec
                        .get(
                            (self.perm_x.get(((i + di as i32) & 255) as usize).unwrap()
                                ^ self.perm_y.get(((j + dj as i32) & 255) as usize).unwrap()
                                ^ self.perm_z.get(((k + dk as i32) & 255) as usize).unwrap())
                                as usize,
                        )
                        .unwrap().clone();
                }
            }
        }
        Self::trilinear_interpolate(c, u, v, w)
    }

    fn trilinear_interpolate(c: [[[Vec3; 2]; 2]; 2], u: f64, v: f64, w: f64) -> f64 {
        let uu = u * u * (3.0 - 2.0 * u);
        let vv = v * v * (3.0 - 2.0 * v);
        let ww = w * w * (3.0 - 2.0 * w);
        let mut accum: f64 = 0.0;
        for i in 0..2 {
            for j in 0..2 {
                for k in 0..2 {
                    let i_f = i as f64;
                    let j_f = j as f64;
                    let k_f = k as f64;
                    let weight_v = Vec3 { x: u - i_f, y: v - j_f, z: w - k_f };
                    accum += (i_f * uu + (1.0 - i_f) * (1.0 - uu)) *
                        (j_f * vv + (1.0 - j_f) * (1.0 - vv)) *
                        (k_f * ww + (1.0 - k_f) * (1.0 - ww)) *
                        c[i][j][k].dot(&weight_v);
                }
            }
        }
        accum
    }

    fn generate_perm() -> Vec<usize> {
        let mut p = (0..POINT_COUNT).collect();
        Self::permute(&mut p, POINT_COUNT);
        p
    }

    fn permute(p: &mut Vec<usize>, n: usize) {
        for i in (1..n).rev() {
            p.swap(i, rand::random::<usize>() % i);
        }
    }
}