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 }
20 }
21
22 #[must_use]
32 pub fn viewport_size(&self) -> Size {
33 let Self { bounds, .. } = self;
34 Size::new(bounds.get_width(), bounds.get_height())
35 }
36
37 pub fn clear(&mut self, color: Color) {
44 let Self {
45 bounds,
46 display_list,
47 } = self;
48 display_list.push(DrawCommand::FillRoundedRect {
49 rect: *bounds,
50 color,
51 radius: CornerRadius::default(),
52 border: Border::default(),
53 });
54 }
55
56 pub fn fill_rect(&mut self, rect: Rect, color: Color) {
64 self.fill_rounded_rect(rect, color, 0.0);
65 }
66
67 pub fn fill_rounded_rect(&mut self, rect: Rect, color: Color, radius: f32) {
76 let Self {
77 bounds,
78 display_list,
79 } = self;
80 let world: Rect = Rect::new(
81 bounds.get_x() + rect.get_x(),
82 bounds.get_y() + rect.get_y(),
83 rect.get_width(),
84 rect.get_height(),
85 );
86 display_list.push(DrawCommand::FillRoundedRect {
87 rect: world,
88 color,
89 radius: CornerRadius::all(radius),
90 border: Border::default(),
91 });
92 }
93
94 pub fn stroke_rect(&mut self, rect: Rect, stroke_width: f32, color: Color) {
103 let Self {
104 bounds,
105 display_list,
106 } = self;
107 let world: Rect = Rect::new(
108 bounds.get_x() + rect.get_x(),
109 bounds.get_y() + rect.get_y(),
110 rect.get_width(),
111 rect.get_height(),
112 );
113 display_list.push(DrawCommand::FillRoundedRect {
114 rect: world,
115 color: COLOR_TRANSPARENT,
116 radius: CornerRadius::default(),
117 border: Border::new(stroke_width, color),
118 });
119 }
120
121 pub fn fill_circle(&mut self, center: Point, radius: f32, color: Color) {
130 let Self {
131 bounds,
132 display_list,
133 } = self;
134 let world: Point = Point::new(
135 bounds.get_x() + center.get_x(),
136 bounds.get_y() + center.get_y(),
137 );
138 display_list.push(DrawCommand::Circle {
139 center: world,
140 radius,
141 color,
142 });
143 }
144
145 pub fn draw_image(&mut self, rect: Rect, buffer: ImageBuffer) {
153 let Self {
154 bounds,
155 display_list,
156 } = self;
157 let world: Rect = Rect::new(
158 bounds.get_x() + rect.get_x(),
159 bounds.get_y() + rect.get_y(),
160 rect.get_width(),
161 rect.get_height(),
162 );
163 display_list.push(DrawCommand::Image {
164 rect: world,
165 buffer,
166 radius: CornerRadius::default(),
167 });
168 }
169
170 pub fn draw_line(&mut self, from: Point, to: Point, width: f32, color: Color) {
180 let Self {
181 bounds,
182 display_list,
183 } = self;
184 display_list.push(DrawCommand::Line {
185 from: Point::new(bounds.get_x() + from.get_x(), bounds.get_y() + from.get_y()),
186 to: Point::new(bounds.get_x() + to.get_x(), bounds.get_y() + to.get_y()),
187 color,
188 width,
189 });
190 }
191
192 pub fn draw_text(&mut self, position: Point, text: String, font_size: f32, color: Color) {
202 let Self {
203 bounds,
204 display_list,
205 } = self;
206 let mut style: TextStyle = TextStyle::default();
207 style.set_font_size(font_size);
208 style.set_color(color);
209 display_list.push(DrawCommand::TextRun {
210 rect: Rect::new(
211 bounds.get_x() + position.get_x(),
212 bounds.get_y() + position.get_y(),
213 (bounds.get_width() - position.get_x()).max(0.0),
214 font_size * 1.6,
215 ),
216 text,
217 style,
218 });
219 }
220
221 pub fn blit_framebuffer(&mut self, rect: Rect, buffer: ImageBuffer) {
229 let Self {
230 bounds,
231 display_list,
232 } = self;
233 let world: Rect = Rect::new(
234 bounds.get_x() + rect.get_x(),
235 bounds.get_y() + rect.get_y(),
236 rect.get_width(),
237 rect.get_height(),
238 );
239 display_list.push(DrawCommand::Image {
240 rect: world,
241 buffer,
242 radius: CornerRadius::default(),
243 });
244 }
245
246 pub fn fill_triangle(&mut self, p0: Point, p1: Point, p2: Point, color: Color) {
256 let Self {
257 bounds,
258 display_list,
259 } = self;
260 let ox: f32 = bounds.get_x();
261 let oy: f32 = bounds.get_y();
262 display_list.push(DrawCommand::Triangle {
263 p0: Point::new(ox + p0.get_x(), oy + p0.get_y()),
264 p1: Point::new(ox + p1.get_x(), oy + p1.get_y()),
265 p2: Point::new(ox + p2.get_x(), oy + p2.get_y()),
266 color,
267 });
268 }
269
270 pub fn draw_sprite_frame(
280 &mut self,
281 sheet: &SpriteSheet,
282 frame_index: u32,
283 rect: Rect,
284 tint: Color,
285 ) {
286 let src_rect: Rect = sheet.frame_rect(frame_index);
287 let Self {
288 bounds,
289 display_list,
290 } = self;
291 display_list.push(DrawCommand::SpriteRegion {
292 rect: Rect::new(
293 bounds.get_x() + rect.get_x(),
294 bounds.get_y() + rect.get_y(),
295 rect.get_width(),
296 rect.get_height(),
297 ),
298 buffer: sheet.get_texture().clone(),
299 src_rect,
300 tint,
301 });
302 }
303
304 pub fn render_tilemap(&mut self, tilemap: &TileMap, camera: &Camera2D) {
312 let vp: Size = self.viewport_size();
313 let vis: Rect = camera.visible_world_rect(vp);
314 let ts: f32 = tilemap.get_tile_size();
315 let zoom: f32 = camera.get_zoom().max(0.25);
316 let min_c: usize = (vis.get_x() / ts).floor().max(0.0) as usize;
317 let max_c: usize = ((vis.right() / ts).ceil().max(0.0) as usize).min(tilemap.get_columns());
318 let min_r: usize = (vis.get_y() / ts).floor().max(0.0) as usize;
319 let max_r: usize = ((vis.bottom() / ts).ceil().max(0.0) as usize).min(tilemap.get_rows());
320 let tile_px: f32 = (ts * zoom).max(1.0);
321 for row in min_r..max_r {
322 for col in min_c..max_c {
323 let tid: u16 = tilemap.tile_at(col, row);
324 if tid == 0 {
325 continue;
326 }
327 let Some(entry) = tilemap.get_palette().get(tid as usize) else {
328 continue;
329 };
330 let world_pt: Point = Point::new((col as f32) * ts, (row as f32) * ts);
331 let screen_pt: Point = camera.world_to_screen(world_pt, vp);
332 let tile_rect: Rect = Rect::new(
333 screen_pt.get_x(),
334 screen_pt.get_y(),
335 tile_px + 0.5,
336 tile_px + 0.5,
337 );
338 self.fill_rect(tile_rect, entry.get_color());
339 }
340 }
341 }
342
343 pub fn render_world(&mut self, world: &GameWorld, camera: &Camera2D) -> usize {
355 let vp: Size = self.viewport_size();
356 let vis: Rect = camera.visible_world_rect(vp);
357 let zoom: f32 = camera.get_zoom().max(0.25);
358 let mut draw_order: Vec<(i32, usize)> = Vec::with_capacity(world.get_live_count());
359 for (idx, ent) in world.get_entities().iter().enumerate() {
360 if !ent.get_alive() {
361 continue;
362 }
363 let Some(sp) = ent.sprite_component() else {
364 continue;
365 };
366 if !sp.get_visible() {
367 continue;
368 }
369 if ent.world_bounds().intersect(vis).is_none() {
370 continue;
371 }
372 draw_order.push((sp.get_z_order(), idx));
373 }
374 draw_order.sort_by(|a: &(i32, usize), b: &(i32, usize)| {
375 a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1))
376 });
377 let rendered: usize = draw_order.len();
378 for (_, idx) in draw_order.into_iter() {
379 let ent: &EntityRecord = &world.get_entities()[idx];
380 let Some(sp) = ent.sprite_component() else {
381 continue;
382 };
383 let tr: EntityTransform = ent.get_transform();
384 let center: Point = camera.world_to_screen(tr.get_position(), vp);
385 let w: f32 = sp.get_size().get_width() * tr.get_scale().get_width() * zoom;
386 let h: f32 = sp.get_size().get_height() * tr.get_scale().get_height() * zoom;
387 match sp.get_shape() {
388 EntityVisualShape::Rect => {
389 let rect: Rect =
390 Rect::new(center.get_x() - w * 0.5, center.get_y() - h * 0.5, w, h);
391 self.fill_rounded_rect(rect, sp.get_color(), sp.get_corner_radius() * zoom);
392 if sp.get_accent().get_a() > 0 {
393 self.stroke_rect(rect, 1.5, sp.get_accent());
394 }
395 }
396 EntityVisualShape::Circle => {
397 let r: f32 = (w.min(h) * 0.5).max(1.0);
398 self.fill_circle(center, r, sp.get_color());
399 if sp.get_accent().get_a() > 0 && r > 3.0 {
400 self.fill_circle(center, r * 0.45, sp.get_accent());
401 }
402 }
403 EntityVisualShape::Triangle => {
404 let ang: f32 = tr.get_rotation_rad();
405 let cos_a: f32 = ang.cos();
406 let sin_a: f32 = ang.sin();
407 let rx: f32 = w * 0.55;
408 let ry: f32 = h * 0.48;
409 let nose: Point =
410 Point::new(center.get_x() + cos_a * rx, center.get_y() + sin_a * rx);
411 let left: Point = Point::new(
412 center.get_x() - cos_a * (rx * 0.72) - sin_a * ry,
413 center.get_y() - sin_a * (rx * 0.72) + cos_a * ry,
414 );
415 let right: Point = Point::new(
416 center.get_x() - cos_a * (rx * 0.72) + sin_a * ry,
417 center.get_y() - sin_a * (rx * 0.72) - cos_a * ry,
418 );
419 self.fill_triangle(nose, left, right, sp.get_color());
420 if sp.get_accent().get_a() > 0 {
421 self.fill_circle(center, (w.min(h) * 0.16).max(2.0), sp.get_accent());
422 }
423 }
424 EntityVisualShape::Diamond => {
425 let hw: f32 = w * 0.5;
426 let hh: f32 = h * 0.5;
427 let top: Point = Point::new(center.get_x(), center.get_y() - hh);
428 let right: Point = Point::new(center.get_x() + hw, center.get_y());
429 let bottom: Point = Point::new(center.get_x(), center.get_y() + hh);
430 let left: Point = Point::new(center.get_x() - hw, center.get_y());
431 self.fill_triangle(top, right, bottom, sp.get_color());
432 self.fill_triangle(top, bottom, left, sp.get_color());
433 if sp.get_accent().get_a() > 0 {
434 self.fill_circle(center, (w.min(h) * 0.18).max(2.0), sp.get_accent());
435 }
436 }
437 }
438 }
439 rendered
440 }
441
442 pub fn render_particles(&mut self, particles: &ParticleSystem, camera: &Camera2D) -> usize {
454 let vp: Size = self.viewport_size();
455 let vis: Rect = camera.visible_world_rect(vp);
456 let zoom: f32 = camera.get_zoom().max(0.25);
457 let n: usize = particles.get_active_count();
458 let mut count: usize = 0;
459 for i in 0..n {
460 let pos: Point = Point::new(particles.pos_x[i], particles.pos_y[i]);
461 if !vis.contains(pos) {
462 continue;
463 }
464 let t: f32 = (particles.age[i] / particles.lifetime[i].max(0.001)).clamp(0.0, 1.0);
465 let s0: f32 = particles.start_size[i];
466 let s1: f32 = particles.end_size[i];
467 let r: f32 = ((s0 + (s1 - s0) * t) * zoom).max(0.8);
468 let col: Color = particles.start_color[i].lerp(particles.end_color[i], t);
469 if col.get_a() == 0 {
470 continue;
471 }
472 let screen: Point = camera.world_to_screen(pos, vp);
473 self.fill_circle(screen, r, col);
474 count += 1;
475 }
476 count
477 }
478
479 pub fn draw_debug_colliders(&mut self, world: &GameWorld, camera: &Camera2D) {
487 let vp: Size = self.viewport_size();
488 let vis: Rect = camera.visible_world_rect(vp);
489 let zoom: f32 = camera.get_zoom().max(0.25);
490 for ent in world.get_entities().iter() {
491 if !ent.get_alive() {
492 continue;
493 }
494 let Some(col) = ent.collider_component() else {
495 continue;
496 };
497 let aabb: Rect = col.world_aabb(ent.get_transform().get_position());
498 if aabb.intersect(vis).is_none() {
499 continue;
500 }
501 let tl: Point = camera.world_to_screen(Point::new(aabb.get_x(), aabb.get_y()), vp);
502 let color: Color = if col.get_is_trigger() {
503 Color::rgba(250, 204, 21, 180)
504 } else {
505 Color::rgba(34, 197, 94, 180)
506 };
507 self.stroke_rect(
508 Rect::new(
509 tl.get_x(),
510 tl.get_y(),
511 aabb.get_width() * zoom,
512 aabb.get_height() * zoom,
513 ),
514 1.0,
515 color,
516 );
517 }
518 }
519}
520
521impl GameEngineHost {
523 #[must_use]
534 pub fn new<S>(scene: S, fixed_dt: f32) -> Self
535 where
536 S: GameScene + 'static,
537 {
538 Self {
539 clock: Rc::new(RefCell::new(FrameClock::new(fixed_dt, 8))),
540 input: Rc::new(RefCell::new(InputState::new())),
541 scene: Rc::new(RefCell::new(scene)),
542 viewport_nodes: Rc::new(RefCell::new(Vec::new())),
543 paused: Rc::new(Cell::new(false)),
544 }
545 }
546
547 pub fn set_paused(&self, paused: bool) {
554 self.get_paused().set(paused);
555 }
556
557 #[must_use]
567 pub fn is_paused(&self) -> bool {
568 self.get_paused().get()
569 }
570
571 #[must_use]
582 pub fn active_viewport_bounds(&self, tree: &SceneTree) -> Vec<Rect> {
583 if self.is_paused() {
584 return Vec::new();
585 }
586 let mut rects: Vec<Rect> = Vec::new();
587 if let Ok(mut nodes) = self.get_viewport_nodes().try_borrow_mut() {
588 nodes.retain(|(_, id): &(SceneHandle, NodeId)| tree.get_node(*id).is_some());
589 for (_, id) in nodes.iter() {
590 if tree.is_node_visible(*id)
591 && let Some(bounds) = tree.node_screen_bounds(*id)
592 && bounds.get_width() > 0.0
593 && bounds.get_height() > 0.0
594 {
595 rects.push(bounds);
596 }
597 }
598 }
599 rects
600 }
601
602 pub fn ingest_event(&self, event: &WindowEvent) {
609 if let Ok(mut input) = self.get_input().try_borrow_mut() {
610 input.ingest(event);
611 }
612 }
613
614 pub fn step(&self, dt_secs: f32) -> u32 {
625 if self.is_paused() {
626 return 0;
627 }
628 let (steps, fixed_dt): (u32, f32) = match self.get_clock().try_borrow_mut() {
629 Ok(mut clock) => (clock.tick(dt_secs), clock.get_fixed_dt()),
630 Err(_) => (0, 1.0 / 60.0),
631 };
632 let input_snapshot: InputState = self
633 .get_input()
634 .try_borrow()
635 .map(|guard: Ref<'_, InputState>| guard.clone())
636 .unwrap_or_default();
637 let Self { scene, .. } = self;
638 if let Ok(mut game) = scene.try_borrow_mut() {
639 for _ in 0..steps {
640 game.fixed_update(fixed_dt, &input_snapshot);
641 }
642 game.update(dt_secs, &input_snapshot);
643 }
644 if let Ok(mut input) = self.get_input().try_borrow_mut() {
645 input.begin_frame();
646 }
647 if let Ok(nodes) = self.get_viewport_nodes().try_borrow() {
648 for (scene_handle, node_id) in nodes.iter() {
649 scene_handle.mark_dirty(*node_id, DIRTY_PAINT);
650 }
651 }
652 steps
653 }
654
655 pub fn set_virtual_stick(&self, dx: f32, dy: f32) {
663 if let Ok(mut input) = self.get_input().try_borrow_mut() {
664 input.set_virtual_stick(dx, dy);
665 }
666 }
667
668 pub fn press_key(&self, code: KeyCode) {
675 self.ingest_event(&WindowEvent::KeyDown(
676 WindowId::new(1),
677 KeyEvent::new(code, Modifiers::default(), false),
678 ));
679 }
680
681 pub fn release_key(&self, code: KeyCode) {
688 self.ingest_event(&WindowEvent::KeyUp(
689 WindowId::new(1),
690 KeyEvent::new(code, Modifiers::default(), false),
691 ));
692 }
693
694 #[must_use]
708 pub fn mount_viewport(&self, style: Style) -> NodeId {
709 let Self { clock, scene, .. } = self;
710 let clock_c: Rc<RefCell<FrameClock>> = clock.clone();
711 let scene_c: Rc<RefCell<dyn GameScene>> = scene.clone();
712 let mut ctx: Context = current_context();
713 let node: NodeId = ctx.canvas(
714 style,
715 move |bounds: Rect, display_list: &mut DisplayList| {
716 let alpha: f32 = clock_c
717 .try_borrow()
718 .map(|c: Ref<'_, FrameClock>| c.get_alpha())
719 .unwrap_or(1.0);
720 if let Ok(mut game) = scene_c.try_borrow_mut() {
721 let mut render_ctx: GameRenderContext<'_> =
722 GameRenderContext::new(bounds, display_list);
723 game.render(alpha, &mut render_ctx);
724 }
725 },
726 );
727 if let Ok(mut nodes) = self.get_viewport_nodes().try_borrow_mut() {
728 nodes.push((ctx.get_scene().clone(), node));
729 }
730 let drag_origin: Rc<RefCell<Option<Point>>> = Rc::new(RefCell::new(None));
731 let origin_down: Rc<RefCell<Option<Point>>> = drag_origin.clone();
732 let origin_move: Rc<RefCell<Option<Point>>> = drag_origin.clone();
733 let origin_up: Rc<RefCell<Option<Point>>> = drag_origin;
734 let host_move: Self = self.clone();
735 let host_up: Self = self.clone();
736 ctx.on_pointer_down(node, move |ev: &UiEvent| {
737 if let UiEventKind::PointerDown(pt) = ev.get_kind()
738 && let Ok(mut guard) = origin_down.try_borrow_mut()
739 {
740 *guard = Some(*pt);
741 }
742 });
743 ctx.on_pointer_move(node, move |ev: &UiEvent| {
744 if let UiEventKind::PointerMove(pt) = ev.get_kind()
745 && let Ok(guard) = origin_move.try_borrow()
746 && let Some(orig) = *guard
747 {
748 let dx: f32 = ((pt.get_x() - orig.get_x()) / 48.0).clamp(-1.0, 1.0);
749 let dy: f32 = ((pt.get_y() - orig.get_y()) / 48.0).clamp(-1.0, 1.0);
750 host_move.set_virtual_stick(dx, dy);
751 }
752 });
753 ctx.on_pointer_up(node, move |_: &UiEvent| {
754 if let Ok(mut guard) = origin_up.try_borrow_mut() {
755 *guard = None;
756 }
757 host_up.set_virtual_stick(0.0, 0.0);
758 });
759 node
760 }
761}