Skip to main content

euv_core/game/fluid_kit/ocean/
impl.rs

1use super::*;
2
3/// Default clear coastal seawater optical configuration.
4impl Default for OceanOpticalConfig {
5    /// Returns the default physical seawater Beer-Lambert, Fresnel, SSS, and caustics configuration.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - Default optical configuration.
10    fn default() -> Self {
11        Self::from_preset(OceanPreset::CoastalSwell)
12    }
13}
14
15/// Preset optical profile constructors for `OceanOpticalConfig`.
16impl OceanOpticalConfig {
17    /// Returns a curated physically based optical configuration tuned for `preset`.
18    ///
19    /// # Arguments
20    ///
21    /// - `OceanPreset` - Target sea-state preset.
22    ///
23    /// # Returns
24    ///
25    /// - `Self` - Preset optical parameters.
26    #[must_use]
27    pub fn from_preset(preset: OceanPreset) -> Self {
28        match preset {
29            OceanPreset::CalmLagoon => Self {
30                absorption_coeff: Vec3::new(0.32, 0.08, 0.05),
31                deep_scatter_color: Vec3::new(0.02, 0.16, 0.24),
32                shallow_tint_color: Vec3::new(0.08, 0.56, 0.58),
33                sss_color: Vec3::new(0.06, 0.62, 0.52),
34                foam_color: Vec3::new(0.95, 0.97, 0.99),
35                fresnel_f0: OCEAN_FRESNEL_F0,
36                sss_strength: 0.72,
37                caustics_strength: 1.35,
38                foam_jacobian_threshold: 0.72,
39            },
40            OceanPreset::CoastalSwell => Self {
41                absorption_coeff: Vec3::from_array(OCEAN_DEFAULT_ABSORPTION_RGB),
42                deep_scatter_color: Vec3::new(0.015, 0.09, 0.17),
43                shallow_tint_color: Vec3::new(0.05, 0.38, 0.42),
44                sss_color: Vec3::new(0.04, 0.48, 0.40),
45                foam_color: Vec3::new(0.92, 0.95, 0.98),
46                fresnel_f0: OCEAN_FRESNEL_F0,
47                sss_strength: 0.85,
48                caustics_strength: 1.0,
49                foam_jacobian_threshold: 0.78,
50            },
51            OceanPreset::OpenOcean => Self {
52                absorption_coeff: Vec3::new(0.48, 0.18, 0.07),
53                deep_scatter_color: Vec3::new(0.008, 0.045, 0.12),
54                shallow_tint_color: Vec3::new(0.02, 0.18, 0.30),
55                sss_color: Vec3::new(0.03, 0.36, 0.34),
56                foam_color: Vec3::new(0.90, 0.94, 0.97),
57                fresnel_f0: OCEAN_FRESNEL_F0,
58                sss_strength: 0.68,
59                caustics_strength: 0.65,
60                foam_jacobian_threshold: 0.80,
61            },
62            OceanPreset::StormyGale => Self {
63                absorption_coeff: Vec3::new(0.55, 0.28, 0.16),
64                deep_scatter_color: Vec3::new(0.012, 0.035, 0.065),
65                shallow_tint_color: Vec3::new(0.04, 0.12, 0.16),
66                sss_color: Vec3::new(0.05, 0.28, 0.26),
67                foam_color: Vec3::new(0.86, 0.90, 0.93),
68                fresnel_f0: OCEAN_FRESNEL_F0,
69                sss_strength: 0.55,
70                caustics_strength: 0.35,
71                foam_jacobian_threshold: 0.88,
72            },
73        }
74    }
75}
76
77/// Default `CoastalSwell` ocean sea-state configuration.
78impl Default for OceanConfig {
79    /// Returns the default `CoastalSwell` ocean configuration.
80    ///
81    /// # Returns
82    ///
83    /// - `Self` - Default ocean configuration.
84    fn default() -> Self {
85        Self::from_preset(OceanPreset::CoastalSwell)
86    }
87}
88
89/// Preset constructors and sanitization helpers for `OceanConfig`.
90impl OceanConfig {
91    /// Builds a complete sea-state `OceanConfig` tailored to `preset`.
92    ///
93    /// # Arguments
94    ///
95    /// - `OceanPreset` - Desired sea-state preset.
96    ///
97    /// # Returns
98    ///
99    /// - `Self` - Ready ocean configuration.
100    #[must_use]
101    pub fn from_preset(preset: OceanPreset) -> Self {
102        let (wind_speed, fetch_km, choppiness): (f32, f32, f32) = match preset {
103            OceanPreset::CalmLagoon => (4.5, 12.0, 0.42),
104            OceanPreset::CoastalSwell => (10.5, 65.0, 0.72),
105            OceanPreset::OpenOcean => (15.0, 220.0, 0.88),
106            OceanPreset::StormyGale => (24.0, 480.0, 1.15),
107        };
108        Self {
109            preset,
110            wind_speed_mps: wind_speed,
111            wind_direction: Vec2::new(0.86, 0.51),
112            fetch_km,
113            choppiness,
114            mean_water_level_y: 0.0,
115            gravity_mps2: OCEAN_GRAVITY_MPS2,
116            cascade_count: OCEAN_DEFAULT_CASCADES,
117            seed: OCEAN_DEFAULT_SEED,
118            optics: OceanOpticalConfig::from_preset(preset),
119        }
120    }
121
122    /// Returns a clamped, finite copy of this ocean configuration.
123    ///
124    /// # Returns
125    ///
126    /// - `Self` - Validated ocean configuration.
127    #[must_use]
128    pub fn sanitized(self) -> Self {
129        let dir: Vec2 = self.get_wind_direction();
130        let dx: f32 = ocean_sanitize_f32(dir.get_x(), 1.0);
131        let dz: f32 = ocean_sanitize_f32(dir.get_y(), 0.0);
132        let len: f32 = (dx * dx + dz * dz).sqrt();
133        let norm_dir: Vec2 = if len > 1e-5 {
134            Vec2::new(dx / len, dz / len)
135        } else {
136            Vec2::new(1.0, 0.0)
137        };
138        let mut optics: OceanOpticalConfig = self.get_optics();
139        optics.set_fresnel_f0(
140            ocean_sanitize_f32(optics.get_fresnel_f0(), OCEAN_FRESNEL_F0).clamp(0.005, 0.25),
141        );
142        optics.set_sss_strength(ocean_sanitize_f32(optics.get_sss_strength(), 0.7).clamp(0.0, 3.0));
143        optics.set_caustics_strength(
144            ocean_sanitize_f32(optics.get_caustics_strength(), 1.0).clamp(0.0, 4.0),
145        );
146        optics.set_foam_jacobian_threshold(
147            ocean_sanitize_f32(optics.get_foam_jacobian_threshold(), 0.78).clamp(0.15, 1.15),
148        );
149        Self {
150            preset: self.get_preset(),
151            wind_speed_mps: ocean_sanitize_f32(self.get_wind_speed_mps(), 10.0).clamp(0.5, 45.0),
152            wind_direction: norm_dir,
153            fetch_km: ocean_sanitize_f32(self.get_fetch_km(), 60.0).clamp(1.0, 2000.0),
154            choppiness: ocean_sanitize_f32(self.get_choppiness(), 0.75).clamp(0.0, 1.5),
155            mean_water_level_y: ocean_sanitize_f32(self.get_mean_water_level_y(), 0.0),
156            gravity_mps2: ocean_sanitize_f32(self.get_gravity_mps2(), OCEAN_GRAVITY_MPS2)
157                .clamp(1.0, 30.0),
158            cascade_count: self.get_cascade_count().clamp(1, 4),
159            seed: self.get_seed().max(1),
160            optics,
161        }
162    }
163}
164
165/// Default `OceanPatchDesc` for a `120 m × 120 m` LOD ocean mesh patch.
166impl Default for OceanPatchDesc {
167    /// Returns a balanced default ocean mesh patch descriptor.
168    ///
169    /// # Returns
170    ///
171    /// - `Self` - Default ocean patch descriptor.
172    fn default() -> Self {
173        Self {
174            center_xz: Vec2::zero(),
175            extent_x: 120.0,
176            extent_z: 120.0,
177            subdivisions_x: 48,
178            subdivisions_z: 48,
179            lod_radial_falloff: 0.45,
180            seabed_y: -14.0,
181        }
182    }
183}
184
185/// Default `CoastalSwell` `OceanSurface3D` instance.
186impl Default for OceanSurface3D {
187    /// Creates an `OceanSurface3D` configured with `OceanPreset::CoastalSwell`.
188    ///
189    /// # Returns
190    ///
191    /// - `Self` - Ready default ocean simulator.
192    fn default() -> Self {
193        Self::from_preset(OceanPreset::CoastalSwell)
194    }
195}
196
197/// Multi-cascade Gerstner + JONSWAP evaluation, optical shading, caustics, and LOD mesh patch builder for `OceanSurface3D`.
198impl OceanSurface3D {
199    /// Constructs an `OceanSurface3D` from a sea-state `OceanPreset`.
200    ///
201    /// # Arguments
202    ///
203    /// - `OceanPreset` - Desired sea-state preset.
204    ///
205    /// # Returns
206    ///
207    /// - `Self` - Initialized ocean surface synthesizer.
208    #[must_use]
209    pub fn from_preset(preset: OceanPreset) -> Self {
210        Self::from_config(OceanConfig::from_preset(preset))
211    }
212
213    /// Constructs an `OceanSurface3D` from a custom `OceanConfig`.
214    ///
215    /// # Arguments
216    ///
217    /// - `OceanConfig` - Ocean sea-state and optical configuration.
218    ///
219    /// # Returns
220    ///
221    /// - `Self` - Initialized ocean surface synthesizer with JONSWAP waves.
222    #[must_use]
223    pub fn from_config(config: OceanConfig) -> Self {
224        let clean: OceanConfig = config.sanitized();
225        let waves: Vec<GerstnerWaveComponent> = synthesize_jonswap_gerstner_waves(clean);
226        Self {
227            config: clean,
228            waves,
229            sim_time_secs: 0.0,
230        }
231    }
232
233    /// Advances the internal ocean simulation clock by `dt_secs` with zero heap allocations.
234    ///
235    /// # Arguments
236    ///
237    /// - `f32` - Frame time step in seconds.
238    pub fn step(&mut self, dt_secs: f32) {
239        let safe_dt: f32 = ocean_sanitize_f32(dt_secs, 0.0).clamp(0.0, 1.0);
240        let next_t: f32 = self.get_sim_time_secs() + safe_dt;
241        self.set_sim_time_secs(next_t);
242    }
243
244    /// Evaluates analytical 3D Gerstner displacement, exact surface normal, Jacobian, and foam mask at parametric `(coord_x, coord_z)`.
245    ///
246    /// # Arguments
247    ///
248    /// - `f32` - Undisplaced horizontal X coordinate in meters.
249    /// - `f32` - Undisplaced horizontal Z coordinate in meters.
250    ///
251    /// # Returns
252    ///
253    /// - `OceanSurfaceSample` - Exact analytical surface evaluation at current simulation time.
254    #[must_use]
255    pub fn sample_parametric(&self, coord_x: f32, coord_z: f32) -> OceanSurfaceSample {
256        evaluate_gerstner_sample(
257            self.get_waves(),
258            self.get_config(),
259            self.get_sim_time_secs(),
260            coord_x,
261            coord_z,
262        )
263    }
264
265    /// Evaluates the ocean surface at exact world-space horizontal `(world_x, world_z)` via iterative Gerstner displacement inversion.
266    ///
267    /// # Arguments
268    ///
269    /// - `f32` - World-space X coordinate in meters.
270    /// - `f32` - World-space Z coordinate in meters.
271    ///
272    /// # Returns
273    ///
274    /// - `OceanSurfaceSample` - Ocean surface sample whose displaced `(x, z)` aligns with `(world_x, world_z)`.
275    #[must_use]
276    pub fn sample_world_xz(&self, world_x: f32, world_z: f32) -> OceanSurfaceSample {
277        let safe_wx: f32 = ocean_sanitize_f32(world_x, 0.0);
278        let safe_wz: f32 = ocean_sanitize_f32(world_z, 0.0);
279        let mut guess_x: f32 = safe_wx;
280        let mut guess_z: f32 = safe_wz;
281        let mut sample: OceanSurfaceSample = self.sample_parametric(guess_x, guess_z);
282        for _iter in 0..OCEAN_INVERSE_ITERS {
283            let err_x: f32 = sample.get_displaced_position().get_x() - safe_wx;
284            let err_z: f32 = sample.get_displaced_position().get_z() - safe_wz;
285            guess_x -= err_x;
286            guess_z -= err_z;
287            sample = self.sample_parametric(guess_x, guess_z);
288        }
289        sample
290    }
291
292    /// Evaluates physical Beer-Lambert depth absorption, Schlick Fresnel (`F0 = 0.02`), backlit emerald SSS, and seabed caustics.
293    ///
294    /// # Arguments
295    ///
296    /// - `&OceanSurfaceSample` - Analytical surface geometry sample.
297    /// - `Vec3` - Unit view direction pointing from surface point toward camera.
298    /// - `Vec3` - Unit sun light direction pointing toward the sun.
299    /// - `f32` - Local water column depth from surface down to seabed in meters.
300    /// - `Vec3` - Linear RGB reflected sky radiance along the mirror reflection direction.
301    ///
302    /// # Returns
303    ///
304    /// - `OceanOpticalSample` - Physical water transmittance, Fresnel, SSS, caustics, and shaded linear color.
305    #[must_use]
306    pub fn evaluate_optics(
307        &self,
308        surface: &OceanSurfaceSample,
309        view_dir: Vec3,
310        sun_dir: Vec3,
311        water_depth_m: f32,
312        sky_reflection: Vec3,
313    ) -> OceanOpticalSample {
314        let optics: OceanOpticalConfig = self.get_config().get_optics();
315        let depth: f32 = ocean_sanitize_f32(water_depth_m, 10.0).max(0.0);
316        let absorb: Vec3 = optics.get_absorption_coeff();
317        let transmittance: Vec3 = Vec3::new(
318            (-absorb.get_x().max(0.0) * depth).exp().clamp(0.0, 1.0),
319            (-absorb.get_y().max(0.0) * depth).exp().clamp(0.0, 1.0),
320            (-absorb.get_z().max(0.0) * depth).exp().clamp(0.0, 1.0),
321        );
322        let normal: Vec3 = surface.get_normal().normalize();
323        let safe_view: Vec3 = view_dir.normalize();
324        let safe_sun: Vec3 = sun_dir.normalize();
325        let n_dot_v: f32 = normal.dot(safe_view).clamp(0.0, 1.0);
326        let f0: f32 = optics.get_fresnel_f0();
327        let fresnel: f32 = (f0 + (1.0 - f0) * (1.0 - n_dot_v).powi(5)).clamp(f0, 1.0);
328        let backlit_dir: Vec3 = safe_sun.add(normal.scale(0.35)).normalize();
329        let backlit_align: f32 = safe_view.dot(backlit_dir.scale(-1.0)).clamp(0.0, 1.0);
330        let crest_thinness: f32 =
331            (0.25 + surface.get_displacement().get_y().max(0.0) * 0.65).clamp(0.1, 1.6);
332        let sss_factor: f32 = optics.get_sss_strength()
333            * backlit_align.powi(3)
334            * crest_thinness
335            * safe_sun.get_y().max(0.05);
336        let subsurface_scatter: Vec3 = optics.get_sss_color().scale(sss_factor.max(0.0));
337        let pos: Vec3 = surface.get_displaced_position();
338        let seabed_pos: Vec3 = Vec3::new(pos.get_x(), pos.get_y() - depth, pos.get_z());
339        let caustics_intensity: f32 = evaluate_ocean_caustics(
340            self.get_waves(),
341            self.get_config().get_gravity_mps2(),
342            self.get_sim_time_secs(),
343            seabed_pos,
344            safe_sun,
345            depth,
346            optics.get_caustics_strength(),
347        );
348        let deep: Vec3 = optics.get_deep_scatter_color();
349        let shallow: Vec3 = optics.get_shallow_tint_color();
350        let refracted: Vec3 = Vec3::new(
351            deep.get_x() + (shallow.get_x() - deep.get_x()) * transmittance.get_x(),
352            deep.get_y() + (shallow.get_y() - deep.get_y()) * transmittance.get_y(),
353            deep.get_z() + (shallow.get_z() - deep.get_z()) * transmittance.get_z(),
354        )
355        .add(subsurface_scatter)
356        .add(Vec3::splat(caustics_intensity * 0.12).scale(transmittance.get_y()));
357        let base_water: Vec3 = refracted
358            .scale(1.0 - fresnel)
359            .add(sky_reflection.scale(fresnel));
360        let foam: f32 = surface.get_foam_mask().clamp(0.0, 1.0);
361        let water_color: Vec3 = base_water.lerp(optics.get_foam_color(), foam);
362        OceanOpticalSample::new(
363            transmittance,
364            fresnel,
365            subsurface_scatter,
366            caustics_intensity,
367            water_color,
368        )
369    }
370
371    /// Evaluates analytical seabed caustics projection intensity at an arbitrary seabed world point.
372    ///
373    /// # Arguments
374    ///
375    /// - `Vec3` - Seabed world position `(x, y, z)`.
376    /// - `Vec3` - Unit sun light direction pointing toward the sun.
377    ///
378    /// # Returns
379    ///
380    /// - `f32` - Non-negative seabed caustics projection intensity.
381    #[must_use]
382    pub fn sample_seabed_caustics(&self, seabed_pos: Vec3, sun_dir: Vec3) -> f32 {
383        let depth: f32 = (self.get_config().get_mean_water_level_y() - seabed_pos.get_y()).max(0.0);
384        evaluate_ocean_caustics(
385            self.get_waves(),
386            self.get_config().get_gravity_mps2(),
387            self.get_sim_time_secs(),
388            seabed_pos,
389            sun_dir,
390            depth,
391            self.get_config().get_optics().get_caustics_strength(),
392        )
393    }
394
395    /// Builds a projected-grid / LOD `Mesh3D` patch evaluated at the current ocean simulation time.
396    ///
397    /// # Arguments
398    ///
399    /// - `&OceanPatchDesc` - Patch center, extent, subdivision resolution, and radial LOD falloff.
400    /// - `&str` - Asset mesh name (falls back to `OCEAN_DEFAULT_PATCH_NAME` when empty).
401    /// - `PbrMaterial` - Surface PBR material assigned to the generated mesh.
402    ///
403    /// # Returns
404    ///
405    /// - `Mesh3D` - Indexed 3D ocean surface patch with analytical normals, tangents, UVs, and foam/depth vertex colors.
406    #[must_use]
407    pub fn build_patch_mesh(
408        &self,
409        desc: &OceanPatchDesc,
410        name: &str,
411        material: PbrMaterial,
412    ) -> Mesh3D {
413        let sub_x: usize = desc.get_subdivisions_x().clamp(2, 256);
414        let sub_z: usize = desc.get_subdivisions_z().clamp(2, 256);
415        let verts_x: usize = sub_x + 1;
416        let verts_z: usize = sub_z + 1;
417        let half_x: f32 = ocean_sanitize_f32(desc.get_extent_x(), 120.0).max(1.0) * 0.5;
418        let half_z: f32 = ocean_sanitize_f32(desc.get_extent_z(), 120.0).max(1.0) * 0.5;
419        let falloff: f32 = ocean_sanitize_f32(desc.get_lod_radial_falloff(), 0.0).clamp(0.0, 2.5);
420        let center: Vec2 = desc.get_center_xz();
421        let seabed_y: f32 = ocean_sanitize_f32(desc.get_seabed_y(), -14.0);
422        let mut vertices: Vec<Vertex3D> = Vec::with_capacity(verts_x * verts_z);
423        for iz in 0..verts_z {
424            let v_frac: f32 = iz as f32 / sub_z as f32;
425            let nz_lin: f32 = v_frac * 2.0 - 1.0;
426            let nz_lod: f32 = nz_lin.signum() * nz_lin.abs().powf(1.0 + falloff);
427            let coord_z: f32 = center.get_y() + nz_lod * half_z;
428            for ix in 0..verts_x {
429                let u_frac: f32 = ix as f32 / sub_x as f32;
430                let nx_lin: f32 = u_frac * 2.0 - 1.0;
431                let nx_lod: f32 = nx_lin.signum() * nx_lin.abs().powf(1.0 + falloff);
432                let coord_x: f32 = center.get_x() + nx_lod * half_x;
433                let sample: OceanSurfaceSample = self.sample_parametric(coord_x, coord_z);
434                let tan: Vec3 = sample.get_tangent_x().normalize();
435                let depth: f32 = (sample.get_displaced_position().get_y() - seabed_y).max(0.0);
436                let optical: OceanOpticalSample = self.evaluate_optics(
437                    &sample,
438                    Vec3::new(0.0, 0.72, 0.69),
439                    Vec3::new(0.4, 0.8, 0.44),
440                    depth,
441                    Vec3::new(0.35, 0.55, 0.85),
442                );
443                let col: Vec3 = optical.get_water_color();
444                let rgba: [u8; 4] = [
445                    (col.get_x().clamp(0.0, 1.0) * 255.0).round() as u8,
446                    (col.get_y().clamp(0.0, 1.0) * 255.0).round() as u8,
447                    (col.get_z().clamp(0.0, 1.0) * 255.0).round() as u8,
448                    255,
449                ];
450                let vertex: Vertex3D = Vertex3D::from_full(
451                    sample.get_displaced_position(),
452                    sample.get_normal(),
453                    [tan.get_x(), tan.get_y(), tan.get_z(), 1.0],
454                    [u_frac, v_frac],
455                    [sample.get_foam_mask(), sample.get_jacobian()],
456                    rgba,
457                    0b1111,
458                );
459                vertices.push(vertex);
460            }
461        }
462        let mut indices: Vec<[u32; 3]> = Vec::with_capacity(sub_x * sub_z * 2);
463        for iz in 0..sub_z {
464            for ix in 0..sub_x {
465                let i00: u32 = (iz * verts_x + ix) as u32;
466                let i10: u32 = i00 + 1;
467                let i01: u32 = ((iz + 1) * verts_x + ix) as u32;
468                let i11: u32 = i01 + 1;
469                indices.push([i00, i01, i10]);
470                indices.push([i10, i01, i11]);
471            }
472        }
473        let mesh_name: String = if name.is_empty() {
474            OCEAN_DEFAULT_PATCH_NAME.to_string()
475        } else {
476            name.to_string()
477        };
478        Mesh3D::from_parts(mesh_name, vertices, indices, material)
479    }
480}
481
482/// Default `BuoyantHullConfig` representing a 450 kg rigid inflatable boat hull.
483impl Default for BuoyantHullConfig {
484    /// Returns a balanced default rigid-body floating hull configuration.
485    ///
486    /// # Returns
487    ///
488    /// - `Self` - Default hull physical configuration.
489    fn default() -> Self {
490        Self {
491            mass_kg: 450.0,
492            inertia_diag: Vec3::new(320.0, 480.0, 190.0),
493            fluid_density_kgm3: OCEAN_SEAWATER_DENSITY_KGM3,
494            gravity_mps2: OCEAN_GRAVITY_MPS2,
495            linear_drag: 2600.0,
496            quadratic_drag: 900.0,
497            angular_drag: 650.0,
498            slope_alignment_torque: 240.0,
499            max_linear_speed: 35.0,
500            max_angular_speed: 6.0,
501        }
502    }
503}
504
505/// Sanitization helpers for `BuoyantHullConfig`.
506impl BuoyantHullConfig {
507    /// Returns a validated finite copy of this hull configuration.
508    ///
509    /// # Returns
510    ///
511    /// - `Self` - Sanitized hull configuration.
512    #[must_use]
513    pub fn sanitized(self) -> Self {
514        let inertia: Vec3 = self.get_inertia_diag();
515        Self {
516            mass_kg: ocean_sanitize_f32(self.get_mass_kg(), 450.0).clamp(0.1, 1_000_000.0),
517            inertia_diag: Vec3::new(
518                ocean_sanitize_f32(inertia.get_x(), 320.0).max(0.1),
519                ocean_sanitize_f32(inertia.get_y(), 480.0).max(0.1),
520                ocean_sanitize_f32(inertia.get_z(), 190.0).max(0.1),
521            ),
522            fluid_density_kgm3: ocean_sanitize_f32(
523                self.get_fluid_density_kgm3(),
524                OCEAN_SEAWATER_DENSITY_KGM3,
525            )
526            .clamp(100.0, 5000.0),
527            gravity_mps2: ocean_sanitize_f32(self.get_gravity_mps2(), OCEAN_GRAVITY_MPS2)
528                .clamp(0.5, 30.0),
529            linear_drag: ocean_sanitize_f32(self.get_linear_drag(), 480.0).clamp(0.0, 500_000.0),
530            quadratic_drag: ocean_sanitize_f32(self.get_quadratic_drag(), 160.0)
531                .clamp(0.0, 500_000.0),
532            angular_drag: ocean_sanitize_f32(self.get_angular_drag(), 260.0).clamp(0.0, 500_000.0),
533            slope_alignment_torque: ocean_sanitize_f32(self.get_slope_alignment_torque(), 180.0)
534                .clamp(0.0, 500_000.0),
535            max_linear_speed: ocean_sanitize_f32(self.get_max_linear_speed(), 35.0)
536                .clamp(1.0, 200.0),
537            max_angular_speed: ocean_sanitize_f32(self.get_max_angular_speed(), 6.0)
538                .clamp(0.2, 40.0),
539        }
540    }
541}
542
543/// Default floating box-boat `BuoyantHull3D`.
544impl Default for BuoyantHull3D {
545    /// Creates a default 4-meter floating hull positioned at the origin.
546    ///
547    /// # Returns
548    ///
549    /// - `Self` - Ready buoyant hull simulator.
550    fn default() -> Self {
551        Self::box_hull(
552            Vec3::zero(),
553            Vec3::new(1.8, 0.7, 3.8),
554            BuoyantHullConfig::default(),
555        )
556    }
557}
558
559/// Archimedes buoyancy, hydrodynamic drag, and coupled stepping API for `BuoyantHull3D`.
560impl BuoyantHull3D {
561    /// Constructs a `BuoyantHull3D` with custom hydrodynamic config and distributed pontoon probes.
562    ///
563    /// # Arguments
564    ///
565    /// - `Vec3` - Initial world-space center of mass position.
566    /// - `BuoyantHullConfig` - Hull mass, inertia, and drag parameters.
567    /// - `Vec<PontoonSamplePoint>` - Local-space buoyancy sample points.
568    ///
569    /// # Returns
570    ///
571    /// - `Self` - Initialized floating rigid body.
572    #[must_use]
573    pub fn from_config_and_pontoons(
574        position: Vec3,
575        config: BuoyantHullConfig,
576        pontoons: Vec<PontoonSamplePoint>,
577    ) -> Self {
578        let clean: BuoyantHullConfig = config.sanitized();
579        let active_pontoons: Vec<PontoonSamplePoint> = if pontoons.is_empty() {
580            let vol: f32 = 2.0 * clean.get_mass_kg() / clean.get_fluid_density_kgm3();
581            vec![PontoonSamplePoint::new(Vec3::zero(), vol, 0.35)]
582        } else {
583            pontoons
584        };
585        Self {
586            config: clean,
587            position,
588            velocity: Vec3::zero(),
589            orientation: Quat::identity(),
590            angular_velocity: Vec3::zero(),
591            pontoons: active_pontoons,
592            submerged_fraction: 0.0,
593            buoyancy_force: Vec3::zero(),
594        }
595    }
596
597    /// Creates a symmetric 8-point rectangular boat/crate hull whose buoyancy volume supports floatation equilibrium.
598    ///
599    /// # Arguments
600    ///
601    /// - `Vec3` - Initial world-space center of mass position.
602    /// - `Vec3` - Hull dimensions `(beam_x, height_y, length_z)` in meters.
603    /// - `BuoyantHullConfig` - Hull physical configuration.
604    ///
605    /// # Returns
606    ///
607    /// - `Self` - Symmetric 8-pontoon floating hull.
608    #[must_use]
609    pub fn box_hull(position: Vec3, extents: Vec3, config: BuoyantHullConfig) -> Self {
610        let clean: BuoyantHullConfig = config.sanitized();
611        let hx: f32 = ocean_sanitize_f32(extents.get_x(), 1.8).max(0.2) * 0.42;
612        let hy: f32 = ocean_sanitize_f32(extents.get_y(), 0.7).max(0.15) * 0.35;
613        let hz: f32 = ocean_sanitize_f32(extents.get_z(), 3.8).max(0.2) * 0.44;
614        let min_float_vol: f32 = 2.1 * clean.get_mass_kg() / clean.get_fluid_density_kgm3();
615        let hull_block_coeff: f32 = 0.55;
616        let box_vol: f32 = (hull_block_coeff
617            * extents.get_x().abs()
618            * extents.get_y().abs()
619            * extents.get_z().abs())
620        .max(min_float_vol);
621        let per_point_vol: f32 = box_vol / 8.0;
622        let sample_radius: f32 = (extents.get_y().abs() * 0.45).max(0.12);
623        let offsets: [Vec3; 8] = [
624            Vec3::new(-hx, -hy, -hz),
625            Vec3::new(hx, -hy, -hz),
626            Vec3::new(-hx, -hy, 0.0),
627            Vec3::new(hx, -hy, 0.0),
628            Vec3::new(-hx, -hy, hz),
629            Vec3::new(hx, -hy, hz),
630            Vec3::new(0.0, -hy * 0.7, -hz * 0.65),
631            Vec3::new(0.0, -hy * 0.7, hz * 0.65),
632        ];
633        let mut pontoons: Vec<PontoonSamplePoint> = Vec::with_capacity(8);
634        for offset in offsets {
635            pontoons.push(PontoonSamplePoint::new(
636                offset,
637                per_point_vol,
638                sample_radius,
639            ));
640        }
641        Self::from_config_and_pontoons(position, clean, pontoons)
642    }
643
644    /// Advances rigid-body buoyancy and hydrodynamic drag coupled to a live `OceanSurface3D`.
645    ///
646    /// # Arguments
647    ///
648    /// - `&OceanSurface3D` - Live ocean surface queried at each world-space pontoon point.
649    /// - `f32` - Integration step duration in seconds.
650    pub fn step_on_ocean(&mut self, ocean: &OceanSurface3D, dt_secs: f32) {
651        let clamped_dt: f32 = ocean_sanitize_f32(dt_secs, 0.0).clamp(0.0, BUOYANT_HULL_MAX_DT_SECS);
652        if clamped_dt <= 1e-6 {
653            return;
654        }
655        let pos: Vec3 = self.get_position();
656        let orient: Quat = self.get_orientation().normalize();
657        let mut samples: [(f32, Vec3); 16] = [(0.0, Vec3::new(0.0, 1.0, 0.0)); 16];
658        let count: usize = self.get_pontoons().len().min(16);
659        for (idx, pontoon) in self.get_pontoons().iter().take(count).enumerate() {
660            let world_pt: Vec3 = pos.add(orient.rotate_vec3(pontoon.get_local_offset()));
661            let surf: OceanSurfaceSample =
662                ocean.sample_world_xz(world_pt.get_x(), world_pt.get_z());
663            samples[idx] = (surf.get_displaced_position().get_y(), surf.get_normal());
664        }
665        integrate_buoyant_hull_step(self, &samples[..count], clamped_dt);
666    }
667
668    /// Advances rigid-body buoyancy and hydrodynamic drag coupled to an interactive `WaveHeightfield2D`.
669    ///
670    /// # Arguments
671    ///
672    /// - `&WaveHeightfield2D` - Live shallow-water heightfield queried at each pontoon point.
673    /// - `f32` - Integration step duration in seconds.
674    pub fn step_on_heightfield(&mut self, field: &WaveHeightfield2D, dt_secs: f32) {
675        let clamped_dt: f32 = ocean_sanitize_f32(dt_secs, 0.0).clamp(0.0, BUOYANT_HULL_MAX_DT_SECS);
676        if clamped_dt <= 1e-6 {
677            return;
678        }
679        let pos: Vec3 = self.get_position();
680        let orient: Quat = self.get_orientation().normalize();
681        let mut samples: [(f32, Vec3); 16] = [(0.0, Vec3::new(0.0, 1.0, 0.0)); 16];
682        let count: usize = self.get_pontoons().len().min(16);
683        for (idx, pontoon) in self.get_pontoons().iter().take(count).enumerate() {
684            let world_pt: Vec3 = pos.add(orient.rotate_vec3(pontoon.get_local_offset()));
685            samples[idx] = field.sample_height_and_normal(world_pt.get_x(), world_pt.get_z());
686        }
687        integrate_buoyant_hull_step(self, &samples[..count], clamped_dt);
688    }
689
690    /// Advances rigid-body buoyancy on a flat horizontal water plane at elevation `water_y`.
691    ///
692    /// # Arguments
693    ///
694    /// - `f32` - World-space elevation of the calm water plane.
695    /// - `f32` - Integration step duration in seconds.
696    pub fn step_on_plane(&mut self, water_y: f32, dt_secs: f32) {
697        let clamped_dt: f32 = ocean_sanitize_f32(dt_secs, 0.0).clamp(0.0, BUOYANT_HULL_MAX_DT_SECS);
698        if clamped_dt <= 1e-6 {
699            return;
700        }
701        let safe_y: f32 = ocean_sanitize_f32(water_y, 0.0);
702        let count: usize = self.get_pontoons().len().min(16);
703        let samples: [(f32, Vec3); 16] = [(safe_y, Vec3::new(0.0, 1.0, 0.0)); 16];
704        integrate_buoyant_hull_step(self, &samples[..count], clamped_dt);
705    }
706}