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        };
50        state.refresh_stats();
51        state
52    }
53
54    /// Recomputes `GyroLiquidStats` from current solver, renderer, and sensor fields.
55    ///
56    /// # Arguments
57    ///
58    /// - `&Self` - Mutable scene state.
59    pub(crate) fn refresh_stats(&mut self) {
60        let solver: &LiquidFluidSolver = self.get_solver();
61        let cfg: GyroLiquidConfig = solver.get_config();
62        let ren: &LiquidOpticalRenderer = self.get_renderer();
63        let next: GyroLiquidStats = GyroLiquidStats {
64            particle_count: solver.get_particle_count(),
65            bubble_count: solver.get_bubble_count(),
66            buoyant_body_count: solver.get_buoyant_body_count(),
67            kinetic_energy_mj: solver.get_kinetic_energy_mj(),
68            gravity_x: solver.get_gravity_x(),
69            gravity_y: solver.get_gravity_y(),
70            gravity_z: solver.get_gravity_z(),
71            tilt_angle_deg: solver.get_active_roll_rad().to_degrees(),
72            peak_wave_height_m: solver.get_peak_wave_height_m(),
73            sim_time_ms: self.get_last_sim_ms(),
74            render_time_ms: self.get_last_render_ms(),
75            sensor_mode: self.get_sensor_mode(),
76            sensor_active: self.get_sensor_active(),
77            vessel_width_m: cfg.get_vessel_width_m(),
78            vessel_height_m: cfg.get_vessel_height_m(),
79            fill_ratio: cfg.get_fill_ratio(),
80            render_width: ren.get_last_width(),
81            render_height: ren.get_last_height(),
82        };
83        self.set_stats(next);
84    }
85
86    /// Resolves the active hardware `DeviceMotionSample` from explicit injection, bound reactive signal, or thread-local sensor stream.
87    ///
88    /// # Arguments
89    ///
90    /// - `&Self` - Scene state reference.
91    ///
92    /// # Returns
93    ///
94    /// - `Option<DeviceMotionSample>` - Active sensor sample when live hardware input should drive this tick.
95    #[must_use]
96    pub(crate) fn resolve_active_sensor_sample(&self) -> Option<DeviceMotionSample> {
97        if self.get_sensor_mode() == FluidSensorMode::VirtualTilt {
98            return None;
99        }
100        if let Some(manual) = self.get_manual_motion_sample() {
101            return Some(manual);
102        }
103        if let Some(sig) = self.get_device_motion_signal() {
104            let sample: DeviceMotionSample = sig.get_untracked();
105            if sample.get_sensor_active() || self.get_sensor_mode() == FluidSensorMode::LiveHardware
106            {
107                return Some(sample);
108            }
109        }
110        let latest: DeviceMotionSample = latest_device_motion();
111        if latest.get_sensor_active() {
112            return Some(latest);
113        }
114        if self.get_sensor_mode() == FluidSensorMode::LiveHardware {
115            return Some(latest);
116        }
117        None
118    }
119}
120
121/// Interactive physics controls, sensor bindings, telemetry inspection, and offscreen pooled rendering on `GyroLiquidGameScene`.
122impl GyroLiquidGameScene {
123    /// Creates a new `GyroLiquidGameScene` with custom physical `config`.
124    ///
125    /// # Arguments
126    ///
127    /// - `GyroLiquidConfig` - Physical container, fill ratio, viscosity, and solver configuration.
128    ///
129    /// # Returns
130    ///
131    /// - `Self` - Shareable liquid water game scene handle.
132    #[must_use]
133    pub fn with_config(config: GyroLiquidConfig) -> Self {
134        Self {
135            inner: Rc::new(RefCell::new(GyroLiquidSceneState::with_config(config))),
136        }
137    }
138
139    /// Binds a reactive `Signal<DeviceMotionSample>` (e.g. from `use_device_motion()`) so live hardware sensor updates drive the liquid seamlessly.
140    ///
141    /// # Arguments
142    ///
143    /// - `&Self` - Liquid game scene handle.
144    /// - `Signal<DeviceMotionSample>` - Reactive device motion signal.
145    pub fn bind_device_motion(&self, signal: Signal<DeviceMotionSample>) {
146        if let Ok(mut st) = self.get_inner().try_borrow_mut() {
147            st.set_device_motion_signal(Some(signal));
148        }
149    }
150
151    /// Injects an explicit `DeviceMotionSample` (useful for live custom bridges or deterministic testing) and clears it when passed `None`.
152    ///
153    /// # Arguments
154    ///
155    /// - `&Self` - Liquid game scene handle.
156    /// - `Option<DeviceMotionSample>` - Hardware or synthetic motion sample.
157    pub fn set_device_motion(&self, sample: Option<DeviceMotionSample>) {
158        if let Ok(mut st) = self.get_inner().try_borrow_mut() {
159            st.set_manual_motion_sample(sample);
160        }
161    }
162
163    /// Selects the sensor input mode (`Auto`, `LiveHardware`, or `VirtualTilt`).
164    ///
165    /// # Arguments
166    ///
167    /// - `&Self` - Liquid game scene handle.
168    /// - `FluidSensorMode` - Desired sensor driving mode.
169    pub fn set_sensor_mode(&self, mode: FluidSensorMode) {
170        if let Ok(mut st) = self.get_inner().try_borrow_mut() {
171            st.set_sensor_mode(mode);
172            st.refresh_stats();
173        }
174    }
175
176    /// Sets virtual desktop/simulator tilt angles (`roll_rad`, `pitch_rad`).
177    ///
178    /// # Arguments
179    ///
180    /// - `&Self` - Liquid game scene handle.
181    /// - `f32` - In-plane roll angle in radians (`0.0` = upright, `+π/2` = clockwise right-down).
182    /// - `f32` - Out-of-plane pitch angle in radians (`0.0` = upright vertical, `+π/2` = face-up flat).
183    pub fn set_virtual_tilt(&self, roll_rad: f32, pitch_rad: f32) {
184        if let Ok(mut st) = self.get_inner().try_borrow_mut() {
185            st.get_mut_solver().set_virtual_tilt(roll_rad, pitch_rad);
186            st.refresh_stats();
187        }
188    }
189
190    /// Rotates the virtual container angle by `delta_rad` radians (positive clockwise in screen space).
191    ///
192    /// # Arguments
193    ///
194    /// - `&Self` - Liquid game scene handle.
195    /// - `f32` - Rotation increment in radians.
196    pub fn rotate_container_by(&self, delta_rad: f32) {
197        if let Ok(mut st) = self.get_inner().try_borrow_mut() {
198            st.get_mut_solver().rotate_container_by(delta_rad);
199            st.refresh_stats();
200        }
201    }
202
203    /// Injects a physical linear frame shake acceleration impulse `(ax, ay)` in `m/s²`.
204    ///
205    /// # Arguments
206    ///
207    /// - `&Self` - Liquid game scene handle.
208    /// - `f32` - Horizontal shake acceleration in `m/s²`.
209    /// - `f32` - Vertical shake acceleration in `m/s²`.
210    pub fn apply_shake_impulse(&self, ax: f32, ay: f32) {
211        if let Ok(mut st) = self.get_inner().try_borrow_mut() {
212            st.get_mut_solver().apply_shake_impulse(ax, ay);
213        }
214    }
215
216    /// Applies a direct pointer/touch stirring wake impulse at normalized vessel coordinates `(norm_x, norm_y)`.
217    ///
218    /// # Arguments
219    ///
220    /// - `&Self` - Liquid game scene handle.
221    /// - `f32` - Normalized x-coordinate in `[0.0, 1.0]`.
222    /// - `f32` - Normalized y-coordinate in `[0.0, 1.0]`.
223    /// - `f32` - Stir velocity x-component in `m/s`.
224    /// - `f32` - Stir velocity y-component in `m/s`.
225    pub fn apply_stir_impulse(&self, norm_x: f32, norm_y: f32, vel_x_mps: f32, vel_y_mps: f32) {
226        if let Ok(mut st) = self.get_inner().try_borrow_mut() {
227            st.get_mut_solver()
228                .apply_stir_impulse(norm_x, norm_y, vel_x_mps, vel_y_mps);
229        }
230    }
231
232    /// Updates the liquid fill ratio (`0.20..=0.85`) and captures a discontinuous snapshot cleanly.
233    ///
234    /// # Arguments
235    ///
236    /// - `&Self` - Liquid game scene handle.
237    /// - `f32` - Target fill fraction in `[0.20, 0.85]`.
238    pub fn set_fill_ratio(&self, fill_ratio: f32) {
239        if let Ok(mut st) = self.get_inner().try_borrow_mut() {
240            st.get_mut_solver().set_fill_ratio(fill_ratio);
241            let GyroLiquidSceneState {
242                solver, snapshots, ..
243            } = &mut *st;
244            snapshots.capture_discontinuous_into(|dst: &mut FluidSimSnapshot| {
245                solver.capture_snapshot_into(dst);
246            });
247            st.refresh_stats();
248        }
249    }
250
251    /// Updates the relative liquid viscosity (`0.2..=6.0`, where `1.0` = 20 °C pure water).
252    ///
253    /// # Arguments
254    ///
255    /// - `&Self` - Liquid game scene handle.
256    /// - `f32` - Relative viscosity multiplier.
257    pub fn set_viscosity(&self, viscosity: f32) {
258        if let Ok(mut st) = self.get_inner().try_borrow_mut() {
259            st.get_mut_solver().set_viscosity(viscosity);
260        }
261    }
262
263    /// Updates the relative liquid surface tension (`0.0..=3.0`, where `1.0` = `0.0728 N/m`).
264    ///
265    /// # Arguments
266    ///
267    /// - `&Self` - Liquid game scene handle.
268    /// - `f32` - Relative surface tension multiplier.
269    pub fn set_surface_tension(&self, surface_tension: f32) {
270        if let Ok(mut st) = self.get_inner().try_borrow_mut() {
271            st.get_mut_solver().set_surface_tension(surface_tension);
272        }
273    }
274
275    /// Enables or disables Archimedes buoyant floating objects (orb + ice cube).
276    ///
277    /// # Arguments
278    ///
279    /// - `&Self` - Liquid game scene handle.
280    /// - `bool` - Whether floating buoyant objects are active.
281    pub fn set_buoyant_bodies_enabled(&self, enabled: bool) {
282        if let Ok(mut st) = self.get_inner().try_borrow_mut() {
283            st.get_mut_solver().set_buoyant_bodies_enabled(enabled);
284            let GyroLiquidSceneState {
285                solver, snapshots, ..
286            } = &mut *st;
287            snapshots.capture_discontinuous_into(|dst: &mut FluidSimSnapshot| {
288                solver.capture_snapshot_into(dst);
289            });
290            st.refresh_stats();
291        }
292    }
293
294    /// Resets the water, buoyant objects, bubbles, and virtual tilt to a calm upright resting pool.
295    ///
296    /// # Arguments
297    ///
298    /// - `&Self` - Liquid game scene handle.
299    pub fn reset_water(&self) {
300        if let Ok(mut st) = self.get_inner().try_borrow_mut() {
301            st.get_mut_solver().set_virtual_tilt(0.0, 0.0);
302            st.get_mut_solver().set_prev_virtual_roll_rad(0.0);
303            st.get_mut_solver().reset_water();
304            let GyroLiquidSceneState {
305                solver, snapshots, ..
306            } = &mut *st;
307            snapshots.capture_discontinuous_into(|dst: &mut FluidSimSnapshot| {
308                solver.capture_snapshot_into(dst);
309            });
310            st.refresh_stats();
311        }
312    }
313
314    /// Returns the latest read-only `GyroLiquidStats` telemetry snapshot.
315    ///
316    /// # Arguments
317    ///
318    /// - `&Self` - Liquid game scene handle.
319    ///
320    /// # Returns
321    ///
322    /// - `GyroLiquidStats` - Current live telemetry struct.
323    #[must_use]
324    pub fn stats(&self) -> GyroLiquidStats {
325        self.get_inner()
326            .try_borrow()
327            .map(|st: Ref<'_, GyroLiquidSceneState>| st.get_stats())
328            .unwrap_or_default()
329    }
330
331    /// Returns the liquid center of mass `(x_m, y_m)` in SI meters inside the physical vessel.
332    ///
333    /// # Arguments
334    ///
335    /// - `&Self` - Liquid game scene handle.
336    ///
337    /// # Returns
338    ///
339    /// - `(f32, f32)` - Center of mass in meters.
340    #[must_use]
341    pub fn center_of_mass(&self) -> (f32, f32) {
342        self.get_inner()
343            .try_borrow()
344            .map(|st: Ref<'_, GyroLiquidSceneState>| st.get_solver().center_of_mass())
345            .unwrap_or((DEFAULT_VESSEL_WIDTH_M * 0.5, DEFAULT_VESSEL_HEIGHT_M * 0.5))
346    }
347
348    /// Copies the currently active buoyant bodies for inspection or HUD overlays.
349    ///
350    /// # Arguments
351    ///
352    /// - `&Self` - Liquid game scene handle.
353    ///
354    /// # Returns
355    ///
356    /// - `Vec<BuoyantBody>` - Active buoyant rigid body states.
357    #[must_use]
358    pub fn buoyant_bodies(&self) -> Vec<BuoyantBody> {
359        self.get_inner()
360            .try_borrow()
361            .map(|st: Ref<'_, GyroLiquidSceneState>| {
362                let cnt: usize = st.get_solver().get_buoyant_body_count();
363                st.get_solver().get_buoyant_bodies()[..cnt].to_vec()
364            })
365            .unwrap_or_default()
366    }
367
368    /// Returns `true` if any active particle or buoyant body has NaN/Inf state or escaped container bounds.
369    ///
370    /// # Arguments
371    ///
372    /// - `&Self` - Liquid game scene handle.
373    ///
374    /// # Returns
375    ///
376    /// - `bool` - Whether solver state is invalid or escaped.
377    #[must_use]
378    pub fn has_invalid_or_escaped_state(&self) -> bool {
379        self.get_inner()
380            .try_borrow()
381            .map(|st: Ref<'_, GyroLiquidSceneState>| st.get_solver().has_invalid_or_escaped_state())
382            .unwrap_or(false)
383    }
384
385    /// Renders the interpolated liquid scene directly into the internal `RenderBufferPool` for offscreen inspection or custom blitting.
386    ///
387    /// # Arguments
388    ///
389    /// - `&Self` - Liquid game scene handle.
390    /// - `u32` - Target viewport width in logical pixels.
391    /// - `u32` - Target viewport height in logical pixels.
392    /// - `f32` - Interpolation alpha in `[0.0, 1.0]`.
393    ///
394    /// # Returns
395    ///
396    /// - `Option<PooledFrameLease>` - Rendered zero-copy RGBA8 frame lease.
397    #[must_use]
398    pub fn render_to_pooled_frame(
399        &self,
400        viewport_w: u32,
401        viewport_h: u32,
402        alpha: f32,
403    ) -> Option<PooledFrameLease> {
404        let mut st: RefMut<'_, GyroLiquidSceneState> = self.get_inner().try_borrow_mut().ok()?;
405        let vw: u32 = viewport_w.max(FLUID_RENDER_MIN_DIM);
406        let vh: u32 = viewport_h.max(FLUID_RENDER_MIN_DIM);
407        st.get_mut_solver()
408            .adapt_vessel_aspect((vw as f32) / (vh as f32));
409        let next_fence: u64 = st.get_frame_fence().saturating_add(1);
410        st.set_frame_fence(next_fence);
411        #[cfg(not(target_arch = "wasm32"))]
412        let t0: Instant = Instant::now();
413        let lease: Option<PooledFrameLease> = {
414            let GyroLiquidSceneState {
415                snapshots,
416                renderer,
417                frame_pool,
418                ..
419            } = &mut *st;
420            let snap: &FluidSimSnapshot = snapshots.sample_cached(alpha);
421            renderer.render_snapshot_into_pool(snap, vw, vh, frame_pool, next_fence)
422        };
423        #[cfg(not(target_arch = "wasm32"))]
424        {
425            let elapsed_ms: f32 = (t0.elapsed().as_nanos() as f32) * 1.0e-6;
426            st.set_last_render_ms(elapsed_ms);
427        }
428        st.refresh_stats();
429        lease
430    }
431}
432
433/// `GameScene` integration driving fixed-step SI liquid physics, sensor ingestion, pointer stirring, and zero-copy pooled optical rendering inside `GameEngineHost`.
434impl GameScene for GyroLiquidGameScene {
435    /// Advances SI PBF liquid physics by one fixed timestep `dt` using live hardware sensors (or virtual tilt) plus pointer stirring and keyboard controls.
436    ///
437    /// # Arguments
438    ///
439    /// - `&Self` - Mutable liquid scene handle.
440    /// - `f32` - Fixed simulation timestep in seconds.
441    /// - `&InputState` - Real-time polled pointer and keyboard input state.
442    fn fixed_update(&mut self, dt: f32, input: &InputState) {
443        let Ok(mut st) = self.get_inner().try_borrow_mut() else {
444            return;
445        };
446        #[cfg(not(target_arch = "wasm32"))]
447        let t0: Instant = Instant::now();
448        let safe_dt: f32 = dt.clamp(1.0 / 480.0, FLUID_MAX_STEP_DT);
449        let sensor_opt: Option<DeviceMotionSample> = st.resolve_active_sensor_sample();
450        if let Some(sample) = sensor_opt {
451            st.set_sensor_active(sample.get_sensor_active());
452            st.get_mut_solver().apply_device_motion(sample, safe_dt);
453        } else {
454            st.set_sensor_active(false);
455            let roll_axis: f32 = input.axis(KeyCode::ArrowLeft, KeyCode::ArrowRight)
456                + input.axis(
457                    KeyCode::Character(FLUID_KEY_CHAR_LEFT),
458                    KeyCode::Character(FLUID_KEY_CHAR_RIGHT),
459                );
460            let pitch_axis: f32 = input.axis(KeyCode::ArrowDown, KeyCode::ArrowUp)
461                + input.axis(
462                    KeyCode::Character(FLUID_KEY_CHAR_DOWN),
463                    KeyCode::Character(FLUID_KEY_CHAR_UP),
464                );
465            if roll_axis.abs() > 0.01 {
466                st.get_mut_solver().rotate_container_by(
467                    roll_axis.clamp(-1.0, 1.0) * FLUID_KEY_ROLL_SPEED_RAD_S * safe_dt,
468                );
469            }
470            if pitch_axis.abs() > 0.01 {
471                let cur_roll: f32 = st.get_solver().get_virtual_roll_rad();
472                let next_pitch: f32 = st.get_solver().get_virtual_pitch_rad()
473                    + pitch_axis.clamp(-1.0, 1.0) * FLUID_KEY_PITCH_SPEED_RAD_S * safe_dt;
474                st.get_mut_solver().set_virtual_tilt(cur_roll, next_pitch);
475            }
476            st.get_mut_solver().sync_virtual_motion(safe_dt);
477        }
478        if input.is_key_just_pressed(KeyCode::Space) {
479            st.get_mut_solver()
480                .apply_shake_impulse(FLUID_KEY_SHAKE_X_MPS2, FLUID_KEY_SHAKE_Y_MPS2);
481        }
482        if input.is_key_just_pressed(KeyCode::Character(FLUID_KEY_CHAR_RESET)) {
483            st.get_mut_solver().set_virtual_tilt(0.0, 0.0);
484            st.get_mut_solver().set_prev_virtual_roll_rad(0.0);
485            st.get_mut_solver().reset_water();
486        }
487        if input.is_button_down(PointerButton::Primary) {
488            let vp: Rect = st.get_last_viewport_bounds();
489            let bw: f32 = vp.get_width().max(1.0);
490            let bh: f32 = vp.get_height().max(1.0);
491            let ptr: Point = input.get_pointer_position();
492            let delta: Point = input.get_pointer_delta();
493            let nx: f32 = (ptr.get_x() - vp.get_x()) / bw;
494            let ny: f32 = (ptr.get_y() - vp.get_y()) / bh;
495            if (0.0..=1.0).contains(&nx) && (0.0..=1.0).contains(&ny) {
496                let d_mag: f32 = delta.get_x().hypot(delta.get_y());
497                if d_mag > 0.25 {
498                    let vw_m: f32 = st.get_solver().get_config().get_vessel_width_m();
499                    let vh_m: f32 = st.get_solver().get_config().get_vessel_height_m();
500                    let vx_mps: f32 = (delta.get_x() / bw) * vw_m / safe_dt;
501                    let vy_mps: f32 = (delta.get_y() / bh) * vh_m / safe_dt;
502                    st.get_mut_solver()
503                        .apply_stir_impulse(nx, ny, vx_mps, vy_mps);
504                }
505            }
506        }
507        st.get_mut_solver().step(safe_dt);
508        {
509            let GyroLiquidSceneState {
510                solver, snapshots, ..
511            } = &mut *st;
512            snapshots.capture_into(|dst: &mut FluidSimSnapshot| {
513                solver.capture_snapshot_into(dst);
514            });
515        }
516        #[cfg(not(target_arch = "wasm32"))]
517        {
518            let elapsed_ms: f32 = (t0.elapsed().as_nanos() as f32) * 1.0e-6;
519            st.set_last_sim_ms(elapsed_ms);
520        }
521        st.refresh_stats();
522    }
523
524    /// Renders the photorealistic optical water into the bounded `RenderBufferPool` and blits it zero-copy into `ctx`, adapting cleanly to arbitrary resize and fullscreen bounds.
525    ///
526    /// # Arguments
527    ///
528    /// - `&Self` - Mutable liquid scene handle.
529    /// - `f32` - Render interpolation alpha in `[0.0, 1.0]`.
530    /// - `&mut GameRenderContext<'_>` - Active viewport draw surface.
531    fn render(&mut self, alpha: f32, ctx: &mut GameRenderContext<'_>) {
532        let Ok(mut st) = self.get_inner().try_borrow_mut() else {
533            return;
534        };
535        let bounds: Rect = ctx.bounds;
536        let vp_w: f32 = bounds.get_width().max(64.0);
537        let vp_h: f32 = bounds.get_height().max(64.0);
538        st.set_last_viewport_bounds(bounds);
539        st.get_mut_solver().adapt_vessel_aspect(vp_w / vp_h);
540        let next_fence: u64 = st.get_frame_fence().saturating_add(1);
541        st.set_frame_fence(next_fence);
542        #[cfg(not(target_arch = "wasm32"))]
543        let t0: Instant = Instant::now();
544        let lease_opt: Option<PooledFrameLease> = {
545            let GyroLiquidSceneState {
546                snapshots,
547                renderer,
548                frame_pool,
549                ..
550            } = &mut *st;
551            let snap: &FluidSimSnapshot = snapshots.sample_cached(alpha);
552            renderer.render_snapshot_into_pool(
553                snap,
554                vp_w.round() as u32,
555                vp_h.round() as u32,
556                frame_pool,
557                next_fence,
558            )
559        };
560        if let Some(lease) = lease_opt {
561            let dst_rect: Rect = Rect::new(0.0, 0.0, vp_w, vp_h);
562            ctx.blit_pooled_frame(dst_rect, &lease);
563            lease.submit_in_flight();
564            let _: usize = st.get_frame_pool().retire_fence(next_fence);
565        }
566        #[cfg(not(target_arch = "wasm32"))]
567        {
568            let elapsed_ms: f32 = (t0.elapsed().as_nanos() as f32) * 1.0e-6;
569            st.set_last_render_ms(elapsed_ms);
570        }
571        st.refresh_stats();
572    }
573}