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]
148 pub fn is_direct_gpu_active(&self) -> bool {
149 let Self { display_list, .. } = self;
150 display_list.get_direct_gpu_scene_enabled()
151 }
152
153 #[must_use]
159 pub fn scene_workload_scale(&self) -> f32 {
160 active_scene_workload_scale()
161 }
162
163 pub fn submit_gpu_scene_pass(&mut self, rect: Rect, pass: DirectGpuScenePass) {
170 let Self {
171 bounds,
172 display_list,
173 ..
174 } = self;
175 let world: Rect = Rect::new(
176 bounds.get_x() + rect.get_x(),
177 bounds.get_y() + rect.get_y(),
178 rect.get_width(),
179 rect.get_height(),
180 );
181 display_list.set_gpu_scene_pass(Some(pass));
182 display_list.push(DrawCommand::ExternalSurface {
183 rect: world,
184 radius: CornerRadius::default(),
185 });
186 }
187
188 #[must_use]
198 pub fn viewport_size(&self) -> Size {
199 let Self { bounds, .. } = self;
200 Size::new(bounds.get_width(), bounds.get_height())
201 }
202
203 #[must_use]
213 pub fn scale_factor(&self) -> f32 {
214 let Self { display_list, .. } = self;
215 let raw: f32 = display_list.get_scale_factor();
216 if raw.is_finite() && raw > 0.0 {
217 raw.clamp(0.5, 6.0)
218 } else {
219 1.0
220 }
221 }
222
223 pub fn clear(&mut self, color: Color) {
230 let Self {
231 bounds,
232 display_list,
233 ..
234 } = self;
235 display_list.push(DrawCommand::FillRoundedRect {
236 rect: *bounds,
237 color,
238 radius: CornerRadius::default(),
239 border: Border::default(),
240 });
241 }
242
243 pub fn fill_rect(&mut self, rect: Rect, color: Color) {
251 self.fill_rounded_rect(rect, color, 0.0);
252 }
253
254 pub fn fill_rounded_rect(&mut self, rect: Rect, color: Color, radius: f32) {
263 let Self {
264 bounds,
265 display_list,
266 ..
267 } = self;
268 let world: Rect = Rect::new(
269 bounds.get_x() + rect.get_x(),
270 bounds.get_y() + rect.get_y(),
271 rect.get_width(),
272 rect.get_height(),
273 );
274 display_list.push(DrawCommand::FillRoundedRect {
275 rect: world,
276 color,
277 radius: CornerRadius::all(radius),
278 border: Border::default(),
279 });
280 }
281
282 pub fn stroke_rect(&mut self, rect: Rect, stroke_width: f32, color: Color) {
291 let Self {
292 bounds,
293 display_list,
294 ..
295 } = self;
296 let world: Rect = Rect::new(
297 bounds.get_x() + rect.get_x(),
298 bounds.get_y() + rect.get_y(),
299 rect.get_width(),
300 rect.get_height(),
301 );
302 display_list.push(DrawCommand::FillRoundedRect {
303 rect: world,
304 color: COLOR_TRANSPARENT,
305 radius: CornerRadius::default(),
306 border: Border::new(stroke_width, color),
307 });
308 }
309
310 pub fn fill_circle(&mut self, center: Point, radius: f32, color: Color) {
319 let Self {
320 bounds,
321 display_list,
322 ..
323 } = self;
324 let world: Point = Point::new(
325 bounds.get_x() + center.get_x(),
326 bounds.get_y() + center.get_y(),
327 );
328 display_list.push(DrawCommand::Circle {
329 center: world,
330 radius,
331 color,
332 });
333 }
334
335 pub fn draw_image(&mut self, rect: Rect, buffer: ImageBuffer) {
343 let Self {
344 bounds,
345 display_list,
346 ..
347 } = self;
348 let world: Rect = Rect::new(
349 bounds.get_x() + rect.get_x(),
350 bounds.get_y() + rect.get_y(),
351 rect.get_width(),
352 rect.get_height(),
353 );
354 display_list.push(DrawCommand::Image {
355 rect: world,
356 buffer,
357 radius: CornerRadius::default(),
358 });
359 }
360
361 pub fn draw_line(&mut self, from: Point, to: Point, width: f32, color: Color) {
371 let Self {
372 bounds,
373 display_list,
374 ..
375 } = self;
376 display_list.push(DrawCommand::Line {
377 from: Point::new(bounds.get_x() + from.get_x(), bounds.get_y() + from.get_y()),
378 to: Point::new(bounds.get_x() + to.get_x(), bounds.get_y() + to.get_y()),
379 color,
380 width,
381 });
382 }
383
384 pub fn draw_text(&mut self, position: Point, text: String, font_size: f32, color: Color) {
394 let Self {
395 bounds,
396 display_list,
397 ..
398 } = self;
399 let mut style: TextStyle = TextStyle::default();
400 style.set_font_size(font_size);
401 style.set_color(color);
402 display_list.push(DrawCommand::TextRun {
403 rect: Rect::new(
404 bounds.get_x() + position.get_x(),
405 bounds.get_y() + position.get_y(),
406 (bounds.get_width() - position.get_x()).max(0.0),
407 font_size * 1.6,
408 ),
409 text,
410 style,
411 });
412 }
413
414 pub fn draw_text_str(&mut self, position: Point, text: &str, font_size: f32, color: Color) {
424 let Self {
425 bounds,
426 display_list,
427 ..
428 } = self;
429 let pooled: String = display_list.alloc_text(text);
430 let mut style: TextStyle = TextStyle::default();
431 style.set_font_size(font_size);
432 style.set_color(color);
433 display_list.push(DrawCommand::TextRun {
434 rect: Rect::new(
435 bounds.get_x() + position.get_x(),
436 bounds.get_y() + position.get_y(),
437 (bounds.get_width() - position.get_x()).max(0.0),
438 font_size * 1.6,
439 ),
440 text: pooled,
441 style,
442 });
443 }
444
445 pub fn blit_framebuffer(&mut self, rect: Rect, buffer: ImageBuffer) {
453 let Self {
454 bounds,
455 display_list,
456 ..
457 } = self;
458 let world: Rect = Rect::new(
459 bounds.get_x() + rect.get_x(),
460 bounds.get_y() + rect.get_y(),
461 rect.get_width(),
462 rect.get_height(),
463 );
464 display_list.push(DrawCommand::Image {
465 rect: world,
466 buffer,
467 radius: CornerRadius::default(),
468 });
469 }
470
471 pub fn fill_triangle(&mut self, p0: Point, p1: Point, p2: Point, color: Color) {
481 let Self {
482 bounds,
483 display_list,
484 ..
485 } = self;
486 let ox: f32 = bounds.get_x();
487 let oy: f32 = bounds.get_y();
488 display_list.push(DrawCommand::Triangle {
489 p0: Point::new(ox + p0.get_x(), oy + p0.get_y()),
490 p1: Point::new(ox + p1.get_x(), oy + p1.get_y()),
491 p2: Point::new(ox + p2.get_x(), oy + p2.get_y()),
492 color,
493 });
494 }
495
496 pub fn draw_sprite_frame(
506 &mut self,
507 sheet: &SpriteSheet,
508 frame_index: u32,
509 rect: Rect,
510 tint: Color,
511 ) {
512 let src_rect: Rect = sheet.frame_rect(frame_index);
513 let Self {
514 bounds,
515 display_list,
516 ..
517 } = self;
518 display_list.push(DrawCommand::SpriteRegion {
519 rect: Rect::new(
520 bounds.get_x() + rect.get_x(),
521 bounds.get_y() + rect.get_y(),
522 rect.get_width(),
523 rect.get_height(),
524 ),
525 buffer: sheet.get_texture().clone(),
526 src_rect,
527 tint,
528 });
529 }
530
531 pub fn render_tilemap(&mut self, tilemap: &TileMap, camera: &Camera2D) {
539 let box_size: Size = self.viewport_size();
540 let vis: Rect = camera.visible_world_rect(box_size);
541 let timestamp_val: f32 = tilemap.get_tile_size();
542 let (cam_x, cam_y, zoom, half_w, half_h): (f32, f32, f32, f32, f32) =
543 camera.projection_params(box_size);
544 let min_c: usize = (vis.get_x() / timestamp_val).floor().max(0.0) as usize;
545 let max_c: usize =
546 ((vis.right() / timestamp_val).ceil().max(0.0) as usize).min(tilemap.get_columns());
547 let min_r: usize = (vis.get_y() / timestamp_val).floor().max(0.0) as usize;
548 let max_r: usize =
549 ((vis.bottom() / timestamp_val).ceil().max(0.0) as usize).min(tilemap.get_rows());
550 let tile_px: f32 = (timestamp_val * zoom).max(1.0);
551 if tilemap.has_fresh_chunk_cache() {
552 for chunk in tilemap.cached_chunks().iter() {
553 if chunk.get_max_col() <= min_c
554 || chunk.get_min_col() >= max_c
555 || chunk.get_max_row() <= min_r
556 || chunk.get_min_row() >= max_r
557 {
558 continue;
559 }
560 for run in chunk.get_runs().iter() {
561 let red_val: usize = run.get_row();
562 if red_val < min_r || red_val >= max_r {
563 continue;
564 }
565 let c0: usize = run.get_col().max(min_c);
566 let c1: usize = (run.get_col() + run.get_span_cols()).min(max_c);
567 if c0 >= c1 {
568 continue;
569 }
570 let sx: f32 = ((c0 as f32) * timestamp_val - cam_x) * zoom + half_w;
571 let sy: f32 = ((red_val as f32) * timestamp_val - cam_y) * zoom + half_h;
572 let run_w: f32 = ((c1 - c0) as f32) * tile_px + 0.5;
573 self.fill_rect(Rect::new(sx, sy, run_w, tile_px + 0.5), run.get_color());
574 }
575 }
576 return;
577 }
578 let palette: &[TilePaletteEntry] = tilemap.get_palette().as_slice();
579 for row in min_r..max_r {
580 let sy: f32 = ((row as f32) * timestamp_val - cam_y) * zoom + half_h;
581 let mut col: usize = min_c;
582 while col < max_c {
583 let tid: u16 = tilemap.tile_at(col, row);
584 if tid == 0 {
585 col += 1;
586 continue;
587 }
588 let Some(entry) = palette.get(tid as usize) else {
589 col += 1;
590 continue;
591 };
592 let color: Color = entry.get_color();
593 let start_col: usize = col;
594 col += 1;
595 while col < max_c {
596 let next_tid: u16 = tilemap.tile_at(col, row);
597 if next_tid == 0 {
598 break;
599 }
600 let same_color: bool = palette
601 .get(next_tid as usize)
602 .is_some_and(|event_ref: &TilePaletteEntry| event_ref.get_color() == color);
603 if !same_color {
604 break;
605 }
606 col += 1;
607 }
608 let sx: f32 = ((start_col as f32) * timestamp_val - cam_x) * zoom + half_w;
609 let run_w: f32 = ((col - start_col) as f32) * tile_px + 0.5;
610 self.fill_rect(Rect::new(sx, sy, run_w, tile_px + 0.5), color);
611 }
612 }
613 }
614
615 pub fn render_world(&mut self, world: &GameWorld, camera: &Camera2D) -> usize {
627 let box_size: Size = self.viewport_size();
628 let vis: Rect = camera.visible_world_rect(box_size);
629 let (cam_x, cam_y, zoom, half_w, half_h): (f32, f32, f32, f32, f32) =
630 camera.projection_params(box_size);
631 let mut draw_order: Vec<(i32, usize)> = Vec::with_capacity(world.get_live_count());
632 for (idx, ent) in world.get_entities().iter().enumerate() {
633 if !ent.get_alive() {
634 continue;
635 }
636 let Some(sp) = ent.sprite_component() else {
637 continue;
638 };
639 if !sp.get_visible() {
640 continue;
641 }
642 if ent.world_bounds().intersect(vis).is_none() {
643 continue;
644 }
645 draw_order.push((sp.get_z_order(), idx));
646 }
647 draw_order.sort_by(|alpha_val: &(i32, usize), blue_val: &(i32, usize)| {
648 alpha_val
649 .0
650 .cmp(&blue_val.0)
651 .then_with(|| alpha_val.1.cmp(&blue_val.1))
652 });
653 let rendered: usize = draw_order.len();
654 for (_, idx) in draw_order.into_iter() {
655 let ent: &EntityRecord = &world.get_entities()[idx];
656 let Some(sp) = ent.sprite_component() else {
657 continue;
658 };
659 let transform_val: EntityTransform = ent.get_transform();
660 let pos: Point = transform_val.get_position();
661 let center: Point = Point::new(
662 (pos.get_x() - cam_x) * zoom + half_w,
663 (pos.get_y() - cam_y) * zoom + half_h,
664 );
665 let width_val: f32 =
666 sp.get_size().get_width() * transform_val.get_scale().get_width() * zoom;
667 let height_val: f32 =
668 sp.get_size().get_height() * transform_val.get_scale().get_height() * zoom;
669 match sp.get_shape() {
670 EntityVisualShape::Rect => {
671 let rect: Rect = Rect::new(
672 center.get_x() - width_val * 0.5,
673 center.get_y() - height_val * 0.5,
674 width_val,
675 height_val,
676 );
677 self.fill_rounded_rect(rect, sp.get_color(), sp.get_corner_radius() * zoom);
678 if sp.get_accent().get_alpha() > 0 {
679 self.stroke_rect(rect, 1.5, sp.get_accent());
680 }
681 }
682 EntityVisualShape::Circle => {
683 let red_val: f32 = (width_val.min(height_val) * 0.5).max(1.0);
684 self.fill_circle(center, red_val, sp.get_color());
685 if sp.get_accent().get_alpha() > 0 && red_val > 3.0 {
686 self.fill_circle(center, red_val * 0.45, sp.get_accent());
687 }
688 }
689 EntityVisualShape::Triangle => {
690 let ang: f32 = transform_val.get_rotation_rad();
691 let cos_a: f32 = ang.cos();
692 let sin_a: f32 = ang.sin();
693 let rx: f32 = width_val * 0.55;
694 let ry: f32 = height_val * 0.48;
695 let nose: Point =
696 Point::new(center.get_x() + cos_a * rx, center.get_y() + sin_a * rx);
697 let left: Point = Point::new(
698 center.get_x() - cos_a * (rx * 0.72) - sin_a * ry,
699 center.get_y() - sin_a * (rx * 0.72) + cos_a * ry,
700 );
701 let right: Point = Point::new(
702 center.get_x() - cos_a * (rx * 0.72) + sin_a * ry,
703 center.get_y() - sin_a * (rx * 0.72) - cos_a * ry,
704 );
705 self.fill_triangle(nose, left, right, sp.get_color());
706 if sp.get_accent().get_alpha() > 0 {
707 self.fill_circle(
708 center,
709 (width_val.min(height_val) * 0.16).max(2.0),
710 sp.get_accent(),
711 );
712 }
713 }
714 EntityVisualShape::Diamond => {
715 let hw: f32 = width_val * 0.5;
716 let hh: f32 = height_val * 0.5;
717 let top: Point = Point::new(center.get_x(), center.get_y() - hh);
718 let right: Point = Point::new(center.get_x() + hw, center.get_y());
719 let bottom: Point = Point::new(center.get_x(), center.get_y() + hh);
720 let left: Point = Point::new(center.get_x() - hw, center.get_y());
721 self.fill_triangle(top, right, bottom, sp.get_color());
722 self.fill_triangle(top, bottom, left, sp.get_color());
723 if sp.get_accent().get_alpha() > 0 {
724 self.fill_circle(
725 center,
726 (width_val.min(height_val) * 0.18).max(2.0),
727 sp.get_accent(),
728 );
729 }
730 }
731 }
732 }
733 rendered
734 }
735
736 pub fn render_snapshot_world(
748 &mut self,
749 world: &GameWorld,
750 snapshot: &World2DSnapshot,
751 ) -> usize {
752 let camera: Camera2D = snapshot.get_camera();
753 let box_size: Size = self.viewport_size();
754 let vis: Rect = camera.visible_world_rect(box_size);
755 let (cam_x, cam_y, zoom, half_w, half_h): (f32, f32, f32, f32, f32) =
756 camera.projection_params(box_size);
757 let poses: &[EntityPose2D] = snapshot.get_entities().as_slice();
758 let records: &[EntityRecord] = world.get_entities().as_slice();
759 let mut stack_order: [(i32, usize); 128] = [(0, 0); 128];
760 let mut stack_len: usize = 0;
761 let mut heap_order: Vec<(i32, usize)> = Vec::new();
762 for (idx, pose) in poses.iter().enumerate() {
763 if !pose.get_alive() {
764 continue;
765 }
766 let Some(ent) = records.get(idx) else {
767 continue;
768 };
769 if ent.get_id() != pose.get_id() {
770 continue;
771 }
772 let Some(sp) = ent.sprite_component() else {
773 continue;
774 };
775 if !sp.get_visible() {
776 continue;
777 }
778 let transform_val: EntityTransform = pose.get_transform();
779 let pos: Point = transform_val.get_position();
780 let border_width: f32 =
781 sp.get_size().get_width() * transform_val.get_scale().get_width();
782 let bh: f32 = sp.get_size().get_height() * transform_val.get_scale().get_height();
783 let bounds: Rect = Rect::new(
784 pos.get_x() - border_width * 0.5,
785 pos.get_y() - bh * 0.5,
786 border_width,
787 bh,
788 );
789 if bounds.intersect(vis).is_none() {
790 continue;
791 }
792 let item: (i32, usize) = (sp.get_z_order(), idx);
793 if heap_order.is_empty() && stack_len < stack_order.len() {
794 stack_order[stack_len] = item;
795 stack_len += 1;
796 } else {
797 if heap_order.is_empty() {
798 heap_order.reserve(poses.len());
799 heap_order.extend_from_slice(&stack_order[..stack_len]);
800 }
801 heap_order.push(item);
802 }
803 }
804 let order_slice: &mut [(i32, usize)] = if heap_order.is_empty() {
805 &mut stack_order[..stack_len]
806 } else {
807 heap_order.as_mut_slice()
808 };
809 order_slice.sort_unstable_by(|alpha_val: &(i32, usize), blue_val: &(i32, usize)| {
810 alpha_val
811 .0
812 .cmp(&blue_val.0)
813 .then_with(|| alpha_val.1.cmp(&blue_val.1))
814 });
815 let rendered: usize = order_slice.len();
816 for &(_, idx) in order_slice.iter() {
817 let ent: &EntityRecord = &records[idx];
818 let Some(sp) = ent.sprite_component() else {
819 continue;
820 };
821 let object_transform: EntityTransform = poses[idx].get_transform();
822 let pos: Point = object_transform.get_position();
823 let center: Point = Point::new(
824 (pos.get_x() - cam_x) * zoom + half_w,
825 (pos.get_y() - cam_y) * zoom + half_h,
826 );
827 let width_val: f32 =
828 sp.get_size().get_width() * object_transform.get_scale().get_width() * zoom;
829 let height_val: f32 =
830 sp.get_size().get_height() * object_transform.get_scale().get_height() * zoom;
831 match sp.get_shape() {
832 EntityVisualShape::Rect => {
833 let rect: Rect = Rect::new(
834 center.get_x() - width_val * 0.5,
835 center.get_y() - height_val * 0.5,
836 width_val,
837 height_val,
838 );
839 self.fill_rounded_rect(rect, sp.get_color(), sp.get_corner_radius() * zoom);
840 if sp.get_accent().get_alpha() > 0 {
841 self.stroke_rect(rect, 1.5, sp.get_accent());
842 }
843 }
844 EntityVisualShape::Circle => {
845 let red_val: f32 = (width_val.min(height_val) * 0.5).max(1.0);
846 self.fill_circle(center, red_val, sp.get_color());
847 if sp.get_accent().get_alpha() > 0 && red_val > 3.0 {
848 self.fill_circle(center, red_val * 0.45, sp.get_accent());
849 }
850 }
851 EntityVisualShape::Triangle => {
852 let ang: f32 = object_transform.get_rotation_rad();
853 let cos_a: f32 = ang.cos();
854 let sin_a: f32 = ang.sin();
855 let rx: f32 = width_val * 0.55;
856 let ry: f32 = height_val * 0.48;
857 let nose: Point =
858 Point::new(center.get_x() + cos_a * rx, center.get_y() + sin_a * rx);
859 let left: Point = Point::new(
860 center.get_x() - cos_a * (rx * 0.72) - sin_a * ry,
861 center.get_y() - sin_a * (rx * 0.72) + cos_a * ry,
862 );
863 let right: Point = Point::new(
864 center.get_x() - cos_a * (rx * 0.72) + sin_a * ry,
865 center.get_y() - sin_a * (rx * 0.72) - cos_a * ry,
866 );
867 self.fill_triangle(nose, left, right, sp.get_color());
868 if sp.get_accent().get_alpha() > 0 {
869 self.fill_circle(
870 center,
871 (width_val.min(height_val) * 0.16).max(2.0),
872 sp.get_accent(),
873 );
874 }
875 }
876 EntityVisualShape::Diamond => {
877 let hw: f32 = width_val * 0.5;
878 let hh: f32 = height_val * 0.5;
879 let top: Point = Point::new(center.get_x(), center.get_y() - hh);
880 let right: Point = Point::new(center.get_x() + hw, center.get_y());
881 let bottom: Point = Point::new(center.get_x(), center.get_y() + hh);
882 let left: Point = Point::new(center.get_x() - hw, center.get_y());
883 self.fill_triangle(top, right, bottom, sp.get_color());
884 self.fill_triangle(top, bottom, left, sp.get_color());
885 if sp.get_accent().get_alpha() > 0 {
886 self.fill_circle(
887 center,
888 (width_val.min(height_val) * 0.18).max(2.0),
889 sp.get_accent(),
890 );
891 }
892 }
893 }
894 }
895 rendered
896 }
897
898 pub fn render_interpolated_world(
912 &mut self,
913 world: &GameWorld,
914 prev: &World2DSnapshot,
915 curr: &World2DSnapshot,
916 alpha: f32,
917 ) -> usize {
918 let interp: World2DSnapshot = prev.interpolate(curr, alpha);
919 self.render_snapshot_world(world, &interp)
920 }
921
922 pub fn render_particles(&mut self, particles: &ParticleSystem, camera: &Camera2D) -> usize {
934 let box_size: Size = self.viewport_size();
935 let vis: Rect = camera.visible_world_rect(box_size);
936 let (cam_x, cam_y, zoom, half_w, half_h): (f32, f32, f32, f32, f32) =
937 camera.projection_params(box_size);
938 let item_count: usize = particles.get_active_count();
939 let mut count: usize = 0;
940 for item_index in 0..item_count {
941 let pos: Point = Point::new(particles.pos_x[item_index], particles.pos_y[item_index]);
942 if !vis.contains(pos) {
943 continue;
944 }
945 let blend_factor: f32 = (particles.age[item_index]
946 / particles.lifetime[item_index].max(0.001))
947 .clamp(0.0, 1.0);
948 let s0: f32 = particles.start_size[item_index];
949 let s1: f32 = particles.end_size[item_index];
950 let red_val: f32 = ((s0 + (s1 - s0) * blend_factor) * zoom).max(0.8);
951 let col: Color = particles.start_color[item_index]
952 .lerp(particles.end_color[item_index], blend_factor);
953 if col.get_alpha() == 0 {
954 continue;
955 }
956 let screen: Point = Point::new(
957 (pos.get_x() - cam_x) * zoom + half_w,
958 (pos.get_y() - cam_y) * zoom + half_h,
959 );
960 self.fill_circle(screen, red_val, col);
961 count += 1;
962 }
963 count
964 }
965
966 pub fn draw_debug_colliders(&mut self, world: &GameWorld, camera: &Camera2D) {
974 let box_size: Size = self.viewport_size();
975 let vis: Rect = camera.visible_world_rect(box_size);
976 let (cam_x, cam_y, zoom, half_w, half_h): (f32, f32, f32, f32, f32) =
977 camera.projection_params(box_size);
978 for ent in world.get_entities().iter() {
979 if !ent.get_alive() {
980 continue;
981 }
982 let Some(col) = ent.collider_component() else {
983 continue;
984 };
985 let bounds_rect: Rect = col.world_bounds(ent.get_transform().get_position());
986 if bounds_rect.intersect(vis).is_none() {
987 continue;
988 }
989 let tl_x: f32 = (bounds_rect.get_x() - cam_x) * zoom + half_w;
990 let tl_y: f32 = (bounds_rect.get_y() - cam_y) * zoom + half_h;
991 let color: Color = if col.get_is_trigger() {
992 Color::rgba(250, 204, 21, 180)
993 } else {
994 Color::rgba(34, 197, 94, 180)
995 };
996 self.stroke_rect(
997 Rect::new(
998 tl_x,
999 tl_y,
1000 bounds_rect.get_width() * zoom,
1001 bounds_rect.get_height() * zoom,
1002 ),
1003 1.0,
1004 color,
1005 );
1006 }
1007 }
1008}
1009
1010impl GameEngineHost {
1012 #[must_use]
1023 pub fn new<TextValue>(scene: TextValue, fixed_dt: f32) -> Self
1024 where
1025 TextValue: GameScene + 'static,
1026 {
1027 Self {
1028 clock: Rc::new(RefCell::new(FrameClock::new(fixed_dt, 8))),
1029 input: Rc::new(RefCell::new(InputState::new())),
1030 scene: Rc::new(RefCell::new(scene)),
1031 viewport_nodes: Rc::new(RefCell::new(Vec::new())),
1032 last_gpu_composite: Rc::new(RefCell::new(None)),
1033 paused: Rc::new(Cell::new(false)),
1034 }
1035 }
1036
1037 #[must_use]
1047 pub fn last_gpu_composite(&self) -> Option<GpuCompositeDescriptor> {
1048 self.get_last_gpu_composite()
1049 .try_borrow()
1050 .ok()
1051 .and_then(|green_val: Ref<'_, Option<GpuCompositeDescriptor>>| *green_val)
1052 }
1053
1054 #[must_use]
1064 pub fn take_last_gpu_composite(&self) -> Option<GpuCompositeDescriptor> {
1065 self.get_last_gpu_composite()
1066 .try_borrow_mut()
1067 .ok()
1068 .and_then(|mut green_val: RefMut<'_, Option<GpuCompositeDescriptor>>| green_val.take())
1069 }
1070
1071 pub fn set_paused(&self, paused: bool) {
1078 self.get_paused().set(paused);
1079 }
1080
1081 #[must_use]
1091 pub fn is_paused(&self) -> bool {
1092 self.get_paused().get()
1093 }
1094
1095 #[must_use]
1106 pub fn active_viewport_bounds(&self, tree: &SceneTree) -> Vec<Rect> {
1107 let mut rects: Vec<Rect> = Vec::new();
1108 let _: bool = self.collect_active_viewport_bounds(tree, &mut rects);
1109 rects
1110 }
1111
1112 pub fn collect_active_viewport_bounds(&self, tree: &SceneTree, out: &mut Vec<Rect>) -> bool {
1124 if self.is_paused() {
1125 return false;
1126 }
1127 let start_len: usize = out.len();
1128 if let Ok(mut nodes) = self.get_viewport_nodes().try_borrow_mut() {
1129 nodes.retain(|(_, id): &(SceneHandle, NodeId)| tree.get_node(*id).is_some());
1130 for (_, id) in nodes.iter() {
1131 if tree.is_node_visible(*id)
1132 && let Some(bounds) = tree.node_screen_bounds(*id)
1133 && bounds.get_width() > 0.0
1134 && bounds.get_height() > 0.0
1135 {
1136 out.push(bounds);
1137 }
1138 }
1139 }
1140 out.len() > start_len
1141 }
1142
1143 pub fn ingest_event(&self, event: &WindowEvent) {
1150 if self.is_paused() {
1151 return;
1152 }
1153 if let Ok(mut input) = self.get_input().try_borrow_mut() {
1154 input.ingest(event);
1155 }
1156 }
1157
1158 pub fn step_ns(&self, dt_ns: u64) -> u32 {
1169 if self.is_paused() {
1170 return 0;
1171 }
1172 let (steps, fixed_dt, dt_secs): (u32, f32, f32) = match self.get_clock().try_borrow_mut() {
1173 Ok(mut clock) => {
1174 let source_val: u32 = clock.tick_ns(dt_ns);
1175 (source_val, clock.get_fixed_dt(), clock.get_delta_secs())
1176 }
1177 Err(_) => (0, 1.0 / 60.0, ((dt_ns as f64) / 1_000_000_000.0) as f32),
1178 };
1179 self.dispatch_step_with_counts(steps, fixed_dt, dt_secs);
1180 self.mark_viewports_dirty();
1181 steps
1182 }
1183
1184 pub fn step_decoupled_ns(&self, present_dt_ns: u64) -> SimPresentFrame {
1195 if self.is_paused() {
1196 let alpha: f32 = self
1197 .get_clock()
1198 .try_borrow()
1199 .map(|char_item: Ref<'_, FrameClock>| char_item.get_alpha())
1200 .unwrap_or(0.0);
1201 let fixed_dt: f32 = self
1202 .get_clock()
1203 .try_borrow()
1204 .map(|color_item: Ref<'_, FrameClock>| color_item.get_fixed_dt())
1205 .unwrap_or(1.0 / 60.0);
1206 return SimPresentFrame::new(0, alpha, fixed_dt, 0.0, true, false);
1207 }
1208 let (steps, fixed_dt, dt_secs, alpha, hit_clamp): (u32, f32, f32, f32, bool) =
1209 match self.get_clock().try_borrow_mut() {
1210 Ok(mut clock) => {
1211 let fixed_ns: u64 = clock.get_fixed_step_ns().max(CLOCK_MIN_FIXED_STEP_NS);
1212 let max_sub: u32 = clock.get_max_substeps().max(1);
1213 let pre_acc: u64 = clock.get_accumulator_ns();
1214 let clamped_ns: u64 = present_dt_ns.min(CLOCK_MAX_FRAME_DT_NS);
1215 let uncapped: u64 = pre_acc.saturating_add(clamped_ns) / fixed_ns;
1216 let clamped: bool =
1217 present_dt_ns > CLOCK_MAX_FRAME_DT_NS || uncapped > (max_sub as u64);
1218 let source_val: u32 = clock.tick_ns(present_dt_ns);
1219 (
1220 source_val,
1221 clock.get_fixed_dt(),
1222 clock.get_delta_secs(),
1223 clock.get_alpha(),
1224 clamped,
1225 )
1226 }
1227 Err(_) => (
1228 0,
1229 1.0 / 60.0,
1230 ((present_dt_ns as f64) / CLOCK_NS_PER_SEC_F64) as f32,
1231 0.0,
1232 false,
1233 ),
1234 };
1235 self.dispatch_step_with_counts(steps, fixed_dt, dt_secs);
1236 self.mark_viewports_dirty();
1237 SimPresentFrame::new(steps, alpha, fixed_dt, dt_secs, steps == 0, hit_clamp)
1238 }
1239
1240 pub fn step(&self, dt_secs: f32) -> u32 {
1251 if self.is_paused() {
1252 return 0;
1253 }
1254 let (steps, fixed_dt): (u32, f32) = match self.get_clock().try_borrow_mut() {
1255 Ok(mut clock) => (clock.tick(dt_secs), clock.get_fixed_dt()),
1256 Err(_) => (0, 1.0 / 60.0),
1257 };
1258 self.dispatch_step_with_counts(steps, fixed_dt, dt_secs);
1259 self.mark_viewports_dirty();
1260 steps
1261 }
1262
1263 fn dispatch_step_with_counts(&self, steps: u32, fixed_dt: f32, dt_secs: f32) {
1272 let Self { scene, .. } = self;
1273 if let Ok(mut game) = scene.try_borrow_mut() {
1274 let input_copy: InputState = self
1275 .get_input()
1276 .try_borrow()
1277 .map(|red_val: Ref<'_, InputState>| *red_val)
1278 .unwrap_or_default();
1279 if steps == 0 {
1280 game.update(dt_secs, &input_copy);
1281 } else {
1282 game.fixed_update(fixed_dt, &input_copy);
1283 if let Ok(mut input_mut) = self.get_input().try_borrow_mut() {
1284 input_mut.begin_frame();
1285 }
1286 let cleared: InputState = input_copy.without_edges();
1287 for _ in 1..steps {
1288 game.fixed_update(fixed_dt, &cleared);
1289 }
1290 game.update(dt_secs, &cleared);
1291 }
1292 } else if steps > 0
1293 && let Ok(mut input) = self.get_input().try_borrow_mut()
1294 {
1295 input.begin_frame();
1296 }
1297 }
1298
1299 pub fn mark_viewports_dirty(&self) {
1305 if let Ok(mut nodes) = self.get_viewport_nodes().try_borrow_mut() {
1306 nodes.retain(|(scene_handle, node_id): &(SceneHandle, NodeId)| {
1307 let (alive, visible): (bool, bool) = scene_handle.with_read(
1308 |tree: &SceneTree| -> (bool, bool) {
1309 let exists: bool = tree.get_node(*node_id).is_some();
1310 let vis: bool = exists
1311 && tree.is_node_visible(*node_id)
1312 && tree.node_screen_bounds(*node_id).is_some_and(
1313 |rect_bounds: Rect| {
1314 rect_bounds.get_width() > 0.0 && rect_bounds.get_height() > 0.0
1315 },
1316 );
1317 (exists, vis)
1318 },
1319 (false, false),
1320 );
1321 if visible {
1322 scene_handle.mark_dirty(*node_id, DIRTY_PAINT);
1323 }
1324 alive
1325 });
1326 }
1327 }
1328
1329 pub fn step_paced(&self, decision: &PacingDecision) -> u32 {
1340 match decision.get_action() {
1341 PacingAction::StepAndRender => self.step_ns(decision.get_sim_dt_ns()),
1342 PacingAction::RenderWithoutSimAdvance => {
1343 self.mark_viewports_dirty();
1344 0
1345 }
1346 PacingAction::DeferToNextVsync
1347 | PacingAction::WaitInFlight
1348 | PacingAction::SkipUserCap => 0,
1349 }
1350 }
1351
1352 pub fn set_virtual_stick(&self, dx: f32, dy: f32) {
1360 if let Ok(mut input) = self.get_input().try_borrow_mut() {
1361 input.set_virtual_stick(dx, dy);
1362 }
1363 }
1364
1365 pub fn press_key(&self, code: KeyCode) {
1372 self.ingest_event(&WindowEvent::KeyDown(
1373 WindowId::new(1),
1374 KeyEvent::new(code, Modifiers::default(), false),
1375 ));
1376 }
1377
1378 pub fn release_key(&self, code: KeyCode) {
1385 self.ingest_event(&WindowEvent::KeyUp(
1386 WindowId::new(1),
1387 KeyEvent::new(code, Modifiers::default(), false),
1388 ));
1389 }
1390
1391 #[must_use]
1405 pub fn mount_viewport(&self, style: Style) -> NodeId {
1406 let Self {
1407 clock,
1408 scene,
1409 last_gpu_composite,
1410 ..
1411 } = self;
1412 let clock_c: Rc<RefCell<FrameClock>> = clock.clone();
1413 let scene_c: Rc<RefCell<dyn GameScene>> = scene.clone();
1414 let gpu_out_c: Rc<RefCell<Option<GpuCompositeDescriptor>>> = last_gpu_composite.clone();
1415 let mut ctx: Context = current_context();
1416 let node: NodeId = ctx.canvas(
1417 style,
1418 move |bounds: Rect, display_list: &mut DisplayList| {
1419 let alpha: f32 = clock_c
1420 .try_borrow()
1421 .map(|char_item: Ref<'_, FrameClock>| char_item.get_alpha())
1422 .unwrap_or(1.0);
1423 if let Ok(mut game) = scene_c.try_borrow_mut() {
1424 let mut render_ctx: GameRenderContext<'_> =
1425 GameRenderContext::new(bounds, display_list);
1426 game.render(alpha, &mut render_ctx);
1427 let gpu_target: Option<GpuCompositeDescriptor> =
1428 render_ctx.take_gpu_composite_target();
1429 if let Ok(mut slot) = gpu_out_c.try_borrow_mut() {
1430 *slot = gpu_target;
1431 }
1432 }
1433 },
1434 );
1435 if let Ok(mut nodes) = self.get_viewport_nodes().try_borrow_mut() {
1436 nodes.retain(|(sh, nid): &(SceneHandle, NodeId)| {
1437 sh.with_read(|tree: &SceneTree| tree.get_node(*nid).is_some(), false)
1438 });
1439 nodes.push((ctx.get_scene().clone(), node));
1440 }
1441 let drag_origin: Rc<RefCell<Option<Point>>> = Rc::new(RefCell::new(None));
1442 let origin_down: Rc<RefCell<Option<Point>>> = drag_origin.clone();
1443 let origin_move: Rc<RefCell<Option<Point>>> = drag_origin.clone();
1444 let origin_up: Rc<RefCell<Option<Point>>> = drag_origin;
1445 let host_move: Self = self.clone();
1446 let host_up: Self = self.clone();
1447 ctx.on_pointer_down(node, move |ui_event: &UiEvent| {
1448 if let UiEventKind::PointerDown(sample_point) = ui_event.get_kind()
1449 && let Ok(mut guard) = origin_down.try_borrow_mut()
1450 {
1451 *guard = Some(*sample_point);
1452 }
1453 });
1454 ctx.on_pointer_move(node, move |interaction_event: &UiEvent| {
1455 if let UiEventKind::PointerMove(target_point) = interaction_event.get_kind()
1456 && let Ok(guard) = origin_move.try_borrow()
1457 && let Some(orig) = *guard
1458 {
1459 let dx: f32 = ((target_point.get_x() - orig.get_x()) / 48.0).clamp(-1.0, 1.0);
1460 let dy: f32 = ((target_point.get_y() - orig.get_y()) / 48.0).clamp(-1.0, 1.0);
1461 host_move.set_virtual_stick(dx, dy);
1462 }
1463 });
1464 ctx.on_pointer_up(node, move |_: &UiEvent| {
1465 if let Ok(mut guard) = origin_up.try_borrow_mut() {
1466 *guard = None;
1467 }
1468 host_up.set_virtual_stick(0.0, 0.0);
1469 });
1470 node
1471 }
1472}