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