1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! Wrappers for stochastically sampled variables.
use crate::geom::Point;
use crate::spectrum::blackbody_wavelength;
use rand::prelude::*;
use rand_distr::num_traits::{Float, FromPrimitive};
use rand_distr::uniform::SampleUniform;
use rand_distr::Distribution;
use rand_distr::{Normal, StandardNormal};
use std::sync::Arc;
/// Wrapper for a bounded stocastically sampled value
///
/// a `Sampler` encloses the distribution function and bounds for a random
/// variable of type `T`, such that is can be sampled with an external random
/// number generator of type `R`
///
/// Several constructors are provided for common distributions of values, however
/// if a custom one is needed it can be provided as a closure and set of bounds to
/// `Sampler::from_fn`
#[derive(Clone)]
pub struct Sampler<T: Copy, R: Rng> {
sample: Arc<dyn Fn(&mut R) -> T + Send + Sync>,
bounds: (T, T),
}
impl<T, R> Sampler<T, R>
where
R: Rng,
T: Copy + Send + Sync + 'static,
{
/// Creates a new `Sampler` with a constant distibution.
///
/// When sampled the `Sampler` will always return `c`
pub fn new_const<A>(c: A) -> Self
where
A: Into<T>,
{
let c = c.into();
Self {
sample: Arc::new(move |_| c),
bounds: (c, c),
}
}
}
impl<T, R> Sampler<T, R>
where
R: Rng,
T: Copy + Float + SampleUniform + Send + Sync + 'static,
{
/// Creates a new `Sampler` with a uniform distibution.
///
/// When sampled the `Sampler` will always return a value between `a` and `b` (inclusive)
pub fn new_range<A, B>(a: A, b: B) -> Self
where
A: Into<T>,
B: Into<T>,
{
let a = a.into();
let b = b.into();
if a == b {
return Self::new_const(a);
}
let lower = T::min(a, b);
let upper = T::max(a, b);
Self {
sample: Arc::new(move |r| r.gen_range(lower..=upper)),
bounds: (lower, upper),
}
}
}
impl<T, R> Sampler<T, R>
where
R: Rng,
T: Copy + Float + From<f32> + Send + Sync + 'static,
StandardNormal: Distribution<T>,
{
/// Creates a new `Sampler` with a normal (gaussian) distibution.
///
/// Real gaussian's have infinate bounds, this can cause problems in the raytracing engine, so
/// this implementation wraps at 3 standard deviations.
///
/// When sampled the `Sampler` will always return a value between `mean - 3 * std_dev` and `mean + 3 * std_dev` (inclusive)
pub fn new_gaussian<A, B>(mean: A, std_dev: B) -> Self
where
A: Copy + Into<T>,
B: Copy + Into<T>,
{
let width: T = std_dev.into() * 3.0.into();
let mean = mean.into();
let g = Normal::new(0.0.into(), std_dev.into()).unwrap();
Self {
sample: Arc::new(move |r| (g.sample(r) % width) + mean),
bounds: (mean - width, mean + width),
}
}
}
impl<T, R> Sampler<T, R>
where
R: Rng,
T: Copy + Float + SampleUniform + FromPrimitive + From<f32> + Send + Sync + 'static,
{
/// Creates a new `Sampler` with a blackbody radiation curve distibution.
///
/// This is only really useful for creating realistic white lights of a given colour temprature, or stars.
///
/// This sampler should be used carefully; it can lead to unexpected results when used on a value other than `Light.wavelength`.
/// It is also __substancially__ slower than the other `Sampler` types. When Sampled it will return a value between
/// 0 and `T::MAX` (probably larger than you want) This can cause all sorts of weird problems for collision detection, so _please_
/// don't use this on a `SamplerPoint`
pub fn new_blackbody<A>(temperature: A) -> Self
where
A: Into<T>,
{
let t = temperature.into();
Self {
sample: Arc::new(move |r| blackbody_wavelength(t, r.gen_range(0.0.into()..1.0.into()))),
bounds: (0.0.into(), T::max_value()),
}
}
}
impl<T, R> Sampler<T, R>
where
T: Copy,
R: Rng,
{
/// Creates a new `Sampler` with a distribution dictated by `f`
///
/// `f` must always return a value within the bounds specified by `lower` & `upper`
///
/// This is very low level access to how the renderer works; you're in control,
/// if you break it it's your fault!
pub fn from_fn(f: Arc<dyn Fn(&mut R) -> T + Send + Sync>, lower: T, upper: T) -> Self {
Self {
sample: f,
bounds: (lower, upper),
}
}
/// Get a sampled value from this `Sampler` using random number generator `rng`
#[inline(always)]
pub fn sample(&self, rng: &mut R) -> T {
(self.sample)(rng)
}
/// Get the bounds of a possible sampled value (useful for spacial partitioning and limit checks etc)
#[inline(always)]
pub fn bounds(&self) -> (T, T) {
self.bounds
}
}
/// A single value of type `T` will be interpreted as a constant distribution if turned into a sampler.
///
/// # Example:
/// ```
/// extern crate rand;
///
/// use rustic_zen::sampler::Sampler;
/// use rand::prelude::*;
/// let mut r = rand::thread_rng();
///
/// let s: Sampler<f64, ThreadRng> = 5.0.into();
///
/// assert_eq!(s.sample(&mut r), 5.0); // will always be true
/// ```
impl<T, R> From<T> for Sampler<T, R>
where
T: Copy + From<T> + Send + Sync + 'static,
R: Rng,
{
fn from(value: T) -> Self {
Self::new_const(value)
}
}
/// A tuple of type `(T,T)` will be interpreted as a uniform distribution if turned into a sampler.
///
/// # Example:
/// ```
/// extern crate rand;
///
/// use rustic_zen::sampler::Sampler;
/// use rand::prelude::*;
/// let mut r = rand::thread_rng();
///
/// let s: Sampler<f64, ThreadRng> = (5.0,10.0).into();
///
/// assert!(s.sample(&mut r) >= 5.0); // will always be true
/// assert!(s.sample(&mut r) <= 10.0); // will always be true
/// ```
impl<T, R> From<(T, T)> for Sampler<T, R>
where
T: Copy + Float + SampleUniform + Send + Sync + From<f32> + 'static,
R: Rng,
{
fn from(value: (T, T)) -> Self {
Self::new_range(value.0, value.1)
}
}
/// Wrapper around two `Sampler`s to make a Stochasically sampled point.
#[derive(Clone)]
pub struct SamplerPoint<R: Rng> {
x: Sampler<f64, R>,
y: Sampler<f64, R>,
}
/// A tuple of type `(Sampler::<T>,Sampler<T>)` will be interpreted as a uniform distribution if turned into a sampler.
///
/// # Example:
/// ```
/// extern crate rand;
///
/// use rustic_zen::sampler::SamplerPoint;
/// use rustic_zen::sampler::Sampler;
/// use rand::prelude::*;
/// let mut r = rand::thread_rng();
///
/// // results in a rounds soft distribution, useful for area lights.
/// let _p: SamplerPoint<ThreadRng> = (Sampler::new_gaussian(0.0, 3.0), Sampler::new_gaussian(0.0, 3.0)).into();
///
/// ```
///
/// This is the only way to construct a `SamplerPoint`. This shorthand can be extended using the `Sampler`'s into traits:
/// ```
/// extern crate rand;
///
/// use rustic_zen::sampler::SamplerPoint;
/// use rustic_zen::geom::Point;
/// use rand::prelude::*;
/// let mut r = rand::thread_rng();
///
/// // results in a fixed point at 0.0, 0.0
/// let _p: SamplerPoint<ThreadRng> = (0.0, 0.0).into();
///
/// // results in a uniformly distributed square from 0.0, 0.0 to 10.0, 10.0
/// let _p: SamplerPoint<ThreadRng> = ((0.0, 10.0), (0.0, 10.0)).into();
/// ```
impl<R> From<Point> for SamplerPoint<R>
where
R: Rng,
{
fn from(value: Point) -> Self {
Self {
x: value.x.into(),
y: value.y.into(),
}
}
}
impl<A, B, R> From<(A, B)> for SamplerPoint<R>
where
A: Into<Sampler<f64, R>>,
B: Into<Sampler<f64, R>>,
R: Rng,
{
fn from(value: (A, B)) -> Self {
Self {
x: value.0.into(),
y: value.1.into(),
}
}
}
impl<R> SamplerPoint<R>
where
R: Rng,
{
#[inline(always)]
pub(crate) fn get(&self, rng: &mut R) -> Point {
Point {
x: self.x.sample(rng),
y: self.y.sample(rng),
}
}
}
#[cfg(test)]
mod tests {
type RandGen = rand_pcg::Pcg64Mcg;
use rand::prelude::*;
use super::Sampler;
#[test]
fn const_bounds() {
// test bounds with 1000 random numbers
for _ in 0..1000 {
let mut stdrng = RandGen::from_entropy();
let f: f64 = stdrng.gen();
let s = Sampler::<f64, RandGen>::new_const(f);
let (a, b) = s.bounds();
assert_eq!(a, b);
assert_eq!(a, f);
assert_eq!(b, f);
}
}
#[test]
fn range_bounds() {
for _ in 0..1000 {
let mut stdrng = RandGen::from_entropy();
let a: f64 = stdrng.gen();
let b: f64 = stdrng.gen();
let s = Sampler::<f64, RandGen>::new_range(a, b);
let (c, d) = s.bounds();
assert_eq!(a.min(b), c);
assert_eq!(a.max(b), d);
}
}
#[test]
fn val_const() {
let mut rng = RandGen::from_entropy();
let mut stdrng = RandGen::from_entropy();
let f: f64 = stdrng.gen();
let s = Sampler::new_const(f);
for _ in 0..1000 {
let y: f64 = s.sample(&mut rng);
assert_eq!(y, f);
}
}
#[test]
fn val_range() {
let mut rng = RandGen::from_entropy();
let mut stdrng = RandGen::from_entropy();
let mut f1: f64 = stdrng.gen();
let mut f2: f64 = stdrng.gen();
if f1 < f2 {
let tmp = f1;
f1 = f2;
f2 = tmp;
}
let s = Sampler::new_range(f1, f2);
// This does actually run 100,000 times despite finishing so quickly
for _ in 0..100000 {
let y: f64 = s.sample(&mut rng);
assert!(y <= f1);
assert!(y >= f2);
}
}
#[test]
fn blackbody_works() {
let mut rng = RandGen::from_entropy();
// Get a sampled value from the range of valid wavelenghts
let w: Sampler<f64, rand_pcg::Mcg128Xsl64> = Sampler::new_range(780.0, 360.0);
// create sample with random wavelenght
let s = Sampler::new_blackbody(w.sample(&mut rng));
// Check s can be sampled without panicing
let _: f64 = s.sample(&mut rng);
}
#[test]
fn blackbody_white_light_64() {
let mut rng = RandGen::from_entropy();
let s = Sampler::new_blackbody(0.0);
// Check s can be sampled without panicing
let _: f64 = s.sample(&mut rng);
}
#[test]
fn blackbody_white_light_32() {
let mut rng = RandGen::from_entropy();
let s = Sampler::new_blackbody(0.0);
// Check s can be sampled without panicing
let _: f32 = s.sample(&mut rng);
}
#[test]
fn gaussian_at_zero() {
let mut rng = RandGen::from_entropy();
let s = Sampler::new_gaussian(0.0, 10.0);
// Check s can be sampled without panicing
let _: f64 = s.sample(&mut rng);
}
#[test]
fn range_big_first() {
let mut rng = RandGen::from_entropy();
let s = Sampler::new_range(10.0, 0.0);
// Check s can be sampled without panicing
let _: f64 = s.sample(&mut rng);
}
#[test]
fn range_small_first() {
let mut rng = RandGen::from_entropy();
let s = Sampler::new_range(0.0, 10.0);
// Check s can be sampled without panicing
let _: f64 = s.sample(&mut rng);
}
}