Skip to main content

euv_core/game/fluid/scene/
impl.rs

1use super::*;
2
3/// Default handheld gyroscope liquid water game scene.
4impl Default for GyroLiquidGameScene {
5    /// Creates a `GyroLiquidGameScene` configured with `GyroLiquidConfig::default()`.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - Shareable liquid water game scene handle.
10    fn default() -> Self {
11        Self::with_config(GyroLiquidConfig::default())
12    }
13}
14
15/// Internal state construction and telemetry refresh helpers for `GyroLiquidSceneState`.
16impl GyroLiquidSceneState {
17    /// Constructs an initialized `GyroLiquidSceneState` with pre-warmed snapshots and bounded frame pool.
18    ///
19    /// # Arguments
20    ///
21    /// - `GyroLiquidConfig` - Physical simulation configuration.
22    ///
23    /// # Returns
24    ///
25    /// - `Self` - Ready scene state.
26    #[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    /// Recomputes `GyroLiquidStats` from current solver, renderer, and sensor fields.
56    ///
57    /// # Arguments
58    ///
59    /// - `&Self` - Mutable scene state.
60    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    /// Resolves the active hardware `DeviceMotionSample` from explicit injection, bound reactive signal, or thread-local sensor stream.
88    ///
89    /// # Arguments
90    ///
91    /// - `&Self` - Scene state reference.
92    ///
93    /// # Returns
94    ///
95    /// - `Option<DeviceMotionSample>` - Active sensor sample when live hardware input should drive this tick.
96    #[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
122/// Interactive physics controls, sensor bindings, telemetry inspection, and offscreen pooled rendering on `GyroLiquidGameScene`.
123impl GyroLiquidGameScene {
124    /// Creates a new `GyroLiquidGameScene` with custom physical `config`.
125    ///
126    /// # Arguments
127    ///
128    /// - `GyroLiquidConfig` - Physical container, fill ratio, viscosity, and solver configuration.
129    ///
130    /// # Returns
131    ///
132    /// - `Self` - Shareable liquid water game scene handle.
133    #[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    /// Binds a reactive `Signal<DeviceMotionSample>` (e.g. from `use_device_motion()`) so live hardware sensor updates drive the liquid seamlessly.
141    ///
142    /// # Arguments
143    ///
144    /// - `&Self` - Liquid game scene handle.
145    /// - `Signal<DeviceMotionSample>` - Reactive device motion signal.
146    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    /// Injects an explicit `DeviceMotionSample` (useful for live custom bridges or deterministic testing) and clears it when passed `None`.
153    ///
154    /// # Arguments
155    ///
156    /// - `&Self` - Liquid game scene handle.
157    /// - `Option<DeviceMotionSample>` - Hardware or synthetic motion sample.
158    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    /// Selects the sensor input mode (`Auto`, `LiveHardware`, or `VirtualTilt`).
165    ///
166    /// # Arguments
167    ///
168    /// - `&Self` - Liquid game scene handle.
169    /// - `FluidSensorMode` - Desired sensor driving mode.
170    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    /// Sets virtual desktop/simulator tilt angles (`roll_rad`, `pitch_rad`).
178    ///
179    /// # Arguments
180    ///
181    /// - `&Self` - Liquid game scene handle.
182    /// - `f32` - In-plane roll angle in radians (`0.0` = upright, `+π/2` = clockwise right-down).
183    /// - `f32` - Out-of-plane pitch angle in radians (`0.0` = upright vertical, `+π/2` = face-up flat).
184    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    /// Rotates the virtual container angle by `delta_rad` radians (positive clockwise in screen space).
194    ///
195    /// # Arguments
196    ///
197    /// - `&Self` - Liquid game scene handle.
198    /// - `f32` - Rotation increment in radians.
199    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    /// Injects a physical linear frame shake acceleration impulse `(ax, ay)` in `m/s²`.
207    ///
208    /// # Arguments
209    ///
210    /// - `&Self` - Liquid game scene handle.
211    /// - `f32` - Horizontal shake acceleration in `m/s²`.
212    /// - `f32` - Vertical shake acceleration in `m/s²`.
213    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    /// Applies a direct pointer/touch stirring wake impulse at normalized vessel coordinates `(norm_x, norm_y)`.
220    ///
221    /// # Arguments
222    ///
223    /// - `&Self` - Liquid game scene handle.
224    /// - `f32` - Normalized x-coordinate in `[0.0, 1.0]`.
225    /// - `f32` - Normalized y-coordinate in `[0.0, 1.0]`.
226    /// - `f32` - Stir velocity x-component in `m/s`.
227    /// - `f32` - Stir velocity y-component in `m/s`.
228    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    /// Updates the liquid fill ratio (`0.20..=0.85`) and captures a discontinuous snapshot cleanly.
237    ///
238    /// # Arguments
239    ///
240    /// - `&Self` - Liquid game scene handle.
241    /// - `f32` - Target fill fraction in `[0.20, 0.85]`.
242    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    /// Updates the relative liquid viscosity (`0.2..=6.0`, where `1.0` = 20 °C pure water).
256    ///
257    /// # Arguments
258    ///
259    /// - `&Self` - Liquid game scene handle.
260    /// - `f32` - Relative viscosity multiplier.
261    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    /// Updates the relative liquid surface tension (`0.0..=3.0`, where `1.0` = `0.0728 N/m`).
268    ///
269    /// # Arguments
270    ///
271    /// - `&Self` - Liquid game scene handle.
272    /// - `f32` - Relative surface tension multiplier.
273    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    /// Enables or disables Archimedes buoyant floating objects (orb + ice cube).
282    ///
283    /// # Arguments
284    ///
285    /// - `&Self` - Liquid game scene handle.
286    /// - `bool` - Whether floating buoyant objects are active.
287    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    /// Resets the water, buoyant objects, bubbles, and virtual tilt to a calm upright resting pool.
303    ///
304    /// # Arguments
305    ///
306    /// - `&Self` - Liquid game scene handle.
307    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    /// Returns the latest read-only `GyroLiquidStats` telemetry snapshot.
324    ///
325    /// # Arguments
326    ///
327    /// - `&Self` - Liquid game scene handle.
328    ///
329    /// # Returns
330    ///
331    /// - `GyroLiquidStats` - Current live telemetry struct.
332    #[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    /// Returns the liquid center of mass `(x_m, y_m)` in SI meters inside the physical vessel.
341    ///
342    /// # Arguments
343    ///
344    /// - `&Self` - Liquid game scene handle.
345    ///
346    /// # Returns
347    ///
348    /// - `(f32, f32)` - Center of mass in meters.
349    #[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    /// Copies the currently active buoyant bodies for inspection or HUD overlays.
360    ///
361    /// # Arguments
362    ///
363    /// - `&Self` - Liquid game scene handle.
364    ///
365    /// # Returns
366    ///
367    /// - `Vec<BuoyantBody>` - Active buoyant rigid body states.
368    #[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    /// Returns `true` if any active particle or buoyant body has NaN/Inf state or escaped container bounds.
380    ///
381    /// # Arguments
382    ///
383    /// - `&Self` - Liquid game scene handle.
384    ///
385    /// # Returns
386    ///
387    /// - `bool` - Whether solver state is invalid or escaped.
388    #[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    /// Returns the active explicit optical resolution scale multiplier (`1.0` default = lossless 1:1 physical pixels).
399    ///
400    /// # Arguments
401    ///
402    /// - `&Self` - Liquid game scene handle.
403    ///
404    /// # Returns
405    ///
406    /// - `f32` - Active resolution scale multiplier in `[FLUID_MIN_RESOLUTION_SCALE, FLUID_MAX_RESOLUTION_SCALE]`.
407    #[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    /// Configures an explicit user optical resolution scale multiplier (`1.0` = lossless native 1:1 physical pixels).
416    ///
417    /// # Arguments
418    ///
419    /// - `&Self` - Liquid game scene handle.
420    /// - `f32` - Desired quality scale multiplier clamped to `[FLUID_MIN_RESOLUTION_SCALE, FLUID_MAX_RESOLUTION_SCALE]`.
421    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    /// Renders the interpolated liquid scene directly into the internal `RenderBufferPool` for offscreen inspection or custom blitting.
433    ///
434    /// # Arguments
435    ///
436    /// - `&Self` - Liquid game scene handle.
437    /// - `u32` - Target viewport width in logical pixels.
438    /// - `u32` - Target viewport height in logical pixels.
439    /// - `f32` - Interpolation alpha in `[0.0, 1.0]`.
440    ///
441    /// # Returns
442    ///
443    /// - `Option<PooledFrameLease>` - Rendered zero-copy RGBA8 frame lease.
444    #[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
490/// `GameScene` integration driving fixed-step SI liquid physics, sensor ingestion, pointer stirring, and zero-copy pooled optical rendering inside `GameEngineHost`.
491impl GameScene for GyroLiquidGameScene {
492    /// Advances SI PBF liquid physics by one fixed timestep `dt` using live hardware sensors (or virtual tilt) plus pointer stirring and keyboard controls.
493    ///
494    /// # Arguments
495    ///
496    /// - `&Self` - Mutable liquid scene handle.
497    /// - `f32` - Fixed simulation timestep in seconds.
498    /// - `&InputState` - Real-time polled pointer and keyboard input state.
499    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    /// Renders the photorealistic optical water into the bounded `RenderBufferPool` and blits it zero-copy into `ctx`, adapting cleanly to arbitrary resize and fullscreen bounds.
583    ///
584    /// # Arguments
585    ///
586    /// - `&Self` - Mutable liquid scene handle.
587    /// - `f32` - Render interpolation alpha in `[0.0, 1.0]`.
588    /// - `&mut GameRenderContext<'_>` - Active viewport draw surface.
589    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}