bevy_math/sampling/mesh_sampling.rs
1//! Functionality related to random sampling from triangle meshes.
2
3use crate::{
4 primitives::{Measured2d, Triangle3d},
5 ShapeSample, Vec3,
6};
7use alloc::vec::Vec;
8use rand::Rng;
9use rand_distr::{Distribution, WeightedAliasIndex, WeightedError};
10
11/// A [distribution] that caches data to allow fast sampling from a collection of triangles.
12/// Generally used through [`sample`] or [`sample_iter`].
13///
14/// [distribution]: Distribution
15/// [`sample`]: Distribution::sample
16/// [`sample_iter`]: Distribution::sample_iter
17///
18/// Example
19/// ```
20/// # use bevy_math::{Vec3, primitives::*};
21/// # use bevy_math::sampling::mesh_sampling::UniformMeshSampler;
22/// # use rand::{SeedableRng, rngs::StdRng, distributions::Distribution};
23/// let faces = Tetrahedron::default().faces();
24/// let sampler = UniformMeshSampler::try_new(faces).unwrap();
25/// let rng = StdRng::seed_from_u64(8765309);
26/// // 50 random points on the tetrahedron:
27/// let samples: Vec<Vec3> = sampler.sample_iter(rng).take(50).collect();
28/// ```
29pub struct UniformMeshSampler {
30 triangles: Vec<Triangle3d>,
31 face_distribution: WeightedAliasIndex<f32>,
32}
33
34impl Distribution<Vec3> for UniformMeshSampler {
35 fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Vec3 {
36 let face_index = self.face_distribution.sample(rng);
37 self.triangles[face_index].sample_interior(rng)
38 }
39}
40
41impl UniformMeshSampler {
42 /// Construct a new [`UniformMeshSampler`] from a list of [triangles].
43 ///
44 /// Returns an error if the distribution of areas for the collection of triangles could not be formed
45 /// (most notably if the collection has zero surface area).
46 ///
47 /// [triangles]: Triangle3d
48 pub fn try_new<T: IntoIterator<Item = Triangle3d>>(
49 triangles: T,
50 ) -> Result<Self, WeightedError> {
51 let triangles: Vec<Triangle3d> = triangles.into_iter().collect();
52 let areas = triangles.iter().map(Measured2d::area).collect();
53
54 WeightedAliasIndex::new(areas).map(|face_distribution| Self {
55 triangles,
56 face_distribution,
57 })
58 }
59}