Add Distribution
access methods for ShapeSample
trait
#13315
Merged
+107
−1
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Stolen from #12835.
Objective
Sometimes you want to sample a whole bunch of points from a shape instead of just one. You can write your own loop to do this, but it's really more idiomatic to use a
rand
Distribution
with thesample_iter
method. Distributions also support other useful things like mapping, and they are suitable as generic items for consumption by other APIs.Solution
ShapeSample
has been given two new automatic trait methods,interior_dist
andboundary_dist
. They both have similar signatures (recall thatOutput
is the output type forShapeSample
):These have default implementations which are powered by wrapper structs
InteriorOf
andBoundaryOf
that actually implementDistribution
— the implementations effectively just callShapeSample::sample_interior
andShapeSample::sample_boundary
on the contained type.The upshot is that this allows iteration as follows:
Alternatively, you can use
InteriorOf
/BoundaryOf
explicitly to similar effect:Changelog
InteriorOf
andBoundaryOf
distribution wrapper structs inbevy_math::sampling::shape_sampling
.interior_dist
andboundary_dist
automatic trait methods toShapeSample
.shape_sampling
module public with explanatory documentation.Discussion
Design choices
The main point of interest here is just the choice of
impl Distribution
instead of explicitly usingInteriorOf
/BoundaryOf
return types forinterior_dist
andboundary_dist
. The reason for this choice is that it allows future optimizations for repeated sampling — for example, instead of just wrapping the base type,interior_dist
/boundary_dist
could construct auxiliary data that is held over between sampling operations.