euv_core/game/fluid/scene/
impl.rs1use super::*;
2
3impl Default for GyroLiquidGameScene {
5 fn default() -> Self {
11 Self::with_config(GyroLiquidConfig::default())
12 }
13}
14
15impl GyroLiquidSceneState {
17 #[must_use]
27 pub(crate) fn with_config(config: GyroLiquidConfig) -> Self {
28 let solver: LiquidFluidSolver = LiquidFluidSolver::with_config(config);
29 let mut init_snap: FluidSimSnapshot = FluidSimSnapshot::default();
30 solver.capture_snapshot_into(&mut init_snap);
31 let snapshots: DoubleBufferedSnapshot<FluidSimSnapshot> =
32 DoubleBufferedSnapshot::new(init_snap);
33 let renderer: LiquidOpticalRenderer = LiquidOpticalRenderer::new_renderer();
34 let frame_pool: RenderBufferPool = RenderBufferPool::with_capacity(FLUID_SCENE_POOL_SLOTS);
35 let mut state: Self = Self {
36 solver,
37 snapshots,
38 renderer,
39 frame_pool,
40 frame_fence: 0,
41 sensor_mode: FluidSensorMode::Auto,
42 device_motion_signal: None,
43 manual_motion_sample: None,
44 sensor_active: false,
45 last_viewport_bounds: Rect::new(0.0, 0.0, 640.0, 480.0),
46 last_sim_ms: 0.0,
47 last_render_ms: 0.0,
48 stats: GyroLiquidStats::default(),
49 resolution_scale: FLUID_DEFAULT_RESOLUTION_SCALE,
50 };
51 state.refresh_stats();
52 state
53 }
54
55 pub(crate) fn refresh_stats(&mut self) {
61 let solver: &LiquidFluidSolver = self.get_solver();
62 let config_spec: GyroLiquidConfig = solver.get_config();
63 let ren: &LiquidOpticalRenderer = self.get_renderer();
64 let next: GyroLiquidStats = GyroLiquidStats {
65 particle_count: solver.get_particle_count(),
66 bubble_count: solver.get_bubble_count(),
67 buoyant_body_count: solver.get_buoyant_body_count(),
68 kinetic_energy_mj: solver.get_kinetic_energy_mj(),
69 gravity_x: solver.get_gravity_x(),
70 gravity_y: solver.get_gravity_y(),
71 gravity_z: solver.get_gravity_z(),
72 tilt_angle_deg: solver.get_active_roll_rad().to_degrees(),
73 peak_wave_height_m: solver.get_peak_wave_height_m(),
74 sim_time_ms: self.get_last_sim_ms(),
75 render_time_ms: self.get_last_render_ms(),
76 sensor_mode: self.get_sensor_mode(),
77 sensor_active: self.get_sensor_active(),
78 vessel_width_m: config_spec.get_vessel_width_m(),
79 vessel_height_m: config_spec.get_vessel_height_m(),
80 fill_ratio: config_spec.get_fill_ratio(),
81 render_width: ren.get_last_width(),
82 render_height: ren.get_last_height(),
83 };
84 self.set_stats(next);
85 }
86
87 #[must_use]
97 pub(crate) fn resolve_active_sensor_sample(&self) -> Option<DeviceMotionSample> {
98 if self.get_sensor_mode() == FluidSensorMode::VirtualTilt {
99 return None;
100 }
101 if let Some(manual) = self.get_manual_motion_sample() {
102 return Some(manual);
103 }
104 if let Some(sig) = self.get_device_motion_signal() {
105 let sample: DeviceMotionSample = sig.get_untracked();
106 if sample.get_sensor_active() || self.get_sensor_mode() == FluidSensorMode::LiveHardware
107 {
108 return Some(sample);
109 }
110 }
111 let latest: DeviceMotionSample = latest_device_motion();
112 if latest.get_sensor_active() {
113 return Some(latest);
114 }
115 if self.get_sensor_mode() == FluidSensorMode::LiveHardware {
116 return Some(latest);
117 }
118 None
119 }
120}
121
122impl GyroLiquidGameScene {
124 #[must_use]
134 pub fn with_config(config: GyroLiquidConfig) -> Self {
135 Self {
136 inner: Rc::new(RefCell::new(GyroLiquidSceneState::with_config(config))),
137 }
138 }
139
140 pub fn bind_device_motion(&self, signal: Signal<DeviceMotionSample>) {
147 if let Ok(mut node_style) = self.get_inner().try_borrow_mut() {
148 node_style.set_device_motion_signal(Some(signal));
149 }
150 }
151
152 pub fn set_device_motion(&self, sample: Option<DeviceMotionSample>) {
159 if let Ok(mut node_style) = self.get_inner().try_borrow_mut() {
160 node_style.set_manual_motion_sample(sample);
161 }
162 }
163
164 pub fn set_sensor_mode(&self, mode: FluidSensorMode) {
171 if let Ok(mut node_style) = self.get_inner().try_borrow_mut() {
172 node_style.set_sensor_mode(mode);
173 node_style.refresh_stats();
174 }
175 }
176
177 pub fn set_virtual_tilt(&self, roll_rad: f32, pitch_rad: f32) {
185 if let Ok(mut node_style) = self.get_inner().try_borrow_mut() {
186 node_style
187 .get_mut_solver()
188 .set_virtual_tilt(roll_rad, pitch_rad);
189 node_style.refresh_stats();
190 }
191 }
192
193 pub fn rotate_container_by(&self, delta_rad: f32) {
200 if let Ok(mut node_style) = self.get_inner().try_borrow_mut() {
201 node_style.get_mut_solver().rotate_container_by(delta_rad);
202 node_style.refresh_stats();
203 }
204 }
205
206 pub fn apply_shake_impulse(&self, ax: f32, ay: f32) {
214 if let Ok(mut node_style) = self.get_inner().try_borrow_mut() {
215 node_style.get_mut_solver().apply_shake_impulse(ax, ay);
216 }
217 }
218
219 pub fn apply_stir_impulse(&self, norm_x: f32, norm_y: f32, vel_x_mps: f32, vel_y_mps: f32) {
229 if let Ok(mut node_style) = self.get_inner().try_borrow_mut() {
230 node_style
231 .get_mut_solver()
232 .apply_stir_impulse(norm_x, norm_y, vel_x_mps, vel_y_mps);
233 }
234 }
235
236 pub fn set_fill_ratio(&self, fill_ratio: f32) {
243 if let Ok(mut node_style) = self.get_inner().try_borrow_mut() {
244 node_style.get_mut_solver().set_fill_ratio(fill_ratio);
245 let GyroLiquidSceneState {
246 solver, snapshots, ..
247 } = &mut *node_style;
248 snapshots.capture_discontinuous_into(|dst: &mut FluidSimSnapshot| {
249 solver.capture_snapshot_into(dst);
250 });
251 node_style.refresh_stats();
252 }
253 }
254
255 pub fn set_viscosity(&self, viscosity: f32) {
262 if let Ok(mut node_style) = self.get_inner().try_borrow_mut() {
263 node_style.get_mut_solver().set_viscosity(viscosity);
264 }
265 }
266
267 pub fn set_surface_tension(&self, surface_tension: f32) {
274 if let Ok(mut node_style) = self.get_inner().try_borrow_mut() {
275 node_style
276 .get_mut_solver()
277 .set_surface_tension(surface_tension);
278 }
279 }
280
281 pub fn set_buoyant_bodies_enabled(&self, enabled: bool) {
288 if let Ok(mut node_style) = self.get_inner().try_borrow_mut() {
289 node_style
290 .get_mut_solver()
291 .set_buoyant_bodies_enabled(enabled);
292 let GyroLiquidSceneState {
293 solver, snapshots, ..
294 } = &mut *node_style;
295 snapshots.capture_discontinuous_into(|dst: &mut FluidSimSnapshot| {
296 solver.capture_snapshot_into(dst);
297 });
298 node_style.refresh_stats();
299 }
300 }
301
302 pub fn reset_water(&self) {
308 if let Ok(mut node_style) = self.get_inner().try_borrow_mut() {
309 node_style.get_mut_solver().set_virtual_tilt(0.0, 0.0);
310 node_style.get_mut_solver().set_prev_virtual_roll_rad(0.0);
311 node_style.get_mut_solver().reset_water();
312 node_style.get_mut_renderer().set_cam_initialized(false);
313 let GyroLiquidSceneState {
314 solver, snapshots, ..
315 } = &mut *node_style;
316 snapshots.capture_discontinuous_into(|dst: &mut FluidSimSnapshot| {
317 solver.capture_snapshot_into(dst);
318 });
319 node_style.refresh_stats();
320 }
321 }
322
323 #[must_use]
333 pub fn stats(&self) -> GyroLiquidStats {
334 self.get_inner()
335 .try_borrow()
336 .map(|node_style: Ref<'_, GyroLiquidSceneState>| node_style.get_stats())
337 .unwrap_or_default()
338 }
339
340 #[must_use]
350 pub fn center_of_mass(&self) -> (f32, f32) {
351 self.get_inner()
352 .try_borrow()
353 .map(|node_style: Ref<'_, GyroLiquidSceneState>| {
354 node_style.get_solver().center_of_mass()
355 })
356 .unwrap_or((DEFAULT_VESSEL_WIDTH_M * 0.5, DEFAULT_VESSEL_HEIGHT_M * 0.5))
357 }
358
359 #[must_use]
369 pub fn buoyant_bodies(&self) -> Vec<BuoyantBody> {
370 self.get_inner()
371 .try_borrow()
372 .map(|node_style: Ref<'_, GyroLiquidSceneState>| {
373 let cnt: usize = node_style.get_solver().get_buoyant_body_count();
374 node_style.get_solver().get_buoyant_bodies()[..cnt].to_vec()
375 })
376 .unwrap_or_default()
377 }
378
379 #[must_use]
389 pub fn has_invalid_or_escaped_state(&self) -> bool {
390 self.get_inner()
391 .try_borrow()
392 .map(|node_style: Ref<'_, GyroLiquidSceneState>| {
393 node_style.get_solver().has_invalid_or_escaped_state()
394 })
395 .unwrap_or(false)
396 }
397
398 #[must_use]
408 pub fn resolution_scale(&self) -> f32 {
409 self.get_inner()
410 .try_borrow()
411 .map(|state_guard: Ref<'_, GyroLiquidSceneState>| state_guard.get_resolution_scale())
412 .unwrap_or(FLUID_DEFAULT_RESOLUTION_SCALE)
413 }
414
415 pub fn set_resolution_scale(&self, scale: f32) {
422 let safe_scale: f32 = if scale.is_finite() && scale > 0.0 {
423 scale.clamp(FLUID_MIN_RESOLUTION_SCALE, FLUID_MAX_RESOLUTION_SCALE)
424 } else {
425 FLUID_DEFAULT_RESOLUTION_SCALE
426 };
427 if let Ok(mut state_guard) = self.get_inner().try_borrow_mut() {
428 state_guard.set_resolution_scale(safe_scale);
429 }
430 }
431
432 #[must_use]
445 pub fn render_to_pooled_frame(
446 &self,
447 viewport_w: u32,
448 viewport_h: u32,
449 alpha: f32,
450 ) -> Option<PooledFrameLease> {
451 let mut node_style: RefMut<'_, GyroLiquidSceneState> =
452 self.get_inner().try_borrow_mut().ok()?;
453 let vw: u32 = viewport_w.max(FLUID_RENDER_MIN_DIM);
454 let vh: u32 = viewport_h.max(FLUID_RENDER_MIN_DIM);
455 if node_style
456 .get_mut_solver()
457 .adapt_vessel_aspect_changed((vw as f32) / (vh as f32))
458 {
459 let GyroLiquidSceneState {
460 solver, snapshots, ..
461 } = &mut *node_style;
462 snapshots.capture_discontinuous_into(|dst: &mut FluidSimSnapshot| {
463 solver.capture_snapshot_into(dst);
464 });
465 }
466 let next_fence: u64 = node_style.get_frame_fence().saturating_add(1);
467 node_style.set_frame_fence(next_fence);
468 #[cfg(not(target_arch = "wasm32"))]
469 let t0: Instant = Instant::now();
470 let lease: Option<PooledFrameLease> = {
471 let GyroLiquidSceneState {
472 snapshots,
473 renderer,
474 frame_pool,
475 ..
476 } = &mut *node_style;
477 let snap: &FluidSimSnapshot = snapshots.sample_cached(alpha);
478 renderer.render_snapshot_into_pool(snap, vw, vh, frame_pool, next_fence)
479 };
480 #[cfg(not(target_arch = "wasm32"))]
481 {
482 let elapsed_ms: f32 = (t0.elapsed().as_nanos() as f32) * 1.0e-6;
483 node_style.set_last_render_ms(elapsed_ms);
484 }
485 node_style.refresh_stats();
486 lease
487 }
488}
489
490impl GameScene for GyroLiquidGameScene {
492 fn fixed_update(&mut self, dt: f32, input: &InputState) {
500 let Ok(mut node_style) = self.get_inner().try_borrow_mut() else {
501 return;
502 };
503 #[cfg(not(target_arch = "wasm32"))]
504 let t0: Instant = Instant::now();
505 let safe_dt: f32 = dt.clamp(1.0e-5, FLUID_MAX_STEP_DT);
506 let sensor_opt: Option<DeviceMotionSample> = node_style.resolve_active_sensor_sample();
507 if let Some(sample) = sensor_opt {
508 node_style.set_sensor_active(sample.get_sensor_active());
509 node_style
510 .get_mut_solver()
511 .apply_device_motion(sample, safe_dt);
512 } else {
513 node_style.set_sensor_active(false);
514 let roll_axis: f32 = input.axis(KeyCode::ArrowLeft, KeyCode::ArrowRight)
515 + input.axis(
516 KeyCode::Character(FLUID_KEY_CHAR_LEFT),
517 KeyCode::Character(FLUID_KEY_CHAR_RIGHT),
518 );
519 let pitch_axis: f32 = input.axis(KeyCode::ArrowDown, KeyCode::ArrowUp)
520 + input.axis(
521 KeyCode::Character(FLUID_KEY_CHAR_DOWN),
522 KeyCode::Character(FLUID_KEY_CHAR_UP),
523 );
524 if roll_axis.abs() > 0.01 {
525 node_style.get_mut_solver().rotate_container_by(
526 roll_axis.clamp(-1.0, 1.0) * FLUID_KEY_ROLL_SPEED_RAD_S * safe_dt,
527 );
528 }
529 if pitch_axis.abs() > 0.01 {
530 let cur_roll: f32 = node_style.get_solver().get_virtual_roll_rad();
531 let next_pitch: f32 = node_style.get_solver().get_virtual_pitch_rad()
532 + pitch_axis.clamp(-1.0, 1.0) * FLUID_KEY_PITCH_SPEED_RAD_S * safe_dt;
533 node_style
534 .get_mut_solver()
535 .set_virtual_tilt(cur_roll, next_pitch);
536 }
537 node_style.get_mut_solver().sync_virtual_motion(safe_dt);
538 }
539 if input.is_key_just_pressed(KeyCode::Character(FLUID_KEY_CHAR_RESET)) {
540 node_style.get_mut_solver().set_virtual_tilt(0.0, 0.0);
541 node_style.get_mut_solver().set_prev_virtual_roll_rad(0.0);
542 node_style.get_mut_solver().reset_water();
543 }
544 if input.is_button_down(PointerButton::Primary) {
545 let rect_bounds: Rect = node_style.get_last_viewport_bounds();
546 let border_width: f32 = rect_bounds.get_width().max(1.0);
547 let bh: f32 = rect_bounds.get_height().max(1.0);
548 let ptr: Point = input.get_pointer_position();
549 let delta: Point = input.get_pointer_delta();
550 let nx: f32 = (ptr.get_x() - rect_bounds.get_x()) / border_width;
551 let ny: f32 = (ptr.get_y() - rect_bounds.get_y()) / bh;
552 if (0.0..=1.0).contains(&nx) && (0.0..=1.0).contains(&ny) {
553 let d_mag: f32 = delta.get_x().hypot(delta.get_y());
554 if d_mag > 0.25 {
555 let vw_m: f32 = node_style.get_solver().get_config().get_vessel_width_m();
556 let vh_m: f32 = node_style.get_solver().get_config().get_vessel_height_m();
557 let vx_mps: f32 = (delta.get_x() / border_width) * vw_m / safe_dt;
558 let vy_mps: f32 = (delta.get_y() / bh) * vh_m / safe_dt;
559 node_style
560 .get_mut_solver()
561 .apply_stir_impulse(nx, ny, vx_mps, vy_mps);
562 }
563 }
564 }
565 node_style.get_mut_solver().step(safe_dt);
566 {
567 let GyroLiquidSceneState {
568 solver, snapshots, ..
569 } = &mut *node_style;
570 snapshots.capture_into(|dst: &mut FluidSimSnapshot| {
571 solver.capture_snapshot_into(dst);
572 });
573 }
574 #[cfg(not(target_arch = "wasm32"))]
575 {
576 let elapsed_ms: f32 = (t0.elapsed().as_nanos() as f32) * 1.0e-6;
577 node_style.set_last_sim_ms(elapsed_ms);
578 }
579 node_style.refresh_stats();
580 }
581
582 fn render(&mut self, alpha: f32, ctx: &mut GameRenderContext<'_>) {
590 let Ok(mut node_style) = self.get_inner().try_borrow_mut() else {
591 return;
592 };
593 let bounds: Rect = ctx.bounds;
594 let vp_w: f32 = bounds.get_width().max(64.0);
595 let vp_h: f32 = bounds.get_height().max(64.0);
596 let dpr: f32 = clamp_viewport_scale(ctx.scale_factor());
597 let raw_phys_w: u32 = compute_lossless_physical_dim(f64::from(vp_w), dpr);
598 let raw_phys_h: u32 = compute_lossless_physical_dim(f64::from(vp_h), dpr);
599 let res_scale: f32 = node_style.get_resolution_scale() * ctx.scene_workload_scale();
600 let (mut target_phys_w, mut target_phys_h): (u32, u32) =
601 LiquidOpticalRenderer::resolve_render_dimensions_with_scale(
602 raw_phys_w, raw_phys_h, res_scale,
603 );
604 if !ctx.is_direct_gpu_active() {
605 let total_px: u64 = (target_phys_w as u64).saturating_mul(target_phys_h as u64);
606 if total_px > FLUID_SOFTWARE_FALLBACK_MAX_PIXELS {
607 let cap_scale: f32 =
608 ((FLUID_SOFTWARE_FALLBACK_MAX_PIXELS as f64) / (total_px as f64)).sqrt() as f32;
609 target_phys_w = ((target_phys_w as f32) * cap_scale)
610 .round()
611 .clamp(FLUID_RENDER_MIN_DIM as f32, FLUID_RENDER_MAX_DIM as f32)
612 as u32;
613 target_phys_h = ((target_phys_h as f32) * cap_scale)
614 .round()
615 .clamp(FLUID_RENDER_MIN_DIM as f32, FLUID_RENDER_MAX_DIM as f32)
616 as u32;
617 }
618 }
619 node_style.set_last_viewport_bounds(bounds);
620 if node_style
621 .get_mut_solver()
622 .adapt_vessel_aspect_changed(vp_w / vp_h)
623 {
624 let GyroLiquidSceneState {
625 solver, snapshots, ..
626 } = &mut *node_style;
627 snapshots.capture_discontinuous_into(|dst: &mut FluidSimSnapshot| {
628 solver.capture_snapshot_into(dst);
629 });
630 }
631 let next_fence: u64 = node_style.get_frame_fence().saturating_add(1);
632 node_style.set_frame_fence(next_fence);
633 #[cfg(not(target_arch = "wasm32"))]
634 let t0: Instant = Instant::now();
635 if ctx.is_direct_gpu_active() {
636 let mut ocean_pass: Box<GpuOceanScenePass> = take_recycled_ocean_scene_pass();
637 {
638 let GyroLiquidSceneState {
639 snapshots,
640 renderer,
641 ..
642 } = &mut *node_style;
643 let snap: &FluidSimSnapshot = snapshots.sample_cached(alpha);
644 renderer.build_gpu_ocean_pass_into(
645 snap,
646 target_phys_w,
647 target_phys_h,
648 &mut ocean_pass,
649 );
650 }
651 let dst_rect: Rect = Rect::new(0.0, 0.0, vp_w, vp_h);
652 ctx.submit_gpu_scene_pass(dst_rect, DirectGpuScenePass::OceanFluid(ocean_pass));
653 } else {
654 let lease_opt: Option<PooledFrameLease> = {
655 let GyroLiquidSceneState {
656 snapshots,
657 renderer,
658 frame_pool,
659 ..
660 } = &mut *node_style;
661 let snap: &FluidSimSnapshot = snapshots.sample_cached(alpha);
662 renderer.render_snapshot_into_pool(
663 snap,
664 target_phys_w,
665 target_phys_h,
666 frame_pool,
667 next_fence,
668 )
669 };
670 if let Some(lease) = lease_opt {
671 let dst_rect: Rect = Rect::new(0.0, 0.0, vp_w, vp_h);
672 ctx.blit_pooled_frame(dst_rect, &lease);
673 lease.submit_in_flight();
674 let _: usize = node_style.get_frame_pool().retire_fence(next_fence);
675 }
676 }
677 #[cfg(not(target_arch = "wasm32"))]
678 {
679 let elapsed_ms: f32 = (t0.elapsed().as_nanos() as f32) * 1.0e-6;
680 node_style.set_last_render_ms(elapsed_ms);
681 }
682 node_style.refresh_stats();
683 }
684}