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        }
20    }
21
22    /// Returns the logical width and height of the game viewport.
23    ///
24    /// # Arguments
25    ///
26    /// - `&Self` - Render context reference.
27    ///
28    /// # Returns
29    ///
30    /// - `Size` - Viewport size in logical pixels.
31    #[must_use]
32    pub fn viewport_size(&self) -> Size {
33        let Self { bounds, .. } = self;
34        Size::new(bounds.get_width(), bounds.get_height())
35    }
36
37    /// Fills the entire game viewport with `color`.
38    ///
39    /// # Arguments
40    ///
41    /// - `&Self` - Mutable render context.
42    /// - `Color` - Background clear color.
43    pub fn clear(&mut self, color: Color) {
44        let Self {
45            bounds,
46            display_list,
47        } = self;
48        display_list.push(DrawCommand::FillRoundedRect {
49            rect: *bounds,
50            color,
51            radius: CornerRadius::default(),
52            border: Border::default(),
53        });
54    }
55
56    /// Draws an axis-aligned solid rectangle in viewport-local coordinates.
57    ///
58    /// # Arguments
59    ///
60    /// - `&Self` - Mutable render context.
61    /// - `Rect` - Local rectangle bounds.
62    /// - `Color` - Fill color.
63    pub fn fill_rect(&mut self, rect: Rect, color: Color) {
64        self.fill_rounded_rect(rect, color, 0.0);
65    }
66
67    /// Draws a rounded solid rectangle in viewport-local coordinates.
68    ///
69    /// # Arguments
70    ///
71    /// - `&Self` - Mutable render context.
72    /// - `Rect` - Local rectangle bounds.
73    /// - `Color` - Fill color.
74    /// - `f32` - Corner radius in logical pixels.
75    pub fn fill_rounded_rect(&mut self, rect: Rect, color: Color, radius: f32) {
76        let Self {
77            bounds,
78            display_list,
79        } = self;
80        let world: Rect = Rect::new(
81            bounds.get_x() + rect.get_x(),
82            bounds.get_y() + rect.get_y(),
83            rect.get_width(),
84            rect.get_height(),
85        );
86        display_list.push(DrawCommand::FillRoundedRect {
87            rect: world,
88            color,
89            radius: CornerRadius::all(radius),
90            border: Border::default(),
91        });
92    }
93
94    /// Draws an outlined rectangle in viewport-local coordinates.
95    ///
96    /// # Arguments
97    ///
98    /// - `&Self` - Mutable render context.
99    /// - `Rect` - Local rectangle bounds.
100    /// - `f32` - Stroke thickness in logical pixels.
101    /// - `Color` - Stroke color.
102    pub fn stroke_rect(&mut self, rect: Rect, stroke_width: f32, color: Color) {
103        let Self {
104            bounds,
105            display_list,
106        } = self;
107        let world: Rect = Rect::new(
108            bounds.get_x() + rect.get_x(),
109            bounds.get_y() + rect.get_y(),
110            rect.get_width(),
111            rect.get_height(),
112        );
113        display_list.push(DrawCommand::FillRoundedRect {
114            rect: world,
115            color: COLOR_TRANSPARENT,
116            radius: CornerRadius::default(),
117            border: Border::new(stroke_width, color),
118        });
119    }
120
121    /// Draws a filled circle in viewport-local coordinates.
122    ///
123    /// # Arguments
124    ///
125    /// - `&Self` - Mutable render context.
126    /// - `Point` - Circle center in viewport-local coordinates.
127    /// - `f32` - Circle radius in logical pixels.
128    /// - `Color` - Fill color.
129    pub fn fill_circle(&mut self, center: Point, radius: f32, color: Color) {
130        let Self {
131            bounds,
132            display_list,
133        } = self;
134        let world: Point = Point::new(
135            bounds.get_x() + center.get_x(),
136            bounds.get_y() + center.get_y(),
137        );
138        display_list.push(DrawCommand::Circle {
139            center: world,
140            radius,
141            color,
142        });
143    }
144
145    /// Draws an RGBA8 `ImageBuffer` stretched into `rect` inside this game viewport (ideal for 3D render targets).
146    ///
147    /// # Arguments
148    ///
149    /// - `&Self` - Mutable render context.
150    /// - `Rect` - Local destination rectangle inside the viewport.
151    /// - `ImageBuffer` - Source RGBA8 pixel buffer.
152    pub fn draw_image(&mut self, rect: Rect, buffer: ImageBuffer) {
153        let Self {
154            bounds,
155            display_list,
156        } = self;
157        let world: Rect = Rect::new(
158            bounds.get_x() + rect.get_x(),
159            bounds.get_y() + rect.get_y(),
160            rect.get_width(),
161            rect.get_height(),
162        );
163        display_list.push(DrawCommand::Image {
164            rect: world,
165            buffer,
166            radius: CornerRadius::default(),
167        });
168    }
169
170    /// Draws an anti-aliased line segment in viewport-local coordinates.
171    ///
172    /// # Arguments
173    ///
174    /// - `&Self` - Mutable render context.
175    /// - `Point` - Segment start point.
176    /// - `Point` - Segment end point.
177    /// - `f32` - Line width in logical pixels.
178    /// - `Color` - Line color.
179    pub fn draw_line(&mut self, from: Point, to: Point, width: f32, color: Color) {
180        let Self {
181            bounds,
182            display_list,
183        } = self;
184        display_list.push(DrawCommand::Line {
185            from: Point::new(bounds.get_x() + from.get_x(), bounds.get_y() + from.get_y()),
186            to: Point::new(bounds.get_x() + to.get_x(), bounds.get_y() + to.get_y()),
187            color,
188            width,
189        });
190    }
191
192    /// Draws HUD or debug text inside the game viewport.
193    ///
194    /// # Arguments
195    ///
196    /// - `&Self` - Mutable render context.
197    /// - `Point` - Top-left local position.
198    /// - `String` - Text string.
199    /// - `f32` - Font size in logical pixels.
200    /// - `Color` - Text color.
201    pub fn draw_text(&mut self, position: Point, text: String, font_size: f32, color: Color) {
202        let Self {
203            bounds,
204            display_list,
205        } = self;
206        let mut style: TextStyle = TextStyle::default();
207        style.set_font_size(font_size);
208        style.set_color(color);
209        display_list.push(DrawCommand::TextRun {
210            rect: Rect::new(
211                bounds.get_x() + position.get_x(),
212                bounds.get_y() + position.get_y(),
213                (bounds.get_width() - position.get_x()).max(0.0),
214                font_size * 1.6,
215            ),
216            text,
217            style,
218        });
219    }
220
221    /// Blits an external 2D/3D engine RGBA8 `ImageBuffer` directly into the viewport.
222    ///
223    /// # Arguments
224    ///
225    /// - `&Self` - Mutable render context.
226    /// - `Rect` - Local destination rectangle.
227    /// - `ImageBuffer` - External engine rendered frame or sprite sheet.
228    pub fn blit_framebuffer(&mut self, rect: Rect, buffer: ImageBuffer) {
229        let Self {
230            bounds,
231            display_list,
232        } = self;
233        let world: Rect = Rect::new(
234            bounds.get_x() + rect.get_x(),
235            bounds.get_y() + rect.get_y(),
236            rect.get_width(),
237            rect.get_height(),
238        );
239        display_list.push(DrawCommand::Image {
240            rect: world,
241            buffer,
242            radius: CornerRadius::default(),
243        });
244    }
245
246    /// Draws a filled triangle in viewport-local coordinates.
247    ///
248    /// # Arguments
249    ///
250    /// - `&Self` - Mutable render context.
251    /// - `Point` - First vertex.
252    /// - `Point` - Second vertex.
253    /// - `Point` - Third vertex.
254    /// - `Color` - Fill color.
255    pub fn fill_triangle(&mut self, p0: Point, p1: Point, p2: Point, color: Color) {
256        let Self {
257            bounds,
258            display_list,
259        } = self;
260        let ox: f32 = bounds.get_x();
261        let oy: f32 = bounds.get_y();
262        display_list.push(DrawCommand::Triangle {
263            p0: Point::new(ox + p0.get_x(), oy + p0.get_y()),
264            p1: Point::new(ox + p1.get_x(), oy + p1.get_y()),
265            p2: Point::new(ox + p2.get_x(), oy + p2.get_y()),
266            color,
267        });
268    }
269
270    /// Draws a cropped frame from a `SpriteSheet` into `rect` with multiplicative `tint`.
271    ///
272    /// # Arguments
273    ///
274    /// - `&Self` - Mutable render context.
275    /// - `&SpriteSheet` - Source sprite sheet.
276    /// - `u32` - Zero-based animation frame index.
277    /// - `Rect` - Destination viewport-local rectangle.
278    /// - `Color` - Multiplicative tint color.
279    pub fn draw_sprite_frame(
280        &mut self,
281        sheet: &SpriteSheet,
282        frame_index: u32,
283        rect: Rect,
284        tint: Color,
285    ) {
286        let src_rect: Rect = sheet.frame_rect(frame_index);
287        let Self {
288            bounds,
289            display_list,
290        } = self;
291        display_list.push(DrawCommand::SpriteRegion {
292            rect: Rect::new(
293                bounds.get_x() + rect.get_x(),
294                bounds.get_y() + rect.get_y(),
295                rect.get_width(),
296                rect.get_height(),
297            ),
298            buffer: sheet.get_texture().clone(),
299            src_rect,
300            tint,
301        });
302    }
303
304    /// Renders all visible tiles of `tilemap` through `camera` using O(visible) frustum culling.
305    ///
306    /// # Arguments
307    ///
308    /// - `&Self` - Mutable render context.
309    /// - `&TileMap` - Grid tilemap to draw.
310    /// - `&Camera2D` - Active 2D world camera.
311    pub fn render_tilemap(&mut self, tilemap: &TileMap, camera: &Camera2D) {
312        let vp: Size = self.viewport_size();
313        let vis: Rect = camera.visible_world_rect(vp);
314        let ts: f32 = tilemap.get_tile_size();
315        let zoom: f32 = camera.get_zoom().max(0.25);
316        let min_c: usize = (vis.get_x() / ts).floor().max(0.0) as usize;
317        let max_c: usize = ((vis.right() / ts).ceil().max(0.0) as usize).min(tilemap.get_columns());
318        let min_r: usize = (vis.get_y() / ts).floor().max(0.0) as usize;
319        let max_r: usize = ((vis.bottom() / ts).ceil().max(0.0) as usize).min(tilemap.get_rows());
320        let tile_px: f32 = (ts * zoom).max(1.0);
321        for row in min_r..max_r {
322            for col in min_c..max_c {
323                let tid: u16 = tilemap.tile_at(col, row);
324                if tid == 0 {
325                    continue;
326                }
327                let Some(entry) = tilemap.get_palette().get(tid as usize) else {
328                    continue;
329                };
330                let world_pt: Point = Point::new((col as f32) * ts, (row as f32) * ts);
331                let screen_pt: Point = camera.world_to_screen(world_pt, vp);
332                let tile_rect: Rect = Rect::new(
333                    screen_pt.get_x(),
334                    screen_pt.get_y(),
335                    tile_px + 0.5,
336                    tile_px + 0.5,
337                );
338                self.fill_rect(tile_rect, entry.get_color());
339            }
340        }
341    }
342
343    /// Renders all visible sprite entities in `world` through `camera`, sorted by `z_order` with frustum culling.
344    ///
345    /// # Arguments
346    ///
347    /// - `&Self` - Mutable render context.
348    /// - `&GameWorld` - Active ECS world.
349    /// - `&Camera2D` - Active 2D world camera.
350    ///
351    /// # Returns
352    ///
353    /// - `usize` - Number of visible entities drawn after frustum culling.
354    pub fn render_world(&mut self, world: &GameWorld, camera: &Camera2D) -> usize {
355        let vp: Size = self.viewport_size();
356        let vis: Rect = camera.visible_world_rect(vp);
357        let zoom: f32 = camera.get_zoom().max(0.25);
358        let mut draw_order: Vec<(i32, usize)> = Vec::with_capacity(world.get_live_count());
359        for (idx, ent) in world.get_entities().iter().enumerate() {
360            if !ent.get_alive() {
361                continue;
362            }
363            let Some(sp) = ent.sprite_component() else {
364                continue;
365            };
366            if !sp.get_visible() {
367                continue;
368            }
369            if ent.world_bounds().intersect(vis).is_none() {
370                continue;
371            }
372            draw_order.push((sp.get_z_order(), idx));
373        }
374        draw_order.sort_by(|a: &(i32, usize), b: &(i32, usize)| {
375            a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1))
376        });
377        let rendered: usize = draw_order.len();
378        for (_, idx) in draw_order.into_iter() {
379            let ent: &EntityRecord = &world.get_entities()[idx];
380            let Some(sp) = ent.sprite_component() else {
381                continue;
382            };
383            let tr: EntityTransform = ent.get_transform();
384            let center: Point = camera.world_to_screen(tr.get_position(), vp);
385            let w: f32 = sp.get_size().get_width() * tr.get_scale().get_width() * zoom;
386            let h: f32 = sp.get_size().get_height() * tr.get_scale().get_height() * zoom;
387            match sp.get_shape() {
388                EntityVisualShape::Rect => {
389                    let rect: Rect =
390                        Rect::new(center.get_x() - w * 0.5, center.get_y() - h * 0.5, w, h);
391                    self.fill_rounded_rect(rect, sp.get_color(), sp.get_corner_radius() * zoom);
392                    if sp.get_accent().get_a() > 0 {
393                        self.stroke_rect(rect, 1.5, sp.get_accent());
394                    }
395                }
396                EntityVisualShape::Circle => {
397                    let r: f32 = (w.min(h) * 0.5).max(1.0);
398                    self.fill_circle(center, r, sp.get_color());
399                    if sp.get_accent().get_a() > 0 && r > 3.0 {
400                        self.fill_circle(center, r * 0.45, sp.get_accent());
401                    }
402                }
403                EntityVisualShape::Triangle => {
404                    let ang: f32 = tr.get_rotation_rad();
405                    let cos_a: f32 = ang.cos();
406                    let sin_a: f32 = ang.sin();
407                    let rx: f32 = w * 0.55;
408                    let ry: f32 = h * 0.48;
409                    let nose: Point =
410                        Point::new(center.get_x() + cos_a * rx, center.get_y() + sin_a * rx);
411                    let left: Point = Point::new(
412                        center.get_x() - cos_a * (rx * 0.72) - sin_a * ry,
413                        center.get_y() - sin_a * (rx * 0.72) + cos_a * ry,
414                    );
415                    let right: Point = Point::new(
416                        center.get_x() - cos_a * (rx * 0.72) + sin_a * ry,
417                        center.get_y() - sin_a * (rx * 0.72) - cos_a * ry,
418                    );
419                    self.fill_triangle(nose, left, right, sp.get_color());
420                    if sp.get_accent().get_a() > 0 {
421                        self.fill_circle(center, (w.min(h) * 0.16).max(2.0), sp.get_accent());
422                    }
423                }
424                EntityVisualShape::Diamond => {
425                    let hw: f32 = w * 0.5;
426                    let hh: f32 = h * 0.5;
427                    let top: Point = Point::new(center.get_x(), center.get_y() - hh);
428                    let right: Point = Point::new(center.get_x() + hw, center.get_y());
429                    let bottom: Point = Point::new(center.get_x(), center.get_y() + hh);
430                    let left: Point = Point::new(center.get_x() - hw, center.get_y());
431                    self.fill_triangle(top, right, bottom, sp.get_color());
432                    self.fill_triangle(top, bottom, left, sp.get_color());
433                    if sp.get_accent().get_a() > 0 {
434                        self.fill_circle(center, (w.min(h) * 0.18).max(2.0), sp.get_accent());
435                    }
436                }
437            }
438        }
439        rendered
440    }
441
442    /// Renders all active pooled particles in `particles` through `camera` with frustum culling and lifetime interpolation.
443    ///
444    /// # Arguments
445    ///
446    /// - `&Self` - Mutable render context.
447    /// - `&ParticleSystem` - Active particle system.
448    /// - `&Camera2D` - Active 2D world camera.
449    ///
450    /// # Returns
451    ///
452    /// - `usize` - Number of visible particles rendered.
453    pub fn render_particles(&mut self, particles: &ParticleSystem, camera: &Camera2D) -> usize {
454        let vp: Size = self.viewport_size();
455        let vis: Rect = camera.visible_world_rect(vp);
456        let zoom: f32 = camera.get_zoom().max(0.25);
457        let n: usize = particles.get_active_count();
458        let mut count: usize = 0;
459        for i in 0..n {
460            let pos: Point = Point::new(particles.pos_x[i], particles.pos_y[i]);
461            if !vis.contains(pos) {
462                continue;
463            }
464            let t: f32 = (particles.age[i] / particles.lifetime[i].max(0.001)).clamp(0.0, 1.0);
465            let s0: f32 = particles.start_size[i];
466            let s1: f32 = particles.end_size[i];
467            let r: f32 = ((s0 + (s1 - s0) * t) * zoom).max(0.8);
468            let col: Color = particles.start_color[i].lerp(particles.end_color[i], t);
469            if col.get_a() == 0 {
470                continue;
471            }
472            let screen: Point = camera.world_to_screen(pos, vp);
473            self.fill_circle(screen, r, col);
474            count += 1;
475        }
476        count
477    }
478
479    /// Draws wireframe collider bounds for debugging physics shapes inside `world`.
480    ///
481    /// # Arguments
482    ///
483    /// - `&Self` - Mutable render context.
484    /// - `&GameWorld` - Active ECS world.
485    /// - `&Camera2D` - Active 2D world camera.
486    pub fn draw_debug_colliders(&mut self, world: &GameWorld, camera: &Camera2D) {
487        let vp: Size = self.viewport_size();
488        let vis: Rect = camera.visible_world_rect(vp);
489        let zoom: f32 = camera.get_zoom().max(0.25);
490        for ent in world.get_entities().iter() {
491            if !ent.get_alive() {
492                continue;
493            }
494            let Some(col) = ent.collider_component() else {
495                continue;
496            };
497            let aabb: Rect = col.world_aabb(ent.get_transform().get_position());
498            if aabb.intersect(vis).is_none() {
499                continue;
500            }
501            let tl: Point = camera.world_to_screen(Point::new(aabb.get_x(), aabb.get_y()), vp);
502            let color: Color = if col.get_is_trigger() {
503                Color::rgba(250, 204, 21, 180)
504            } else {
505                Color::rgba(34, 197, 94, 180)
506            };
507            self.stroke_rect(
508                Rect::new(
509                    tl.get_x(),
510                    tl.get_y(),
511                    aabb.get_width() * zoom,
512                    aabb.get_height() * zoom,
513                ),
514                1.0,
515                color,
516            );
517        }
518    }
519}
520
521/// Host construction, fixed-step execution, and scene mounting for `GameEngineHost`.
522impl GameEngineHost {
523    /// Creates a new `GameEngineHost` wrapping `scene` with a `fixed_dt` simulation cadence.
524    ///
525    /// # Arguments
526    ///
527    /// - `S` - User game scene implementing `GameScene`.
528    /// - `f32` - Fixed physics timestep in seconds (e.g. `1.0 / 60.0`).
529    ///
530    /// # Returns
531    ///
532    /// - `Self` - Constructed engine host.
533    #[must_use]
534    pub fn new<S>(scene: S, fixed_dt: f32) -> Self
535    where
536        S: GameScene + 'static,
537    {
538        Self {
539            clock: Rc::new(RefCell::new(FrameClock::new(fixed_dt, 8))),
540            input: Rc::new(RefCell::new(InputState::new())),
541            scene: Rc::new(RefCell::new(scene)),
542            viewport_nodes: Rc::new(RefCell::new(Vec::new())),
543            paused: Rc::new(Cell::new(false)),
544        }
545    }
546
547    /// Pauses or resumes simulation stepping for this game engine host (driven by `Lifecycle::on_freeze`/`on_resume`).
548    ///
549    /// # Arguments
550    ///
551    /// - `&Self` - Engine host reference.
552    /// - `bool` - `true` to pause simulation; `false` to resume.
553    pub fn set_paused(&self, paused: bool) {
554        self.get_paused().set(paused);
555    }
556
557    /// Returns `true` when this game engine host is currently paused.
558    ///
559    /// # Arguments
560    ///
561    /// - `&Self` - Engine host reference.
562    ///
563    /// # Returns
564    ///
565    /// - `bool` - Pause state.
566    #[must_use]
567    pub fn is_paused(&self) -> bool {
568        self.get_paused().get()
569    }
570
571    /// Returns screen-space bounds of all mounted, currently visible viewports backed by this host.
572    ///
573    /// # Arguments
574    ///
575    /// - `&Self` - Engine host reference.
576    /// - `&SceneTree` - Active scene tree.
577    ///
578    /// # Returns
579    ///
580    /// - `Vec<Rect>` - Visible viewport rectangles (empty when paused or not on screen).
581    #[must_use]
582    pub fn active_viewport_bounds(&self, tree: &SceneTree) -> Vec<Rect> {
583        if self.is_paused() {
584            return Vec::new();
585        }
586        let mut rects: Vec<Rect> = Vec::new();
587        if let Ok(mut nodes) = self.get_viewport_nodes().try_borrow_mut() {
588            nodes.retain(|(_, id): &(SceneHandle, NodeId)| tree.get_node(*id).is_some());
589            for (_, id) in nodes.iter() {
590                if tree.is_node_visible(*id)
591                    && let Some(bounds) = tree.node_screen_bounds(*id)
592                    && bounds.get_width() > 0.0
593                    && bounds.get_height() > 0.0
594                {
595                    rects.push(bounds);
596                }
597            }
598        }
599        rects
600    }
601
602    /// Feeds a `WindowEvent` into the hosted game `InputState`.
603    ///
604    /// # Arguments
605    ///
606    /// - `&Self` - Engine host reference.
607    /// - `&WindowEvent` - Event received from the OS window.
608    pub fn ingest_event(&self, event: &WindowEvent) {
609        if let Ok(mut input) = self.get_input().try_borrow_mut() {
610            input.ingest(event);
611        }
612    }
613
614    /// Advances the hosted game scene by `dt_secs` using fixed-timestep accumulation.
615    ///
616    /// # Arguments
617    ///
618    /// - `&Self` - Engine host reference.
619    /// - `f32` - Elapsed wall seconds since the previous tick.
620    ///
621    /// # Returns
622    ///
623    /// - `u32` - Number of fixed physics steps executed.
624    pub fn step(&self, dt_secs: f32) -> u32 {
625        if self.is_paused() {
626            return 0;
627        }
628        let (steps, fixed_dt): (u32, f32) = match self.get_clock().try_borrow_mut() {
629            Ok(mut clock) => (clock.tick(dt_secs), clock.get_fixed_dt()),
630            Err(_) => (0, 1.0 / 60.0),
631        };
632        let input_snapshot: InputState = self
633            .get_input()
634            .try_borrow()
635            .map(|guard: Ref<'_, InputState>| guard.clone())
636            .unwrap_or_default();
637        let Self { scene, .. } = self;
638        if let Ok(mut game) = scene.try_borrow_mut() {
639            for _ in 0..steps {
640                game.fixed_update(fixed_dt, &input_snapshot);
641            }
642            game.update(dt_secs, &input_snapshot);
643        }
644        if let Ok(mut input) = self.get_input().try_borrow_mut() {
645            input.begin_frame();
646        }
647        if let Ok(nodes) = self.get_viewport_nodes().try_borrow() {
648            for (scene_handle, node_id) in nodes.iter() {
649                scene_handle.mark_dirty(*node_id, DIRTY_PAINT);
650            }
651        }
652        steps
653    }
654
655    /// Sets the virtual analog joystick vector `(dx, dy)` in `[-1.0, 1.0]` for mobile/tablet/gamepad play.
656    ///
657    /// # Arguments
658    ///
659    /// - `&Self` - Engine host reference.
660    /// - `f32` - Horizontal axis.
661    /// - `f32` - Vertical axis.
662    pub fn set_virtual_stick(&self, dx: f32, dy: f32) {
663        if let Ok(mut input) = self.get_input().try_borrow_mut() {
664            input.set_virtual_stick(dx, dy);
665        }
666    }
667
668    /// Presses a virtual game key (ideal for holdable mobile touch D-pad buttons).
669    ///
670    /// # Arguments
671    ///
672    /// - `&Self` - Engine host reference.
673    /// - `KeyCode` - Virtual key code to hold down.
674    pub fn press_key(&self, code: KeyCode) {
675        self.ingest_event(&WindowEvent::KeyDown(
676            WindowId::new(1),
677            KeyEvent::new(code, Modifiers::default(), false),
678        ));
679    }
680
681    /// Releases a previously pressed virtual game key.
682    ///
683    /// # Arguments
684    ///
685    /// - `&Self` - Engine host reference.
686    /// - `KeyCode` - Virtual key code to release.
687    pub fn release_key(&self, code: KeyCode) {
688        self.ingest_event(&WindowEvent::KeyUp(
689            WindowId::new(1),
690            KeyEvent::new(code, Modifiers::default(), false),
691        ));
692    }
693
694    /// Mounts a live `Canvas` viewport into the active ambient `Context` backed by this `GameScene`.
695    ///
696    /// Supports multi-platform interaction automatically: keyboard/mouse on Desktop & Web plus
697    /// direct drag-to-steer virtual analog joystick on touch/mobile/tablet screens.
698    ///
699    /// # Arguments
700    ///
701    /// - `&Self` - Engine host reference.
702    /// - `Style` - Layout and visual style of the game viewport.
703    ///
704    /// # Returns
705    ///
706    /// - `NodeId` - Mounted game viewport scene node.
707    #[must_use]
708    pub fn mount_viewport(&self, style: Style) -> NodeId {
709        let Self { clock, scene, .. } = self;
710        let clock_c: Rc<RefCell<FrameClock>> = clock.clone();
711        let scene_c: Rc<RefCell<dyn GameScene>> = scene.clone();
712        let mut ctx: Context = current_context();
713        let node: NodeId = ctx.canvas(
714            style,
715            move |bounds: Rect, display_list: &mut DisplayList| {
716                let alpha: f32 = clock_c
717                    .try_borrow()
718                    .map(|c: Ref<'_, FrameClock>| c.get_alpha())
719                    .unwrap_or(1.0);
720                if let Ok(mut game) = scene_c.try_borrow_mut() {
721                    let mut render_ctx: GameRenderContext<'_> =
722                        GameRenderContext::new(bounds, display_list);
723                    game.render(alpha, &mut render_ctx);
724                }
725            },
726        );
727        if let Ok(mut nodes) = self.get_viewport_nodes().try_borrow_mut() {
728            nodes.push((ctx.get_scene().clone(), node));
729        }
730        let drag_origin: Rc<RefCell<Option<Point>>> = Rc::new(RefCell::new(None));
731        let origin_down: Rc<RefCell<Option<Point>>> = drag_origin.clone();
732        let origin_move: Rc<RefCell<Option<Point>>> = drag_origin.clone();
733        let origin_up: Rc<RefCell<Option<Point>>> = drag_origin;
734        let host_move: Self = self.clone();
735        let host_up: Self = self.clone();
736        ctx.on_pointer_down(node, move |ev: &UiEvent| {
737            if let UiEventKind::PointerDown(pt) = ev.get_kind()
738                && let Ok(mut guard) = origin_down.try_borrow_mut()
739            {
740                *guard = Some(*pt);
741            }
742        });
743        ctx.on_pointer_move(node, move |ev: &UiEvent| {
744            if let UiEventKind::PointerMove(pt) = ev.get_kind()
745                && let Ok(guard) = origin_move.try_borrow()
746                && let Some(orig) = *guard
747            {
748                let dx: f32 = ((pt.get_x() - orig.get_x()) / 48.0).clamp(-1.0, 1.0);
749                let dy: f32 = ((pt.get_y() - orig.get_y()) / 48.0).clamp(-1.0, 1.0);
750                host_move.set_virtual_stick(dx, dy);
751            }
752        });
753        ctx.on_pointer_up(node, move |_: &UiEvent| {
754            if let Ok(mut guard) = origin_up.try_borrow_mut() {
755                *guard = None;
756            }
757            host_up.set_virtual_stick(0.0, 0.0);
758        });
759        node
760    }
761}