Skip to main content

euv_core/game/fluid_kit/sph3d/
struct.rs

1use super::*;
2
3/// Composable solid collider enforcing particle containment or obstacle exclusion with friction and restitution.
4#[derive(Clone, Copy, Data, Debug, New, PartialEq)]
5pub struct SphSolidCollider {
6    /// Underlying geometric collider primitive.
7    #[get(type(copy))]
8    pub(crate) shape: SphColliderShape,
9    /// Tangential wall friction factor in `[0.0, 1.0]`.
10    #[get(type(copy))]
11    pub(crate) friction: f32,
12    /// Normal bounce restitution factor in `[0.0, 1.0]`.
13    #[get(type(copy))]
14    pub(crate) restitution: f32,
15    /// Whether this collider participates in simulation steps.
16    #[get(type(copy))]
17    pub(crate) enabled: bool,
18}
19
20/// Continuous particle fluid emitter spawning new liquid particles at a configured rate.
21#[derive(Clone, Copy, Data, Debug, New, PartialEq)]
22pub struct SphFluidEmitter {
23    /// World-space emission origin.
24    #[get(type(copy))]
25    pub(crate) position: Vec3,
26    /// Initial emitted particle velocity in meters per second.
27    #[get(type(copy))]
28    pub(crate) velocity: Vec3,
29    /// Nozzle disk/sphere spawn jitter radius in meters.
30    #[get(type(copy))]
31    pub(crate) radius: f32,
32    /// Emission rate in particles per second.
33    #[get(type(copy))]
34    pub(crate) rate_per_sec: f32,
35    /// Fractional emission accumulator carried across frames.
36    #[get(type(copy))]
37    pub(crate) accumulator: f32,
38    /// Whether this emitter is actively spawning particles.
39    #[get(type(copy))]
40    pub(crate) enabled: bool,
41}
42
43/// Spherical fluid drain sink removing particles entering its capture radius.
44#[derive(Clone, Copy, Data, Debug, New, PartialEq)]
45pub struct SphFluidDrain {
46    /// World-space drain center.
47    #[get(type(copy))]
48    pub(crate) position: Vec3,
49    /// Capture radius in meters within which particles are removed.
50    #[get(type(copy))]
51    pub(crate) radius: f32,
52    /// Whether this drain is active.
53    #[get(type(copy))]
54    pub(crate) enabled: bool,
55}
56
57/// Declarative configuration for the 2D/3D Position-Based Fluids `SphLiquidSolver3D`.
58#[derive(Clone, Copy, Data, Debug, PartialEq)]
59pub struct SphSolverConfig {
60    /// Simulation dimensionality (`Dim2` or `Dim3`).
61    #[get(type(copy))]
62    pub(crate) domain_mode: FluidDomainMode,
63    /// Outer safety domain minimum corner `(min_x, min_y, min_z)`.
64    #[get(type(copy))]
65    pub(crate) domain_min: Vec3,
66    /// Outer safety domain maximum corner `(max_x, max_y, max_z)`.
67    #[get(type(copy))]
68    pub(crate) domain_max: Vec3,
69    /// Kernel smoothing support radius `h` in meters.
70    #[get(type(copy))]
71    pub(crate) smoothing_radius: f32,
72    /// Target fluid rest density `rho_0` in `kg/m^3`.
73    #[get(type(copy))]
74    pub(crate) rest_density: f32,
75    /// Mass of each individual fluid particle in kg (`<= 0.0` auto-calibrates from spacing).
76    #[get(type(copy))]
77    pub(crate) particle_mass: f32,
78    /// Constant external body acceleration vector (default `(0, -9.80665, 0)`).
79    #[get(type(copy))]
80    pub(crate) gravity: Vec3,
81    /// Number of PBF substeps executed per `step(dt)` call.
82    #[get(type(copy))]
83    pub(crate) substeps: u32,
84    /// Number of Jacobi density constraint iterations per substep.
85    #[get(type(copy))]
86    pub(crate) solver_iterations: u32,
87    /// Dimensionless Constraint Force Mixing regularization parameter.
88    #[get(type(copy))]
89    pub(crate) cfm_epsilon: f32,
90    /// Artificial tensile-instability pressure strength `k` (`s_corr`, Macklin & Mueller).
91    #[get(type(copy))]
92    pub(crate) scorr_k: f32,
93    /// Artificial tensile-instability reference distance fraction `delta_q / h`.
94    #[get(type(copy))]
95    pub(crate) scorr_dq_ratio: f32,
96    /// Artificial tensile-instability kernel ratio exponent `n` (typically `4`).
97    #[get(type(copy))]
98    pub(crate) scorr_n: u32,
99    /// XSPH artificial viscosity smoothing factor.
100    #[get(type(copy))]
101    pub(crate) xsph_viscosity: f32,
102    /// Vorticity confinement eddy restoration strength.
103    #[get(type(copy))]
104    pub(crate) vorticity_epsilon: f32,
105    /// Akinci cohesion surface tension gain.
106    #[get(type(copy))]
107    pub(crate) surface_tension_cohesion: f32,
108    /// Akinci surface-curvature minimization gain.
109    #[get(type(copy))]
110    pub(crate) surface_tension_curvature: f32,
111    /// Pre-allocated maximum active particle capacity.
112    #[get(type(copy))]
113    pub(crate) max_particles: usize,
114    /// Power-of-two spatial hash table bucket count.
115    #[get(type(copy))]
116    pub(crate) hash_table_size: usize,
117    /// Maximum particle speed clamp in meters per second.
118    #[get(type(copy))]
119    pub(crate) max_speed: f32,
120    /// Deterministic PRNG seed for spawning and emission jitter.
121    #[get(type(copy))]
122    pub(crate) seed: u64,
123}
124
125/// Single simulated PBF/SPH liquid particle carrying kinematics, density, and Akinci surface normal.
126#[derive(Clone, Copy, Data, Debug, Default, New, PartialEq)]
127pub struct SphParticle {
128    /// Current world-space position in meters (`z == 0.0` in `Dim2`).
129    #[get(type(copy))]
130    pub(crate) position: Vec3,
131    /// Current world-space velocity in meters per second (`z == 0.0` in `Dim2`).
132    #[get(type(copy))]
133    pub(crate) velocity: Vec3,
134    /// Latest Poly6 kernel density estimate `rho_i` in `kg/m^3`.
135    #[get(type(copy))]
136    pub(crate) density: f32,
137    /// Akinci color-field surface normal vector `n_i` pointing into liquid interior.
138    #[get(type(copy))]
139    pub(crate) color_normal: Vec3,
140}
141
142/// Read-only diagnostics snapshot summarizing density convergence, energy, and total mass.
143#[derive(Clone, Copy, Data, Debug, Default, New, PartialEq)]
144pub struct SphSolverStats {
145    /// Active simulated particle count.
146    #[get(type(copy))]
147    pub(crate) particle_count: usize,
148    /// Mean particle density across all active particles.
149    #[get(type(copy))]
150    pub(crate) mean_density: f32,
151    /// Maximum instantaneous particle density across all active particles.
152    #[get(type(copy))]
153    pub(crate) max_density: f32,
154    /// Mean positive over-compression density error `mean(max(0, rho / rho_0 - 1))`.
155    #[get(type(copy))]
156    pub(crate) mean_compression_error: f32,
157    /// Total fluid kinetic energy `0.5 * sum(m * |v|^2)` in joules.
158    #[get(type(copy))]
159    pub(crate) kinetic_energy: f32,
160    /// Total conserved fluid mass `particle_count * particle_mass` in kg.
161    #[get(type(copy))]
162    pub(crate) total_mass: f32,
163    /// Total completed simulation ticks.
164    #[get(type(copy))]
165    pub(crate) step_count: u64,
166}
167
168/// Pre-allocated scratch buffers enabling zero steady-state heap allocations during `SphLiquidSolver3D::step`.
169#[derive(Clone, Data, Debug, Default, PartialEq)]
170pub(crate) struct SphScratchBuffers {
171    /// Predicted particle positions for the active PBF substep.
172    pub(crate) predicted_positions: Vec<Vec3>,
173    /// Per-particle Lagrange density multipliers `lambda_i`.
174    pub(crate) lambdas: Vec<f32>,
175    /// Per-particle Jacobi position correction deltas `delta_p_i`.
176    pub(crate) delta_positions: Vec<Vec3>,
177    /// Per-particle curl/vorticity vectors `omega_i`.
178    pub(crate) vorticities: Vec<Vec3>,
179    /// Per-particle XSPH velocity smoothing deltas.
180    pub(crate) xsph_deltas: Vec<Vec3>,
181    /// Per-particle Akinci cohesion + curvature velocity impulses.
182    pub(crate) tension_deltas: Vec<Vec3>,
183    /// Per-bucket counting-sort particle counts.
184    pub(crate) cell_counts: Vec<u32>,
185    /// Prefix-summed spatial hash bucket start offsets (`hash_table_size + 1`).
186    pub(crate) cell_offsets: Vec<u32>,
187    /// Mutable counting-sort write cursors per bucket.
188    pub(crate) cell_cursors: Vec<u32>,
189    /// Cached hash bucket index per particle.
190    pub(crate) particle_hashes: Vec<u32>,
191    /// Counting-sorted particle indices grouped by hash bucket.
192    pub(crate) sorted_indices: Vec<u32>,
193    /// Neighbor count cached for each particle.
194    pub(crate) neighbor_counts: Vec<u16>,
195    /// Flat neighbor index matrix (`max_particles * SPH_MAX_NEIGHBORS`).
196    pub(crate) neighbor_indices: Vec<u32>,
197}
198
199/// Precomputed dimension-specific SPH kernel normalization coefficients.
200#[derive(Clone, Copy, Data, Debug, Default, New, PartialEq)]
201pub(crate) struct SphKernelConstants {
202    /// Smoothing support radius `h`.
203    #[get(type(copy))]
204    pub(crate) h: f32,
205    /// Squared smoothing radius `h^2`.
206    #[get(type(copy))]
207    pub(crate) h2: f32,
208    /// Poly6 normalization scalar.
209    #[get(type(copy))]
210    pub(crate) poly6_coeff: f32,
211    /// Spiky gradient normalization scalar (negative).
212    #[get(type(copy))]
213    pub(crate) spiky_grad_coeff: f32,
214    /// Poly6 gradient normalization scalar (negative) for Akinci color-field normal.
215    #[get(type(copy))]
216    pub(crate) poly6_grad_coeff: f32,
217    /// Akinci cohesion spline normalization scalar.
218    #[get(type(copy))]
219    pub(crate) akinci_cohesion_coeff: f32,
220    /// Poly6 kernel value at tensile reference distance `delta_q`.
221    #[get(type(copy))]
222    pub(crate) w_dq_inv: f32,
223}
224
225/// Production Position-Based Fluids (PBF/SPH) 2D & 3D particle liquid engine with zero steady-state allocations.
226#[derive(Clone, Data, Debug, PartialEq)]
227pub struct SphLiquidSolver3D {
228    /// Sanitized solver physical configuration.
229    #[get(type(copy))]
230    pub(crate) config: SphSolverConfig,
231    /// Dense active particle buffer pre-allocated to `config.max_particles`.
232    pub(crate) particles: Vec<SphParticle>,
233    /// Registered solid boundary and obstacle colliders.
234    pub(crate) colliders: Vec<SphSolidCollider>,
235    /// Registered continuous liquid emitters.
236    pub(crate) emitters: Vec<SphFluidEmitter>,
237    /// Registered spherical particle drains.
238    pub(crate) drains: Vec<SphFluidDrain>,
239    /// Pre-allocated O(N) spatial hash and solver scratch buffers.
240    pub(crate) scratch: SphScratchBuffers,
241    /// Deterministic PRNG state.
242    #[get(type(copy))]
243    pub(crate) rng_state: u64,
244    /// Total completed `step` invocations.
245    #[get(type(copy))]
246    pub(crate) step_count: u64,
247    /// Accumulated simulation time in seconds.
248    #[get(type(copy))]
249    pub(crate) sim_time_secs: f32,
250}