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