1use super::*;
2
3impl Default for WaveHeightfieldConfig {
5 fn default() -> Self {
11 Self {
12 width: 64,
13 height: 64,
14 cell_size_m: WAKE_DEFAULT_CELL_SIZE_M,
15 wave_speed_mps: WAKE_DEFAULT_WAVE_SPEED_MPS,
16 damping: WAKE_DEFAULT_DAMPING,
17 sponge_width: WAKE_DEFAULT_SPONGE_WIDTH,
18 sponge_strength: WAKE_DEFAULT_SPONGE_STRENGTH,
19 foam_decay_rate: WAKE_DEFAULT_FOAM_DECAY,
20 origin_xz: Vec2::new(-8.0, -8.0),
21 base_water_y: 0.0,
22 }
23 }
24}
25
26impl WaveHeightfieldConfig {
28 #[must_use]
40 pub fn with_grid(width: usize, height: usize, cell_size_m: f32) -> Self {
41 let clamped_w: usize = width.clamp(WAKE_MIN_GRID_DIM, WAKE_MAX_GRID_DIM);
42 let clamped_h: usize = height.clamp(WAKE_MIN_GRID_DIM, WAKE_MAX_GRID_DIM);
43 let safe_dx: f32 = wake_sanitize_f32(cell_size_m, WAKE_DEFAULT_CELL_SIZE_M).max(0.02);
44 let half_x: f32 = 0.5 * (clamped_w.saturating_sub(1) as f32) * safe_dx;
45 let half_z: f32 = 0.5 * (clamped_h.saturating_sub(1) as f32) * safe_dx;
46 Self {
47 width: clamped_w,
48 height: clamped_h,
49 cell_size_m: safe_dx,
50 origin_xz: Vec2::new(-half_x, -half_z),
51 ..Self::default()
52 }
53 }
54
55 #[must_use]
61 pub fn sanitized(self) -> Self {
62 let width: usize = self.get_width().clamp(WAKE_MIN_GRID_DIM, WAKE_MAX_GRID_DIM);
63 let height: usize = self
64 .get_height()
65 .clamp(WAKE_MIN_GRID_DIM, WAKE_MAX_GRID_DIM);
66 let max_sponge: usize = width.min(height) / 3;
67 Self {
68 width,
69 height,
70 cell_size_m: wake_sanitize_f32(self.get_cell_size_m(), WAKE_DEFAULT_CELL_SIZE_M)
71 .max(0.02),
72 wave_speed_mps: wake_sanitize_f32(
73 self.get_wave_speed_mps(),
74 WAKE_DEFAULT_WAVE_SPEED_MPS,
75 )
76 .clamp(0.1, 40.0),
77 damping: wake_sanitize_f32(self.get_damping(), WAKE_DEFAULT_DAMPING).clamp(0.0, 20.0),
78 sponge_width: self.get_sponge_width().min(max_sponge),
79 sponge_strength: wake_sanitize_f32(
80 self.get_sponge_strength(),
81 WAKE_DEFAULT_SPONGE_STRENGTH,
82 )
83 .clamp(0.0, 40.0),
84 foam_decay_rate: wake_sanitize_f32(self.get_foam_decay_rate(), WAKE_DEFAULT_FOAM_DECAY)
85 .clamp(0.01, 20.0),
86 origin_xz: Vec2::new(
87 wake_sanitize_f32(self.get_origin_xz().get_x(), 0.0),
88 wake_sanitize_f32(self.get_origin_xz().get_y(), 0.0),
89 ),
90 base_water_y: wake_sanitize_f32(self.get_base_water_y(), 0.0),
91 }
92 }
93}
94
95impl Default for WaveHeightfield2D {
97 fn default() -> Self {
103 Self::from_config(WaveHeightfieldConfig::default())
104 }
105}
106
107impl WaveHeightfield2D {
109 #[must_use]
119 pub fn from_config(config: WaveHeightfieldConfig) -> Self {
120 let clean: WaveHeightfieldConfig = config.sanitized();
121 let total: usize = clean.get_width() * clean.get_height();
122 let cell_damping: Vec<f32> = compute_wake_damping_profile(
123 clean.get_width(),
124 clean.get_height(),
125 clean.get_damping(),
126 clean.get_sponge_width(),
127 clean.get_sponge_strength(),
128 );
129 Self {
130 config: clean,
131 heights_curr: vec![0.0; total],
132 heights_prev: vec![0.0; total],
133 heights_next: vec![0.0; total],
134 obstacle_mask: vec![0; total],
135 foam: vec![0.0; total],
136 cell_damping,
137 last_dt_sub: 1.0 / 60.0,
138 sim_time_secs: 0.0,
139 }
140 }
141
142 pub fn reset(&mut self) {
144 self.get_mut_heights_curr().fill(0.0);
145 self.get_mut_heights_prev().fill(0.0);
146 self.get_mut_heights_next().fill(0.0);
147 self.get_mut_foam().fill(0.0);
148 self.set_sim_time_secs(0.0);
149 }
150
151 pub fn step(&mut self, dt_secs: f32) {
157 let clamped_dt: f32 = wake_sanitize_f32(dt_secs, 0.0).clamp(0.0, WAKE_MAX_DT_SECS);
158 if clamped_dt <= 1e-6 {
159 return;
160 }
161 let cfg: WaveHeightfieldConfig = self.get_config();
162 let dx: f32 = cfg.get_cell_size_m();
163 let speed: f32 = cfg.get_wave_speed_mps();
164 let max_sub_dt: f32 = (WAKE_MAX_CFL_NUMBER * dx / speed).max(1e-5);
165 let substeps: usize =
166 ((clamped_dt / max_sub_dt).ceil() as usize).clamp(1, WAKE_MAX_SUBSTEPS);
167 let dt_sub: f32 = clamped_dt / substeps as f32;
168 let courant: f32 = (speed * dt_sub / dx).min(WAKE_MAX_CFL_NUMBER);
169 let courant_sq: f32 = courant * courant;
170 let width: usize = cfg.get_width();
171 let height: usize = cfg.get_height();
172 let foam_decay: f32 = cfg.get_foam_decay_rate();
173 let mut heights_curr: Vec<f32> = take(self.get_mut_heights_curr());
174 let mut heights_prev: Vec<f32> = take(self.get_mut_heights_prev());
175 let mut heights_next: Vec<f32> = take(self.get_mut_heights_next());
176 let mut foam: Vec<f32> = take(self.get_mut_foam());
177 let obstacle_mask: Vec<u8> = take(self.get_mut_obstacle_mask());
178 let cell_damping: Vec<f32> = take(self.get_mut_cell_damping());
179 let substep_params: WakeSubstepParams =
180 WakeSubstepParams::new(width, height, courant_sq, dt_sub, foam_decay);
181 for _step_index in 0..substeps {
182 step_wake_substep(
183 substep_params,
184 &heights_curr,
185 &heights_prev,
186 &obstacle_mask,
187 &cell_damping,
188 &mut heights_next,
189 &mut foam,
190 );
191 swap(&mut heights_prev, &mut heights_curr);
192 swap(&mut heights_curr, &mut heights_next);
193 }
194 self.set_heights_curr(heights_curr);
195 self.set_heights_prev(heights_prev);
196 self.set_heights_next(heights_next);
197 self.set_foam(foam);
198 self.set_obstacle_mask(obstacle_mask);
199 self.set_cell_damping(cell_damping);
200 self.set_last_dt_sub(dt_sub);
201 let next_time: f32 = self.get_sim_time_secs() + clamped_dt;
202 self.set_sim_time_secs(next_time);
203 }
204
205 pub fn inject_splash(&mut self, world_x: f32, world_z: f32, radius_m: f32, amplitude_m: f32) {
214 let cfg: WaveHeightfieldConfig = self.get_config();
215 let foam_boost: f32 = (amplitude_m.abs() * 1.4).clamp(0.0, 0.85);
216 let mut heights_curr: Vec<f32> = take(self.get_mut_heights_curr());
217 let mut heights_prev: Vec<f32> = take(self.get_mut_heights_prev());
218 let mut foam: Vec<f32> = take(self.get_mut_foam());
219 let obstacle_mask: Vec<u8> = take(self.get_mut_obstacle_mask());
220 let impulse: WakeImpulseDesc =
221 WakeImpulseDesc::new(world_x, world_z, radius_m, amplitude_m, foam_boost);
222 apply_wake_radial_impulse(
223 cfg,
224 impulse,
225 &obstacle_mask,
226 (&mut heights_curr, &mut heights_prev),
227 &mut foam,
228 );
229 self.set_heights_curr(heights_curr);
230 self.set_heights_prev(heights_prev);
231 self.set_foam(foam);
232 self.set_obstacle_mask(obstacle_mask);
233 }
234
235 pub fn inject_boat_wake(
245 &mut self,
246 world_x: f32,
247 world_z: f32,
248 velocity_xz: Vec2,
249 hull_radius_m: f32,
250 wake_strength: f32,
251 ) {
252 let vx: f32 = wake_sanitize_f32(velocity_xz.get_x(), 0.0);
253 let vz: f32 = wake_sanitize_f32(velocity_xz.get_y(), 0.0);
254 let speed: f32 = (vx * vx + vz * vz).sqrt();
255 let safe_radius: f32 =
256 wake_sanitize_f32(hull_radius_m, self.get_config().get_cell_size_m() * 2.0).max(0.1);
257 let safe_strength: f32 = wake_sanitize_f32(wake_strength, 1.0).clamp(0.0, 4.0);
258 if speed <= 1e-4 || safe_strength <= 1e-5 {
259 return;
260 }
261 let dir_x: f32 = vx / speed;
262 let dir_z: f32 = vz / speed;
263 let bow_x: f32 = world_x + dir_x * safe_radius * 0.75;
264 let bow_z: f32 = world_z + dir_z * safe_radius * 0.75;
265 let stern_x: f32 = world_x - dir_x * safe_radius * 0.85;
266 let stern_z: f32 = world_z - dir_z * safe_radius * 0.85;
267 let amp: f32 = (0.045 * speed.min(14.0) * safe_strength).min(0.65);
268 let cfg: WaveHeightfieldConfig = self.get_config();
269 let mut heights_curr: Vec<f32> = take(self.get_mut_heights_curr());
270 let mut heights_prev: Vec<f32> = take(self.get_mut_heights_prev());
271 let mut foam: Vec<f32> = take(self.get_mut_foam());
272 let obstacle_mask: Vec<u8> = take(self.get_mut_obstacle_mask());
273 let bow_impulse: WakeImpulseDesc = WakeImpulseDesc::new(
274 bow_x,
275 bow_z,
276 safe_radius * 0.85,
277 amp,
278 (amp * 1.1).clamp(0.0, 0.75),
279 );
280 let stern_impulse: WakeImpulseDesc = WakeImpulseDesc::new(
281 stern_x,
282 stern_z,
283 safe_radius * 1.05,
284 -amp * 0.85,
285 (amp * 1.5).clamp(0.0, 0.95),
286 );
287 apply_wake_radial_impulse(
288 cfg,
289 bow_impulse,
290 &obstacle_mask,
291 (&mut heights_curr, &mut heights_prev),
292 &mut foam,
293 );
294 apply_wake_radial_impulse(
295 cfg,
296 stern_impulse,
297 &obstacle_mask,
298 (&mut heights_curr, &mut heights_prev),
299 &mut foam,
300 );
301 self.set_heights_curr(heights_curr);
302 self.set_heights_prev(heights_prev);
303 self.set_foam(foam);
304 self.set_obstacle_mask(obstacle_mask);
305 }
306
307 pub fn inject_raindrop(&mut self, world_x: f32, world_z: f32, intensity: f32) {
315 let clamped: f32 = wake_sanitize_f32(intensity, 0.5).clamp(0.0, 2.0);
316 let radius: f32 = self.get_config().get_cell_size_m() * 1.5;
317 self.inject_splash(world_x, world_z, radius, -0.04 * clamped);
318 }
319
320 pub fn set_obstacle_rect(
330 &mut self,
331 min_x: f32,
332 min_z: f32,
333 max_x: f32,
334 max_z: f32,
335 solid: bool,
336 ) {
337 let cfg: WaveHeightfieldConfig = self.get_config();
338 let width: usize = cfg.get_width();
339 let height: usize = cfg.get_height();
340 let dx: f32 = cfg.get_cell_size_m();
341 let origin: Vec2 = cfg.get_origin_xz();
342 let lo_x: f32 = min_x.min(max_x);
343 let hi_x: f32 = min_x.max(max_x);
344 let lo_z: f32 = min_z.min(max_z);
345 let hi_z: f32 = min_z.max(max_z);
346 let flag: u8 = u8::from(solid);
347 let mut mask: Vec<u8> = take(self.get_mut_obstacle_mask());
348 let mut curr: Vec<f32> = take(self.get_mut_heights_curr());
349 let mut prev: Vec<f32> = take(self.get_mut_heights_prev());
350 let mut foam: Vec<f32> = take(self.get_mut_foam());
351 for row in 0..height {
352 let wz: f32 = origin.get_y() + row as f32 * dx;
353 if wz < lo_z || wz > hi_z {
354 continue;
355 }
356 for col in 0..width {
357 let wx: f32 = origin.get_x() + col as f32 * dx;
358 if wx >= lo_x && wx <= hi_x {
359 let idx: usize = row * width + col;
360 mask[idx] = flag;
361 if solid {
362 curr[idx] = 0.0;
363 prev[idx] = 0.0;
364 foam[idx] = 0.0;
365 }
366 }
367 }
368 }
369 self.set_obstacle_mask(mask);
370 self.set_heights_curr(curr);
371 self.set_heights_prev(prev);
372 self.set_foam(foam);
373 }
374
375 pub fn set_obstacle_circle(
384 &mut self,
385 center_x: f32,
386 center_z: f32,
387 radius_m: f32,
388 solid: bool,
389 ) {
390 let cfg: WaveHeightfieldConfig = self.get_config();
391 let width: usize = cfg.get_width();
392 let height: usize = cfg.get_height();
393 let dx: f32 = cfg.get_cell_size_m();
394 let origin: Vec2 = cfg.get_origin_xz();
395 let r_sq: f32 = radius_m.max(0.0) * radius_m.max(0.0);
396 let flag: u8 = u8::from(solid);
397 let mut mask: Vec<u8> = take(self.get_mut_obstacle_mask());
398 let mut curr: Vec<f32> = take(self.get_mut_heights_curr());
399 let mut prev: Vec<f32> = take(self.get_mut_heights_prev());
400 let mut foam: Vec<f32> = take(self.get_mut_foam());
401 for row in 0..height {
402 let dz: f32 = origin.get_y() + row as f32 * dx - center_z;
403 for col in 0..width {
404 let dist_x: f32 = origin.get_x() + col as f32 * dx - center_x;
405 if dist_x * dist_x + dz * dz <= r_sq {
406 let idx: usize = row * width + col;
407 mask[idx] = flag;
408 if solid {
409 curr[idx] = 0.0;
410 prev[idx] = 0.0;
411 foam[idx] = 0.0;
412 }
413 }
414 }
415 }
416 self.set_obstacle_mask(mask);
417 self.set_heights_curr(curr);
418 self.set_heights_prev(prev);
419 self.set_foam(foam);
420 }
421
422 pub fn clear_obstacles(&mut self) {
424 self.get_mut_obstacle_mask().fill(0);
425 }
426
427 #[must_use]
438 pub fn is_obstacle_cell(&self, col: usize, row: usize) -> bool {
439 let cfg: WaveHeightfieldConfig = self.get_config();
440 if col >= cfg.get_width() || row >= cfg.get_height() {
441 return false;
442 }
443 self.get_obstacle_mask()[row * cfg.get_width() + col] != 0
444 }
445
446 #[must_use]
457 pub fn sample_displacement(&self, world_x: f32, world_z: f32) -> f32 {
458 let cfg: WaveHeightfieldConfig = self.get_config();
459 let origin: Vec2 = cfg.get_origin_xz();
460 let dx: f32 = cfg.get_cell_size_m();
461 let gx: f32 = (world_x - origin.get_x()) / dx;
462 let gz: f32 = (world_z - origin.get_y()) / dx;
463 wake_bilinear_sample(
464 self.get_heights_curr(),
465 cfg.get_width(),
466 cfg.get_height(),
467 gx,
468 gz,
469 )
470 }
471
472 #[must_use]
483 pub fn sample_height(&self, world_x: f32, world_z: f32) -> f32 {
484 self.get_config().get_base_water_y() + self.sample_displacement(world_x, world_z)
485 }
486
487 #[must_use]
498 pub fn sample_height_and_normal(&self, world_x: f32, world_z: f32) -> (f32, Vec3) {
499 let cfg: WaveHeightfieldConfig = self.get_config();
500 let eps: f32 = cfg.get_cell_size_m();
501 let h_center: f32 = self.sample_height(world_x, world_z);
502 let h_left: f32 = self.sample_displacement(world_x - eps, world_z);
503 let h_right: f32 = self.sample_displacement(world_x + eps, world_z);
504 let h_back: f32 = self.sample_displacement(world_x, world_z - eps);
505 let h_fwd: f32 = self.sample_displacement(world_x, world_z + eps);
506 let dh_dx: f32 = (h_right - h_left) / (2.0 * eps);
507 let dh_dz: f32 = (h_fwd - h_back) / (2.0 * eps);
508 let normal: Vec3 = Vec3::new(-dh_dx, 1.0, -dh_dz).normalize();
509 (h_center, normal)
510 }
511
512 #[must_use]
523 pub fn sample_foam(&self, world_x: f32, world_z: f32) -> f32 {
524 let cfg: WaveHeightfieldConfig = self.get_config();
525 let origin: Vec2 = cfg.get_origin_xz();
526 let dx: f32 = cfg.get_cell_size_m();
527 let gx: f32 = (world_x - origin.get_x()) / dx;
528 let gz: f32 = (world_z - origin.get_y()) / dx;
529 wake_bilinear_sample(self.get_foam(), cfg.get_width(), cfg.get_height(), gx, gz)
530 .clamp(0.0, 1.0)
531 }
532
533 #[must_use]
539 pub fn total_wave_energy(&self) -> f32 {
540 let cfg: WaveHeightfieldConfig = self.get_config();
541 let width: usize = cfg.get_width();
542 let height: usize = cfg.get_height();
543 let dx: f32 = cfg.get_cell_size_m();
544 let inv_dt: f32 = 1.0 / self.get_last_dt_sub().max(1e-5);
545 let c_over_dx: f32 = cfg.get_wave_speed_mps() / dx;
546 let c2_inv_dx2: f32 = c_over_dx * c_over_dx;
547 let cell_area: f32 = dx * dx;
548 let curr: &[f32] = self.get_heights_curr();
549 let prev: &[f32] = self.get_heights_prev();
550 let mask: &[u8] = self.get_obstacle_mask();
551 let mut energy: f32 = 0.0;
552 for row in 0..height {
553 for col in 0..width {
554 let idx: usize = row * width + col;
555 if mask[idx] != 0 {
556 continue;
557 }
558 let vel: f32 = (curr[idx] - prev[idx]) * inv_dt;
559 let grad_x: f32 = if col + 1 < width && mask[idx + 1] == 0 {
560 curr[idx + 1] - curr[idx]
561 } else {
562 0.0
563 };
564 let grad_z: f32 = if row + 1 < height && mask[idx + width] == 0 {
565 curr[idx + width] - curr[idx]
566 } else {
567 0.0
568 };
569 energy += 0.5
570 * cell_area
571 * (vel * vel + c2_inv_dx2 * (grad_x * grad_x + grad_z * grad_z));
572 }
573 }
574 energy
575 }
576
577 #[must_use]
583 pub fn max_abs_height(&self) -> f32 {
584 let mut max_val: f32 = 0.0;
585 for &val in self.get_heights_curr().iter() {
586 let abs_v: f32 = val.abs();
587 if abs_v > max_val {
588 max_val = abs_v;
589 }
590 }
591 max_val
592 }
593
594 #[must_use]
605 pub fn build_mesh(&self, name: &str, material: PbrMaterial) -> Mesh3D {
606 let cfg: WaveHeightfieldConfig = self.get_config();
607 let width: usize = cfg.get_width();
608 let height: usize = cfg.get_height();
609 let dx: f32 = cfg.get_cell_size_m();
610 let origin: Vec2 = cfg.get_origin_xz();
611 let base_y: f32 = cfg.get_base_water_y();
612 let inv_w: f32 = 1.0 / (width.saturating_sub(1).max(1) as f32);
613 let inv_h: f32 = 1.0 / (height.saturating_sub(1).max(1) as f32);
614 let mut vertices: Vec<Vertex3D> = Vec::with_capacity(width * height);
615 for row in 0..height {
616 let wz: f32 = origin.get_y() + row as f32 * dx;
617 let v_coord: f32 = row as f32 * inv_h;
618 for col in 0..width {
619 let wx: f32 = origin.get_x() + col as f32 * dx;
620 let u_coord: f32 = col as f32 * inv_w;
621 let idx: usize = row * width + col;
622 let h_val: f32 = self.get_heights_curr()[idx];
623 let (_, normal): (f32, Vec3) = self.sample_height_and_normal(wx, wz);
624 let foam_v: f32 = self.get_foam()[idx].clamp(0.0, 1.0);
625 let foam_u8: u8 = (foam_v * 255.0).round() as u8;
626 let vert: Vertex3D = Vertex3D::from_full(
627 Vec3::new(wx, base_y + h_val, wz),
628 normal,
629 [1.0, 0.0, 0.0, 1.0],
630 [u_coord, v_coord],
631 [foam_v, 0.0],
632 [255, 255, 255, foam_u8.max(180)],
633 0b1101,
634 );
635 vertices.push(vert);
636 }
637 }
638 let quad_count: usize = width.saturating_sub(1) * height.saturating_sub(1);
639 let mut indices: Vec<[u32; 3]> = Vec::with_capacity(quad_count * 2);
640 for row in 0..height.saturating_sub(1) {
641 for col in 0..width.saturating_sub(1) {
642 let i00: u32 = (row * width + col) as u32;
643 let i10: u32 = i00 + 1;
644 let i01: u32 = ((row + 1) * width + col) as u32;
645 let i11: u32 = i01 + 1;
646 indices.push([i00, i01, i10]);
647 indices.push([i10, i01, i11]);
648 }
649 }
650 let mesh_name: String = if name.is_empty() {
651 WAKE_DEFAULT_MESH_NAME.to_string()
652 } else {
653 name.to_string()
654 };
655 Mesh3D::from_parts(mesh_name, vertices, indices, material)
656 }
657}