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    /// Blits a pooled CPU fallback frame lease into `rect` inside this game viewport.
69    ///
70    /// # Arguments
71    ///
72    /// - `&Self` - Mutable render context.
73    /// - `Rect` - Local destination rectangle.
74    /// - `&PooledFrameLease` - Rendered pooled RGBA8 frame lease.
75    pub fn blit_pooled_frame(&mut self, rect: Rect, lease: &PooledFrameLease) {
76        self.blit_framebuffer(rect, lease.to_image_buffer_copy());
77    }
78
79    /// Returns the logical width and height of the game viewport.
80    ///
81    /// # Arguments
82    ///
83    /// - `&Self` - Render context reference.
84    ///
85    /// # Returns
86    ///
87    /// - `Size` - Viewport size in logical pixels.
88    #[must_use]
89    pub fn viewport_size(&self) -> Size {
90        let Self { bounds, .. } = self;
91        Size::new(bounds.get_width(), bounds.get_height())
92    }
93
94    /// Fills the entire game viewport with `color`.
95    ///
96    /// # Arguments
97    ///
98    /// - `&Self` - Mutable render context.
99    /// - `Color` - Background clear color.
100    pub fn clear(&mut self, color: Color) {
101        let Self {
102            bounds,
103            display_list,
104            ..
105        } = self;
106        display_list.push(DrawCommand::FillRoundedRect {
107            rect: *bounds,
108            color,
109            radius: CornerRadius::default(),
110            border: Border::default(),
111        });
112    }
113
114    /// Draws an axis-aligned solid rectangle in viewport-local coordinates.
115    ///
116    /// # Arguments
117    ///
118    /// - `&Self` - Mutable render context.
119    /// - `Rect` - Local rectangle bounds.
120    /// - `Color` - Fill color.
121    pub fn fill_rect(&mut self, rect: Rect, color: Color) {
122        self.fill_rounded_rect(rect, color, 0.0);
123    }
124
125    /// Draws a rounded solid rectangle in viewport-local coordinates.
126    ///
127    /// # Arguments
128    ///
129    /// - `&Self` - Mutable render context.
130    /// - `Rect` - Local rectangle bounds.
131    /// - `Color` - Fill color.
132    /// - `f32` - Corner radius in logical pixels.
133    pub fn fill_rounded_rect(&mut self, rect: Rect, color: Color, radius: f32) {
134        let Self {
135            bounds,
136            display_list,
137            ..
138        } = self;
139        let world: Rect = Rect::new(
140            bounds.get_x() + rect.get_x(),
141            bounds.get_y() + rect.get_y(),
142            rect.get_width(),
143            rect.get_height(),
144        );
145        display_list.push(DrawCommand::FillRoundedRect {
146            rect: world,
147            color,
148            radius: CornerRadius::all(radius),
149            border: Border::default(),
150        });
151    }
152
153    /// Draws an outlined rectangle in viewport-local coordinates.
154    ///
155    /// # Arguments
156    ///
157    /// - `&Self` - Mutable render context.
158    /// - `Rect` - Local rectangle bounds.
159    /// - `f32` - Stroke thickness in logical pixels.
160    /// - `Color` - Stroke color.
161    pub fn stroke_rect(&mut self, rect: Rect, stroke_width: f32, color: Color) {
162        let Self {
163            bounds,
164            display_list,
165            ..
166        } = self;
167        let world: Rect = Rect::new(
168            bounds.get_x() + rect.get_x(),
169            bounds.get_y() + rect.get_y(),
170            rect.get_width(),
171            rect.get_height(),
172        );
173        display_list.push(DrawCommand::FillRoundedRect {
174            rect: world,
175            color: COLOR_TRANSPARENT,
176            radius: CornerRadius::default(),
177            border: Border::new(stroke_width, color),
178        });
179    }
180
181    /// Draws a filled circle in viewport-local coordinates.
182    ///
183    /// # Arguments
184    ///
185    /// - `&Self` - Mutable render context.
186    /// - `Point` - Circle center in viewport-local coordinates.
187    /// - `f32` - Circle radius in logical pixels.
188    /// - `Color` - Fill color.
189    pub fn fill_circle(&mut self, center: Point, radius: f32, color: Color) {
190        let Self {
191            bounds,
192            display_list,
193            ..
194        } = self;
195        let world: Point = Point::new(
196            bounds.get_x() + center.get_x(),
197            bounds.get_y() + center.get_y(),
198        );
199        display_list.push(DrawCommand::Circle {
200            center: world,
201            radius,
202            color,
203        });
204    }
205
206    /// Draws an RGBA8 `ImageBuffer` stretched into `rect` inside this game viewport (ideal for 3D render targets).
207    ///
208    /// # Arguments
209    ///
210    /// - `&Self` - Mutable render context.
211    /// - `Rect` - Local destination rectangle inside the viewport.
212    /// - `ImageBuffer` - Source RGBA8 pixel buffer.
213    pub fn draw_image(&mut self, rect: Rect, buffer: ImageBuffer) {
214        let Self {
215            bounds,
216            display_list,
217            ..
218        } = self;
219        let world: Rect = Rect::new(
220            bounds.get_x() + rect.get_x(),
221            bounds.get_y() + rect.get_y(),
222            rect.get_width(),
223            rect.get_height(),
224        );
225        display_list.push(DrawCommand::Image {
226            rect: world,
227            buffer,
228            radius: CornerRadius::default(),
229        });
230    }
231
232    /// Draws an anti-aliased line segment in viewport-local coordinates.
233    ///
234    /// # Arguments
235    ///
236    /// - `&Self` - Mutable render context.
237    /// - `Point` - Segment start point.
238    /// - `Point` - Segment end point.
239    /// - `f32` - Line width in logical pixels.
240    /// - `Color` - Line color.
241    pub fn draw_line(&mut self, from: Point, to: Point, width: f32, color: Color) {
242        let Self {
243            bounds,
244            display_list,
245            ..
246        } = self;
247        display_list.push(DrawCommand::Line {
248            from: Point::new(bounds.get_x() + from.get_x(), bounds.get_y() + from.get_y()),
249            to: Point::new(bounds.get_x() + to.get_x(), bounds.get_y() + to.get_y()),
250            color,
251            width,
252        });
253    }
254
255    /// Draws HUD or debug text inside the game viewport.
256    ///
257    /// # Arguments
258    ///
259    /// - `&Self` - Mutable render context.
260    /// - `Point` - Top-left local position.
261    /// - `String` - Text string.
262    /// - `f32` - Font size in logical pixels.
263    /// - `Color` - Text color.
264    pub fn draw_text(&mut self, position: Point, text: String, font_size: f32, color: Color) {
265        let Self {
266            bounds,
267            display_list,
268            ..
269        } = self;
270        let mut style: TextStyle = TextStyle::default();
271        style.set_font_size(font_size);
272        style.set_color(color);
273        display_list.push(DrawCommand::TextRun {
274            rect: Rect::new(
275                bounds.get_x() + position.get_x(),
276                bounds.get_y() + position.get_y(),
277                (bounds.get_width() - position.get_x()).max(0.0),
278                font_size * 1.6,
279            ),
280            text,
281            style,
282        });
283    }
284
285    /// Blits an external 2D/3D engine RGBA8 `ImageBuffer` directly into the viewport.
286    ///
287    /// # Arguments
288    ///
289    /// - `&Self` - Mutable render context.
290    /// - `Rect` - Local destination rectangle.
291    /// - `ImageBuffer` - External engine rendered frame or sprite sheet.
292    pub fn blit_framebuffer(&mut self, rect: Rect, buffer: ImageBuffer) {
293        let Self {
294            bounds,
295            display_list,
296            ..
297        } = self;
298        let world: Rect = Rect::new(
299            bounds.get_x() + rect.get_x(),
300            bounds.get_y() + rect.get_y(),
301            rect.get_width(),
302            rect.get_height(),
303        );
304        display_list.push(DrawCommand::Image {
305            rect: world,
306            buffer,
307            radius: CornerRadius::default(),
308        });
309    }
310
311    /// Draws a filled triangle in viewport-local coordinates.
312    ///
313    /// # Arguments
314    ///
315    /// - `&Self` - Mutable render context.
316    /// - `Point` - First vertex.
317    /// - `Point` - Second vertex.
318    /// - `Point` - Third vertex.
319    /// - `Color` - Fill color.
320    pub fn fill_triangle(&mut self, p0: Point, p1: Point, p2: Point, color: Color) {
321        let Self {
322            bounds,
323            display_list,
324            ..
325        } = self;
326        let ox: f32 = bounds.get_x();
327        let oy: f32 = bounds.get_y();
328        display_list.push(DrawCommand::Triangle {
329            p0: Point::new(ox + p0.get_x(), oy + p0.get_y()),
330            p1: Point::new(ox + p1.get_x(), oy + p1.get_y()),
331            p2: Point::new(ox + p2.get_x(), oy + p2.get_y()),
332            color,
333        });
334    }
335
336    /// Draws a cropped frame from a `SpriteSheet` into `rect` with multiplicative `tint`.
337    ///
338    /// # Arguments
339    ///
340    /// - `&Self` - Mutable render context.
341    /// - `&SpriteSheet` - Source sprite sheet.
342    /// - `u32` - Zero-based animation frame index.
343    /// - `Rect` - Destination viewport-local rectangle.
344    /// - `Color` - Multiplicative tint color.
345    pub fn draw_sprite_frame(
346        &mut self,
347        sheet: &SpriteSheet,
348        frame_index: u32,
349        rect: Rect,
350        tint: Color,
351    ) {
352        let src_rect: Rect = sheet.frame_rect(frame_index);
353        let Self {
354            bounds,
355            display_list,
356            ..
357        } = self;
358        display_list.push(DrawCommand::SpriteRegion {
359            rect: Rect::new(
360                bounds.get_x() + rect.get_x(),
361                bounds.get_y() + rect.get_y(),
362                rect.get_width(),
363                rect.get_height(),
364            ),
365            buffer: sheet.get_texture().clone(),
366            src_rect,
367            tint,
368        });
369    }
370
371    /// Renders all visible tiles of `tilemap` through `camera` using O(visible) frustum culling.
372    ///
373    /// # Arguments
374    ///
375    /// - `&Self` - Mutable render context.
376    /// - `&TileMap` - Grid tilemap to draw.
377    /// - `&Camera2D` - Active 2D world camera.
378    pub fn render_tilemap(&mut self, tilemap: &TileMap, camera: &Camera2D) {
379        let vp: Size = self.viewport_size();
380        let vis: Rect = camera.visible_world_rect(vp);
381        let ts: f32 = tilemap.get_tile_size();
382        let zoom: f32 = camera.get_zoom().max(0.25);
383        let min_c: usize = (vis.get_x() / ts).floor().max(0.0) as usize;
384        let max_c: usize = ((vis.right() / ts).ceil().max(0.0) as usize).min(tilemap.get_columns());
385        let min_r: usize = (vis.get_y() / ts).floor().max(0.0) as usize;
386        let max_r: usize = ((vis.bottom() / ts).ceil().max(0.0) as usize).min(tilemap.get_rows());
387        let tile_px: f32 = (ts * zoom).max(1.0);
388        for row in min_r..max_r {
389            for col in min_c..max_c {
390                let tid: u16 = tilemap.tile_at(col, row);
391                if tid == 0 {
392                    continue;
393                }
394                let Some(entry) = tilemap.get_palette().get(tid as usize) else {
395                    continue;
396                };
397                let world_pt: Point = Point::new((col as f32) * ts, (row as f32) * ts);
398                let screen_pt: Point = camera.world_to_screen(world_pt, vp);
399                let tile_rect: Rect = Rect::new(
400                    screen_pt.get_x(),
401                    screen_pt.get_y(),
402                    tile_px + 0.5,
403                    tile_px + 0.5,
404                );
405                self.fill_rect(tile_rect, entry.get_color());
406            }
407        }
408    }
409
410    /// Renders all visible sprite entities in `world` through `camera`, sorted by `z_order` with frustum culling.
411    ///
412    /// # Arguments
413    ///
414    /// - `&Self` - Mutable render context.
415    /// - `&GameWorld` - Active ECS world.
416    /// - `&Camera2D` - Active 2D world camera.
417    ///
418    /// # Returns
419    ///
420    /// - `usize` - Number of visible entities drawn after frustum culling.
421    pub fn render_world(&mut self, world: &GameWorld, camera: &Camera2D) -> usize {
422        let vp: Size = self.viewport_size();
423        let vis: Rect = camera.visible_world_rect(vp);
424        let zoom: f32 = camera.get_zoom().max(0.25);
425        let mut draw_order: Vec<(i32, usize)> = Vec::with_capacity(world.get_live_count());
426        for (idx, ent) in world.get_entities().iter().enumerate() {
427            if !ent.get_alive() {
428                continue;
429            }
430            let Some(sp) = ent.sprite_component() else {
431                continue;
432            };
433            if !sp.get_visible() {
434                continue;
435            }
436            if ent.world_bounds().intersect(vis).is_none() {
437                continue;
438            }
439            draw_order.push((sp.get_z_order(), idx));
440        }
441        draw_order.sort_by(|a: &(i32, usize), b: &(i32, usize)| {
442            a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1))
443        });
444        let rendered: usize = draw_order.len();
445        for (_, idx) in draw_order.into_iter() {
446            let ent: &EntityRecord = &world.get_entities()[idx];
447            let Some(sp) = ent.sprite_component() else {
448                continue;
449            };
450            let tr: EntityTransform = ent.get_transform();
451            let center: Point = camera.world_to_screen(tr.get_position(), vp);
452            let w: f32 = sp.get_size().get_width() * tr.get_scale().get_width() * zoom;
453            let h: f32 = sp.get_size().get_height() * tr.get_scale().get_height() * zoom;
454            match sp.get_shape() {
455                EntityVisualShape::Rect => {
456                    let rect: Rect =
457                        Rect::new(center.get_x() - w * 0.5, center.get_y() - h * 0.5, w, h);
458                    self.fill_rounded_rect(rect, sp.get_color(), sp.get_corner_radius() * zoom);
459                    if sp.get_accent().get_a() > 0 {
460                        self.stroke_rect(rect, 1.5, sp.get_accent());
461                    }
462                }
463                EntityVisualShape::Circle => {
464                    let r: f32 = (w.min(h) * 0.5).max(1.0);
465                    self.fill_circle(center, r, sp.get_color());
466                    if sp.get_accent().get_a() > 0 && r > 3.0 {
467                        self.fill_circle(center, r * 0.45, sp.get_accent());
468                    }
469                }
470                EntityVisualShape::Triangle => {
471                    let ang: f32 = tr.get_rotation_rad();
472                    let cos_a: f32 = ang.cos();
473                    let sin_a: f32 = ang.sin();
474                    let rx: f32 = w * 0.55;
475                    let ry: f32 = h * 0.48;
476                    let nose: Point =
477                        Point::new(center.get_x() + cos_a * rx, center.get_y() + sin_a * rx);
478                    let left: Point = Point::new(
479                        center.get_x() - cos_a * (rx * 0.72) - sin_a * ry,
480                        center.get_y() - sin_a * (rx * 0.72) + cos_a * ry,
481                    );
482                    let right: Point = Point::new(
483                        center.get_x() - cos_a * (rx * 0.72) + sin_a * ry,
484                        center.get_y() - sin_a * (rx * 0.72) - cos_a * ry,
485                    );
486                    self.fill_triangle(nose, left, right, sp.get_color());
487                    if sp.get_accent().get_a() > 0 {
488                        self.fill_circle(center, (w.min(h) * 0.16).max(2.0), sp.get_accent());
489                    }
490                }
491                EntityVisualShape::Diamond => {
492                    let hw: f32 = w * 0.5;
493                    let hh: f32 = h * 0.5;
494                    let top: Point = Point::new(center.get_x(), center.get_y() - hh);
495                    let right: Point = Point::new(center.get_x() + hw, center.get_y());
496                    let bottom: Point = Point::new(center.get_x(), center.get_y() + hh);
497                    let left: Point = Point::new(center.get_x() - hw, center.get_y());
498                    self.fill_triangle(top, right, bottom, sp.get_color());
499                    self.fill_triangle(top, bottom, left, sp.get_color());
500                    if sp.get_accent().get_a() > 0 {
501                        self.fill_circle(center, (w.min(h) * 0.18).max(2.0), sp.get_accent());
502                    }
503                }
504            }
505        }
506        rendered
507    }
508
509    /// Renders all visible 2D entities in `world` using discontinuity-safe render-time interpolation between `prev` and `curr` snapshots at `alpha`.
510    ///
511    /// # Arguments
512    ///
513    /// - `&Self` - Mutable render context.
514    /// - `&GameWorld` - Authoritative ECS world providing sprite appearance metadata.
515    /// - `&World2DSnapshot` - Previous fixed-step immutable snapshot.
516    /// - `&World2DSnapshot` - Current fixed-step immutable snapshot.
517    /// - `f32` - Normalized interpolation factor in `[0.0, 1.0]`.
518    ///
519    /// # Returns
520    ///
521    /// - `usize` - Number of visible interpolated entities drawn.
522    pub fn render_interpolated_world(
523        &mut self,
524        world: &GameWorld,
525        prev: &World2DSnapshot,
526        curr: &World2DSnapshot,
527        alpha: f32,
528    ) -> usize {
529        let interp: World2DSnapshot = prev.interpolate(curr, alpha);
530        let camera: Camera2D = interp.get_camera();
531        let vp: Size = self.viewport_size();
532        let vis: Rect = camera.visible_world_rect(vp);
533        let zoom: f32 = camera.get_zoom().max(0.25);
534        let poses: &[EntityPose2D] = interp.get_entities().as_slice();
535        let records: &[EntityRecord] = world.get_entities().as_slice();
536        let mut draw_order: Vec<(i32, usize)> = Vec::with_capacity(poses.len());
537        for (idx, pose) in poses.iter().enumerate() {
538            if !pose.get_alive() {
539                continue;
540            }
541            let Some(ent) = records.get(idx) else {
542                continue;
543            };
544            if ent.get_id() != pose.get_id() {
545                continue;
546            }
547            let Some(sp) = ent.sprite_component() else {
548                continue;
549            };
550            if !sp.get_visible() {
551                continue;
552            }
553            let tr: EntityTransform = pose.get_transform();
554            let pos: Point = tr.get_position();
555            let bw: f32 = sp.get_size().get_width() * tr.get_scale().get_width();
556            let bh: f32 = sp.get_size().get_height() * tr.get_scale().get_height();
557            let bounds: Rect = Rect::new(pos.get_x() - bw * 0.5, pos.get_y() - bh * 0.5, bw, bh);
558            if bounds.intersect(vis).is_none() {
559                continue;
560            }
561            draw_order.push((sp.get_z_order(), idx));
562        }
563        draw_order.sort_by(|a: &(i32, usize), b: &(i32, usize)| {
564            a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1))
565        });
566        let rendered: usize = draw_order.len();
567        for (_, idx) in draw_order.into_iter() {
568            let ent: &EntityRecord = &records[idx];
569            let Some(sp) = ent.sprite_component() else {
570                continue;
571            };
572            let tr: EntityTransform = poses[idx].get_transform();
573            let center: Point = camera.world_to_screen(tr.get_position(), vp);
574            let w: f32 = sp.get_size().get_width() * tr.get_scale().get_width() * zoom;
575            let h: f32 = sp.get_size().get_height() * tr.get_scale().get_height() * zoom;
576            match sp.get_shape() {
577                EntityVisualShape::Rect => {
578                    let rect: Rect =
579                        Rect::new(center.get_x() - w * 0.5, center.get_y() - h * 0.5, w, h);
580                    self.fill_rounded_rect(rect, sp.get_color(), sp.get_corner_radius() * zoom);
581                    if sp.get_accent().get_a() > 0 {
582                        self.stroke_rect(rect, 1.5, sp.get_accent());
583                    }
584                }
585                EntityVisualShape::Circle => {
586                    let r: f32 = (w.min(h) * 0.5).max(1.0);
587                    self.fill_circle(center, r, sp.get_color());
588                    if sp.get_accent().get_a() > 0 && r > 3.0 {
589                        self.fill_circle(center, r * 0.45, sp.get_accent());
590                    }
591                }
592                EntityVisualShape::Triangle => {
593                    let ang: f32 = tr.get_rotation_rad();
594                    let cos_a: f32 = ang.cos();
595                    let sin_a: f32 = ang.sin();
596                    let rx: f32 = w * 0.55;
597                    let ry: f32 = h * 0.48;
598                    let nose: Point =
599                        Point::new(center.get_x() + cos_a * rx, center.get_y() + sin_a * rx);
600                    let left: Point = Point::new(
601                        center.get_x() - cos_a * (rx * 0.72) - sin_a * ry,
602                        center.get_y() - sin_a * (rx * 0.72) + cos_a * ry,
603                    );
604                    let right: Point = Point::new(
605                        center.get_x() - cos_a * (rx * 0.72) + sin_a * ry,
606                        center.get_y() - sin_a * (rx * 0.72) - cos_a * ry,
607                    );
608                    self.fill_triangle(nose, left, right, sp.get_color());
609                    if sp.get_accent().get_a() > 0 {
610                        self.fill_circle(center, (w.min(h) * 0.16).max(2.0), sp.get_accent());
611                    }
612                }
613                EntityVisualShape::Diamond => {
614                    let hw: f32 = w * 0.5;
615                    let hh: f32 = h * 0.5;
616                    let top: Point = Point::new(center.get_x(), center.get_y() - hh);
617                    let right: Point = Point::new(center.get_x() + hw, center.get_y());
618                    let bottom: Point = Point::new(center.get_x(), center.get_y() + hh);
619                    let left: Point = Point::new(center.get_x() - hw, center.get_y());
620                    self.fill_triangle(top, right, bottom, sp.get_color());
621                    self.fill_triangle(top, bottom, left, sp.get_color());
622                    if sp.get_accent().get_a() > 0 {
623                        self.fill_circle(center, (w.min(h) * 0.18).max(2.0), sp.get_accent());
624                    }
625                }
626            }
627        }
628        rendered
629    }
630
631    /// Renders all active pooled particles in `particles` through `camera` with frustum culling and lifetime interpolation.
632    ///
633    /// # Arguments
634    ///
635    /// - `&Self` - Mutable render context.
636    /// - `&ParticleSystem` - Active particle system.
637    /// - `&Camera2D` - Active 2D world camera.
638    ///
639    /// # Returns
640    ///
641    /// - `usize` - Number of visible particles rendered.
642    pub fn render_particles(&mut self, particles: &ParticleSystem, camera: &Camera2D) -> usize {
643        let vp: Size = self.viewport_size();
644        let vis: Rect = camera.visible_world_rect(vp);
645        let zoom: f32 = camera.get_zoom().max(0.25);
646        let n: usize = particles.get_active_count();
647        let mut count: usize = 0;
648        for i in 0..n {
649            let pos: Point = Point::new(particles.pos_x[i], particles.pos_y[i]);
650            if !vis.contains(pos) {
651                continue;
652            }
653            let t: f32 = (particles.age[i] / particles.lifetime[i].max(0.001)).clamp(0.0, 1.0);
654            let s0: f32 = particles.start_size[i];
655            let s1: f32 = particles.end_size[i];
656            let r: f32 = ((s0 + (s1 - s0) * t) * zoom).max(0.8);
657            let col: Color = particles.start_color[i].lerp(particles.end_color[i], t);
658            if col.get_a() == 0 {
659                continue;
660            }
661            let screen: Point = camera.world_to_screen(pos, vp);
662            self.fill_circle(screen, r, col);
663            count += 1;
664        }
665        count
666    }
667
668    /// Draws wireframe collider bounds for debugging physics shapes inside `world`.
669    ///
670    /// # Arguments
671    ///
672    /// - `&Self` - Mutable render context.
673    /// - `&GameWorld` - Active ECS world.
674    /// - `&Camera2D` - Active 2D world camera.
675    pub fn draw_debug_colliders(&mut self, world: &GameWorld, camera: &Camera2D) {
676        let vp: Size = self.viewport_size();
677        let vis: Rect = camera.visible_world_rect(vp);
678        let zoom: f32 = camera.get_zoom().max(0.25);
679        for ent in world.get_entities().iter() {
680            if !ent.get_alive() {
681                continue;
682            }
683            let Some(col) = ent.collider_component() else {
684                continue;
685            };
686            let aabb: Rect = col.world_aabb(ent.get_transform().get_position());
687            if aabb.intersect(vis).is_none() {
688                continue;
689            }
690            let tl: Point = camera.world_to_screen(Point::new(aabb.get_x(), aabb.get_y()), vp);
691            let color: Color = if col.get_is_trigger() {
692                Color::rgba(250, 204, 21, 180)
693            } else {
694                Color::rgba(34, 197, 94, 180)
695            };
696            self.stroke_rect(
697                Rect::new(
698                    tl.get_x(),
699                    tl.get_y(),
700                    aabb.get_width() * zoom,
701                    aabb.get_height() * zoom,
702                ),
703                1.0,
704                color,
705            );
706        }
707    }
708}
709
710/// Host construction, fixed-step execution, and scene mounting for `GameEngineHost`.
711impl GameEngineHost {
712    /// Creates a new `GameEngineHost` wrapping `scene` with a `fixed_dt` simulation cadence.
713    ///
714    /// # Arguments
715    ///
716    /// - `S` - User game scene implementing `GameScene`.
717    /// - `f32` - Fixed physics timestep in seconds (e.g. `1.0 / 60.0`).
718    ///
719    /// # Returns
720    ///
721    /// - `Self` - Constructed engine host.
722    #[must_use]
723    pub fn new<S>(scene: S, fixed_dt: f32) -> Self
724    where
725        S: GameScene + 'static,
726    {
727        Self {
728            clock: Rc::new(RefCell::new(FrameClock::new(fixed_dt, 8))),
729            input: Rc::new(RefCell::new(InputState::new())),
730            scene: Rc::new(RefCell::new(scene)),
731            viewport_nodes: Rc::new(RefCell::new(Vec::new())),
732            paused: Rc::new(Cell::new(false)),
733        }
734    }
735
736    /// Pauses or resumes simulation stepping for this game engine host (driven by `Lifecycle::on_freeze`/`on_resume`).
737    ///
738    /// # Arguments
739    ///
740    /// - `&Self` - Engine host reference.
741    /// - `bool` - `true` to pause simulation; `false` to resume.
742    pub fn set_paused(&self, paused: bool) {
743        self.get_paused().set(paused);
744    }
745
746    /// Returns `true` when this game engine host is currently paused.
747    ///
748    /// # Arguments
749    ///
750    /// - `&Self` - Engine host reference.
751    ///
752    /// # Returns
753    ///
754    /// - `bool` - Pause state.
755    #[must_use]
756    pub fn is_paused(&self) -> bool {
757        self.get_paused().get()
758    }
759
760    /// Returns screen-space bounds of all mounted, currently visible viewports backed by this host.
761    ///
762    /// # Arguments
763    ///
764    /// - `&Self` - Engine host reference.
765    /// - `&SceneTree` - Active scene tree.
766    ///
767    /// # Returns
768    ///
769    /// - `Vec<Rect>` - Visible viewport rectangles (empty when paused or not on screen).
770    #[must_use]
771    pub fn active_viewport_bounds(&self, tree: &SceneTree) -> Vec<Rect> {
772        if self.is_paused() {
773            return Vec::new();
774        }
775        let mut rects: Vec<Rect> = Vec::new();
776        if let Ok(mut nodes) = self.get_viewport_nodes().try_borrow_mut() {
777            nodes.retain(|(_, id): &(SceneHandle, NodeId)| tree.get_node(*id).is_some());
778            for (_, id) in nodes.iter() {
779                if tree.is_node_visible(*id)
780                    && let Some(bounds) = tree.node_screen_bounds(*id)
781                    && bounds.get_width() > 0.0
782                    && bounds.get_height() > 0.0
783                {
784                    rects.push(bounds);
785                }
786            }
787        }
788        rects
789    }
790
791    /// Feeds a `WindowEvent` into the hosted game `InputState`.
792    ///
793    /// # Arguments
794    ///
795    /// - `&Self` - Engine host reference.
796    /// - `&WindowEvent` - Event received from the OS window.
797    pub fn ingest_event(&self, event: &WindowEvent) {
798        if let Ok(mut input) = self.get_input().try_borrow_mut() {
799            input.ingest(event);
800        }
801    }
802
803    /// Advances the hosted game scene by `dt_secs` using fixed-timestep accumulation.
804    ///
805    /// # Arguments
806    ///
807    /// - `&Self` - Engine host reference.
808    /// - `f32` - Elapsed wall seconds since the previous tick.
809    ///
810    /// # Returns
811    ///
812    /// - `u32` - Number of fixed physics steps executed.
813    pub fn step(&self, dt_secs: f32) -> u32 {
814        if self.is_paused() {
815            return 0;
816        }
817        let (steps, fixed_dt): (u32, f32) = match self.get_clock().try_borrow_mut() {
818            Ok(mut clock) => (clock.tick(dt_secs), clock.get_fixed_dt()),
819            Err(_) => (0, 1.0 / 60.0),
820        };
821        let input_with_edges: InputState = self
822            .get_input()
823            .try_borrow()
824            .map(|guard: Ref<'_, InputState>| guard.clone())
825            .unwrap_or_default();
826        let held_only_input: InputState = input_with_edges.without_edges();
827        let Self { scene, .. } = self;
828        if let Ok(mut game) = scene.try_borrow_mut() {
829            for substep_idx in 0..steps {
830                let step_input: &InputState = if substep_idx == 0 {
831                    &input_with_edges
832                } else {
833                    &held_only_input
834                };
835                game.fixed_update(fixed_dt, step_input);
836            }
837            let update_input: &InputState = if steps > 0 {
838                &held_only_input
839            } else {
840                &input_with_edges
841            };
842            game.update(dt_secs, update_input);
843        }
844        if steps > 0
845            && let Ok(mut input) = self.get_input().try_borrow_mut()
846        {
847            input.begin_frame();
848        }
849        self.mark_viewports_dirty();
850        steps
851    }
852
853    /// Marks all mounted game viewport nodes paint-dirty without advancing simulation clocks (e.g. for lifecycle first frames or HUD-independent refreshes).
854    ///
855    /// # Arguments
856    ///
857    /// - `&Self` - Engine host reference.
858    pub fn mark_viewports_dirty(&self) {
859        if let Ok(nodes) = self.get_viewport_nodes().try_borrow() {
860            for (scene_handle, node_id) in nodes.iter() {
861                scene_handle.mark_dirty(*node_id, DIRTY_PAINT);
862            }
863        }
864    }
865
866    /// Executes a `PacingDecision` from `FramePacingController`, advancing simulation strictly on VSync decisions and never on deferred non-VSync triggers.
867    ///
868    /// # Arguments
869    ///
870    /// - `&Self` - Engine host reference.
871    /// - `&PacingDecision` - Authoritative pacing decision for the current trigger.
872    ///
873    /// # Returns
874    ///
875    /// - `u32` - Number of fixed simulation steps executed (`0` when deferred, capped, or lifecycle-first-frame).
876    pub fn step_paced(&self, decision: &PacingDecision) -> u32 {
877        match decision.get_action() {
878            PacingAction::StepAndRender => self.step(decision.get_sim_dt_secs()),
879            PacingAction::RenderWithoutSimAdvance => {
880                self.mark_viewports_dirty();
881                0
882            }
883            PacingAction::DeferToNextVsync
884            | PacingAction::WaitInFlight
885            | PacingAction::SkipUserCap => 0,
886        }
887    }
888
889    /// Sets the virtual analog joystick vector `(dx, dy)` in `[-1.0, 1.0]` for mobile/tablet/gamepad play.
890    ///
891    /// # Arguments
892    ///
893    /// - `&Self` - Engine host reference.
894    /// - `f32` - Horizontal axis.
895    /// - `f32` - Vertical axis.
896    pub fn set_virtual_stick(&self, dx: f32, dy: f32) {
897        if let Ok(mut input) = self.get_input().try_borrow_mut() {
898            input.set_virtual_stick(dx, dy);
899        }
900    }
901
902    /// Presses a virtual game key (ideal for holdable mobile touch D-pad buttons).
903    ///
904    /// # Arguments
905    ///
906    /// - `&Self` - Engine host reference.
907    /// - `KeyCode` - Virtual key code to hold down.
908    pub fn press_key(&self, code: KeyCode) {
909        self.ingest_event(&WindowEvent::KeyDown(
910            WindowId::new(1),
911            KeyEvent::new(code, Modifiers::default(), false),
912        ));
913    }
914
915    /// Releases a previously pressed virtual game key.
916    ///
917    /// # Arguments
918    ///
919    /// - `&Self` - Engine host reference.
920    /// - `KeyCode` - Virtual key code to release.
921    pub fn release_key(&self, code: KeyCode) {
922        self.ingest_event(&WindowEvent::KeyUp(
923            WindowId::new(1),
924            KeyEvent::new(code, Modifiers::default(), false),
925        ));
926    }
927
928    /// Mounts a live `Canvas` viewport into the active ambient `Context` backed by this `GameScene`.
929    ///
930    /// Supports multi-platform interaction automatically: keyboard/mouse on Desktop & Web plus
931    /// direct drag-to-steer virtual analog joystick on touch/mobile/tablet screens.
932    ///
933    /// # Arguments
934    ///
935    /// - `&Self` - Engine host reference.
936    /// - `Style` - Layout and visual style of the game viewport.
937    ///
938    /// # Returns
939    ///
940    /// - `NodeId` - Mounted game viewport scene node.
941    #[must_use]
942    pub fn mount_viewport(&self, style: Style) -> NodeId {
943        let Self { clock, scene, .. } = self;
944        let clock_c: Rc<RefCell<FrameClock>> = clock.clone();
945        let scene_c: Rc<RefCell<dyn GameScene>> = scene.clone();
946        let mut ctx: Context = current_context();
947        let node: NodeId = ctx.canvas(
948            style,
949            move |bounds: Rect, display_list: &mut DisplayList| {
950                let alpha: f32 = clock_c
951                    .try_borrow()
952                    .map(|c: Ref<'_, FrameClock>| c.get_alpha())
953                    .unwrap_or(1.0);
954                if let Ok(mut game) = scene_c.try_borrow_mut() {
955                    let mut render_ctx: GameRenderContext<'_> =
956                        GameRenderContext::new(bounds, display_list);
957                    game.render(alpha, &mut render_ctx);
958                }
959            },
960        );
961        if let Ok(mut nodes) = self.get_viewport_nodes().try_borrow_mut() {
962            nodes.push((ctx.get_scene().clone(), node));
963        }
964        let drag_origin: Rc<RefCell<Option<Point>>> = Rc::new(RefCell::new(None));
965        let origin_down: Rc<RefCell<Option<Point>>> = drag_origin.clone();
966        let origin_move: Rc<RefCell<Option<Point>>> = drag_origin.clone();
967        let origin_up: Rc<RefCell<Option<Point>>> = drag_origin;
968        let host_move: Self = self.clone();
969        let host_up: Self = self.clone();
970        ctx.on_pointer_down(node, move |ev: &UiEvent| {
971            if let UiEventKind::PointerDown(pt) = ev.get_kind()
972                && let Ok(mut guard) = origin_down.try_borrow_mut()
973            {
974                *guard = Some(*pt);
975            }
976        });
977        ctx.on_pointer_move(node, move |ev: &UiEvent| {
978            if let UiEventKind::PointerMove(pt) = ev.get_kind()
979                && let Ok(guard) = origin_move.try_borrow()
980                && let Some(orig) = *guard
981            {
982                let dx: f32 = ((pt.get_x() - orig.get_x()) / 48.0).clamp(-1.0, 1.0);
983                let dy: f32 = ((pt.get_y() - orig.get_y()) / 48.0).clamp(-1.0, 1.0);
984                host_move.set_virtual_stick(dx, dy);
985            }
986        });
987        ctx.on_pointer_up(node, move |_: &UiEvent| {
988            if let Ok(mut guard) = origin_up.try_borrow_mut() {
989                *guard = None;
990            }
991            host_up.set_virtual_stick(0.0, 0.0);
992        });
993        node
994    }
995}