valib 0.2.6

valflrt's utility crate
Documentation
use std::f64::consts::TAU;

/// An utility struct used to obtain fibonacci-lattice points.
/// See <https://observablehq.com/@meetamit/fibonacci-lattices>.
pub struct FibonacciLattice {
    epsilon: f64,
}

impl FibonacciLattice {
    /// Creates a new FibonacciLattice with parameters `phi` and `epsilon`.
    /// See <https://observablehq.com/@meetamit/fibonacci-lattices>.
    pub fn new(epsilon: f64) -> FibonacciLattice {
        FibonacciLattice { epsilon }
    }

    /// Yields an iterator of tuples `(x, y)` representing points on a square, in the cartesian
    /// coordinate system.
    pub fn square_iter(&self, n: usize) -> impl Iterator<Item = (f64, f64)> {
        const PHI: f64 = 1.618033988749895;

        (0..n).map(move |i| {
            (
                i as f64 / PHI % 1.,
                (i as f64 + self.epsilon) / ((n - 1) as f64 + 2. * self.epsilon),
            )
        })
    }

    /// Yields an iterator of tuples `(r, theta)` representing points on a disk, in the polar coordinate
    /// system.
    pub fn disk_iter(&self, n: usize) -> impl Iterator<Item = (f64, f64)> {
        self.square_iter(n).map(|(x, y)| (x * TAU, y.sqrt()))
    }

    /// Yields an iterator of tuples `(theta, phi)` representing points on a sphere, in the spherical
    /// coordinate system.
    pub fn sphere_iter(&self, n: usize) -> impl Iterator<Item = (f64, f64)> {
        self.square_iter(n)
            .map(|(x, y)| (x * TAU, (1. - 2. * y).acos()))
    }
}

impl Default for FibonacciLattice {
    fn default() -> Self {
        FibonacciLattice { epsilon: 0.5 }
    }
}