vox_geometry_rust 0.1.2

Geometry Tools for Rust
Documentation
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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
/*
 * // Copyright (c) 2021 Feng Yang
 * //
 * // I am making my contributions/submissions to this project solely in my
 * // personal capacity and am not conveying any rights to any intellectual
 * // property of any third parties.
 */

use crate::implicit_surface3::ImplicitSurface3Ptr;
use crate::bounding_box3::BoundingBox3D;
use crate::vector3::Vector3D;
use crate::particle_emitter3::*;
use crate::particle_system_data3::ParticleSystemData3Ptr;
use crate::bcc_lattice_point_generator::*;
use crate::surface3::Surface3Ptr;
use crate::surface_to_implicit3::SurfaceToImplicit3;
use crate::point_hash_grid_searcher3::PointHashGridSearcher3;
use crate::point_generator3::PointGenerator3;
use crate::point_neighbor_searcher3::PointNeighborSearcher3;
use crate::usize3::USize3;
use std::sync::{RwLock, Arc};
use rand::prelude::*;
use rand_pcg::{Pcg64, Lcg128Xsl64};
use rayon::prelude::*;
use log::info;

///
/// # Callback function type for update calls.
///
/// This type of callback function will take the emitter pointer, current
/// time, and time interval in seconds.
///
pub type OnBeginUpdateCallback = fn(&mut VolumeParticleEmitter3, f64, f64);

///
/// # 3-D volumetric particle emitter.
///
/// This class emits particles from volumetric geometry.
///
pub struct VolumeParticleEmitter3 {
    _rng: Lcg128Xsl64,
    _implicit_surface: ImplicitSurface3Ptr,
    _bounds: BoundingBox3D,
    _spacing: f64,
    _initial_vel: Vector3D,
    _linear_vel: Vector3D,
    _angular_vel: Vector3D,
    _points_gen: BccLatticePointGeneratorPtr,

    _max_number_of_particles: usize,
    _number_of_emitted_particles: usize,

    _jitter: f64,
    _is_one_shot: bool,
    _allow_overlapping: bool,

    _emitter_data: ParticleEmitter3Data,
    _on_begin_update_callback: Option<OnBeginUpdateCallback>,
}

impl VolumeParticleEmitter3 {
    /// Constructs an emitter that spawns particles from given implicit surface
    /// which defines the volumetric geometry. Provided bounding box limits
    /// the particle generation region.
    ///
    /// - parameter:   implicit_surface         The implicit surface.
    /// - parameter:   max_region               The max region.
    /// - parameter:   spacing                 The spacing between particles.
    /// - parameter:   initial_vel              The initial velocity of new particles.
    /// - parameter:   linear_vel               The linear velocity of the emitter.
    /// - parameter:   angular_vel              The angular velocity of the emitter.
    /// - parameter:   max_number_of_particles    The max number of particles to be
    ///                                     emitted.
    /// - parameter:   jitter                  The jitter amount between 0 and 1.
    /// - parameter:   is_one_shot               True if emitter gets disabled after one shot.
    /// - parameter:   allow_overlapping        True if particles can be overlapped.
    /// - parameter:   seed                    The random seed.
    ///
    pub fn new(implicit_surface: ImplicitSurface3Ptr,
               max_region: BoundingBox3D,
               spacing: f64,
               initial_vel: Option<Vector3D>,
               linear_vel: Option<Vector3D>,
               angular_vel: Option<Vector3D>,
               max_number_of_particles: Option<usize>,
               jitter: Option<f64>,
               is_one_shot: Option<bool>,
               allow_overlapping: Option<bool>,
               seed: Option<u64>) -> VolumeParticleEmitter3 {
        return VolumeParticleEmitter3 {
            _rng: Pcg64::seed_from_u64(seed.unwrap_or(0)),
            _implicit_surface: implicit_surface,
            _bounds: max_region,
            _spacing: spacing,
            _initial_vel: initial_vel.unwrap_or(Vector3D::new_default()),
            _linear_vel: linear_vel.unwrap_or(Vector3D::new_default()),
            _angular_vel: angular_vel.unwrap_or(Vector3D::new_default()),
            _points_gen: Arc::new(RwLock::new(BccLatticePointGenerator {})),
            _max_number_of_particles: max_number_of_particles.unwrap_or(usize::MAX),
            _number_of_emitted_particles: 0,
            _jitter: jitter.unwrap_or(0.0),
            _is_one_shot: is_one_shot.unwrap_or(true),
            _allow_overlapping: allow_overlapping.unwrap_or(false),
            _emitter_data: ParticleEmitter3Data::new(),
            _on_begin_update_callback: None,
        };
    }

    /// Returns source surface.
    pub fn surface(&self) -> ImplicitSurface3Ptr {
        return self._implicit_surface.clone();
    }

    /// Sets the source surface.
    pub fn set_surface(&mut self, new_surface: ImplicitSurface3Ptr) {
        self._implicit_surface = new_surface;
    }

    /// Returns max particle gen region.
    pub fn max_region(&self) -> BoundingBox3D {
        return self._bounds.clone();
    }

    /// Sets the max particle gen region.
    pub fn set_max_region(&mut self, new_max_region: BoundingBox3D) {
        self._bounds = new_max_region;
    }

    /// Returns jitter amount.
    pub fn jitter(&self) -> f64 {
        return self._jitter;
    }

    /// Sets jitter amount between 0 and 1.
    pub fn set_jitter(&mut self, new_jitter: f64) {
        self._jitter = crate::math_utils::clamp(new_jitter, 0.0, 1.0);
    }

    /// Returns true if particles should be emitted just once.
    pub fn is_one_shot(&self) -> bool {
        return self._is_one_shot;
    }

    ///
    /// \brief      Sets the flag to true if particles are emitted just once.
    ///
    /// If true is set, the emitter will generate particles only once even after
    /// multiple emit calls. If false, it will keep generating particles from
    /// the volumetric geometry. Default value is true.
    ///
    /// - parameter:   new_value True if particles should be emitted just once.
    ///
    pub fn set_is_one_shot(&mut self, new_value: bool) {
        self._is_one_shot = new_value;
    }

    /// Returns true if particles can be overlapped.
    pub fn allow_overlapping(&self) -> bool {
        return self._allow_overlapping;
    }

    ///
    /// \brief      Sets the flag to true if particles can overlap each other.
    ///
    /// If true is set, the emitter will generate particles even if the new
    /// particles can find existing nearby particles within the particle
    /// spacing.
    ///
    /// - parameter:   new_value True if particles can be overlapped.
    ///
    pub fn set_allow_overlapping(&mut self, new_value: bool) {
        self._allow_overlapping = new_value;
    }

    /// Returns max number of particles to be emitted.
    pub fn max_number_of_particles(&self) -> usize {
        return self._max_number_of_particles;
    }

    /// Sets the max number of particles to be emitted.
    pub fn set_max_number_of_particles(&mut self, new_max_number_of_particles: usize) {
        self._max_number_of_particles = new_max_number_of_particles;
    }

    /// Returns the spacing between particles.
    pub fn spacing(&self) -> f64 {
        return self._spacing;
    }

    /// Sets the spacing between particles.
    pub fn set_spacing(&mut self, new_spacing: f64) {
        self._spacing = new_spacing;
    }

    /// Sets the initial velocity of the particles.
    pub fn initial_velocity(&self) -> Vector3D {
        return self._initial_vel;
    }

    /// Returns the initial velocity of the particles.
    pub fn set_initial_velocity(&mut self, new_initial_vel: Vector3D) {
        self._initial_vel = new_initial_vel;
    }

    /// Returns the linear velocity of the emitter.
    pub fn linear_velocity(&self) -> Vector3D {
        return self._linear_vel;
    }

    /// Sets the linear velocity of the emitter.
    pub fn set_linear_velocity(&mut self, new_linear_vel: Vector3D) {
        self._linear_vel = new_linear_vel;
    }

    /// Returns the angular velocity of the emitter.
    pub fn angular_velocity(&self) -> Vector3D {
        return self._angular_vel;
    }

    /// Sets the linear velocity of the emitter.
    pub fn set_angular_velocity(&mut self, new_angular_vel: Vector3D) {
        self._angular_vel = new_angular_vel;
    }

    fn emit(&mut self, particles: ParticleSystemData3Ptr, new_positions: &mut Vec<Vector3D>,
            new_velocities: &mut Vec<Vector3D>) {
        self._implicit_surface.read().unwrap().update_query_engine();

        let mut region = self._bounds.clone();
        if self._implicit_surface.read().unwrap().is_bounded() {
            let surface_bbox = self._implicit_surface.read().unwrap().bounding_box();
            region.lower_corner = crate::vector3::max(&region.lower_corner, &surface_bbox.lower_corner);
            region.upper_corner = crate::vector3::min(&region.upper_corner, &surface_bbox.upper_corner);
        }

        // Reserving more space for jittering
        let j = self.jitter();
        let max_jitter_dist = 0.5 * j * self._spacing;
        let mut num_new_particles = 0;

        if self._allow_overlapping || self._is_one_shot {
            self._points_gen.clone().read().unwrap().for_each_point(&region, self._spacing, &mut |point: &Vector3D| {
                let random_dir = crate::samplers::uniform_sample_sphere(self.random(), self.random());
                let offset = random_dir * max_jitter_dist;
                let candidate = *point + offset;
                if self._implicit_surface.read().unwrap().signed_distance(&candidate) <= 0.0 {
                    if self._number_of_emitted_particles < self._max_number_of_particles {
                        new_positions.push(candidate);
                        self._number_of_emitted_particles += 1;
                        num_new_particles += 1;
                    } else {
                        return false;
                    }
                }

                return true;
            });
        } else {
            // Use serial hash grid searcher for continuous update.
            let mut neighbor_searcher = PointHashGridSearcher3::new_vec(
                USize3::new(64, 64, 64),
                3.0 * self._spacing);
            if !self._allow_overlapping {
                neighbor_searcher.build(particles.read().unwrap().positions());
            }

            self._points_gen.clone().read().unwrap().for_each_point(&region, self._spacing, &mut |point: &Vector3D| {
                let random_dir = crate::samplers::uniform_sample_sphere(self.random(), self.random());
                let offset = random_dir * max_jitter_dist;
                let candidate = *point + offset;
                if self._implicit_surface.read().unwrap().is_inside(&candidate) &&
                    (!self._allow_overlapping &&
                        !neighbor_searcher.has_nearby_point(&candidate, self._spacing)) {
                    if self._number_of_emitted_particles < self._max_number_of_particles {
                        new_positions.push(candidate);
                        neighbor_searcher.add(candidate);
                        self._number_of_emitted_particles += 1;
                        num_new_particles += 1;
                    } else {
                        return false;
                    }
                }

                return true;
            });
        }

        info!("Number of newly generated particles: {}", num_new_particles);
        info!("Number of total generated particles: {}", self._number_of_emitted_particles);

        new_velocities.resize(new_positions.len(), Vector3D::new_default());
        {
            let translate = self._implicit_surface.read().unwrap().view().transform.translation();
            let linear_vel = self._linear_vel;
            let angular_vel = self._angular_vel;
            let initial_vel = self._initial_vel;
            (new_velocities, new_positions).into_par_iter().for_each(|(vel, pos)| {
                let r = *pos - translate;
                *vel = linear_vel + angular_vel.cross(&r) + initial_vel;
            });
        }
    }

    fn random(&mut self) -> f64 {
        return self._rng.gen_range(0.0..1.0);
    }

    ///
    /// \brief      Sets the callback function to be called when
    ///             ParticleEmitter3::update function is invoked.
    ///
    /// The callback function takes current simulation time in seconds unit. Use
    /// this callback to track any motion or state changes related to this
    /// emitter.
    ///
    /// - parameter:   callback The callback function.
    ///
    pub fn set_on_begin_update_callback(&mut self, callback: OnBeginUpdateCallback) {
        self._on_begin_update_callback = Some(callback);
    }
}

impl ParticleEmitter3 for VolumeParticleEmitter3 {
    fn update(&mut self, current_time_in_seconds: f64, time_interval_in_seconds: f64) where Self: Sized {
        match self._on_begin_update_callback {
            None => {}
            Some(callback) => {
                callback(self, current_time_in_seconds,
                         time_interval_in_seconds);
            }
        }

        self.on_update(current_time_in_seconds, time_interval_in_seconds);
    }

    fn on_update(&mut self, _: f64, _: f64) {
        let particles;
        match self.target() {
            None => {
                return;
            }
            Some(target) => {
                particles = target.clone();
            }
        }

        if !self.is_enabled() {
            return;
        }

        let mut new_positions: Vec<Vector3D> = Vec::new();
        let mut new_velocities: Vec<Vector3D> = Vec::new();

        self.emit(particles.clone(), &mut new_positions, &mut new_velocities);

        particles.write().unwrap().add_particles(&new_positions, Some(&new_velocities), None);

        if self._is_one_shot {
            self.set_is_enabled(false);
        }
    }

    fn view(&self) -> &ParticleEmitter3Data {
        return &self._emitter_data;
    }

    fn view_mut(&mut self) -> &mut ParticleEmitter3Data {
        return &mut self._emitter_data;
    }
}

/// Shared pointer for the VolumeParticleEmitter3 type.
pub type VolumeParticleEmitter3Ptr = Arc<RwLock<VolumeParticleEmitter3>>;

///
/// # Front-end to create VolumeParticleEmitter3 objects step by step.
///
pub struct Builder {
    _implicit_surface: Option<ImplicitSurface3Ptr>,
    _is_bound_set: bool,
    _bounds: BoundingBox3D,
    _spacing: f64,
    _initial_vel: Vector3D,
    _linear_vel: Vector3D,
    _angular_vel: Vector3D,
    _max_number_of_particles: usize,
    _jitter: f64,
    _is_one_shot: bool,
    _allow_overlapping: bool,
    _seed: u64,
}

impl Builder {
    /// Returns builder with implicit surface defining volume shape.
    pub fn with_implicit_surface(&mut self, implicit_surface: ImplicitSurface3Ptr) -> &mut Self {
        self._implicit_surface = Some(implicit_surface);
        if !self._is_bound_set {
            self._bounds = self._implicit_surface.as_ref().unwrap().read().unwrap().bounding_box();
        }
        return self;
    }

    /// Returns builder with surface defining volume shape.
    pub fn with_surface(&mut self, surface: Surface3Ptr) -> &mut Self {
        self._implicit_surface = Some(Arc::new(RwLock::new(SurfaceToImplicit3::new(surface.clone(),
                                                                                   None, None))));
        if !self._is_bound_set {
            self._bounds = surface.read().unwrap().bounding_box();
        }
        return self;
    }

    /// Returns builder with max region.
    pub fn with_max_region(&mut self, bounds: BoundingBox3D) -> &mut Self {
        self._bounds = bounds;
        self._is_bound_set = true;
        return self;
    }

    /// Returns builder with spacing.
    pub fn with_spacing(&mut self, spacing: f64) -> &mut Self {
        self._spacing = spacing;
        return self;
    }

    /// Returns builder with initial velocity.
    pub fn with_initial_velocity(&mut self, initial_vel: Vector3D) -> &mut Self {
        self._initial_vel = initial_vel;
        return self;
    }

    /// Returns builder with linear velocity.
    pub fn with_linear_velocity(&mut self, linear_vel: Vector3D) -> &mut Self {
        self._linear_vel = linear_vel;
        return self;
    }

    /// Returns builder with angular velocity.
    pub fn with_angular_velocity(&mut self, angular_vel: Vector3D) -> &mut Self {
        self._angular_vel = angular_vel;
        return self;
    }

    /// Returns builder with max number of particles.
    pub fn with_max_number_of_particles(&mut self, max_number_of_particles: usize) -> &mut Self {
        self._max_number_of_particles = max_number_of_particles;
        return self;
    }

    /// Returns builder with jitter amount.
    pub fn with_jitter(&mut self, jitter: f64) -> &mut Self {
        self._jitter = jitter;
        return self;
    }

    /// Returns builder with one-shot flag.
    pub fn with_is_one_shot(&mut self, is_one_shot: bool) -> &mut Self {
        self._is_one_shot = is_one_shot;
        return self;
    }

    /// Returns builder with overlapping flag.
    pub fn with_allow_overlapping(&mut self, allow_overlapping: bool) -> &mut Self {
        self._allow_overlapping = allow_overlapping;
        return self;
    }

    /// Returns builder with random seed.
    pub fn with_random_seed(&mut self, seed: u64) -> &mut Self {
        self._seed = seed;
        return self;
    }

    /// Builds VolumeParticleEmitter3.
    pub fn build(&mut self) -> VolumeParticleEmitter3 {
        return VolumeParticleEmitter3::new(self._implicit_surface.as_ref().unwrap().clone(),
                                           self._bounds.clone(),
                                           self._spacing,
                                           Some(self._initial_vel),
                                           Some(self._linear_vel),
                                           Some(self._angular_vel),
                                           Some(self._max_number_of_particles),
                                           Some(self._jitter),
                                           Some(self._is_one_shot),
                                           Some(self._allow_overlapping),
                                           Some(self._seed));
    }

    /// Builds shared pointer of VolumeParticleEmitter3 instance.
    pub fn make_shared(&mut self) -> VolumeParticleEmitter3Ptr {
        return VolumeParticleEmitter3Ptr::new(RwLock::new(self.build()));
    }

    /// constructor
    pub fn new() -> Builder {
        return Builder {
            _implicit_surface: None,
            _is_bound_set: false,
            _bounds: BoundingBox3D::new_default(),
            _spacing: 0.1,
            _initial_vel: Vector3D::new_default(),
            _linear_vel: Vector3D::new_default(),
            _angular_vel: Vector3D::new_default(),
            _max_number_of_particles: usize::MAX,
            _jitter: 0.0,
            _is_one_shot: true,
            _allow_overlapping: false,
            _seed: 0,
        };
    }
}