use super::*;
impl Default for OceanOpticalConfig {
fn default() -> Self {
Self::from_preset(OceanPreset::CoastalSwell)
}
}
impl OceanOpticalConfig {
#[must_use]
pub fn from_preset(preset: OceanPreset) -> Self {
match preset {
OceanPreset::CalmLagoon => Self {
absorption_coeff: Vec3::new(0.32, 0.08, 0.05),
deep_scatter_color: Vec3::new(0.02, 0.16, 0.24),
shallow_tint_color: Vec3::new(0.08, 0.56, 0.58),
sss_color: Vec3::new(0.06, 0.62, 0.52),
foam_color: Vec3::new(0.95, 0.97, 0.99),
fresnel_f0: OCEAN_FRESNEL_F0,
sss_strength: 0.72,
caustics_strength: 1.35,
foam_jacobian_threshold: 0.72,
},
OceanPreset::CoastalSwell => Self {
absorption_coeff: Vec3::from_array(OCEAN_DEFAULT_ABSORPTION_RGB),
deep_scatter_color: Vec3::new(0.015, 0.09, 0.17),
shallow_tint_color: Vec3::new(0.05, 0.38, 0.42),
sss_color: Vec3::new(0.04, 0.48, 0.40),
foam_color: Vec3::new(0.92, 0.95, 0.98),
fresnel_f0: OCEAN_FRESNEL_F0,
sss_strength: 0.85,
caustics_strength: 1.0,
foam_jacobian_threshold: 0.78,
},
OceanPreset::OpenOcean => Self {
absorption_coeff: Vec3::new(0.48, 0.18, 0.07),
deep_scatter_color: Vec3::new(0.008, 0.045, 0.12),
shallow_tint_color: Vec3::new(0.02, 0.18, 0.30),
sss_color: Vec3::new(0.03, 0.36, 0.34),
foam_color: Vec3::new(0.90, 0.94, 0.97),
fresnel_f0: OCEAN_FRESNEL_F0,
sss_strength: 0.68,
caustics_strength: 0.65,
foam_jacobian_threshold: 0.80,
},
OceanPreset::StormyGale => Self {
absorption_coeff: Vec3::new(0.55, 0.28, 0.16),
deep_scatter_color: Vec3::new(0.012, 0.035, 0.065),
shallow_tint_color: Vec3::new(0.04, 0.12, 0.16),
sss_color: Vec3::new(0.05, 0.28, 0.26),
foam_color: Vec3::new(0.86, 0.90, 0.93),
fresnel_f0: OCEAN_FRESNEL_F0,
sss_strength: 0.55,
caustics_strength: 0.35,
foam_jacobian_threshold: 0.88,
},
}
}
}
impl Default for OceanConfig {
fn default() -> Self {
Self::from_preset(OceanPreset::CoastalSwell)
}
}
impl OceanConfig {
#[must_use]
pub fn from_preset(preset: OceanPreset) -> Self {
let (wind_speed, fetch_km, choppiness): (f32, f32, f32) = match preset {
OceanPreset::CalmLagoon => (4.5, 12.0, 0.42),
OceanPreset::CoastalSwell => (10.5, 65.0, 0.72),
OceanPreset::OpenOcean => (15.0, 220.0, 0.88),
OceanPreset::StormyGale => (24.0, 480.0, 1.15),
};
Self {
preset,
wind_speed_mps: wind_speed,
wind_direction: Vec2::new(0.86, 0.51),
fetch_km,
choppiness,
mean_water_level_y: 0.0,
gravity_mps2: OCEAN_GRAVITY_MPS2,
cascade_count: OCEAN_DEFAULT_CASCADES,
seed: OCEAN_DEFAULT_SEED,
optics: OceanOpticalConfig::from_preset(preset),
}
}
#[must_use]
pub fn sanitized(self) -> Self {
let dir: Vec2 = self.get_wind_direction();
let dx: f32 = ocean_sanitize_f32(dir.get_x(), 1.0);
let dz: f32 = ocean_sanitize_f32(dir.get_y(), 0.0);
let len: f32 = (dx * dx + dz * dz).sqrt();
let norm_dir: Vec2 = if len > 1e-5 {
Vec2::new(dx / len, dz / len)
} else {
Vec2::new(1.0, 0.0)
};
let mut optics: OceanOpticalConfig = self.get_optics();
optics.set_fresnel_f0(
ocean_sanitize_f32(optics.get_fresnel_f0(), OCEAN_FRESNEL_F0).clamp(0.005, 0.25),
);
optics.set_sss_strength(ocean_sanitize_f32(optics.get_sss_strength(), 0.7).clamp(0.0, 3.0));
optics.set_caustics_strength(
ocean_sanitize_f32(optics.get_caustics_strength(), 1.0).clamp(0.0, 4.0),
);
optics.set_foam_jacobian_threshold(
ocean_sanitize_f32(optics.get_foam_jacobian_threshold(), 0.78).clamp(0.15, 1.15),
);
Self {
preset: self.get_preset(),
wind_speed_mps: ocean_sanitize_f32(self.get_wind_speed_mps(), 10.0).clamp(0.5, 45.0),
wind_direction: norm_dir,
fetch_km: ocean_sanitize_f32(self.get_fetch_km(), 60.0).clamp(1.0, 2000.0),
choppiness: ocean_sanitize_f32(self.get_choppiness(), 0.75).clamp(0.0, 1.5),
mean_water_level_y: ocean_sanitize_f32(self.get_mean_water_level_y(), 0.0),
gravity_mps2: ocean_sanitize_f32(self.get_gravity_mps2(), OCEAN_GRAVITY_MPS2)
.clamp(1.0, 30.0),
cascade_count: self.get_cascade_count().clamp(1, 4),
seed: self.get_seed().max(1),
optics,
}
}
}
impl Default for OceanPatchDesc {
fn default() -> Self {
Self {
center_xz: Vec2::zero(),
extent_x: 120.0,
extent_z: 120.0,
subdivisions_x: 48,
subdivisions_z: 48,
lod_radial_falloff: 0.45,
seabed_y: -14.0,
}
}
}
impl Default for OceanSurface3D {
fn default() -> Self {
Self::from_preset(OceanPreset::CoastalSwell)
}
}
impl OceanSurface3D {
#[must_use]
pub fn from_preset(preset: OceanPreset) -> Self {
Self::from_config(OceanConfig::from_preset(preset))
}
#[must_use]
pub fn from_config(config: OceanConfig) -> Self {
let clean: OceanConfig = config.sanitized();
let waves: Vec<GerstnerWaveComponent> = synthesize_jonswap_gerstner_waves(clean);
Self {
config: clean,
waves,
sim_time_secs: 0.0,
}
}
pub fn step(&mut self, dt_secs: f32) {
let safe_dt: f32 = ocean_sanitize_f32(dt_secs, 0.0).clamp(0.0, 1.0);
let next_t: f32 = self.get_sim_time_secs() + safe_dt;
self.set_sim_time_secs(next_t);
}
#[must_use]
pub fn sample_parametric(&self, coord_x: f32, coord_z: f32) -> OceanSurfaceSample {
evaluate_gerstner_sample(
self.get_waves(),
self.get_config(),
self.get_sim_time_secs(),
coord_x,
coord_z,
)
}
#[must_use]
pub fn sample_world_xz(&self, world_x: f32, world_z: f32) -> OceanSurfaceSample {
let safe_wx: f32 = ocean_sanitize_f32(world_x, 0.0);
let safe_wz: f32 = ocean_sanitize_f32(world_z, 0.0);
let mut guess_x: f32 = safe_wx;
let mut guess_z: f32 = safe_wz;
let mut sample: OceanSurfaceSample = self.sample_parametric(guess_x, guess_z);
for _iter in 0..OCEAN_INVERSE_ITERS {
let err_x: f32 = sample.get_displaced_position().get_x() - safe_wx;
let err_z: f32 = sample.get_displaced_position().get_z() - safe_wz;
guess_x -= err_x;
guess_z -= err_z;
sample = self.sample_parametric(guess_x, guess_z);
}
sample
}
#[must_use]
pub fn evaluate_optics(
&self,
surface: &OceanSurfaceSample,
view_dir: Vec3,
sun_dir: Vec3,
water_depth_m: f32,
sky_reflection: Vec3,
) -> OceanOpticalSample {
let optics: OceanOpticalConfig = self.get_config().get_optics();
let depth: f32 = ocean_sanitize_f32(water_depth_m, 10.0).max(0.0);
let absorb: Vec3 = optics.get_absorption_coeff();
let transmittance: Vec3 = Vec3::new(
(-absorb.get_x().max(0.0) * depth).exp().clamp(0.0, 1.0),
(-absorb.get_y().max(0.0) * depth).exp().clamp(0.0, 1.0),
(-absorb.get_z().max(0.0) * depth).exp().clamp(0.0, 1.0),
);
let normal: Vec3 = surface.get_normal().normalize();
let safe_view: Vec3 = view_dir.normalize();
let safe_sun: Vec3 = sun_dir.normalize();
let n_dot_v: f32 = normal.dot(safe_view).clamp(0.0, 1.0);
let f0: f32 = optics.get_fresnel_f0();
let fresnel: f32 = (f0 + (1.0 - f0) * (1.0 - n_dot_v).powi(5)).clamp(f0, 1.0);
let backlit_dir: Vec3 = safe_sun.add(normal.scale(0.35)).normalize();
let backlit_align: f32 = safe_view.dot(backlit_dir.scale(-1.0)).clamp(0.0, 1.0);
let crest_thinness: f32 =
(0.25 + surface.get_displacement().get_y().max(0.0) * 0.65).clamp(0.1, 1.6);
let sss_factor: f32 = optics.get_sss_strength()
* backlit_align.powi(3)
* crest_thinness
* safe_sun.get_y().max(0.05);
let subsurface_scatter: Vec3 = optics.get_sss_color().scale(sss_factor.max(0.0));
let pos: Vec3 = surface.get_displaced_position();
let seabed_pos: Vec3 = Vec3::new(pos.get_x(), pos.get_y() - depth, pos.get_z());
let caustics_intensity: f32 = evaluate_ocean_caustics(
self.get_waves(),
self.get_config().get_gravity_mps2(),
self.get_sim_time_secs(),
seabed_pos,
safe_sun,
depth,
optics.get_caustics_strength(),
);
let deep: Vec3 = optics.get_deep_scatter_color();
let shallow: Vec3 = optics.get_shallow_tint_color();
let refracted: Vec3 = Vec3::new(
deep.get_x() + (shallow.get_x() - deep.get_x()) * transmittance.get_x(),
deep.get_y() + (shallow.get_y() - deep.get_y()) * transmittance.get_y(),
deep.get_z() + (shallow.get_z() - deep.get_z()) * transmittance.get_z(),
)
.add(subsurface_scatter)
.add(Vec3::splat(caustics_intensity * 0.12).scale(transmittance.get_y()));
let base_water: Vec3 = refracted
.scale(1.0 - fresnel)
.add(sky_reflection.scale(fresnel));
let foam: f32 = surface.get_foam_mask().clamp(0.0, 1.0);
let water_color: Vec3 = base_water.lerp(optics.get_foam_color(), foam);
OceanOpticalSample::new(
transmittance,
fresnel,
subsurface_scatter,
caustics_intensity,
water_color,
)
}
#[must_use]
pub fn sample_seabed_caustics(&self, seabed_pos: Vec3, sun_dir: Vec3) -> f32 {
let depth: f32 = (self.get_config().get_mean_water_level_y() - seabed_pos.get_y()).max(0.0);
evaluate_ocean_caustics(
self.get_waves(),
self.get_config().get_gravity_mps2(),
self.get_sim_time_secs(),
seabed_pos,
sun_dir,
depth,
self.get_config().get_optics().get_caustics_strength(),
)
}
#[must_use]
pub fn build_patch_mesh(
&self,
desc: &OceanPatchDesc,
name: &str,
material: PbrMaterial,
) -> Mesh3D {
let sub_x: usize = desc.get_subdivisions_x().clamp(2, 256);
let sub_z: usize = desc.get_subdivisions_z().clamp(2, 256);
let verts_x: usize = sub_x + 1;
let verts_z: usize = sub_z + 1;
let half_x: f32 = ocean_sanitize_f32(desc.get_extent_x(), 120.0).max(1.0) * 0.5;
let half_z: f32 = ocean_sanitize_f32(desc.get_extent_z(), 120.0).max(1.0) * 0.5;
let falloff: f32 = ocean_sanitize_f32(desc.get_lod_radial_falloff(), 0.0).clamp(0.0, 2.5);
let center: Vec2 = desc.get_center_xz();
let seabed_y: f32 = ocean_sanitize_f32(desc.get_seabed_y(), -14.0);
let mut vertices: Vec<Vertex3D> = Vec::with_capacity(verts_x * verts_z);
for iz in 0..verts_z {
let v_frac: f32 = iz as f32 / sub_z as f32;
let nz_lin: f32 = v_frac * 2.0 - 1.0;
let nz_lod: f32 = nz_lin.signum() * nz_lin.abs().powf(1.0 + falloff);
let coord_z: f32 = center.get_y() + nz_lod * half_z;
for ix in 0..verts_x {
let u_frac: f32 = ix as f32 / sub_x as f32;
let nx_lin: f32 = u_frac * 2.0 - 1.0;
let nx_lod: f32 = nx_lin.signum() * nx_lin.abs().powf(1.0 + falloff);
let coord_x: f32 = center.get_x() + nx_lod * half_x;
let sample: OceanSurfaceSample = self.sample_parametric(coord_x, coord_z);
let tan: Vec3 = sample.get_tangent_x().normalize();
let depth: f32 = (sample.get_displaced_position().get_y() - seabed_y).max(0.0);
let optical: OceanOpticalSample = self.evaluate_optics(
&sample,
Vec3::new(0.0, 0.72, 0.69),
Vec3::new(0.4, 0.8, 0.44),
depth,
Vec3::new(0.35, 0.55, 0.85),
);
let col: Vec3 = optical.get_water_color();
let rgba: [u8; 4] = [
(col.get_x().clamp(0.0, 1.0) * 255.0).round() as u8,
(col.get_y().clamp(0.0, 1.0) * 255.0).round() as u8,
(col.get_z().clamp(0.0, 1.0) * 255.0).round() as u8,
255,
];
let vertex: Vertex3D = Vertex3D::from_full(
sample.get_displaced_position(),
sample.get_normal(),
[tan.get_x(), tan.get_y(), tan.get_z(), 1.0],
[u_frac, v_frac],
[sample.get_foam_mask(), sample.get_jacobian()],
rgba,
0b1111,
);
vertices.push(vertex);
}
}
let mut indices: Vec<[u32; 3]> = Vec::with_capacity(sub_x * sub_z * 2);
for iz in 0..sub_z {
for ix in 0..sub_x {
let i00: u32 = (iz * verts_x + ix) as u32;
let i10: u32 = i00 + 1;
let i01: u32 = ((iz + 1) * verts_x + ix) as u32;
let i11: u32 = i01 + 1;
indices.push([i00, i01, i10]);
indices.push([i10, i01, i11]);
}
}
let mesh_name: String = if name.is_empty() {
OCEAN_DEFAULT_PATCH_NAME.to_string()
} else {
name.to_string()
};
Mesh3D::from_parts(mesh_name, vertices, indices, material)
}
}
impl Default for BuoyantHullConfig {
fn default() -> Self {
Self {
mass_kg: 450.0,
inertia_diag: Vec3::new(320.0, 480.0, 190.0),
fluid_density_kgm3: OCEAN_SEAWATER_DENSITY_KGM3,
gravity_mps2: OCEAN_GRAVITY_MPS2,
linear_drag: 2600.0,
quadratic_drag: 900.0,
angular_drag: 650.0,
slope_alignment_torque: 240.0,
max_linear_speed: 35.0,
max_angular_speed: 6.0,
}
}
}
impl BuoyantHullConfig {
#[must_use]
pub fn sanitized(self) -> Self {
let inertia: Vec3 = self.get_inertia_diag();
Self {
mass_kg: ocean_sanitize_f32(self.get_mass_kg(), 450.0).clamp(0.1, 1_000_000.0),
inertia_diag: Vec3::new(
ocean_sanitize_f32(inertia.get_x(), 320.0).max(0.1),
ocean_sanitize_f32(inertia.get_y(), 480.0).max(0.1),
ocean_sanitize_f32(inertia.get_z(), 190.0).max(0.1),
),
fluid_density_kgm3: ocean_sanitize_f32(
self.get_fluid_density_kgm3(),
OCEAN_SEAWATER_DENSITY_KGM3,
)
.clamp(100.0, 5000.0),
gravity_mps2: ocean_sanitize_f32(self.get_gravity_mps2(), OCEAN_GRAVITY_MPS2)
.clamp(0.5, 30.0),
linear_drag: ocean_sanitize_f32(self.get_linear_drag(), 480.0).clamp(0.0, 500_000.0),
quadratic_drag: ocean_sanitize_f32(self.get_quadratic_drag(), 160.0)
.clamp(0.0, 500_000.0),
angular_drag: ocean_sanitize_f32(self.get_angular_drag(), 260.0).clamp(0.0, 500_000.0),
slope_alignment_torque: ocean_sanitize_f32(self.get_slope_alignment_torque(), 180.0)
.clamp(0.0, 500_000.0),
max_linear_speed: ocean_sanitize_f32(self.get_max_linear_speed(), 35.0)
.clamp(1.0, 200.0),
max_angular_speed: ocean_sanitize_f32(self.get_max_angular_speed(), 6.0)
.clamp(0.2, 40.0),
}
}
}
impl Default for BuoyantHull3D {
fn default() -> Self {
Self::box_hull(
Vec3::zero(),
Vec3::new(1.8, 0.7, 3.8),
BuoyantHullConfig::default(),
)
}
}
impl BuoyantHull3D {
#[must_use]
pub fn from_config_and_pontoons(
position: Vec3,
config: BuoyantHullConfig,
pontoons: Vec<PontoonSamplePoint>,
) -> Self {
let clean: BuoyantHullConfig = config.sanitized();
let active_pontoons: Vec<PontoonSamplePoint> = if pontoons.is_empty() {
let vol: f32 = 2.0 * clean.get_mass_kg() / clean.get_fluid_density_kgm3();
vec![PontoonSamplePoint::new(Vec3::zero(), vol, 0.35)]
} else {
pontoons
};
Self {
config: clean,
position,
velocity: Vec3::zero(),
orientation: Quat::identity(),
angular_velocity: Vec3::zero(),
pontoons: active_pontoons,
submerged_fraction: 0.0,
buoyancy_force: Vec3::zero(),
}
}
#[must_use]
pub fn box_hull(position: Vec3, extents: Vec3, config: BuoyantHullConfig) -> Self {
let clean: BuoyantHullConfig = config.sanitized();
let hx: f32 = ocean_sanitize_f32(extents.get_x(), 1.8).max(0.2) * 0.42;
let hy: f32 = ocean_sanitize_f32(extents.get_y(), 0.7).max(0.15) * 0.35;
let hz: f32 = ocean_sanitize_f32(extents.get_z(), 3.8).max(0.2) * 0.44;
let min_float_vol: f32 = 2.1 * clean.get_mass_kg() / clean.get_fluid_density_kgm3();
let hull_block_coeff: f32 = 0.55;
let box_vol: f32 = (hull_block_coeff
* extents.get_x().abs()
* extents.get_y().abs()
* extents.get_z().abs())
.max(min_float_vol);
let per_point_vol: f32 = box_vol / 8.0;
let sample_radius: f32 = (extents.get_y().abs() * 0.45).max(0.12);
let offsets: [Vec3; 8] = [
Vec3::new(-hx, -hy, -hz),
Vec3::new(hx, -hy, -hz),
Vec3::new(-hx, -hy, 0.0),
Vec3::new(hx, -hy, 0.0),
Vec3::new(-hx, -hy, hz),
Vec3::new(hx, -hy, hz),
Vec3::new(0.0, -hy * 0.7, -hz * 0.65),
Vec3::new(0.0, -hy * 0.7, hz * 0.65),
];
let mut pontoons: Vec<PontoonSamplePoint> = Vec::with_capacity(8);
for offset in offsets {
pontoons.push(PontoonSamplePoint::new(
offset,
per_point_vol,
sample_radius,
));
}
Self::from_config_and_pontoons(position, clean, pontoons)
}
pub fn step_on_ocean(&mut self, ocean: &OceanSurface3D, dt_secs: f32) {
let clamped_dt: f32 = ocean_sanitize_f32(dt_secs, 0.0).clamp(0.0, BUOYANT_HULL_MAX_DT_SECS);
if clamped_dt <= 1e-6 {
return;
}
let pos: Vec3 = self.get_position();
let orient: Quat = self.get_orientation().normalize();
let mut samples: [(f32, Vec3); 16] = [(0.0, Vec3::new(0.0, 1.0, 0.0)); 16];
let count: usize = self.get_pontoons().len().min(16);
for (idx, pontoon) in self.get_pontoons().iter().take(count).enumerate() {
let world_pt: Vec3 = pos.add(orient.rotate_vec3(pontoon.get_local_offset()));
let surf: OceanSurfaceSample =
ocean.sample_world_xz(world_pt.get_x(), world_pt.get_z());
samples[idx] = (surf.get_displaced_position().get_y(), surf.get_normal());
}
integrate_buoyant_hull_step(self, &samples[..count], clamped_dt);
}
pub fn step_on_heightfield(&mut self, field: &WaveHeightfield2D, dt_secs: f32) {
let clamped_dt: f32 = ocean_sanitize_f32(dt_secs, 0.0).clamp(0.0, BUOYANT_HULL_MAX_DT_SECS);
if clamped_dt <= 1e-6 {
return;
}
let pos: Vec3 = self.get_position();
let orient: Quat = self.get_orientation().normalize();
let mut samples: [(f32, Vec3); 16] = [(0.0, Vec3::new(0.0, 1.0, 0.0)); 16];
let count: usize = self.get_pontoons().len().min(16);
for (idx, pontoon) in self.get_pontoons().iter().take(count).enumerate() {
let world_pt: Vec3 = pos.add(orient.rotate_vec3(pontoon.get_local_offset()));
samples[idx] = field.sample_height_and_normal(world_pt.get_x(), world_pt.get_z());
}
integrate_buoyant_hull_step(self, &samples[..count], clamped_dt);
}
pub fn step_on_plane(&mut self, water_y: f32, dt_secs: f32) {
let clamped_dt: f32 = ocean_sanitize_f32(dt_secs, 0.0).clamp(0.0, BUOYANT_HULL_MAX_DT_SECS);
if clamped_dt <= 1e-6 {
return;
}
let safe_y: f32 = ocean_sanitize_f32(water_y, 0.0);
let count: usize = self.get_pontoons().len().min(16);
let samples: [(f32, Vec3); 16] = [(safe_y, Vec3::new(0.0, 1.0, 0.0)); 16];
integrate_buoyant_hull_step(self, &samples[..count], clamped_dt);
}
}