euv-core 0.57.0

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
use super::*;

/// Default 3D PBF/SPH liquid solver configuration.
impl Default for SphSolverConfig {
    /// Returns a balanced default 3D PBF liquid solver configuration.
    ///
    /// # Returns
    ///
    /// - `Self` - Default 3D solver configuration.
    fn default() -> Self {
        Self::default_3d()
    }
}

/// Dimensional preset constructors and sanitization helpers for `SphSolverConfig`.
impl SphSolverConfig {
    /// Creates a calibrated default 2D planar liquid PBF configuration (`z = 0`).
    ///
    /// # Returns
    ///
    /// - `Self` - Ready 2D PBF configuration with rest-density-matched particle mass.
    #[must_use]
    pub fn default_2d() -> Self {
        let h: f32 = SPH_DEFAULT_SMOOTHING_RADIUS_2D;
        let spacing: f32 = h / 2.5;
        let mass: f32 = SPH_DEFAULT_REST_DENSITY * spacing * spacing;
        Self {
            domain_mode: FluidDomainMode::Dim2,
            domain_min: Vec3::new(-1.0, 0.0, 0.0),
            domain_max: Vec3::new(1.0, 2.0, 0.0),
            smoothing_radius: h,
            rest_density: SPH_DEFAULT_REST_DENSITY,
            particle_mass: mass,
            gravity: Vec3::new(0.0, SPH_DEFAULT_GRAVITY_Y, 0.0),
            substeps: 2,
            solver_iterations: 4,
            cfm_epsilon: 0.08,
            scorr_k: 0.001_2,
            scorr_dq_ratio: 0.25,
            scorr_n: 4,
            xsph_viscosity: 0.035,
            vorticity_epsilon: 0.000_25,
            surface_tension_cohesion: 0.012,
            surface_tension_curvature: 0.008,
            max_particles: SPH_DEFAULT_MAX_PARTICLES,
            hash_table_size: SPH_DEFAULT_HASH_TABLE_SIZE,
            max_speed: 16.0,
            seed: SPH_DEFAULT_SEED,
        }
    }

    /// Creates a calibrated default 3D volumetric liquid PBF configuration.
    ///
    /// # Returns
    ///
    /// - `Self` - Ready 3D PBF configuration with rest-density-matched particle mass.
    #[must_use]
    pub fn default_3d() -> Self {
        let h: f32 = SPH_DEFAULT_SMOOTHING_RADIUS_3D;
        let spacing: f32 = h / 2.5;
        let mass: f32 = SPH_DEFAULT_REST_DENSITY * spacing * spacing * spacing;
        Self {
            domain_mode: FluidDomainMode::Dim3,
            domain_min: Vec3::new(-1.0, 0.0, -1.0),
            domain_max: Vec3::new(1.0, 2.0, 1.0),
            smoothing_radius: h,
            rest_density: SPH_DEFAULT_REST_DENSITY,
            particle_mass: mass,
            gravity: Vec3::new(0.0, SPH_DEFAULT_GRAVITY_Y, 0.0),
            substeps: 2,
            solver_iterations: 4,
            cfm_epsilon: 0.08,
            scorr_k: 0.001_2,
            scorr_dq_ratio: 0.25,
            scorr_n: 4,
            xsph_viscosity: 0.035,
            vorticity_epsilon: 0.000_25,
            surface_tension_cohesion: 0.012,
            surface_tension_curvature: 0.008,
            max_particles: SPH_DEFAULT_MAX_PARTICLES,
            hash_table_size: SPH_DEFAULT_HASH_TABLE_SIZE,
            max_speed: 16.0,
            seed: SPH_DEFAULT_SEED,
        }
    }

    /// Returns a validated, finite copy of this configuration with power-of-two hash table sizing.
    ///
    /// # Returns
    ///
    /// - `Self` - Sanitized solver configuration.
    #[must_use]
    pub fn sanitized(self) -> Self {
        let mode: FluidDomainMode = self.get_domain_mode();
        let h: f32 = sph_sanitize_f32(self.get_smoothing_radius(), SPH_DEFAULT_SMOOTHING_RADIUS_3D)
            .clamp(0.01, 5.0);
        let rho0: f32 = sph_sanitize_f32(self.get_rest_density(), SPH_DEFAULT_REST_DENSITY)
            .clamp(10.0, 20_000.0);
        let nominal_d: f32 = h / 2.5;
        let default_mass: f32 = match mode {
            FluidDomainMode::Dim2 => rho0 * nominal_d * nominal_d,
            FluidDomainMode::Dim3 => rho0 * nominal_d * nominal_d * nominal_d,
        };
        let raw_mass: f32 = sph_sanitize_f32(self.get_particle_mass(), default_mass);
        let mass: f32 = if raw_mass > 1e-6 {
            raw_mass
        } else {
            default_mass
        };
        let raw_min: Vec3 = sph_project_vec3(self.get_domain_min(), mode);
        let raw_max: Vec3 = sph_project_vec3(self.get_domain_max(), mode);
        let min_v: Vec3 = raw_min.min(raw_max);
        let max_v: Vec3 = Vec3::new(
            raw_max.get_x().max(min_v.get_x() + h),
            raw_max.get_y().max(min_v.get_y() + h),
            match mode {
                FluidDomainMode::Dim2 => 0.0,
                FluidDomainMode::Dim3 => raw_max.get_z().max(min_v.get_z() + h),
            },
        );
        let hash_size: usize = self
            .get_hash_table_size()
            .clamp(256, 65_536)
            .next_power_of_two();
        Self {
            domain_mode: mode,
            domain_min: min_v,
            domain_max: max_v,
            smoothing_radius: h,
            rest_density: rho0,
            particle_mass: mass,
            gravity: sph_project_vec3(self.get_gravity(), mode),
            substeps: self.get_substeps().clamp(1, 8),
            solver_iterations: self.get_solver_iterations().clamp(1, 12),
            cfm_epsilon: sph_sanitize_f32(self.get_cfm_epsilon(), 0.08).clamp(1e-4, 100.0),
            scorr_k: sph_sanitize_f32(self.get_scorr_k(), 0.001_2).clamp(0.0, 0.05),
            scorr_dq_ratio: sph_sanitize_f32(self.get_scorr_dq_ratio(), 0.25).clamp(0.05, 0.8),
            scorr_n: self.get_scorr_n().clamp(1, 8),
            xsph_viscosity: sph_sanitize_f32(self.get_xsph_viscosity(), 0.035).clamp(0.0, 0.5),
            vorticity_epsilon: sph_sanitize_f32(self.get_vorticity_epsilon(), 0.000_25)
                .clamp(0.0, 0.05),
            surface_tension_cohesion: sph_sanitize_f32(self.get_surface_tension_cohesion(), 0.012)
                .clamp(0.0, 2.0),
            surface_tension_curvature: sph_sanitize_f32(
                self.get_surface_tension_curvature(),
                0.008,
            )
            .clamp(0.0, 2.0),
            max_particles: self.get_max_particles().clamp(16, 32_768),
            hash_table_size: hash_size,
            max_speed: sph_sanitize_f32(self.get_max_speed(), 16.0).clamp(1.0, 120.0),
            seed: self.get_seed().max(1),
        }
    }
}

/// Pre-allocation constructor for `SphScratchBuffers`.
impl SphScratchBuffers {
    /// Allocates all solver scratch buffers once to exact fixed capacities.
    ///
    /// # Arguments
    ///
    /// - `usize` - Maximum active particle capacity.
    /// - `usize` - Power-of-two spatial hash bucket count.
    ///
    /// # Returns
    ///
    /// - `Self` - Pre-allocated zero-steady-state-allocation scratch buffers.
    pub(crate) fn preallocate(max_particles: usize, hash_table_size: usize) -> Self {
        Self {
            predicted_positions: vec![Vec3::zero(); max_particles],
            lambdas: vec![0.0; max_particles],
            delta_positions: vec![Vec3::zero(); max_particles],
            vorticities: vec![Vec3::zero(); max_particles],
            xsph_deltas: vec![Vec3::zero(); max_particles],
            tension_deltas: vec![Vec3::zero(); max_particles],
            cell_counts: vec![0; hash_table_size],
            cell_offsets: vec![0; hash_table_size + 1],
            cell_cursors: vec![0; hash_table_size],
            particle_hashes: vec![0; max_particles],
            sorted_indices: vec![0; max_particles],
            neighbor_counts: vec![0; max_particles],
            neighbor_indices: vec![0; max_particles * SPH_MAX_NEIGHBORS],
        }
    }
}

/// Default empty 3D `SphLiquidSolver3D`.
impl Default for SphLiquidSolver3D {
    /// Creates a pre-allocated 3D `SphLiquidSolver3D` with default physical parameters.
    ///
    /// # Returns
    ///
    /// - `Self` - Pre-allocated PBF/SPH solver.
    fn default() -> Self {
        Self::from_config(SphSolverConfig::default_3d())
    }
}

/// Simulation, spawner, collider, emitter, drain, and diagnostics API for `SphLiquidSolver3D`.
impl SphLiquidSolver3D {
    /// Constructs a pre-allocated `SphLiquidSolver3D` from `config` so `step(dt)` performs zero heap allocations.
    ///
    /// # Arguments
    ///
    /// - `SphSolverConfig` - Desired 2D or 3D PBF/SPH solver configuration.
    ///
    /// # Returns
    ///
    /// - `Self` - Ready pre-allocated solver.
    #[must_use]
    pub fn from_config(config: SphSolverConfig) -> Self {
        let clean: SphSolverConfig = config.sanitized();
        let max_p: usize = clean.get_max_particles();
        let hash_sz: usize = clean.get_hash_table_size();
        Self {
            config: clean,
            particles: Vec::with_capacity(max_p),
            colliders: Vec::new(),
            emitters: Vec::new(),
            drains: Vec::new(),
            scratch: SphScratchBuffers::preallocate(max_p, hash_sz),
            rng_state: clean.get_seed(),
            step_count: 0,
            sim_time_secs: 0.0,
        }
    }

    /// Removes all active particles and resets step counters while preserving colliders and pre-allocated capacity.
    pub fn clear_particles(&mut self) {
        self.get_mut_particles().clear();
        self.set_step_count(0);
        self.set_sim_time_secs(0.0);
    }

    /// Registers a composable solid collider (`Box`, `Sphere`, `Capsule`, `Cylinder`, `Plane`, or `MovingContainer`).
    ///
    /// # Arguments
    ///
    /// - `SphSolidCollider` - Collider to append to the active simulation.
    pub fn add_collider(&mut self, collider: SphSolidCollider) {
        self.get_mut_colliders().push(collider);
    }

    /// Registers a continuous fluid particle emitter.
    ///
    /// # Arguments
    ///
    /// - `SphFluidEmitter` - Emitter configuration to append.
    pub fn add_emitter(&mut self, emitter: SphFluidEmitter) {
        self.get_mut_emitters().push(emitter);
    }

    /// Registers a spherical particle drain sink.
    ///
    /// # Arguments
    ///
    /// - `SphFluidDrain` - Drain sink configuration to append.
    pub fn add_drain(&mut self, drain: SphFluidDrain) {
        self.get_mut_drains().push(drain);
    }

    /// Spawns a single liquid particle if active capacity permits.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - Initial world-space particle position.
    /// - `Vec3` - Initial world-space particle velocity.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` if the particle was spawned, `false` when at capacity.
    pub fn spawn_particle(&mut self, position: Vec3, velocity: Vec3) -> bool {
        let cfg: SphSolverConfig = self.get_config();
        if self.get_particles().len() >= cfg.get_max_particles() {
            return false;
        }
        let colliders: Vec<SphSolidCollider> = take(self.get_mut_colliders());
        let clamped_pos: Vec3 = clamp_sph_position(position, cfg, &colliders);
        self.set_colliders(colliders);
        let projected_vel: Vec3 = sph_project_vec3(velocity, cfg.get_domain_mode());
        let particle: SphParticle = SphParticle::new(
            clamped_pos,
            projected_vel,
            cfg.get_rest_density(),
            Vec3::zero(),
        );
        self.get_mut_particles().push(particle);
        true
    }

    /// Spawns a packed 2D or 3D rectangular block of liquid particles with tiny deterministic jitter.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - Minimum corner of the liquid block.
    /// - `Vec3` - Maximum corner of the liquid block.
    /// - `f32` - Nominal lattice spacing in meters (`<= 0.0` defaults to `h / 2.5`).
    ///
    /// # Returns
    ///
    /// - `usize` - Number of newly spawned particles.
    pub fn spawn_box_block(&mut self, min_corner: Vec3, max_corner: Vec3, spacing: f32) -> usize {
        let cfg: SphSolverConfig = self.get_config();
        let mode: FluidDomainMode = cfg.get_domain_mode();
        let default_d: f32 = cfg.get_smoothing_radius() / 2.5;
        let step: f32 = if spacing.is_finite() && spacing > 1e-4 {
            spacing
        } else {
            default_d
        };
        let lo: Vec3 = sph_project_vec3(min_corner.min(max_corner), mode);
        let hi: Vec3 = sph_project_vec3(min_corner.max(max_corner), mode);
        let jitter: f32 = step * 0.04;
        let mut rng: u64 = self.get_rng_state();
        let mut spawned: usize = 0;
        let nx: usize = (((hi.get_x() - lo.get_x()) / step).floor().max(0.0) as usize) + 1;
        let ny: usize = (((hi.get_y() - lo.get_y()) / step).floor().max(0.0) as usize) + 1;
        let nz: usize = match mode {
            FluidDomainMode::Dim2 => 1,
            FluidDomainMode::Dim3 => {
                (((hi.get_z() - lo.get_z()) / step).floor().max(0.0) as usize) + 1
            }
        };
        for iz in 0..nz {
            for iy in 0..ny {
                for ix in 0..nx {
                    let jx: f32 = (sph_next_unit_f32(&mut rng) - 0.5) * jitter;
                    let jy: f32 = (sph_next_unit_f32(&mut rng) - 0.5) * jitter;
                    let jz: f32 = match mode {
                        FluidDomainMode::Dim2 => 0.0,
                        FluidDomainMode::Dim3 => (sph_next_unit_f32(&mut rng) - 0.5) * jitter,
                    };
                    let px: f32 = lo.get_x() + (ix as f32 + 0.5) * step + jx;
                    let py: f32 = lo.get_y() + (iy as f32 + 0.5) * step + jy;
                    let pz: f32 = match mode {
                        FluidDomainMode::Dim2 => 0.0,
                        FluidDomainMode::Dim3 => lo.get_z() + (iz as f32 + 0.5) * step + jz,
                    };
                    if px <= hi.get_x()
                        && py <= hi.get_y()
                        && (mode == FluidDomainMode::Dim2 || pz <= hi.get_z())
                    {
                        if self.spawn_particle(Vec3::new(px, py, pz), Vec3::zero()) {
                            spawned += 1;
                        } else {
                            self.set_rng_state(rng);
                            return spawned;
                        }
                    }
                }
            }
        }
        self.set_rng_state(rng);
        spawned
    }

    /// Spawns a spherical (or circular in `Dim2`) cluster of liquid particles.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - Cluster center position in world space.
    /// - `f32` - Cluster radius in meters.
    /// - `f32` - Nominal lattice spacing in meters (`<= 0.0` defaults to `h / 2.5`).
    ///
    /// # Returns
    ///
    /// - `usize` - Number of newly spawned particles.
    pub fn spawn_sphere_cluster(&mut self, center: Vec3, radius: f32, spacing: f32) -> usize {
        let cfg: SphSolverConfig = self.get_config();
        let mode: FluidDomainMode = cfg.get_domain_mode();
        let default_d: f32 = cfg.get_smoothing_radius() / 2.5;
        let step: f32 = if spacing.is_finite() && spacing > 1e-4 {
            spacing
        } else {
            default_d
        };
        let safe_r: f32 = sph_sanitize_f32(radius, step * 2.0).max(step * 0.5);
        let r_sq: f32 = safe_r * safe_r;
        let steps: i32 = (safe_r / step).ceil() as i32;
        let z_span: i32 = match mode {
            FluidDomainMode::Dim2 => 0,
            FluidDomainMode::Dim3 => steps,
        };
        let mut spawned: usize = 0;
        for iz in -z_span..=z_span {
            for iy in -steps..=steps {
                for ix in -steps..=steps {
                    let offset: Vec3 =
                        Vec3::new(ix as f32 * step, iy as f32 * step, iz as f32 * step);
                    if offset.length_sq() <= r_sq {
                        let pos: Vec3 = sph_project_vec3(center.add(offset), mode);
                        if self.spawn_particle(pos, Vec3::zero()) {
                            spawned += 1;
                        } else {
                            return spawned;
                        }
                    }
                }
            }
        }
        spawned
    }

    /// Advances the PBF/SPH liquid simulation by `dt_secs` with zero steady-state heap allocations.
    ///
    /// # Arguments
    ///
    /// - `f32` - Frame step duration in seconds.
    pub fn step(&mut self, dt_secs: f32) {
        let clamped_dt: f32 = sph_sanitize_f32(dt_secs, 0.0).clamp(0.0, SPH_MAX_DT_SECS);
        if clamped_dt <= 1e-6 {
            return;
        }
        let cfg: SphSolverConfig = self.get_config();
        let mode: FluidDomainMode = cfg.get_domain_mode();
        let mut rng: u64 = self.get_rng_state();
        let mut emitters: Vec<SphFluidEmitter> = take(self.get_mut_emitters());
        let drains: Vec<SphFluidDrain> = take(self.get_mut_drains());
        let colliders: Vec<SphSolidCollider> = take(self.get_mut_colliders());
        let mut particles: Vec<SphParticle> = take(self.get_mut_particles());
        for emitter in emitters.iter_mut() {
            if !emitter.get_enabled() || emitter.get_rate_per_sec() <= 0.0 {
                continue;
            }
            let acc: f32 = emitter.get_accumulator() + emitter.get_rate_per_sec() * clamped_dt;
            let emit_count: usize = acc.floor().max(0.0) as usize;
            emitter.set_accumulator(acc - emit_count as f32);
            let nozzle_r: f32 = emitter.get_radius().abs();
            for _emit_idx in 0..emit_count {
                if particles.len() >= cfg.get_max_particles() {
                    break;
                }
                let jx: f32 = (sph_next_unit_f32(&mut rng) * 2.0 - 1.0) * nozzle_r;
                let jy: f32 = (sph_next_unit_f32(&mut rng) * 2.0 - 1.0) * nozzle_r;
                let jz: f32 = match mode {
                    FluidDomainMode::Dim2 => 0.0,
                    FluidDomainMode::Dim3 => (sph_next_unit_f32(&mut rng) * 2.0 - 1.0) * nozzle_r,
                };
                let spawn_pos: Vec3 = clamp_sph_position(
                    emitter.get_position().add(Vec3::new(jx, jy, jz)),
                    cfg,
                    &colliders,
                );
                let spawn_vel: Vec3 = sph_project_vec3(emitter.get_velocity(), mode);
                particles.push(SphParticle::new(
                    spawn_pos,
                    spawn_vel,
                    cfg.get_rest_density(),
                    Vec3::zero(),
                ));
            }
        }
        if !drains.is_empty() {
            let mut idx: usize = 0;
            while idx < particles.len() {
                let p_pos: Vec3 = particles[idx].get_position();
                let mut drained: bool = false;
                for drain in drains.iter() {
                    if !drain.get_enabled() {
                        continue;
                    }
                    let r: f32 = drain.get_radius().abs();
                    if p_pos.sub(drain.get_position()).length_sq() <= r * r {
                        drained = true;
                        break;
                    }
                }
                if drained {
                    let _: SphParticle = particles.swap_remove(idx);
                } else {
                    idx += 1;
                }
            }
        }
        let count: usize = particles.len();
        if count > 0 {
            let substeps: u32 = cfg.get_substeps().max(1);
            let dt_sub: f32 = clamped_dt / substeps as f32;
            let k: SphKernelConstants = compute_sph_kernel_constants(cfg);
            let gravity_dv: Vec3 = cfg.get_gravity().scale(dt_sub);
            let mut scratch: SphScratchBuffers = take(self.get_mut_scratch());
            for _sub in 0..substeps {
                let mut predicted: Vec<Vec3> = take(scratch.get_mut_predicted_positions());
                for idx in 0..count {
                    let vel: Vec3 = particles[idx].get_velocity().add(gravity_dv);
                    let pred: Vec3 = particles[idx].get_position().add(vel.scale(dt_sub));
                    predicted[idx] = clamp_sph_position(pred, cfg, &colliders);
                }
                scratch.set_predicted_positions(predicted);
                rebuild_sph_spatial_hash_and_neighbors(cfg, count, &mut scratch);
                run_sph_pbf_iterations(cfg, k, &mut particles, &colliders, &mut scratch);
                apply_sph_post_solve_forces(
                    cfg,
                    k,
                    dt_sub,
                    &mut particles,
                    &colliders,
                    &mut scratch,
                );
            }
            self.set_scratch(scratch);
        }
        self.set_particles(particles);
        self.set_colliders(colliders);
        self.set_emitters(emitters);
        self.set_drains(drains);
        self.set_rng_state(rng);
        let next_steps: u64 = self.get_step_count() + 1;
        let next_time: f32 = self.get_sim_time_secs() + clamped_dt;
        self.set_step_count(next_steps);
        self.set_sim_time_secs(next_time);
    }

    /// Computes live density convergence, kinetic energy, and total mass diagnostics across all active particles.
    ///
    /// # Returns
    ///
    /// - `SphSolverStats` - Aggregate particle statistics snapshot.
    #[must_use]
    pub fn stats(&self) -> SphSolverStats {
        let particles: &[SphParticle] = self.get_particles();
        let count: usize = particles.len();
        if count == 0 {
            return SphSolverStats::new(0, 0.0, 0.0, 0.0, 0.0, 0.0, self.get_step_count());
        }
        let cfg: SphSolverConfig = self.get_config();
        let rho0: f32 = cfg.get_rest_density();
        let mass: f32 = cfg.get_particle_mass();
        let mut sum_rho: f32 = 0.0;
        let mut max_rho: f32 = 0.0;
        let mut sum_err: f32 = 0.0;
        let mut ke: f32 = 0.0;
        for particle in particles.iter() {
            let rho: f32 = particle.get_density();
            sum_rho += rho;
            if rho > max_rho {
                max_rho = rho;
            }
            sum_err += (rho / rho0 - 1.0).max(0.0);
            ke += 0.5 * mass * particle.get_velocity().length_sq();
        }
        let inv_n: f32 = 1.0 / count as f32;
        SphSolverStats::new(
            count,
            sum_rho * inv_n,
            max_rho,
            sum_err * inv_n,
            ke,
            mass * count as f32,
            self.get_step_count(),
        )
    }
}