Skip to main content

euv_core/game/fluid_kit/sph3d/
impl.rs

1use super::*;
2
3/// Default 3D PBF/SPH liquid solver configuration.
4impl Default for SphSolverConfig {
5    /// Returns a balanced default 3D PBF liquid solver configuration.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - Default 3D solver configuration.
10    fn default() -> Self {
11        Self::default_3d()
12    }
13}
14
15/// Dimensional preset constructors and sanitization helpers for `SphSolverConfig`.
16impl SphSolverConfig {
17    /// Creates a calibrated default 2D planar liquid PBF configuration (`z = 0`).
18    ///
19    /// # Returns
20    ///
21    /// - `Self` - Ready 2D PBF configuration with rest-density-matched particle mass.
22    #[must_use]
23    pub fn default_2d() -> Self {
24        let h: f32 = SPH_DEFAULT_SMOOTHING_RADIUS_2D;
25        let spacing: f32 = h / 2.5;
26        let mass: f32 = SPH_DEFAULT_REST_DENSITY * spacing * spacing;
27        Self {
28            domain_mode: FluidDomainMode::Dim2,
29            domain_min: Vec3::new(-1.0, 0.0, 0.0),
30            domain_max: Vec3::new(1.0, 2.0, 0.0),
31            smoothing_radius: h,
32            rest_density: SPH_DEFAULT_REST_DENSITY,
33            particle_mass: mass,
34            gravity: Vec3::new(0.0, SPH_DEFAULT_GRAVITY_Y, 0.0),
35            substeps: 2,
36            solver_iterations: 4,
37            cfm_epsilon: 0.08,
38            scorr_k: 0.001_2,
39            scorr_dq_ratio: 0.25,
40            scorr_n: 4,
41            xsph_viscosity: 0.035,
42            vorticity_epsilon: 0.000_25,
43            surface_tension_cohesion: 0.012,
44            surface_tension_curvature: 0.008,
45            max_particles: SPH_DEFAULT_MAX_PARTICLES,
46            hash_table_size: SPH_DEFAULT_HASH_TABLE_SIZE,
47            max_speed: 16.0,
48            seed: SPH_DEFAULT_SEED,
49        }
50    }
51
52    /// Creates a calibrated default 3D volumetric liquid PBF configuration.
53    ///
54    /// # Returns
55    ///
56    /// - `Self` - Ready 3D PBF configuration with rest-density-matched particle mass.
57    #[must_use]
58    pub fn default_3d() -> Self {
59        let h: f32 = SPH_DEFAULT_SMOOTHING_RADIUS_3D;
60        let spacing: f32 = h / 2.5;
61        let mass: f32 = SPH_DEFAULT_REST_DENSITY * spacing * spacing * spacing;
62        Self {
63            domain_mode: FluidDomainMode::Dim3,
64            domain_min: Vec3::new(-1.0, 0.0, -1.0),
65            domain_max: Vec3::new(1.0, 2.0, 1.0),
66            smoothing_radius: h,
67            rest_density: SPH_DEFAULT_REST_DENSITY,
68            particle_mass: mass,
69            gravity: Vec3::new(0.0, SPH_DEFAULT_GRAVITY_Y, 0.0),
70            substeps: 2,
71            solver_iterations: 4,
72            cfm_epsilon: 0.08,
73            scorr_k: 0.001_2,
74            scorr_dq_ratio: 0.25,
75            scorr_n: 4,
76            xsph_viscosity: 0.035,
77            vorticity_epsilon: 0.000_25,
78            surface_tension_cohesion: 0.012,
79            surface_tension_curvature: 0.008,
80            max_particles: SPH_DEFAULT_MAX_PARTICLES,
81            hash_table_size: SPH_DEFAULT_HASH_TABLE_SIZE,
82            max_speed: 16.0,
83            seed: SPH_DEFAULT_SEED,
84        }
85    }
86
87    /// Returns a validated, finite copy of this configuration with power-of-two hash table sizing.
88    ///
89    /// # Returns
90    ///
91    /// - `Self` - Sanitized solver configuration.
92    #[must_use]
93    pub fn sanitized(self) -> Self {
94        let mode: FluidDomainMode = self.get_domain_mode();
95        let h: f32 = sph_sanitize_f32(self.get_smoothing_radius(), SPH_DEFAULT_SMOOTHING_RADIUS_3D)
96            .clamp(0.01, 5.0);
97        let rho0: f32 = sph_sanitize_f32(self.get_rest_density(), SPH_DEFAULT_REST_DENSITY)
98            .clamp(10.0, 20_000.0);
99        let nominal_d: f32 = h / 2.5;
100        let default_mass: f32 = match mode {
101            FluidDomainMode::Dim2 => rho0 * nominal_d * nominal_d,
102            FluidDomainMode::Dim3 => rho0 * nominal_d * nominal_d * nominal_d,
103        };
104        let raw_mass: f32 = sph_sanitize_f32(self.get_particle_mass(), default_mass);
105        let mass: f32 = if raw_mass > 1e-6 {
106            raw_mass
107        } else {
108            default_mass
109        };
110        let raw_min: Vec3 = sph_project_vec3(self.get_domain_min(), mode);
111        let raw_max: Vec3 = sph_project_vec3(self.get_domain_max(), mode);
112        let min_v: Vec3 = raw_min.min(raw_max);
113        let max_v: Vec3 = Vec3::new(
114            raw_max.get_x().max(min_v.get_x() + h),
115            raw_max.get_y().max(min_v.get_y() + h),
116            match mode {
117                FluidDomainMode::Dim2 => 0.0,
118                FluidDomainMode::Dim3 => raw_max.get_z().max(min_v.get_z() + h),
119            },
120        );
121        let hash_size: usize = self
122            .get_hash_table_size()
123            .clamp(256, 65_536)
124            .next_power_of_two();
125        Self {
126            domain_mode: mode,
127            domain_min: min_v,
128            domain_max: max_v,
129            smoothing_radius: h,
130            rest_density: rho0,
131            particle_mass: mass,
132            gravity: sph_project_vec3(self.get_gravity(), mode),
133            substeps: self.get_substeps().clamp(1, 8),
134            solver_iterations: self.get_solver_iterations().clamp(1, 12),
135            cfm_epsilon: sph_sanitize_f32(self.get_cfm_epsilon(), 0.08).clamp(1e-4, 100.0),
136            scorr_k: sph_sanitize_f32(self.get_scorr_k(), 0.001_2).clamp(0.0, 0.05),
137            scorr_dq_ratio: sph_sanitize_f32(self.get_scorr_dq_ratio(), 0.25).clamp(0.05, 0.8),
138            scorr_n: self.get_scorr_n().clamp(1, 8),
139            xsph_viscosity: sph_sanitize_f32(self.get_xsph_viscosity(), 0.035).clamp(0.0, 0.5),
140            vorticity_epsilon: sph_sanitize_f32(self.get_vorticity_epsilon(), 0.000_25)
141                .clamp(0.0, 0.05),
142            surface_tension_cohesion: sph_sanitize_f32(self.get_surface_tension_cohesion(), 0.012)
143                .clamp(0.0, 2.0),
144            surface_tension_curvature: sph_sanitize_f32(
145                self.get_surface_tension_curvature(),
146                0.008,
147            )
148            .clamp(0.0, 2.0),
149            max_particles: self.get_max_particles().clamp(16, 32_768),
150            hash_table_size: hash_size,
151            max_speed: sph_sanitize_f32(self.get_max_speed(), 16.0).clamp(1.0, 120.0),
152            seed: self.get_seed().max(1),
153        }
154    }
155}
156
157/// Pre-allocation constructor for `SphScratchBuffers`.
158impl SphScratchBuffers {
159    /// Allocates all solver scratch buffers once to exact fixed capacities.
160    ///
161    /// # Arguments
162    ///
163    /// - `usize` - Maximum active particle capacity.
164    /// - `usize` - Power-of-two spatial hash bucket count.
165    ///
166    /// # Returns
167    ///
168    /// - `Self` - Pre-allocated zero-steady-state-allocation scratch buffers.
169    pub(crate) fn preallocate(max_particles: usize, hash_table_size: usize) -> Self {
170        Self {
171            predicted_positions: vec![Vec3::zero(); max_particles],
172            lambdas: vec![0.0; max_particles],
173            delta_positions: vec![Vec3::zero(); max_particles],
174            vorticities: vec![Vec3::zero(); max_particles],
175            xsph_deltas: vec![Vec3::zero(); max_particles],
176            tension_deltas: vec![Vec3::zero(); max_particles],
177            cell_counts: vec![0; hash_table_size],
178            cell_offsets: vec![0; hash_table_size + 1],
179            cell_cursors: vec![0; hash_table_size],
180            particle_hashes: vec![0; max_particles],
181            sorted_indices: vec![0; max_particles],
182            neighbor_counts: vec![0; max_particles],
183            neighbor_indices: vec![0; max_particles * SPH_MAX_NEIGHBORS],
184        }
185    }
186}
187
188/// Default empty 3D `SphLiquidSolver3D`.
189impl Default for SphLiquidSolver3D {
190    /// Creates a pre-allocated 3D `SphLiquidSolver3D` with default physical parameters.
191    ///
192    /// # Returns
193    ///
194    /// - `Self` - Pre-allocated PBF/SPH solver.
195    fn default() -> Self {
196        Self::from_config(SphSolverConfig::default_3d())
197    }
198}
199
200/// Simulation, spawner, collider, emitter, drain, and diagnostics API for `SphLiquidSolver3D`.
201impl SphLiquidSolver3D {
202    /// Constructs a pre-allocated `SphLiquidSolver3D` from `config` so `step(dt)` performs zero heap allocations.
203    ///
204    /// # Arguments
205    ///
206    /// - `SphSolverConfig` - Desired 2D or 3D PBF/SPH solver configuration.
207    ///
208    /// # Returns
209    ///
210    /// - `Self` - Ready pre-allocated solver.
211    #[must_use]
212    pub fn from_config(config: SphSolverConfig) -> Self {
213        let clean: SphSolverConfig = config.sanitized();
214        let max_p: usize = clean.get_max_particles();
215        let hash_sz: usize = clean.get_hash_table_size();
216        Self {
217            config: clean,
218            particles: Vec::with_capacity(max_p),
219            colliders: Vec::new(),
220            emitters: Vec::new(),
221            drains: Vec::new(),
222            scratch: SphScratchBuffers::preallocate(max_p, hash_sz),
223            rng_state: clean.get_seed(),
224            step_count: 0,
225            sim_time_secs: 0.0,
226        }
227    }
228
229    /// Removes all active particles and resets step counters while preserving colliders and pre-allocated capacity.
230    pub fn clear_particles(&mut self) {
231        self.get_mut_particles().clear();
232        self.set_step_count(0);
233        self.set_sim_time_secs(0.0);
234    }
235
236    /// Registers a composable solid collider (`Box`, `Sphere`, `Capsule`, `Cylinder`, `Plane`, or `MovingContainer`).
237    ///
238    /// # Arguments
239    ///
240    /// - `SphSolidCollider` - Collider to append to the active simulation.
241    pub fn add_collider(&mut self, collider: SphSolidCollider) {
242        self.get_mut_colliders().push(collider);
243    }
244
245    /// Registers a continuous fluid particle emitter.
246    ///
247    /// # Arguments
248    ///
249    /// - `SphFluidEmitter` - Emitter configuration to append.
250    pub fn add_emitter(&mut self, emitter: SphFluidEmitter) {
251        self.get_mut_emitters().push(emitter);
252    }
253
254    /// Registers a spherical particle drain sink.
255    ///
256    /// # Arguments
257    ///
258    /// - `SphFluidDrain` - Drain sink configuration to append.
259    pub fn add_drain(&mut self, drain: SphFluidDrain) {
260        self.get_mut_drains().push(drain);
261    }
262
263    /// Spawns a single liquid particle if active capacity permits.
264    ///
265    /// # Arguments
266    ///
267    /// - `Vec3` - Initial world-space particle position.
268    /// - `Vec3` - Initial world-space particle velocity.
269    ///
270    /// # Returns
271    ///
272    /// - `bool` - `true` if the particle was spawned, `false` when at capacity.
273    pub fn spawn_particle(&mut self, position: Vec3, velocity: Vec3) -> bool {
274        let cfg: SphSolverConfig = self.get_config();
275        if self.get_particles().len() >= cfg.get_max_particles() {
276            return false;
277        }
278        let colliders: Vec<SphSolidCollider> = take(self.get_mut_colliders());
279        let clamped_pos: Vec3 = clamp_sph_position(position, cfg, &colliders);
280        self.set_colliders(colliders);
281        let projected_vel: Vec3 = sph_project_vec3(velocity, cfg.get_domain_mode());
282        let particle: SphParticle = SphParticle::new(
283            clamped_pos,
284            projected_vel,
285            cfg.get_rest_density(),
286            Vec3::zero(),
287        );
288        self.get_mut_particles().push(particle);
289        true
290    }
291
292    /// Spawns a packed 2D or 3D rectangular block of liquid particles with tiny deterministic jitter.
293    ///
294    /// # Arguments
295    ///
296    /// - `Vec3` - Minimum corner of the liquid block.
297    /// - `Vec3` - Maximum corner of the liquid block.
298    /// - `f32` - Nominal lattice spacing in meters (`<= 0.0` defaults to `h / 2.5`).
299    ///
300    /// # Returns
301    ///
302    /// - `usize` - Number of newly spawned particles.
303    pub fn spawn_box_block(&mut self, min_corner: Vec3, max_corner: Vec3, spacing: f32) -> usize {
304        let cfg: SphSolverConfig = self.get_config();
305        let mode: FluidDomainMode = cfg.get_domain_mode();
306        let default_d: f32 = cfg.get_smoothing_radius() / 2.5;
307        let step: f32 = if spacing.is_finite() && spacing > 1e-4 {
308            spacing
309        } else {
310            default_d
311        };
312        let lo: Vec3 = sph_project_vec3(min_corner.min(max_corner), mode);
313        let hi: Vec3 = sph_project_vec3(min_corner.max(max_corner), mode);
314        let jitter: f32 = step * 0.04;
315        let mut rng: u64 = self.get_rng_state();
316        let mut spawned: usize = 0;
317        let nx: usize = (((hi.get_x() - lo.get_x()) / step).floor().max(0.0) as usize) + 1;
318        let ny: usize = (((hi.get_y() - lo.get_y()) / step).floor().max(0.0) as usize) + 1;
319        let nz: usize = match mode {
320            FluidDomainMode::Dim2 => 1,
321            FluidDomainMode::Dim3 => {
322                (((hi.get_z() - lo.get_z()) / step).floor().max(0.0) as usize) + 1
323            }
324        };
325        for iz in 0..nz {
326            for iy in 0..ny {
327                for ix in 0..nx {
328                    let jx: f32 = (sph_next_unit_f32(&mut rng) - 0.5) * jitter;
329                    let jy: f32 = (sph_next_unit_f32(&mut rng) - 0.5) * jitter;
330                    let jz: f32 = match mode {
331                        FluidDomainMode::Dim2 => 0.0,
332                        FluidDomainMode::Dim3 => (sph_next_unit_f32(&mut rng) - 0.5) * jitter,
333                    };
334                    let px: f32 = lo.get_x() + (ix as f32 + 0.5) * step + jx;
335                    let py: f32 = lo.get_y() + (iy as f32 + 0.5) * step + jy;
336                    let pz: f32 = match mode {
337                        FluidDomainMode::Dim2 => 0.0,
338                        FluidDomainMode::Dim3 => lo.get_z() + (iz as f32 + 0.5) * step + jz,
339                    };
340                    if px <= hi.get_x()
341                        && py <= hi.get_y()
342                        && (mode == FluidDomainMode::Dim2 || pz <= hi.get_z())
343                    {
344                        if self.spawn_particle(Vec3::new(px, py, pz), Vec3::zero()) {
345                            spawned += 1;
346                        } else {
347                            self.set_rng_state(rng);
348                            return spawned;
349                        }
350                    }
351                }
352            }
353        }
354        self.set_rng_state(rng);
355        spawned
356    }
357
358    /// Spawns a spherical (or circular in `Dim2`) cluster of liquid particles.
359    ///
360    /// # Arguments
361    ///
362    /// - `Vec3` - Cluster center position in world space.
363    /// - `f32` - Cluster radius in meters.
364    /// - `f32` - Nominal lattice spacing in meters (`<= 0.0` defaults to `h / 2.5`).
365    ///
366    /// # Returns
367    ///
368    /// - `usize` - Number of newly spawned particles.
369    pub fn spawn_sphere_cluster(&mut self, center: Vec3, radius: f32, spacing: f32) -> usize {
370        let cfg: SphSolverConfig = self.get_config();
371        let mode: FluidDomainMode = cfg.get_domain_mode();
372        let default_d: f32 = cfg.get_smoothing_radius() / 2.5;
373        let step: f32 = if spacing.is_finite() && spacing > 1e-4 {
374            spacing
375        } else {
376            default_d
377        };
378        let safe_r: f32 = sph_sanitize_f32(radius, step * 2.0).max(step * 0.5);
379        let r_sq: f32 = safe_r * safe_r;
380        let steps: i32 = (safe_r / step).ceil() as i32;
381        let z_span: i32 = match mode {
382            FluidDomainMode::Dim2 => 0,
383            FluidDomainMode::Dim3 => steps,
384        };
385        let mut spawned: usize = 0;
386        for iz in -z_span..=z_span {
387            for iy in -steps..=steps {
388                for ix in -steps..=steps {
389                    let offset: Vec3 =
390                        Vec3::new(ix as f32 * step, iy as f32 * step, iz as f32 * step);
391                    if offset.length_sq() <= r_sq {
392                        let pos: Vec3 = sph_project_vec3(center.add(offset), mode);
393                        if self.spawn_particle(pos, Vec3::zero()) {
394                            spawned += 1;
395                        } else {
396                            return spawned;
397                        }
398                    }
399                }
400            }
401        }
402        spawned
403    }
404
405    /// Advances the PBF/SPH liquid simulation by `dt_secs` with zero steady-state heap allocations.
406    ///
407    /// # Arguments
408    ///
409    /// - `f32` - Frame step duration in seconds.
410    pub fn step(&mut self, dt_secs: f32) {
411        let clamped_dt: f32 = sph_sanitize_f32(dt_secs, 0.0).clamp(0.0, SPH_MAX_DT_SECS);
412        if clamped_dt <= 1e-6 {
413            return;
414        }
415        let cfg: SphSolverConfig = self.get_config();
416        let mode: FluidDomainMode = cfg.get_domain_mode();
417        let mut rng: u64 = self.get_rng_state();
418        let mut emitters: Vec<SphFluidEmitter> = take(self.get_mut_emitters());
419        let drains: Vec<SphFluidDrain> = take(self.get_mut_drains());
420        let colliders: Vec<SphSolidCollider> = take(self.get_mut_colliders());
421        let mut particles: Vec<SphParticle> = take(self.get_mut_particles());
422        for emitter in emitters.iter_mut() {
423            if !emitter.get_enabled() || emitter.get_rate_per_sec() <= 0.0 {
424                continue;
425            }
426            let acc: f32 = emitter.get_accumulator() + emitter.get_rate_per_sec() * clamped_dt;
427            let emit_count: usize = acc.floor().max(0.0) as usize;
428            emitter.set_accumulator(acc - emit_count as f32);
429            let nozzle_r: f32 = emitter.get_radius().abs();
430            for _emit_idx in 0..emit_count {
431                if particles.len() >= cfg.get_max_particles() {
432                    break;
433                }
434                let jx: f32 = (sph_next_unit_f32(&mut rng) * 2.0 - 1.0) * nozzle_r;
435                let jy: f32 = (sph_next_unit_f32(&mut rng) * 2.0 - 1.0) * nozzle_r;
436                let jz: f32 = match mode {
437                    FluidDomainMode::Dim2 => 0.0,
438                    FluidDomainMode::Dim3 => (sph_next_unit_f32(&mut rng) * 2.0 - 1.0) * nozzle_r,
439                };
440                let spawn_pos: Vec3 = clamp_sph_position(
441                    emitter.get_position().add(Vec3::new(jx, jy, jz)),
442                    cfg,
443                    &colliders,
444                );
445                let spawn_vel: Vec3 = sph_project_vec3(emitter.get_velocity(), mode);
446                particles.push(SphParticle::new(
447                    spawn_pos,
448                    spawn_vel,
449                    cfg.get_rest_density(),
450                    Vec3::zero(),
451                ));
452            }
453        }
454        if !drains.is_empty() {
455            let mut idx: usize = 0;
456            while idx < particles.len() {
457                let p_pos: Vec3 = particles[idx].get_position();
458                let mut drained: bool = false;
459                for drain in drains.iter() {
460                    if !drain.get_enabled() {
461                        continue;
462                    }
463                    let r: f32 = drain.get_radius().abs();
464                    if p_pos.sub(drain.get_position()).length_sq() <= r * r {
465                        drained = true;
466                        break;
467                    }
468                }
469                if drained {
470                    let _: SphParticle = particles.swap_remove(idx);
471                } else {
472                    idx += 1;
473                }
474            }
475        }
476        let count: usize = particles.len();
477        if count > 0 {
478            let substeps: u32 = cfg.get_substeps().max(1);
479            let dt_sub: f32 = clamped_dt / substeps as f32;
480            let k: SphKernelConstants = compute_sph_kernel_constants(cfg);
481            let gravity_dv: Vec3 = cfg.get_gravity().scale(dt_sub);
482            let mut scratch: SphScratchBuffers = take(self.get_mut_scratch());
483            for _sub in 0..substeps {
484                let mut predicted: Vec<Vec3> = take(scratch.get_mut_predicted_positions());
485                for idx in 0..count {
486                    let vel: Vec3 = particles[idx].get_velocity().add(gravity_dv);
487                    let pred: Vec3 = particles[idx].get_position().add(vel.scale(dt_sub));
488                    predicted[idx] = clamp_sph_position(pred, cfg, &colliders);
489                }
490                scratch.set_predicted_positions(predicted);
491                rebuild_sph_spatial_hash_and_neighbors(cfg, count, &mut scratch);
492                run_sph_pbf_iterations(cfg, k, &mut particles, &colliders, &mut scratch);
493                apply_sph_post_solve_forces(
494                    cfg,
495                    k,
496                    dt_sub,
497                    &mut particles,
498                    &colliders,
499                    &mut scratch,
500                );
501            }
502            self.set_scratch(scratch);
503        }
504        self.set_particles(particles);
505        self.set_colliders(colliders);
506        self.set_emitters(emitters);
507        self.set_drains(drains);
508        self.set_rng_state(rng);
509        let next_steps: u64 = self.get_step_count() + 1;
510        let next_time: f32 = self.get_sim_time_secs() + clamped_dt;
511        self.set_step_count(next_steps);
512        self.set_sim_time_secs(next_time);
513    }
514
515    /// Computes live density convergence, kinetic energy, and total mass diagnostics across all active particles.
516    ///
517    /// # Returns
518    ///
519    /// - `SphSolverStats` - Aggregate particle statistics snapshot.
520    #[must_use]
521    pub fn stats(&self) -> SphSolverStats {
522        let particles: &[SphParticle] = self.get_particles();
523        let count: usize = particles.len();
524        if count == 0 {
525            return SphSolverStats::new(0, 0.0, 0.0, 0.0, 0.0, 0.0, self.get_step_count());
526        }
527        let cfg: SphSolverConfig = self.get_config();
528        let rho0: f32 = cfg.get_rest_density();
529        let mass: f32 = cfg.get_particle_mass();
530        let mut sum_rho: f32 = 0.0;
531        let mut max_rho: f32 = 0.0;
532        let mut sum_err: f32 = 0.0;
533        let mut ke: f32 = 0.0;
534        for particle in particles.iter() {
535            let rho: f32 = particle.get_density();
536            sum_rho += rho;
537            if rho > max_rho {
538                max_rho = rho;
539            }
540            sum_err += (rho / rho0 - 1.0).max(0.0);
541            ke += 0.5 * mass * particle.get_velocity().length_sq();
542        }
543        let inv_n: f32 = 1.0 / count as f32;
544        SphSolverStats::new(
545            count,
546            sum_rho * inv_n,
547            max_rho,
548            sum_err * inv_n,
549            ke,
550            mass * count as f32,
551            self.get_step_count(),
552        )
553    }
554}