1use super::*;
2
3impl Default for PhysicsConfig {
5 fn default() -> Self {
11 Self {
12 gravity: Point::new(0.0, 0.0),
13 cell_size: DEFAULT_SPATIAL_CELL_SIZE,
14 position_correction: 0.8,
15 arena_bounds: None,
16 }
17 }
18}
19
20impl Default for PhysicsWorld2D {
22 fn default() -> Self {
28 Self::with_config(PhysicsConfig::default())
29 }
30}
31
32impl RaycastQuery2D {
34 #[must_use]
45 pub const fn new(origin: Point, direction: Point) -> Self {
46 Self {
47 origin,
48 direction,
49 max_distance: 1000.0,
50 layer_mask: u32::MAX,
51 }
52 }
53
54 #[must_use]
65 pub fn with_max_distance(mut self, max_distance: f32) -> Self {
66 self.set_max_distance(max_distance.max(0.0));
67 self
68 }
69
70 #[must_use]
81 pub fn with_layer_mask(mut self, layer_mask: u32) -> Self {
82 self.set_layer_mask(layer_mask);
83 self
84 }
85}
86
87impl PhysicsWorld2D {
89 #[must_use]
99 pub fn with_config(config: PhysicsConfig) -> Self {
100 Self {
101 config,
102 body_bounds: Vec::new(),
103 cell_counts: Vec::new(),
104 cell_offsets: Vec::new(),
105 cell_cursors: Vec::new(),
106 cell_items: Vec::new(),
107 active_cells: Vec::new(),
108 sparse_table: Vec::new(),
109 sparse_nodes: Vec::new(),
110 sparse_active: Vec::new(),
111 sparse_bucket_scratch: Vec::new(),
112 last_stats: PhysicsStepStats::default(),
113 }
114 }
115
116 #[inline(always)]
127 #[must_use]
128 fn pack_cell_key(cx: i32, cy: i32) -> u64 {
129 let raw: u64 = ((cx as u32 as u64) << 32) | (cy as u32 as u64);
130 if raw == u64::MAX { u64::MAX - 1 } else { raw }
131 }
132
133 #[inline]
143 fn resolve_pair(
144 entities: &mut [EntityRecord],
145 ia: usize,
146 ib: usize,
147 pos_corr: f32,
148 events: &mut Vec<CollisionEvent>,
149 ) {
150 let (id_a, pos_a, vel_a, body_a, col_a): (
151 EntityId,
152 Point,
153 Velocity2D,
154 RigidBody2D,
155 Collider2D,
156 ) = {
157 let ent: &EntityRecord = &entities[ia];
158 let Some(col) = ent.collider_component() else {
159 return;
160 };
161 (
162 ent.get_id(),
163 ent.get_transform().get_position(),
164 ent.get_velocity(),
165 ent.body_component()
166 .unwrap_or_else(|| RigidBody2D::static_body(0.5)),
167 col,
168 )
169 };
170 let (id_b, pos_b, vel_b, body_b, col_b): (
171 EntityId,
172 Point,
173 Velocity2D,
174 RigidBody2D,
175 Collider2D,
176 ) = {
177 let ent: &EntityRecord = &entities[ib];
178 let Some(col) = ent.collider_component() else {
179 return;
180 };
181 (
182 ent.get_id(),
183 ent.get_transform().get_position(),
184 ent.get_velocity(),
185 ent.body_component()
186 .unwrap_or_else(|| RigidBody2D::static_body(0.5)),
187 col,
188 )
189 };
190 let Some((normal, penetration)) =
191 Self::narrow_phase(pos_a, col_a.get_shape(), pos_b, col_b.get_shape())
192 else {
193 return;
194 };
195 let is_trigger: bool = col_a.get_is_trigger() || col_b.get_is_trigger();
196 events.push(CollisionEvent::new(
197 id_a,
198 id_b,
199 normal,
200 penetration,
201 is_trigger,
202 ));
203 if is_trigger {
204 return;
205 }
206 let inv_a: f32 = body_a.get_inv_mass();
207 let inv_b: f32 = body_b.get_inv_mass();
208 let inv_sum: f32 = inv_a + inv_b;
209 if inv_sum <= 0.0 {
210 return;
211 }
212 let corr_mag: f32 = (penetration / inv_sum) * pos_corr;
213 let nx_n: f32 = normal.get_x();
214 let ny_n: f32 = normal.get_y();
215 let corr_x: f32 = nx_n * corr_mag;
216 let corr_y: f32 = ny_n * corr_mag;
217 let next_pos_a: Point = Point::new(
218 pos_a.get_x() - corr_x * inv_a,
219 pos_a.get_y() - corr_y * inv_a,
220 );
221 let next_pos_b: Point = Point::new(
222 pos_b.get_x() + corr_x * inv_b,
223 pos_b.get_y() + corr_y * inv_b,
224 );
225 let rvx: f32 = vel_b.get_vx() - vel_a.get_vx();
226 let rvy: f32 = vel_b.get_vy() - vel_a.get_vy();
227 let vel_along_normal: f32 = rvx * nx_n + rvy * ny_n;
228 let mut next_vel_a: Velocity2D = vel_a;
229 let mut next_vel_b: Velocity2D = vel_b;
230 if vel_along_normal < 0.0 {
231 let e: f32 = body_a.get_restitution().min(body_b.get_restitution());
232 let j: f32 = -(1.0 + e) * vel_along_normal / inv_sum;
233 let imp_x: f32 = j * nx_n;
234 let imp_y: f32 = j * ny_n;
235 next_vel_a.set_vx(vel_a.get_vx() - imp_x * inv_a);
236 next_vel_a.set_vy(vel_a.get_vy() - imp_y * inv_a);
237 next_vel_b.set_vx(vel_b.get_vx() + imp_x * inv_b);
238 next_vel_b.set_vy(vel_b.get_vy() + imp_y * inv_b);
239 }
240 entities[ia].get_mut_transform().set_position(next_pos_a);
241 entities[ia].set_velocity(next_vel_a);
242 entities[ib].get_mut_transform().set_position(next_pos_b);
243 entities[ib].set_velocity(next_vel_b);
244 }
245
246 pub fn step(&mut self, world: &mut GameWorld, dt_secs: f32) -> Vec<CollisionEvent> {
258 let cfg: PhysicsConfig = self.get_config();
259 let gx_dt: f32 = cfg.get_gravity().get_x() * dt_secs;
260 let gy_dt: f32 = cfg.get_gravity().get_y() * dt_secs;
261 let pos_corr: f32 = cfg.get_position_correction();
262 let inv_cell: f32 = 1.0 / cfg.get_cell_size().max(8.0);
263 let arena_opt: Option<Rect> = {
264 let PhysicsConfig { arena_bounds, .. } = cfg;
265 arena_bounds
266 };
267 let Self {
268 body_bounds,
269 cell_counts,
270 cell_offsets,
271 cell_cursors,
272 cell_items,
273 active_cells,
274 sparse_table,
275 sparse_nodes,
276 sparse_active,
277 sparse_bucket_scratch,
278 ..
279 } = self;
280 body_bounds.clear();
281 let mut integrated: usize = 0;
282 let mut grid_min_cx: i32 = i32::MAX;
283 let mut grid_max_cx: i32 = i32::MIN;
284 let mut grid_min_cy: i32 = i32::MAX;
285 let mut grid_max_cy: i32 = i32::MIN;
286 let mut total_cell_refs: usize = 0;
287 let entities: &mut [EntityRecord] = world.get_mut_entities().as_mut_slice();
288 for (idx, ent) in entities.iter_mut().enumerate() {
289 if !ent.get_alive() {
290 continue;
291 }
292 if let Some(body) = ent.body_component() {
293 match body.get_kind() {
294 BodyKind::Static => {}
295 BodyKind::Kinematic => {
296 let vel: Velocity2D = ent.get_velocity();
297 let pos: Point = ent.get_transform().get_position();
298 let next_pos: Point = Point::new(
299 pos.get_x() + vel.get_vx() * dt_secs,
300 pos.get_y() + vel.get_vy() * dt_secs,
301 );
302 let next_rot: f32 =
303 ent.get_transform().get_rotation_rad() + vel.get_angular() * dt_secs;
304 ent.get_mut_transform().set_position(next_pos);
305 ent.get_mut_transform().set_rotation_rad(next_rot);
306 integrated += 1;
307 }
308 BodyKind::Dynamic => {
309 let mut vel: Velocity2D = ent.get_velocity();
310 let g_scale: f32 = body.get_gravity_scale();
311 let damp: f32 = (1.0 - body.get_linear_drag() * dt_secs).clamp(0.0, 1.0);
312 vel.set_vx((vel.get_vx() + gx_dt * g_scale) * damp);
313 vel.set_vy((vel.get_vy() + gy_dt * g_scale) * damp);
314 let pos: Point = ent.get_transform().get_position();
315 let mut nx: f32 = pos.get_x() + vel.get_vx() * dt_secs;
316 let mut ny: f32 = pos.get_y() + vel.get_vy() * dt_secs;
317 if let Some(arena) = arena_opt {
318 let (half_w, half_h): (f32, f32) = match ent.collider_component() {
319 Some(col) => match col.get_shape() {
320 ColliderShape::Circle { radius } => (radius, radius),
321 ColliderShape::Aabb { width, height } => {
322 (width * 0.5, height * 0.5)
323 }
324 },
325 None => (0.0, 0.0),
326 };
327 let rest: f32 = body.get_restitution();
328 let min_x: f32 = arena.get_x() + half_w;
329 let max_x: f32 = arena.right() - half_w;
330 let min_y: f32 = arena.get_y() + half_h;
331 let max_y: f32 = arena.bottom() - half_h;
332 if nx < min_x {
333 nx = min_x;
334 vel.set_vx(vel.get_vx().abs() * rest);
335 } else if nx > max_x {
336 nx = max_x;
337 vel.set_vx(-vel.get_vx().abs() * rest);
338 }
339 if ny < min_y {
340 ny = min_y;
341 vel.set_vy(vel.get_vy().abs() * rest);
342 } else if ny > max_y {
343 ny = max_y;
344 vel.set_vy(-vel.get_vy().abs() * rest);
345 }
346 }
347 let next_rot: f32 =
348 ent.get_transform().get_rotation_rad() + vel.get_angular() * dt_secs;
349 ent.set_velocity(vel);
350 ent.get_mut_transform().set_position(Point::new(nx, ny));
351 ent.get_mut_transform().set_rotation_rad(next_rot);
352 integrated += 1;
353 }
354 }
355 }
356 if let Some(col) = ent.collider_component() {
357 let aabb: Rect = col.world_aabb(ent.get_transform().get_position());
358 let min_cx: i32 = (aabb.get_x() * inv_cell).floor() as i32;
359 let max_cx: i32 = (aabb.right() * inv_cell).floor() as i32;
360 let min_cy: i32 = (aabb.get_y() * inv_cell).floor() as i32;
361 let max_cy: i32 = (aabb.bottom() * inv_cell).floor() as i32;
362 grid_min_cx = grid_min_cx.min(min_cx);
363 grid_max_cx = grid_max_cx.max(max_cx);
364 grid_min_cy = grid_min_cy.min(min_cy);
365 grid_max_cy = grid_max_cy.max(max_cy);
366 let span_x: usize = ((max_cx as i64) - (min_cx as i64) + 1).max(1) as usize;
367 let span_y: usize = ((max_cy as i64) - (min_cy as i64) + 1).max(1) as usize;
368 total_cell_refs = total_cell_refs.saturating_add(span_x.saturating_mul(span_y));
369 body_bounds.push(BodyGridBounds {
370 entity_idx: idx as u32,
371 min_cx,
372 max_cx,
373 min_cy,
374 max_cy,
375 layer: col.get_layer(),
376 mask: col.get_mask(),
377 });
378 }
379 }
380 let mut broad_count: usize = 0;
381 let mut events: Vec<CollisionEvent> = Vec::new();
382 if body_bounds.len() >= 2 {
383 let span_x_i64: i64 = (grid_max_cx as i64) - (grid_min_cx as i64) + 1;
384 let span_y_i64: i64 = (grid_max_cy as i64) - (grid_min_cy as i64) + 1;
385 let use_dense: bool = span_x_i64 > 0
386 && span_y_i64 > 0
387 && span_x_i64 <= FLAT_GRID_MAX_AXIS
388 && span_y_i64 <= FLAT_GRID_MAX_AXIS
389 && ((span_x_i64 * span_y_i64) as usize) <= FLAT_GRID_MAX_CELLS;
390 if use_dense {
391 let grid_w: usize = span_x_i64 as usize;
392 let grid_h: usize = span_y_i64 as usize;
393 let grid_cells: usize = grid_w * grid_h;
394 cell_counts.resize(grid_cells, 0);
395 cell_counts.fill(0);
396 for b in body_bounds.iter() {
397 let rx0: usize = (b.min_cx - grid_min_cx) as usize;
398 let rx1: usize = (b.max_cx - grid_min_cx) as usize;
399 let ry0: usize = (b.min_cy - grid_min_cy) as usize;
400 let ry1: usize = (b.max_cy - grid_min_cy) as usize;
401 for ry in ry0..=ry1 {
402 let row_off: usize = ry * grid_w;
403 for rx in rx0..=rx1 {
404 cell_counts[row_off + rx] += 1;
405 }
406 }
407 }
408 cell_offsets.resize(grid_cells, 0);
409 cell_cursors.resize(grid_cells, 0);
410 active_cells.clear();
411 let mut running: u32 = 0;
412 for ry in 0..grid_h {
413 let cy: i32 = grid_min_cy + (ry as i32);
414 let row_off: usize = ry * grid_w;
415 for rx in 0..grid_w {
416 let cidx: usize = row_off + rx;
417 let cnt: u32 = cell_counts[cidx];
418 cell_offsets[cidx] = running;
419 cell_cursors[cidx] = running;
420 running += cnt;
421 if cnt >= 2 {
422 active_cells.push((cidx, grid_min_cx + (rx as i32), cy));
423 }
424 }
425 }
426 cell_items.resize(running as usize, 0);
427 for (slot_idx, b) in body_bounds.iter().enumerate() {
428 let slot_u32: u32 = slot_idx as u32;
429 let rx0: usize = (b.min_cx - grid_min_cx) as usize;
430 let rx1: usize = (b.max_cx - grid_min_cx) as usize;
431 let ry0: usize = (b.min_cy - grid_min_cy) as usize;
432 let ry1: usize = (b.max_cy - grid_min_cy) as usize;
433 for ry in ry0..=ry1 {
434 let row_off: usize = ry * grid_w;
435 for rx in rx0..=rx1 {
436 let cidx: usize = row_off + rx;
437 let dst: usize = cell_cursors[cidx] as usize;
438 cell_items[dst] = slot_u32;
439 cell_cursors[cidx] = (dst + 1) as u32;
440 }
441 }
442 }
443 for &(cidx, cx, cy) in active_cells.iter() {
444 let start: usize = cell_offsets[cidx] as usize;
445 let end: usize = cell_cursors[cidx] as usize;
446 let bucket: &[u32] = &cell_items[start..end];
447 let n: usize = bucket.len();
448 for i in 0..n {
449 let ba: BodyGridBounds = body_bounds[bucket[i] as usize];
450 for &sb_u32 in &bucket[(i + 1)..] {
451 let bb: BodyGridBounds = body_bounds[sb_u32 as usize];
452 if ba.min_cx.max(bb.min_cx) == cx && ba.min_cy.max(bb.min_cy) == cy {
453 broad_count += 1;
454 if (ba.layer & bb.mask) != 0 && (bb.layer & ba.mask) != 0 {
455 Self::resolve_pair(
456 entities,
457 ba.entity_idx as usize,
458 bb.entity_idx as usize,
459 pos_corr,
460 &mut events,
461 );
462 }
463 }
464 }
465 }
466 }
467 } else {
468 let needed_cap: usize = (total_cell_refs.saturating_mul(2).max(64))
469 .next_power_of_two()
470 .max(64);
471 let empty_cell: SparseGridCell = SparseGridCell {
472 key: u64::MAX,
473 cx: 0,
474 cy: 0,
475 head: u32::MAX,
476 count: 0,
477 };
478 if sparse_table.len() < needed_cap {
479 sparse_table.resize(needed_cap, empty_cell);
480 }
481 let cap: usize = sparse_table.len();
482 let mask: usize = cap - 1;
483 sparse_table.fill(empty_cell);
484 sparse_nodes.clear();
485 sparse_active.clear();
486 for (slot_idx, b) in body_bounds.iter().enumerate() {
487 let slot_u32: u32 = slot_idx as u32;
488 for cy in b.min_cy..=b.max_cy {
489 for cx in b.min_cx..=b.max_cx {
490 let key: u64 = Self::pack_cell_key(cx, cy);
491 let mut h: usize =
492 (key.wrapping_mul(SPARSE_GRID_HASH_MULT) >> 32) as usize & mask;
493 loop {
494 let cell: &mut SparseGridCell = &mut sparse_table[h];
495 if cell.key == u64::MAX {
496 cell.key = key;
497 cell.cx = cx;
498 cell.cy = cy;
499 let node_idx: u32 = sparse_nodes.len() as u32;
500 sparse_nodes.push(SparseGridNode {
501 body_slot: slot_u32,
502 next: u32::MAX,
503 });
504 cell.head = node_idx;
505 cell.count = 1;
506 break;
507 } else if cell.key == key {
508 let prev_head: u32 = cell.head;
509 let node_idx: u32 = sparse_nodes.len() as u32;
510 sparse_nodes.push(SparseGridNode {
511 body_slot: slot_u32,
512 next: prev_head,
513 });
514 cell.head = node_idx;
515 cell.count += 1;
516 if cell.count == 2 {
517 sparse_active.push(h);
518 }
519 break;
520 }
521 h = (h + 1) & mask;
522 }
523 }
524 }
525 }
526 for &table_idx in sparse_active.iter() {
527 let cell: SparseGridCell = sparse_table[table_idx];
528 sparse_bucket_scratch.clear();
529 let mut cur: u32 = cell.head;
530 while cur != u32::MAX {
531 let node: SparseGridNode = sparse_nodes[cur as usize];
532 sparse_bucket_scratch.push(node.body_slot);
533 cur = node.next;
534 }
535 sparse_bucket_scratch.reverse();
536 let n: usize = sparse_bucket_scratch.len();
537 for i in 0..n {
538 let ba: BodyGridBounds = body_bounds[sparse_bucket_scratch[i] as usize];
539 for &sb_u32 in &sparse_bucket_scratch[(i + 1)..] {
540 let bb: BodyGridBounds = body_bounds[sb_u32 as usize];
541 if ba.min_cx.max(bb.min_cx) == cell.cx
542 && ba.min_cy.max(bb.min_cy) == cell.cy
543 {
544 broad_count += 1;
545 if (ba.layer & bb.mask) != 0 && (bb.layer & ba.mask) != 0 {
546 Self::resolve_pair(
547 entities,
548 ba.entity_idx as usize,
549 bb.entity_idx as usize,
550 pos_corr,
551 &mut events,
552 );
553 }
554 }
555 }
556 }
557 }
558 }
559 }
560 self.set_last_stats(PhysicsStepStats::new(integrated, broad_count, events.len()));
561 events
562 }
563
564 #[must_use]
578 pub fn raycast(
579 world: &GameWorld,
580 origin: Point,
581 direction: Point,
582 max_distance: f32,
583 layer_mask: u32,
584 ) -> Option<RaycastHit> {
585 let len: f32 =
586 (direction.get_x() * direction.get_x() + direction.get_y() * direction.get_y()).sqrt();
587 if len <= 1e-6 || max_distance <= 0.0 {
588 return None;
589 }
590 let dx: f32 = direction.get_x() / len;
591 let dy: f32 = direction.get_y() / len;
592 let mut closest: Option<RaycastHit> = None;
593 let mut best_t: f32 = max_distance;
594 for ent in world.get_entities().iter() {
595 if !ent.get_alive() {
596 continue;
597 }
598 let Some(col) = ent.collider_component() else {
599 continue;
600 };
601 if (col.get_layer() & layer_mask) == 0 {
602 continue;
603 }
604 let pos: Point = ent.get_transform().get_position();
605 let hit_opt: Option<(f32, Point)> = match col.get_shape() {
606 ColliderShape::Circle { radius } => {
607 Self::ray_vs_circle(origin, (dx, dy), pos, radius, best_t)
608 }
609 ColliderShape::Aabb { width, height } => Self::ray_vs_aabb(
610 origin,
611 (dx, dy),
612 Rect::new(
613 pos.get_x() - width * 0.5,
614 pos.get_y() - height * 0.5,
615 width,
616 height,
617 ),
618 best_t,
619 ),
620 };
621 if let Some((t, normal)) = hit_opt
622 && t < best_t
623 {
624 best_t = t;
625 let hit_pt: Point = Point::new(origin.get_x() + dx * t, origin.get_y() + dy * t);
626 closest = Some(RaycastHit::new(ent.get_id(), hit_pt, normal, t));
627 }
628 }
629 closest
630 }
631
632 #[must_use]
643 pub fn raycast_query(world: &GameWorld, query: &RaycastQuery2D) -> Option<RaycastHit> {
644 Self::raycast(
645 world,
646 query.get_origin(),
647 query.get_direction(),
648 query.get_max_distance(),
649 query.get_layer_mask(),
650 )
651 }
652
653 fn narrow_phase(
666 pos_a: Point,
667 shape_a: ColliderShape,
668 pos_b: Point,
669 shape_b: ColliderShape,
670 ) -> Option<(Point, f32)> {
671 match (shape_a, shape_b) {
672 (ColliderShape::Circle { radius: ra }, ColliderShape::Circle { radius: rb }) => {
673 let dx: f32 = pos_b.get_x() - pos_a.get_x();
674 let dy: f32 = pos_b.get_y() - pos_a.get_y();
675 let r_sum: f32 = ra + rb;
676 let dist_sq: f32 = dx * dx + dy * dy;
677 if dist_sq >= r_sum * r_sum {
678 return None;
679 }
680 let dist: f32 = dist_sq.sqrt();
681 if dist <= 1e-5 {
682 Some((Point::new(1.0, 0.0), r_sum))
683 } else {
684 let inv_dist: f32 = 1.0 / dist;
685 Some((Point::new(dx * inv_dist, dy * inv_dist), r_sum - dist))
686 }
687 }
688 (
689 ColliderShape::Aabb {
690 width: wa,
691 height: ha,
692 },
693 ColliderShape::Aabb {
694 width: wb,
695 height: hb,
696 },
697 ) => {
698 let dx: f32 = pos_b.get_x() - pos_a.get_x();
699 let dy: f32 = pos_b.get_y() - pos_a.get_y();
700 let ox: f32 = (wa + wb) * 0.5 - dx.abs();
701 if ox <= 0.0 {
702 return None;
703 }
704 let oy: f32 = (ha + hb) * 0.5 - dy.abs();
705 if oy <= 0.0 {
706 return None;
707 }
708 if ox < oy {
709 let nx: f32 = if dx < 0.0 { -1.0 } else { 1.0 };
710 Some((Point::new(nx, 0.0), ox))
711 } else {
712 let ny: f32 = if dy < 0.0 { -1.0 } else { 1.0 };
713 Some((Point::new(0.0, ny), oy))
714 }
715 }
716 (ColliderShape::Circle { radius }, ColliderShape::Aabb { width, height }) => {
717 Self::circle_vs_aabb(pos_a, radius, pos_b, width, height)
718 }
719 (ColliderShape::Aabb { width, height }, ColliderShape::Circle { radius }) => {
720 Self::circle_vs_aabb(pos_b, radius, pos_a, width, height)
721 .map(|(n, pen): (Point, f32)| (Point::new(-n.get_x(), -n.get_y()), pen))
722 }
723 }
724 }
725
726 fn circle_vs_aabb(
740 c_pos: Point,
741 radius: f32,
742 b_pos: Point,
743 bw: f32,
744 bh: f32,
745 ) -> Option<(Point, f32)> {
746 let half_w: f32 = bw * 0.5;
747 let half_h: f32 = bh * 0.5;
748 let rel_x: f32 = c_pos.get_x() - b_pos.get_x();
749 let rel_y: f32 = c_pos.get_y() - b_pos.get_y();
750 let closest_x: f32 = rel_x.clamp(-half_w, half_w);
751 let closest_y: f32 = rel_y.clamp(-half_h, half_h);
752 let dx: f32 = rel_x - closest_x;
753 let dy: f32 = rel_y - closest_y;
754 let dist_sq: f32 = dx * dx + dy * dy;
755 if dist_sq >= radius * radius {
756 return None;
757 }
758 let dist: f32 = dist_sq.sqrt();
759 if dist <= 1e-5 {
760 let ox: f32 = half_w - rel_x.abs();
761 let oy: f32 = half_h - rel_y.abs();
762 if ox < oy {
763 let nx: f32 = if rel_x < 0.0 { 1.0 } else { -1.0 };
764 Some((Point::new(nx, 0.0), ox + radius))
765 } else {
766 let ny: f32 = if rel_y < 0.0 { 1.0 } else { -1.0 };
767 Some((Point::new(0.0, ny), oy + radius))
768 }
769 } else {
770 Some((Point::new(-dx / dist, -dy / dist), radius - dist))
771 }
772 }
773
774 fn ray_vs_circle(
788 origin: Point,
789 dir: (f32, f32),
790 center: Point,
791 radius: f32,
792 max_dist: f32,
793 ) -> Option<(f32, Point)> {
794 let oc_x: f32 = origin.get_x() - center.get_x();
795 let oc_y: f32 = origin.get_y() - center.get_y();
796 let b: f32 = oc_x * dir.0 + oc_y * dir.1;
797 let c: f32 = oc_x * oc_x + oc_y * oc_y - radius * radius;
798 let disc: f32 = b * b - c;
799 if disc < 0.0 {
800 return None;
801 }
802 let t: f32 = -b - disc.sqrt();
803 if t < 0.0 || t > max_dist {
804 return None;
805 }
806 let hx: f32 = origin.get_x() + dir.0 * t;
807 let hy: f32 = origin.get_y() + dir.1 * t;
808 let inv_r: f32 = 1.0 / radius.max(1e-5);
809 Some((
810 t,
811 Point::new((hx - center.get_x()) * inv_r, (hy - center.get_y()) * inv_r),
812 ))
813 }
814
815 fn ray_vs_aabb(
828 origin: Point,
829 dir: (f32, f32),
830 rect: Rect,
831 max_dist: f32,
832 ) -> Option<(f32, Point)> {
833 let mut t_min: f32 = 0.0;
834 let mut t_max: f32 = max_dist;
835 let mut normal: Point = Point::new(0.0, 0.0);
836 if dir.0.abs() < 1e-6 {
837 if origin.get_x() < rect.get_x() || origin.get_x() > rect.right() {
838 return None;
839 }
840 } else {
841 let inv: f32 = 1.0 / dir.0;
842 let mut t1: f32 = (rect.get_x() - origin.get_x()) * inv;
843 let mut t2: f32 = (rect.right() - origin.get_x()) * inv;
844 let mut nx: f32 = -1.0;
845 if t1 > t2 {
846 swap(&mut t1, &mut t2);
847 nx = 1.0;
848 }
849 if t1 > t_min {
850 t_min = t1;
851 normal = Point::new(nx, 0.0);
852 }
853 t_max = t_max.min(t2);
854 if t_min > t_max {
855 return None;
856 }
857 }
858 if dir.1.abs() < 1e-6 {
859 if origin.get_y() < rect.get_y() || origin.get_y() > rect.bottom() {
860 return None;
861 }
862 } else {
863 let inv: f32 = 1.0 / dir.1;
864 let mut t1: f32 = (rect.get_y() - origin.get_y()) * inv;
865 let mut t2: f32 = (rect.bottom() - origin.get_y()) * inv;
866 let mut ny: f32 = -1.0;
867 if t1 > t2 {
868 swap(&mut t1, &mut t2);
869 ny = 1.0;
870 }
871 if t1 > t_min {
872 t_min = t1;
873 normal = Point::new(0.0, ny);
874 }
875 t_max = t_max.min(t2);
876 if t_min > t_max {
877 return None;
878 }
879 }
880 Some((t_min, normal))
881 }
882}