noise_functions/
sample.rs

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
#[cfg(feature = "nightly-simd")]
use core::simd::{f32x2, f32x4};

use crate::Noise;

/// Trait for sampling noises.
pub trait Sample<const DIM: usize, Point = [f32; DIM]>: Noise {
    fn sample(&self, point: Point) -> f32;
}

impl<const DIM: usize, Point, N> Sample<DIM, Point> for &N
where
    N: Sample<DIM, Point>,
{
    #[inline(always)]
    fn sample(&self, point: Point) -> f32 {
        N::sample(self, point)
    }
}

macro_rules! helper_trait {
	($(#[$attr:meta])* $trait:ident, $fn:ident, $dim:literal as $ty:ty $(as $ty_param:ty)?) => {
		#[doc = concat!(
			"Helper trait that provides `",
			stringify!($fn),
			"` for every `Sample<",
			stringify!($dim),
			$(", ", stringify!($ty_param),)?
			">`.",
		)]
		///
		#[doc = concat!(
			"It also works for any `impl Into<",
			stringify!($ty),
			">`.",
		)]
		$(#[$attr])*
		pub trait $trait: Sample<$dim $(, $ty_param)?> {
			fn $fn(&self, point: impl Into<$ty>) -> f32;
		}

		$(#[$attr])*
		impl<N> $trait for N
		where
			N: Sample<$dim $(, $ty_param)?>,
		{
			#[inline(always)]
			fn $fn(&self, point: impl Into<$ty>) -> f32 {
				N::sample(self, point.into())
			}
		}
	};
}

helper_trait!(Sample2, sample2, 2 as [f32; 2]);
helper_trait!(Sample3, sample3, 3 as [f32; 3]);
helper_trait!(Sample4, sample4, 4 as [f32; 4]);

helper_trait!(
    #[cfg(feature = "nightly-simd")]
    Sample2a,
    sample2a,
    2 as f32x2 as f32x2
);

helper_trait!(
    #[cfg(feature = "nightly-simd")]
    Sample3a,
    sample3a,
    3 as f32x4 as f32x4
);

helper_trait!(
    #[cfg(feature = "nightly-simd")]
    Sample4a,
    sample4a,
    4 as f32x4 as f32x4
);

/// Trait for sampling noises with a seed.
pub trait SampleWithSeed<const DIM: usize, Point = [f32; DIM]>: Sample<DIM, Point> {
    fn sample_with_seed(&self, point: Point, seed: i32) -> f32;
}