euv-core 0.48.1

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
use super::*;

/// Default handheld gyroscope liquid water game scene.
impl Default for GyroLiquidGameScene {
    /// Creates a `GyroLiquidGameScene` configured with `GyroLiquidConfig::default()`.
    ///
    /// # Returns
    ///
    /// - `Self` - Shareable liquid water game scene handle.
    fn default() -> Self {
        Self::with_config(GyroLiquidConfig::default())
    }
}

/// Internal state construction and telemetry refresh helpers for `GyroLiquidSceneState`.
impl GyroLiquidSceneState {
    /// Constructs an initialized `GyroLiquidSceneState` with pre-warmed snapshots and bounded frame pool.
    ///
    /// # Arguments
    ///
    /// - `GyroLiquidConfig` - Physical simulation configuration.
    ///
    /// # Returns
    ///
    /// - `Self` - Ready scene state.
    #[must_use]
    pub(crate) fn with_config(config: GyroLiquidConfig) -> Self {
        let solver: LiquidFluidSolver = LiquidFluidSolver::with_config(config);
        let mut init_snap: FluidSimSnapshot = FluidSimSnapshot::default();
        solver.capture_snapshot_into(&mut init_snap);
        let snapshots: DoubleBufferedSnapshot<FluidSimSnapshot> =
            DoubleBufferedSnapshot::new(init_snap);
        let renderer: LiquidOpticalRenderer = LiquidOpticalRenderer::new_renderer();
        let frame_pool: RenderBufferPool = RenderBufferPool::with_capacity(FLUID_SCENE_POOL_SLOTS);
        let mut state: Self = Self {
            solver,
            snapshots,
            renderer,
            frame_pool,
            frame_fence: 0,
            sensor_mode: FluidSensorMode::Auto,
            device_motion_signal: None,
            manual_motion_sample: None,
            sensor_active: false,
            last_viewport_bounds: Rect::new(0.0, 0.0, 640.0, 480.0),
            last_sim_ms: 0.0,
            last_render_ms: 0.0,
            stats: GyroLiquidStats::default(),
        };
        state.refresh_stats();
        state
    }

    /// Recomputes `GyroLiquidStats` from current solver, renderer, and sensor fields.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene state.
    pub(crate) fn refresh_stats(&mut self) {
        let solver: &LiquidFluidSolver = self.get_solver();
        let cfg: GyroLiquidConfig = solver.get_config();
        let ren: &LiquidOpticalRenderer = self.get_renderer();
        let next: GyroLiquidStats = GyroLiquidStats {
            particle_count: solver.get_particle_count(),
            bubble_count: solver.get_bubble_count(),
            buoyant_body_count: solver.get_buoyant_body_count(),
            kinetic_energy_mj: solver.get_kinetic_energy_mj(),
            gravity_x: solver.get_gravity_x(),
            gravity_y: solver.get_gravity_y(),
            gravity_z: solver.get_gravity_z(),
            tilt_angle_deg: solver.get_active_roll_rad().to_degrees(),
            peak_wave_height_m: solver.get_peak_wave_height_m(),
            sim_time_ms: self.get_last_sim_ms(),
            render_time_ms: self.get_last_render_ms(),
            sensor_mode: self.get_sensor_mode(),
            sensor_active: self.get_sensor_active(),
            vessel_width_m: cfg.get_vessel_width_m(),
            vessel_height_m: cfg.get_vessel_height_m(),
            fill_ratio: cfg.get_fill_ratio(),
            render_width: ren.get_last_width(),
            render_height: ren.get_last_height(),
        };
        self.set_stats(next);
    }

    /// Resolves the active hardware `DeviceMotionSample` from explicit injection, bound reactive signal, or thread-local sensor stream.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene state reference.
    ///
    /// # Returns
    ///
    /// - `Option<DeviceMotionSample>` - Active sensor sample when live hardware input should drive this tick.
    #[must_use]
    pub(crate) fn resolve_active_sensor_sample(&self) -> Option<DeviceMotionSample> {
        if self.get_sensor_mode() == FluidSensorMode::VirtualTilt {
            return None;
        }
        if let Some(manual) = self.get_manual_motion_sample() {
            return Some(manual);
        }
        if let Some(sig) = self.get_device_motion_signal() {
            let sample: DeviceMotionSample = sig.get_untracked();
            if sample.get_sensor_active() || self.get_sensor_mode() == FluidSensorMode::LiveHardware
            {
                return Some(sample);
            }
        }
        let latest: DeviceMotionSample = latest_device_motion();
        if latest.get_sensor_active() {
            return Some(latest);
        }
        if self.get_sensor_mode() == FluidSensorMode::LiveHardware {
            return Some(latest);
        }
        None
    }
}

/// Interactive physics controls, sensor bindings, telemetry inspection, and offscreen pooled rendering on `GyroLiquidGameScene`.
impl GyroLiquidGameScene {
    /// Creates a new `GyroLiquidGameScene` with custom physical `config`.
    ///
    /// # Arguments
    ///
    /// - `GyroLiquidConfig` - Physical container, fill ratio, viscosity, and solver configuration.
    ///
    /// # Returns
    ///
    /// - `Self` - Shareable liquid water game scene handle.
    #[must_use]
    pub fn with_config(config: GyroLiquidConfig) -> Self {
        Self {
            inner: Rc::new(RefCell::new(GyroLiquidSceneState::with_config(config))),
        }
    }

    /// Binds a reactive `Signal<DeviceMotionSample>` (e.g. from `use_device_motion()`) so live hardware sensor updates drive the liquid seamlessly.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Liquid game scene handle.
    /// - `Signal<DeviceMotionSample>` - Reactive device motion signal.
    pub fn bind_device_motion(&self, signal: Signal<DeviceMotionSample>) {
        if let Ok(mut st) = self.get_inner().try_borrow_mut() {
            st.set_device_motion_signal(Some(signal));
        }
    }

    /// Injects an explicit `DeviceMotionSample` (useful for live custom bridges or deterministic testing) and clears it when passed `None`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Liquid game scene handle.
    /// - `Option<DeviceMotionSample>` - Hardware or synthetic motion sample.
    pub fn set_device_motion(&self, sample: Option<DeviceMotionSample>) {
        if let Ok(mut st) = self.get_inner().try_borrow_mut() {
            st.set_manual_motion_sample(sample);
        }
    }

    /// Selects the sensor input mode (`Auto`, `LiveHardware`, or `VirtualTilt`).
    ///
    /// # Arguments
    ///
    /// - `&Self` - Liquid game scene handle.
    /// - `FluidSensorMode` - Desired sensor driving mode.
    pub fn set_sensor_mode(&self, mode: FluidSensorMode) {
        if let Ok(mut st) = self.get_inner().try_borrow_mut() {
            st.set_sensor_mode(mode);
            st.refresh_stats();
        }
    }

    /// Sets virtual desktop/simulator tilt angles (`roll_rad`, `pitch_rad`).
    ///
    /// # Arguments
    ///
    /// - `&Self` - Liquid game scene handle.
    /// - `f32` - In-plane roll angle in radians (`0.0` = upright, `+Ï€/2` = clockwise right-down).
    /// - `f32` - Out-of-plane pitch angle in radians (`0.0` = upright vertical, `+Ï€/2` = face-up flat).
    pub fn set_virtual_tilt(&self, roll_rad: f32, pitch_rad: f32) {
        if let Ok(mut st) = self.get_inner().try_borrow_mut() {
            st.get_mut_solver().set_virtual_tilt(roll_rad, pitch_rad);
            st.refresh_stats();
        }
    }

    /// Rotates the virtual container angle by `delta_rad` radians (positive clockwise in screen space).
    ///
    /// # Arguments
    ///
    /// - `&Self` - Liquid game scene handle.
    /// - `f32` - Rotation increment in radians.
    pub fn rotate_container_by(&self, delta_rad: f32) {
        if let Ok(mut st) = self.get_inner().try_borrow_mut() {
            st.get_mut_solver().rotate_container_by(delta_rad);
            st.refresh_stats();
        }
    }

    /// Injects a physical linear frame shake acceleration impulse `(ax, ay)` in `m/s²`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Liquid game scene handle.
    /// - `f32` - Horizontal shake acceleration in `m/s²`.
    /// - `f32` - Vertical shake acceleration in `m/s²`.
    pub fn apply_shake_impulse(&self, ax: f32, ay: f32) {
        if let Ok(mut st) = self.get_inner().try_borrow_mut() {
            st.get_mut_solver().apply_shake_impulse(ax, ay);
        }
    }

    /// Applies a direct pointer/touch stirring wake impulse at normalized vessel coordinates `(norm_x, norm_y)`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Liquid game scene handle.
    /// - `f32` - Normalized x-coordinate in `[0.0, 1.0]`.
    /// - `f32` - Normalized y-coordinate in `[0.0, 1.0]`.
    /// - `f32` - Stir velocity x-component in `m/s`.
    /// - `f32` - Stir velocity y-component in `m/s`.
    pub fn apply_stir_impulse(&self, norm_x: f32, norm_y: f32, vel_x_mps: f32, vel_y_mps: f32) {
        if let Ok(mut st) = self.get_inner().try_borrow_mut() {
            st.get_mut_solver()
                .apply_stir_impulse(norm_x, norm_y, vel_x_mps, vel_y_mps);
        }
    }

    /// Updates the liquid fill ratio (`0.20..=0.85`) and captures a discontinuous snapshot cleanly.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Liquid game scene handle.
    /// - `f32` - Target fill fraction in `[0.20, 0.85]`.
    pub fn set_fill_ratio(&self, fill_ratio: f32) {
        if let Ok(mut st) = self.get_inner().try_borrow_mut() {
            st.get_mut_solver().set_fill_ratio(fill_ratio);
            let GyroLiquidSceneState {
                solver, snapshots, ..
            } = &mut *st;
            snapshots.capture_discontinuous_into(|dst: &mut FluidSimSnapshot| {
                solver.capture_snapshot_into(dst);
            });
            st.refresh_stats();
        }
    }

    /// Updates the relative liquid viscosity (`0.2..=6.0`, where `1.0` = 20 °C pure water).
    ///
    /// # Arguments
    ///
    /// - `&Self` - Liquid game scene handle.
    /// - `f32` - Relative viscosity multiplier.
    pub fn set_viscosity(&self, viscosity: f32) {
        if let Ok(mut st) = self.get_inner().try_borrow_mut() {
            st.get_mut_solver().set_viscosity(viscosity);
        }
    }

    /// Updates the relative liquid surface tension (`0.0..=3.0`, where `1.0` = `0.0728 N/m`).
    ///
    /// # Arguments
    ///
    /// - `&Self` - Liquid game scene handle.
    /// - `f32` - Relative surface tension multiplier.
    pub fn set_surface_tension(&self, surface_tension: f32) {
        if let Ok(mut st) = self.get_inner().try_borrow_mut() {
            st.get_mut_solver().set_surface_tension(surface_tension);
        }
    }

    /// Enables or disables Archimedes buoyant floating objects (orb + ice cube).
    ///
    /// # Arguments
    ///
    /// - `&Self` - Liquid game scene handle.
    /// - `bool` - Whether floating buoyant objects are active.
    pub fn set_buoyant_bodies_enabled(&self, enabled: bool) {
        if let Ok(mut st) = self.get_inner().try_borrow_mut() {
            st.get_mut_solver().set_buoyant_bodies_enabled(enabled);
            let GyroLiquidSceneState {
                solver, snapshots, ..
            } = &mut *st;
            snapshots.capture_discontinuous_into(|dst: &mut FluidSimSnapshot| {
                solver.capture_snapshot_into(dst);
            });
            st.refresh_stats();
        }
    }

    /// Resets the water, buoyant objects, bubbles, and virtual tilt to a calm upright resting pool.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Liquid game scene handle.
    pub fn reset_water(&self) {
        if let Ok(mut st) = self.get_inner().try_borrow_mut() {
            st.get_mut_solver().set_virtual_tilt(0.0, 0.0);
            st.get_mut_solver().set_prev_virtual_roll_rad(0.0);
            st.get_mut_solver().reset_water();
            let GyroLiquidSceneState {
                solver, snapshots, ..
            } = &mut *st;
            snapshots.capture_discontinuous_into(|dst: &mut FluidSimSnapshot| {
                solver.capture_snapshot_into(dst);
            });
            st.refresh_stats();
        }
    }

    /// Returns the latest read-only `GyroLiquidStats` telemetry snapshot.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Liquid game scene handle.
    ///
    /// # Returns
    ///
    /// - `GyroLiquidStats` - Current live telemetry struct.
    #[must_use]
    pub fn stats(&self) -> GyroLiquidStats {
        self.get_inner()
            .try_borrow()
            .map(|st: Ref<'_, GyroLiquidSceneState>| st.get_stats())
            .unwrap_or_default()
    }

    /// Returns the liquid center of mass `(x_m, y_m)` in SI meters inside the physical vessel.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Liquid game scene handle.
    ///
    /// # Returns
    ///
    /// - `(f32, f32)` - Center of mass in meters.
    #[must_use]
    pub fn center_of_mass(&self) -> (f32, f32) {
        self.get_inner()
            .try_borrow()
            .map(|st: Ref<'_, GyroLiquidSceneState>| st.get_solver().center_of_mass())
            .unwrap_or((DEFAULT_VESSEL_WIDTH_M * 0.5, DEFAULT_VESSEL_HEIGHT_M * 0.5))
    }

    /// Copies the currently active buoyant bodies for inspection or HUD overlays.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Liquid game scene handle.
    ///
    /// # Returns
    ///
    /// - `Vec<BuoyantBody>` - Active buoyant rigid body states.
    #[must_use]
    pub fn buoyant_bodies(&self) -> Vec<BuoyantBody> {
        self.get_inner()
            .try_borrow()
            .map(|st: Ref<'_, GyroLiquidSceneState>| {
                let cnt: usize = st.get_solver().get_buoyant_body_count();
                st.get_solver().get_buoyant_bodies()[..cnt].to_vec()
            })
            .unwrap_or_default()
    }

    /// Returns `true` if any active particle or buoyant body has NaN/Inf state or escaped container bounds.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Liquid game scene handle.
    ///
    /// # Returns
    ///
    /// - `bool` - Whether solver state is invalid or escaped.
    #[must_use]
    pub fn has_invalid_or_escaped_state(&self) -> bool {
        self.get_inner()
            .try_borrow()
            .map(|st: Ref<'_, GyroLiquidSceneState>| st.get_solver().has_invalid_or_escaped_state())
            .unwrap_or(false)
    }

    /// Renders the interpolated liquid scene directly into the internal `RenderBufferPool` for offscreen inspection or custom blitting.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Liquid game scene handle.
    /// - `u32` - Target viewport width in logical pixels.
    /// - `u32` - Target viewport height in logical pixels.
    /// - `f32` - Interpolation alpha in `[0.0, 1.0]`.
    ///
    /// # Returns
    ///
    /// - `Option<PooledFrameLease>` - Rendered zero-copy RGBA8 frame lease.
    #[must_use]
    pub fn render_to_pooled_frame(
        &self,
        viewport_w: u32,
        viewport_h: u32,
        alpha: f32,
    ) -> Option<PooledFrameLease> {
        let mut st: RefMut<'_, GyroLiquidSceneState> = self.get_inner().try_borrow_mut().ok()?;
        let vw: u32 = viewport_w.max(FLUID_RENDER_MIN_DIM);
        let vh: u32 = viewport_h.max(FLUID_RENDER_MIN_DIM);
        st.get_mut_solver()
            .adapt_vessel_aspect((vw as f32) / (vh as f32));
        let next_fence: u64 = st.get_frame_fence().saturating_add(1);
        st.set_frame_fence(next_fence);
        #[cfg(not(target_arch = "wasm32"))]
        let t0: Instant = Instant::now();
        let lease: Option<PooledFrameLease> = {
            let GyroLiquidSceneState {
                snapshots,
                renderer,
                frame_pool,
                ..
            } = &mut *st;
            let snap: &FluidSimSnapshot = snapshots.sample_cached(alpha);
            renderer.render_snapshot_into_pool(snap, vw, vh, frame_pool, next_fence)
        };
        #[cfg(not(target_arch = "wasm32"))]
        {
            let elapsed_ms: f32 = (t0.elapsed().as_nanos() as f32) * 1.0e-6;
            st.set_last_render_ms(elapsed_ms);
        }
        st.refresh_stats();
        lease
    }
}

/// `GameScene` integration driving fixed-step SI liquid physics, sensor ingestion, pointer stirring, and zero-copy pooled optical rendering inside `GameEngineHost`.
impl GameScene for GyroLiquidGameScene {
    /// Advances SI PBF liquid physics by one fixed timestep `dt` using live hardware sensors (or virtual tilt) plus pointer stirring and keyboard controls.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable liquid scene handle.
    /// - `f32` - Fixed simulation timestep in seconds.
    /// - `&InputState` - Real-time polled pointer and keyboard input state.
    fn fixed_update(&mut self, dt: f32, input: &InputState) {
        let Ok(mut st) = self.get_inner().try_borrow_mut() else {
            return;
        };
        #[cfg(not(target_arch = "wasm32"))]
        let t0: Instant = Instant::now();
        let safe_dt: f32 = dt.clamp(1.0 / 480.0, FLUID_MAX_STEP_DT);
        let sensor_opt: Option<DeviceMotionSample> = st.resolve_active_sensor_sample();
        if let Some(sample) = sensor_opt {
            st.set_sensor_active(sample.get_sensor_active());
            st.get_mut_solver().apply_device_motion(sample, safe_dt);
        } else {
            st.set_sensor_active(false);
            let roll_axis: f32 = input.axis(KeyCode::ArrowLeft, KeyCode::ArrowRight)
                + input.axis(
                    KeyCode::Character(FLUID_KEY_CHAR_LEFT),
                    KeyCode::Character(FLUID_KEY_CHAR_RIGHT),
                );
            let pitch_axis: f32 = input.axis(KeyCode::ArrowDown, KeyCode::ArrowUp)
                + input.axis(
                    KeyCode::Character(FLUID_KEY_CHAR_DOWN),
                    KeyCode::Character(FLUID_KEY_CHAR_UP),
                );
            if roll_axis.abs() > 0.01 {
                st.get_mut_solver().rotate_container_by(
                    roll_axis.clamp(-1.0, 1.0) * FLUID_KEY_ROLL_SPEED_RAD_S * safe_dt,
                );
            }
            if pitch_axis.abs() > 0.01 {
                let cur_roll: f32 = st.get_solver().get_virtual_roll_rad();
                let next_pitch: f32 = st.get_solver().get_virtual_pitch_rad()
                    + pitch_axis.clamp(-1.0, 1.0) * FLUID_KEY_PITCH_SPEED_RAD_S * safe_dt;
                st.get_mut_solver().set_virtual_tilt(cur_roll, next_pitch);
            }
            st.get_mut_solver().sync_virtual_motion(safe_dt);
        }
        if input.is_key_just_pressed(KeyCode::Space) {
            st.get_mut_solver()
                .apply_shake_impulse(FLUID_KEY_SHAKE_X_MPS2, FLUID_KEY_SHAKE_Y_MPS2);
        }
        if input.is_key_just_pressed(KeyCode::Character(FLUID_KEY_CHAR_RESET)) {
            st.get_mut_solver().set_virtual_tilt(0.0, 0.0);
            st.get_mut_solver().set_prev_virtual_roll_rad(0.0);
            st.get_mut_solver().reset_water();
        }
        if input.is_button_down(PointerButton::Primary) {
            let vp: Rect = st.get_last_viewport_bounds();
            let bw: f32 = vp.get_width().max(1.0);
            let bh: f32 = vp.get_height().max(1.0);
            let ptr: Point = input.get_pointer_position();
            let delta: Point = input.get_pointer_delta();
            let nx: f32 = (ptr.get_x() - vp.get_x()) / bw;
            let ny: f32 = (ptr.get_y() - vp.get_y()) / bh;
            if (0.0..=1.0).contains(&nx) && (0.0..=1.0).contains(&ny) {
                let d_mag: f32 = delta.get_x().hypot(delta.get_y());
                if d_mag > 0.25 {
                    let vw_m: f32 = st.get_solver().get_config().get_vessel_width_m();
                    let vh_m: f32 = st.get_solver().get_config().get_vessel_height_m();
                    let vx_mps: f32 = (delta.get_x() / bw) * vw_m / safe_dt;
                    let vy_mps: f32 = (delta.get_y() / bh) * vh_m / safe_dt;
                    st.get_mut_solver()
                        .apply_stir_impulse(nx, ny, vx_mps, vy_mps);
                }
            }
        }
        st.get_mut_solver().step(safe_dt);
        {
            let GyroLiquidSceneState {
                solver, snapshots, ..
            } = &mut *st;
            snapshots.capture_into(|dst: &mut FluidSimSnapshot| {
                solver.capture_snapshot_into(dst);
            });
        }
        #[cfg(not(target_arch = "wasm32"))]
        {
            let elapsed_ms: f32 = (t0.elapsed().as_nanos() as f32) * 1.0e-6;
            st.set_last_sim_ms(elapsed_ms);
        }
        st.refresh_stats();
    }

    /// Renders the photorealistic optical water into the bounded `RenderBufferPool` and blits it zero-copy into `ctx`, adapting cleanly to arbitrary resize and fullscreen bounds.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable liquid scene handle.
    /// - `f32` - Render interpolation alpha in `[0.0, 1.0]`.
    /// - `&mut GameRenderContext<'_>` - Active viewport draw surface.
    fn render(&mut self, alpha: f32, ctx: &mut GameRenderContext<'_>) {
        let Ok(mut st) = self.get_inner().try_borrow_mut() else {
            return;
        };
        let bounds: Rect = ctx.bounds;
        let vp_w: f32 = bounds.get_width().max(64.0);
        let vp_h: f32 = bounds.get_height().max(64.0);
        let dpr: f32 = ctx.scale_factor().clamp(1.0, 3.0);
        let target_phys_w: u32 = (vp_w * dpr).round().max(64.0) as u32;
        let target_phys_h: u32 = (vp_h * dpr).round().max(64.0) as u32;
        st.set_last_viewport_bounds(bounds);
        st.get_mut_solver().adapt_vessel_aspect(vp_w / vp_h);
        let next_fence: u64 = st.get_frame_fence().saturating_add(1);
        st.set_frame_fence(next_fence);
        #[cfg(not(target_arch = "wasm32"))]
        let t0: Instant = Instant::now();
        let lease_opt: Option<PooledFrameLease> = {
            let GyroLiquidSceneState {
                snapshots,
                renderer,
                frame_pool,
                ..
            } = &mut *st;
            let snap: &FluidSimSnapshot = snapshots.sample_cached(alpha);
            renderer.render_snapshot_into_pool(
                snap,
                target_phys_w,
                target_phys_h,
                frame_pool,
                next_fence,
            )
        };
        if let Some(lease) = lease_opt {
            let dst_rect: Rect = Rect::new(0.0, 0.0, vp_w, vp_h);
            ctx.blit_pooled_frame(dst_rect, &lease);
            lease.submit_in_flight();
            let _: usize = st.get_frame_pool().retire_fence(next_fence);
        }
        #[cfg(not(target_arch = "wasm32"))]
        {
            let elapsed_ms: f32 = (t0.elapsed().as_nanos() as f32) * 1.0e-6;
            st.set_last_render_ms(elapsed_ms);
        }
        st.refresh_stats();
    }
}