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 };
50 state.refresh_stats();
51 state
52 }
53
54 pub(crate) fn refresh_stats(&mut self) {
60 let solver: &LiquidFluidSolver = self.get_solver();
61 let config_spec: 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: config_spec.get_vessel_width_m(),
78 vessel_height_m: config_spec.get_vessel_height_m(),
79 fill_ratio: config_spec.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 #[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
121impl GyroLiquidGameScene {
123 #[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 pub fn bind_device_motion(&self, signal: Signal<DeviceMotionSample>) {
146 if let Ok(mut node_style) = self.get_inner().try_borrow_mut() {
147 node_style.set_device_motion_signal(Some(signal));
148 }
149 }
150
151 pub fn set_device_motion(&self, sample: Option<DeviceMotionSample>) {
158 if let Ok(mut node_style) = self.get_inner().try_borrow_mut() {
159 node_style.set_manual_motion_sample(sample);
160 }
161 }
162
163 pub fn set_sensor_mode(&self, mode: FluidSensorMode) {
170 if let Ok(mut node_style) = self.get_inner().try_borrow_mut() {
171 node_style.set_sensor_mode(mode);
172 node_style.refresh_stats();
173 }
174 }
175
176 pub fn set_virtual_tilt(&self, roll_rad: f32, pitch_rad: f32) {
184 if let Ok(mut node_style) = self.get_inner().try_borrow_mut() {
185 node_style
186 .get_mut_solver()
187 .set_virtual_tilt(roll_rad, pitch_rad);
188 node_style.refresh_stats();
189 }
190 }
191
192 pub fn rotate_container_by(&self, delta_rad: f32) {
199 if let Ok(mut node_style) = self.get_inner().try_borrow_mut() {
200 node_style.get_mut_solver().rotate_container_by(delta_rad);
201 node_style.refresh_stats();
202 }
203 }
204
205 pub fn apply_shake_impulse(&self, ax: f32, ay: f32) {
213 if let Ok(mut node_style) = self.get_inner().try_borrow_mut() {
214 node_style.get_mut_solver().apply_shake_impulse(ax, ay);
215 }
216 }
217
218 pub fn apply_stir_impulse(&self, norm_x: f32, norm_y: f32, vel_x_mps: f32, vel_y_mps: f32) {
228 if let Ok(mut node_style) = self.get_inner().try_borrow_mut() {
229 node_style
230 .get_mut_solver()
231 .apply_stir_impulse(norm_x, norm_y, vel_x_mps, vel_y_mps);
232 }
233 }
234
235 pub fn set_fill_ratio(&self, fill_ratio: f32) {
242 if let Ok(mut node_style) = self.get_inner().try_borrow_mut() {
243 node_style.get_mut_solver().set_fill_ratio(fill_ratio);
244 let GyroLiquidSceneState {
245 solver, snapshots, ..
246 } = &mut *node_style;
247 snapshots.capture_discontinuous_into(|dst: &mut FluidSimSnapshot| {
248 solver.capture_snapshot_into(dst);
249 });
250 node_style.refresh_stats();
251 }
252 }
253
254 pub fn set_viscosity(&self, viscosity: f32) {
261 if let Ok(mut node_style) = self.get_inner().try_borrow_mut() {
262 node_style.get_mut_solver().set_viscosity(viscosity);
263 }
264 }
265
266 pub fn set_surface_tension(&self, surface_tension: f32) {
273 if let Ok(mut node_style) = self.get_inner().try_borrow_mut() {
274 node_style
275 .get_mut_solver()
276 .set_surface_tension(surface_tension);
277 }
278 }
279
280 pub fn set_buoyant_bodies_enabled(&self, enabled: bool) {
287 if let Ok(mut node_style) = self.get_inner().try_borrow_mut() {
288 node_style
289 .get_mut_solver()
290 .set_buoyant_bodies_enabled(enabled);
291 let GyroLiquidSceneState {
292 solver, snapshots, ..
293 } = &mut *node_style;
294 snapshots.capture_discontinuous_into(|dst: &mut FluidSimSnapshot| {
295 solver.capture_snapshot_into(dst);
296 });
297 node_style.refresh_stats();
298 }
299 }
300
301 pub fn reset_water(&self) {
307 if let Ok(mut node_style) = self.get_inner().try_borrow_mut() {
308 node_style.get_mut_solver().set_virtual_tilt(0.0, 0.0);
309 node_style.get_mut_solver().set_prev_virtual_roll_rad(0.0);
310 node_style.get_mut_solver().reset_water();
311 let GyroLiquidSceneState {
312 solver, snapshots, ..
313 } = &mut *node_style;
314 snapshots.capture_discontinuous_into(|dst: &mut FluidSimSnapshot| {
315 solver.capture_snapshot_into(dst);
316 });
317 node_style.refresh_stats();
318 }
319 }
320
321 #[must_use]
331 pub fn stats(&self) -> GyroLiquidStats {
332 self.get_inner()
333 .try_borrow()
334 .map(|node_style: Ref<'_, GyroLiquidSceneState>| node_style.get_stats())
335 .unwrap_or_default()
336 }
337
338 #[must_use]
348 pub fn center_of_mass(&self) -> (f32, f32) {
349 self.get_inner()
350 .try_borrow()
351 .map(|node_style: Ref<'_, GyroLiquidSceneState>| {
352 node_style.get_solver().center_of_mass()
353 })
354 .unwrap_or((DEFAULT_VESSEL_WIDTH_M * 0.5, DEFAULT_VESSEL_HEIGHT_M * 0.5))
355 }
356
357 #[must_use]
367 pub fn buoyant_bodies(&self) -> Vec<BuoyantBody> {
368 self.get_inner()
369 .try_borrow()
370 .map(|node_style: Ref<'_, GyroLiquidSceneState>| {
371 let cnt: usize = node_style.get_solver().get_buoyant_body_count();
372 node_style.get_solver().get_buoyant_bodies()[..cnt].to_vec()
373 })
374 .unwrap_or_default()
375 }
376
377 #[must_use]
387 pub fn has_invalid_or_escaped_state(&self) -> bool {
388 self.get_inner()
389 .try_borrow()
390 .map(|node_style: Ref<'_, GyroLiquidSceneState>| {
391 node_style.get_solver().has_invalid_or_escaped_state()
392 })
393 .unwrap_or(false)
394 }
395
396 #[must_use]
409 pub fn render_to_pooled_frame(
410 &self,
411 viewport_w: u32,
412 viewport_h: u32,
413 alpha: f32,
414 ) -> Option<PooledFrameLease> {
415 let mut node_style: RefMut<'_, GyroLiquidSceneState> =
416 self.get_inner().try_borrow_mut().ok()?;
417 let vw: u32 = viewport_w.max(FLUID_RENDER_MIN_DIM);
418 let vh: u32 = viewport_h.max(FLUID_RENDER_MIN_DIM);
419 if node_style
420 .get_mut_solver()
421 .adapt_vessel_aspect_changed((vw as f32) / (vh as f32))
422 {
423 let GyroLiquidSceneState {
424 solver, snapshots, ..
425 } = &mut *node_style;
426 snapshots.capture_discontinuous_into(|dst: &mut FluidSimSnapshot| {
427 solver.capture_snapshot_into(dst);
428 });
429 }
430 let next_fence: u64 = node_style.get_frame_fence().saturating_add(1);
431 node_style.set_frame_fence(next_fence);
432 #[cfg(not(target_arch = "wasm32"))]
433 let t0: Instant = Instant::now();
434 let lease: Option<PooledFrameLease> = {
435 let GyroLiquidSceneState {
436 snapshots,
437 renderer,
438 frame_pool,
439 ..
440 } = &mut *node_style;
441 let snap: &FluidSimSnapshot = snapshots.sample_cached(alpha);
442 renderer.render_snapshot_into_pool(snap, vw, vh, frame_pool, next_fence)
443 };
444 #[cfg(not(target_arch = "wasm32"))]
445 {
446 let elapsed_ms: f32 = (t0.elapsed().as_nanos() as f32) * 1.0e-6;
447 node_style.set_last_render_ms(elapsed_ms);
448 }
449 node_style.refresh_stats();
450 lease
451 }
452}
453
454impl GameScene for GyroLiquidGameScene {
456 fn fixed_update(&mut self, dt: f32, input: &InputState) {
464 let Ok(mut node_style) = self.get_inner().try_borrow_mut() else {
465 return;
466 };
467 #[cfg(not(target_arch = "wasm32"))]
468 let t0: Instant = Instant::now();
469 let safe_dt: f32 = dt.clamp(1.0 / 480.0, FLUID_MAX_STEP_DT);
470 let sensor_opt: Option<DeviceMotionSample> = node_style.resolve_active_sensor_sample();
471 if let Some(sample) = sensor_opt {
472 node_style.set_sensor_active(sample.get_sensor_active());
473 node_style
474 .get_mut_solver()
475 .apply_device_motion(sample, safe_dt);
476 } else {
477 node_style.set_sensor_active(false);
478 let roll_axis: f32 = input.axis(KeyCode::ArrowLeft, KeyCode::ArrowRight)
479 + input.axis(
480 KeyCode::Character(FLUID_KEY_CHAR_LEFT),
481 KeyCode::Character(FLUID_KEY_CHAR_RIGHT),
482 );
483 let pitch_axis: f32 = input.axis(KeyCode::ArrowDown, KeyCode::ArrowUp)
484 + input.axis(
485 KeyCode::Character(FLUID_KEY_CHAR_DOWN),
486 KeyCode::Character(FLUID_KEY_CHAR_UP),
487 );
488 if roll_axis.abs() > 0.01 {
489 node_style.get_mut_solver().rotate_container_by(
490 roll_axis.clamp(-1.0, 1.0) * FLUID_KEY_ROLL_SPEED_RAD_S * safe_dt,
491 );
492 }
493 if pitch_axis.abs() > 0.01 {
494 let cur_roll: f32 = node_style.get_solver().get_virtual_roll_rad();
495 let next_pitch: f32 = node_style.get_solver().get_virtual_pitch_rad()
496 + pitch_axis.clamp(-1.0, 1.0) * FLUID_KEY_PITCH_SPEED_RAD_S * safe_dt;
497 node_style
498 .get_mut_solver()
499 .set_virtual_tilt(cur_roll, next_pitch);
500 }
501 node_style.get_mut_solver().sync_virtual_motion(safe_dt);
502 }
503 if input.is_key_just_pressed(KeyCode::Character(FLUID_KEY_CHAR_RESET)) {
504 node_style.get_mut_solver().set_virtual_tilt(0.0, 0.0);
505 node_style.get_mut_solver().set_prev_virtual_roll_rad(0.0);
506 node_style.get_mut_solver().reset_water();
507 }
508 if input.is_button_down(PointerButton::Primary) {
509 let rect_bounds: Rect = node_style.get_last_viewport_bounds();
510 let border_width: f32 = rect_bounds.get_width().max(1.0);
511 let bh: f32 = rect_bounds.get_height().max(1.0);
512 let ptr: Point = input.get_pointer_position();
513 let delta: Point = input.get_pointer_delta();
514 let nx: f32 = (ptr.get_x() - rect_bounds.get_x()) / border_width;
515 let ny: f32 = (ptr.get_y() - rect_bounds.get_y()) / bh;
516 if (0.0..=1.0).contains(&nx) && (0.0..=1.0).contains(&ny) {
517 let d_mag: f32 = delta.get_x().hypot(delta.get_y());
518 if d_mag > 0.25 {
519 let vw_m: f32 = node_style.get_solver().get_config().get_vessel_width_m();
520 let vh_m: f32 = node_style.get_solver().get_config().get_vessel_height_m();
521 let vx_mps: f32 = (delta.get_x() / border_width) * vw_m / safe_dt;
522 let vy_mps: f32 = (delta.get_y() / bh) * vh_m / safe_dt;
523 node_style
524 .get_mut_solver()
525 .apply_stir_impulse(nx, ny, vx_mps, vy_mps);
526 }
527 }
528 }
529 node_style.get_mut_solver().step(safe_dt);
530 {
531 let GyroLiquidSceneState {
532 solver, snapshots, ..
533 } = &mut *node_style;
534 snapshots.capture_into(|dst: &mut FluidSimSnapshot| {
535 solver.capture_snapshot_into(dst);
536 });
537 }
538 #[cfg(not(target_arch = "wasm32"))]
539 {
540 let elapsed_ms: f32 = (t0.elapsed().as_nanos() as f32) * 1.0e-6;
541 node_style.set_last_sim_ms(elapsed_ms);
542 }
543 node_style.refresh_stats();
544 }
545
546 fn render(&mut self, alpha: f32, ctx: &mut GameRenderContext<'_>) {
554 let Ok(mut node_style) = self.get_inner().try_borrow_mut() else {
555 return;
556 };
557 let bounds: Rect = ctx.bounds;
558 let vp_w: f32 = bounds.get_width().max(64.0);
559 let vp_h: f32 = bounds.get_height().max(64.0);
560 let dpr: f32 = ctx.scale_factor().clamp(1.0, 3.0);
561 let target_phys_w: u32 = (vp_w * dpr).round().max(64.0) as u32;
562 let target_phys_h: u32 = (vp_h * dpr).round().max(64.0) as u32;
563 node_style.set_last_viewport_bounds(bounds);
564 if node_style
565 .get_mut_solver()
566 .adapt_vessel_aspect_changed(vp_w / vp_h)
567 {
568 let GyroLiquidSceneState {
569 solver, snapshots, ..
570 } = &mut *node_style;
571 snapshots.capture_discontinuous_into(|dst: &mut FluidSimSnapshot| {
572 solver.capture_snapshot_into(dst);
573 });
574 }
575 let next_fence: u64 = node_style.get_frame_fence().saturating_add(1);
576 node_style.set_frame_fence(next_fence);
577 #[cfg(not(target_arch = "wasm32"))]
578 let t0: Instant = Instant::now();
579 let lease_opt: Option<PooledFrameLease> = {
580 let GyroLiquidSceneState {
581 snapshots,
582 renderer,
583 frame_pool,
584 ..
585 } = &mut *node_style;
586 let snap: &FluidSimSnapshot = snapshots.sample_cached(alpha);
587 renderer.render_snapshot_into_pool(
588 snap,
589 target_phys_w,
590 target_phys_h,
591 frame_pool,
592 next_fence,
593 )
594 };
595 if let Some(lease) = lease_opt {
596 let dst_rect: Rect = Rect::new(0.0, 0.0, vp_w, vp_h);
597 ctx.blit_pooled_frame(dst_rect, &lease);
598 lease.submit_in_flight();
599 let _: usize = node_style.get_frame_pool().retire_fence(next_fence);
600 }
601 #[cfg(not(target_arch = "wasm32"))]
602 {
603 let elapsed_ms: f32 = (t0.elapsed().as_nanos() as f32) * 1.0e-6;
604 node_style.set_last_render_ms(elapsed_ms);
605 }
606 node_style.refresh_stats();
607 }
608}