noise_functions/modifiers/
triangle_wave.rs

1#[cfg(feature = "nightly-simd")]
2use core::simd::{LaneCount, Simd, SupportedLaneCount};
3
4use crate::{math::floor, Noise, Sample};
5
6/// Applies a triangle wave to the output of a noise function.
7///
8/// This outputs values is in the [-1, 1] range.
9///
10/// **Note:** This modifier assumes the base noise returns values in the [-1, 1] range.
11pub struct TriangleWave<N, F> {
12    pub noise: N,
13    pub frequency: F,
14}
15
16impl<N, F> Noise for TriangleWave<N, F> {}
17
18impl<N, F, const DIM: usize> Sample<DIM> for TriangleWave<N, F>
19where
20    N: Sample<DIM>,
21    F: Sample<DIM>,
22{
23    #[inline]
24    fn sample_with_seed(&self, point: [f32; DIM], seed: i32) -> f32 {
25        apply(self.noise.sample_with_seed(point, seed), self.frequency.sample_with_seed(point, seed))
26    }
27}
28
29#[cfg(feature = "nightly-simd")]
30impl<N, F, const DIM: usize, const LANES: usize> Sample<DIM, Simd<f32, LANES>> for TriangleWave<N, F>
31where
32    N: Sample<DIM, Simd<f32, LANES>>,
33    F: Sample<DIM, Simd<f32, LANES>>,
34    LaneCount<LANES>: SupportedLaneCount,
35{
36    #[inline]
37    fn sample_with_seed(&self, point: Simd<f32, LANES>, seed: i32) -> f32 {
38        apply(self.noise.sample_with_seed(point, seed), self.frequency.sample_with_seed(point, seed))
39    }
40}
41
42#[inline]
43fn apply(value: f32, frequency: f32) -> f32 {
44    let v = (value + 1.0) * frequency;
45    let v = v - floor(v * 0.5) * 2.0;
46    let v = if v < 1.0 { v } else { 2.0 - v };
47    (v - 0.5) * 2.0
48}