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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
// Copyright (c) 2017 The Noise-rs Developers.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT
// or http://opensource.org/licenses/MIT>, at your option. All files in the
// project carrying such notice may not be copied, modified, or distributed
// except according to those terms.

use {PermutationTable, math};
use math::{Point2, Point3, Point4};
use modules::{NoiseModule, Seedable};
use num_traits::Float;

/// Default noise seed for the Worley noise module.
pub const DEFAULT_WORLEY_SEED: usize = 0;
/// Default RangeFunction for the Worley noise module.
pub const DEFAULT_WORLEY_RANGEFUNCTION: RangeFunction = RangeFunction::Euclidean;
/// Default frequency for the Worley noise module.
pub const DEFAULT_WORLEY_FREQUENCY: f32 = 1.0;
/// Default displacement for the Worley noise module.
pub const DEFAULT_WORLEY_DISPLACEMENT: f32 = 1.0;

/// Noise module that outputs Worley noise.
#[derive(Clone, Copy, Debug)]
pub struct Worley<T> {
    perm_table: PermutationTable,

    /// Seed.
    pub seed: usize,

    /// Specifies the range function to use when calculating the boundaries of
    /// the cell.
    pub range_function: RangeFunction,

    /// Determines if the distance from the nearest seed point is applied to
    /// the output value.
    pub enable_range: bool,

    /// Frequency of the seed points.
    pub frequency: T,

    /// Scale of the random displacement to apply to each cell.
    ///
    /// The noise module assigns each Worley cell a random constant value from
    /// a value noise function. The `displacement` _value_ controls the range
    /// random values to assign to each cell. The range of random values is +/-
    /// the displacement value.
    pub displacement: T,
}

impl<T> Worley<T>
    where T: Float,
{
    pub fn new() -> Worley<T> {
        Worley {
            perm_table: PermutationTable::new(DEFAULT_WORLEY_SEED as u32),
            seed: DEFAULT_WORLEY_SEED,
            range_function: DEFAULT_WORLEY_RANGEFUNCTION,
            enable_range: false,
            frequency: math::cast(DEFAULT_WORLEY_FREQUENCY),
            displacement: math::cast(DEFAULT_WORLEY_DISPLACEMENT),
        }
    }

    /// Sets the range function used by the Worley cells.
    pub fn set_range_function(self, range_function: RangeFunction) -> Worley<T> {
        Worley { range_function: range_function, ..self }
    }

    /// Enables or disables applying the distance from the nearest seed point
    /// to the output value.
    pub fn enable_range(self, enable_range: bool) -> Worley<T> {
        Worley { enable_range: enable_range, ..self }
    }

    /// Sets the frequency of the seed points.
    pub fn set_frequency(self, frequency: T) -> Worley<T> {
        Worley { frequency: frequency, ..self }
    }

    pub fn set_displacement(self, displacement: T) -> Worley<T> {
        Worley { displacement: displacement, ..self }
    }
}

impl<T> Seedable for Worley<T> {
    /// Sets the seed value used by the Worley cells.
    fn set_seed(self, seed: usize) -> Worley<T> {
        Worley {
            perm_table: PermutationTable::new(seed as u32),
            seed: seed,
            ..self
        }
    }
}

/// Set of distance functions that can be used in the Worley noise module.
#[derive(Clone, Copy, Debug)]
pub enum RangeFunction {
    /// The standard linear distance. Expensive to compute because it requires
    /// square root calculations.
    Euclidean,

    /// Same as Euclidean, but without the square root calculations. Distance
    /// results will be smaller, however, but hash patterns will be the same.
    EuclideanSquared,

    /// Measured by only moving in straight lines along the axes. Diagonal
    /// movement is not allowed, which leads to increased distances.
    Manhattan,

    /// Measured by taking the largest distance along any axis as the total
    /// distance. Since this eliminates all but one dimension, it results in
    /// significantly shorter distances and produces regions where the
    /// distances are uniform.
    Chebyshev,

    /// Experimental function where all values are multiplied together and then
    /// added up like a quadratic equation.
    Quadratic,
}

fn calculate_range<T: Float>(range_function: RangeFunction, p1: &[T], p2: &[T]) -> T {
    match range_function {
        RangeFunction::Euclidean => range_euclidean(p1, p2),
        RangeFunction::EuclideanSquared => range_euclidean_squared(p1, p2),
        RangeFunction::Manhattan => range_manhattan(p1, p2),
        RangeFunction::Chebyshev => range_chebyshev(p1, p2),
        RangeFunction::Quadratic => range_quadratic(p1, p2),
    }
}

fn range_euclidean<T: Float>(p1: &[T], p2: &[T]) -> T {
    p1.iter()
        .zip(p2.iter())
        .map(|(a, b)| *a - *b)
        .map(|a| a * a)
        .fold(T::zero(), |acc, x| acc + x)
        .sqrt()
}

fn range_euclidean_squared<T: Float>(p1: &[T], p2: &[T]) -> T {
    p1.iter()
        .zip(p2.iter())
        .map(|(a, b)| *a - *b)
        .map(|a| a * a)
        .fold(T::zero(), |acc, x| acc + x)
}

fn range_manhattan<T: Float>(p1: &[T], p2: &[T]) -> T {
    p1.iter()
        .zip(p2.iter())
        .map(|(a, b)| *a - *b)
        .map(|a| a.abs())
        .fold(T::zero(), |acc, x| acc + x)
}

fn range_chebyshev<T: Float>(p1: &[T], p2: &[T]) -> T {
    p1.iter()
        .zip(p2.iter())
        .map(|(a, b)| *a - *b)
        .map(|a| a.abs())
        .fold(T::min_value(), |a, b| a.max(b))
}

fn range_quadratic<T: Float>(p1: &[T], p2: &[T]) -> T {
    let temp: Vec<T> = p1.iter()
        .zip(p2.iter())
        .map(|(a, b)| *a - *b)
        .collect();

    let length = temp.len();
    let mut result = T::zero();

    for i in 0..length {
        for j in 0..length {
            result = result + (temp[i] * temp[j]);
        }
    }

    result
}

impl<T: Float> NoiseModule<Point2<T>> for Worley<T> {
    type Output = T;

    fn get(&self, point: Point2<T>) -> T {
        #[inline(always)]
        fn get_point<T: Float>(perm_table: &PermutationTable, whole: Point2<i64>) -> Point2<T> {
            math::add2(get_vec2(perm_table.get2(whole)), math::cast2::<_, T>(whole))
        }

        let half: T = math::cast(0.5);

        let point = &math::mul2(point, self.frequency);

        let cell = math::map2(*point, T::floor);
        let whole = math::map2(cell, math::cast::<_, i64>);
        let frac = math::sub2(*point, cell);

        let x_half = frac[0] > half;
        let y_half = frac[1] > half;

        let near = [whole[0] + (x_half as i64), whole[1] + (y_half as i64)];
        let far = [whole[0] + (!x_half as i64), whole[1] + (!y_half as i64)];

        let mut seed_cell = near;
        let seed_point = get_point(&self.perm_table, near);
        let mut range = calculate_range(self.range_function, point, &seed_point);

        let x_range = (half - frac[0]) * (half - frac[0]); // x-distance squared to center line
        let y_range = (half - frac[1]) * (half - frac[1]); // y-distance squared to center line

        macro_rules! test_point(
            [$x:expr, $y:expr] => {
                {
                    let cur_point = get_point(&self.perm_table, [$x, $y]);
                    let cur_range = calculate_range(self.range_function, point, &cur_point);
                    if cur_range < range {
                        range = cur_range;
                        seed_cell = [$x, $y];
                    }
                }
            }
        );

        if x_range < range {
            test_point![far[0], near[1]];
        }

        if y_range < range {
            test_point![near[0], far[1]];
        }

        if x_range < range && y_range < range {
            test_point![far[0], far[1]];
        }

        let value;

        if self.enable_range {
            value = range;
        } else {
            value = self.displacement * math::cast::<_, T>(self.perm_table.get2(seed_cell)) *
                    math::cast(1.0 / 255.0);
        }

        value * math::cast(2.0) - T::one()
    }
}

#[inline(always)]
#[cfg_attr(rustfmt, rustfmt_skip)]
fn get_vec2<T: Float>(index: usize) -> Point2<T> {
    let length = math::cast::<_, T>((index & 0xF8) >> 3) * math::cast(0.5 / 31.0);
    let diag = length * math::cast(::std::f64::consts::FRAC_1_SQRT_2);
    let one = length;
    let zero = T::zero();
    match index & 0x07 {
        0 => [ diag,  diag],
        1 => [ diag, -diag],
        2 => [-diag,  diag],
        3 => [-diag, -diag],
        4 => [ one,   zero],
        5 => [-one,   zero],
        6 => [ zero,  one],
        7 => [ zero, -one],
        _ => unreachable!(),
    }
}

impl<T: Float> NoiseModule<Point3<T>> for Worley<T> {
    type Output = T;

    fn get(&self, point: Point3<T>) -> T {
        #[inline(always)]
        fn get_point<T: Float>(perm_table: &PermutationTable,
                               whole: math::Point3<i64>)
                               -> Point3<T> {
            math::add3(get_vec3(perm_table.get3(whole)), math::cast3::<_, T>(whole))
        }

        let half: T = math::cast(0.5);

        let point = &math::mul3(point, self.frequency);

        let cell = math::map3(*point, T::floor);
        let whole = math::map3(cell, math::cast::<_, i64>);
        let frac = math::sub3(*point, cell);

        let x_half = frac[0] > half;
        let y_half = frac[1] > half;
        let z_half = frac[2] > half;

        let near =
            [whole[0] + (x_half as i64), whole[1] + (y_half as i64), whole[2] + (z_half as i64)];
        let far =
            [whole[0] + (!x_half as i64), whole[1] + (!y_half as i64), whole[2] + (!z_half as i64)];

        let mut seed_cell = near;
        let seed_point = get_point(&self.perm_table, near);
        let mut range = calculate_range(self.range_function, point, &seed_point);

        let x_range = (half - frac[0]) * (half - frac[0]); // x-distance squared to center line
        let y_range = (half - frac[1]) * (half - frac[1]); // y-distance squared to center line
        let z_range = (half - frac[2]) * (half - frac[2]); // z-distance squared to center line

        macro_rules! test_point(
            [$x:expr, $y:expr, $z:expr] => {
                {
                    let cur_point = get_point(&self.perm_table, [$x, $y, $z]);
                    let cur_range = calculate_range(self.range_function, point, &cur_point);
                    if cur_range < range {
                        range = cur_range;
                        seed_cell = [$x, $y, $z];
                    }
                }
            }
        );

        if x_range < range {
            test_point![far[0], near[1], near[2]];
        }
        if y_range < range {
            test_point![near[0], far[1], near[2]];
        }
        if z_range < range {
            test_point![near[0], near[1], far[2]];
        }

        if x_range < range && y_range < range {
            test_point![far[0], far[1], near[2]];
        }
        if x_range < range && z_range < range {
            test_point![far[0], near[1], far[2]];
        }
        if y_range < range && z_range < range {
            test_point![near[0], far[1], far[2]];
        }

        if x_range < range && y_range < range && z_range < range {
            test_point![far[0], far[1], far[2]];
        }

        let value;

        if self.enable_range {
            value = range;
        } else {
            value = self.displacement * math::cast::<_, T>(self.perm_table.get3(seed_cell)) *
                    math::cast(1.0 / 255.0);
        }

        value * math::cast(2.0) - T::one()
    }
}

#[inline(always)]
#[cfg_attr(rustfmt, rustfmt_skip)]
fn get_vec3<T: Float>(index: usize) -> Point3<T> {
    let length = math::cast::<_, T>((index & 0xE0) >> 5) * math::cast(0.5 / 7.0);
    let diag = length * math::cast(::std::f64::consts::FRAC_1_SQRT_2);
    let one = length;
    let zero = T::zero();
    match index % 18 {
        0  => [ diag,  diag,  zero],
        1  => [ diag, -diag,  zero],
        2  => [-diag,  diag,  zero],
        3  => [-diag, -diag,  zero],
        4  => [ diag,  zero,  diag],
        5  => [ diag,  zero, -diag],
        6  => [-diag,  zero,  diag],
        7  => [-diag,  zero, -diag],
        8  => [ zero,  diag,  diag],
        9  => [ zero,  diag, -diag],
        10 => [ zero, -diag,  diag],
        11 => [ zero, -diag, -diag],
        12 => [ one,   zero,  zero],
        13 => [ zero,  one,   zero],
        14 => [ zero,  zero,  one],
        15 => [-one,   zero,  zero],
        16 => [ zero, -one,   zero],
        17 => [ zero,  zero, -one],
        _ => panic!("Attempt to access 3D gradient {} of 18", index % 18),
    }
}

impl<T: Float> NoiseModule<Point4<T>> for Worley<T> {
    type Output = T;

    fn get(&self, point: Point4<T>) -> T {
        #[inline(always)]
        fn get_point<T: Float>(perm_table: &PermutationTable, whole: Point4<i64>) -> Point4<T> {
            math::add4(get_vec4(perm_table.get4(whole)), math::cast4::<_, T>(whole))
        }

        let half: T = math::cast(0.5);

        let point = &math::mul4(point, self.frequency);

        let cell = math::map4(*point, T::floor);
        let whole = math::map4(cell, math::cast::<_, i64>);
        let frac = math::sub4(*point, cell);

        let x_half = frac[0] > half;
        let y_half = frac[1] > half;
        let z_half = frac[2] > half;
        let w_half = frac[3] > half;

        let near = [whole[0] + (x_half as i64),
                    whole[1] + (y_half as i64),
                    whole[2] + (z_half as i64),
                    whole[3] + (w_half as i64)];
        let far = [whole[0] + (!x_half as i64),
                   whole[1] + (!y_half as i64),
                   whole[2] + (!z_half as i64),
                   whole[3] + (!w_half as i64)];

        let mut seed_cell = near;
        let seed_point = get_point(&self.perm_table, near);
        let mut range = calculate_range(self.range_function, point, &seed_point);

        let x_range = (half - frac[0]) * (half - frac[0]); // x-distance squared to center line
        let y_range = (half - frac[1]) * (half - frac[1]); // y-distance squared to center line
        let z_range = (half - frac[2]) * (half - frac[2]); // z-distance squared to center line
        let w_range = (half - frac[3]) * (half - frac[3]); // w-distance squared to center line

        macro_rules! test_point(
            [$x:expr, $y:expr, $z:expr, $w:expr] => {
                {
                    let cur_point = get_point(&self.perm_table, [$x, $y, $z, $w]);
                    let cur_range = calculate_range(self.range_function, point, &cur_point);
                    if cur_range < range {
                        range = cur_range;
                        seed_cell = [$x, $y, $z, $w];
                    }
                }
            }
        );

        if x_range < range {
            test_point![far[0], near[1], near[2], near[3]];
        }
        if y_range < range {
            test_point![near[0], far[1], near[2], near[3]];
        }
        if z_range < range {
            test_point![near[0], near[1], far[2], near[3]];
        }
        if w_range < range {
            test_point![near[0], near[1], near[2], far[3]];
        }

        if x_range < range && y_range < range {
            test_point![far[0], far[1], near[2], near[3]];
        }
        if x_range < range && z_range < range {
            test_point![far[0], near[1], far[2], near[3]];
        }
        if x_range < range && w_range < range {
            test_point![far[0], near[1], near[2], far[3]];
        }
        if y_range < range && z_range < range {
            test_point![near[0], far[1], far[2], near[3]];
        }
        if y_range < range && w_range < range {
            test_point![near[0], far[1], near[2], far[3]];
        }
        if z_range < range && w_range < range {
            test_point![near[0], near[1], far[2], far[3]];
        }

        if x_range < range && y_range < range && z_range < range {
            test_point![far[0], far[1], far[2], near[3]];
        }
        if x_range < range && y_range < range && w_range < range {
            test_point![far[0], far[1], near[2], far[3]];
        }
        if x_range < range && z_range < range && w_range < range {
            test_point![far[0], near[1], far[2], far[3]];
        }
        if y_range < range && z_range < range && w_range < range {
            test_point![near[0], far[1], far[2], far[3]];
        }

        if x_range < range && y_range < range && z_range < range && w_range < range {
            test_point![far[0], far[1], far[2], far[3]];
        }

        let value;

        if self.enable_range {
            value = range;
        } else {
            value = self.displacement * math::cast::<_, T>(self.perm_table.get4(seed_cell)) *
                math::cast(1.0 / 255.0);
        }

        value * math::cast(2.0) - T::one()
    }
}

#[inline(always)]
#[cfg_attr(rustfmt, rustfmt_skip)]
fn get_vec4<T: Float>(index: usize) -> Point4<T> {
    let length = math::cast::<_, T>((index & 0xE0) >> 5) * math::cast(0.5 / 7.0);
    let diag = length * math::cast(0.57735026919);
    let zero = T::zero();
    match index % 32 {
        0  => [ diag,  diag,  diag,  zero],
        1  => [ diag, -diag,  diag,  zero],
        2  => [-diag,  diag,  diag,  zero],
        3  => [-diag, -diag,  diag,  zero],
        4  => [ diag,  diag, -diag,  zero],
        5  => [ diag, -diag, -diag,  zero],
        6  => [-diag,  diag, -diag,  zero],
        7  => [-diag, -diag, -diag,  zero],
        8  => [ diag,  diag,  zero,  diag],
        9  => [ diag, -diag,  zero,  diag],
        10 => [-diag,  diag,  zero,  diag],
        11 => [-diag, -diag,  zero,  diag],
        12 => [ diag,  diag,  zero, -diag],
        13 => [ diag, -diag,  zero, -diag],
        14 => [-diag,  diag,  zero, -diag],
        15 => [-diag, -diag,  zero, -diag],
        16 => [ diag,  zero,  diag,  diag],
        17 => [ diag,  zero, -diag,  diag],
        18 => [-diag,  zero,  diag,  diag],
        19 => [-diag,  zero, -diag,  diag],
        20 => [ diag,  zero,  diag, -diag],
        21 => [ diag,  zero, -diag, -diag],
        22 => [-diag,  zero,  diag, -diag],
        23 => [-diag,  zero, -diag, -diag],
        24 => [ zero,  diag,  diag,  diag],
        25 => [ zero,  diag, -diag,  diag],
        26 => [ zero, -diag,  diag,  diag],
        27 => [ zero, -diag, -diag,  diag],
        28 => [ zero,  diag,  diag, -diag],
        29 => [ zero,  diag, -diag, -diag],
        30 => [ zero, -diag,  diag, -diag],
        31 => [ zero, -diag, -diag, -diag],
        _ => panic!("Attempt to access 4D gradient {} of 32", index % 32),
    }
}