Skip to main content

euv_core/game/viewport/
impl.rs

1use super::*;
2
3/// Viewport-local drawing primitives for `GameRenderContext`.
4impl<'a> GameRenderContext<'a> {
5    /// Creates a `GameRenderContext` bound to `bounds` and `display_list`.
6    ///
7    /// # Arguments
8    ///
9    /// - `Rect` - Viewport bounds in root logical coordinates.
10    /// - `&'a mut DisplayList` - Target display list.
11    ///
12    /// # Returns
13    ///
14    /// - `Self` - Constructed viewport render context.
15    pub fn new(bounds: Rect, display_list: &'a mut DisplayList) -> Self {
16        Self {
17            bounds,
18            display_list,
19            gpu_composite: None,
20        }
21    }
22
23    /// Binds a shared same-device GPU render target texture to be composited directly beneath EUV HUD overlays in a single present without CPU readback.
24    ///
25    /// # Arguments
26    ///
27    /// - `&Self` - Mutable render context.
28    /// - `Rect` - Local destination rectangle inside the viewport.
29    /// - `GpuTextureHandle` - Valid same-device GPU render target handle.
30    ///
31    /// # Returns
32    ///
33    /// - `bool` - `true` when the handle is valid and bound for direct GPU compositing.
34    pub fn composite_gpu_texture(&mut self, rect: Rect, handle: GpuTextureHandle) -> bool {
35        if !handle.is_valid() {
36            return false;
37        }
38        let Self {
39            bounds,
40            gpu_composite,
41            ..
42        } = self;
43        let world: Rect = Rect::new(
44            bounds.get_x() + rect.get_x(),
45            bounds.get_y() + rect.get_y(),
46            rect.get_width(),
47            rect.get_height(),
48        );
49        *gpu_composite = Some(GpuCompositeDescriptor::new(world, handle, 0, true));
50        true
51    }
52
53    /// Returns the bound GPU composite descriptor emitted during this frame, if any.
54    ///
55    /// # Arguments
56    ///
57    /// - `&Self` - Render context reference.
58    ///
59    /// # Returns
60    ///
61    /// - `Option<GpuCompositeDescriptor>` - Bound GPU composite target descriptor.
62    #[must_use]
63    pub fn gpu_composite_target(&self) -> Option<GpuCompositeDescriptor> {
64        let Self { gpu_composite, .. } = self;
65        *gpu_composite
66    }
67
68    /// Consumes and returns the bound GPU composite descriptor emitted during this frame for direct single-pass UI+3D compositing.
69    ///
70    /// # Arguments
71    ///
72    /// - `&Self` - Mutable render context.
73    ///
74    /// # Returns
75    ///
76    /// - `Option<GpuCompositeDescriptor>` - Bound GPU composite target descriptor if one was attached.
77    #[must_use]
78    pub fn take_gpu_composite_target(&mut self) -> Option<GpuCompositeDescriptor> {
79        let Self { gpu_composite, .. } = self;
80        gpu_composite.take()
81    }
82
83    /// Composes a `GpuSharedSurface` directly onto the shared GPU present chain with zero CPU readback.
84    ///
85    /// # Arguments
86    ///
87    /// - `&Self` - Mutable render context.
88    /// - `&mut GpuSharedSurface` - Shared 3D+HUD GPU presentation surface.
89    /// - `u64` - Active compositor logical GPU device identifier.
90    ///
91    /// # Returns
92    ///
93    /// - `SharedGpuCompositeReceipt` - Honest receipt reporting zero-readback GPU compositing telemetry.
94    pub fn compose_shared_gpu_surface(
95        &mut self,
96        surface: &mut GpuSharedSurface,
97        compositor_device_id: u64,
98    ) -> SharedGpuCompositeReceipt {
99        surface.compose_frame(compositor_device_id, self)
100    }
101
102    /// Blits a pooled CPU fallback frame lease into `rect` inside this game viewport with zero per-frame pixel copy.
103    ///
104    /// # Arguments
105    ///
106    /// - `&Self` - Mutable render context.
107    /// - `Rect` - Local destination rectangle.
108    /// - `&PooledFrameLease` - Rendered pooled RGBA8 frame lease.
109    pub fn blit_pooled_frame(&mut self, rect: Rect, lease: &PooledFrameLease) {
110        let frame_ref: PooledFrameRef = lease.to_frame_ref();
111        self.blit_pooled_frame_ref(rect, &frame_ref);
112    }
113
114    /// Blits a zero-copy `PooledFrameRef` handle into `rect` inside this game viewport via `Arc` sharing without pixel copy.
115    ///
116    /// # Arguments
117    ///
118    /// - `&Self` - Mutable render context.
119    /// - `Rect` - Local destination rectangle.
120    /// - `&PooledFrameRef` - Shared pooled RGBA8 frame reference.
121    pub fn blit_pooled_frame_ref(&mut self, rect: Rect, frame: &PooledFrameRef) {
122        let Self {
123            bounds,
124            display_list,
125            ..
126        } = self;
127        let world: Rect = Rect::new(
128            bounds.get_x() + rect.get_x(),
129            bounds.get_y() + rect.get_y(),
130            rect.get_width(),
131            rect.get_height(),
132        );
133        display_list.push(DrawCommand::SharedImage {
134            rect: world,
135            width: frame.get_width(),
136            height: frame.get_height(),
137            pixels: frame.shared_pixels(),
138            radius: CornerRadius::default(),
139        });
140    }
141
142    /// Returns `true` when the active compositor executes hardware GPU offscreen scene passes (`OceanFluid` / `World3d`) directly without CPU pixel rasterization.
143    ///
144    /// # Returns
145    ///
146    /// - `bool` - `true` when direct-GPU hardware scene rendering is active.
147    #[must_use]
148    pub fn is_direct_gpu_active(&self) -> bool {
149        let Self { display_list, .. } = self;
150        display_list.get_direct_gpu_scene_enabled()
151    }
152
153    /// Returns the hysteresis-stabilized offscreen 3D/water shader workload scale (`1.0` = `100%` maximum quality, never affecting UI/text/vector 1:1 physical pixels).
154    ///
155    /// # Returns
156    ///
157    /// - `f32` - Stabilized offscreen workload resolution multiplier in `[0.35, 1.0]`.
158    #[must_use]
159    pub fn scene_workload_scale(&self) -> f32 {
160        active_scene_workload_scale()
161    }
162
163    /// Submits a hardware GPU offscreen scene pass (`OceanFluid` or `World3d`) and emits a matching `DrawCommand::ExternalSurface` composite quad.
164    ///
165    /// # Arguments
166    ///
167    /// - `Rect` - Local destination rectangle inside the viewport.
168    /// - `DirectGpuScenePass` - Hardware GPU offscreen render pass descriptor.
169    pub fn submit_gpu_scene_pass(&mut self, rect: Rect, pass: DirectGpuScenePass) {
170        let Self {
171            bounds,
172            display_list,
173            ..
174        } = self;
175        let world: Rect = Rect::new(
176            bounds.get_x() + rect.get_x(),
177            bounds.get_y() + rect.get_y(),
178            rect.get_width(),
179            rect.get_height(),
180        );
181        display_list.set_gpu_scene_pass(Some(pass));
182        display_list.push(DrawCommand::ExternalSurface {
183            rect: world,
184            radius: CornerRadius::default(),
185        });
186    }
187
188    /// Returns the logical width and height of the game viewport.
189    ///
190    /// # Arguments
191    ///
192    /// - `&Self` - Render context reference.
193    ///
194    /// # Returns
195    ///
196    /// - `Size` - Viewport size in logical pixels.
197    #[must_use]
198    pub fn viewport_size(&self) -> Size {
199        let Self { bounds, .. } = self;
200        Size::new(bounds.get_width(), bounds.get_height())
201    }
202
203    /// Returns the active display DPI scale factor of the target `DisplayList` (`>= 0.5`).
204    ///
205    /// # Arguments
206    ///
207    /// - `&Self` - Render context reference.
208    ///
209    /// # Returns
210    ///
211    /// - `f32` - Active display DPI scale factor.
212    #[must_use]
213    pub fn scale_factor(&self) -> f32 {
214        let Self { display_list, .. } = self;
215        let raw: f32 = display_list.get_scale_factor();
216        if raw.is_finite() && raw > 0.0 {
217            raw.clamp(0.5, 6.0)
218        } else {
219            1.0
220        }
221    }
222
223    /// Fills the entire game viewport with `color`.
224    ///
225    /// # Arguments
226    ///
227    /// - `&Self` - Mutable render context.
228    /// - `Color` - Background clear color.
229    pub fn clear(&mut self, color: Color) {
230        let Self {
231            bounds,
232            display_list,
233            ..
234        } = self;
235        display_list.push(DrawCommand::FillRoundedRect {
236            rect: *bounds,
237            color,
238            radius: CornerRadius::default(),
239            border: Border::default(),
240        });
241    }
242
243    /// Draws an axis-aligned solid rectangle in viewport-local coordinates.
244    ///
245    /// # Arguments
246    ///
247    /// - `&Self` - Mutable render context.
248    /// - `Rect` - Local rectangle bounds.
249    /// - `Color` - Fill color.
250    pub fn fill_rect(&mut self, rect: Rect, color: Color) {
251        self.fill_rounded_rect(rect, color, 0.0);
252    }
253
254    /// Draws a rounded solid rectangle in viewport-local coordinates.
255    ///
256    /// # Arguments
257    ///
258    /// - `&Self` - Mutable render context.
259    /// - `Rect` - Local rectangle bounds.
260    /// - `Color` - Fill color.
261    /// - `f32` - Corner radius in logical pixels.
262    pub fn fill_rounded_rect(&mut self, rect: Rect, color: Color, radius: f32) {
263        let Self {
264            bounds,
265            display_list,
266            ..
267        } = self;
268        let world: Rect = Rect::new(
269            bounds.get_x() + rect.get_x(),
270            bounds.get_y() + rect.get_y(),
271            rect.get_width(),
272            rect.get_height(),
273        );
274        display_list.push(DrawCommand::FillRoundedRect {
275            rect: world,
276            color,
277            radius: CornerRadius::all(radius),
278            border: Border::default(),
279        });
280    }
281
282    /// Draws an outlined rectangle in viewport-local coordinates.
283    ///
284    /// # Arguments
285    ///
286    /// - `&Self` - Mutable render context.
287    /// - `Rect` - Local rectangle bounds.
288    /// - `f32` - Stroke thickness in logical pixels.
289    /// - `Color` - Stroke color.
290    pub fn stroke_rect(&mut self, rect: Rect, stroke_width: f32, color: Color) {
291        let Self {
292            bounds,
293            display_list,
294            ..
295        } = self;
296        let world: Rect = Rect::new(
297            bounds.get_x() + rect.get_x(),
298            bounds.get_y() + rect.get_y(),
299            rect.get_width(),
300            rect.get_height(),
301        );
302        display_list.push(DrawCommand::FillRoundedRect {
303            rect: world,
304            color: COLOR_TRANSPARENT,
305            radius: CornerRadius::default(),
306            border: Border::new(stroke_width, color),
307        });
308    }
309
310    /// Draws a filled circle in viewport-local coordinates.
311    ///
312    /// # Arguments
313    ///
314    /// - `&Self` - Mutable render context.
315    /// - `Point` - Circle center in viewport-local coordinates.
316    /// - `f32` - Circle radius in logical pixels.
317    /// - `Color` - Fill color.
318    pub fn fill_circle(&mut self, center: Point, radius: f32, color: Color) {
319        let Self {
320            bounds,
321            display_list,
322            ..
323        } = self;
324        let world: Point = Point::new(
325            bounds.get_x() + center.get_x(),
326            bounds.get_y() + center.get_y(),
327        );
328        display_list.push(DrawCommand::Circle {
329            center: world,
330            radius,
331            color,
332        });
333    }
334
335    /// Draws an RGBA8 `ImageBuffer` stretched into `rect` inside this game viewport (ideal for 3D render targets).
336    ///
337    /// # Arguments
338    ///
339    /// - `&Self` - Mutable render context.
340    /// - `Rect` - Local destination rectangle inside the viewport.
341    /// - `ImageBuffer` - Source RGBA8 pixel buffer.
342    pub fn draw_image(&mut self, rect: Rect, buffer: ImageBuffer) {
343        let Self {
344            bounds,
345            display_list,
346            ..
347        } = self;
348        let world: Rect = Rect::new(
349            bounds.get_x() + rect.get_x(),
350            bounds.get_y() + rect.get_y(),
351            rect.get_width(),
352            rect.get_height(),
353        );
354        display_list.push(DrawCommand::Image {
355            rect: world,
356            buffer,
357            radius: CornerRadius::default(),
358        });
359    }
360
361    /// Draws an anti-aliased line segment in viewport-local coordinates.
362    ///
363    /// # Arguments
364    ///
365    /// - `&Self` - Mutable render context.
366    /// - `Point` - Segment start point.
367    /// - `Point` - Segment end point.
368    /// - `f32` - Line width in logical pixels.
369    /// - `Color` - Line color.
370    pub fn draw_line(&mut self, from: Point, to: Point, width: f32, color: Color) {
371        let Self {
372            bounds,
373            display_list,
374            ..
375        } = self;
376        display_list.push(DrawCommand::Line {
377            from: Point::new(bounds.get_x() + from.get_x(), bounds.get_y() + from.get_y()),
378            to: Point::new(bounds.get_x() + to.get_x(), bounds.get_y() + to.get_y()),
379            color,
380            width,
381        });
382    }
383
384    /// Draws HUD or debug text inside the game viewport.
385    ///
386    /// # Arguments
387    ///
388    /// - `&Self` - Mutable render context.
389    /// - `Point` - Top-left local position.
390    /// - `String` - Text string.
391    /// - `f32` - Font size in logical pixels.
392    /// - `Color` - Text color.
393    pub fn draw_text(&mut self, position: Point, text: String, font_size: f32, color: Color) {
394        let Self {
395            bounds,
396            display_list,
397            ..
398        } = self;
399        let mut style: TextStyle = TextStyle::default();
400        style.set_font_size(font_size);
401        style.set_color(color);
402        display_list.push(DrawCommand::TextRun {
403            rect: Rect::new(
404                bounds.get_x() + position.get_x(),
405                bounds.get_y() + position.get_y(),
406                (bounds.get_width() - position.get_x()).max(0.0),
407                font_size * 1.6,
408            ),
409            text,
410            style,
411        });
412    }
413
414    /// Draws HUD or debug text from a borrowed slice using the display list's recycled string pool for zero steady-state allocations.
415    ///
416    /// # Arguments
417    ///
418    /// - `&Self` - Mutable render context.
419    /// - `Point` - Top-left local position.
420    /// - `&str` - Borrowed UTF-8 text slice.
421    /// - `f32` - Font size in logical pixels.
422    /// - `Color` - Text color.
423    pub fn draw_text_str(&mut self, position: Point, text: &str, font_size: f32, color: Color) {
424        let Self {
425            bounds,
426            display_list,
427            ..
428        } = self;
429        let pooled: String = display_list.alloc_text(text);
430        let mut style: TextStyle = TextStyle::default();
431        style.set_font_size(font_size);
432        style.set_color(color);
433        display_list.push(DrawCommand::TextRun {
434            rect: Rect::new(
435                bounds.get_x() + position.get_x(),
436                bounds.get_y() + position.get_y(),
437                (bounds.get_width() - position.get_x()).max(0.0),
438                font_size * 1.6,
439            ),
440            text: pooled,
441            style,
442        });
443    }
444
445    /// Blits an external 2D/3D engine RGBA8 `ImageBuffer` directly into the viewport.
446    ///
447    /// # Arguments
448    ///
449    /// - `&Self` - Mutable render context.
450    /// - `Rect` - Local destination rectangle.
451    /// - `ImageBuffer` - External engine rendered frame or sprite sheet.
452    pub fn blit_framebuffer(&mut self, rect: Rect, buffer: ImageBuffer) {
453        let Self {
454            bounds,
455            display_list,
456            ..
457        } = self;
458        let world: Rect = Rect::new(
459            bounds.get_x() + rect.get_x(),
460            bounds.get_y() + rect.get_y(),
461            rect.get_width(),
462            rect.get_height(),
463        );
464        display_list.push(DrawCommand::Image {
465            rect: world,
466            buffer,
467            radius: CornerRadius::default(),
468        });
469    }
470
471    /// Draws a filled triangle in viewport-local coordinates.
472    ///
473    /// # Arguments
474    ///
475    /// - `&Self` - Mutable render context.
476    /// - `Point` - First vertex.
477    /// - `Point` - Second vertex.
478    /// - `Point` - Third vertex.
479    /// - `Color` - Fill color.
480    pub fn fill_triangle(&mut self, p0: Point, p1: Point, p2: Point, color: Color) {
481        let Self {
482            bounds,
483            display_list,
484            ..
485        } = self;
486        let ox: f32 = bounds.get_x();
487        let oy: f32 = bounds.get_y();
488        display_list.push(DrawCommand::Triangle {
489            p0: Point::new(ox + p0.get_x(), oy + p0.get_y()),
490            p1: Point::new(ox + p1.get_x(), oy + p1.get_y()),
491            p2: Point::new(ox + p2.get_x(), oy + p2.get_y()),
492            color,
493        });
494    }
495
496    /// Draws a cropped frame from a `SpriteSheet` into `rect` with multiplicative `tint`.
497    ///
498    /// # Arguments
499    ///
500    /// - `&Self` - Mutable render context.
501    /// - `&SpriteSheet` - Source sprite sheet.
502    /// - `u32` - Zero-based animation frame index.
503    /// - `Rect` - Destination viewport-local rectangle.
504    /// - `Color` - Multiplicative tint color.
505    pub fn draw_sprite_frame(
506        &mut self,
507        sheet: &SpriteSheet,
508        frame_index: u32,
509        rect: Rect,
510        tint: Color,
511    ) {
512        let src_rect: Rect = sheet.frame_rect(frame_index);
513        let Self {
514            bounds,
515            display_list,
516            ..
517        } = self;
518        display_list.push(DrawCommand::SpriteRegion {
519            rect: Rect::new(
520                bounds.get_x() + rect.get_x(),
521                bounds.get_y() + rect.get_y(),
522                rect.get_width(),
523                rect.get_height(),
524            ),
525            buffer: sheet.get_texture().clone(),
526            src_rect,
527            tint,
528        });
529    }
530
531    /// Renders all visible tiles of `tilemap` through `camera` using hoisted camera shake, cached static chunk batches, and horizontal run merging.
532    ///
533    /// # Arguments
534    ///
535    /// - `&Self` - Mutable render context.
536    /// - `&TileMap` - Grid tilemap to draw.
537    /// - `&Camera2D` - Active 2D world camera.
538    pub fn render_tilemap(&mut self, tilemap: &TileMap, camera: &Camera2D) {
539        let box_size: Size = self.viewport_size();
540        let vis: Rect = camera.visible_world_rect(box_size);
541        let timestamp_val: f32 = tilemap.get_tile_size();
542        let (cam_x, cam_y, zoom, half_w, half_h): (f32, f32, f32, f32, f32) =
543            camera.projection_params(box_size);
544        let min_c: usize = (vis.get_x() / timestamp_val).floor().max(0.0) as usize;
545        let max_c: usize =
546            ((vis.right() / timestamp_val).ceil().max(0.0) as usize).min(tilemap.get_columns());
547        let min_r: usize = (vis.get_y() / timestamp_val).floor().max(0.0) as usize;
548        let max_r: usize =
549            ((vis.bottom() / timestamp_val).ceil().max(0.0) as usize).min(tilemap.get_rows());
550        let tile_px: f32 = (timestamp_val * zoom).max(1.0);
551        if tilemap.has_fresh_chunk_cache() {
552            for chunk in tilemap.cached_chunks().iter() {
553                if chunk.get_max_col() <= min_c
554                    || chunk.get_min_col() >= max_c
555                    || chunk.get_max_row() <= min_r
556                    || chunk.get_min_row() >= max_r
557                {
558                    continue;
559                }
560                for run in chunk.get_runs().iter() {
561                    let red_val: usize = run.get_row();
562                    if red_val < min_r || red_val >= max_r {
563                        continue;
564                    }
565                    let c0: usize = run.get_col().max(min_c);
566                    let c1: usize = (run.get_col() + run.get_span_cols()).min(max_c);
567                    if c0 >= c1 {
568                        continue;
569                    }
570                    let sx: f32 = ((c0 as f32) * timestamp_val - cam_x) * zoom + half_w;
571                    let sy: f32 = ((red_val as f32) * timestamp_val - cam_y) * zoom + half_h;
572                    let run_w: f32 = ((c1 - c0) as f32) * tile_px + 0.5;
573                    self.fill_rect(Rect::new(sx, sy, run_w, tile_px + 0.5), run.get_color());
574                }
575            }
576            return;
577        }
578        let palette: &[TilePaletteEntry] = tilemap.get_palette().as_slice();
579        for row in min_r..max_r {
580            let sy: f32 = ((row as f32) * timestamp_val - cam_y) * zoom + half_h;
581            let mut col: usize = min_c;
582            while col < max_c {
583                let tid: u16 = tilemap.tile_at(col, row);
584                if tid == 0 {
585                    col += 1;
586                    continue;
587                }
588                let Some(entry) = palette.get(tid as usize) else {
589                    col += 1;
590                    continue;
591                };
592                let color: Color = entry.get_color();
593                let start_col: usize = col;
594                col += 1;
595                while col < max_c {
596                    let next_tid: u16 = tilemap.tile_at(col, row);
597                    if next_tid == 0 {
598                        break;
599                    }
600                    let same_color: bool = palette
601                        .get(next_tid as usize)
602                        .is_some_and(|event_ref: &TilePaletteEntry| event_ref.get_color() == color);
603                    if !same_color {
604                        break;
605                    }
606                    col += 1;
607                }
608                let sx: f32 = ((start_col as f32) * timestamp_val - cam_x) * zoom + half_w;
609                let run_w: f32 = ((col - start_col) as f32) * tile_px + 0.5;
610                self.fill_rect(Rect::new(sx, sy, run_w, tile_px + 0.5), color);
611            }
612        }
613    }
614
615    /// Renders all visible sprite entities in `world` through `camera`, sorted by `z_order` with frustum culling and hoisted camera shake.
616    ///
617    /// # Arguments
618    ///
619    /// - `&Self` - Mutable render context.
620    /// - `&GameWorld` - Active ECS world.
621    /// - `&Camera2D` - Active 2D world camera.
622    ///
623    /// # Returns
624    ///
625    /// - `usize` - Number of visible entities drawn after frustum culling.
626    pub fn render_world(&mut self, world: &GameWorld, camera: &Camera2D) -> usize {
627        let box_size: Size = self.viewport_size();
628        let vis: Rect = camera.visible_world_rect(box_size);
629        let (cam_x, cam_y, zoom, half_w, half_h): (f32, f32, f32, f32, f32) =
630            camera.projection_params(box_size);
631        let mut draw_order: Vec<(i32, usize)> = Vec::with_capacity(world.get_live_count());
632        for (idx, ent) in world.get_entities().iter().enumerate() {
633            if !ent.get_alive() {
634                continue;
635            }
636            let Some(sp) = ent.sprite_component() else {
637                continue;
638            };
639            if !sp.get_visible() {
640                continue;
641            }
642            if ent.world_bounds().intersect(vis).is_none() {
643                continue;
644            }
645            draw_order.push((sp.get_z_order(), idx));
646        }
647        draw_order.sort_by(|alpha_val: &(i32, usize), blue_val: &(i32, usize)| {
648            alpha_val
649                .0
650                .cmp(&blue_val.0)
651                .then_with(|| alpha_val.1.cmp(&blue_val.1))
652        });
653        let rendered: usize = draw_order.len();
654        for (_, idx) in draw_order.into_iter() {
655            let ent: &EntityRecord = &world.get_entities()[idx];
656            let Some(sp) = ent.sprite_component() else {
657                continue;
658            };
659            let transform_val: EntityTransform = ent.get_transform();
660            let pos: Point = transform_val.get_position();
661            let center: Point = Point::new(
662                (pos.get_x() - cam_x) * zoom + half_w,
663                (pos.get_y() - cam_y) * zoom + half_h,
664            );
665            let width_val: f32 =
666                sp.get_size().get_width() * transform_val.get_scale().get_width() * zoom;
667            let height_val: f32 =
668                sp.get_size().get_height() * transform_val.get_scale().get_height() * zoom;
669            match sp.get_shape() {
670                EntityVisualShape::Rect => {
671                    let rect: Rect = Rect::new(
672                        center.get_x() - width_val * 0.5,
673                        center.get_y() - height_val * 0.5,
674                        width_val,
675                        height_val,
676                    );
677                    self.fill_rounded_rect(rect, sp.get_color(), sp.get_corner_radius() * zoom);
678                    if sp.get_accent().get_alpha() > 0 {
679                        self.stroke_rect(rect, 1.5, sp.get_accent());
680                    }
681                }
682                EntityVisualShape::Circle => {
683                    let red_val: f32 = (width_val.min(height_val) * 0.5).max(1.0);
684                    self.fill_circle(center, red_val, sp.get_color());
685                    if sp.get_accent().get_alpha() > 0 && red_val > 3.0 {
686                        self.fill_circle(center, red_val * 0.45, sp.get_accent());
687                    }
688                }
689                EntityVisualShape::Triangle => {
690                    let ang: f32 = transform_val.get_rotation_rad();
691                    let cos_a: f32 = ang.cos();
692                    let sin_a: f32 = ang.sin();
693                    let rx: f32 = width_val * 0.55;
694                    let ry: f32 = height_val * 0.48;
695                    let nose: Point =
696                        Point::new(center.get_x() + cos_a * rx, center.get_y() + sin_a * rx);
697                    let left: Point = Point::new(
698                        center.get_x() - cos_a * (rx * 0.72) - sin_a * ry,
699                        center.get_y() - sin_a * (rx * 0.72) + cos_a * ry,
700                    );
701                    let right: Point = Point::new(
702                        center.get_x() - cos_a * (rx * 0.72) + sin_a * ry,
703                        center.get_y() - sin_a * (rx * 0.72) - cos_a * ry,
704                    );
705                    self.fill_triangle(nose, left, right, sp.get_color());
706                    if sp.get_accent().get_alpha() > 0 {
707                        self.fill_circle(
708                            center,
709                            (width_val.min(height_val) * 0.16).max(2.0),
710                            sp.get_accent(),
711                        );
712                    }
713                }
714                EntityVisualShape::Diamond => {
715                    let hw: f32 = width_val * 0.5;
716                    let hh: f32 = height_val * 0.5;
717                    let top: Point = Point::new(center.get_x(), center.get_y() - hh);
718                    let right: Point = Point::new(center.get_x() + hw, center.get_y());
719                    let bottom: Point = Point::new(center.get_x(), center.get_y() + hh);
720                    let left: Point = Point::new(center.get_x() - hw, center.get_y());
721                    self.fill_triangle(top, right, bottom, sp.get_color());
722                    self.fill_triangle(top, bottom, left, sp.get_color());
723                    if sp.get_accent().get_alpha() > 0 {
724                        self.fill_circle(
725                            center,
726                            (width_val.min(height_val) * 0.18).max(2.0),
727                            sp.get_accent(),
728                        );
729                    }
730                }
731            }
732        }
733        rendered
734    }
735
736    /// Renders all visible 2D entities in `world` using a pre-sampled `World2DSnapshot` with zero heap allocation for `<= 128` entities.
737    ///
738    /// # Arguments
739    ///
740    /// - `&Self` - Mutable render context.
741    /// - `&GameWorld` - Authoritative ECS world providing sprite appearance metadata.
742    /// - `&World2DSnapshot` - Pre-interpolated world snapshot.
743    ///
744    /// # Returns
745    ///
746    /// - `usize` - Number of visible interpolated entities drawn.
747    pub fn render_snapshot_world(
748        &mut self,
749        world: &GameWorld,
750        snapshot: &World2DSnapshot,
751    ) -> usize {
752        let camera: Camera2D = snapshot.get_camera();
753        let box_size: Size = self.viewport_size();
754        let vis: Rect = camera.visible_world_rect(box_size);
755        let (cam_x, cam_y, zoom, half_w, half_h): (f32, f32, f32, f32, f32) =
756            camera.projection_params(box_size);
757        let poses: &[EntityPose2D] = snapshot.get_entities().as_slice();
758        let records: &[EntityRecord] = world.get_entities().as_slice();
759        let mut stack_order: [(i32, usize); 128] = [(0, 0); 128];
760        let mut stack_len: usize = 0;
761        let mut heap_order: Vec<(i32, usize)> = Vec::new();
762        for (idx, pose) in poses.iter().enumerate() {
763            if !pose.get_alive() {
764                continue;
765            }
766            let Some(ent) = records.get(idx) else {
767                continue;
768            };
769            if ent.get_id() != pose.get_id() {
770                continue;
771            }
772            let Some(sp) = ent.sprite_component() else {
773                continue;
774            };
775            if !sp.get_visible() {
776                continue;
777            }
778            let transform_val: EntityTransform = pose.get_transform();
779            let pos: Point = transform_val.get_position();
780            let border_width: f32 =
781                sp.get_size().get_width() * transform_val.get_scale().get_width();
782            let bh: f32 = sp.get_size().get_height() * transform_val.get_scale().get_height();
783            let bounds: Rect = Rect::new(
784                pos.get_x() - border_width * 0.5,
785                pos.get_y() - bh * 0.5,
786                border_width,
787                bh,
788            );
789            if bounds.intersect(vis).is_none() {
790                continue;
791            }
792            let item: (i32, usize) = (sp.get_z_order(), idx);
793            if heap_order.is_empty() && stack_len < stack_order.len() {
794                stack_order[stack_len] = item;
795                stack_len += 1;
796            } else {
797                if heap_order.is_empty() {
798                    heap_order.reserve(poses.len());
799                    heap_order.extend_from_slice(&stack_order[..stack_len]);
800                }
801                heap_order.push(item);
802            }
803        }
804        let order_slice: &mut [(i32, usize)] = if heap_order.is_empty() {
805            &mut stack_order[..stack_len]
806        } else {
807            heap_order.as_mut_slice()
808        };
809        order_slice.sort_unstable_by(|alpha_val: &(i32, usize), blue_val: &(i32, usize)| {
810            alpha_val
811                .0
812                .cmp(&blue_val.0)
813                .then_with(|| alpha_val.1.cmp(&blue_val.1))
814        });
815        let rendered: usize = order_slice.len();
816        for &(_, idx) in order_slice.iter() {
817            let ent: &EntityRecord = &records[idx];
818            let Some(sp) = ent.sprite_component() else {
819                continue;
820            };
821            let object_transform: EntityTransform = poses[idx].get_transform();
822            let pos: Point = object_transform.get_position();
823            let center: Point = Point::new(
824                (pos.get_x() - cam_x) * zoom + half_w,
825                (pos.get_y() - cam_y) * zoom + half_h,
826            );
827            let width_val: f32 =
828                sp.get_size().get_width() * object_transform.get_scale().get_width() * zoom;
829            let height_val: f32 =
830                sp.get_size().get_height() * object_transform.get_scale().get_height() * zoom;
831            match sp.get_shape() {
832                EntityVisualShape::Rect => {
833                    let rect: Rect = Rect::new(
834                        center.get_x() - width_val * 0.5,
835                        center.get_y() - height_val * 0.5,
836                        width_val,
837                        height_val,
838                    );
839                    self.fill_rounded_rect(rect, sp.get_color(), sp.get_corner_radius() * zoom);
840                    if sp.get_accent().get_alpha() > 0 {
841                        self.stroke_rect(rect, 1.5, sp.get_accent());
842                    }
843                }
844                EntityVisualShape::Circle => {
845                    let red_val: f32 = (width_val.min(height_val) * 0.5).max(1.0);
846                    self.fill_circle(center, red_val, sp.get_color());
847                    if sp.get_accent().get_alpha() > 0 && red_val > 3.0 {
848                        self.fill_circle(center, red_val * 0.45, sp.get_accent());
849                    }
850                }
851                EntityVisualShape::Triangle => {
852                    let ang: f32 = object_transform.get_rotation_rad();
853                    let cos_a: f32 = ang.cos();
854                    let sin_a: f32 = ang.sin();
855                    let rx: f32 = width_val * 0.55;
856                    let ry: f32 = height_val * 0.48;
857                    let nose: Point =
858                        Point::new(center.get_x() + cos_a * rx, center.get_y() + sin_a * rx);
859                    let left: Point = Point::new(
860                        center.get_x() - cos_a * (rx * 0.72) - sin_a * ry,
861                        center.get_y() - sin_a * (rx * 0.72) + cos_a * ry,
862                    );
863                    let right: Point = Point::new(
864                        center.get_x() - cos_a * (rx * 0.72) + sin_a * ry,
865                        center.get_y() - sin_a * (rx * 0.72) - cos_a * ry,
866                    );
867                    self.fill_triangle(nose, left, right, sp.get_color());
868                    if sp.get_accent().get_alpha() > 0 {
869                        self.fill_circle(
870                            center,
871                            (width_val.min(height_val) * 0.16).max(2.0),
872                            sp.get_accent(),
873                        );
874                    }
875                }
876                EntityVisualShape::Diamond => {
877                    let hw: f32 = width_val * 0.5;
878                    let hh: f32 = height_val * 0.5;
879                    let top: Point = Point::new(center.get_x(), center.get_y() - hh);
880                    let right: Point = Point::new(center.get_x() + hw, center.get_y());
881                    let bottom: Point = Point::new(center.get_x(), center.get_y() + hh);
882                    let left: Point = Point::new(center.get_x() - hw, center.get_y());
883                    self.fill_triangle(top, right, bottom, sp.get_color());
884                    self.fill_triangle(top, bottom, left, sp.get_color());
885                    if sp.get_accent().get_alpha() > 0 {
886                        self.fill_circle(
887                            center,
888                            (width_val.min(height_val) * 0.18).max(2.0),
889                            sp.get_accent(),
890                        );
891                    }
892                }
893            }
894        }
895        rendered
896    }
897
898    /// Renders all visible 2D entities in `world` using discontinuity-safe render-time interpolation between `prev` and `curr` snapshots at `alpha`.
899    ///
900    /// # Arguments
901    ///
902    /// - `&Self` - Mutable render context.
903    /// - `&GameWorld` - Authoritative ECS world providing sprite appearance metadata.
904    /// - `&World2DSnapshot` - Previous fixed-step immutable snapshot.
905    /// - `&World2DSnapshot` - Current fixed-step immutable snapshot.
906    /// - `f32` - Normalized interpolation factor in `[0.0, 1.0]`.
907    ///
908    /// # Returns
909    ///
910    /// - `usize` - Number of visible interpolated entities drawn.
911    pub fn render_interpolated_world(
912        &mut self,
913        world: &GameWorld,
914        prev: &World2DSnapshot,
915        curr: &World2DSnapshot,
916        alpha: f32,
917    ) -> usize {
918        let interp: World2DSnapshot = prev.interpolate(curr, alpha);
919        self.render_snapshot_world(world, &interp)
920    }
921
922    /// Renders all active pooled particles in `particles` through `camera` with frustum culling and lifetime interpolation.
923    ///
924    /// # Arguments
925    ///
926    /// - `&Self` - Mutable render context.
927    /// - `&ParticleSystem` - Active particle system.
928    /// - `&Camera2D` - Active 2D world camera.
929    ///
930    /// # Returns
931    ///
932    /// - `usize` - Number of visible particles rendered.
933    pub fn render_particles(&mut self, particles: &ParticleSystem, camera: &Camera2D) -> usize {
934        let box_size: Size = self.viewport_size();
935        let vis: Rect = camera.visible_world_rect(box_size);
936        let (cam_x, cam_y, zoom, half_w, half_h): (f32, f32, f32, f32, f32) =
937            camera.projection_params(box_size);
938        let item_count: usize = particles.get_active_count();
939        let mut count: usize = 0;
940        for item_index in 0..item_count {
941            let pos: Point = Point::new(particles.pos_x[item_index], particles.pos_y[item_index]);
942            if !vis.contains(pos) {
943                continue;
944            }
945            let blend_factor: f32 = (particles.age[item_index]
946                / particles.lifetime[item_index].max(0.001))
947            .clamp(0.0, 1.0);
948            let s0: f32 = particles.start_size[item_index];
949            let s1: f32 = particles.end_size[item_index];
950            let red_val: f32 = ((s0 + (s1 - s0) * blend_factor) * zoom).max(0.8);
951            let col: Color = particles.start_color[item_index]
952                .lerp(particles.end_color[item_index], blend_factor);
953            if col.get_alpha() == 0 {
954                continue;
955            }
956            let screen: Point = Point::new(
957                (pos.get_x() - cam_x) * zoom + half_w,
958                (pos.get_y() - cam_y) * zoom + half_h,
959            );
960            self.fill_circle(screen, red_val, col);
961            count += 1;
962        }
963        count
964    }
965
966    /// Draws wireframe collider bounds for debugging physics shapes inside `world`.
967    ///
968    /// # Arguments
969    ///
970    /// - `&Self` - Mutable render context.
971    /// - `&GameWorld` - Active ECS world.
972    /// - `&Camera2D` - Active 2D world camera.
973    pub fn draw_debug_colliders(&mut self, world: &GameWorld, camera: &Camera2D) {
974        let box_size: Size = self.viewport_size();
975        let vis: Rect = camera.visible_world_rect(box_size);
976        let (cam_x, cam_y, zoom, half_w, half_h): (f32, f32, f32, f32, f32) =
977            camera.projection_params(box_size);
978        for ent in world.get_entities().iter() {
979            if !ent.get_alive() {
980                continue;
981            }
982            let Some(col) = ent.collider_component() else {
983                continue;
984            };
985            let bounds_rect: Rect = col.world_bounds(ent.get_transform().get_position());
986            if bounds_rect.intersect(vis).is_none() {
987                continue;
988            }
989            let tl_x: f32 = (bounds_rect.get_x() - cam_x) * zoom + half_w;
990            let tl_y: f32 = (bounds_rect.get_y() - cam_y) * zoom + half_h;
991            let color: Color = if col.get_is_trigger() {
992                Color::rgba(250, 204, 21, 180)
993            } else {
994                Color::rgba(34, 197, 94, 180)
995            };
996            self.stroke_rect(
997                Rect::new(
998                    tl_x,
999                    tl_y,
1000                    bounds_rect.get_width() * zoom,
1001                    bounds_rect.get_height() * zoom,
1002                ),
1003                1.0,
1004                color,
1005            );
1006        }
1007    }
1008}
1009
1010/// Host construction, fixed-step execution, and scene mounting for `GameEngineHost`.
1011impl GameEngineHost {
1012    /// Creates a new `GameEngineHost` wrapping `scene` with a `fixed_dt` simulation cadence.
1013    ///
1014    /// # Arguments
1015    ///
1016    /// - `TextValue` - User game scene implementing `GameScene`.
1017    /// - `f32` - Fixed physics timestep in seconds (e.g. `1.0 / 60.0`).
1018    ///
1019    /// # Returns
1020    ///
1021    /// - `Self` - Constructed engine host.
1022    #[must_use]
1023    pub fn new<TextValue>(scene: TextValue, fixed_dt: f32) -> Self
1024    where
1025        TextValue: GameScene + 'static,
1026    {
1027        Self {
1028            clock: Rc::new(RefCell::new(FrameClock::new(fixed_dt, 8))),
1029            input: Rc::new(RefCell::new(InputState::new())),
1030            scene: Rc::new(RefCell::new(scene)),
1031            viewport_nodes: Rc::new(RefCell::new(Vec::new())),
1032            last_gpu_composite: Rc::new(RefCell::new(None)),
1033            paused: Rc::new(Cell::new(false)),
1034        }
1035    }
1036
1037    /// Returns the most recent `GpuCompositeDescriptor` submitted by `GameScene::render` during `mount_viewport` painting, if any.
1038    ///
1039    /// # Arguments
1040    ///
1041    /// - `&Self` - Engine host reference.
1042    ///
1043    /// # Returns
1044    ///
1045    /// - `Option<GpuCompositeDescriptor>` - Bound same-device GPU composite descriptor.
1046    #[must_use]
1047    pub fn last_gpu_composite(&self) -> Option<GpuCompositeDescriptor> {
1048        self.get_last_gpu_composite()
1049            .try_borrow()
1050            .ok()
1051            .and_then(|green_val: Ref<'_, Option<GpuCompositeDescriptor>>| *green_val)
1052    }
1053
1054    /// Takes and clears the most recent `GpuCompositeDescriptor` submitted during `mount_viewport` painting.
1055    ///
1056    /// # Arguments
1057    ///
1058    /// - `&Self` - Engine host reference.
1059    ///
1060    /// # Returns
1061    ///
1062    /// - `Option<GpuCompositeDescriptor>` - Bound same-device GPU composite descriptor.
1063    #[must_use]
1064    pub fn take_last_gpu_composite(&self) -> Option<GpuCompositeDescriptor> {
1065        self.get_last_gpu_composite()
1066            .try_borrow_mut()
1067            .ok()
1068            .and_then(|mut green_val: RefMut<'_, Option<GpuCompositeDescriptor>>| green_val.take())
1069    }
1070
1071    /// Pauses or resumes simulation stepping for this game engine host (driven by `Lifecycle::on_freeze`/`on_resume`).
1072    ///
1073    /// # Arguments
1074    ///
1075    /// - `&Self` - Engine host reference.
1076    /// - `bool` - `true` to pause simulation; `false` to resume.
1077    pub fn set_paused(&self, paused: bool) {
1078        self.get_paused().set(paused);
1079    }
1080
1081    /// Returns `true` when this game engine host is currently paused.
1082    ///
1083    /// # Arguments
1084    ///
1085    /// - `&Self` - Engine host reference.
1086    ///
1087    /// # Returns
1088    ///
1089    /// - `bool` - Pause state.
1090    #[must_use]
1091    pub fn is_paused(&self) -> bool {
1092        self.get_paused().get()
1093    }
1094
1095    /// Returns screen-space bounds of all mounted, currently visible viewports backed by this host.
1096    ///
1097    /// # Arguments
1098    ///
1099    /// - `&Self` - Engine host reference.
1100    /// - `&SceneTree` - Active scene tree.
1101    ///
1102    /// # Returns
1103    ///
1104    /// - `Vec<Rect>` - Visible viewport rectangles (empty when paused or not on screen).
1105    #[must_use]
1106    pub fn active_viewport_bounds(&self, tree: &SceneTree) -> Vec<Rect> {
1107        let mut rects: Vec<Rect> = Vec::new();
1108        let _: bool = self.collect_active_viewport_bounds(tree, &mut rects);
1109        rects
1110    }
1111
1112    /// Appends screen-space bounds of all currently mounted, visible game viewports into `out` without heap allocation.
1113    ///
1114    /// # Arguments
1115    ///
1116    /// - `&Self` - Engine host reference.
1117    /// - `&SceneTree` - Active scene tree.
1118    /// - `&mut Vec<Rect>` - Reusable caller-owned output vector receiving visible viewport rectangles.
1119    ///
1120    /// # Returns
1121    ///
1122    /// - `bool` - `true` when at least one active visible viewport rectangle was appended.
1123    pub fn collect_active_viewport_bounds(&self, tree: &SceneTree, out: &mut Vec<Rect>) -> bool {
1124        if self.is_paused() {
1125            return false;
1126        }
1127        let start_len: usize = out.len();
1128        if let Ok(mut nodes) = self.get_viewport_nodes().try_borrow_mut() {
1129            nodes.retain(|(_, id): &(SceneHandle, NodeId)| tree.get_node(*id).is_some());
1130            for (_, id) in nodes.iter() {
1131                if tree.is_node_visible(*id)
1132                    && let Some(bounds) = tree.node_screen_bounds(*id)
1133                    && bounds.get_width() > 0.0
1134                    && bounds.get_height() > 0.0
1135                {
1136                    out.push(bounds);
1137                }
1138            }
1139        }
1140        out.len() > start_len
1141    }
1142
1143    /// Feeds a `WindowEvent` into the hosted game `InputState`.
1144    ///
1145    /// # Arguments
1146    ///
1147    /// - `&Self` - Engine host reference.
1148    /// - `&WindowEvent` - Event received from the OS window.
1149    pub fn ingest_event(&self, event: &WindowEvent) {
1150        if self.is_paused() {
1151            return;
1152        }
1153        if let Ok(mut input) = self.get_input().try_borrow_mut() {
1154            input.ingest(event);
1155        }
1156    }
1157
1158    /// Advances the hosted game scene by `dt_ns` nanoseconds using integer-nanosecond fixed-timestep accumulation.
1159    ///
1160    /// # Arguments
1161    ///
1162    /// - `&Self` - Engine host reference.
1163    /// - `u64` - Elapsed wall nanoseconds since the previous tick.
1164    ///
1165    /// # Returns
1166    ///
1167    /// - `u32` - Number of fixed physics steps executed.
1168    pub fn step_ns(&self, dt_ns: u64) -> u32 {
1169        if self.is_paused() {
1170            return 0;
1171        }
1172        let (steps, fixed_dt, dt_secs): (u32, f32, f32) = match self.get_clock().try_borrow_mut() {
1173            Ok(mut clock) => {
1174                let source_val: u32 = clock.tick_ns(dt_ns);
1175                (source_val, clock.get_fixed_dt(), clock.get_delta_secs())
1176            }
1177            Err(_) => (0, 1.0 / 60.0, ((dt_ns as f64) / 1_000_000_000.0) as f32),
1178        };
1179        self.dispatch_step_with_counts(steps, fixed_dt, dt_secs);
1180        self.mark_viewports_dirty();
1181        steps
1182    }
1183
1184    /// Advances the hosted game scene by `present_dt_ns` nanoseconds decoupled from presentation cadence, returning exact step counts and render interpolation `alpha`.
1185    ///
1186    /// # Arguments
1187    ///
1188    /// - `&Self` - Engine host reference.
1189    /// - `u64` - Elapsed presentation nanoseconds since the previous present tick.
1190    ///
1191    /// # Returns
1192    ///
1193    /// - `SimPresentFrame` - Per-present step count, interpolation `alpha`, and substep clamp telemetry.
1194    pub fn step_decoupled_ns(&self, present_dt_ns: u64) -> SimPresentFrame {
1195        if self.is_paused() {
1196            let alpha: f32 = self
1197                .get_clock()
1198                .try_borrow()
1199                .map(|char_item: Ref<'_, FrameClock>| char_item.get_alpha())
1200                .unwrap_or(0.0);
1201            let fixed_dt: f32 = self
1202                .get_clock()
1203                .try_borrow()
1204                .map(|color_item: Ref<'_, FrameClock>| color_item.get_fixed_dt())
1205                .unwrap_or(1.0 / 60.0);
1206            return SimPresentFrame::new(0, alpha, fixed_dt, 0.0, true, false);
1207        }
1208        let (steps, fixed_dt, dt_secs, alpha, hit_clamp): (u32, f32, f32, f32, bool) =
1209            match self.get_clock().try_borrow_mut() {
1210                Ok(mut clock) => {
1211                    let fixed_ns: u64 = clock.get_fixed_step_ns().max(CLOCK_MIN_FIXED_STEP_NS);
1212                    let max_sub: u32 = clock.get_max_substeps().max(1);
1213                    let pre_acc: u64 = clock.get_accumulator_ns();
1214                    let clamped_ns: u64 = present_dt_ns.min(CLOCK_MAX_FRAME_DT_NS);
1215                    let uncapped: u64 = pre_acc.saturating_add(clamped_ns) / fixed_ns;
1216                    let clamped: bool =
1217                        present_dt_ns > CLOCK_MAX_FRAME_DT_NS || uncapped > (max_sub as u64);
1218                    let source_val: u32 = clock.tick_ns(present_dt_ns);
1219                    (
1220                        source_val,
1221                        clock.get_fixed_dt(),
1222                        clock.get_delta_secs(),
1223                        clock.get_alpha(),
1224                        clamped,
1225                    )
1226                }
1227                Err(_) => (
1228                    0,
1229                    1.0 / 60.0,
1230                    ((present_dt_ns as f64) / CLOCK_NS_PER_SEC_F64) as f32,
1231                    0.0,
1232                    false,
1233                ),
1234            };
1235        self.dispatch_step_with_counts(steps, fixed_dt, dt_secs);
1236        self.mark_viewports_dirty();
1237        SimPresentFrame::new(steps, alpha, fixed_dt, dt_secs, steps == 0, hit_clamp)
1238    }
1239
1240    /// Advances the hosted game scene by `dt_secs` using fixed-timestep accumulation.
1241    ///
1242    /// # Arguments
1243    ///
1244    /// - `&Self` - Engine host reference.
1245    /// - `f32` - Elapsed wall seconds since the previous tick.
1246    ///
1247    /// # Returns
1248    ///
1249    /// - `u32` - Number of fixed physics steps executed.
1250    pub fn step(&self, dt_secs: f32) -> u32 {
1251        if self.is_paused() {
1252            return 0;
1253        }
1254        let (steps, fixed_dt): (u32, f32) = match self.get_clock().try_borrow_mut() {
1255            Ok(mut clock) => (clock.tick(dt_secs), clock.get_fixed_dt()),
1256            Err(_) => (0, 1.0 / 60.0),
1257        };
1258        self.dispatch_step_with_counts(steps, fixed_dt, dt_secs);
1259        self.mark_viewports_dirty();
1260        steps
1261    }
1262
1263    /// Executes `steps` fixed updates and one variable update while skipping edge clearing when `steps == 0`.
1264    ///
1265    /// # Arguments
1266    ///
1267    /// - `&Self` - Engine host reference.
1268    /// - `u32` - Number of fixed steps to execute.
1269    /// - `f32` - Fixed timestep duration in seconds.
1270    /// - `f32` - Variable frame delta in seconds.
1271    fn dispatch_step_with_counts(&self, steps: u32, fixed_dt: f32, dt_secs: f32) {
1272        let Self { scene, .. } = self;
1273        if let Ok(mut game) = scene.try_borrow_mut() {
1274            let input_copy: InputState = self
1275                .get_input()
1276                .try_borrow()
1277                .map(|red_val: Ref<'_, InputState>| *red_val)
1278                .unwrap_or_default();
1279            if steps == 0 {
1280                game.update(dt_secs, &input_copy);
1281            } else {
1282                game.fixed_update(fixed_dt, &input_copy);
1283                if let Ok(mut input_mut) = self.get_input().try_borrow_mut() {
1284                    input_mut.begin_frame();
1285                }
1286                let cleared: InputState = input_copy.without_edges();
1287                for _ in 1..steps {
1288                    game.fixed_update(fixed_dt, &cleared);
1289                }
1290                game.update(dt_secs, &cleared);
1291            }
1292        } else if steps > 0
1293            && let Ok(mut input) = self.get_input().try_borrow_mut()
1294        {
1295            input.begin_frame();
1296        }
1297    }
1298
1299    /// Marks all mounted live visible game viewport nodes paint-dirty and prunes disposed `NodeId`s automatically.
1300    ///
1301    /// # Arguments
1302    ///
1303    /// - `&Self` - Engine host reference.
1304    pub fn mark_viewports_dirty(&self) {
1305        if let Ok(mut nodes) = self.get_viewport_nodes().try_borrow_mut() {
1306            nodes.retain(|(scene_handle, node_id): &(SceneHandle, NodeId)| {
1307                let (alive, visible): (bool, bool) = scene_handle.with_read(
1308                    |tree: &SceneTree| -> (bool, bool) {
1309                        let exists: bool = tree.get_node(*node_id).is_some();
1310                        let vis: bool = exists
1311                            && tree.is_node_visible(*node_id)
1312                            && tree.node_screen_bounds(*node_id).is_some_and(
1313                                |rect_bounds: Rect| {
1314                                    rect_bounds.get_width() > 0.0 && rect_bounds.get_height() > 0.0
1315                                },
1316                            );
1317                        (exists, vis)
1318                    },
1319                    (false, false),
1320                );
1321                if visible {
1322                    scene_handle.mark_dirty(*node_id, DIRTY_PAINT);
1323                }
1324                alive
1325            });
1326        }
1327    }
1328
1329    /// Executes a `PacingDecision` from `FramePacingController`, advancing simulation strictly on VSync decisions using integer nanoseconds and never on deferred non-VSync triggers.
1330    ///
1331    /// # Arguments
1332    ///
1333    /// - `&Self` - Engine host reference.
1334    /// - `&PacingDecision` - Authoritative pacing decision for the current trigger.
1335    ///
1336    /// # Returns
1337    ///
1338    /// - `u32` - Number of fixed simulation steps executed (`0` when deferred, capped, or lifecycle-first-frame).
1339    pub fn step_paced(&self, decision: &PacingDecision) -> u32 {
1340        match decision.get_action() {
1341            PacingAction::StepAndRender => self.step_ns(decision.get_sim_dt_ns()),
1342            PacingAction::RenderWithoutSimAdvance => {
1343                self.mark_viewports_dirty();
1344                0
1345            }
1346            PacingAction::DeferToNextVsync
1347            | PacingAction::WaitInFlight
1348            | PacingAction::SkipUserCap => 0,
1349        }
1350    }
1351
1352    /// Sets the virtual analog joystick vector `(dx, dy)` in `[-1.0, 1.0]` for mobile/tablet/gamepad play.
1353    ///
1354    /// # Arguments
1355    ///
1356    /// - `&Self` - Engine host reference.
1357    /// - `f32` - Horizontal axis.
1358    /// - `f32` - Vertical axis.
1359    pub fn set_virtual_stick(&self, dx: f32, dy: f32) {
1360        if let Ok(mut input) = self.get_input().try_borrow_mut() {
1361            input.set_virtual_stick(dx, dy);
1362        }
1363    }
1364
1365    /// Presses a virtual game key (ideal for holdable mobile touch D-pad buttons).
1366    ///
1367    /// # Arguments
1368    ///
1369    /// - `&Self` - Engine host reference.
1370    /// - `KeyCode` - Virtual key code to hold down.
1371    pub fn press_key(&self, code: KeyCode) {
1372        self.ingest_event(&WindowEvent::KeyDown(
1373            WindowId::new(1),
1374            KeyEvent::new(code, Modifiers::default(), false),
1375        ));
1376    }
1377
1378    /// Releases a previously pressed virtual game key.
1379    ///
1380    /// # Arguments
1381    ///
1382    /// - `&Self` - Engine host reference.
1383    /// - `KeyCode` - Virtual key code to release.
1384    pub fn release_key(&self, code: KeyCode) {
1385        self.ingest_event(&WindowEvent::KeyUp(
1386            WindowId::new(1),
1387            KeyEvent::new(code, Modifiers::default(), false),
1388        ));
1389    }
1390
1391    /// Mounts a live `Canvas` viewport into the active ambient `Context` backed by this `GameScene`.
1392    ///
1393    /// Supports multi-platform interaction automatically: keyboard/mouse on Desktop & Web plus
1394    /// direct drag-to-steer virtual analog joystick on touch/mobile/tablet screens.
1395    ///
1396    /// # Arguments
1397    ///
1398    /// - `&Self` - Engine host reference.
1399    /// - `Style` - Layout and visual style of the game viewport.
1400    ///
1401    /// # Returns
1402    ///
1403    /// - `NodeId` - Mounted game viewport scene node.
1404    #[must_use]
1405    pub fn mount_viewport(&self, style: Style) -> NodeId {
1406        let Self {
1407            clock,
1408            scene,
1409            last_gpu_composite,
1410            ..
1411        } = self;
1412        let clock_c: Rc<RefCell<FrameClock>> = clock.clone();
1413        let scene_c: Rc<RefCell<dyn GameScene>> = scene.clone();
1414        let gpu_out_c: Rc<RefCell<Option<GpuCompositeDescriptor>>> = last_gpu_composite.clone();
1415        let mut ctx: Context = current_context();
1416        let node: NodeId = ctx.canvas(
1417            style,
1418            move |bounds: Rect, display_list: &mut DisplayList| {
1419                let alpha: f32 = clock_c
1420                    .try_borrow()
1421                    .map(|char_item: Ref<'_, FrameClock>| char_item.get_alpha())
1422                    .unwrap_or(1.0);
1423                if let Ok(mut game) = scene_c.try_borrow_mut() {
1424                    let mut render_ctx: GameRenderContext<'_> =
1425                        GameRenderContext::new(bounds, display_list);
1426                    game.render(alpha, &mut render_ctx);
1427                    let gpu_target: Option<GpuCompositeDescriptor> =
1428                        render_ctx.take_gpu_composite_target();
1429                    if let Ok(mut slot) = gpu_out_c.try_borrow_mut() {
1430                        *slot = gpu_target;
1431                    }
1432                }
1433            },
1434        );
1435        if let Ok(mut nodes) = self.get_viewport_nodes().try_borrow_mut() {
1436            nodes.retain(|(sh, nid): &(SceneHandle, NodeId)| {
1437                sh.with_read(|tree: &SceneTree| tree.get_node(*nid).is_some(), false)
1438            });
1439            nodes.push((ctx.get_scene().clone(), node));
1440        }
1441        let drag_origin: Rc<RefCell<Option<Point>>> = Rc::new(RefCell::new(None));
1442        let origin_down: Rc<RefCell<Option<Point>>> = drag_origin.clone();
1443        let origin_move: Rc<RefCell<Option<Point>>> = drag_origin.clone();
1444        let origin_up: Rc<RefCell<Option<Point>>> = drag_origin;
1445        let host_move: Self = self.clone();
1446        let host_up: Self = self.clone();
1447        ctx.on_pointer_down(node, move |ui_event: &UiEvent| {
1448            if let UiEventKind::PointerDown(sample_point) = ui_event.get_kind()
1449                && let Ok(mut guard) = origin_down.try_borrow_mut()
1450            {
1451                *guard = Some(*sample_point);
1452            }
1453        });
1454        ctx.on_pointer_move(node, move |interaction_event: &UiEvent| {
1455            if let UiEventKind::PointerMove(target_point) = interaction_event.get_kind()
1456                && let Ok(guard) = origin_move.try_borrow()
1457                && let Some(orig) = *guard
1458            {
1459                let dx: f32 = ((target_point.get_x() - orig.get_x()) / 48.0).clamp(-1.0, 1.0);
1460                let dy: f32 = ((target_point.get_y() - orig.get_y()) / 48.0).clamp(-1.0, 1.0);
1461                host_move.set_virtual_stick(dx, dy);
1462            }
1463        });
1464        ctx.on_pointer_up(node, move |_: &UiEvent| {
1465            if let Ok(mut guard) = origin_up.try_borrow_mut() {
1466                *guard = None;
1467            }
1468            host_up.set_virtual_stick(0.0, 0.0);
1469        });
1470        node
1471    }
1472}