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 grid: HashMap::with_capacity(128),
103 seen_pairs: HashSet::with_capacity(256),
104 last_stats: PhysicsStepStats::default(),
105 }
106 }
107
108 pub fn step(&mut self, world: &mut GameWorld, dt_secs: f32) -> Vec<CollisionEvent> {
120 let cfg: PhysicsConfig = self.get_config();
121 let gx: f32 = cfg.get_gravity().get_x();
122 let gy: f32 = cfg.get_gravity().get_y();
123 let inv_cell: f32 = 1.0 / cfg.get_cell_size().max(8.0);
124 let arena_opt: Option<Rect> = {
125 let PhysicsConfig { arena_bounds, .. } = cfg;
126 arena_bounds
127 };
128 let mut integrated: usize = 0;
129 for bucket in self.get_mut_grid().values_mut() {
130 bucket.clear();
131 }
132 self.get_mut_seen_pairs().clear();
133 let entity_len: usize = world.get_entities().len();
134 for idx in 0..entity_len {
135 let ent: &mut EntityRecord = &mut world.get_mut_entities()[idx];
136 if !ent.get_alive() {
137 continue;
138 }
139 if let Some(body) = ent.body_component() {
140 match body.get_kind() {
141 BodyKind::Static => {}
142 BodyKind::Kinematic => {
143 let vel: Velocity2D = ent.get_velocity();
144 let pos: Point = ent.get_transform().get_position();
145 let next_pos: Point = Point::new(
146 pos.get_x() + vel.get_vx() * dt_secs,
147 pos.get_y() + vel.get_vy() * dt_secs,
148 );
149 let next_rot: f32 =
150 ent.get_transform().get_rotation_rad() + vel.get_angular() * dt_secs;
151 ent.get_mut_transform().set_position(next_pos);
152 ent.get_mut_transform().set_rotation_rad(next_rot);
153 integrated += 1;
154 }
155 BodyKind::Dynamic => {
156 let mut vel: Velocity2D = ent.get_velocity();
157 let g_scale: f32 = body.get_gravity_scale();
158 let damp: f32 = (1.0 - body.get_linear_drag() * dt_secs).clamp(0.0, 1.0);
159 vel.set_vx((vel.get_vx() + gx * g_scale * dt_secs) * damp);
160 vel.set_vy((vel.get_vy() + gy * g_scale * dt_secs) * damp);
161 let pos: Point = ent.get_transform().get_position();
162 let mut nx: f32 = pos.get_x() + vel.get_vx() * dt_secs;
163 let mut ny: f32 = pos.get_y() + vel.get_vy() * dt_secs;
164 if let Some(arena) = arena_opt {
165 let (half_w, half_h): (f32, f32) = match ent.collider_component() {
166 Some(col) => match col.get_shape() {
167 ColliderShape::Circle { radius } => (radius, radius),
168 ColliderShape::Aabb { width, height } => {
169 (width * 0.5, height * 0.5)
170 }
171 },
172 None => (0.0, 0.0),
173 };
174 let rest: f32 = body.get_restitution();
175 let min_x: f32 = arena.get_x() + half_w;
176 let max_x: f32 = arena.right() - half_w;
177 let min_y: f32 = arena.get_y() + half_h;
178 let max_y: f32 = arena.bottom() - half_h;
179 if nx < min_x {
180 nx = min_x;
181 vel.set_vx(vel.get_vx().abs() * rest);
182 } else if nx > max_x {
183 nx = max_x;
184 vel.set_vx(-vel.get_vx().abs() * rest);
185 }
186 if ny < min_y {
187 ny = min_y;
188 vel.set_vy(vel.get_vy().abs() * rest);
189 } else if ny > max_y {
190 ny = max_y;
191 vel.set_vy(-vel.get_vy().abs() * rest);
192 }
193 }
194 let next_rot: f32 =
195 ent.get_transform().get_rotation_rad() + vel.get_angular() * dt_secs;
196 ent.set_velocity(vel);
197 ent.get_mut_transform().set_position(Point::new(nx, ny));
198 ent.get_mut_transform().set_rotation_rad(next_rot);
199 integrated += 1;
200 }
201 }
202 }
203 if let Some(col) = ent.collider_component() {
204 let aabb: Rect = col.world_aabb(ent.get_transform().get_position());
205 let min_cx: i32 = (aabb.get_x() * inv_cell).floor() as i32;
206 let max_cx: i32 = (aabb.right() * inv_cell).floor() as i32;
207 let min_cy: i32 = (aabb.get_y() * inv_cell).floor() as i32;
208 let max_cy: i32 = (aabb.bottom() * inv_cell).floor() as i32;
209 for cy in min_cy..=max_cy {
210 for cx in min_cx..=max_cx {
211 self.get_mut_grid().entry((cx, cy)).or_default().push(idx);
212 }
213 }
214 }
215 }
216 let mut candidate_pairs: Vec<(usize, usize)> = Vec::new();
217 {
218 let Self {
219 grid, seen_pairs, ..
220 } = self;
221 for bucket in grid.values() {
222 let n: usize = bucket.len();
223 for i in 0..n {
224 let a: usize = bucket[i];
225 for &b in &bucket[(i + 1)..] {
226 let pair: (usize, usize) = if a < b { (a, b) } else { (b, a) };
227 if seen_pairs.insert(pair) {
228 candidate_pairs.push(pair);
229 }
230 }
231 }
232 }
233 }
234 let broad_count: usize = candidate_pairs.len();
235 let mut events: Vec<CollisionEvent> = Vec::new();
236 for (ia, ib) in candidate_pairs.into_iter() {
237 let (id_a, pos_a, vel_a, body_a, col_a): (
238 EntityId,
239 Point,
240 Velocity2D,
241 RigidBody2D,
242 Collider2D,
243 ) = {
244 let ent: &EntityRecord = &world.get_entities()[ia];
245 let Some(col) = ent.collider_component() else {
246 continue;
247 };
248 (
249 ent.get_id(),
250 ent.get_transform().get_position(),
251 ent.get_velocity(),
252 ent.body_component()
253 .unwrap_or_else(|| RigidBody2D::static_body(0.5)),
254 col,
255 )
256 };
257 let (id_b, pos_b, vel_b, body_b, col_b): (
258 EntityId,
259 Point,
260 Velocity2D,
261 RigidBody2D,
262 Collider2D,
263 ) = {
264 let ent: &EntityRecord = &world.get_entities()[ib];
265 let Some(col) = ent.collider_component() else {
266 continue;
267 };
268 (
269 ent.get_id(),
270 ent.get_transform().get_position(),
271 ent.get_velocity(),
272 ent.body_component()
273 .unwrap_or_else(|| RigidBody2D::static_body(0.5)),
274 col,
275 )
276 };
277 if (col_a.get_layer() & col_b.get_mask()) == 0
278 || (col_b.get_layer() & col_a.get_mask()) == 0
279 {
280 continue;
281 }
282 let Some((normal, penetration)) =
283 Self::narrow_phase(pos_a, col_a.get_shape(), pos_b, col_b.get_shape())
284 else {
285 continue;
286 };
287 let is_trigger: bool = col_a.get_is_trigger() || col_b.get_is_trigger();
288 events.push(CollisionEvent::new(
289 id_a,
290 id_b,
291 normal,
292 penetration,
293 is_trigger,
294 ));
295 if is_trigger {
296 continue;
297 }
298 let inv_a: f32 = body_a.get_inv_mass();
299 let inv_b: f32 = body_b.get_inv_mass();
300 let inv_sum: f32 = inv_a + inv_b;
301 if inv_sum <= 0.0 {
302 continue;
303 }
304 let corr_mag: f32 = (penetration / inv_sum) * cfg.get_position_correction();
305 let corr_x: f32 = normal.get_x() * corr_mag;
306 let corr_y: f32 = normal.get_y() * corr_mag;
307 let next_pos_a: Point = Point::new(
308 pos_a.get_x() - corr_x * inv_a,
309 pos_a.get_y() - corr_y * inv_a,
310 );
311 let next_pos_b: Point = Point::new(
312 pos_b.get_x() + corr_x * inv_b,
313 pos_b.get_y() + corr_y * inv_b,
314 );
315 let rvx: f32 = vel_b.get_vx() - vel_a.get_vx();
316 let rvy: f32 = vel_b.get_vy() - vel_a.get_vy();
317 let vel_along_normal: f32 = rvx * normal.get_x() + rvy * normal.get_y();
318 let mut next_vel_a: Velocity2D = vel_a;
319 let mut next_vel_b: Velocity2D = vel_b;
320 if vel_along_normal < 0.0 {
321 let e: f32 = body_a.get_restitution().min(body_b.get_restitution());
322 let j: f32 = -(1.0 + e) * vel_along_normal / inv_sum;
323 let imp_x: f32 = j * normal.get_x();
324 let imp_y: f32 = j * normal.get_y();
325 next_vel_a.set_vx(vel_a.get_vx() - imp_x * inv_a);
326 next_vel_a.set_vy(vel_a.get_vy() - imp_y * inv_a);
327 next_vel_b.set_vx(vel_b.get_vx() + imp_x * inv_b);
328 next_vel_b.set_vy(vel_b.get_vy() + imp_y * inv_b);
329 }
330 world.get_mut_entities()[ia]
331 .get_mut_transform()
332 .set_position(next_pos_a);
333 world.get_mut_entities()[ia].set_velocity(next_vel_a);
334 world.get_mut_entities()[ib]
335 .get_mut_transform()
336 .set_position(next_pos_b);
337 world.get_mut_entities()[ib].set_velocity(next_vel_b);
338 }
339 self.set_last_stats(PhysicsStepStats::new(integrated, broad_count, events.len()));
340 events
341 }
342
343 #[must_use]
357 pub fn raycast(
358 world: &GameWorld,
359 origin: Point,
360 direction: Point,
361 max_distance: f32,
362 layer_mask: u32,
363 ) -> Option<RaycastHit> {
364 let len: f32 =
365 (direction.get_x() * direction.get_x() + direction.get_y() * direction.get_y()).sqrt();
366 if len <= 1e-6 || max_distance <= 0.0 {
367 return None;
368 }
369 let dx: f32 = direction.get_x() / len;
370 let dy: f32 = direction.get_y() / len;
371 let mut closest: Option<RaycastHit> = None;
372 let mut best_t: f32 = max_distance;
373 for ent in world.get_entities().iter() {
374 if !ent.get_alive() {
375 continue;
376 }
377 let Some(col) = ent.collider_component() else {
378 continue;
379 };
380 if (col.get_layer() & layer_mask) == 0 {
381 continue;
382 }
383 let pos: Point = ent.get_transform().get_position();
384 let hit_opt: Option<(f32, Point)> = match col.get_shape() {
385 ColliderShape::Circle { radius } => {
386 Self::ray_vs_circle(origin, (dx, dy), pos, radius, best_t)
387 }
388 ColliderShape::Aabb { width, height } => Self::ray_vs_aabb(
389 origin,
390 (dx, dy),
391 Rect::new(
392 pos.get_x() - width * 0.5,
393 pos.get_y() - height * 0.5,
394 width,
395 height,
396 ),
397 best_t,
398 ),
399 };
400 if let Some((t, normal)) = hit_opt
401 && t < best_t
402 {
403 best_t = t;
404 let hit_pt: Point = Point::new(origin.get_x() + dx * t, origin.get_y() + dy * t);
405 closest = Some(RaycastHit::new(ent.get_id(), hit_pt, normal, t));
406 }
407 }
408 closest
409 }
410
411 #[must_use]
422 pub fn raycast_query(world: &GameWorld, query: &RaycastQuery2D) -> Option<RaycastHit> {
423 Self::raycast(
424 world,
425 query.get_origin(),
426 query.get_direction(),
427 query.get_max_distance(),
428 query.get_layer_mask(),
429 )
430 }
431
432 fn narrow_phase(
445 pos_a: Point,
446 shape_a: ColliderShape,
447 pos_b: Point,
448 shape_b: ColliderShape,
449 ) -> Option<(Point, f32)> {
450 match (shape_a, shape_b) {
451 (ColliderShape::Circle { radius: ra }, ColliderShape::Circle { radius: rb }) => {
452 let dx: f32 = pos_b.get_x() - pos_a.get_x();
453 let dy: f32 = pos_b.get_y() - pos_a.get_y();
454 let r_sum: f32 = ra + rb;
455 let dist_sq: f32 = dx * dx + dy * dy;
456 if dist_sq >= r_sum * r_sum {
457 return None;
458 }
459 let dist: f32 = dist_sq.sqrt();
460 if dist <= 1e-5 {
461 Some((Point::new(1.0, 0.0), r_sum))
462 } else {
463 Some((Point::new(dx / dist, dy / dist), r_sum - dist))
464 }
465 }
466 (
467 ColliderShape::Aabb {
468 width: wa,
469 height: ha,
470 },
471 ColliderShape::Aabb {
472 width: wb,
473 height: hb,
474 },
475 ) => {
476 let dx: f32 = pos_b.get_x() - pos_a.get_x();
477 let dy: f32 = pos_b.get_y() - pos_a.get_y();
478 let ox: f32 = (wa + wb) * 0.5 - dx.abs();
479 if ox <= 0.0 {
480 return None;
481 }
482 let oy: f32 = (ha + hb) * 0.5 - dy.abs();
483 if oy <= 0.0 {
484 return None;
485 }
486 if ox < oy {
487 let nx: f32 = if dx < 0.0 { -1.0 } else { 1.0 };
488 Some((Point::new(nx, 0.0), ox))
489 } else {
490 let ny: f32 = if dy < 0.0 { -1.0 } else { 1.0 };
491 Some((Point::new(0.0, ny), oy))
492 }
493 }
494 (ColliderShape::Circle { radius }, ColliderShape::Aabb { width, height }) => {
495 Self::circle_vs_aabb(pos_a, radius, pos_b, width, height)
496 }
497 (ColliderShape::Aabb { width, height }, ColliderShape::Circle { radius }) => {
498 Self::circle_vs_aabb(pos_b, radius, pos_a, width, height)
499 .map(|(n, pen): (Point, f32)| (Point::new(-n.get_x(), -n.get_y()), pen))
500 }
501 }
502 }
503
504 fn circle_vs_aabb(
518 c_pos: Point,
519 radius: f32,
520 b_pos: Point,
521 bw: f32,
522 bh: f32,
523 ) -> Option<(Point, f32)> {
524 let half_w: f32 = bw * 0.5;
525 let half_h: f32 = bh * 0.5;
526 let rel_x: f32 = c_pos.get_x() - b_pos.get_x();
527 let rel_y: f32 = c_pos.get_y() - b_pos.get_y();
528 let closest_x: f32 = rel_x.clamp(-half_w, half_w);
529 let closest_y: f32 = rel_y.clamp(-half_h, half_h);
530 let dx: f32 = rel_x - closest_x;
531 let dy: f32 = rel_y - closest_y;
532 let dist_sq: f32 = dx * dx + dy * dy;
533 if dist_sq >= radius * radius {
534 return None;
535 }
536 let dist: f32 = dist_sq.sqrt();
537 if dist <= 1e-5 {
538 let ox: f32 = half_w - rel_x.abs();
539 let oy: f32 = half_h - rel_y.abs();
540 if ox < oy {
541 let nx: f32 = if rel_x < 0.0 { 1.0 } else { -1.0 };
542 Some((Point::new(nx, 0.0), ox + radius))
543 } else {
544 let ny: f32 = if rel_y < 0.0 { 1.0 } else { -1.0 };
545 Some((Point::new(0.0, ny), oy + radius))
546 }
547 } else {
548 Some((Point::new(-dx / dist, -dy / dist), radius - dist))
549 }
550 }
551
552 fn ray_vs_circle(
566 origin: Point,
567 dir: (f32, f32),
568 center: Point,
569 radius: f32,
570 max_dist: f32,
571 ) -> Option<(f32, Point)> {
572 let oc_x: f32 = origin.get_x() - center.get_x();
573 let oc_y: f32 = origin.get_y() - center.get_y();
574 let b: f32 = oc_x * dir.0 + oc_y * dir.1;
575 let c: f32 = oc_x * oc_x + oc_y * oc_y - radius * radius;
576 let disc: f32 = b * b - c;
577 if disc < 0.0 {
578 return None;
579 }
580 let t: f32 = -b - disc.sqrt();
581 if t < 0.0 || t > max_dist {
582 return None;
583 }
584 let hx: f32 = origin.get_x() + dir.0 * t;
585 let hy: f32 = origin.get_y() + dir.1 * t;
586 let inv_r: f32 = 1.0 / radius.max(1e-5);
587 Some((
588 t,
589 Point::new((hx - center.get_x()) * inv_r, (hy - center.get_y()) * inv_r),
590 ))
591 }
592
593 fn ray_vs_aabb(
606 origin: Point,
607 dir: (f32, f32),
608 rect: Rect,
609 max_dist: f32,
610 ) -> Option<(f32, Point)> {
611 let mut t_min: f32 = 0.0;
612 let mut t_max: f32 = max_dist;
613 let mut normal: Point = Point::new(0.0, 0.0);
614 if dir.0.abs() < 1e-6 {
615 if origin.get_x() < rect.get_x() || origin.get_x() > rect.right() {
616 return None;
617 }
618 } else {
619 let inv: f32 = 1.0 / dir.0;
620 let mut t1: f32 = (rect.get_x() - origin.get_x()) * inv;
621 let mut t2: f32 = (rect.right() - origin.get_x()) * inv;
622 let mut nx: f32 = -1.0;
623 if t1 > t2 {
624 swap(&mut t1, &mut t2);
625 nx = 1.0;
626 }
627 if t1 > t_min {
628 t_min = t1;
629 normal = Point::new(nx, 0.0);
630 }
631 t_max = t_max.min(t2);
632 if t_min > t_max {
633 return None;
634 }
635 }
636 if dir.1.abs() < 1e-6 {
637 if origin.get_y() < rect.get_y() || origin.get_y() > rect.bottom() {
638 return None;
639 }
640 } else {
641 let inv: f32 = 1.0 / dir.1;
642 let mut t1: f32 = (rect.get_y() - origin.get_y()) * inv;
643 let mut t2: f32 = (rect.bottom() - origin.get_y()) * inv;
644 let mut ny: f32 = -1.0;
645 if t1 > t2 {
646 swap(&mut t1, &mut t2);
647 ny = 1.0;
648 }
649 if t1 > t_min {
650 t_min = t1;
651 normal = Point::new(0.0, ny);
652 }
653 t_max = t_max.min(t2);
654 if t_min > t_max {
655 return None;
656 }
657 }
658 Some((t_min, normal))
659 }
660}