1use super::*;
2
3impl<'a> GameRenderContext<'a> {
5 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 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 #[must_use]
63 pub fn gpu_composite_target(&self) -> Option<GpuCompositeDescriptor> {
64 let Self { gpu_composite, .. } = self;
65 *gpu_composite
66 }
67
68 #[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 pub fn compose_shared_gpu_surface(
95 &mut self,
96 surface: &mut GpuSharedSurface,
97 compositor_device_id: u64,
98 ) -> SharedGpuCompositeReceipt {
99 surface.compose_frame(compositor_device_id, self)
100 }
101
102 pub fn blit_pooled_frame(&mut self, rect: Rect, lease: &PooledFrameLease) {
110 let frame_ref: PooledFrameRef = lease.to_frame_ref();
111 self.blit_pooled_frame_ref(rect, &frame_ref);
112 }
113
114 pub fn blit_pooled_frame_ref(&mut self, rect: Rect, frame: &PooledFrameRef) {
122 let Self {
123 bounds,
124 display_list,
125 ..
126 } = self;
127 let world: Rect = Rect::new(
128 bounds.get_x() + rect.get_x(),
129 bounds.get_y() + rect.get_y(),
130 rect.get_width(),
131 rect.get_height(),
132 );
133 display_list.push(DrawCommand::SharedImage {
134 rect: world,
135 width: frame.get_width(),
136 height: frame.get_height(),
137 pixels: frame.shared_pixels(),
138 radius: CornerRadius::default(),
139 });
140 }
141
142 #[must_use]
152 pub fn viewport_size(&self) -> Size {
153 let Self { bounds, .. } = self;
154 Size::new(bounds.get_width(), bounds.get_height())
155 }
156
157 #[must_use]
167 pub fn scale_factor(&self) -> f32 {
168 let Self { display_list, .. } = self;
169 let raw: f32 = display_list.get_scale_factor();
170 if raw.is_finite() && raw > 0.0 {
171 raw.clamp(0.5, 6.0)
172 } else {
173 1.0
174 }
175 }
176
177 pub fn clear(&mut self, color: Color) {
184 let Self {
185 bounds,
186 display_list,
187 ..
188 } = self;
189 display_list.push(DrawCommand::FillRoundedRect {
190 rect: *bounds,
191 color,
192 radius: CornerRadius::default(),
193 border: Border::default(),
194 });
195 }
196
197 pub fn fill_rect(&mut self, rect: Rect, color: Color) {
205 self.fill_rounded_rect(rect, color, 0.0);
206 }
207
208 pub fn fill_rounded_rect(&mut self, rect: Rect, color: Color, radius: f32) {
217 let Self {
218 bounds,
219 display_list,
220 ..
221 } = self;
222 let world: Rect = Rect::new(
223 bounds.get_x() + rect.get_x(),
224 bounds.get_y() + rect.get_y(),
225 rect.get_width(),
226 rect.get_height(),
227 );
228 display_list.push(DrawCommand::FillRoundedRect {
229 rect: world,
230 color,
231 radius: CornerRadius::all(radius),
232 border: Border::default(),
233 });
234 }
235
236 pub fn stroke_rect(&mut self, rect: Rect, stroke_width: f32, color: Color) {
245 let Self {
246 bounds,
247 display_list,
248 ..
249 } = self;
250 let world: Rect = Rect::new(
251 bounds.get_x() + rect.get_x(),
252 bounds.get_y() + rect.get_y(),
253 rect.get_width(),
254 rect.get_height(),
255 );
256 display_list.push(DrawCommand::FillRoundedRect {
257 rect: world,
258 color: COLOR_TRANSPARENT,
259 radius: CornerRadius::default(),
260 border: Border::new(stroke_width, color),
261 });
262 }
263
264 pub fn fill_circle(&mut self, center: Point, radius: f32, color: Color) {
273 let Self {
274 bounds,
275 display_list,
276 ..
277 } = self;
278 let world: Point = Point::new(
279 bounds.get_x() + center.get_x(),
280 bounds.get_y() + center.get_y(),
281 );
282 display_list.push(DrawCommand::Circle {
283 center: world,
284 radius,
285 color,
286 });
287 }
288
289 pub fn draw_image(&mut self, rect: Rect, buffer: ImageBuffer) {
297 let Self {
298 bounds,
299 display_list,
300 ..
301 } = self;
302 let world: Rect = Rect::new(
303 bounds.get_x() + rect.get_x(),
304 bounds.get_y() + rect.get_y(),
305 rect.get_width(),
306 rect.get_height(),
307 );
308 display_list.push(DrawCommand::Image {
309 rect: world,
310 buffer,
311 radius: CornerRadius::default(),
312 });
313 }
314
315 pub fn draw_line(&mut self, from: Point, to: Point, width: f32, color: Color) {
325 let Self {
326 bounds,
327 display_list,
328 ..
329 } = self;
330 display_list.push(DrawCommand::Line {
331 from: Point::new(bounds.get_x() + from.get_x(), bounds.get_y() + from.get_y()),
332 to: Point::new(bounds.get_x() + to.get_x(), bounds.get_y() + to.get_y()),
333 color,
334 width,
335 });
336 }
337
338 pub fn draw_text(&mut self, position: Point, text: String, font_size: f32, color: Color) {
348 let Self {
349 bounds,
350 display_list,
351 ..
352 } = self;
353 let mut style: TextStyle = TextStyle::default();
354 style.set_font_size(font_size);
355 style.set_color(color);
356 display_list.push(DrawCommand::TextRun {
357 rect: Rect::new(
358 bounds.get_x() + position.get_x(),
359 bounds.get_y() + position.get_y(),
360 (bounds.get_width() - position.get_x()).max(0.0),
361 font_size * 1.6,
362 ),
363 text,
364 style,
365 });
366 }
367
368 pub fn draw_text_str(&mut self, position: Point, text: &str, font_size: f32, color: Color) {
378 let Self {
379 bounds,
380 display_list,
381 ..
382 } = self;
383 let pooled: String = display_list.alloc_text(text);
384 let mut style: TextStyle = TextStyle::default();
385 style.set_font_size(font_size);
386 style.set_color(color);
387 display_list.push(DrawCommand::TextRun {
388 rect: Rect::new(
389 bounds.get_x() + position.get_x(),
390 bounds.get_y() + position.get_y(),
391 (bounds.get_width() - position.get_x()).max(0.0),
392 font_size * 1.6,
393 ),
394 text: pooled,
395 style,
396 });
397 }
398
399 pub fn blit_framebuffer(&mut self, rect: Rect, buffer: ImageBuffer) {
407 let Self {
408 bounds,
409 display_list,
410 ..
411 } = self;
412 let world: Rect = Rect::new(
413 bounds.get_x() + rect.get_x(),
414 bounds.get_y() + rect.get_y(),
415 rect.get_width(),
416 rect.get_height(),
417 );
418 display_list.push(DrawCommand::Image {
419 rect: world,
420 buffer,
421 radius: CornerRadius::default(),
422 });
423 }
424
425 pub fn fill_triangle(&mut self, p0: Point, p1: Point, p2: Point, color: Color) {
435 let Self {
436 bounds,
437 display_list,
438 ..
439 } = self;
440 let ox: f32 = bounds.get_x();
441 let oy: f32 = bounds.get_y();
442 display_list.push(DrawCommand::Triangle {
443 p0: Point::new(ox + p0.get_x(), oy + p0.get_y()),
444 p1: Point::new(ox + p1.get_x(), oy + p1.get_y()),
445 p2: Point::new(ox + p2.get_x(), oy + p2.get_y()),
446 color,
447 });
448 }
449
450 pub fn draw_sprite_frame(
460 &mut self,
461 sheet: &SpriteSheet,
462 frame_index: u32,
463 rect: Rect,
464 tint: Color,
465 ) {
466 let src_rect: Rect = sheet.frame_rect(frame_index);
467 let Self {
468 bounds,
469 display_list,
470 ..
471 } = self;
472 display_list.push(DrawCommand::SpriteRegion {
473 rect: Rect::new(
474 bounds.get_x() + rect.get_x(),
475 bounds.get_y() + rect.get_y(),
476 rect.get_width(),
477 rect.get_height(),
478 ),
479 buffer: sheet.get_texture().clone(),
480 src_rect,
481 tint,
482 });
483 }
484
485 pub fn render_tilemap(&mut self, tilemap: &TileMap, camera: &Camera2D) {
493 let vp: Size = self.viewport_size();
494 let vis: Rect = camera.visible_world_rect(vp);
495 let ts: f32 = tilemap.get_tile_size();
496 let (cam_x, cam_y, zoom, half_w, half_h): (f32, f32, f32, f32, f32) =
497 camera.projection_params(vp);
498 let min_c: usize = (vis.get_x() / ts).floor().max(0.0) as usize;
499 let max_c: usize = ((vis.right() / ts).ceil().max(0.0) as usize).min(tilemap.get_columns());
500 let min_r: usize = (vis.get_y() / ts).floor().max(0.0) as usize;
501 let max_r: usize = ((vis.bottom() / ts).ceil().max(0.0) as usize).min(tilemap.get_rows());
502 let tile_px: f32 = (ts * zoom).max(1.0);
503 if tilemap.has_fresh_chunk_cache() {
504 for chunk in tilemap.cached_chunks().iter() {
505 if chunk.get_max_col() <= min_c
506 || chunk.get_min_col() >= max_c
507 || chunk.get_max_row() <= min_r
508 || chunk.get_min_row() >= max_r
509 {
510 continue;
511 }
512 for run in chunk.get_runs().iter() {
513 let r: usize = run.get_row();
514 if r < min_r || r >= max_r {
515 continue;
516 }
517 let c0: usize = run.get_col().max(min_c);
518 let c1: usize = (run.get_col() + run.get_span_cols()).min(max_c);
519 if c0 >= c1 {
520 continue;
521 }
522 let sx: f32 = ((c0 as f32) * ts - cam_x) * zoom + half_w;
523 let sy: f32 = ((r as f32) * ts - cam_y) * zoom + half_h;
524 let run_w: f32 = ((c1 - c0) as f32) * tile_px + 0.5;
525 self.fill_rect(Rect::new(sx, sy, run_w, tile_px + 0.5), run.get_color());
526 }
527 }
528 return;
529 }
530 let palette: &[TilePaletteEntry] = tilemap.get_palette().as_slice();
531 for row in min_r..max_r {
532 let sy: f32 = ((row as f32) * ts - cam_y) * zoom + half_h;
533 let mut col: usize = min_c;
534 while col < max_c {
535 let tid: u16 = tilemap.tile_at(col, row);
536 if tid == 0 {
537 col += 1;
538 continue;
539 }
540 let Some(entry) = palette.get(tid as usize) else {
541 col += 1;
542 continue;
543 };
544 let color: Color = entry.get_color();
545 let start_col: usize = col;
546 col += 1;
547 while col < max_c {
548 let next_tid: u16 = tilemap.tile_at(col, row);
549 if next_tid == 0 {
550 break;
551 }
552 let same_color: bool = palette
553 .get(next_tid as usize)
554 .is_some_and(|e: &TilePaletteEntry| e.get_color() == color);
555 if !same_color {
556 break;
557 }
558 col += 1;
559 }
560 let sx: f32 = ((start_col as f32) * ts - cam_x) * zoom + half_w;
561 let run_w: f32 = ((col - start_col) as f32) * tile_px + 0.5;
562 self.fill_rect(Rect::new(sx, sy, run_w, tile_px + 0.5), color);
563 }
564 }
565 }
566
567 pub fn render_world(&mut self, world: &GameWorld, camera: &Camera2D) -> usize {
579 let vp: Size = self.viewport_size();
580 let vis: Rect = camera.visible_world_rect(vp);
581 let (cam_x, cam_y, zoom, half_w, half_h): (f32, f32, f32, f32, f32) =
582 camera.projection_params(vp);
583 let mut draw_order: Vec<(i32, usize)> = Vec::with_capacity(world.get_live_count());
584 for (idx, ent) in world.get_entities().iter().enumerate() {
585 if !ent.get_alive() {
586 continue;
587 }
588 let Some(sp) = ent.sprite_component() else {
589 continue;
590 };
591 if !sp.get_visible() {
592 continue;
593 }
594 if ent.world_bounds().intersect(vis).is_none() {
595 continue;
596 }
597 draw_order.push((sp.get_z_order(), idx));
598 }
599 draw_order.sort_by(|a: &(i32, usize), b: &(i32, usize)| {
600 a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1))
601 });
602 let rendered: usize = draw_order.len();
603 for (_, idx) in draw_order.into_iter() {
604 let ent: &EntityRecord = &world.get_entities()[idx];
605 let Some(sp) = ent.sprite_component() else {
606 continue;
607 };
608 let tr: EntityTransform = ent.get_transform();
609 let pos: Point = tr.get_position();
610 let center: Point = Point::new(
611 (pos.get_x() - cam_x) * zoom + half_w,
612 (pos.get_y() - cam_y) * zoom + half_h,
613 );
614 let w: f32 = sp.get_size().get_width() * tr.get_scale().get_width() * zoom;
615 let h: f32 = sp.get_size().get_height() * tr.get_scale().get_height() * zoom;
616 match sp.get_shape() {
617 EntityVisualShape::Rect => {
618 let rect: Rect =
619 Rect::new(center.get_x() - w * 0.5, center.get_y() - h * 0.5, w, h);
620 self.fill_rounded_rect(rect, sp.get_color(), sp.get_corner_radius() * zoom);
621 if sp.get_accent().get_a() > 0 {
622 self.stroke_rect(rect, 1.5, sp.get_accent());
623 }
624 }
625 EntityVisualShape::Circle => {
626 let r: f32 = (w.min(h) * 0.5).max(1.0);
627 self.fill_circle(center, r, sp.get_color());
628 if sp.get_accent().get_a() > 0 && r > 3.0 {
629 self.fill_circle(center, r * 0.45, sp.get_accent());
630 }
631 }
632 EntityVisualShape::Triangle => {
633 let ang: f32 = tr.get_rotation_rad();
634 let cos_a: f32 = ang.cos();
635 let sin_a: f32 = ang.sin();
636 let rx: f32 = w * 0.55;
637 let ry: f32 = h * 0.48;
638 let nose: Point =
639 Point::new(center.get_x() + cos_a * rx, center.get_y() + sin_a * rx);
640 let left: Point = Point::new(
641 center.get_x() - cos_a * (rx * 0.72) - sin_a * ry,
642 center.get_y() - sin_a * (rx * 0.72) + cos_a * ry,
643 );
644 let right: Point = Point::new(
645 center.get_x() - cos_a * (rx * 0.72) + sin_a * ry,
646 center.get_y() - sin_a * (rx * 0.72) - cos_a * ry,
647 );
648 self.fill_triangle(nose, left, right, sp.get_color());
649 if sp.get_accent().get_a() > 0 {
650 self.fill_circle(center, (w.min(h) * 0.16).max(2.0), sp.get_accent());
651 }
652 }
653 EntityVisualShape::Diamond => {
654 let hw: f32 = w * 0.5;
655 let hh: f32 = h * 0.5;
656 let top: Point = Point::new(center.get_x(), center.get_y() - hh);
657 let right: Point = Point::new(center.get_x() + hw, center.get_y());
658 let bottom: Point = Point::new(center.get_x(), center.get_y() + hh);
659 let left: Point = Point::new(center.get_x() - hw, center.get_y());
660 self.fill_triangle(top, right, bottom, sp.get_color());
661 self.fill_triangle(top, bottom, left, sp.get_color());
662 if sp.get_accent().get_a() > 0 {
663 self.fill_circle(center, (w.min(h) * 0.18).max(2.0), sp.get_accent());
664 }
665 }
666 }
667 }
668 rendered
669 }
670
671 pub fn render_snapshot_world(
683 &mut self,
684 world: &GameWorld,
685 snapshot: &World2DSnapshot,
686 ) -> usize {
687 let camera: Camera2D = snapshot.get_camera();
688 let vp: Size = self.viewport_size();
689 let vis: Rect = camera.visible_world_rect(vp);
690 let (cam_x, cam_y, zoom, half_w, half_h): (f32, f32, f32, f32, f32) =
691 camera.projection_params(vp);
692 let poses: &[EntityPose2D] = snapshot.get_entities().as_slice();
693 let records: &[EntityRecord] = world.get_entities().as_slice();
694 let mut stack_order: [(i32, usize); 128] = [(0, 0); 128];
695 let mut stack_len: usize = 0;
696 let mut heap_order: Vec<(i32, usize)> = Vec::new();
697 for (idx, pose) in poses.iter().enumerate() {
698 if !pose.get_alive() {
699 continue;
700 }
701 let Some(ent) = records.get(idx) else {
702 continue;
703 };
704 if ent.get_id() != pose.get_id() {
705 continue;
706 }
707 let Some(sp) = ent.sprite_component() else {
708 continue;
709 };
710 if !sp.get_visible() {
711 continue;
712 }
713 let tr: EntityTransform = pose.get_transform();
714 let pos: Point = tr.get_position();
715 let bw: f32 = sp.get_size().get_width() * tr.get_scale().get_width();
716 let bh: f32 = sp.get_size().get_height() * tr.get_scale().get_height();
717 let bounds: Rect = Rect::new(pos.get_x() - bw * 0.5, pos.get_y() - bh * 0.5, bw, bh);
718 if bounds.intersect(vis).is_none() {
719 continue;
720 }
721 let item: (i32, usize) = (sp.get_z_order(), idx);
722 if heap_order.is_empty() && stack_len < stack_order.len() {
723 stack_order[stack_len] = item;
724 stack_len += 1;
725 } else {
726 if heap_order.is_empty() {
727 heap_order.reserve(poses.len());
728 heap_order.extend_from_slice(&stack_order[..stack_len]);
729 }
730 heap_order.push(item);
731 }
732 }
733 let order_slice: &mut [(i32, usize)] = if heap_order.is_empty() {
734 &mut stack_order[..stack_len]
735 } else {
736 heap_order.as_mut_slice()
737 };
738 order_slice.sort_unstable_by(|a: &(i32, usize), b: &(i32, usize)| {
739 a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1))
740 });
741 let rendered: usize = order_slice.len();
742 for &(_, idx) in order_slice.iter() {
743 let ent: &EntityRecord = &records[idx];
744 let Some(sp) = ent.sprite_component() else {
745 continue;
746 };
747 let tr: EntityTransform = poses[idx].get_transform();
748 let pos: Point = tr.get_position();
749 let center: Point = Point::new(
750 (pos.get_x() - cam_x) * zoom + half_w,
751 (pos.get_y() - cam_y) * zoom + half_h,
752 );
753 let w: f32 = sp.get_size().get_width() * tr.get_scale().get_width() * zoom;
754 let h: f32 = sp.get_size().get_height() * tr.get_scale().get_height() * zoom;
755 match sp.get_shape() {
756 EntityVisualShape::Rect => {
757 let rect: Rect =
758 Rect::new(center.get_x() - w * 0.5, center.get_y() - h * 0.5, w, h);
759 self.fill_rounded_rect(rect, sp.get_color(), sp.get_corner_radius() * zoom);
760 if sp.get_accent().get_a() > 0 {
761 self.stroke_rect(rect, 1.5, sp.get_accent());
762 }
763 }
764 EntityVisualShape::Circle => {
765 let r: f32 = (w.min(h) * 0.5).max(1.0);
766 self.fill_circle(center, r, sp.get_color());
767 if sp.get_accent().get_a() > 0 && r > 3.0 {
768 self.fill_circle(center, r * 0.45, sp.get_accent());
769 }
770 }
771 EntityVisualShape::Triangle => {
772 let ang: f32 = tr.get_rotation_rad();
773 let cos_a: f32 = ang.cos();
774 let sin_a: f32 = ang.sin();
775 let rx: f32 = w * 0.55;
776 let ry: f32 = h * 0.48;
777 let nose: Point =
778 Point::new(center.get_x() + cos_a * rx, center.get_y() + sin_a * rx);
779 let left: Point = Point::new(
780 center.get_x() - cos_a * (rx * 0.72) - sin_a * ry,
781 center.get_y() - sin_a * (rx * 0.72) + cos_a * ry,
782 );
783 let right: Point = Point::new(
784 center.get_x() - cos_a * (rx * 0.72) + sin_a * ry,
785 center.get_y() - sin_a * (rx * 0.72) - cos_a * ry,
786 );
787 self.fill_triangle(nose, left, right, sp.get_color());
788 if sp.get_accent().get_a() > 0 {
789 self.fill_circle(center, (w.min(h) * 0.16).max(2.0), sp.get_accent());
790 }
791 }
792 EntityVisualShape::Diamond => {
793 let hw: f32 = w * 0.5;
794 let hh: f32 = h * 0.5;
795 let top: Point = Point::new(center.get_x(), center.get_y() - hh);
796 let right: Point = Point::new(center.get_x() + hw, center.get_y());
797 let bottom: Point = Point::new(center.get_x(), center.get_y() + hh);
798 let left: Point = Point::new(center.get_x() - hw, center.get_y());
799 self.fill_triangle(top, right, bottom, sp.get_color());
800 self.fill_triangle(top, bottom, left, sp.get_color());
801 if sp.get_accent().get_a() > 0 {
802 self.fill_circle(center, (w.min(h) * 0.18).max(2.0), sp.get_accent());
803 }
804 }
805 }
806 }
807 rendered
808 }
809
810 pub fn render_interpolated_world(
824 &mut self,
825 world: &GameWorld,
826 prev: &World2DSnapshot,
827 curr: &World2DSnapshot,
828 alpha: f32,
829 ) -> usize {
830 let interp: World2DSnapshot = prev.interpolate(curr, alpha);
831 self.render_snapshot_world(world, &interp)
832 }
833
834 pub fn render_particles(&mut self, particles: &ParticleSystem, camera: &Camera2D) -> usize {
846 let vp: Size = self.viewport_size();
847 let vis: Rect = camera.visible_world_rect(vp);
848 let (cam_x, cam_y, zoom, half_w, half_h): (f32, f32, f32, f32, f32) =
849 camera.projection_params(vp);
850 let n: usize = particles.get_active_count();
851 let mut count: usize = 0;
852 for i in 0..n {
853 let pos: Point = Point::new(particles.pos_x[i], particles.pos_y[i]);
854 if !vis.contains(pos) {
855 continue;
856 }
857 let t: f32 = (particles.age[i] / particles.lifetime[i].max(0.001)).clamp(0.0, 1.0);
858 let s0: f32 = particles.start_size[i];
859 let s1: f32 = particles.end_size[i];
860 let r: f32 = ((s0 + (s1 - s0) * t) * zoom).max(0.8);
861 let col: Color = particles.start_color[i].lerp(particles.end_color[i], t);
862 if col.get_a() == 0 {
863 continue;
864 }
865 let screen: Point = Point::new(
866 (pos.get_x() - cam_x) * zoom + half_w,
867 (pos.get_y() - cam_y) * zoom + half_h,
868 );
869 self.fill_circle(screen, r, col);
870 count += 1;
871 }
872 count
873 }
874
875 pub fn draw_debug_colliders(&mut self, world: &GameWorld, camera: &Camera2D) {
883 let vp: Size = self.viewport_size();
884 let vis: Rect = camera.visible_world_rect(vp);
885 let (cam_x, cam_y, zoom, half_w, half_h): (f32, f32, f32, f32, f32) =
886 camera.projection_params(vp);
887 for ent in world.get_entities().iter() {
888 if !ent.get_alive() {
889 continue;
890 }
891 let Some(col) = ent.collider_component() else {
892 continue;
893 };
894 let aabb: Rect = col.world_aabb(ent.get_transform().get_position());
895 if aabb.intersect(vis).is_none() {
896 continue;
897 }
898 let tl_x: f32 = (aabb.get_x() - cam_x) * zoom + half_w;
899 let tl_y: f32 = (aabb.get_y() - cam_y) * zoom + half_h;
900 let color: Color = if col.get_is_trigger() {
901 Color::rgba(250, 204, 21, 180)
902 } else {
903 Color::rgba(34, 197, 94, 180)
904 };
905 self.stroke_rect(
906 Rect::new(
907 tl_x,
908 tl_y,
909 aabb.get_width() * zoom,
910 aabb.get_height() * zoom,
911 ),
912 1.0,
913 color,
914 );
915 }
916 }
917}
918
919impl GameEngineHost {
921 #[must_use]
932 pub fn new<S>(scene: S, fixed_dt: f32) -> Self
933 where
934 S: GameScene + 'static,
935 {
936 Self {
937 clock: Rc::new(RefCell::new(FrameClock::new(fixed_dt, 8))),
938 input: Rc::new(RefCell::new(InputState::new())),
939 scene: Rc::new(RefCell::new(scene)),
940 viewport_nodes: Rc::new(RefCell::new(Vec::new())),
941 last_gpu_composite: Rc::new(RefCell::new(None)),
942 paused: Rc::new(Cell::new(false)),
943 }
944 }
945
946 #[must_use]
956 pub fn last_gpu_composite(&self) -> Option<GpuCompositeDescriptor> {
957 self.get_last_gpu_composite()
958 .try_borrow()
959 .ok()
960 .and_then(|g: Ref<'_, Option<GpuCompositeDescriptor>>| *g)
961 }
962
963 #[must_use]
973 pub fn take_last_gpu_composite(&self) -> Option<GpuCompositeDescriptor> {
974 self.get_last_gpu_composite()
975 .try_borrow_mut()
976 .ok()
977 .and_then(|mut g: RefMut<'_, Option<GpuCompositeDescriptor>>| g.take())
978 }
979
980 pub fn set_paused(&self, paused: bool) {
987 self.get_paused().set(paused);
988 }
989
990 #[must_use]
1000 pub fn is_paused(&self) -> bool {
1001 self.get_paused().get()
1002 }
1003
1004 #[must_use]
1015 pub fn active_viewport_bounds(&self, tree: &SceneTree) -> Vec<Rect> {
1016 let mut rects: Vec<Rect> = Vec::new();
1017 let _: bool = self.collect_active_viewport_bounds(tree, &mut rects);
1018 rects
1019 }
1020
1021 pub fn collect_active_viewport_bounds(&self, tree: &SceneTree, out: &mut Vec<Rect>) -> bool {
1033 if self.is_paused() {
1034 return false;
1035 }
1036 let start_len: usize = out.len();
1037 if let Ok(mut nodes) = self.get_viewport_nodes().try_borrow_mut() {
1038 nodes.retain(|(_, id): &(SceneHandle, NodeId)| tree.get_node(*id).is_some());
1039 for (_, id) in nodes.iter() {
1040 if tree.is_node_visible(*id)
1041 && let Some(bounds) = tree.node_screen_bounds(*id)
1042 && bounds.get_width() > 0.0
1043 && bounds.get_height() > 0.0
1044 {
1045 out.push(bounds);
1046 }
1047 }
1048 }
1049 out.len() > start_len
1050 }
1051
1052 pub fn ingest_event(&self, event: &WindowEvent) {
1059 if let Ok(mut input) = self.get_input().try_borrow_mut() {
1060 input.ingest(event);
1061 }
1062 }
1063
1064 pub fn step_ns(&self, dt_ns: u64) -> u32 {
1075 if self.is_paused() {
1076 return 0;
1077 }
1078 let (steps, fixed_dt, dt_secs): (u32, f32, f32) = match self.get_clock().try_borrow_mut() {
1079 Ok(mut clock) => {
1080 let s: u32 = clock.tick_ns(dt_ns);
1081 (s, clock.get_fixed_dt(), clock.get_delta_secs())
1082 }
1083 Err(_) => (0, 1.0 / 60.0, ((dt_ns as f64) / 1_000_000_000.0) as f32),
1084 };
1085 self.dispatch_step_with_counts(steps, fixed_dt, dt_secs);
1086 self.mark_viewports_dirty();
1087 steps
1088 }
1089
1090 pub fn step_decoupled_ns(&self, present_dt_ns: u64) -> SimPresentFrame {
1101 if self.is_paused() {
1102 let alpha: f32 = self
1103 .get_clock()
1104 .try_borrow()
1105 .map(|c: Ref<'_, FrameClock>| c.get_alpha())
1106 .unwrap_or(0.0);
1107 let fixed_dt: f32 = self
1108 .get_clock()
1109 .try_borrow()
1110 .map(|c: Ref<'_, FrameClock>| c.get_fixed_dt())
1111 .unwrap_or(1.0 / 60.0);
1112 return SimPresentFrame::new(0, alpha, fixed_dt, 0.0, true, false);
1113 }
1114 let (steps, fixed_dt, dt_secs, alpha, hit_clamp): (u32, f32, f32, f32, bool) =
1115 match self.get_clock().try_borrow_mut() {
1116 Ok(mut clock) => {
1117 let fixed_ns: u64 = clock.get_fixed_step_ns().max(CLOCK_MIN_FIXED_STEP_NS);
1118 let max_sub: u32 = clock.get_max_substeps().max(1);
1119 let pre_acc: u64 = clock.get_accumulator_ns();
1120 let clamped_ns: u64 = present_dt_ns.min(CLOCK_MAX_FRAME_DT_NS);
1121 let uncapped: u64 = pre_acc.saturating_add(clamped_ns) / fixed_ns;
1122 let clamped: bool =
1123 present_dt_ns > CLOCK_MAX_FRAME_DT_NS || uncapped > (max_sub as u64);
1124 let s: u32 = clock.tick_ns(present_dt_ns);
1125 (
1126 s,
1127 clock.get_fixed_dt(),
1128 clock.get_delta_secs(),
1129 clock.get_alpha(),
1130 clamped,
1131 )
1132 }
1133 Err(_) => (
1134 0,
1135 1.0 / 60.0,
1136 ((present_dt_ns as f64) / CLOCK_NS_PER_SEC_F64) as f32,
1137 0.0,
1138 false,
1139 ),
1140 };
1141 self.dispatch_step_with_counts(steps, fixed_dt, dt_secs);
1142 self.mark_viewports_dirty();
1143 SimPresentFrame::new(steps, alpha, fixed_dt, dt_secs, steps == 0, hit_clamp)
1144 }
1145
1146 pub fn step(&self, dt_secs: f32) -> u32 {
1157 if self.is_paused() {
1158 return 0;
1159 }
1160 let (steps, fixed_dt): (u32, f32) = match self.get_clock().try_borrow_mut() {
1161 Ok(mut clock) => (clock.tick(dt_secs), clock.get_fixed_dt()),
1162 Err(_) => (0, 1.0 / 60.0),
1163 };
1164 self.dispatch_step_with_counts(steps, fixed_dt, dt_secs);
1165 self.mark_viewports_dirty();
1166 steps
1167 }
1168
1169 fn dispatch_step_with_counts(&self, steps: u32, fixed_dt: f32, dt_secs: f32) {
1178 let Self { scene, .. } = self;
1179 if let Ok(mut game) = scene.try_borrow_mut() {
1180 let input_copy: InputState = self
1181 .get_input()
1182 .try_borrow()
1183 .map(|r: Ref<'_, InputState>| *r)
1184 .unwrap_or_default();
1185 if steps == 0 {
1186 game.update(dt_secs, &input_copy);
1187 } else {
1188 game.fixed_update(fixed_dt, &input_copy);
1189 if let Ok(mut input_mut) = self.get_input().try_borrow_mut() {
1190 input_mut.begin_frame();
1191 }
1192 let cleared: InputState = input_copy.without_edges();
1193 for _ in 1..steps {
1194 game.fixed_update(fixed_dt, &cleared);
1195 }
1196 game.update(dt_secs, &cleared);
1197 }
1198 } else if steps > 0
1199 && let Ok(mut input) = self.get_input().try_borrow_mut()
1200 {
1201 input.begin_frame();
1202 }
1203 }
1204
1205 pub fn mark_viewports_dirty(&self) {
1211 if let Ok(mut nodes) = self.get_viewport_nodes().try_borrow_mut() {
1212 nodes.retain(|(scene_handle, node_id): &(SceneHandle, NodeId)| {
1213 let (alive, visible): (bool, bool) = scene_handle.with_read(
1214 |tree: &SceneTree| -> (bool, bool) {
1215 let exists: bool = tree.get_node(*node_id).is_some();
1216 let vis: bool = exists
1217 && tree.is_node_visible(*node_id)
1218 && tree
1219 .node_screen_bounds(*node_id)
1220 .is_some_and(|b: Rect| b.get_width() > 0.0 && b.get_height() > 0.0);
1221 (exists, vis)
1222 },
1223 (false, false),
1224 );
1225 if visible {
1226 scene_handle.mark_dirty(*node_id, DIRTY_PAINT);
1227 }
1228 alive
1229 });
1230 }
1231 }
1232
1233 pub fn step_paced(&self, decision: &PacingDecision) -> u32 {
1244 match decision.get_action() {
1245 PacingAction::StepAndRender => self.step_ns(decision.get_sim_dt_ns()),
1246 PacingAction::RenderWithoutSimAdvance => {
1247 self.mark_viewports_dirty();
1248 0
1249 }
1250 PacingAction::DeferToNextVsync
1251 | PacingAction::WaitInFlight
1252 | PacingAction::SkipUserCap => 0,
1253 }
1254 }
1255
1256 pub fn set_virtual_stick(&self, dx: f32, dy: f32) {
1264 if let Ok(mut input) = self.get_input().try_borrow_mut() {
1265 input.set_virtual_stick(dx, dy);
1266 }
1267 }
1268
1269 pub fn press_key(&self, code: KeyCode) {
1276 self.ingest_event(&WindowEvent::KeyDown(
1277 WindowId::new(1),
1278 KeyEvent::new(code, Modifiers::default(), false),
1279 ));
1280 }
1281
1282 pub fn release_key(&self, code: KeyCode) {
1289 self.ingest_event(&WindowEvent::KeyUp(
1290 WindowId::new(1),
1291 KeyEvent::new(code, Modifiers::default(), false),
1292 ));
1293 }
1294
1295 #[must_use]
1309 pub fn mount_viewport(&self, style: Style) -> NodeId {
1310 let Self {
1311 clock,
1312 scene,
1313 last_gpu_composite,
1314 ..
1315 } = self;
1316 let clock_c: Rc<RefCell<FrameClock>> = clock.clone();
1317 let scene_c: Rc<RefCell<dyn GameScene>> = scene.clone();
1318 let gpu_out_c: Rc<RefCell<Option<GpuCompositeDescriptor>>> = last_gpu_composite.clone();
1319 let mut ctx: Context = current_context();
1320 let node: NodeId = ctx.canvas(
1321 style,
1322 move |bounds: Rect, display_list: &mut DisplayList| {
1323 let alpha: f32 = clock_c
1324 .try_borrow()
1325 .map(|c: Ref<'_, FrameClock>| c.get_alpha())
1326 .unwrap_or(1.0);
1327 if let Ok(mut game) = scene_c.try_borrow_mut() {
1328 let mut render_ctx: GameRenderContext<'_> =
1329 GameRenderContext::new(bounds, display_list);
1330 game.render(alpha, &mut render_ctx);
1331 let gpu_target: Option<GpuCompositeDescriptor> =
1332 render_ctx.take_gpu_composite_target();
1333 if let Ok(mut slot) = gpu_out_c.try_borrow_mut() {
1334 *slot = gpu_target;
1335 }
1336 }
1337 },
1338 );
1339 if let Ok(mut nodes) = self.get_viewport_nodes().try_borrow_mut() {
1340 nodes.retain(|(sh, nid): &(SceneHandle, NodeId)| {
1341 sh.with_read(|tree: &SceneTree| tree.get_node(*nid).is_some(), false)
1342 });
1343 nodes.push((ctx.get_scene().clone(), node));
1344 }
1345 let drag_origin: Rc<RefCell<Option<Point>>> = Rc::new(RefCell::new(None));
1346 let origin_down: Rc<RefCell<Option<Point>>> = drag_origin.clone();
1347 let origin_move: Rc<RefCell<Option<Point>>> = drag_origin.clone();
1348 let origin_up: Rc<RefCell<Option<Point>>> = drag_origin;
1349 let host_move: Self = self.clone();
1350 let host_up: Self = self.clone();
1351 ctx.on_pointer_down(node, move |ev: &UiEvent| {
1352 if let UiEventKind::PointerDown(pt) = ev.get_kind()
1353 && let Ok(mut guard) = origin_down.try_borrow_mut()
1354 {
1355 *guard = Some(*pt);
1356 }
1357 });
1358 ctx.on_pointer_move(node, move |ev: &UiEvent| {
1359 if let UiEventKind::PointerMove(pt) = ev.get_kind()
1360 && let Ok(guard) = origin_move.try_borrow()
1361 && let Some(orig) = *guard
1362 {
1363 let dx: f32 = ((pt.get_x() - orig.get_x()) / 48.0).clamp(-1.0, 1.0);
1364 let dy: f32 = ((pt.get_y() - orig.get_y()) / 48.0).clamp(-1.0, 1.0);
1365 host_move.set_virtual_stick(dx, dy);
1366 }
1367 });
1368 ctx.on_pointer_up(node, move |_: &UiEvent| {
1369 if let Ok(mut guard) = origin_up.try_borrow_mut() {
1370 *guard = None;
1371 }
1372 host_up.set_virtual_stick(0.0, 0.0);
1373 });
1374 node
1375 }
1376}