1use super::*;
2
3impl ReactiveSignals {
5 #[must_use]
11 pub(crate) fn create() -> Self {
12 let counter: Signal<i32> = Signal::new(1);
13 let doubled: Memo<i32> = computed!((counter) -> i32 => move |n: i32| n * 2);
14 Self { counter, doubled }
15 }
16}
17
18impl RenderWindowSignals {
20 #[must_use]
30 pub(crate) fn create(default_plat_idx: usize) -> Self {
31 Self {
32 render_mode_index: Signal::new(2),
33 demo_fps_cap_index: Signal::new(0),
34 fullscreen: Signal::new(false),
35 island_active: Signal::new(false),
36 island_progress: Signal::new(25),
37 camera_perm_status: Signal::new(DEFAULT_CAMERA_PERM.to_string()),
38 protocol_status: Signal::new(DEFAULT_PROTOCOL_STATUS.to_string()),
39 a11y_announcements: Signal::new(0),
40 haptic_pulses: Signal::new(0),
41 os_target_platform_idx: Signal::new(default_plat_idx),
42 island_mode_idx: Signal::new(0),
43 system_notifications: Signal::new(vec![(
44 DEFAULT_SYS_NOTIF_TITLE.to_string(),
45 DEFAULT_SYS_NOTIF_BODY.to_string(),
46 )]),
47 permission_statuses: Signal::new(vec![PermissionStatus::NotDetermined; 14]),
48 }
49 }
50}
51
52impl FormsSignals {
54 #[must_use]
60 pub(crate) fn create() -> Self {
61 Self {
62 username: Signal::new(DEFAULT_USERNAME.to_string()),
63 bio: Signal::new(DEFAULT_BIO_TEXT.to_string()),
64 stepper_value: Signal::new(4),
65 radio_index: Signal::new(1),
66 slider_value: Signal::new(65.0),
67 select_index: Signal::new(0),
68 select_open: Signal::new(false),
69 rating_value: Signal::new(4),
70 pin_toggled: Signal::new(false),
71 hardware_accel: Signal::new(true),
72 agree_terms: Signal::new(true),
73 active_tab: Signal::new(0),
74 page_index: Signal::new(1),
75 step_index: Signal::new(1),
76 accordion_open: Signal::new(Some(0)),
77 picker_color: Signal::new(Color::hex(0x2563EB)),
78 picker_time: Signal::new((14, 30)),
79 tag_items: Signal::new(vec![
80 DEFAULT_TAG_RUST.to_string(),
81 DEFAULT_TAG_NATIVE.to_string(),
82 DEFAULT_TAG_WASM.to_string(),
83 ]),
84 tree_selected: Signal::new(None),
85 breadcrumb_active: Signal::new(2),
86 }
87 }
88}
89
90impl OverlaysSignals {
92 #[must_use]
98 pub(crate) fn create() -> Self {
99 Self {
100 modal_open: Signal::new(false),
101 drawer_open: Signal::new(false),
102 sheet_open: Signal::new(false),
103 popover_open: Signal::new(false),
104 dropdown_open: Signal::new(false),
105 dropdown_selected: Signal::new(None),
106 toast_visible: Signal::new(false),
107 notif_visible: Signal::new(false),
108 loading_active: Signal::new(false),
109 }
110 }
111}
112
113impl DataSignals {
115 #[must_use]
121 pub(crate) fn create() -> Self {
122 Self {
123 list_scroll_y: Signal::new(640.0),
124 }
125 }
126}
127
128impl Engine3dSignals {
130 #[must_use]
136 pub(crate) fn max_quality_config() -> RenderQualityConfig {
137 let mut config_spec: RenderQualityConfig =
138 RenderQualityConfig::from_preset(QualityPreset::Cinematic);
139 config_spec
140 .set_resolution_preset(ResolutionPreset::Uhd4k)
141 .set_resolution_scale(1.0)
142 .set_dynamic_resolution(false)
143 .set_target_fps(480.0)
144 .set_ray_tracing(RayTracingMode::FullPathTracedGi)
145 .set_reflection_bounces(3)
146 .set_upscaler(UpscalerMode::Native)
147 .set_anti_aliasing(AntiAliasingMode::Tsr)
148 .set_draw_distance(640.0)
149 .set_lod_bias(0.5)
150 .set_frustum_culling(true)
151 .set_chunk_streaming(true)
152 .set_volumetric_fog(true)
153 .set_gpu_instancing(true)
154 .set_occlusion_culling(true)
155 .set_virtual_shadow_maps(true)
156 .set_clustered_lighting(true)
157 .set_lumen_radiance_cache(true);
158 config_spec
159 }
160
161 #[must_use]
167 pub(crate) fn create() -> Self {
168 Self {
169 engine3d_quality: Signal::new(Self::max_quality_config()),
170 engine3d_preset_idx: Signal::new(4),
171 engine3d_rt_idx: Signal::new(3),
172 engine3d_res_scale: Signal::new(100.0),
173 engine3d_time_of_day: Signal::new(17.2),
174 engine3d_import_queue: Signal::new(0),
175 engine3d_import_status: Signal::new(DEFAULT_ENGINE3D_STATUS.to_string()),
176 engine3d_camera_mode: Signal::new(0),
177 engine3d_tsr_idx: Signal::new(0),
178 engine3d_atmosphere_idx: Signal::new(0),
179 engine3d_fullscreen_open: Signal::new(false),
180 }
181 }
182
183 #[must_use]
194 pub(crate) fn get_or_init(cell: &Cell<Option<Self>>, owner_scope: Scope) -> Self {
195 if let Some(existing) = cell.get() {
196 return existing;
197 }
198 let created: Self = owner_scope.enter(Self::create);
199 cell.set(Some(created));
200 created
201 }
202}
203
204impl DynamicSignals {
206 #[must_use]
212 pub(crate) fn create() -> Self {
213 Self {
214 sibling_counter: Signal::new(0),
215 dynamic_action_log: Signal::new(DEFAULT_DYNAMIC_ACTION_LOG.to_string()),
216 wasm_offline: Signal::new(false),
217 wasm_fault_status: Signal::new(DEFAULT_WASM_STATUS.to_string()),
218 wasm_bg_task: Signal::new(None),
219 }
220 }
221
222 #[must_use]
233 pub(crate) fn get_or_init(cell: &Cell<Option<Self>>, owner_scope: Scope) -> Self {
234 if let Some(existing) = cell.get() {
235 return existing;
236 }
237 let created: Self = owner_scope.enter(Self::create);
238 cell.set(Some(created));
239 created
240 }
241}
242
243impl LabSignals {
245 #[must_use]
251 pub(crate) fn create() -> Self {
252 Self {
253 alert_dialog_open: Signal::new(false),
254 alert_dialog_confirmed: Signal::new(false),
255 collapsible_open: Signal::new(true),
256 toggle_group_index: Signal::new(0),
257 otp_code: Signal::new(DEFAULT_OTP_CODE.to_string()),
258 command_query: Signal::new(String::new()),
259 command_selected: Signal::new(Some(0)),
260 hover_card_open: Signal::new(false),
261 calendar_day: Signal::new(25),
262 menubar_active: Signal::new(None),
263 carousel_index: Signal::new(0),
264 lab_combobox_query: Signal::new(String::new()),
265 lab_combobox_selected: Signal::new(0),
266 lab_combobox_open: Signal::new(false),
267 lab_table_filter: Signal::new(String::new()),
268 lab_table_sort_asc: Signal::new(true),
269 lab_table_selected: Signal::new(Some(0)),
270 lab_date_day: Signal::new(26),
271 lab_date_open: Signal::new(false),
272 lab_input_group_val: Signal::new(DEFAULT_INPUT_GROUP_VAL.to_string()),
273 lab_native_select_idx: Signal::new(0),
274 lab_nav_menu_active: Signal::new(None),
275 lab_split_ratio: Signal::new(0.45),
276 lab_block_scroll_chain: Signal::new(false),
277 lab_stop_click_bubble: Signal::new(true),
278 lab_parent_clicks: Signal::new(0),
279 lab_child_clicks: Signal::new(0),
280 lab_resize_preserve_count: Signal::new(1),
281 lab_rtl_mode: Signal::new(false),
282 }
283 }
284}
285
286impl MediaSignals {
288 #[must_use]
294 pub(crate) fn create() -> Self {
295 Self {
296 media_gif: Signal::new(GifAnimation::default()),
297 media_live: Signal::new(LivePhotoAsset::default()),
298 media_video: Signal::new(VideoTrack::default()),
299 media_audio: Signal::new(AudioTrack::default()),
300 media_pdf: Signal::new(PdfDocument::default()),
301 media_html_link_log: Signal::new(DEFAULT_MEDIA_LINK_LOG.to_string()),
302 media_loading: Signal::new(false),
303 media_bg_task: Signal::new(None),
304 }
305 }
306}
307
308impl MarkdownSignals {
310 #[must_use]
316 pub(crate) fn create() -> Self {
317 Self {
318 markdown_copy_log: Signal::new(DEFAULT_MD_COPY_LOG.to_string()),
319 markdown_link_log: Signal::new(DEFAULT_MD_LINK_LOG.to_string()),
320 markdown_tasks_toggled: Signal::new(0),
321 markdown_lang_tab: Signal::new(0),
322 markdown_selectable: Signal::new(true),
323 }
324 }
325}
326
327impl StressSignals {
329 #[must_use]
335 pub(crate) fn create() -> Self {
336 Self {
337 stress_results: Signal::new(Vec::new()),
338 stress_summary: Signal::new(STRESS_SUMMARY_READY.to_string()),
339 }
340 }
341}
342
343impl ChartsSignals {
345 #[must_use]
351 pub(crate) fn create() -> Self {
352 Self {
353 charts_category_idx: Signal::new(0),
354 charts_event_log: Signal::new(CHARTS_EVENT_READY.to_string()),
355 }
356 }
357}
358
359impl WaterSignals {
361 #[must_use]
367 pub(crate) fn create() -> Self {
368 Self {
369 fill_pct: Signal::new(FLUID_DEFAULT_FILL_RATIO * 100.0),
370 viscosity_idx: Signal::new(0),
371 buoyant_enabled: Signal::new(true),
372 fullscreen_open: Signal::new(false),
373 sensor_perm_status: Signal::new(WATER_PERM_DESKTOP_STATUS.to_string()),
374 stats: Signal::new(GyroLiquidStats::default()),
375 }
376 }
377}
378
379impl LazyWaterScene {
381 #[must_use]
392 pub(crate) fn create_deferred(
393 scene_cell: Rc<RefCell<Option<GyroLiquidGameScene>>>,
394 signals_cell: Rc<Cell<Option<WaterSignals>>>,
395 ) -> Self {
396 Self {
397 scene_cell,
398 signals_cell,
399 stats_throttle_tick: Rc::new(Cell::new(0)),
400 }
401 }
402
403 fn sync_water_stats_throttled(&self, next: GyroLiquidStats) {
409 let Some(sig) = self.get_signals_cell().get() else {
410 return;
411 };
412 let stats_sig: Signal<GyroLiquidStats> = sig.get_stats();
413 let prev: GyroLiquidStats = stats_sig.get_untracked();
414 let state_changed: bool = prev.get_sensor_active() != next.get_sensor_active()
415 || prev.get_particle_count() != next.get_particle_count()
416 || prev.get_buoyant_body_count() != next.get_buoyant_body_count()
417 || prev.get_bubble_count() != next.get_bubble_count()
418 || (prev.get_tilt_angle_deg() - next.get_tilt_angle_deg()).abs() > 0.25
419 || (prev.get_gravity_x() - next.get_gravity_x()).abs() > 0.15
420 || (prev.get_gravity_y() - next.get_gravity_y()).abs() > 0.15
421 || (prev.get_fill_ratio() - next.get_fill_ratio()).abs() > 0.005
422 || (prev.get_kinetic_energy_mj() - next.get_kinetic_energy_mj()).abs() > 0.08;
423 let tick: u8 = self.get_stats_throttle_tick().get().wrapping_add(1);
424 if state_changed || tick >= 10 {
425 self.get_stats_throttle_tick().set(0);
426 let _: bool = stats_sig.set_if_changed(next);
427 } else {
428 self.get_stats_throttle_tick().set(tick);
429 }
430 }
431
432 #[must_use]
438 pub(crate) fn max_quality_config() -> GyroLiquidConfig {
439 let mut config_spec: GyroLiquidConfig = GyroLiquidConfig::default();
440 config_spec
441 .set_substeps(4)
442 .set_solver_iterations(6)
443 .set_base_particle_count(FLUID_MAX_PARTICLES)
444 .set_buoyant_bodies_enabled(true);
445 config_spec
446 }
447
448 #[must_use]
458 pub(crate) fn ensure_scene(&self) -> GyroLiquidGameScene {
459 if let Some(existing) = self.get_scene_cell().borrow().as_ref() {
460 return existing.clone();
461 }
462 let created: GyroLiquidGameScene =
463 GyroLiquidGameScene::with_config(Self::max_quality_config());
464 *self.get_scene_cell().borrow_mut() = Some(created.clone());
465 created
466 }
467}
468
469impl GameScene for LazyWaterScene {
471 fn fixed_update(&mut self, dt: f32, input: &InputState) {
479 let mut scene: GyroLiquidGameScene = self.ensure_scene();
480 let mods: Modifiers = input.get_modifiers();
481 let no_mods: bool = !mods.get_ctrl() && !mods.get_meta() && !mods.get_alt();
482 let allow_shortcuts: bool =
483 no_mods && (EuvOverlayStack::active_count() == 0 || EuvOverlayStack::has_fullscreen());
484 if allow_shortcuts {
485 if input.is_key_just_pressed(KeyCode::Character('q'))
486 || input.is_key_just_pressed(KeyCode::Character('Q'))
487 {
488 scene.set_sensor_mode(FluidSensorMode::VirtualTilt);
489 scene.rotate_container_by(-PI * 0.5);
490 }
491 if input.is_key_just_pressed(KeyCode::Character('e'))
492 || input.is_key_just_pressed(KeyCode::Character('E'))
493 {
494 scene.set_sensor_mode(FluidSensorMode::VirtualTilt);
495 scene.rotate_container_by(PI * 0.5);
496 }
497 if (input.is_key_just_pressed(KeyCode::Character('f'))
498 || input.is_key_just_pressed(KeyCode::Character('F')))
499 && let Some(sig) = self.get_signals_cell().get()
500 {
501 let fs_sig: Signal<bool> = sig.get_fullscreen_open();
502 let next_open: bool = !fs_sig.get_untracked();
503 let _: bool = fs_sig.set_if_changed(next_open);
504 }
505 }
506 scene.fixed_update(dt, input);
507 self.sync_water_stats_throttled(scene.stats());
508 }
509
510 fn render(&mut self, alpha: f32, ctx: &mut GameRenderContext<'_>) {
518 let mut scene: GyroLiquidGameScene = self.ensure_scene();
519 scene.render(alpha, ctx);
520 self.sync_water_stats_throttled(scene.stats());
521 }
522}
523
524impl ShowcaseState {
526 #[must_use]
532 pub fn new() -> Self {
533 Self::new_with_hub(DynamicUpdateHub::new(), false)
534 }
535
536 #[must_use]
547 pub fn new_with_hub(hub: DynamicUpdateHub, bg_workers: bool) -> Self {
548 let (state_scope, _): (Scope, ()) = Scope::run(|_: Scope| {});
549 let game_fullscreen_open_cell: Rc<Cell<Option<Signal<bool>>>> = Rc::new(Cell::new(None));
550 let arena: DemoPhysicsScene =
551 DemoPhysicsScene::create_lazy_arena_with_fullscreen(game_fullscreen_open_cell.clone());
552 let game_host: GameEngineHost = GameEngineHost::new(arena, 1.0 / 60.0);
553 game_host.set_paused(true);
554 let engine3d_signals: Rc<Cell<Option<Engine3dSignals>>> = Rc::new(Cell::new(None));
555 let bg_workers_enabled: Rc<Cell<bool>> = Rc::new(Cell::new(bg_workers));
556 let scene3d: DemoOpenWorld3DScene = DemoOpenWorld3DScene::create_lazy_city_deferred(
557 engine3d_signals.clone(),
558 state_scope,
559 bg_workers_enabled.clone(),
560 );
561 let game3d_host: GameEngineHost = GameEngineHost::new(scene3d, 1.0 / 60.0);
562 game3d_host.set_paused(true);
563 let water_scene_cell: Rc<RefCell<Option<GyroLiquidGameScene>>> =
564 Rc::new(RefCell::new(None));
565 let water_signals: Rc<Cell<Option<WaterSignals>>> = Rc::new(Cell::new(None));
566 let lazy_water: LazyWaterScene =
567 LazyWaterScene::create_deferred(water_scene_cell.clone(), water_signals.clone());
568 let water_host: GameEngineHost = GameEngineHost::new(lazy_water, 1.0 / 60.0);
569 water_host.set_paused(true);
570 let router: EuvRouter = EuvRouter::new(ROUTE_OVERVIEW)
571 .with_default_retention(PageRetention::Freeze)
572 .with_dynamic_hub(hub.clone());
573 let wasm_registry: RegistryWasmFetcher = RegistryWasmFetcher::default();
574 let wasm_manager: WasmDynamicManager = WasmDynamicManager::new(
575 hub.clone(),
576 Rc::new(wasm_registry.clone()),
577 WasmSandboxConfig::default(),
578 );
579 let (
580 default_active_backend,
581 default_rec_backend,
582 default_cpu_mirror,
583 default_timing,
584 default_upload,
585 ): (&str, &str, bool, &str, &str) =
586 Self::default_adaptive_render_profile(current_platform());
587 let state: Self = Self {
588 route: Signal::new(ROUTE_OVERVIEW.to_string()),
589 state_scope,
590 theme: UiThemeState::new(active_feature_scheme(), ThemeMode::Light),
591 game_host,
592 game3d_host,
593 water_host,
594 water_scene_cell,
595 dynamic_hub: hub,
596 wasm_registry,
597 wasm_manager,
598 cmd_palette_open: Signal::new(false),
599 cmd_palette_query: Signal::new(String::new()),
600 auto_hide_chrome: Signal::new(true),
601 show_fps_hud: Signal::new(true),
602 swipe_routing: Signal::new(true),
603 reduced_motion: Signal::new(false),
604 adaptive_auto_switch: Signal::new(false),
605 adaptive_active_backend: Signal::new(default_active_backend.to_string()),
606 adaptive_recommended_backend: Signal::new(default_rec_backend.to_string()),
607 adaptive_cpu_mirror_active: Signal::new(default_cpu_mirror),
608 adaptive_present_timing_source: Signal::new(default_timing.to_string()),
609 adaptive_upload_strategy: Signal::new(default_upload.to_string()),
610 adaptive_handoff_attempts: Signal::new(0),
611 adaptive_handoff_successes: Signal::new(0),
612 adaptive_handoff_aborts: Signal::new(0),
613 router,
614 router_ready: Rc::new(Cell::new(false)),
615 lifecycle_mounts: Signal::new(0),
616 lifecycle_freezes: Signal::new(0),
617 lifecycle_resumes: Signal::new(0),
618 lifecycle_destroys: Signal::new(0),
619 lifecycle_last_event: Signal::new(DEFAULT_LIFECYCLE_BOOT.to_string()),
620 system_event_log: Signal::new(vec![DEFAULT_SYS_EVENT_LOG.to_string()]),
621 system_event_count: Signal::new(0),
622 bg_frozen: Signal::new(false),
623 bg_freeze_count: Signal::new(0),
624 bg_restore_count: Signal::new(0),
625 bg_snap_game2d_running: Rc::new(Cell::new(false)),
626 bg_snap_game3d_running: Rc::new(Cell::new(false)),
627 bg_snap_water_running: Rc::new(Cell::new(false)),
628 bg_snap_gif_playing: Rc::new(Cell::new(false)),
629 bg_snap_live_playing: Rc::new(Cell::new(false)),
630 bg_snap_video_playing: Rc::new(Cell::new(false)),
631 bg_snap_audio_playing: Rc::new(Cell::new(false)),
632 media_loaded: Rc::new(Cell::new(false)),
633 wasm_registry_loaded: Rc::new(Cell::new(false)),
634 stress_loaded: Rc::new(Cell::new(false)),
635 charts_loaded: Rc::new(Cell::new(false)),
636 bg_workers_enabled,
637 default_host_plat_idx: Rc::new(Cell::new(0)),
638 reactive_signals: Rc::new(Cell::new(None)),
639 render_window_signals: Rc::new(Cell::new(None)),
640 forms_signals: Rc::new(Cell::new(None)),
641 overlays_signals: Rc::new(Cell::new(None)),
642 data_signals: Rc::new(Cell::new(None)),
643 engine3d_signals,
644 dynamic_signals: Rc::new(Cell::new(None)),
645 lab_signals: Rc::new(Cell::new(None)),
646 media_signals: Rc::new(Cell::new(None)),
647 markdown_signals: Rc::new(Cell::new(None)),
648 stress_signals: Rc::new(Cell::new(None)),
649 charts_signals: Rc::new(Cell::new(None)),
650 water_signals,
651 game_fullscreen_open_cell,
652 };
653 state.wire_dynamic_hub_actions();
654 state
655 }
656
657 pub fn set_default_host_platform_idx(&self, idx: usize) {
664 self.get_default_host_plat_idx().set(idx);
665 if let Some(rw) = self.get_render_window_signals().get() {
666 let _: bool = rw.get_os_target_platform_idx().set_if_changed(idx);
667 }
668 }
669
670 pub fn set_bg_workers_enabled(&self, enabled: bool) {
677 self.get_bg_workers_enabled().set(enabled);
678 }
679
680 #[must_use]
690 fn default_adaptive_render_profile(
691 platform: PlatformKind,
692 ) -> (&'static str, &'static str, bool, &'static str, &'static str) {
693 let config_spec: RenderConfig = RenderConfig::default();
694 let direct_gpu: bool = config_spec.get_direct_gpu_present();
695 match platform {
696 PlatformKind::MacOs | PlatformKind::Ios | PlatformKind::IpadOs => {
697 if direct_gpu {
698 (
699 ADAPTIVE_BACKEND_METAL_DIRECT,
700 ADAPTIVE_BACKEND_METAL_DIRECT,
701 false,
702 ADAPTIVE_TIMING_COMPOSITOR,
703 ADAPTIVE_UPLOAD_DIRECT_GPU,
704 )
705 } else {
706 (
707 ADAPTIVE_BACKEND_SOFTWARE_CPU,
708 ADAPTIVE_BACKEND_METAL_DIRECT,
709 true,
710 ADAPTIVE_TIMING_PROXY,
711 ADAPTIVE_UPLOAD_MULTI_RECT,
712 )
713 }
714 }
715 PlatformKind::Android | PlatformKind::HarmonyOs => {
716 if direct_gpu {
717 (
718 ADAPTIVE_BACKEND_GLES3_DIRECT,
719 ADAPTIVE_BACKEND_GLES3_DIRECT,
720 false,
721 ADAPTIVE_TIMING_COMPOSITOR,
722 ADAPTIVE_UPLOAD_DIRECT_GPU,
723 )
724 } else {
725 (
726 ADAPTIVE_BACKEND_SOFTWARE_CPU,
727 ADAPTIVE_BACKEND_GLES3_DIRECT,
728 true,
729 ADAPTIVE_TIMING_PROXY,
730 ADAPTIVE_UPLOAD_MULTI_RECT,
731 )
732 }
733 }
734 PlatformKind::Windows => {
735 if direct_gpu {
736 (
737 ADAPTIVE_BACKEND_D3D11_DIRECT,
738 ADAPTIVE_BACKEND_D3D11_DIRECT,
739 false,
740 ADAPTIVE_TIMING_COMPOSITOR,
741 ADAPTIVE_UPLOAD_DIRECT_GPU,
742 )
743 } else {
744 (
745 ADAPTIVE_BACKEND_SOFTWARE_CPU,
746 ADAPTIVE_BACKEND_D3D11_DIRECT,
747 true,
748 ADAPTIVE_TIMING_PROXY,
749 ADAPTIVE_UPLOAD_MULTI_RECT,
750 )
751 }
752 }
753 PlatformKind::Linux => {
754 if direct_gpu {
755 (
756 ADAPTIVE_BACKEND_VULKAN_DIRECT,
757 ADAPTIVE_BACKEND_VULKAN_DIRECT,
758 false,
759 ADAPTIVE_TIMING_COMPOSITOR,
760 ADAPTIVE_UPLOAD_DIRECT_GPU,
761 )
762 } else {
763 (
764 ADAPTIVE_BACKEND_SOFTWARE_CPU,
765 ADAPTIVE_BACKEND_VULKAN_DIRECT,
766 true,
767 ADAPTIVE_TIMING_PROXY,
768 ADAPTIVE_UPLOAD_MULTI_RECT,
769 )
770 }
771 }
772 PlatformKind::Web => (
773 ADAPTIVE_BACKEND_WEBGL2_UPLOAD,
774 ADAPTIVE_BACKEND_WEBGL2_UPLOAD,
775 true,
776 ADAPTIVE_TIMING_PROXY,
777 ADAPTIVE_UPLOAD_MULTI_RECT,
778 ),
779 PlatformKind::Terminal | PlatformKind::TerminalCli => (
780 ADAPTIVE_BACKEND_TERMINAL,
781 ADAPTIVE_BACKEND_TERMINAL,
782 false,
783 ADAPTIVE_TIMING_UNOBSERVABLE,
784 ADAPTIVE_UPLOAD_NONE,
785 ),
786 PlatformKind::Wearable
787 | PlatformKind::MiniApp
788 | PlatformKind::QuickApp
789 | PlatformKind::Headless => (
790 ADAPTIVE_BACKEND_SOFTWARE_CPU,
791 ADAPTIVE_BACKEND_SOFTWARE_CPU,
792 true,
793 ADAPTIVE_TIMING_PROXY,
794 ADAPTIVE_UPLOAD_MULTI_RECT,
795 ),
796 }
797 }
798
799 pub fn sync_adaptive_render_diagnostics(
811 &self,
812 active_backend: &str,
813 recommended_backend: &str,
814 cpu_mirror_active: bool,
815 timing_source: &str,
816 upload_strategy: &str,
817 handoff_counts: (u64, u64, u64),
818 ) {
819 let _: bool = self
820 .get_adaptive_active_backend()
821 .set_if_changed(active_backend.to_string());
822 let _: bool = self
823 .get_adaptive_recommended_backend()
824 .set_if_changed(recommended_backend.to_string());
825 let _: bool = self
826 .get_adaptive_cpu_mirror_active()
827 .set_if_changed(cpu_mirror_active);
828 let _: bool = self
829 .get_adaptive_present_timing_source()
830 .set_if_changed(timing_source.to_string());
831 let _: bool = self
832 .get_adaptive_upload_strategy()
833 .set_if_changed(upload_strategy.to_string());
834 let _: bool = self
835 .get_adaptive_handoff_attempts()
836 .set_if_changed(handoff_counts.0);
837 let _: bool = self
838 .get_adaptive_handoff_successes()
839 .set_if_changed(handoff_counts.1);
840 let _: bool = self
841 .get_adaptive_handoff_aborts()
842 .set_if_changed(handoff_counts.2);
843 }
844
845 #[must_use]
856 fn adaptive_candidate_label(
857 backend: GraphicsBackend,
858 candidate: RenderBackendCandidate,
859 ) -> &'static str {
860 match candidate {
861 RenderBackendCandidate::GpuDirect => match backend {
862 GraphicsBackend::Metal => ADAPTIVE_BACKEND_METAL_DIRECT,
863 GraphicsBackend::Vulkan => ADAPTIVE_BACKEND_VULKAN_DIRECT,
864 GraphicsBackend::Direct3D11 | GraphicsBackend::Direct3D12 => {
865 ADAPTIVE_BACKEND_D3D11_DIRECT
866 }
867 GraphicsBackend::OpenGlEs => ADAPTIVE_BACKEND_GLES3_DIRECT,
868 GraphicsBackend::WebGpu | GraphicsBackend::WebGl2 => ADAPTIVE_BACKEND_WEBGL2_DIRECT,
869 GraphicsBackend::Canvas2d => ADAPTIVE_BACKEND_CANVAS2D,
870 GraphicsBackend::SoftwareCpu | GraphicsBackend::Headless => {
871 ADAPTIVE_BACKEND_SOFTWARE_CPU
872 }
873 },
874 RenderBackendCandidate::GpuUpload => match backend {
875 GraphicsBackend::Metal => ADAPTIVE_BACKEND_METAL_UPLOAD,
876 GraphicsBackend::WebGpu | GraphicsBackend::WebGl2 => ADAPTIVE_BACKEND_WEBGL2_UPLOAD,
877 GraphicsBackend::Vulkan => ADAPTIVE_BACKEND_VULKAN_DIRECT,
878 GraphicsBackend::Direct3D11 | GraphicsBackend::Direct3D12 => {
879 ADAPTIVE_BACKEND_D3D11_DIRECT
880 }
881 GraphicsBackend::OpenGlEs => ADAPTIVE_BACKEND_GLES3_DIRECT,
882 GraphicsBackend::Canvas2d => ADAPTIVE_BACKEND_CANVAS2D,
883 GraphicsBackend::SoftwareCpu | GraphicsBackend::Headless => {
884 ADAPTIVE_BACKEND_SOFTWARE_CPU
885 }
886 },
887 RenderBackendCandidate::Hybrid => ADAPTIVE_BACKEND_HYBRID_SPARSE,
888 RenderBackendCandidate::Software => {
889 if backend == GraphicsBackend::Canvas2d {
890 ADAPTIVE_BACKEND_CANVAS2D
891 } else {
892 ADAPTIVE_BACKEND_SOFTWARE_CPU
893 }
894 }
895 RenderBackendCandidate::Terminal => ADAPTIVE_BACKEND_TERMINAL,
896 }
897 }
898
899 pub fn sync_adaptive_from_app(&self, app: &mut App) {
906 let desired_mode: AdaptiveSwitchMode = if self.get_adaptive_auto_switch().get_untracked() {
907 AdaptiveSwitchMode::AutoSwitch
908 } else {
909 AdaptiveSwitchMode::RecommendOnly
910 };
911 if app.adaptive_switch_mode() != desired_mode {
912 app.set_adaptive_switch_mode(desired_mode);
913 }
914 let metrics: AdaptiveFrameMetrics = app.adaptive_frame_metrics();
915 let snap: AdaptiveRouterSnapshot = metrics.get_adaptive_router();
916 let backend: GraphicsBackend = app.get_renderer().get_active_backend();
917 let active_label: &str =
918 Self::adaptive_candidate_label(backend, snap.get_active_candidate());
919 let rec_label: &str =
920 Self::adaptive_candidate_label(backend, snap.get_recommended_candidate());
921 let timing_label: &str = match metrics.get_present_timing_source() {
922 PresentTimingSource::CompositorMeasured => ADAPTIVE_TIMING_COMPOSITOR,
923 PresentTimingSource::SubmissionProxy => ADAPTIVE_TIMING_PROXY,
924 PresentTimingSource::Unobservable => ADAPTIVE_TIMING_UNOBSERVABLE,
925 };
926 let upload_label: &str = match metrics.get_upload_strategy() {
927 UploadStrategy::DirectGpu => ADAPTIVE_UPLOAD_DIRECT_GPU,
928 UploadStrategy::MultiRect => ADAPTIVE_UPLOAD_MULTI_RECT,
929 UploadStrategy::MergedBbox => ADAPTIVE_UPLOAD_MERGED_BBOX,
930 UploadStrategy::FullFrame => ADAPTIVE_UPLOAD_FULL_FRAME,
931 UploadStrategy::None => ADAPTIVE_UPLOAD_NONE,
932 };
933 let successes: u64 = snap.get_seamless_handoff_successes();
934 let aborts: u64 = snap.get_handoff_aborts();
935 let attempts: u64 = successes.saturating_add(aborts);
936 self.sync_adaptive_render_diagnostics(
937 active_label,
938 rec_label,
939 metrics.get_cpu_mirror_active(),
940 timing_label,
941 upload_label,
942 (attempts, successes, aborts),
943 );
944 }
945
946 pub fn sync_adaptive_from_web_coordinator(
954 &self,
955 app: &mut App,
956 coord: &ShowcaseWebDualCanvasCoordinator,
957 ) {
958 self.sync_adaptive_from_app(app);
959 let active_path: ShowcaseWebPresentationPath = coord.get_active().get_path();
960 let active_label: &str = match active_path {
961 ShowcaseWebPresentationPath::GpuDirect => ADAPTIVE_BACKEND_WEBGL2_DIRECT,
962 ShowcaseWebPresentationPath::GpuUpload => ADAPTIVE_BACKEND_WEBGL2_UPLOAD,
963 ShowcaseWebPresentationPath::Canvas2d => ADAPTIVE_BACKEND_CANVAS2D,
964 };
965 let upload_label: &str = match active_path {
966 ShowcaseWebPresentationPath::GpuDirect => ADAPTIVE_UPLOAD_DIRECT_GPU,
967 ShowcaseWebPresentationPath::GpuUpload => ADAPTIVE_UPLOAD_MULTI_RECT,
968 ShowcaseWebPresentationPath::Canvas2d => ADAPTIVE_UPLOAD_FULL_FRAME,
969 };
970 let timing_label: &str = match coord.get_timing_source() {
971 ShowcaseWebTimingSource::SubmissionProxy => ADAPTIVE_TIMING_PROXY,
972 ShowcaseWebTimingSource::Unobservable => ADAPTIVE_TIMING_UNOBSERVABLE,
973 };
974 let snap: AdaptiveRouterSnapshot = app.adaptive_router_snapshot();
975 let successes: u64 = snap
976 .get_seamless_handoff_successes()
977 .saturating_add(coord.get_completed_swaps());
978 let aborts: u64 = snap
979 .get_handoff_aborts()
980 .saturating_add(coord.get_aborted_swaps());
981 let attempts: u64 = successes.saturating_add(aborts);
982 self.sync_adaptive_render_diagnostics(
983 active_label,
984 active_label,
985 coord.get_cpu_mirror_active(),
986 timing_label,
987 upload_label,
988 (attempts, successes, aborts),
989 );
990 }
991
992 pub fn reset_preferences_to_defaults(&self) {
998 let _: bool = self.get_auto_hide_chrome().set_if_changed(true);
999 let _: bool = self.get_show_fps_hud().set_if_changed(true);
1000 let _: bool = self.get_swipe_routing().set_if_changed(true);
1001 let _: bool = self.get_reduced_motion().set_if_changed(false);
1002 let _: bool = self.get_adaptive_auto_switch().set_if_changed(false);
1003 let _: bool = self
1004 .get_theme()
1005 .get_scheme()
1006 .set_if_changed(active_feature_scheme());
1007 let _: bool = self.get_theme().get_mode().set_if_changed(ThemeMode::Light);
1008 }
1009
1010 fn reactive_group(&self) -> ReactiveSignals {
1020 if let Some(existing) = self.get_reactive_signals().get() {
1021 return existing;
1022 }
1023 let created: ReactiveSignals = self.get_state_scope().enter(ReactiveSignals::create);
1024 self.get_reactive_signals().set(Some(created));
1025 created
1026 }
1027
1028 fn render_window_group(&self) -> RenderWindowSignals {
1038 if let Some(existing) = self.get_render_window_signals().get() {
1039 return existing;
1040 }
1041 let default_plat: usize = self.get_default_host_plat_idx().get();
1042 let created: RenderWindowSignals = self
1043 .get_state_scope()
1044 .enter(|| RenderWindowSignals::create(default_plat));
1045 self.get_render_window_signals().set(Some(created));
1046 created
1047 }
1048
1049 fn forms_group(&self) -> FormsSignals {
1059 if let Some(existing) = self.get_forms_signals().get() {
1060 return existing;
1061 }
1062 let created: FormsSignals = self.get_state_scope().enter(FormsSignals::create);
1063 self.get_forms_signals().set(Some(created));
1064 created
1065 }
1066
1067 fn overlays_group(&self) -> OverlaysSignals {
1077 if let Some(existing) = self.get_overlays_signals().get() {
1078 return existing;
1079 }
1080 let created: OverlaysSignals = self.get_state_scope().enter(OverlaysSignals::create);
1081 self.get_overlays_signals().set(Some(created));
1082 created
1083 }
1084
1085 fn data_group(&self) -> DataSignals {
1095 if let Some(existing) = self.get_data_signals().get() {
1096 return existing;
1097 }
1098 let created: DataSignals = self.get_state_scope().enter(DataSignals::create);
1099 self.get_data_signals().set(Some(created));
1100 created
1101 }
1102
1103 fn engine3d_group(&self) -> Engine3dSignals {
1113 Engine3dSignals::get_or_init(self.get_engine3d_signals().as_ref(), self.get_state_scope())
1114 }
1115
1116 fn dynamic_group(&self) -> DynamicSignals {
1126 DynamicSignals::get_or_init(self.get_dynamic_signals().as_ref(), self.get_state_scope())
1127 }
1128
1129 fn lab_group(&self) -> LabSignals {
1139 if let Some(existing) = self.get_lab_signals().get() {
1140 return existing;
1141 }
1142 let created: LabSignals = self.get_state_scope().enter(LabSignals::create);
1143 self.get_lab_signals().set(Some(created));
1144 created
1145 }
1146
1147 fn media_group(&self) -> MediaSignals {
1157 if let Some(existing) = self.get_media_signals().get() {
1158 return existing;
1159 }
1160 let created: MediaSignals = self.get_state_scope().enter(MediaSignals::create);
1161 self.get_media_signals().set(Some(created));
1162 created
1163 }
1164
1165 fn markdown_group(&self) -> MarkdownSignals {
1175 if let Some(existing) = self.get_markdown_signals().get() {
1176 return existing;
1177 }
1178 let created: MarkdownSignals = self.get_state_scope().enter(MarkdownSignals::create);
1179 self.get_markdown_signals().set(Some(created));
1180 created
1181 }
1182
1183 fn stress_group(&self) -> StressSignals {
1193 if let Some(existing) = self.get_stress_signals().get() {
1194 return existing;
1195 }
1196 let created: StressSignals = self.get_state_scope().enter(StressSignals::create);
1197 self.get_stress_signals().set(Some(created));
1198 created
1199 }
1200
1201 fn charts_group(&self) -> ChartsSignals {
1211 if let Some(existing) = self.get_charts_signals().get() {
1212 return existing;
1213 }
1214 let created: ChartsSignals = self.get_state_scope().enter(ChartsSignals::create);
1215 self.get_charts_signals().set(Some(created));
1216 created
1217 }
1218
1219 fn water_group(&self) -> WaterSignals {
1229 if let Some(existing) = self.get_water_signals().get() {
1230 return existing;
1231 }
1232 let created: WaterSignals = self.get_state_scope().enter(WaterSignals::create);
1233 self.get_water_signals().set(Some(created));
1234 created
1235 }
1236
1237 #[must_use]
1247 pub fn has_water_scene_initialized(&self) -> bool {
1248 self.get_water_scene_cell().borrow().is_some()
1249 }
1250
1251 #[must_use]
1261 pub fn get_or_init_water_scene(&self) -> GyroLiquidGameScene {
1262 if let Some(existing) = self.get_water_scene_cell().borrow().as_ref() {
1263 return existing.clone();
1264 }
1265 let created: GyroLiquidGameScene =
1266 GyroLiquidGameScene::with_config(LazyWaterScene::max_quality_config());
1267 *self.get_water_scene_cell().borrow_mut() = Some(created.clone());
1268 let _: bool = self
1269 .water_group()
1270 .get_stats()
1271 .set_if_changed(created.stats());
1272 created
1273 }
1274
1275 #[must_use]
1285 pub fn get_water_fill_pct(&self) -> Signal<f32> {
1286 self.water_group().get_fill_pct()
1287 }
1288
1289 #[must_use]
1299 pub fn get_water_viscosity_idx(&self) -> Signal<usize> {
1300 self.water_group().get_viscosity_idx()
1301 }
1302
1303 #[must_use]
1313 pub fn get_water_buoyant_enabled(&self) -> Signal<bool> {
1314 self.water_group().get_buoyant_enabled()
1315 }
1316
1317 #[must_use]
1327 pub fn get_water_fullscreen_open(&self) -> Signal<bool> {
1328 self.water_group().get_fullscreen_open()
1329 }
1330
1331 #[must_use]
1341 pub fn get_water_sensor_perm_status(&self) -> Signal<String> {
1342 self.water_group().get_sensor_perm_status()
1343 }
1344
1345 #[must_use]
1355 pub fn get_water_stats(&self) -> Signal<GyroLiquidStats> {
1356 self.water_group().get_stats()
1357 }
1358
1359 #[must_use]
1369 pub fn get_counter(&self) -> Signal<i32> {
1370 self.reactive_group().get_counter()
1371 }
1372
1373 #[must_use]
1383 pub fn get_doubled(&self) -> Memo<i32> {
1384 self.reactive_group().get_doubled()
1385 }
1386
1387 #[must_use]
1397 pub fn get_render_mode_index(&self) -> Signal<usize> {
1398 self.render_window_group().get_render_mode_index()
1399 }
1400
1401 #[must_use]
1411 pub fn get_demo_fps_cap_index(&self) -> Signal<usize> {
1412 self.render_window_group().get_demo_fps_cap_index()
1413 }
1414
1415 #[must_use]
1425 pub fn get_fullscreen(&self) -> Signal<bool> {
1426 self.render_window_group().get_fullscreen()
1427 }
1428
1429 #[must_use]
1439 pub fn get_island_active(&self) -> Signal<bool> {
1440 self.render_window_group().get_island_active()
1441 }
1442
1443 #[must_use]
1453 pub fn get_island_progress(&self) -> Signal<u8> {
1454 self.render_window_group().get_island_progress()
1455 }
1456
1457 #[must_use]
1467 pub fn get_camera_perm_status(&self) -> Signal<String> {
1468 self.render_window_group().get_camera_perm_status()
1469 }
1470
1471 #[must_use]
1481 pub fn get_protocol_status(&self) -> Signal<String> {
1482 self.render_window_group().get_protocol_status()
1483 }
1484
1485 #[must_use]
1495 pub fn get_a11y_announcements(&self) -> Signal<u32> {
1496 self.render_window_group().get_a11y_announcements()
1497 }
1498
1499 #[must_use]
1509 pub fn get_haptic_pulses(&self) -> Signal<u32> {
1510 self.render_window_group().get_haptic_pulses()
1511 }
1512
1513 #[must_use]
1523 pub fn get_os_target_platform_idx(&self) -> Signal<usize> {
1524 self.render_window_group().get_os_target_platform_idx()
1525 }
1526
1527 #[must_use]
1537 pub fn get_island_mode_idx(&self) -> Signal<usize> {
1538 self.render_window_group().get_island_mode_idx()
1539 }
1540
1541 #[must_use]
1551 pub fn get_system_notifications(&self) -> Signal<Vec<(String, String)>> {
1552 self.render_window_group().get_system_notifications()
1553 }
1554
1555 #[must_use]
1565 pub fn get_permission_statuses(&self) -> Signal<Vec<PermissionStatus>> {
1566 self.render_window_group().get_permission_statuses()
1567 }
1568
1569 #[must_use]
1579 pub fn get_username(&self) -> Signal<String> {
1580 self.forms_group().get_username()
1581 }
1582
1583 #[must_use]
1593 pub fn get_bio(&self) -> Signal<String> {
1594 self.forms_group().get_bio()
1595 }
1596
1597 #[must_use]
1607 pub fn get_stepper_value(&self) -> Signal<i64> {
1608 self.forms_group().get_stepper_value()
1609 }
1610
1611 #[must_use]
1621 pub fn get_radio_index(&self) -> Signal<usize> {
1622 self.forms_group().get_radio_index()
1623 }
1624
1625 #[must_use]
1635 pub fn get_slider_value(&self) -> Signal<f32> {
1636 self.forms_group().get_slider_value()
1637 }
1638
1639 #[must_use]
1649 pub fn get_select_index(&self) -> Signal<usize> {
1650 self.forms_group().get_select_index()
1651 }
1652
1653 #[must_use]
1663 pub fn get_select_open(&self) -> Signal<bool> {
1664 self.forms_group().get_select_open()
1665 }
1666
1667 #[must_use]
1677 pub fn get_rating_value(&self) -> Signal<usize> {
1678 self.forms_group().get_rating_value()
1679 }
1680
1681 #[must_use]
1691 pub fn get_pin_toggled(&self) -> Signal<bool> {
1692 self.forms_group().get_pin_toggled()
1693 }
1694
1695 #[must_use]
1705 pub fn get_hardware_accel(&self) -> Signal<bool> {
1706 self.forms_group().get_hardware_accel()
1707 }
1708
1709 #[must_use]
1719 pub fn get_agree_terms(&self) -> Signal<bool> {
1720 self.forms_group().get_agree_terms()
1721 }
1722
1723 #[must_use]
1733 pub fn get_active_tab(&self) -> Signal<usize> {
1734 self.forms_group().get_active_tab()
1735 }
1736
1737 #[must_use]
1747 pub fn get_page_index(&self) -> Signal<usize> {
1748 self.forms_group().get_page_index()
1749 }
1750
1751 #[must_use]
1761 pub fn get_step_index(&self) -> Signal<usize> {
1762 self.forms_group().get_step_index()
1763 }
1764
1765 #[must_use]
1775 pub fn get_accordion_open(&self) -> Signal<Option<usize>> {
1776 self.forms_group().get_accordion_open()
1777 }
1778
1779 #[must_use]
1789 pub fn get_picker_color(&self) -> Signal<Color> {
1790 self.forms_group().get_picker_color()
1791 }
1792
1793 #[must_use]
1803 pub fn get_picker_time(&self) -> Signal<(u8, u8)> {
1804 self.forms_group().get_picker_time()
1805 }
1806
1807 #[must_use]
1817 pub fn get_tag_items(&self) -> Signal<Vec<String>> {
1818 self.forms_group().get_tag_items()
1819 }
1820
1821 #[must_use]
1831 pub fn get_tree_selected(&self) -> Signal<Option<String>> {
1832 self.forms_group().get_tree_selected()
1833 }
1834
1835 #[must_use]
1845 pub fn get_breadcrumb_active(&self) -> Signal<usize> {
1846 self.forms_group().get_breadcrumb_active()
1847 }
1848
1849 #[must_use]
1859 pub fn get_modal_open(&self) -> Signal<bool> {
1860 self.overlays_group().get_modal_open()
1861 }
1862
1863 #[must_use]
1873 pub fn get_drawer_open(&self) -> Signal<bool> {
1874 self.overlays_group().get_drawer_open()
1875 }
1876
1877 #[must_use]
1887 pub fn get_sheet_open(&self) -> Signal<bool> {
1888 self.overlays_group().get_sheet_open()
1889 }
1890
1891 #[must_use]
1901 pub fn get_popover_open(&self) -> Signal<bool> {
1902 self.overlays_group().get_popover_open()
1903 }
1904
1905 #[must_use]
1915 pub fn get_dropdown_open(&self) -> Signal<bool> {
1916 self.overlays_group().get_dropdown_open()
1917 }
1918
1919 #[must_use]
1929 pub fn get_dropdown_selected(&self) -> Signal<Option<usize>> {
1930 self.overlays_group().get_dropdown_selected()
1931 }
1932
1933 #[must_use]
1943 pub fn get_toast_visible(&self) -> Signal<bool> {
1944 self.overlays_group().get_toast_visible()
1945 }
1946
1947 #[must_use]
1957 pub fn get_notif_visible(&self) -> Signal<bool> {
1958 self.overlays_group().get_notif_visible()
1959 }
1960
1961 #[must_use]
1971 pub fn get_loading_active(&self) -> Signal<bool> {
1972 self.overlays_group().get_loading_active()
1973 }
1974
1975 #[must_use]
1985 pub fn get_list_scroll_y(&self) -> Signal<f32> {
1986 self.data_group().get_list_scroll_y()
1987 }
1988
1989 #[must_use]
1999 pub fn get_engine3d_quality(&self) -> Signal<RenderQualityConfig> {
2000 self.engine3d_group().get_engine3d_quality()
2001 }
2002
2003 #[must_use]
2013 pub fn get_engine3d_preset_idx(&self) -> Signal<usize> {
2014 self.engine3d_group().get_engine3d_preset_idx()
2015 }
2016
2017 #[must_use]
2027 pub fn get_engine3d_rt_idx(&self) -> Signal<usize> {
2028 self.engine3d_group().get_engine3d_rt_idx()
2029 }
2030
2031 #[must_use]
2041 pub fn get_engine3d_res_scale(&self) -> Signal<f32> {
2042 self.engine3d_group().get_engine3d_res_scale()
2043 }
2044
2045 #[must_use]
2055 pub fn get_engine3d_time_of_day(&self) -> Signal<f32> {
2056 self.engine3d_group().get_engine3d_time_of_day()
2057 }
2058
2059 #[must_use]
2069 pub fn get_engine3d_import_queue(&self) -> Signal<u64> {
2070 self.engine3d_group().get_engine3d_import_queue()
2071 }
2072
2073 #[must_use]
2083 pub fn get_engine3d_import_status(&self) -> Signal<String> {
2084 self.engine3d_group().get_engine3d_import_status()
2085 }
2086
2087 #[must_use]
2097 pub fn get_engine3d_camera_mode(&self) -> Signal<u8> {
2098 self.engine3d_group().get_engine3d_camera_mode()
2099 }
2100
2101 #[must_use]
2107 pub fn get_engine3d_tsr_idx(&self) -> Signal<usize> {
2108 self.engine3d_group().get_engine3d_tsr_idx()
2109 }
2110
2111 #[must_use]
2121 pub fn get_engine3d_atmosphere_idx(&self) -> Signal<usize> {
2122 self.engine3d_group().get_engine3d_atmosphere_idx()
2123 }
2124
2125 #[must_use]
2135 pub fn get_engine3d_fullscreen_open(&self) -> Signal<bool> {
2136 self.engine3d_group().get_engine3d_fullscreen_open()
2137 }
2138
2139 pub(crate) fn resume_game_host(host: &GameEngineHost) {
2145 if host.is_paused() {
2146 if let Ok(mut input) = host.get_input().try_borrow_mut() {
2147 *input = InputState::default();
2148 }
2149 host.set_paused(false);
2150 }
2151 }
2152
2153 #[must_use]
2163 pub fn get_game_fullscreen_open(&self) -> Signal<bool> {
2164 if let Some(existing) = self.get_game_fullscreen_open_cell().get() {
2165 return existing;
2166 }
2167 let created: Signal<bool> = self.get_state_scope().enter(|| Signal::new(false));
2168 self.get_game_fullscreen_open_cell().set(Some(created));
2169 created
2170 }
2171
2172 #[must_use]
2182 pub fn get_sibling_counter(&self) -> Signal<i32> {
2183 self.dynamic_group().get_sibling_counter()
2184 }
2185
2186 #[must_use]
2196 pub fn get_dynamic_action_log(&self) -> Signal<String> {
2197 self.dynamic_group().get_dynamic_action_log()
2198 }
2199
2200 #[must_use]
2210 pub fn get_wasm_offline(&self) -> Signal<bool> {
2211 self.dynamic_group().get_wasm_offline()
2212 }
2213
2214 #[must_use]
2224 pub fn get_wasm_fault_status(&self) -> Signal<String> {
2225 self.dynamic_group().get_wasm_fault_status()
2226 }
2227
2228 #[must_use]
2238 pub fn get_alert_dialog_open(&self) -> Signal<bool> {
2239 self.lab_group().get_alert_dialog_open()
2240 }
2241
2242 #[must_use]
2252 pub fn get_alert_dialog_confirmed(&self) -> Signal<bool> {
2253 self.lab_group().get_alert_dialog_confirmed()
2254 }
2255
2256 #[must_use]
2266 pub fn get_collapsible_open(&self) -> Signal<bool> {
2267 self.lab_group().get_collapsible_open()
2268 }
2269
2270 #[must_use]
2280 pub fn get_toggle_group_index(&self) -> Signal<usize> {
2281 self.lab_group().get_toggle_group_index()
2282 }
2283
2284 #[must_use]
2294 pub fn get_otp_code(&self) -> Signal<String> {
2295 self.lab_group().get_otp_code()
2296 }
2297
2298 #[must_use]
2308 pub fn get_command_query(&self) -> Signal<String> {
2309 self.lab_group().get_command_query()
2310 }
2311
2312 #[must_use]
2322 pub fn get_command_selected(&self) -> Signal<Option<usize>> {
2323 self.lab_group().get_command_selected()
2324 }
2325
2326 #[must_use]
2336 pub fn get_hover_card_open(&self) -> Signal<bool> {
2337 self.lab_group().get_hover_card_open()
2338 }
2339
2340 #[must_use]
2350 pub fn get_calendar_day(&self) -> Signal<u32> {
2351 self.lab_group().get_calendar_day()
2352 }
2353
2354 #[must_use]
2364 pub fn get_menubar_active(&self) -> Signal<Option<usize>> {
2365 self.lab_group().get_menubar_active()
2366 }
2367
2368 #[must_use]
2378 pub fn get_carousel_index(&self) -> Signal<usize> {
2379 self.lab_group().get_carousel_index()
2380 }
2381
2382 #[must_use]
2392 pub fn get_lab_combobox_query(&self) -> Signal<String> {
2393 self.lab_group().get_lab_combobox_query()
2394 }
2395
2396 #[must_use]
2406 pub fn get_lab_combobox_selected(&self) -> Signal<usize> {
2407 self.lab_group().get_lab_combobox_selected()
2408 }
2409
2410 #[must_use]
2420 pub fn get_lab_combobox_open(&self) -> Signal<bool> {
2421 self.lab_group().get_lab_combobox_open()
2422 }
2423
2424 #[must_use]
2434 pub fn get_lab_table_filter(&self) -> Signal<String> {
2435 self.lab_group().get_lab_table_filter()
2436 }
2437
2438 #[must_use]
2448 pub fn get_lab_table_sort_asc(&self) -> Signal<bool> {
2449 self.lab_group().get_lab_table_sort_asc()
2450 }
2451
2452 #[must_use]
2462 pub fn get_lab_table_selected(&self) -> Signal<Option<usize>> {
2463 self.lab_group().get_lab_table_selected()
2464 }
2465
2466 #[must_use]
2476 pub fn get_lab_date_day(&self) -> Signal<u32> {
2477 self.lab_group().get_lab_date_day()
2478 }
2479
2480 #[must_use]
2490 pub fn get_lab_date_open(&self) -> Signal<bool> {
2491 self.lab_group().get_lab_date_open()
2492 }
2493
2494 #[must_use]
2504 pub fn get_lab_input_group_val(&self) -> Signal<String> {
2505 self.lab_group().get_lab_input_group_val()
2506 }
2507
2508 #[must_use]
2518 pub fn get_lab_native_select_idx(&self) -> Signal<usize> {
2519 self.lab_group().get_lab_native_select_idx()
2520 }
2521
2522 #[must_use]
2532 pub fn get_lab_nav_menu_active(&self) -> Signal<Option<usize>> {
2533 self.lab_group().get_lab_nav_menu_active()
2534 }
2535
2536 #[must_use]
2546 pub fn get_lab_split_ratio(&self) -> Signal<f32> {
2547 self.lab_group().get_lab_split_ratio()
2548 }
2549
2550 #[must_use]
2560 pub fn get_lab_block_scroll_chain(&self) -> Signal<bool> {
2561 self.lab_group().get_lab_block_scroll_chain()
2562 }
2563
2564 #[must_use]
2574 pub fn get_lab_stop_click_bubble(&self) -> Signal<bool> {
2575 self.lab_group().get_lab_stop_click_bubble()
2576 }
2577
2578 #[must_use]
2588 pub fn get_lab_parent_clicks(&self) -> Signal<u32> {
2589 self.lab_group().get_lab_parent_clicks()
2590 }
2591
2592 #[must_use]
2602 pub fn get_lab_child_clicks(&self) -> Signal<u32> {
2603 self.lab_group().get_lab_child_clicks()
2604 }
2605
2606 #[must_use]
2616 pub fn get_lab_resize_preserve_count(&self) -> Signal<u32> {
2617 self.lab_group().get_lab_resize_preserve_count()
2618 }
2619
2620 #[must_use]
2630 pub fn get_lab_rtl_mode(&self) -> Signal<bool> {
2631 self.lab_group().get_lab_rtl_mode()
2632 }
2633
2634 #[must_use]
2644 pub fn get_media_gif(&self) -> Signal<GifAnimation> {
2645 self.media_group().get_media_gif()
2646 }
2647
2648 #[must_use]
2658 pub fn get_media_live(&self) -> Signal<LivePhotoAsset> {
2659 self.media_group().get_media_live()
2660 }
2661
2662 #[must_use]
2672 pub fn get_media_video(&self) -> Signal<VideoTrack> {
2673 self.media_group().get_media_video()
2674 }
2675
2676 #[must_use]
2686 pub fn get_media_audio(&self) -> Signal<AudioTrack> {
2687 self.media_group().get_media_audio()
2688 }
2689
2690 #[must_use]
2700 pub fn get_media_pdf(&self) -> Signal<PdfDocument> {
2701 self.media_group().get_media_pdf()
2702 }
2703
2704 #[must_use]
2714 pub fn get_media_html_link_log(&self) -> Signal<String> {
2715 self.media_group().get_media_html_link_log()
2716 }
2717
2718 #[must_use]
2728 pub fn get_media_loading(&self) -> Signal<bool> {
2729 self.media_group().get_media_loading()
2730 }
2731
2732 #[must_use]
2742 pub fn get_markdown_copy_log(&self) -> Signal<String> {
2743 self.markdown_group().get_markdown_copy_log()
2744 }
2745
2746 #[must_use]
2756 pub fn get_markdown_link_log(&self) -> Signal<String> {
2757 self.markdown_group().get_markdown_link_log()
2758 }
2759
2760 #[must_use]
2770 pub fn get_markdown_tasks_toggled(&self) -> Signal<u32> {
2771 self.markdown_group().get_markdown_tasks_toggled()
2772 }
2773
2774 #[must_use]
2784 pub fn get_markdown_lang_tab(&self) -> Signal<usize> {
2785 self.markdown_group().get_markdown_lang_tab()
2786 }
2787
2788 #[must_use]
2798 pub fn get_markdown_selectable(&self) -> Signal<bool> {
2799 self.markdown_group().get_markdown_selectable()
2800 }
2801
2802 #[must_use]
2812 pub fn get_stress_results(&self) -> Signal<Vec<StressCaseResult>> {
2813 self.stress_group().get_stress_results()
2814 }
2815
2816 #[must_use]
2826 pub fn get_stress_summary(&self) -> Signal<String> {
2827 self.stress_group().get_stress_summary()
2828 }
2829
2830 #[must_use]
2840 pub fn get_charts_category_idx(&self) -> Signal<usize> {
2841 self.charts_group().get_charts_category_idx()
2842 }
2843
2844 #[must_use]
2854 pub fn get_charts_event_log(&self) -> Signal<String> {
2855 self.charts_group().get_charts_event_log()
2856 }
2857
2858 pub fn ensure_media_loaded(&self) {
2864 if self.get_media_loaded().replace(true) {
2865 return;
2866 }
2867 if self.get_bg_workers_enabled().get() {
2868 let group: MediaSignals = self.media_group();
2869 let _: bool = group.get_media_loading().set_if_changed(true);
2870 let task: BackgroundTask<MediaSampleBundle> =
2871 BackgroundTask::spawn(Self::build_media_sample_bundle);
2872 let _: bool = group.get_media_bg_task().set(Some(task));
2873 return;
2874 }
2875 let bundle: MediaSampleBundle = Self::build_media_sample_bundle();
2876 self.commit_media_sample_bundle(bundle);
2877 }
2878
2879 fn build_media_sample_bundle() -> MediaSampleBundle {
2885 MediaSampleBundle {
2886 gif: Self::build_decoded_sample_gif(),
2887 live: LivePhotoAsset::sample_live_photo(),
2888 video: Self::build_decoded_sample_mp4(),
2889 audio: AudioTrack::sample_synth_wav(),
2890 pdf: PdfDocument::sample_pdf(),
2891 }
2892 }
2893
2894 fn commit_media_sample_bundle(&self, bundle: MediaSampleBundle) {
2901 let group: MediaSignals = self.media_group();
2902 let MediaSampleBundle {
2903 gif,
2904 live,
2905 video,
2906 audio,
2907 pdf,
2908 } = bundle;
2909 let _: bool = group.get_media_gif().set(gif);
2910 let _: bool = group.get_media_live().set(live);
2911 let _: bool = group.get_media_video().set(video);
2912 let _: bool = group.get_media_audio().set(audio);
2913 let _: bool = group.get_media_pdf().set(pdf);
2914 let _: bool = group.get_media_loading().set_if_changed(false);
2915 }
2916
2917 fn build_decoded_sample_gif() -> GifAnimation {
2923 let width: u16 = 220;
2924 let height: u16 = 124;
2925 let palette: [[u8; 3]; 8] = [
2926 [17, 24, 39],
2927 [30, 41, 59],
2928 [56, 189, 248],
2929 [168, 85, 247],
2930 [244, 63, 94],
2931 [52, 211, 153],
2932 [226, 232, 240],
2933 [15, 23, 42],
2934 ];
2935 let pixel_count: usize = (width as usize) * (height as usize);
2936 let mut inputs: Vec<GifEncodeFrameInput> = Vec::with_capacity(8);
2937 for frame_idx in 0..8usize {
2938 let accent_idx: u8 = (2 + (frame_idx % 4)) as u8;
2939 let bar_x: usize = (frame_idx * 24) % (width as usize);
2940 let mut indices: Vec<u8> = vec![0u8; pixel_count];
2941 for pos_y in 0..(height as usize) {
2942 let row_off: usize = pos_y * (width as usize);
2943 let is_band: bool = (42..82).contains(&pos_y);
2944 for pos_x in 0..(width as usize) {
2945 let dist: usize = pos_x.abs_diff(bar_x);
2946 let color_idx: u8 = if is_band && dist < 18 {
2947 accent_idx
2948 } else if (pos_x / 16 + pos_y / 16 + frame_idx) % 2 == 0 {
2949 1
2950 } else {
2951 7
2952 };
2953 indices[row_off + pos_x] = color_idx;
2954 }
2955 }
2956 let mut frame: GifEncodeFrameInput = GifEncodeFrameInput::default();
2957 frame
2958 .set_width(width)
2959 .set_height(height)
2960 .set_disposal(GifDisposalMethod::Keep)
2961 .set_delay_cs(12)
2962 .set_indices(indices);
2963 inputs.push(frame);
2964 }
2965 let encoded: Vec<u8> = GifEncoder::encode(width, height, &palette, Some(0), &inputs);
2966 MediaCodecRegistry::decode_gif(&encoded, MEDIA_GIF_TITLE)
2967 .unwrap_or_else(|_: String| GifAnimation::sample_neon_gif())
2968 }
2969
2970 fn build_decoded_sample_mp4() -> VideoTrack {
2976 let width: u32 = 280;
2977 let height: u32 = 158;
2978 let accents: [Color; 4] = [
2979 Color::hex(0x22D3EE),
2980 Color::hex(0x6366F1),
2981 Color::hex(0xEC4899),
2982 Color::hex(0x10B981),
2983 ];
2984 let mut samples: Vec<Mp4BuilderSample> = Vec::with_capacity(12);
2985 for idx in 0..12usize {
2986 let img: ImageBuffer = MediaCodecRegistry::synthesize_frame(
2987 width,
2988 height,
2989 Color::hex(0x090D16),
2990 accents[idx % accents.len()],
2991 idx + 1,
2992 );
2993 let payload: Vec<u8> =
2994 SoftwareVideoDecoder::encode_intra_rgba_packet(width, height, img.get_pixels());
2995 let mut sample: Mp4BuilderSample = Mp4BuilderSample::default();
2996 sample
2997 .set_duration_ticks(1_000)
2998 .set_composition_offset_ticks(0)
2999 .set_is_keyframe(idx % 4 == 0)
3000 .set_payload(payload);
3001 samples.push(sample);
3002 }
3003 let mp4_bytes: Vec<u8> = Mp4ContainerBuilder::build_video_mp4(
3004 width,
3005 height,
3006 1_000,
3007 VideoCodec::H264,
3008 VideoColorInfo::hdr10_bt2020_pq(1000, 400),
3009 &samples,
3010 );
3011 match VideoTrack::from_mp4_bytes(mp4_bytes, MEDIA_VIDEO_TITLE) {
3012 Ok(mut track) => {
3013 let captions: Vec<String> = MEDIA_VIDEO_CAPTIONS
3014 .iter()
3015 .map(|line: &&str| (*line).to_string())
3016 .collect();
3017 track.set_captions(captions);
3018 track
3019 }
3020 Err(_) => VideoTrack::sample_hdr_video(),
3021 }
3022 }
3023
3024 pub fn ensure_wasm_registry_loaded(&self) {
3030 if self.get_wasm_registry_loaded().replace(true) {
3031 return;
3032 }
3033 if self.get_bg_workers_enabled().get() {
3034 let group: DynamicSignals = self.dynamic_group();
3035 let _: bool = group
3036 .get_wasm_fault_status()
3037 .set_if_changed(STATUS_WASM_LOADING.to_string());
3038 let task: BackgroundTask<WasmSampleBundle> =
3039 BackgroundTask::spawn(Self::build_wasm_sample_bundle);
3040 let _: bool = group.get_wasm_bg_task().set(Some(task));
3041 return;
3042 }
3043 Self::populate_wasm_registry(self.get_wasm_registry());
3044 }
3045
3046 pub fn ensure_wasm_registry_ready_now(&self) {
3052 self.ensure_wasm_registry_loaded();
3053 if let Some(group) = self.get_dynamic_signals().get()
3054 && let Some(task) = group.get_wasm_bg_task().get_untracked()
3055 && let Some(bundle) = task.take_blocking()
3056 {
3057 Self::commit_wasm_sample_bundle(self.get_wasm_registry(), bundle);
3058 let _: bool = group.get_wasm_bg_task().set(None);
3059 let _: bool = group
3060 .get_wasm_fault_status()
3061 .set_if_changed(DEFAULT_WASM_STATUS.to_string());
3062 }
3063 }
3064
3065 pub fn poll_async_loads(&self) -> bool {
3075 let mut committed: bool = false;
3076 if let Some(media) = self.get_media_signals().get()
3077 && let Some(task) = media.get_media_bg_task().get_untracked()
3078 && let Some(bundle) = task.try_take()
3079 {
3080 let _: bool = media.get_media_bg_task().set(None);
3081 self.commit_media_sample_bundle(bundle);
3082 committed = true;
3083 }
3084 if let Some(dyn_group) = self.get_dynamic_signals().get()
3085 && let Some(task) = dyn_group.get_wasm_bg_task().get_untracked()
3086 && let Some(bundle) = task.try_take()
3087 {
3088 let _: bool = dyn_group.get_wasm_bg_task().set(None);
3089 Self::commit_wasm_sample_bundle(self.get_wasm_registry(), bundle);
3090 let _: bool = dyn_group
3091 .get_wasm_fault_status()
3092 .set_if_changed(DEFAULT_WASM_STATUS.to_string());
3093 committed = true;
3094 }
3095 committed
3096 }
3097
3098 pub fn ensure_stress_loaded(&self) {
3104 if self.get_stress_loaded().replace(true) {
3105 return;
3106 }
3107 let _: bool = self.get_stress_results().set(default_stress_results());
3108 }
3109
3110 pub fn ensure_charts_loaded(&self) {
3116 let _: bool = self.get_charts_loaded().replace(true);
3117 }
3118
3119 fn build_wasm_sample_bundle() -> WasmSampleBundle {
3125 let p_v1: Vec<u8> = build_partial_widget_wasm(TITLE_WASM_PARTIAL_V1, 1, 0x2563EB);
3126 let p_v2: Vec<u8> = build_partial_widget_wasm(WASM_TITLE_PARTIAL_V2, 2, 0x7C3AED);
3127 let g_v1: Vec<u8> = build_global_app_wasm(WASM_TITLE_GLOBAL_V1, 1);
3128 let g_v2: Vec<u8> = build_global_app_wasm(WASM_TITLE_GLOBAL_V2, 2);
3129 let entries: Vec<WasmRegistryEntry> = vec![
3130 WasmRegistryEntry {
3131 url: URL_WASM_PARTIAL_V1.to_string(),
3132 bytes: p_v1.clone(),
3133 etag: WASM_ETAG_P1.to_string(),
3134 fault: WasmFaultKind::None,
3135 },
3136 WasmRegistryEntry {
3137 url: URL_WASM_PARTIAL_V2.to_string(),
3138 bytes: p_v2,
3139 etag: WASM_ETAG_P2.to_string(),
3140 fault: WasmFaultKind::None,
3141 },
3142 WasmRegistryEntry {
3143 url: URL_WASM_GLOBAL_V1.to_string(),
3144 bytes: g_v1,
3145 etag: WASM_ETAG_G1.to_string(),
3146 fault: WasmFaultKind::None,
3147 },
3148 WasmRegistryEntry {
3149 url: URL_WASM_GLOBAL_V2.to_string(),
3150 bytes: g_v2,
3151 etag: WASM_ETAG_G2.to_string(),
3152 fault: WasmFaultKind::None,
3153 },
3154 WasmRegistryEntry {
3155 url: URL_WASM_TIMEOUT_RETRY.to_string(),
3156 bytes: p_v1.clone(),
3157 etag: WASM_ETAG_RETRY.to_string(),
3158 fault: WasmFaultKind::TimeoutOnceThenSucceed,
3159 },
3160 WasmRegistryEntry {
3161 url: URL_WASM_HTTP_500.to_string(),
3162 bytes: p_v1.clone(),
3163 etag: WASM_ETAG_500.to_string(),
3164 fault: WasmFaultKind::Http500,
3165 },
3166 WasmRegistryEntry {
3167 url: URL_WASM_CORRUPTED.to_string(),
3168 bytes: build_faulty_wasm(WasmFaultKind::CorruptedMagic),
3169 etag: WASM_ETAG_CORRUPT.to_string(),
3170 fault: WasmFaultKind::None,
3171 },
3172 WasmRegistryEntry {
3173 url: URL_WASM_TAMPERED.to_string(),
3174 bytes: p_v1,
3175 etag: WASM_ETAG_TAMPER.to_string(),
3176 fault: WasmFaultKind::TamperedChecksum,
3177 },
3178 WasmRegistryEntry {
3179 url: URL_WASM_BAD_ABI.to_string(),
3180 bytes: build_faulty_wasm(WasmFaultKind::AbiMismatch),
3181 etag: WASM_ETAG_ABI.to_string(),
3182 fault: WasmFaultKind::None,
3183 },
3184 WasmRegistryEntry {
3185 url: URL_WASM_MISSING_EXPORT.to_string(),
3186 bytes: build_faulty_wasm(WasmFaultKind::MissingExport),
3187 etag: WASM_ETAG_NOEXP.to_string(),
3188 fault: WasmFaultKind::None,
3189 },
3190 WasmRegistryEntry {
3191 url: URL_WASM_FUEL_BOMB.to_string(),
3192 bytes: build_faulty_wasm(WasmFaultKind::InfiniteLoopOutOfFuel),
3193 etag: WASM_ETAG_FUEL.to_string(),
3194 fault: WasmFaultKind::None,
3195 },
3196 WasmRegistryEntry {
3197 url: URL_WASM_TRAP.to_string(),
3198 bytes: build_faulty_wasm(WasmFaultKind::ExecutionTrap),
3199 etag: WASM_ETAG_TRAP.to_string(),
3200 fault: WasmFaultKind::None,
3201 },
3202 WasmRegistryEntry {
3203 url: URL_WASM_OVERSIZED.to_string(),
3204 bytes: build_faulty_wasm(WasmFaultKind::OversizedBinary),
3205 etag: WASM_ETAG_BIG.to_string(),
3206 fault: WasmFaultKind::None,
3207 },
3208 ];
3209 WasmSampleBundle { entries }
3210 }
3211
3212 fn commit_wasm_sample_bundle(registry: &RegistryWasmFetcher, bundle: WasmSampleBundle) {
3219 let WasmSampleBundle { entries } = bundle;
3220 for entry in entries.into_iter() {
3221 let WasmRegistryEntry {
3222 url,
3223 bytes,
3224 etag,
3225 fault,
3226 } = entry;
3227 registry.register(url, bytes, etag, fault);
3228 }
3229 }
3230
3231 pub fn populate_wasm_registry(registry: &RegistryWasmFetcher) {
3237 let bundle: WasmSampleBundle = Self::build_wasm_sample_bundle();
3238 Self::commit_wasm_sample_bundle(registry, bundle);
3239 }
3240
3241 #[must_use]
3251 pub fn breadcrumb_for_route(route: &str) -> String {
3252 SHOWCASE_ROUTES
3253 .iter()
3254 .find(|spec: &&ShowcaseRouteSpec| spec.get_path() == route)
3255 .map(|spec: &ShowcaseRouteSpec| spec.get_title())
3256 .unwrap_or(route)
3257 .to_string()
3258 }
3259
3260 fn wire_dynamic_hub_actions(&self) {
3266 let route_sig: Signal<String> = self.get_route();
3267 let dyn_cell: Rc<Cell<Option<DynamicSignals>>> = self.get_dynamic_signals().clone();
3268 let owner_scope: Scope = self.get_state_scope();
3269 let mgr_act: WasmDynamicManager = self.get_wasm_manager().clone();
3270 self.get_dynamic_hub()
3271 .on_action(move |ui_event: &DynamicActionEvent| {
3272 let dyn_group: DynamicSignals =
3273 DynamicSignals::get_or_init(dyn_cell.as_ref(), owner_scope);
3274 let action_log: Signal<String> = dyn_group.get_dynamic_action_log();
3275 let wasm_status: Signal<String> = dyn_group.get_wasm_fault_status();
3276 let summary: String = format!(
3277 "{} from {} ({})",
3278 ui_event.get_action(),
3279 ui_event.get_source_id(),
3280 ui_event.get_payload()
3281 );
3282 let _: bool = action_log.set_if_changed(summary);
3283 if let Some(target_route) = ui_event.get_action().strip_prefix("navigate:") {
3284 let _: bool = route_sig.set_if_changed(target_route.to_string());
3285 } else if ui_event.get_action().as_str() == "return_dynamic" {
3286 let _: bool = route_sig.set_if_changed(ROUTE_DYNAMIC.to_string());
3287 } else if ui_event.get_action().as_str() == "wasm_interact" {
3288 let scope: WasmDynamicScope = WasmDynamicScope::Partial {
3289 slot_id: SLOT_WASM_WIDGET.to_string(),
3290 };
3291 match mgr_act.dispatch_wasm_event(&scope, 1) {
3292 Ok(next_st) => {
3293 let _: bool = wasm_status.set(format!(
3294 "WASM euv_on_event executed inside sandbox -> next_state={next_st} (native UI re-rendered)"
3295 ));
3296 }
3297 Err(err) => {
3298 let _: bool = wasm_status.set(format!("WASM event error: {err}"));
3299 }
3300 }
3301 } else if ui_event.get_action().as_str() == "global_wasm_action" {
3302 match mgr_act.dispatch_wasm_event(&WasmDynamicScope::Global, 1) {
3303 Ok(next_st) => {
3304 let _: bool = wasm_status.set(format!(
3305 "Global WASM euv_on_event executed live -> state={next_st} (full shell re-rendered)"
3306 ));
3307 }
3308 Err(err) => {
3309 let _: bool =
3310 wasm_status.set(format!("Global WASM event error: {err}"));
3311 }
3312 }
3313 } else if ui_event.get_action().as_str() == "global_wasm_rollback" {
3314 match mgr_act.rollback_global("user rollback") {
3315 Ok(ver) => {
3316 let _: bool = wasm_status.set(format!(
3317 "Rolled back Global WASM shell to v{ver} (0 = native shell)"
3318 ));
3319 }
3320 Err(_) => {
3321 mgr_act.restore_native_global();
3322 let _: bool =
3323 wasm_status.set(STATUS_RESTORED_NATIVE_SHELL.to_string());
3324 }
3325 }
3326 } else if ui_event.get_action().as_str() == "global_wasm_restore" {
3327 mgr_act.restore_native_global();
3328 let _: bool = wasm_status.set(STATUS_RESTORED_NATIVE_SHELL.to_string());
3329 }
3330 });
3331 }
3332
3333 pub fn attach_dynamic_hub(&mut self, hub: DynamicUpdateHub) {
3340 let wasm_mgr: WasmDynamicManager = WasmDynamicManager::new(
3341 hub.clone(),
3342 Rc::new(self.get_wasm_registry().clone()),
3343 WasmSandboxConfig::default(),
3344 );
3345 let Self {
3346 dynamic_hub,
3347 wasm_manager,
3348 router,
3349 ..
3350 } = self;
3351 let _: EuvRouter = router.clone().with_dynamic_hub(hub.clone());
3352 *dynamic_hub = hub;
3353 *wasm_manager = wasm_mgr;
3354 self.wire_dynamic_hub_actions();
3355 }
3356
3357 #[cfg(any(debug_assertions, test))]
3367 #[must_use]
3368 pub fn build_ai_hooks(&self) -> AiAppHooks {
3369 let route_get: Signal<String> = self.get_route();
3370 let route_set: Signal<String> = self.get_route();
3371 let theme_get: UiThemeState = self.get_theme().clone();
3372 let theme_set: UiThemeState = self.get_theme().clone();
3373 let e3d_stats_cell: Rc<Cell<Option<Engine3dSignals>>> = self.get_engine3d_signals().clone();
3374 let e3d_ctrl_cell: Rc<Cell<Option<Engine3dSignals>>> = self.get_engine3d_signals().clone();
3375 let owner_scope: Scope = self.get_state_scope();
3376 AiAppHooks::new()
3377 .on_route(move || route_get.get_untracked())
3378 .on_scheme(move || theme_get.get_scheme().get_untracked().as_str().to_string())
3379 .on_game_stats(move || {
3380 let green_val: Engine3dSignals =
3381 Engine3dSignals::get_or_init(e3d_stats_cell.as_ref(), owner_scope);
3382 let raw: String = format!(
3383 "{{\"preset_idx\":{},\"rt_idx\":{},\"resolution_scale_pct\":{:.1},\"time_of_day\":{:.2},\"camera_mode\":{},\"import_status\":{:?}}}",
3384 green_val.get_engine3d_preset_idx().get_untracked(),
3385 green_val.get_engine3d_rt_idx().get_untracked(),
3386 green_val.get_engine3d_res_scale().get_untracked(),
3387 green_val.get_engine3d_time_of_day().get_untracked(),
3388 green_val.get_engine3d_camera_mode().get_untracked(),
3389 green_val.get_engine3d_import_status().get_untracked()
3390 );
3391 AiSchemaProtocol::parse_json_value(&raw)
3392 })
3393 .on_navigate(move |target: &str| {
3394 let _: bool = route_set.set_if_changed(target.to_string());
3395 Ok(())
3396 })
3397 .on_set_theme(move |scheme_opt: Option<&str>, mode_opt: Option<&str>| {
3398 if let Some(s_name) = scheme_opt {
3399 let matched: Option<DesignScheme> = DesignScheme::all()
3400 .into_iter()
3401 .find(|ds: &DesignScheme| ds.as_str().eq_ignore_ascii_case(s_name));
3402 match matched {
3403 Some(ds) => theme_set.select_scheme(ds),
3404 None => return Err(format!("Unknown design scheme: {s_name}")),
3405 }
3406 }
3407 if let Some(m_name) = mode_opt {
3408 let next_mode: ThemeMode = if m_name.eq_ignore_ascii_case("Dark") {
3409 ThemeMode::Dark
3410 } else if m_name.eq_ignore_ascii_case("Light") {
3411 ThemeMode::Light
3412 } else {
3413 return Err(format!("Unknown theme mode: {m_name}"));
3414 };
3415 let _: bool = theme_set.get_mode().set_if_changed(next_mode);
3416 }
3417 Ok(())
3418 })
3419 .on_game_control(move |cmd: &str, payload: &Value| {
3420 let geometry_val: Engine3dSignals =
3421 Engine3dSignals::get_or_init(e3d_ctrl_cell.as_ref(), owner_scope);
3422 let num_val: f64 = payload
3423 .as_f64()
3424 .or_else(|| payload.get("value").and_then(|item_val: &Value| item_val.as_f64()))
3425 .unwrap_or(0.0);
3426 match cmd {
3427 "camera_mode" => {
3428 let next_cam: u8 = (num_val.round() as u8).min(3);
3429 let _: bool = geometry_val.get_engine3d_camera_mode().set_if_changed(next_cam);
3430 Ok(AiSchemaProtocol::parse_json_value(&format!(
3431 "{{\"camera_mode\":{next_cam}}}"
3432 )))
3433 }
3434 "preset" => {
3435 let next_p: usize = (num_val.round() as usize).min(4);
3436 let _: bool = geometry_val.get_engine3d_preset_idx().set_if_changed(next_p);
3437 Ok(AiSchemaProtocol::parse_json_value(&format!(
3438 "{{\"preset_idx\":{next_p}}}"
3439 )))
3440 }
3441 "ray_tracing" => {
3442 let next_rt: usize = (num_val.round() as usize).min(3);
3443 let _: bool = geometry_val.get_engine3d_rt_idx().set_if_changed(next_rt);
3444 Ok(AiSchemaProtocol::parse_json_value(&format!(
3445 "{{\"rt_idx\":{next_rt}}}"
3446 )))
3447 }
3448 "resolution_scale" => {
3449 let next_s: f32 = (num_val as f32).clamp(40.0, 125.0);
3450 let _: bool = geometry_val.get_engine3d_res_scale().set_if_changed(next_s);
3451 Ok(AiSchemaProtocol::parse_json_value(&format!(
3452 "{{\"resolution_scale_pct\":{next_s:.1}}}"
3453 )))
3454 }
3455 "time_of_day" => {
3456 let next_t: f32 = (num_val as f32).clamp(6.0, 23.0);
3457 let _: bool = geometry_val.get_engine3d_time_of_day().set_if_changed(next_t);
3458 Ok(AiSchemaProtocol::parse_json_value(&format!(
3459 "{{\"time_of_day\":{next_t:.2}}}"
3460 )))
3461 }
3462 "import_model" => {
3463 let next_q: u64 = geometry_val
3464 .get_engine3d_import_queue()
3465 .get_untracked()
3466 .saturating_add(1);
3467 let _: bool = geometry_val.get_engine3d_import_queue().set_if_changed(next_q);
3468 Ok(AiSchemaProtocol::parse_json_value(&format!(
3469 "{{\"import_queue\":{next_q}}}"
3470 )))
3471 }
3472 other => Err(format!("Unknown game control command: {other}")),
3473 }
3474 })
3475 .on_set_config({
3476 let node_style: ShowcaseState = self.clone();
3477 move |key: &str, value: &Value| {
3478 let as_bool = |tex_v: &Value| -> Result<bool, String> {
3479 tex_v.as_bool()
3480 .ok_or_else(|| format!("Config key '{key}' expects a boolean value"))
3481 };
3482 let as_usize = |bary_v: &Value| -> Result<usize, String> {
3483 bary_v.as_u64()
3484 .map(|item_count: u64| item_count as usize)
3485 .ok_or_else(|| format!("Config key '{key}' expects an unsigned integer"))
3486 };
3487 let as_f32 = |sample_val: &Value| -> Result<f32, String> {
3488 sample_val.as_f64()
3489 .map(|node_entry: f64| node_entry as f32)
3490 .ok_or_else(|| format!("Config key '{key}' expects a numeric value"))
3491 };
3492 match key {
3493 "route" => {
3494 let target: &str = value.as_str().ok_or_else(|| {
3495 "Config key 'route' expects a string path".to_string()
3496 })?;
3497 let _: bool = node_style.get_route().set_if_changed(target.to_string());
3498 Ok(Value::String(target.to_string()))
3499 }
3500 "theme.scheme" => {
3501 let s_name: &str = value.as_str().ok_or_else(|| {
3502 "Config key 'theme.scheme' expects a string".to_string()
3503 })?;
3504 let matched: Option<DesignScheme> = DesignScheme::all()
3505 .into_iter()
3506 .find(|ds: &DesignScheme| ds.as_str().eq_ignore_ascii_case(s_name));
3507 match matched {
3508 Some(ds) => {
3509 node_style.get_theme().select_scheme(ds);
3510 Ok(Value::String(ds.as_str().to_string()))
3511 }
3512 None => Err(format!("Unknown design scheme: {s_name}")),
3513 }
3514 }
3515 "theme.mode" => {
3516 let m_name: &str = value.as_str().ok_or_else(|| {
3517 "Config key 'theme.mode' expects 'Light' or 'Dark'".to_string()
3518 })?;
3519 let next_mode: ThemeMode = if m_name.eq_ignore_ascii_case("Dark") {
3520 ThemeMode::Dark
3521 } else if m_name.eq_ignore_ascii_case("Light") {
3522 ThemeMode::Light
3523 } else {
3524 return Err(format!("Unknown theme mode: {m_name}"));
3525 };
3526 let _: bool = node_style.get_theme().get_mode().set_if_changed(next_mode);
3527 Ok(Value::String(
3528 if next_mode == ThemeMode::Dark {
3529 "Dark"
3530 } else {
3531 "Light"
3532 }
3533 .to_string(),
3534 ))
3535 }
3536 "shell.auto_hide_chrome" => {
3537 let flag_value: bool = as_bool(value)?;
3538 let _: bool = node_style.get_auto_hide_chrome().set_if_changed(flag_value);
3539 Ok(Value::Bool(flag_value))
3540 }
3541 "shell.show_fps_hud" => {
3542 let is_matched: bool = as_bool(value)?;
3543 let _: bool = node_style.get_show_fps_hud().set_if_changed(is_matched);
3544 Ok(Value::Bool(is_matched))
3545 }
3546 "shell.swipe_routing" => {
3547 let blue_val: bool = as_bool(value)?;
3548 let _: bool = node_style.get_swipe_routing().set_if_changed(blue_val);
3549 Ok(Value::Bool(blue_val))
3550 }
3551 "shell.reduced_motion" => {
3552 let byte_val: bool = as_bool(value)?;
3553 let _: bool = node_style.get_reduced_motion().set_if_changed(byte_val);
3554 Ok(Value::Bool(byte_val))
3555 }
3556 "shell.cmd_palette_open" => {
3557 let bounds_val: bool = as_bool(value)?;
3558 let _: bool = node_style.get_cmd_palette_open().set_if_changed(bounds_val);
3559 Ok(Value::Bool(bounds_val))
3560 }
3561 "render.adaptive_auto_switch" => {
3562 let second_val: bool = as_bool(value)?;
3563 let _: bool = node_style.get_adaptive_auto_switch().set_if_changed(second_val);
3564 Ok(Value::Bool(second_val))
3565 }
3566 "render.mode_index" => {
3567 let idx: usize = if let Some(source_val) = value.as_str() {
3568 if source_val.eq_ignore_ascii_case("Software") {
3569 1
3570 } else if source_val.eq_ignore_ascii_case("Hardware") {
3571 2
3572 } else if source_val.eq_ignore_ascii_case("Hybrid") {
3573 3
3574 } else {
3575 0
3576 }
3577 } else {
3578 as_usize(value)?.min(3)
3579 };
3580 let _: bool = node_style.get_render_mode_index().set_if_changed(idx);
3581 Ok(Value::from(idx as u64))
3582 }
3583 "window.fullscreen" => {
3584 let flag_value_primary: bool = as_bool(value)?;
3585 let _: bool = node_style.get_fullscreen().set_if_changed(flag_value_primary);
3586 Ok(Value::Bool(flag_value_primary))
3587 }
3588 "window.demo_fps_cap_index" => {
3589 let idx: usize = as_usize(value)?.min(6);
3590 let _: bool = node_style.get_demo_fps_cap_index().set_if_changed(idx);
3591 Ok(Value::from(idx as u64))
3592 }
3593 "markdown.selectable" => {
3594 let flag_value_secondary: bool = as_bool(value)?;
3595 let _: bool = node_style.get_markdown_selectable().set_if_changed(flag_value_secondary);
3596 Ok(Value::Bool(flag_value_secondary))
3597 }
3598 "markdown.lang_tab" => {
3599 let idx: usize = as_usize(value)?.min(3);
3600 let _: bool = node_style.get_markdown_lang_tab().set_if_changed(idx);
3601 Ok(Value::from(idx as u64))
3602 }
3603 "charts.category_idx" => {
3604 let idx: usize = as_usize(value)?.min(5);
3605 let _: bool = node_style.get_charts_category_idx().set_if_changed(idx);
3606 Ok(Value::from(idx as u64))
3607 }
3608 "lab.rtl" => {
3609 let flag_value_next: bool = as_bool(value)?;
3610 let _: bool = node_style.get_lab_rtl_mode().set_if_changed(flag_value_next);
3611 Ok(Value::Bool(flag_value_next))
3612 }
3613 "lab.block_scroll_chain" => {
3614 let flag_value_alt: bool = as_bool(value)?;
3615 let _: bool = node_style.get_lab_block_scroll_chain().set_if_changed(flag_value_alt);
3616 Ok(Value::Bool(flag_value_alt))
3617 }
3618 "lab.stop_click_bubble" => {
3619 let flag_value_inner: bool = as_bool(value)?;
3620 let _: bool = node_style.get_lab_stop_click_bubble().set_if_changed(flag_value_inner);
3621 Ok(Value::Bool(flag_value_inner))
3622 }
3623 "overlays.modal_open" => {
3624 let flag_value_local: bool = as_bool(value)?;
3625 let _: bool = node_style.get_modal_open().set_if_changed(flag_value_local);
3626 Ok(Value::Bool(flag_value_local))
3627 }
3628 "overlays.drawer_open" => {
3629 let flag_value_cur: bool = as_bool(value)?;
3630 let _: bool = node_style.get_drawer_open().set_if_changed(flag_value_cur);
3631 Ok(Value::Bool(flag_value_cur))
3632 }
3633 "overlays.sheet_open" => {
3634 let flag_value_slot: bool = as_bool(value)?;
3635 let _: bool = node_style.get_sheet_open().set_if_changed(flag_value_slot);
3636 Ok(Value::Bool(flag_value_slot))
3637 }
3638 "overlays.popover_open" => {
3639 let flag_value_2: bool = as_bool(value)?;
3640 let _: bool = node_style.get_popover_open().set_if_changed(flag_value_2);
3641 Ok(Value::Bool(flag_value_2))
3642 }
3643 "overlays.toast_visible" => {
3644 let flag_value_3: bool = as_bool(value)?;
3645 let _: bool = node_style.get_toast_visible().set_if_changed(flag_value_3);
3646 Ok(Value::Bool(flag_value_3))
3647 }
3648 "overlays.loading_active" => {
3649 let flag_value_4: bool = as_bool(value)?;
3650 let _: bool = node_style.get_loading_active().set_if_changed(flag_value_4);
3651 Ok(Value::Bool(flag_value_4))
3652 }
3653 "water.fill_pct" => {
3654 let pct: f32 = as_f32(value)?.clamp(25.0, 80.0);
3655 let _: bool = node_style.get_water_fill_pct().set_if_changed(pct);
3656 Ok(Value::from(pct))
3657 }
3658 "water.viscosity_idx" => {
3659 let idx: usize = as_usize(value)?.min(2);
3660 let _: bool = node_style.get_water_viscosity_idx().set_if_changed(idx);
3661 Ok(Value::from(idx as u64))
3662 }
3663 "water.buoyant_enabled" => {
3664 let flag_value_5: bool = as_bool(value)?;
3665 let _: bool = node_style.get_water_buoyant_enabled().set_if_changed(flag_value_5);
3666 Ok(Value::Bool(flag_value_5))
3667 }
3668 "engine3d.preset_idx" => {
3669 let idx: usize = as_usize(value)?.min(4);
3670 let _: bool = node_style.get_engine3d_preset_idx().set_if_changed(idx);
3671 Ok(Value::from(idx as u64))
3672 }
3673 "engine3d.rt_idx" => {
3674 let idx: usize = as_usize(value)?.min(3);
3675 let _: bool = node_style.get_engine3d_rt_idx().set_if_changed(idx);
3676 Ok(Value::from(idx as u64))
3677 }
3678 "engine3d.res_scale" => {
3679 let scale: f32 = as_f32(value)?.clamp(40.0, 125.0);
3680 let _: bool = node_style.get_engine3d_res_scale().set_if_changed(scale);
3681 Ok(Value::from(scale))
3682 }
3683 "engine3d.time_of_day" => {
3684 let tod: f32 = as_f32(value)?.clamp(6.0, 23.0);
3685 let _: bool = node_style.get_engine3d_time_of_day().set_if_changed(tod);
3686 Ok(Value::from(tod))
3687 }
3688 "engine3d.camera_mode" => {
3689 let mode: u8 = (as_usize(value)? as u8).min(3);
3690 let _: bool = node_style.get_engine3d_camera_mode().set_if_changed(mode);
3691 Ok(Value::from(mode))
3692 }
3693 "reset_defaults" => {
3694 let flag_value_6: bool = as_bool(value)?;
3695 if flag_value_6 {
3696 node_style.reset_preferences_to_defaults();
3697 }
3698 Ok(Value::Bool(flag_value_6))
3699 }
3700 other => Err(format!("Unknown showcase config key: {other}")),
3701 }
3702 }
3703 })
3704 .on_get_config({
3705 let active_style: ShowcaseState = self.clone();
3706 move |_keys: &[String]| {
3707 let mode_str: &str = if active_style.get_theme().get_mode().get_untracked()
3708 == ThemeMode::Dark
3709 {
3710 "Dark"
3711 } else {
3712 "Light"
3713 };
3714 let mut parts: Vec<String> = vec![
3715 format!("\"route\":{:?}", active_style.get_route().get_untracked()),
3716 format!(
3717 "\"theme.scheme\":{:?}",
3718 active_style.get_theme().get_scheme().get_untracked().as_str()
3719 ),
3720 format!("\"theme.mode\":{:?}", mode_str),
3721 format!(
3722 "\"shell.auto_hide_chrome\":{}",
3723 active_style.get_auto_hide_chrome().get_untracked()
3724 ),
3725 format!(
3726 "\"shell.show_fps_hud\":{}",
3727 active_style.get_show_fps_hud().get_untracked()
3728 ),
3729 format!(
3730 "\"shell.swipe_routing\":{}",
3731 active_style.get_swipe_routing().get_untracked()
3732 ),
3733 format!(
3734 "\"shell.reduced_motion\":{}",
3735 active_style.get_reduced_motion().get_untracked()
3736 ),
3737 format!(
3738 "\"shell.cmd_palette_open\":{}",
3739 active_style.get_cmd_palette_open().get_untracked()
3740 ),
3741 format!(
3742 "\"render.adaptive_auto_switch\":{}",
3743 active_style.get_adaptive_auto_switch().get_untracked()
3744 ),
3745 ];
3746 if let Some(rw) = active_style.get_render_window_signals().get() {
3747 parts.push(format!(
3748 "\"render.mode_index\":{}",
3749 rw.get_render_mode_index().get_untracked()
3750 ));
3751 parts.push(format!(
3752 "\"window.fullscreen\":{}",
3753 rw.get_fullscreen().get_untracked()
3754 ));
3755 parts.push(format!(
3756 "\"window.demo_fps_cap_index\":{}",
3757 rw.get_demo_fps_cap_index().get_untracked()
3758 ));
3759 }
3760 if let Some(md) = active_style.get_markdown_signals().get() {
3761 parts.push(format!(
3762 "\"markdown.selectable\":{}",
3763 md.get_markdown_selectable().get_untracked()
3764 ));
3765 parts.push(format!(
3766 "\"markdown.lang_tab\":{}",
3767 md.get_markdown_lang_tab().get_untracked()
3768 ));
3769 }
3770 if let Some(ch) = active_style.get_charts_signals().get() {
3771 parts.push(format!(
3772 "\"charts.category_idx\":{}",
3773 ch.get_charts_category_idx().get_untracked()
3774 ));
3775 }
3776 if let Some(lab) = active_style.get_lab_signals().get() {
3777 parts.push(format!(
3778 "\"lab.rtl\":{}",
3779 lab.get_lab_rtl_mode().get_untracked()
3780 ));
3781 parts.push(format!(
3782 "\"lab.block_scroll_chain\":{}",
3783 lab.get_lab_block_scroll_chain().get_untracked()
3784 ));
3785 parts.push(format!(
3786 "\"lab.stop_click_bubble\":{}",
3787 lab.get_lab_stop_click_bubble().get_untracked()
3788 ));
3789 }
3790 if let Some(overflow_mode) = active_style.get_overlays_signals().get() {
3791 parts.push(format!(
3792 "\"overlays.modal_open\":{}",
3793 overflow_mode.get_modal_open().get_untracked()
3794 ));
3795 parts.push(format!(
3796 "\"overlays.drawer_open\":{}",
3797 overflow_mode.get_drawer_open().get_untracked()
3798 ));
3799 parts.push(format!(
3800 "\"overlays.sheet_open\":{}",
3801 overflow_mode.get_sheet_open().get_untracked()
3802 ));
3803 }
3804 if let Some(width_val) = active_style.get_water_signals().get() {
3805 parts.push(format!(
3806 "\"water.fill_pct\":{:.1}",
3807 width_val.get_fill_pct().get_untracked()
3808 ));
3809 parts.push(format!(
3810 "\"water.viscosity_idx\":{}",
3811 width_val.get_viscosity_idx().get_untracked()
3812 ));
3813 parts.push(format!(
3814 "\"water.buoyant_enabled\":{}",
3815 width_val.get_buoyant_enabled().get_untracked()
3816 ));
3817 }
3818 if let Some(e3d) = active_style.get_engine3d_signals().get() {
3819 parts.push(format!(
3820 "\"engine3d.preset_idx\":{}",
3821 e3d.get_engine3d_preset_idx().get_untracked()
3822 ));
3823 parts.push(format!(
3824 "\"engine3d.rt_idx\":{}",
3825 e3d.get_engine3d_rt_idx().get_untracked()
3826 ));
3827 parts.push(format!(
3828 "\"engine3d.res_scale\":{:.1}",
3829 e3d.get_engine3d_res_scale().get_untracked()
3830 ));
3831 parts.push(format!(
3832 "\"engine3d.time_of_day\":{:.2}",
3833 e3d.get_engine3d_time_of_day().get_untracked()
3834 ));
3835 parts.push(format!(
3836 "\"engine3d.camera_mode\":{}",
3837 e3d.get_engine3d_camera_mode().get_untracked()
3838 ));
3839 }
3840 AiSchemaProtocol::parse_json_value(&format!("{{{}}}", parts.join(",")))
3841 }
3842 })
3843 }
3844
3845 #[must_use]
3851 pub fn nav_items() -> Vec<EuvNavItem> {
3852 SHOWCASE_ROUTES
3853 .iter()
3854 .map(|spec: &ShowcaseRouteSpec| {
3855 EuvNavItem::new(spec.get_path().to_string(), spec.get_label().to_string())
3856 .section(spec.get_section())
3857 })
3858 .collect()
3859 }
3860
3861 #[must_use]
3871 pub fn selected_render_mode(&self) -> RenderMode {
3872 match self.get_render_mode_index().get_untracked() {
3873 1 => RenderMode::Software,
3874 2 => RenderMode::Hardware,
3875 3 => RenderMode::Hybrid,
3876 _ => RenderMode::Auto,
3877 }
3878 }
3879
3880 #[must_use]
3890 pub fn selected_demo_fps_cap(&self) -> Option<u32> {
3891 match self.get_demo_fps_cap_index().get_untracked() {
3892 1 => Some(30),
3893 2 => Some(60),
3894 3 => Some(120),
3895 4 => Some(144),
3896 5 => Some(240),
3897 6 => Some(360),
3898 _ => None,
3899 }
3900 }
3901
3902 pub fn next_scheme(&self) {
3908 let all: [DesignScheme; 17] = DesignScheme::all();
3909 let current: DesignScheme = self.get_theme().get_scheme().get_untracked();
3910 let pos: usize = all
3911 .iter()
3912 .position(|source_val: &DesignScheme| *source_val == current)
3913 .unwrap_or(0);
3914 let next: DesignScheme = all[(pos + 1) % all.len()];
3915 let _: bool = self.get_theme().get_scheme().set_if_changed(next);
3916 }
3917
3918 pub fn toggle_theme_mode(&self) {
3924 let cur: ThemeMode = self.get_theme().get_mode().get_untracked();
3925 let next: ThemeMode = match cur {
3926 ThemeMode::Light => ThemeMode::Dark,
3927 ThemeMode::Dark => ThemeMode::Light,
3928 };
3929 let _: bool = self.get_theme().get_mode().set_if_changed(next);
3930 }
3931
3932 pub fn freeze_for_background(&self) {
3938 if self.get_bg_frozen().get_untracked() {
3939 return;
3940 }
3941 let game2d_running: bool = !self.get_game_host().is_paused();
3942 self.get_bg_snap_game2d_running().set(game2d_running);
3943 self.get_game_host().set_paused(true);
3944 let game3d_running: bool = !self.get_game3d_host().is_paused();
3945 self.get_bg_snap_game3d_running().set(game3d_running);
3946 self.get_game3d_host().set_paused(true);
3947 let water_running: bool = !self.get_water_host().is_paused();
3948 self.get_bg_snap_water_running().set(water_running);
3949 self.get_water_host().set_paused(true);
3950 if self.get_media_loaded().get() {
3951 let gif_playing: bool = self.get_media_gif().get_untracked().get_playing();
3952 self.get_bg_snap_gif_playing().set(gif_playing);
3953 if gif_playing {
3954 let _: bool = {
3955 if let Some(mut updated_value) = (self.get_media_gif()).try_get_untracked() {
3956 {
3957 let gif: &mut GifAnimation = &mut updated_value;
3958 gif.set_playing(false);
3959 }
3960 (self.get_media_gif()).set(updated_value)
3961 } else {
3962 false
3963 }
3964 };
3965 }
3966 let live_playing: bool = self.get_media_live().get_untracked().get_active_motion();
3967 self.get_bg_snap_live_playing().set(live_playing);
3968 if live_playing {
3969 let _: bool = {
3970 if let Some(mut updated_value) = (self.get_media_live()).try_get_untracked() {
3971 {
3972 let live: &mut LivePhotoAsset = &mut updated_value;
3973 live.set_motion_playing(false);
3974 }
3975 (self.get_media_live()).set(updated_value)
3976 } else {
3977 false
3978 }
3979 };
3980 }
3981 let video_playing: bool =
3982 self.get_media_video().get_untracked().get_state() == PlaybackState::Playing;
3983 self.get_bg_snap_video_playing().set(video_playing);
3984 if video_playing {
3985 let _: bool = {
3986 if let Some(mut updated_value) = (self.get_media_video()).try_get_untracked() {
3987 {
3988 let video: &mut VideoTrack = &mut updated_value;
3989 video.set_state(PlaybackState::Paused);
3990 }
3991 (self.get_media_video()).set(updated_value)
3992 } else {
3993 false
3994 }
3995 };
3996 }
3997 let audio_playing: bool =
3998 self.get_media_audio().get_untracked().get_state() == PlaybackState::Playing;
3999 self.get_bg_snap_audio_playing().set(audio_playing);
4000 if audio_playing {
4001 let _: bool = {
4002 if let Some(mut updated_value) = (self.get_media_audio()).try_get_untracked() {
4003 {
4004 let audio: &mut AudioTrack = &mut updated_value;
4005 audio.set_state(PlaybackState::Paused);
4006 }
4007 (self.get_media_audio()).set(updated_value)
4008 } else {
4009 false
4010 }
4011 };
4012 }
4013 }
4014 let _: bool = self.get_bg_frozen().set_if_changed(true);
4015 let _: bool = {
4016 if let Some(mut updated_value) = (self.get_bg_freeze_count()).try_get_untracked() {
4017 {
4018 let count: &mut u32 = &mut updated_value;
4019 *count = count.saturating_add(1);
4020 }
4021 (self.get_bg_freeze_count()).set(updated_value)
4022 } else {
4023 false
4024 }
4025 };
4026 }
4027
4028 pub fn restore_from_foreground(&self) {
4034 if !self.get_bg_frozen().get_untracked() {
4035 return;
4036 }
4037 let active_route: String = self.get_route().get_untracked();
4038 if self.get_bg_snap_game2d_running().replace(false) && active_route == ROUTE_GAME {
4039 Self::resume_game_host(self.get_game_host());
4040 }
4041 if self.get_bg_snap_game3d_running().replace(false) && active_route == ROUTE_GAME_3D {
4042 Self::resume_game_host(self.get_game3d_host());
4043 }
4044 if self.get_bg_snap_water_running().replace(false) && active_route == ROUTE_WATER {
4045 Self::resume_game_host(self.get_water_host());
4046 }
4047 if self.get_bg_snap_gif_playing().replace(false) {
4048 let _: bool = {
4049 if let Some(mut updated_value) = (self.get_media_gif()).try_get_untracked() {
4050 {
4051 let gif: &mut GifAnimation = &mut updated_value;
4052 gif.set_playing(true);
4053 }
4054 (self.get_media_gif()).set(updated_value)
4055 } else {
4056 false
4057 }
4058 };
4059 }
4060 if self.get_bg_snap_live_playing().replace(false) {
4061 let _: bool = {
4062 if let Some(mut updated_value) = (self.get_media_live()).try_get_untracked() {
4063 {
4064 let live: &mut LivePhotoAsset = &mut updated_value;
4065 live.set_motion_playing(true);
4066 }
4067 (self.get_media_live()).set(updated_value)
4068 } else {
4069 false
4070 }
4071 };
4072 }
4073 if self.get_bg_snap_video_playing().replace(false) {
4074 let _: bool = {
4075 if let Some(mut updated_value) = (self.get_media_video()).try_get_untracked() {
4076 {
4077 let video: &mut VideoTrack = &mut updated_value;
4078 video.set_state(PlaybackState::Playing);
4079 }
4080 (self.get_media_video()).set(updated_value)
4081 } else {
4082 false
4083 }
4084 };
4085 }
4086 if self.get_bg_snap_audio_playing().replace(false) {
4087 let _: bool = {
4088 if let Some(mut updated_value) = (self.get_media_audio()).try_get_untracked() {
4089 {
4090 let audio: &mut AudioTrack = &mut updated_value;
4091 audio.set_state(PlaybackState::Playing);
4092 }
4093 (self.get_media_audio()).set(updated_value)
4094 } else {
4095 false
4096 }
4097 };
4098 }
4099 let _: bool = self.get_bg_frozen().set_if_changed(false);
4100 let _: bool = {
4101 if let Some(mut updated_value) = (self.get_bg_restore_count()).try_get_untracked() {
4102 {
4103 let count: &mut u32 = &mut updated_value;
4104 *count = count.saturating_add(1);
4105 }
4106 (self.get_bg_restore_count()).set(updated_value)
4107 } else {
4108 false
4109 }
4110 };
4111 }
4112}
4113
4114impl Default for ShowcaseState {
4116 fn default() -> Self {
4122 Self::new()
4123 }
4124}
4125
4126impl DemoPhysicsScene {
4128 #[must_use]
4134 pub fn create_lazy_arena() -> Self {
4135 Self::create_lazy_arena_with_fullscreen(Rc::new(Cell::new(None)))
4136 }
4137
4138 #[must_use]
4148 pub(crate) fn create_lazy_arena_with_fullscreen(
4149 fullscreen_open_cell: Rc<Cell<Option<Signal<bool>>>>,
4150 ) -> Self {
4151 Self {
4152 world: GameWorld::default(),
4153 physics: PhysicsWorld2D::default(),
4154 camera: Camera2D::default(),
4155 particles: ParticleSystem::default(),
4156 tilemap: TileMap::empty(0, 0, 48.0),
4157 actions: ActionMap::default(),
4158 audio: AudioBus::default(),
4159 player_id: EntityId::default(),
4160 fire_cooldown: 0.0,
4161 dash_cooldown: 0.0,
4162 score: 0,
4163 wave: 1,
4164 show_colliders: false,
4165 smoothed_fps: 0.0,
4166 ticks: 0,
4167 viewport_size: Size::new(820.0, 340.0),
4168 initialized: false,
4169 snapshots: DoubleBufferedSnapshot::new(World2DSnapshot::default()),
4170 to_despawn_scratch: Vec::new(),
4171 last_sampled_tick: u64::MAX,
4172 last_sampled_alpha_milli: i32::MIN,
4173 cached_interp: None,
4174 shockwaves: [(0.0, 0.0, 0.0, 0.0); 16],
4175 fullscreen_open_cell,
4176 }
4177 }
4178
4179 fn ensure_initialized(&mut self) {
4185 if self.get_initialized() {
4186 return;
4187 }
4188 let fs_cell: Rc<Cell<Option<Signal<bool>>>> = self.get_fullscreen_open_cell().clone();
4189 let mut hydrated: Self = Self::create_arena();
4190 hydrated.set_fullscreen_open_cell(fs_cell);
4191 *self = hydrated;
4192 }
4193
4194 #[must_use]
4200 pub fn create_arena() -> Self {
4201 let mut tilemap: TileMap = TileMap::empty(24, 14, 48.0);
4202 let floor_a: u16 = tilemap.add_palette_entry(TilePaletteEntry::new(
4203 Color::hex(0x0B1120),
4204 Color::rgba(30, 41, 59, 90),
4205 false,
4206 ));
4207 let floor_b: u16 = tilemap.add_palette_entry(TilePaletteEntry::new(
4208 Color::hex(0x0F172A),
4209 Color::rgba(30, 41, 59, 90),
4210 false,
4211 ));
4212 let wall_tile: u16 = tilemap.add_palette_entry(TilePaletteEntry::new(
4213 Color::hex(0x1E293B),
4214 Color::hex(0x38BDF8),
4215 true,
4216 ));
4217 for row in 0..tilemap.get_rows() {
4218 for col in 0..tilemap.get_columns() {
4219 let is_border: bool = row == 0
4220 || col == 0
4221 || row + 1 == tilemap.get_rows()
4222 || col + 1 == tilemap.get_columns();
4223 let tid: u16 = if is_border {
4224 wall_tile
4225 } else if (row + col) % 2 == 0 {
4226 floor_a
4227 } else {
4228 floor_b
4229 };
4230 tilemap.set_tile(col, row, tid);
4231 }
4232 }
4233 let world_rect: Rect = tilemap.world_bounds();
4234 let inner_arena: Rect = Rect::new(
4235 78.0,
4236 78.0,
4237 (world_rect.get_width() - 156.0).max(200.0),
4238 (world_rect.get_height() - 156.0).max(200.0),
4239 );
4240 let mut world: GameWorld = GameWorld::with_capacity(512);
4241 let center: Point = Point::new(world_rect.get_width() * 0.5, world_rect.get_height() * 0.5);
4242 let player_id: EntityId = world.spawn(EntityTag::Player, center);
4243 if let Some(player) = world.get_entity_mut(player_id) {
4244 player.set_body(Some(RigidBody2D::dynamic(1.0, 0.4, 3.2)));
4245 player.set_collider(Some(Collider2D::circle(
4246 14.0,
4247 COLLISION_LAYER_PLAYER,
4248 COLLISION_MASK_PLAYER_DEFAULT,
4249 false,
4250 )));
4251 player.set_sprite(Some(Sprite2D::new(
4252 EntityVisualShape::Triangle,
4253 Size::new(30.0, 26.0),
4254 Color::hex(0x38BDF8),
4255 Color::hex(0xE0F2FE),
4256 10,
4257 0.0,
4258 true,
4259 )));
4260 }
4261 let pillars: [(f32, f32); 4] = [
4262 (368.0, 224.0),
4263 (784.0, 224.0),
4264 (368.0, 448.0),
4265 (784.0, 448.0),
4266 ];
4267 for (px, py) in pillars.into_iter() {
4268 let pid: EntityId = world.spawn(EntityTag::Obstacle, Point::new(px, py));
4269 if let Some(obs) = world.get_entity_mut(pid) {
4270 obs.set_body(Some(RigidBody2D::static_body(0.85)));
4271 obs.set_collider(Some(Collider2D::axis_aligned_box(
4272 52.0,
4273 52.0,
4274 COLLISION_LAYER_WORLD,
4275 COLLISION_LAYER_ALL,
4276 false,
4277 )));
4278 obs.set_sprite(Some(Sprite2D::new(
4279 EntityVisualShape::Rect,
4280 Size::new(52.0, 52.0),
4281 Color::hex(0x1E293B),
4282 Color::hex(0x6366F1),
4283 2,
4284 8.0,
4285 true,
4286 )));
4287 }
4288 }
4289 let bumper_specs: [(f32, f32, f32, f32); 4] = [
4290 (464.0, 266.0, 58.0, -44.0),
4291 (688.0, 266.0, -52.0, 48.0),
4292 (464.0, 406.0, 46.0, 54.0),
4293 (688.0, 406.0, -60.0, -38.0),
4294 ];
4295 for (bx, by, bvx, bvy) in bumper_specs.into_iter() {
4296 let bid: EntityId = world.spawn(EntityTag::Pickup, Point::new(bx, by));
4297 if let Some(orb) = world.get_entity_mut(bid) {
4298 orb.set_velocity(Velocity2D::new(bvx, bvy, 2.2));
4299 orb.set_body(Some(RigidBody2D::dynamic(0.9, 0.98, 0.02)));
4300 orb.set_collider(Some(Collider2D::circle(
4301 11.0,
4302 COLLISION_LAYER_ENEMY,
4303 COLLISION_LAYER_ALL,
4304 false,
4305 )));
4306 orb.set_sprite(Some(Sprite2D::new(
4307 EntityVisualShape::Circle,
4308 Size::new(22.0, 22.0),
4309 Color::hex(0xA855F7),
4310 Color::hex(0xE9D5FF),
4311 5,
4312 0.0,
4313 true,
4314 )));
4315 }
4316 }
4317 let mut phys_cfg: PhysicsConfig = PhysicsConfig::default();
4318 phys_cfg.set_arena_bounds(Some(inner_arena));
4319 let mut camera: Camera2D = Camera2D::at(center, 1.0);
4320 camera.set_world_bounds(Some(world_rect));
4321 let mut scene: Self = Self {
4322 world,
4323 physics: PhysicsWorld2D::with_config(phys_cfg),
4324 camera,
4325 particles: ParticleSystem::with_capacity(4096),
4326 tilemap,
4327 actions: ActionMap::default(),
4328 audio: AudioBus::default(),
4329 player_id,
4330 fire_cooldown: 0.0,
4331 dash_cooldown: 0.0,
4332 score: 0,
4333 wave: 1,
4334 show_colliders: false,
4335 smoothed_fps: 0.0,
4336 ticks: 0,
4337 viewport_size: Size::new(820.0, 340.0),
4338 initialized: true,
4339 snapshots: DoubleBufferedSnapshot::new(World2DSnapshot::default()),
4340 to_despawn_scratch: Vec::with_capacity(64),
4341 last_sampled_tick: u64::MAX,
4342 last_sampled_alpha_milli: i32::MIN,
4343 cached_interp: None,
4344 shockwaves: [(0.0, 0.0, 0.0, 0.0); 16],
4345 fullscreen_open_cell: Rc::new(Cell::new(None)),
4346 };
4347 scene.spawn_enemy_wave(8);
4348 let mut boot_glow: ParticleEmitterConfig = ParticleEmitterConfig::default();
4349 boot_glow
4350 .set_min_speed(18.0)
4351 .set_max_speed(72.0)
4352 .set_min_life(0.65)
4353 .set_max_life(1.45)
4354 .set_start_size(3.4)
4355 .set_start_color(Color::hex(0x38BDF8))
4356 .set_end_color(Color::rgba(168, 85, 247, 0));
4357 scene.get_mut_particles().emit_burst(center, 48, boot_glow);
4358 scene.push_shockwave(center, 14.0);
4359 let initial_snap: World2DSnapshot =
4360 World2DSnapshot::capture(scene.get_world(), scene.get_camera(), true, Vec::new());
4361 scene.set_snapshots(DoubleBufferedSnapshot::new(initial_snap));
4362 scene
4363 }
4364
4365 fn push_shockwave(&mut self, origin: Point, initial_radius: f32) {
4372 let Self { shockwaves, .. } = self;
4373 let mut target_slot: usize = 0;
4374 let mut lowest_life: f32 = f32::INFINITY;
4375 for (slot_idx, slot) in shockwaves.iter().enumerate() {
4376 if slot.3 <= 0.001 {
4377 target_slot = slot_idx;
4378 break;
4379 }
4380 if slot.3 < lowest_life {
4381 lowest_life = slot.3;
4382 target_slot = slot_idx;
4383 }
4384 }
4385 shockwaves[target_slot] = (origin.get_x(), origin.get_y(), initial_radius, 1.0);
4386 }
4387
4388 #[must_use]
4400 fn rotate_screen_offset(center: Point, offset: (f32, f32), cs: (f32, f32)) -> Point {
4401 let (ox, oy): (f32, f32) = offset;
4402 let (ca, sa): (f32, f32) = cs;
4403 Point::new(
4404 center.get_x() + ox * ca - oy * sa,
4405 center.get_y() + ox * sa + oy * ca,
4406 )
4407 }
4408
4409 fn render_tactical_arena_floor(
4418 &self,
4419 ctx: &mut GameRenderContext<'_>,
4420 cam: &Camera2D,
4421 size: Size,
4422 phase_secs: f32,
4423 ) {
4424 let world_rect: Rect = self.get_tilemap().world_bounds();
4425 let (cam_x, cam_y, zoom, half_w, half_h): (f32, f32, f32, f32, f32) =
4426 cam.projection_params(size);
4427 let vp_w: f32 = size.get_width();
4428 let vp_h: f32 = size.get_height();
4429 for star_idx in 0..28u32 {
4430 let hx: u32 = star_idx.wrapping_mul(73_856_093) ^ 0x5A17_9C3B;
4431 let hy: u32 = star_idx.wrapping_mul(19_349_663) ^ 0x3D91_4F27;
4432 let parallax: f32 = 0.22 + ((star_idx & 3) as f32) * 0.12;
4433 let raw_sx: f32 = ((hx & 0xFFFF) as f32 / 65535.0) * vp_w - cam_x * parallax * 0.25;
4434 let raw_sy: f32 = ((hy & 0xFFFF) as f32 / 65535.0) * vp_h - cam_y * parallax * 0.25;
4435 let sx: f32 = raw_sx.rem_euclid(vp_w.max(1.0));
4436 let sy: f32 = raw_sy.rem_euclid(vp_h.max(1.0));
4437 let star_rad: f32 = 0.9 + ((star_idx % 3) as f32) * 0.45;
4438 let twinkle: f32 = 0.55 + 0.45 * (phase_secs * 2.2 + (star_idx as f32)).sin();
4439 let star_alpha: u8 = ((38.0 + 48.0 * twinkle) as u8).min(110);
4440 let star_col: Color = if star_idx % 4 == 0 {
4441 Color::rgba(56, 189, 248, star_alpha)
4442 } else if star_idx % 4 == 1 {
4443 Color::rgba(168, 85, 247, star_alpha)
4444 } else {
4445 Color::rgba(203, 213, 225, star_alpha)
4446 };
4447 ctx.fill_circle(Point::new(sx, sy), star_rad, star_col);
4448 }
4449 let inner_x0: f32 = (48.0 - cam_x) * zoom + half_w;
4450 let inner_y0: f32 = (48.0 - cam_y) * zoom + half_h;
4451 let inner_w: f32 = (world_rect.get_width() - 96.0) * zoom;
4452 let inner_h: f32 = (world_rect.get_height() - 96.0) * zoom;
4453 ctx.fill_rounded_rect(
4454 Rect::new(inner_x0, inner_y0, inner_w, inner_h),
4455 Color::hex(0x060C1B),
4456 10.0 * zoom,
4457 );
4458 let center_pt: Point = Point::new(
4459 (world_rect.get_width() * 0.5 - cam_x) * zoom + half_w,
4460 (world_rect.get_height() * 0.5 - cam_y) * zoom + half_h,
4461 );
4462 let ring_segs: usize = 32;
4463 let ring_step: f32 = (2.0 * PI) / (ring_segs as f32);
4464 for &(ring_r_world, ring_col) in [
4465 (108.0_f32, Color::rgba(99, 102, 241, 34)),
4466 (196.0_f32, Color::rgba(56, 189, 248, 28)),
4467 ]
4468 .iter()
4469 {
4470 let rr: f32 = ring_r_world * zoom;
4471 for seg in 0..ring_segs {
4472 if seg % 4 == 3 {
4473 continue;
4474 }
4475 let a0: f32 = (seg as f32) * ring_step;
4476 let a1: f32 = ((seg + 1) as f32) * ring_step;
4477 let p0: Point = Point::new(
4478 center_pt.get_x() + a0.cos() * rr,
4479 center_pt.get_y() + a0.sin() * rr,
4480 );
4481 let p1: Point = Point::new(
4482 center_pt.get_x() + a1.cos() * rr,
4483 center_pt.get_y() + a1.sin() * rr,
4484 );
4485 ctx.draw_line(p0, p1, 1.0, ring_col);
4486 }
4487 }
4488 let tick_in: f32 = 96.0 * zoom;
4489 let tick_out: f32 = 208.0 * zoom;
4490 for &(dx, dy) in [(1.0_f32, 0.0_f32), (-1.0, 0.0), (0.0, 1.0), (0.0, -1.0)].iter() {
4491 ctx.draw_line(
4492 Point::new(
4493 center_pt.get_x() + dx * tick_in,
4494 center_pt.get_y() + dy * tick_in,
4495 ),
4496 Point::new(
4497 center_pt.get_x() + dx * tick_out,
4498 center_pt.get_y() + dy * tick_out,
4499 ),
4500 1.0,
4501 Color::rgba(56, 189, 248, 30),
4502 );
4503 }
4504 let cols: usize = self.get_tilemap().get_columns();
4505 let rows: usize = self.get_tilemap().get_rows();
4506 let tile_sz: f32 = self.get_tilemap().get_tile_size();
4507 for col in 1..cols {
4508 let wx: f32 = (col as f32) * tile_sz;
4509 let sx: f32 = (wx - cam_x) * zoom + half_w;
4510 if sx < -2.0 || sx > vp_w + 2.0 {
4511 continue;
4512 }
4513 let major: bool = col % 2 == 0;
4514 let line_col: Color = if major {
4515 Color::rgba(56, 189, 248, 28)
4516 } else {
4517 Color::rgba(30, 58, 138, 22)
4518 };
4519 ctx.draw_line(
4520 Point::new(sx, inner_y0.max(0.0)),
4521 Point::new(sx, (inner_y0 + inner_h).min(vp_h)),
4522 if major { 1.1 } else { 0.8 },
4523 line_col,
4524 );
4525 }
4526 for row in 1..rows {
4527 let wy: f32 = (row as f32) * tile_sz;
4528 let sy: f32 = (wy - cam_y) * zoom + half_h;
4529 if sy < -2.0 || sy > vp_h + 2.0 {
4530 continue;
4531 }
4532 let major: bool = row % 2 == 0;
4533 let line_col: Color = if major {
4534 Color::rgba(56, 189, 248, 28)
4535 } else {
4536 Color::rgba(30, 58, 138, 22)
4537 };
4538 ctx.draw_line(
4539 Point::new(inner_x0.max(0.0), sy),
4540 Point::new((inner_x0 + inner_w).min(vp_w), sy),
4541 if major { 1.1 } else { 0.8 },
4542 line_col,
4543 );
4544 }
4545 let pulse: f32 = 0.72 + 0.28 * (phase_secs * 3.1).sin();
4546 let node_alpha: u8 = (62.0 * pulse) as u8;
4547 for row in (2..rows).step_by(2) {
4548 let sy: f32 = ((row as f32) * tile_sz - cam_y) * zoom + half_h;
4549 if sy < -4.0 || sy > vp_h + 4.0 {
4550 continue;
4551 }
4552 for col in (2..cols).step_by(2) {
4553 let sx: f32 = ((col as f32) * tile_sz - cam_x) * zoom + half_w;
4554 if sx < -4.0 || sx > vp_w + 4.0 {
4555 continue;
4556 }
4557 ctx.fill_circle(
4558 Point::new(sx, sy),
4559 1.8 * zoom,
4560 Color::rgba(56, 189, 248, node_alpha),
4561 );
4562 }
4563 }
4564 let wall_x0: f32 = inner_x0.clamp(2.0, vp_w - 4.0);
4565 let wall_y0: f32 = inner_y0.clamp(2.0, vp_h - 4.0);
4566 let wall_x1: f32 = (inner_x0 + inner_w).clamp(wall_x0 + 2.0, vp_w - 2.0);
4567 let wall_y1: f32 = (inner_y0 + inner_h).clamp(wall_y0 + 2.0, vp_h - 2.0);
4568 let wall_rect: Rect = Rect::new(wall_x0, wall_y0, wall_x1 - wall_x0, wall_y1 - wall_y0);
4569 ctx.stroke_rect(wall_rect, 5.0 * zoom, Color::rgba(56, 189, 248, 48));
4570 ctx.stroke_rect(wall_rect, 1.8 * zoom, Color::rgba(125, 211, 252, 225));
4571 }
4572
4573 fn render_layered_entities(
4586 &self,
4587 ctx: &mut GameRenderContext<'_>,
4588 snap: &World2DSnapshot,
4589 size: Size,
4590 phase_secs: f32,
4591 ) -> usize {
4592 let cam: Camera2D = snap.get_camera();
4593 let (cam_x, cam_y, zoom, half_w, half_h): (f32, f32, f32, f32, f32) =
4594 cam.projection_params(size);
4595 let vp_w: f32 = size.get_width();
4596 let vp_h: f32 = size.get_height();
4597 let world_ref: &GameWorld = self.get_world();
4598 let mut drawn: usize = 0;
4599 for pose in snap.get_entities().iter() {
4600 if !pose.get_alive() {
4601 continue;
4602 }
4603 let Some(ent) = world_ref.get_entity(pose.get_id()) else {
4604 continue;
4605 };
4606 let tr: EntityTransform = pose.get_transform();
4607 let pos: Point = tr.get_position();
4608 let center: Point = Point::new(
4609 (pos.get_x() - cam_x) * zoom + half_w,
4610 (pos.get_y() - cam_y) * zoom + half_h,
4611 );
4612 let margin: f32 = 64.0 * zoom;
4613 if center.get_x() < -margin
4614 || center.get_x() > vp_w + margin
4615 || center.get_y() < -margin
4616 || center.get_y() > vp_h + margin
4617 {
4618 continue;
4619 }
4620 drawn += 1;
4621 let rot: f32 = tr.get_rotation_rad();
4622 let (sa, ca): (f32, f32) = rot.sin_cos();
4623 let cs: (f32, f32) = (ca, sa);
4624 match ent.get_tag() {
4625 EntityTag::Obstacle => {
4626 let s_full: f32 = 52.0 * zoom;
4627 let half_s: f32 = s_full * 0.5;
4628 let pulse: f32 = 0.78 + 0.22 * (phase_secs * 3.2 + pos.get_x() * 0.02).sin();
4629 ctx.fill_circle(center, 46.0 * zoom, Color::rgba(99, 102, 241, 24));
4630 ctx.fill_rounded_rect(
4631 Rect::new(
4632 center.get_x() - half_s + 4.0 * zoom,
4633 center.get_y() - half_s + 5.0 * zoom,
4634 s_full,
4635 s_full,
4636 ),
4637 Color::rgba(2, 6, 23, 175),
4638 9.0 * zoom,
4639 );
4640 ctx.fill_rounded_rect(
4641 Rect::new(
4642 center.get_x() - half_s,
4643 center.get_y() - half_s,
4644 s_full,
4645 s_full,
4646 ),
4647 Color::hex(0x0F172A),
4648 8.0 * zoom,
4649 );
4650 ctx.stroke_rect(
4651 Rect::new(
4652 center.get_x() - half_s,
4653 center.get_y() - half_s,
4654 s_full,
4655 s_full,
4656 ),
4657 1.6 * zoom,
4658 Color::rgba(99, 102, 241, 190),
4659 );
4660 let inner_s: f32 = 34.0 * zoom;
4661 let inner_h: f32 = inner_s * 0.5;
4662 ctx.fill_rounded_rect(
4663 Rect::new(
4664 center.get_x() - inner_h,
4665 center.get_y() - inner_h,
4666 inner_s,
4667 inner_s,
4668 ),
4669 Color::hex(0x1E293B),
4670 5.0 * zoom,
4671 );
4672 ctx.fill_circle(center, 11.5 * zoom * pulse, Color::rgba(56, 189, 248, 52));
4673 ctx.fill_circle(center, 6.2 * zoom, Color::hex(0x818CF8));
4674 ctx.fill_circle(center, 2.8 * zoom, Color::hex(0xE0F2FE));
4675 }
4676 EntityTag::Pickup => {
4677 let pulse: f32 = 0.85 + 0.15 * (phase_secs * 5.0 + pos.get_x()).sin();
4678 let r_orb: f32 = 11.0 * zoom;
4679 ctx.fill_circle(center, r_orb * 2.4 * pulse, Color::rgba(168, 85, 247, 30));
4680 ctx.fill_circle(center, r_orb * 1.45, Color::rgba(56, 189, 248, 48));
4681 let p_top: Point = Self::rotate_screen_offset(center, (0.0, -r_orb), cs);
4682 let p_right: Point = Self::rotate_screen_offset(center, (r_orb, 0.0), cs);
4683 let p_bot: Point = Self::rotate_screen_offset(center, (0.0, r_orb), cs);
4684 let p_left: Point = Self::rotate_screen_offset(center, (-r_orb, 0.0), cs);
4685 ctx.fill_triangle(p_top, p_right, p_bot, Color::hex(0xC084FC));
4686 ctx.fill_triangle(p_top, p_bot, p_left, Color::hex(0x9333EA));
4687 ctx.fill_circle(center, 4.2 * zoom, Color::hex(0xF5D0FE));
4688 ctx.fill_circle(center, 2.0 * zoom, COLOR_WHITE);
4689 }
4690 EntityTag::Enemy => {
4691 let is_interceptor: bool = ent
4692 .sprite_component()
4693 .is_some_and(|sp: Sprite2D| sp.get_shape() == EntityVisualShape::Diamond);
4694 let pulse: f32 = 0.82 + 0.18 * (phase_secs * 6.0 + pos.get_y() * 0.05).sin();
4695 let sz: f32 = 15.0 * zoom;
4696 if is_interceptor {
4697 ctx.fill_circle(center, sz * 2.1, Color::rgba(244, 63, 94, 30));
4698 ctx.fill_circle(center, sz * 1.3, Color::rgba(251, 113, 133, 46));
4699 let nose: Point = Self::rotate_screen_offset(center, (sz * 1.35, 0.0), cs);
4700 let wing_l: Point =
4701 Self::rotate_screen_offset(center, (-sz * 0.55, -sz * 1.05), cs);
4702 let wing_r: Point =
4703 Self::rotate_screen_offset(center, (-sz * 0.55, sz * 1.05), cs);
4704 let tail: Point = Self::rotate_screen_offset(center, (-sz * 1.05, 0.0), cs);
4705 ctx.fill_triangle(nose, wing_l, tail, Color::hex(0xE11D48));
4706 ctx.fill_triangle(nose, tail, wing_r, Color::hex(0xFB7185));
4707 let core_f: Point =
4708 Self::rotate_screen_offset(center, (sz * 0.65, 0.0), cs);
4709 let core_l: Point =
4710 Self::rotate_screen_offset(center, (-sz * 0.35, -sz * 0.38), cs);
4711 let core_r: Point =
4712 Self::rotate_screen_offset(center, (-sz * 0.35, sz * 0.38), cs);
4713 ctx.fill_triangle(core_f, core_l, core_r, Color::hex(0x1E1B4B));
4714 ctx.fill_circle(center, 4.4 * zoom * pulse, Color::hex(0xFDE047));
4715 ctx.fill_circle(center, 2.1 * zoom, COLOR_WHITE);
4716 } else {
4717 ctx.fill_circle(center, sz * 2.1, Color::rgba(245, 158, 11, 28));
4718 ctx.fill_circle(center, sz * 1.3, Color::rgba(251, 191, 36, 42));
4719 let spin_rot: f32 = rot + phase_secs * 1.8;
4720 let (sb, cb): (f32, f32) = spin_rot.sin_cos();
4721 let blade_cs: (f32, f32) = (cb, sb);
4722 for blade_idx in 0..4usize {
4723 let angle_off: f32 = (blade_idx as f32) * (PI * 0.5);
4724 let (s_o, c_o): (f32, f32) = angle_off.sin_cos();
4725 let b_cs: (f32, f32) = (
4726 blade_cs.0 * c_o - blade_cs.1 * s_o,
4727 blade_cs.0 * s_o + blade_cs.1 * c_o,
4728 );
4729 let tip: Point =
4730 Self::rotate_screen_offset(center, (sz * 1.28, 0.0), b_cs);
4731 let b_l: Point =
4732 Self::rotate_screen_offset(center, (sz * 0.35, -sz * 0.38), b_cs);
4733 let b_r: Point =
4734 Self::rotate_screen_offset(center, (sz * 0.35, sz * 0.38), b_cs);
4735 ctx.fill_triangle(tip, b_l, b_r, Color::hex(0xD97706));
4736 }
4737 ctx.fill_circle(center, sz * 0.78, Color::hex(0x1E293B));
4738 ctx.fill_circle(center, sz * 0.54, Color::hex(0xF59E0B));
4739 ctx.fill_circle(center, 4.2 * zoom * pulse, Color::hex(0xFEF08A));
4740 ctx.fill_circle(center, 2.0 * zoom, COLOR_WHITE);
4741 }
4742 }
4743 EntityTag::Projectile => {
4744 let tail: Point = Self::rotate_screen_offset(center, (-16.0 * zoom, 0.0), cs);
4745 ctx.draw_line(tail, center, 5.5 * zoom, Color::rgba(52, 211, 153, 52));
4746 ctx.draw_line(tail, center, 2.4 * zoom, Color::rgba(110, 231, 183, 195));
4747 ctx.fill_circle(center, 9.5 * zoom, Color::rgba(16, 185, 129, 44));
4748 ctx.fill_circle(center, 4.5 * zoom, Color::hex(0x34D399));
4749 ctx.fill_circle(center, 2.3 * zoom, COLOR_WHITE);
4750 }
4751 EntityTag::Player => {
4752 let s_val: f32 = 16.5 * zoom;
4753 let exhaust_flicker: f32 = 0.84 + 0.28 * (phase_secs * 24.0).sin().abs();
4754 ctx.fill_circle(center, s_val * 1.45, Color::rgba(56, 189, 248, 20));
4755 ctx.fill_circle(center, s_val * 0.92, Color::rgba(14, 165, 233, 34));
4756 for nozzle_y in [-5.4_f32, 5.4_f32] {
4757 let base_l: Point = Self::rotate_screen_offset(
4758 center,
4759 (-s_val * 0.72, (nozzle_y - 2.6) * zoom),
4760 cs,
4761 );
4762 let base_r: Point = Self::rotate_screen_offset(
4763 center,
4764 (-s_val * 0.72, (nozzle_y + 2.6) * zoom),
4765 cs,
4766 );
4767 let tip_out: Point = Self::rotate_screen_offset(
4768 center,
4769 (-s_val * (1.38 + 0.45 * exhaust_flicker), nozzle_y * zoom),
4770 cs,
4771 );
4772 let tip_in: Point = Self::rotate_screen_offset(
4773 center,
4774 (-s_val * (1.05 + 0.25 * exhaust_flicker), nozzle_y * zoom),
4775 cs,
4776 );
4777 ctx.fill_triangle(base_l, base_r, tip_out, Color::rgba(56, 189, 248, 175));
4778 ctx.fill_triangle(base_l, base_r, tip_in, Color::hex(0xE0F2FE));
4779 }
4780 let nose: Point = Self::rotate_screen_offset(center, (s_val * 1.38, 0.0), cs);
4781 let w_l_out: Point =
4782 Self::rotate_screen_offset(center, (-s_val * 0.92, -s_val * 1.12), cs);
4783 let w_r_out: Point =
4784 Self::rotate_screen_offset(center, (-s_val * 0.92, s_val * 1.12), cs);
4785 let stern: Point = Self::rotate_screen_offset(center, (-s_val * 0.56, 0.0), cs);
4786 ctx.fill_triangle(nose, w_l_out, stern, Color::hex(0x0284C7));
4787 ctx.fill_triangle(nose, stern, w_r_out, Color::hex(0x38BDF8));
4788 let hull_l: Point =
4789 Self::rotate_screen_offset(center, (-s_val * 0.68, -s_val * 0.58), cs);
4790 let hull_r: Point =
4791 Self::rotate_screen_offset(center, (-s_val * 0.68, s_val * 0.58), cs);
4792 ctx.fill_triangle(nose, hull_l, hull_r, Color::hex(0x7DD3FC));
4793 let canopy_f: Point =
4794 Self::rotate_screen_offset(center, (s_val * 0.66, 0.0), cs);
4795 let canopy_l: Point =
4796 Self::rotate_screen_offset(center, (-s_val * 0.12, -s_val * 0.26), cs);
4797 let canopy_r: Point =
4798 Self::rotate_screen_offset(center, (-s_val * 0.12, s_val * 0.26), cs);
4799 ctx.fill_triangle(canopy_f, canopy_l, canopy_r, Color::hex(0x0F172A));
4800 let glint_pt: Point =
4801 Self::rotate_screen_offset(center, (s_val * 0.30, -s_val * 0.04), cs);
4802 ctx.fill_circle(glint_pt, 2.4 * zoom, Color::hex(0xE0F2FE));
4803 }
4804 _ => {}
4805 }
4806 }
4807 drawn
4808 }
4809
4810 pub fn spawn_enemy_wave(&mut self, count: usize) {
4817 let bounds: Rect = self.get_tilemap().world_bounds();
4818 let cx: f32 = bounds.get_width() * 0.5;
4819 let cy: f32 = bounds.get_height() * 0.5;
4820 for idx in 0..count {
4821 let angle: f32 = ((idx as f32) / (count.max(1) as f32)) * 6.283_185_5
4822 + (self.get_wave() as f32) * 0.45;
4823 let radius: f32 = 138.0 + ((idx % 3) as f32) * 44.0;
4824 let sx: f32 = (cx + angle.cos() * radius).clamp(96.0, bounds.get_width() - 96.0);
4825 let sy: f32 = (cy + angle.sin() * radius).clamp(96.0, bounds.get_height() - 96.0);
4826 let speed: f32 = 95.0 + ((idx % 4) as f32) * 28.0;
4827 let eid: EntityId = self
4828 .get_mut_world()
4829 .spawn(EntityTag::Enemy, Point::new(sx, sy));
4830 if let Some(enemy) = self.get_mut_world().get_entity_mut(eid) {
4831 enemy.set_velocity(Velocity2D::new(
4832 -angle.sin() * speed,
4833 angle.cos() * speed,
4834 1.5,
4835 ));
4836 enemy.set_body(Some(RigidBody2D::dynamic(1.2, 0.95, 0.05)));
4837 enemy.set_collider(Some(Collider2D::circle(
4838 13.0,
4839 COLLISION_LAYER_ENEMY,
4840 COLLISION_LAYER_ALL,
4841 false,
4842 )));
4843 enemy.set_sprite(Some(Sprite2D::new(
4844 if idx % 2 == 0 {
4845 EntityVisualShape::Diamond
4846 } else {
4847 EntityVisualShape::Circle
4848 },
4849 Size::new(26.0, 26.0),
4850 if idx % 2 == 0 {
4851 Color::hex(0xF43F5E)
4852 } else {
4853 Color::hex(0xF59E0B)
4854 },
4855 Color::hex(0xFEF08A),
4856 6,
4857 0.0,
4858 true,
4859 )));
4860 }
4861 }
4862 }
4863
4864 fn fire_projectile(&mut self, origin: Point, aim_angle: f32) {
4872 let dir_x: f32 = aim_angle.cos();
4873 let dir_y: f32 = aim_angle.sin();
4874 let launch: Point =
4875 Point::new(origin.get_x() + dir_x * 20.0, origin.get_y() + dir_y * 20.0);
4876 let pid: EntityId = self.get_mut_world().spawn(EntityTag::Projectile, launch);
4877 if let Some(proj) = self.get_mut_world().get_entity_mut(pid) {
4878 proj.get_mut_transform().set_rotation_rad(aim_angle);
4879 proj.set_velocity(Velocity2D::new(dir_x * 520.0, dir_y * 520.0, 0.0));
4880 proj.set_body(Some(RigidBody2D::dynamic(0.2, 0.9, 0.0)));
4881 proj.set_collider(Some(Collider2D::circle(
4882 5.0,
4883 COLLISION_LAYER_PROJECTILE,
4884 COLLISION_LAYER_ENEMY | COLLISION_LAYER_WORLD,
4885 true,
4886 )));
4887 proj.set_sprite(Some(Sprite2D::new(
4888 EntityVisualShape::Circle,
4889 Size::new(10.0, 10.0),
4890 Color::hex(0x34D399),
4891 Color::hex(0xFFFFFF),
4892 8,
4893 0.0,
4894 true,
4895 )));
4896 proj.set_ttl_secs(Some(1.4));
4897 }
4898 let mut muzzle: ParticleEmitterConfig = ParticleEmitterConfig::default();
4899 muzzle
4900 .set_base_angle(aim_angle)
4901 .set_spread_rad(0.45)
4902 .set_min_speed(80.0)
4903 .set_max_speed(180.0)
4904 .set_min_life(0.12)
4905 .set_max_life(0.26)
4906 .set_start_size(3.5)
4907 .set_start_color(Color::hex(0x34D399))
4908 .set_end_color(Color::rgba(56, 189, 248, 0));
4909 self.get_mut_particles().emit_burst(launch, 6, muzzle);
4910 self.get_mut_audio().play(SoundCue::Laser, 0.65, 0.0, 1.05);
4911 }
4912}
4913
4914impl GameScene for DemoPhysicsScene {
4916 fn fixed_update(&mut self, dt: f32, input: &InputState) {
4924 self.ensure_initialized();
4925 let mods: Modifiers = input.get_modifiers();
4926 let no_mods: bool = !mods.get_ctrl() && !mods.get_meta() && !mods.get_alt();
4927 let allow_shortcuts: bool =
4928 no_mods && (EuvOverlayStack::active_count() == 0 || EuvOverlayStack::has_fullscreen());
4929 if allow_shortcuts
4930 && (input.is_key_just_pressed(KeyCode::Character('f'))
4931 || input.is_key_just_pressed(KeyCode::Character('F')))
4932 && let Some(fs_sig) = self.get_fullscreen_open_cell().get()
4933 {
4934 let next_open: bool = !fs_sig.get_untracked();
4935 let _: bool = fs_sig.set_if_changed(next_open);
4936 }
4937 let move_vec: Point = self.get_actions().movement_vector(input);
4938 let fire_pressed: bool = self.get_actions().is_active(GameAction::Fire, input);
4939 let dash_pressed: bool = self.get_actions().is_just_pressed(GameAction::Dash, input);
4940 let wave_pressed: bool = self
4941 .get_actions()
4942 .is_just_pressed(GameAction::ActionAlt, input);
4943 if wave_pressed {
4944 let next_wave: u32 = self.get_wave().saturating_add(1);
4945 self.set_wave(next_wave);
4946 self.spawn_enemy_wave(6);
4947 }
4948 let fire_cd: f32 = (self.get_fire_cooldown() - dt).max(0.0);
4949 let dash_cd: f32 = (self.get_dash_cooldown() - dt).max(0.0);
4950 self.set_fire_cooldown(fire_cd);
4951 self.set_dash_cooldown(dash_cd);
4952 let player_id: EntityId = self.get_player_id();
4953 let mut player_pos: Point = Point::new(576.0, 336.0);
4954 let mut aim_angle: f32 = 0.0;
4955 let mut dashed: bool = false;
4956 if let Some(player) = self.get_mut_world().get_entity_mut(player_id) {
4957 player_pos = player.get_transform().get_position();
4958 let accel: f32 = 1650.0;
4959 let mut vel: Velocity2D = player.get_velocity();
4960 vel.set_vx(vel.get_vx() + move_vec.get_x() * accel * dt);
4961 vel.set_vy(vel.get_vy() + move_vec.get_y() * accel * dt);
4962 let mut rot: f32 = player.get_transform().get_rotation_rad();
4963 if move_vec.get_x().abs() > 0.05 || move_vec.get_y().abs() > 0.05 {
4964 rot = move_vec.get_y().atan2(move_vec.get_x());
4965 } else {
4966 rot += dt * 0.8;
4967 }
4968 if dash_pressed && dash_cd <= 0.0 {
4969 vel.set_vx(vel.get_vx() + rot.cos() * 440.0);
4970 vel.set_vy(vel.get_vy() + rot.sin() * 440.0);
4971 dashed = true;
4972 }
4973 player.set_velocity(vel);
4974 player.get_mut_transform().set_rotation_rad(rot);
4975 aim_angle = rot;
4976 }
4977 if dashed {
4978 self.set_dash_cooldown(0.45);
4979 self.get_mut_camera().add_trauma(0.25);
4980 let mut burst: ParticleEmitterConfig = ParticleEmitterConfig::default();
4981 burst
4982 .set_base_angle(aim_angle + PI)
4983 .set_spread_rad(0.9)
4984 .set_start_color(Color::hex(0x38BDF8))
4985 .set_end_color(Color::rgba(56, 189, 248, 0));
4986 self.get_mut_particles().emit_burst(player_pos, 36, burst);
4987 self.push_shockwave(player_pos, 16.0);
4988 self.get_mut_audio().play(SoundCue::Dash, 0.8, 0.0, 1.0);
4989 }
4990 let stern: Point = Point::new(
4991 player_pos.get_x() - aim_angle.cos() * 14.0,
4992 player_pos.get_y() - aim_angle.sin() * 14.0,
4993 );
4994 let mut thruster: ParticleEmitterConfig = ParticleEmitterConfig::default();
4995 thruster
4996 .set_base_angle(aim_angle + PI)
4997 .set_spread_rad(0.38)
4998 .set_min_speed(42.0)
4999 .set_max_speed(105.0)
5000 .set_min_life(0.16)
5001 .set_max_life(0.34)
5002 .set_start_size(3.2)
5003 .set_start_color(Color::hex(0x38BDF8))
5004 .set_end_color(Color::rgba(99, 102, 241, 0));
5005 self.get_mut_particles().emit_burst(stern, 4, thruster);
5006 if (fire_pressed || self.get_ticks().is_multiple_of(22)) && fire_cd <= 0.0 {
5007 self.fire_projectile(player_pos, aim_angle);
5008 self.set_fire_cooldown(0.14);
5009 }
5010 let collisions: Vec<CollisionEvent> = {
5011 let Self { world, physics, .. } = self;
5012 physics.step(world, dt)
5013 };
5014 {
5015 let Self {
5016 world,
5017 to_despawn_scratch,
5018 camera,
5019 audio,
5020 ..
5021 } = self;
5022 to_despawn_scratch.clear();
5023 for ui_event in collisions.into_iter() {
5024 let tag_a: Option<EntityTag> = world
5025 .get_entity(ui_event.get_entity_a())
5026 .map(EntityRecord::get_tag);
5027 let tag_b: Option<EntityTag> = world
5028 .get_entity(ui_event.get_entity_b())
5029 .map(EntityRecord::get_tag);
5030 match (tag_a, tag_b) {
5031 (Some(EntityTag::Projectile), Some(EntityTag::Enemy)) => {
5032 if let Some(event_ref) = world.get_entity(ui_event.get_entity_b()) {
5033 to_despawn_scratch.push((
5034 ui_event.get_entity_b(),
5035 event_ref.get_transform().get_position(),
5036 true,
5037 ));
5038 }
5039 to_despawn_scratch.push((ui_event.get_entity_a(), Point::default(), false));
5040 }
5041 (Some(EntityTag::Enemy), Some(EntityTag::Projectile)) => {
5042 if let Some(error_val) = world.get_entity(ui_event.get_entity_a()) {
5043 to_despawn_scratch.push((
5044 ui_event.get_entity_a(),
5045 error_val.get_transform().get_position(),
5046 true,
5047 ));
5048 }
5049 to_despawn_scratch.push((ui_event.get_entity_b(), Point::default(), false));
5050 }
5051 (Some(EntityTag::Projectile), Some(EntityTag::Obstacle)) => {
5052 to_despawn_scratch.push((ui_event.get_entity_a(), Point::default(), false));
5053 }
5054 (Some(EntityTag::Obstacle), Some(EntityTag::Projectile)) => {
5055 to_despawn_scratch.push((ui_event.get_entity_b(), Point::default(), false));
5056 }
5057 (Some(EntityTag::Player), Some(EntityTag::Enemy))
5058 | (Some(EntityTag::Enemy), Some(EntityTag::Player)) => {
5059 camera.add_trauma(0.35);
5060 audio.play(SoundCue::Bounce, 0.7, 0.0, 0.85);
5061 }
5062 _ => {}
5063 }
5064 }
5065 }
5066 {
5067 let Self {
5068 world,
5069 to_despawn_scratch,
5070 score,
5071 camera,
5072 particles,
5073 audio,
5074 shockwaves,
5075 ..
5076 } = self;
5077 for &(eid, pos, is_enemy) in to_despawn_scratch.iter() {
5078 if world.despawn(eid) && is_enemy {
5079 *score = score.saturating_add(100);
5080 camera.add_trauma(0.32);
5081 let mut exp: ParticleEmitterConfig = ParticleEmitterConfig::default();
5082 exp.set_min_speed(70.0)
5083 .set_max_speed(260.0)
5084 .set_start_size(5.5)
5085 .set_start_color(Color::hex(0xFB7185))
5086 .set_end_color(Color::rgba(250, 204, 21, 0));
5087 particles.emit_burst(pos, 48, exp);
5088 for ring in shockwaves.iter_mut() {
5089 if ring.3 <= 0.001 {
5090 *ring = (pos.get_x(), pos.get_y(), 12.0, 1.0);
5091 break;
5092 }
5093 }
5094 audio.play(SoundCue::Explosion, 0.9, 0.0, 0.95);
5095 }
5096 }
5097 to_despawn_scratch.clear();
5098 for ring in shockwaves.iter_mut() {
5099 if ring.3 > 0.0 {
5100 ring.2 += 210.0 * dt;
5101 ring.3 = (ring.3 - 2.35 * dt).max(0.0);
5102 }
5103 }
5104 }
5105 if self.get_world().count_by_tag(EntityTag::Enemy) < 3 {
5106 let next_wave: u32 = self.get_wave().saturating_add(1);
5107 self.set_wave(next_wave);
5108 self.spawn_enemy_wave(6);
5109 }
5110 let _: usize = self.get_mut_world().tick_lifetimes(dt);
5111 let _: usize = self.get_mut_particles().update(dt);
5112 let _: Vec<AudioCommand> = self.get_mut_audio().drain();
5113 if let Some(player) = self.get_world().get_entity(player_id) {
5114 let point_coords: Point = player.get_transform().get_position();
5115 let box_size: Size = self.get_viewport_size();
5116 self.get_mut_camera()
5117 .follow(point_coords, 7.5, dt, box_size);
5118 }
5119 self.set_ticks(self.get_ticks().saturating_add(1));
5120 self.set_last_sampled_tick(u64::MAX);
5121 let next_snap: World2DSnapshot =
5122 World2DSnapshot::capture(self.get_world(), self.get_camera(), false, Vec::new());
5123 self.get_mut_snapshots().commit(next_snap);
5124 }
5125
5126 fn update(&mut self, dt: f32, _input: &InputState) {
5134 if dt > 0.0001 {
5135 let inst_fps: f32 = (1.0 / dt).clamp(1.0, 9999.0);
5136 let prev: f32 = self.get_smoothed_fps();
5137 let next: f32 = if prev <= 0.5 {
5138 inst_fps
5139 } else {
5140 prev * 0.85 + inst_fps * 0.15
5141 };
5142 self.set_smoothed_fps(next);
5143 }
5144 }
5145
5146 fn render(&mut self, alpha: f32, ctx: &mut GameRenderContext<'_>) {
5154 self.ensure_initialized();
5155 let size: Size = ctx.viewport_size();
5156 if size.get_width() > 32.0 && size.get_height() > 32.0 {
5157 let fit_zoom: f32 = (size.get_width() / 860.0)
5158 .min(size.get_height() / 620.0)
5159 .clamp(0.48, 1.28);
5160 let vp_changed: bool = size != self.get_viewport_size();
5161 let zoom_changed: bool = (self.get_camera().get_zoom() - fit_zoom).abs() > 0.001;
5162 if vp_changed || zoom_changed {
5163 self.set_viewport_size(size);
5164 self.get_mut_camera().set_zoom(fit_zoom);
5165 self.get_mut_snapshots()
5166 .get_mut_prev_state()
5167 .get_mut_camera()
5168 .set_zoom(fit_zoom);
5169 self.get_mut_snapshots()
5170 .get_mut_curr_state()
5171 .get_mut_camera()
5172 .set_zoom(fit_zoom);
5173 self.set_last_sampled_tick(u64::MAX);
5174 }
5175 }
5176 ctx.clear(Color::hex(0x030712));
5177 let alpha_milli: i32 = (alpha.clamp(0.0, 1.0) * 1000.0).round() as i32;
5178 let cur_ticks: u64 = self.get_ticks();
5179 let needs_resample: bool = self.get_last_sampled_tick() != cur_ticks
5180 || self.get_last_sampled_alpha_milli() != alpha_milli
5181 || {
5182 let Self { cached_interp, .. } = self;
5183 cached_interp.is_none()
5184 };
5185 if needs_resample {
5186 let sampled: World2DSnapshot = self.get_snapshots().sample(alpha);
5187 let Self {
5188 cached_interp,
5189 last_sampled_tick,
5190 last_sampled_alpha_milli,
5191 ..
5192 } = self;
5193 *cached_interp = Some(sampled);
5194 *last_sampled_tick = cur_ticks;
5195 *last_sampled_alpha_milli = alpha_milli;
5196 }
5197 let player_id: EntityId = self.get_player_id();
5198 let (cam, interp_player_tr): (Camera2D, Option<EntityTransform>) = {
5199 let Self {
5200 cached_interp,
5201 world,
5202 camera,
5203 ..
5204 } = self;
5205 match cached_interp.as_ref() {
5206 Some(snap) => {
5207 let transform_val: Option<EntityTransform> = snap
5208 .get_entities()
5209 .iter()
5210 .find(|pose: &&EntityPose2D| pose.get_alive() && pose.get_id() == player_id)
5211 .map(EntityPose2D::get_transform)
5212 .or_else(|| world.get_entity(player_id).map(EntityRecord::get_transform));
5213 (snap.get_camera(), transform_val)
5214 }
5215 None => (
5216 *camera,
5217 world.get_entity(player_id).map(EntityRecord::get_transform),
5218 ),
5219 }
5220 };
5221 let phase_secs: f32 = ((cur_ticks as f32) + alpha) * (1.0 / 60.0);
5222 self.render_tactical_arena_floor(ctx, &cam, size, phase_secs);
5223 if let Some(player_tr) = interp_player_tr {
5224 let origin: Point = player_tr.get_position();
5225 let rot: f32 = player_tr.get_rotation_rad();
5226 let dir: Point = Point::new(rot.cos(), rot.sin());
5227 let (end_world, locked_target): (Point, bool) = match PhysicsWorld2D::raycast(
5228 self.get_world(),
5229 origin,
5230 dir,
5231 340.0,
5232 COLLISION_LAYER_ENEMY | COLLISION_LAYER_WORLD,
5233 ) {
5234 Some(hit) => (hit.get_point(), true),
5235 None => (
5236 Point::new(
5237 origin.get_x() + dir.get_x() * 340.0,
5238 origin.get_y() + dir.get_y() * 340.0,
5239 ),
5240 false,
5241 ),
5242 };
5243 let s0: Point = cam.world_to_screen(origin, size);
5244 let s1: Point = cam.world_to_screen(end_world, size);
5245 let beam_outer: Color = if locked_target {
5246 Color::rgba(244, 63, 94, 42)
5247 } else {
5248 Color::rgba(56, 189, 248, 32)
5249 };
5250 let beam_core: Color = if locked_target {
5251 Color::rgba(251, 113, 133, 195)
5252 } else {
5253 Color::rgba(125, 211, 252, 165)
5254 };
5255 ctx.draw_line(s0, s1, 5.4, beam_outer);
5256 ctx.draw_line(s0, s1, 1.6, beam_core);
5257 let ret_r: f32 = if locked_target { 9.5 } else { 5.5 };
5258 ctx.fill_circle(s1, ret_r * 1.4, beam_outer);
5259 ctx.fill_circle(s1, 3.0, beam_core);
5260 }
5261 let shockwave_copy: [(f32, f32, f32, f32); 16] = *self.get_shockwaves();
5262 let zoom: f32 = cam.get_zoom();
5263 for &(wx, wy, rad_w, life) in shockwave_copy.iter() {
5264 if life <= 0.01 {
5265 continue;
5266 }
5267 let sc: Point = cam.world_to_screen(Point::new(wx, wy), size);
5268 let sr: f32 = rad_w * zoom;
5269 let ring_alpha: u8 = (life * 92.0).clamp(0.0, 120.0) as u8;
5270 ctx.fill_circle(sc, sr, Color::rgba(56, 189, 248, ring_alpha / 3));
5271 let segs: usize = 16;
5272 let step: f32 = (2.0 * PI) / (segs as f32);
5273 for seg in 0..segs {
5274 let a0: f32 = (seg as f32) * step;
5275 let a1: f32 = ((seg + 1) as f32) * step;
5276 let p0: Point = Point::new(sc.get_x() + a0.cos() * sr, sc.get_y() + a0.sin() * sr);
5277 let p1: Point = Point::new(sc.get_x() + a1.cos() * sr, sc.get_y() + a1.sin() * sr);
5278 ctx.draw_line(p0, p1, 2.0, Color::rgba(125, 211, 252, ring_alpha));
5279 }
5280 }
5281 let drawn_entities: usize = match self.try_get_cached_interp() {
5282 Some(snap) => self.render_layered_entities(ctx, snap, size, phase_secs),
5283 None => 0,
5284 };
5285 let drawn_particles: usize = ctx.render_particles(self.get_particles(), &cam);
5286 if self.get_show_colliders() {
5287 ctx.draw_debug_colliders(self.get_world(), &cam);
5288 }
5289 let hud_text: String = format!(
5290 "{:.0} FPS · W{} · {} pts · {} Ent · {} Part · DASH",
5291 self.get_smoothed_fps().max(60.0),
5292 self.get_wave(),
5293 self.get_score(),
5294 drawn_entities,
5295 drawn_particles
5296 );
5297 let dash_charge: f32 = (1.0 - self.get_dash_cooldown() / 0.45).clamp(0.0, 1.0);
5298 let pill_w: f32 = ((hud_text.len() as f32) * 6.8 + 64.0)
5299 .clamp(210.0, (size.get_width() - 20.0).max(210.0));
5300 let pill_y: f32 = (size.get_height() - 36.0).max(48.0);
5301 let pill_rect: Rect = Rect::new(10.0, pill_y, pill_w, 26.0);
5302 ctx.fill_rounded_rect(pill_rect, Color::rgba(6, 11, 24, 216), 8.0);
5303 ctx.stroke_rect(pill_rect, 1.0, Color::rgba(56, 189, 248, 95));
5304 let bar_w: f32 = 42.0;
5305 let bar_x: f32 = 10.0 + pill_w - bar_w - 10.0;
5306 ctx.fill_rounded_rect(
5307 Rect::new(bar_x, pill_y + 9.0, bar_w, 7.0),
5308 Color::rgba(30, 41, 59, 220),
5309 3.5,
5310 );
5311 ctx.fill_rounded_rect(
5312 Rect::new(bar_x, pill_y + 9.0, (bar_w * dash_charge).max(3.0), 7.0),
5313 Color::hex(0x38BDF8),
5314 3.5,
5315 );
5316 ctx.draw_text(
5317 Point::new(18.0, pill_y + 5.5),
5318 hud_text,
5319 11.0,
5320 Color::hex(0xE2E8F0),
5321 );
5322 }
5323}
5324
5325impl DemoOpenWorld3DScene {
5327 #[must_use]
5339 pub(crate) fn create_lazy_city_deferred(
5340 signals_cell: Rc<Cell<Option<Engine3dSignals>>>,
5341 state_scope: Scope,
5342 bg_workers_enabled: Rc<Cell<bool>>,
5343 ) -> Self {
5344 Self {
5345 world: World3D::default(),
5346 renderer: Renderer3D::default(),
5347 actions: ActionMap::default(),
5348 signals_cell,
5349 state_scope,
5350 bg_workers_enabled,
5351 bg_city_task: None,
5352 last_import_seq: 0,
5353 smoothed_fps: 0.0,
5354 initialized: false,
5355 snapshots: DoubleBufferedSnapshot::new(World3DSnapshot::default()),
5356 frame_pool: RenderBufferPool::with_capacity(3),
5357 gpu_target: GpuCompositeTarget::default(),
5358 frame_fence: 0,
5359 last_camera_mode: 0,
5360 last_atmosphere_idx: 0,
5361 ticks: 0,
5362 cached_world_frame: None,
5363 cached_world_rev: u64::MAX,
5364 cached_alpha_milli: i32::MIN,
5365 cached_dims: (0, 0),
5366 cached_quality: Engine3dSignals::max_quality_config(),
5367 last_render_ms: 0.0,
5368 gpu_mesh_buffer: None,
5369 gpu_mesh_ranges: Vec::new(),
5370 gpu_mesh_rev: 0,
5371 gpu_mesh_lib_len: 0,
5372 }
5373 }
5374
5375 fn active_signals(&self) -> Engine3dSignals {
5385 Engine3dSignals::get_or_init(self.get_signals_cell().as_ref(), self.get_state_scope())
5386 }
5387
5388 fn install_world(&mut self, world: World3D) {
5395 let initial_snap: World3DSnapshot =
5396 World3DSnapshot::capture(&world, 0, true, Vec::new(), Vec::new());
5397 let init_mode: u8 = world.get_camera_mode();
5398 self.set_world(world);
5399 self.set_snapshots(DoubleBufferedSnapshot::new(initial_snap));
5400 self.set_last_camera_mode(init_mode);
5401 self.get_mut_gpu_target().mark_world_dirty();
5402 self.set_cached_world_frame(None);
5403 self.set_cached_world_rev(u64::MAX);
5404 self.set_gpu_mesh_buffer(None);
5405 self.get_mut_gpu_mesh_ranges().clear();
5406 self.set_gpu_mesh_lib_len(0);
5407 self.set_initialized(true);
5408 let _: bool = self
5409 .active_signals()
5410 .get_engine3d_import_status()
5411 .set_if_changed(DEFAULT_ENGINE3D_STATUS.to_string());
5412 }
5413
5414 fn ensure_initialized(&mut self) -> bool {
5424 if self.get_initialized() {
5425 return true;
5426 }
5427 let ready_world: Option<World3D> = {
5428 let Self { bg_city_task, .. } = self;
5429 if let Some(task) = bg_city_task.as_ref() {
5430 if let Some(world) = task.try_take() {
5431 *bg_city_task = None;
5432 Some(world)
5433 } else {
5434 return false;
5435 }
5436 } else {
5437 None
5438 }
5439 };
5440 if let Some(world) = ready_world {
5441 self.install_world(world);
5442 return true;
5443 }
5444 if self.get_bg_workers_enabled().get() {
5445 let task: BackgroundTask<World3D> =
5446 BackgroundTask::spawn(World3D::create_open_world_city);
5447 let _: bool = self
5448 .active_signals()
5449 .get_engine3d_import_status()
5450 .set_if_changed(STATUS_ENGINE3D_LOADING.to_string());
5451 self.set_bg_city_task(Some(task));
5452 return false;
5453 }
5454 let world: World3D = World3D::create_open_world_city();
5455 self.install_world(world);
5456 true
5457 }
5458
5459 #[must_use]
5473 pub fn create_city(
5474 quality_signal: Signal<RenderQualityConfig>,
5475 time_signal: Signal<f32>,
5476 import_signal: Signal<u64>,
5477 status_signal: Signal<String>,
5478 camera_mode_signal: Signal<u8>,
5479 ) -> Self {
5480 let group: Engine3dSignals = Engine3dSignals {
5481 engine3d_quality: quality_signal,
5482 engine3d_preset_idx: Signal::new(4),
5483 engine3d_rt_idx: Signal::new(3),
5484 engine3d_res_scale: Signal::new(100.0),
5485 engine3d_time_of_day: time_signal,
5486 engine3d_import_queue: import_signal,
5487 engine3d_import_status: status_signal,
5488 engine3d_camera_mode: camera_mode_signal,
5489 engine3d_tsr_idx: Signal::new(0),
5490 engine3d_atmosphere_idx: Signal::new(0),
5491 engine3d_fullscreen_open: Signal::new(false),
5492 };
5493 let (state_scope, _): (Scope, ()) = Scope::run(|_: Scope| {});
5494 let mut scene: Self = Self::create_lazy_city_deferred(
5495 Rc::new(Cell::new(Some(group))),
5496 state_scope,
5497 Rc::new(Cell::new(false)),
5498 );
5499 let _: bool = scene.ensure_initialized();
5500 scene
5501 }
5502}
5503
5504impl GameScene for DemoOpenWorld3DScene {
5506 fn fixed_update(&mut self, dt: f32, input: &InputState) {
5514 if !self.ensure_initialized() {
5515 return;
5516 }
5517 let prev_world_rev: u64 = self.get_world().get_world_revision();
5518 let signals: Engine3dSignals = self.active_signals();
5519 let req_seq: u64 = signals.get_engine3d_import_queue().get_untracked();
5520 if req_seq != self.get_last_import_seq() {
5521 self.set_last_import_seq(req_seq);
5522 let is_obj: bool = req_seq % 2 == 1;
5523 let z_pos: f32 = -4.0 - ((req_seq % 5) as f32) * 8.0;
5524 let x_pos: f32 = if is_obj { -5.5 } else { 5.5 };
5525 let import_res: Result<ImportedModel3D, String> = if is_obj {
5526 self.get_mut_world().import_model(
5527 ModelFormat::Obj,
5528 SAMPLE_OBJ_MONUMENT,
5529 Transform3D::new(Vec3::new(x_pos, 0.0, z_pos), 0.0, Vec3::splat(1.0)),
5530 PbrMaterial::pbr(Color::hex(0xF59E0B), 0.9, 0.14, 0.72),
5531 0.85,
5532 )
5533 } else {
5534 self.get_mut_world().import_model(
5535 ModelFormat::GltfJson,
5536 SAMPLE_GLTF_TOWER,
5537 Transform3D::new(Vec3::new(x_pos, 0.0, z_pos), 0.0, Vec3::splat(1.0)),
5538 PbrMaterial::pbr(Color::hex(0x38BDF8), 0.85, 0.12, 0.80),
5539 -0.70,
5540 )
5541 };
5542 if let Ok(info) = import_res {
5543 let msg: String = format!(
5544 "Imported {} ({:?}): {} verts, {} tris (LOD0+LOD1 + BVH rebuilt)",
5545 info.get_name(),
5546 info.get_format(),
5547 info.get_total_vertices(),
5548 info.get_total_triangles()
5549 );
5550 let _: bool = signals.get_engine3d_import_status().set_if_changed(msg);
5551 }
5552 }
5553 let atmo_idx: usize = signals.get_engine3d_atmosphere_idx().get_untracked();
5554 if atmo_idx != self.get_last_atmosphere_idx() {
5555 self.set_last_atmosphere_idx(atmo_idx);
5556 let preset_hour: f32 = self
5557 .get_mut_world()
5558 .apply_atmosphere_preset(atmo_idx.min(3) as u8);
5559 let _: bool = signals
5560 .get_engine3d_time_of_day()
5561 .set_if_changed(preset_hour);
5562 } else {
5563 let hour: f32 = signals.get_engine3d_time_of_day().get_untracked();
5564 if (hour - self.get_world().get_sun().get_time_of_day()).abs() > 0.05 {
5565 self.get_mut_world()
5566 .set_sun(DirectionalLight3D::from_time_of_day(hour));
5567 }
5568 }
5569 let mods: Modifiers = input.get_modifiers();
5570 let no_mods: bool = !mods.get_ctrl() && !mods.get_meta() && !mods.get_alt();
5571 let allow_shortcuts: bool =
5572 no_mods && (EuvOverlayStack::active_count() == 0 || EuvOverlayStack::has_fullscreen());
5573 if allow_shortcuts {
5574 if input.is_key_just_pressed(KeyCode::Character('c'))
5575 || input.is_key_just_pressed(KeyCode::Character('C'))
5576 {
5577 let next_cam: u8 = (signals.get_engine3d_camera_mode().get_untracked() + 1) % 4;
5578 let _: bool = signals.get_engine3d_camera_mode().set_if_changed(next_cam);
5579 }
5580 if input.is_key_just_pressed(KeyCode::Character('f'))
5581 || input.is_key_just_pressed(KeyCode::Character('F'))
5582 {
5583 let fs_sig: Signal<bool> = signals.get_engine3d_fullscreen_open();
5584 let next_open: bool = !fs_sig.get_untracked();
5585 let _: bool = fs_sig.set_if_changed(next_open);
5586 }
5587 }
5588 let cam_mode: u8 = signals.get_engine3d_camera_mode().get_untracked();
5589 let cam_cut: bool = cam_mode != self.get_last_camera_mode();
5590 if cam_mode != self.get_world().get_camera_mode() {
5591 self.get_mut_world().set_camera_mode(cam_mode);
5592 }
5593 self.set_last_camera_mode(cam_mode);
5594 let Self { world, actions, .. } = self;
5595 world.step_simulation(dt, input, actions);
5596 let next_tick: u64 = self.get_ticks().saturating_add(1);
5597 self.set_ticks(next_tick);
5598 let world_changed: bool =
5599 cam_cut || self.get_world().get_world_revision() != prev_world_rev;
5600 if cam_cut {
5601 let Self {
5602 world, snapshots, ..
5603 } = self;
5604 snapshots.capture_discontinuous_into(|dst: &mut World3DSnapshot| {
5605 dst.capture_dynamic_into(world, next_tick, true, &[], &[]);
5606 });
5607 } else {
5608 let Self {
5609 world, snapshots, ..
5610 } = self;
5611 snapshots.capture_into(|dst: &mut World3DSnapshot| {
5612 dst.capture_dynamic_into(world, next_tick, false, &[], &[]);
5613 });
5614 }
5615 if world_changed {
5616 self.get_mut_gpu_target().mark_world_dirty();
5617 }
5618 }
5619
5620 fn update(&mut self, dt: f32, _input: &InputState) {
5628 if dt > 0.0001 {
5629 let inst_fps: f32 = (1.0 / dt).clamp(1.0, 9999.0);
5630 let prev: f32 = self.get_smoothed_fps();
5631 let next: f32 = if prev <= 0.5 {
5632 inst_fps
5633 } else {
5634 prev * 0.85 + inst_fps * 0.15
5635 };
5636 self.set_smoothed_fps(next);
5637 self.get_mut_gpu_target().mark_hud_dirty();
5638 }
5639 }
5640
5641 fn render(&mut self, alpha: f32, ctx: &mut GameRenderContext<'_>) {
5649 let size: Size = ctx.viewport_size();
5650 if !self.ensure_initialized() {
5651 ctx.clear(Color::hex(0x090D16));
5652 ctx.fill_rounded_rect(
5653 Rect::new(
5654 10.0,
5655 10.0,
5656 (size.get_width() - 20.0).clamp(200.0, 560.0),
5657 28.0,
5658 ),
5659 Color::rgba(15, 23, 42, 220),
5660 6.0,
5661 );
5662 ctx.draw_text(
5663 Point::new(18.0, 16.0),
5664 HUD_3D_LOADING_TITLE.to_string(),
5665 11.5,
5666 Color::hex(0x38BDF8),
5667 );
5668 return;
5669 }
5670 let signals: Engine3dSignals = self.active_signals();
5671 let mut quality: RenderQualityConfig = signals.get_engine3d_quality().get_untracked();
5672 let prev_render_ms: f32 = self.get_last_render_ms();
5673 if quality.get_dynamic_resolution() && prev_render_ms > 0.05 {
5674 let _: FramePacingTelemetry3D = self
5675 .get_mut_renderer()
5676 .apply_frame_pacing_feedback(prev_render_ms, &mut quality);
5677 }
5678 let dpr: f32 = clamp_viewport_scale(ctx.scale_factor());
5679 let user_res_scale: f32 =
5680 if quality.get_resolution_scale().is_finite() && quality.get_resolution_scale() > 0.0 {
5681 quality.get_resolution_scale().clamp(0.25, 2.0)
5682 } else {
5683 1.0
5684 };
5685 let phys_w: u32 = compute_lossless_physical_dim(
5686 f64::from(size.get_width().max(64.0)) * f64::from(user_res_scale),
5687 dpr,
5688 );
5689 let phys_h: u32 = compute_lossless_physical_dim(
5690 f64::from(size.get_height().max(64.0)) * f64::from(user_res_scale),
5691 dpr,
5692 );
5693 let vw: u32 = phys_w.clamp(160, 16_384);
5694 let vh: u32 = phys_h.clamp(160, 16_384);
5695 let next_fence: u64 = self.get_frame_fence().saturating_add(1);
5696 self.set_frame_fence(next_fence);
5697 let dst_rect: Rect = Rect::new(0.0, 0.0, size.get_width(), size.get_height());
5698 let alpha_milli: i32 = (alpha.clamp(0.0, 1.0) * 1000.0).round() as i32;
5699 let world_rev: u64 = self.get_gpu_target().get_world_revision();
5700 let can_reuse_world: bool = !self.get_gpu_target().needs_world_render()
5701 && self.get_cached_world_rev() == world_rev
5702 && self.get_cached_dims() == (vw, vh)
5703 && self.get_cached_quality() == quality
5704 && self.get_cached_alpha_milli() == alpha_milli;
5705 let mut blitted_pooled: bool = false;
5706 let mut direct_gpu_submitted: bool = false;
5707 let gpu_handle: GpuTextureHandle = self.get_gpu_target().get_handle();
5708 if ctx.is_direct_gpu_active() {
5709 #[cfg(not(target_arch = "wasm32"))]
5710 let render_started: Instant = Instant::now();
5711 let mesh_lib_len: usize = self.get_world().get_mesh_library().len();
5712 let needs_mesh_rebuild: bool = {
5713 let Self {
5714 gpu_mesh_buffer, ..
5715 } = self;
5716 gpu_mesh_buffer.is_none() || self.get_gpu_mesh_lib_len() != mesh_lib_len
5717 };
5718 if needs_mesh_rebuild {
5719 let next_rev: u64 = self.get_gpu_mesh_rev().saturating_add(1);
5720 let (built_buf, built_ranges): (Arc<GpuWorld3dMeshBuffer>, Vec<(u32, u32)>) =
5721 self.get_world().build_gpu_mesh_buffer(next_rev);
5722 self.set_gpu_mesh_rev(next_rev);
5723 self.set_gpu_mesh_lib_len(mesh_lib_len);
5724 self.set_gpu_mesh_buffer(Some(built_buf));
5725 self.set_gpu_mesh_ranges(built_ranges);
5726 }
5727 let scene_pass_opt: Option<GpuWorld3dScenePass> = {
5728 let Self {
5729 world,
5730 snapshots,
5731 gpu_mesh_buffer,
5732 gpu_mesh_ranges,
5733 ..
5734 } = self;
5735 gpu_mesh_buffer
5736 .as_ref()
5737 .map(|mesh_buf: &Arc<GpuWorld3dMeshBuffer>| {
5738 world.build_gpu_scene_pass(
5739 snapshots,
5740 alpha,
5741 (vw, vh),
5742 &quality,
5743 (mesh_buf, gpu_mesh_ranges.as_slice()),
5744 )
5745 })
5746 };
5747 if let Some(scene_pass) = scene_pass_opt {
5748 let inst_count: usize = scene_pass.get_instances().len();
5749 let batch_count: usize = scene_pass.get_draw_batches().len();
5750 let tri_count: usize = scene_pass
5751 .get_draw_batches()
5752 .iter()
5753 .map(|range: &GpuWorld3dMeshRange| {
5754 ((range.get_vertex_count() as usize) / 3)
5755 .saturating_mul(range.get_instance_count() as usize)
5756 })
5757 .sum();
5758 ctx.submit_gpu_scene_pass(
5759 dst_rect,
5760 DirectGpuScenePass::World3d(Box::new(scene_pass)),
5761 );
5762 #[cfg(not(target_arch = "wasm32"))]
5763 let measured_ms: f32 = (render_started.elapsed().as_nanos() as f32) / 1_000_000.0;
5764 #[cfg(target_arch = "wasm32")]
5765 let measured_ms: f32 = 0.25;
5766 self.set_last_render_ms(measured_ms);
5767 let last_stats: &mut RenderStats3D = self.get_mut_renderer().get_mut_last_stats();
5768 last_stats.set_render_width(vw);
5769 last_stats.set_render_height(vh);
5770 last_stats.set_visible_objects(inst_count);
5771 last_stats.set_instanced_batches(batch_count);
5772 last_stats.set_triangles_drawn(tri_count);
5773 let hud_rev: u64 = self.get_gpu_target().get_hud_revision();
5774 let target: &mut GpuCompositeTarget = self.get_mut_gpu_target();
5775 target.set_presented_world_revision(world_rev);
5776 target.set_presented_hud_revision(hud_rev);
5777 blitted_pooled = true;
5778 direct_gpu_submitted = true;
5779 }
5780 } else if gpu_handle.is_valid() && ctx.composite_gpu_texture(dst_rect, gpu_handle) {
5781 let _: Option<GpuCompositeDescriptor> = self
5782 .get_mut_gpu_target()
5783 .record_composite_present(next_fence);
5784 blitted_pooled = true;
5785 } else if can_reuse_world {
5786 let reused_ref: Option<PooledFrameRef> = {
5787 let Self {
5788 cached_world_frame, ..
5789 } = self;
5790 cached_world_frame.clone()
5791 };
5792 if let Some(cached_ref) = reused_ref {
5793 ctx.blit_pooled_frame_ref(dst_rect, &cached_ref);
5794 let hud_rev: u64 = self.get_gpu_target().get_hud_revision();
5795 let next_reuse: u64 = self
5796 .get_gpu_target()
5797 .get_hud_only_reuses()
5798 .saturating_add(1);
5799 let target: &mut GpuCompositeTarget = self.get_mut_gpu_target();
5800 target.set_presented_hud_revision(hud_rev);
5801 target.set_hud_only_reuses(next_reuse);
5802 blitted_pooled = true;
5803 }
5804 }
5805 if !blitted_pooled {
5806 self.set_cached_world_frame(None);
5807 #[cfg(not(target_arch = "wasm32"))]
5808 let render_started: Instant = Instant::now();
5809 let use_tsr_upscale: bool = quality.get_anti_aliasing() == AntiAliasingMode::Tsr
5810 && quality.get_resolution_scale() < 0.99;
5811 let pooled_lease: Option<PooledFrameLease> = {
5812 let Self {
5813 world,
5814 renderer,
5815 snapshots,
5816 frame_pool,
5817 ..
5818 } = self;
5819 if use_tsr_upscale {
5820 renderer.render_world_tsr_into_pool(
5821 world,
5822 (vw, vh),
5823 &quality,
5824 (frame_pool, next_fence),
5825 )
5826 } else {
5827 renderer.render_world_interpolated_into_pool(
5828 world,
5829 snapshots,
5830 alpha,
5831 (vw, vh),
5832 &quality,
5833 (frame_pool, next_fence),
5834 )
5835 }
5836 };
5837 if let Some(lease) = pooled_lease {
5838 ctx.blit_pooled_frame(dst_rect, &lease);
5839 let cached_ref: PooledFrameRef = lease.to_frame_ref();
5840 lease.submit_in_flight();
5841 let _: usize = self.get_frame_pool().retire_fence(next_fence);
5842 self.set_cached_world_frame(Some(cached_ref));
5843 blitted_pooled = true;
5844 }
5845 if !blitted_pooled {
5846 let frame_img: ImageBuffer = {
5847 let Self {
5848 world, renderer, ..
5849 } = self;
5850 renderer.render_world(world, vw, vh, &quality)
5851 };
5852 ctx.draw_image(dst_rect, frame_img);
5853 }
5854 #[cfg(not(target_arch = "wasm32"))]
5855 let measured_ms: f32 = (render_started.elapsed().as_nanos() as f32) / 1_000_000.0;
5856 #[cfg(target_arch = "wasm32")]
5857 let measured_ms: f32 = if self.get_smoothed_fps() > 1.0 {
5858 1000.0 / self.get_smoothed_fps()
5859 } else {
5860 16.67
5861 };
5862 self.set_last_render_ms(measured_ms);
5863 self.set_cached_world_rev(world_rev);
5864 self.set_cached_dims((vw, vh));
5865 self.set_cached_quality(quality);
5866 self.set_cached_alpha_milli(alpha_milli);
5867 let hud_rev: u64 = self.get_gpu_target().get_hud_revision();
5868 let target: &mut GpuCompositeTarget = self.get_mut_gpu_target();
5869 target.set_presented_world_revision(world_rev);
5870 target.set_presented_hud_revision(hud_rev);
5871 }
5872 let stats: RenderStats3D = self.get_renderer().get_last_stats();
5873 let fps: f32 = self.get_smoothed_fps();
5874 let exp_val: f32 = self.get_renderer().get_adapted_exposure();
5875 let aa_tag: &str = match quality.get_anti_aliasing() {
5876 AntiAliasingMode::Tsr => HUD_AA_TSR,
5877 AntiAliasingMode::Taa => HUD_AA_TAA,
5878 AntiAliasingMode::Fxaa => HUD_AA_FXAA,
5879 AntiAliasingMode::Off => HUD_AA_OFF,
5880 };
5881 let compact_hud: bool = size.get_width() < 520.0;
5882 let render_ms: f32 = self.get_last_render_ms();
5883 let rays_k: f32 = (stats.get_rays_traced() as f32) * 0.001;
5884 let tris_k: f32 = (stats.get_triangles_drawn() as f32) * 0.001;
5885 let hud_text: String = if direct_gpu_submitted {
5886 if compact_hud {
5887 format!(
5888 "{fps:.0} FPS · GPU {}x{} · {render_ms:.2}ms · {tris_k:.1}k tris",
5889 stats.get_render_width(),
5890 stats.get_render_height(),
5891 )
5892 } else {
5893 format!(
5894 "{fps:.0} FPS · GPU PBR {:?} · {}x{} · {render_ms:.2}ms · {} inst · {} draws · {tris_k:.1}k tris · Exp {exp_val:.2}",
5895 quality.get_preset(),
5896 stats.get_render_width(),
5897 stats.get_render_height(),
5898 stats.get_visible_objects(),
5899 stats.get_instanced_batches(),
5900 )
5901 }
5902 } else if compact_hud {
5903 format!(
5904 "{fps:.0} FPS · {}x{} · {render_ms:.1}ms · {rays_k:.1}k rays",
5905 stats.get_render_width(),
5906 stats.get_render_height(),
5907 )
5908 } else {
5909 format!(
5910 "{fps:.0} FPS · {:?} {aa_tag} · {}x{} · {render_ms:.1}ms · {rays_k:.1}k rays · Reproj {} · Exp {exp_val:.2}",
5911 quality.get_preset(),
5912 stats.get_render_width(),
5913 stats.get_render_height(),
5914 stats.get_probe_reproj_hits(),
5915 )
5916 };
5917 let hud_w: f32 = ((hud_text.len() as f32) * 5.2 + 20.0)
5918 .clamp(160.0, (size.get_width() - 20.0).max(160.0));
5919 let hud_y: f32 = (size.get_height() - 36.0).max(48.0);
5920 let hud_rect: Rect = Rect::new(10.0, hud_y, hud_w, 26.0);
5921 ctx.fill_rounded_rect(hud_rect, Color::rgba(9, 13, 24, 212), 8.0);
5922 ctx.stroke_rect(hud_rect, 1.0, Color::rgba(148, 163, 184, 72));
5923 ctx.draw_text(
5924 Point::new(18.0, hud_y + 5.5),
5925 hud_text,
5926 10.5,
5927 Color::hex(0xE2E8F0),
5928 );
5929 }
5930}