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