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