Skip to main content

euv_core/game/physics/
impl.rs

1use super::*;
2
3/// Default zero-gravity top-down 2D physics configuration.
4impl Default for PhysicsConfig {
5    /// Creates a default zero-gravity `PhysicsConfig` with `64px` spatial-hash cells.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - Default physics configuration.
10    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
20/// Default empty 2D physics world.
21impl Default for PhysicsWorld2D {
22    /// Creates a `PhysicsWorld2D` using `PhysicsConfig::default()`.
23    ///
24    /// # Returns
25    ///
26    /// - `Self` - Ready physics world.
27    fn default() -> Self {
28        Self::with_config(PhysicsConfig::default())
29    }
30}
31
32/// Fluent query builder for `RaycastQuery2D`.
33impl RaycastQuery2D {
34    /// Creates a 2D raycast query from `origin` along `direction` with default `1000.0` distance and all layers enabled.
35    ///
36    /// # Arguments
37    ///
38    /// - `Point` - Ray origin.
39    /// - `Point` - Ray direction vector.
40    ///
41    /// # Returns
42    ///
43    /// - `Self` - Ready raycast query.
44    #[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    /// Sets maximum travel distance for the raycast.
55    ///
56    /// # Arguments
57    ///
58    /// - `Self` - Source query.
59    /// - `f32` - Maximum distance in world units.
60    ///
61    /// # Returns
62    ///
63    /// - `Self` - Updated query.
64    #[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    /// Sets the collision layer filter bitmask for the raycast.
71    ///
72    /// # Arguments
73    ///
74    /// - `Self` - Source query.
75    /// - `u32` - Collision layer bitmask.
76    ///
77    /// # Returns
78    ///
79    /// - `Self` - Updated query.
80    #[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
87/// Broad-phase flat spatial grid, narrow-phase contact resolution, and raycasting for `PhysicsWorld2D`.
88impl PhysicsWorld2D {
89    /// Creates a `PhysicsWorld2D` configured with `config`.
90    ///
91    /// # Arguments
92    ///
93    /// - `PhysicsConfig` - Physics simulation parameters.
94    ///
95    /// # Returns
96    ///
97    /// - `Self` - Configured 2D physics solver.
98    #[must_use]
99    pub fn with_config(config: PhysicsConfig) -> Self {
100        Self {
101            config,
102            body_bounds: Vec::with_capacity(64),
103            cell_counts: Vec::with_capacity(512),
104            cell_offsets: Vec::with_capacity(512),
105            cell_cursors: Vec::with_capacity(512),
106            cell_items: Vec::with_capacity(256),
107            active_cells: Vec::with_capacity(128),
108            sparse_table: Vec::new(),
109            sparse_nodes: Vec::new(),
110            sparse_active: Vec::new(),
111            sparse_bucket_scratch: Vec::new(),
112            events_scratch: Vec::with_capacity(64),
113            touched_dense_cells: Vec::with_capacity(256),
114            touched_sparse_slots: Vec::new(),
115            grid_min_cx: 0,
116            grid_min_cy: 0,
117            grid_w: 0,
118            grid_h: 0,
119            grid_cell_size: DEFAULT_SPATIAL_CELL_SIZE,
120            grid_dense_valid: false,
121            last_stats: PhysicsStepStats::default(),
122        }
123    }
124
125    /// Returns a read-only slice of collision events recorded during the most recent `step` or `step_in_place`.
126    ///
127    /// # Arguments
128    ///
129    /// - `&Self` - Physics world reference.
130    ///
131    /// # Returns
132    ///
133    /// - `&[CollisionEvent]` - Persistent contact events slice.
134    #[must_use]
135    pub fn last_events(&self) -> &[CollisionEvent] {
136        let Self { events_scratch, .. } = self;
137        events_scratch.as_slice()
138    }
139
140    /// Packs `(cx, cy)` integer coordinates into a unique 64-bit hash key reserving `u64::MAX` for empty slots.
141    ///
142    /// # Arguments
143    ///
144    /// - `i32` - Grid cell X coordinate.
145    /// - `i32` - Grid cell Y coordinate.
146    ///
147    /// # Returns
148    ///
149    /// - `u64` - Unique cell key in `0..u64::MAX`.
150    #[inline(always)]
151    #[must_use]
152    fn pack_cell_key(cx: i32, cy: i32) -> u64 {
153        let raw: u64 = ((cx as u32 as u64) << 32) | (cy as u32 as u64);
154        if raw == u64::MAX { u64::MAX - 1 } else { raw }
155    }
156
157    /// Evaluates narrow-phase contact and applies Baumgarte separation and impulse response for one deduplicated entity pair.
158    ///
159    /// # Arguments
160    ///
161    /// - `&mut [EntityRecord]` - Mutable ECS entity slice.
162    /// - `usize` - First entity arena index.
163    /// - `usize` - Second entity arena index.
164    /// - `f32` - Baumgarte positional correction factor.
165    /// - `&mut Vec<CollisionEvent>` - Output contact event buffer.
166    #[inline]
167    fn resolve_pair(
168        entities: &mut [EntityRecord],
169        ia: usize,
170        ib: usize,
171        pos_corr: f32,
172        events: &mut Vec<CollisionEvent>,
173    ) {
174        let (id_a, pos_a, vel_a, body_a, col_a): (
175            EntityId,
176            Point,
177            Velocity2D,
178            RigidBody2D,
179            Collider2D,
180        ) = {
181            let ent: &EntityRecord = &entities[ia];
182            let Some(col) = ent.collider_component() else {
183                return;
184            };
185            (
186                ent.get_id(),
187                ent.get_transform().get_position(),
188                ent.get_velocity(),
189                ent.body_component()
190                    .unwrap_or_else(|| RigidBody2D::static_body(0.5)),
191                col,
192            )
193        };
194        let (id_b, pos_b, vel_b, body_b, col_b): (
195            EntityId,
196            Point,
197            Velocity2D,
198            RigidBody2D,
199            Collider2D,
200        ) = {
201            let ent: &EntityRecord = &entities[ib];
202            let Some(col) = ent.collider_component() else {
203                return;
204            };
205            (
206                ent.get_id(),
207                ent.get_transform().get_position(),
208                ent.get_velocity(),
209                ent.body_component()
210                    .unwrap_or_else(|| RigidBody2D::static_body(0.5)),
211                col,
212            )
213        };
214        let Some((normal, penetration)) =
215            Self::narrow_phase(pos_a, col_a.get_shape(), pos_b, col_b.get_shape())
216        else {
217            return;
218        };
219        let is_trigger: bool = col_a.get_is_trigger() || col_b.get_is_trigger();
220        events.push(CollisionEvent::new(
221            id_a,
222            id_b,
223            normal,
224            penetration,
225            is_trigger,
226        ));
227        if is_trigger {
228            return;
229        }
230        let inv_a: f32 = body_a.get_inv_mass();
231        let inv_b: f32 = body_b.get_inv_mass();
232        let inv_sum: f32 = inv_a + inv_b;
233        if inv_sum <= 0.0 {
234            return;
235        }
236        let corr_mag: f32 = (penetration / inv_sum) * pos_corr;
237        let nx_n: f32 = normal.get_x();
238        let ny_n: f32 = normal.get_y();
239        let corr_x: f32 = nx_n * corr_mag;
240        let corr_y: f32 = ny_n * corr_mag;
241        let next_pos_a: Point = Point::new(
242            pos_a.get_x() - corr_x * inv_a,
243            pos_a.get_y() - corr_y * inv_a,
244        );
245        let next_pos_b: Point = Point::new(
246            pos_b.get_x() + corr_x * inv_b,
247            pos_b.get_y() + corr_y * inv_b,
248        );
249        let rvx: f32 = vel_b.get_vx() - vel_a.get_vx();
250        let rvy: f32 = vel_b.get_vy() - vel_a.get_vy();
251        let vel_along_normal: f32 = rvx * nx_n + rvy * ny_n;
252        let mut next_vel_a: Velocity2D = vel_a;
253        let mut next_vel_b: Velocity2D = vel_b;
254        if vel_along_normal < 0.0 {
255            let e: f32 = body_a.get_restitution().min(body_b.get_restitution());
256            let j: f32 = -(1.0 + e) * vel_along_normal / inv_sum;
257            let imp_x: f32 = j * nx_n;
258            let imp_y: f32 = j * ny_n;
259            next_vel_a.set_vx(vel_a.get_vx() - imp_x * inv_a);
260            next_vel_a.set_vy(vel_a.get_vy() - imp_y * inv_a);
261            next_vel_b.set_vx(vel_b.get_vx() + imp_x * inv_b);
262            next_vel_b.set_vy(vel_b.get_vy() + imp_y * inv_b);
263        }
264        entities[ia].get_mut_transform().set_position(next_pos_a);
265        entities[ia].set_velocity(next_vel_a);
266        entities[ib].get_mut_transform().set_position(next_pos_b);
267        entities[ib].set_velocity(next_vel_b);
268    }
269
270    /// Integrates velocities/positions, resolves flat spatial-grid collisions using touched-cell clearing and persistent event storage with zero steady-state allocations, and returns a borrowed event slice.
271    ///
272    /// # Arguments
273    ///
274    /// - `&Self` - Mutable physics world.
275    /// - `&mut GameWorld` - Mutable ECS world containing entities and colliders.
276    /// - `f32` - Fixed physics timestep in seconds.
277    ///
278    /// # Returns
279    ///
280    /// - `&[CollisionEvent]` - Borrowed slice of solid and trigger contacts detected this step.
281    pub fn step_in_place(&mut self, world: &mut GameWorld, dt_secs: f32) -> &[CollisionEvent] {
282        let cfg: PhysicsConfig = self.get_config();
283        let gx_dt: f32 = cfg.get_gravity().get_x() * dt_secs;
284        let gy_dt: f32 = cfg.get_gravity().get_y() * dt_secs;
285        let pos_corr: f32 = cfg.get_position_correction();
286        let cell_size: f32 = cfg.get_cell_size().max(8.0);
287        let inv_cell: f32 = 1.0 / cell_size;
288        let arena_opt: Option<Rect> = {
289            let PhysicsConfig { arena_bounds, .. } = cfg;
290            arena_bounds
291        };
292        let Self {
293            body_bounds,
294            cell_counts,
295            cell_offsets,
296            cell_cursors,
297            cell_items,
298            active_cells,
299            sparse_table,
300            sparse_nodes,
301            sparse_active,
302            sparse_bucket_scratch,
303            events_scratch,
304            touched_dense_cells,
305            touched_sparse_slots,
306            grid_min_cx: stored_min_cx,
307            grid_min_cy: stored_min_cy,
308            grid_w: stored_grid_w,
309            grid_h: stored_grid_h,
310            grid_cell_size: stored_cell_size,
311            grid_dense_valid,
312            ..
313        } = self;
314        body_bounds.clear();
315        events_scratch.clear();
316        *grid_dense_valid = false;
317        let mut integrated: usize = 0;
318        let mut grid_min_cx: i32 = i32::MAX;
319        let mut grid_max_cx: i32 = i32::MIN;
320        let mut grid_min_cy: i32 = i32::MAX;
321        let mut grid_max_cy: i32 = i32::MIN;
322        let mut total_cell_refs: usize = 0;
323        let entities: &mut [EntityRecord] = world.get_mut_entities().as_mut_slice();
324        for (idx, ent) in entities.iter_mut().enumerate() {
325            if !ent.get_alive() {
326                continue;
327            }
328            if let Some(body) = ent.body_component() {
329                match body.get_kind() {
330                    BodyKind::Static => {}
331                    BodyKind::Kinematic => {
332                        let vel: Velocity2D = ent.get_velocity();
333                        let pos: Point = ent.get_transform().get_position();
334                        let next_pos: Point = Point::new(
335                            pos.get_x() + vel.get_vx() * dt_secs,
336                            pos.get_y() + vel.get_vy() * dt_secs,
337                        );
338                        let next_rot: f32 =
339                            ent.get_transform().get_rotation_rad() + vel.get_angular() * dt_secs;
340                        ent.get_mut_transform().set_position(next_pos);
341                        ent.get_mut_transform().set_rotation_rad(next_rot);
342                        integrated += 1;
343                    }
344                    BodyKind::Dynamic => {
345                        let mut vel: Velocity2D = ent.get_velocity();
346                        let g_scale: f32 = body.get_gravity_scale();
347                        let damp: f32 = (1.0 - body.get_linear_drag() * dt_secs).clamp(0.0, 1.0);
348                        vel.set_vx((vel.get_vx() + gx_dt * g_scale) * damp);
349                        vel.set_vy((vel.get_vy() + gy_dt * g_scale) * damp);
350                        let pos: Point = ent.get_transform().get_position();
351                        let mut nx: f32 = pos.get_x() + vel.get_vx() * dt_secs;
352                        let mut ny: f32 = pos.get_y() + vel.get_vy() * dt_secs;
353                        if let Some(arena) = arena_opt {
354                            let (half_w, half_h): (f32, f32) = match ent.collider_component() {
355                                Some(col) => match col.get_shape() {
356                                    ColliderShape::Circle { radius } => (radius, radius),
357                                    ColliderShape::Aabb { width, height } => {
358                                        (width * 0.5, height * 0.5)
359                                    }
360                                },
361                                None => (0.0, 0.0),
362                            };
363                            let rest: f32 = body.get_restitution();
364                            let min_x: f32 = arena.get_x() + half_w;
365                            let max_x: f32 = arena.right() - half_w;
366                            let min_y: f32 = arena.get_y() + half_h;
367                            let max_y: f32 = arena.bottom() - half_h;
368                            if nx < min_x {
369                                nx = min_x;
370                                vel.set_vx(vel.get_vx().abs() * rest);
371                            } else if nx > max_x {
372                                nx = max_x;
373                                vel.set_vx(-vel.get_vx().abs() * rest);
374                            }
375                            if ny < min_y {
376                                ny = min_y;
377                                vel.set_vy(vel.get_vy().abs() * rest);
378                            } else if ny > max_y {
379                                ny = max_y;
380                                vel.set_vy(-vel.get_vy().abs() * rest);
381                            }
382                        }
383                        let next_rot: f32 =
384                            ent.get_transform().get_rotation_rad() + vel.get_angular() * dt_secs;
385                        ent.set_velocity(vel);
386                        ent.get_mut_transform().set_position(Point::new(nx, ny));
387                        ent.get_mut_transform().set_rotation_rad(next_rot);
388                        integrated += 1;
389                    }
390                }
391            }
392            if let Some(col) = ent.collider_component() {
393                let aabb: Rect = col.world_aabb(ent.get_transform().get_position());
394                let min_cx: i32 = (aabb.get_x() * inv_cell).floor() as i32;
395                let max_cx: i32 = (aabb.right() * inv_cell).floor() as i32;
396                let min_cy: i32 = (aabb.get_y() * inv_cell).floor() as i32;
397                let max_cy: i32 = (aabb.bottom() * inv_cell).floor() as i32;
398                grid_min_cx = grid_min_cx.min(min_cx);
399                grid_max_cx = grid_max_cx.max(max_cx);
400                grid_min_cy = grid_min_cy.min(min_cy);
401                grid_max_cy = grid_max_cy.max(max_cy);
402                let span_x: usize = ((max_cx as i64) - (min_cx as i64) + 1).max(1) as usize;
403                let span_y: usize = ((max_cy as i64) - (min_cy as i64) + 1).max(1) as usize;
404                total_cell_refs = total_cell_refs.saturating_add(span_x.saturating_mul(span_y));
405                body_bounds.push(BodyGridBounds {
406                    entity_idx: idx as u32,
407                    min_cx,
408                    max_cx,
409                    min_cy,
410                    max_cy,
411                    layer: col.get_layer(),
412                    mask: col.get_mask(),
413                });
414            }
415        }
416        let mut broad_count: usize = 0;
417        if !body_bounds.is_empty() {
418            let span_x_i64: i64 = (grid_max_cx as i64) - (grid_min_cx as i64) + 1;
419            let span_y_i64: i64 = (grid_max_cy as i64) - (grid_min_cy as i64) + 1;
420            let use_dense: bool = span_x_i64 > 0
421                && span_y_i64 > 0
422                && span_x_i64 <= FLAT_GRID_MAX_AXIS
423                && span_y_i64 <= FLAT_GRID_MAX_AXIS
424                && ((span_x_i64 * span_y_i64) as usize) <= FLAT_GRID_MAX_CELLS;
425            if use_dense {
426                let grid_w: usize = span_x_i64 as usize;
427                let grid_h: usize = span_y_i64 as usize;
428                let grid_cells: usize = grid_w * grid_h;
429                for &cidx in touched_dense_cells.iter() {
430                    if cidx < cell_counts.len() {
431                        cell_counts[cidx] = 0;
432                    }
433                    if cidx < cell_offsets.len() {
434                        cell_offsets[cidx] = 0;
435                    }
436                    if cidx < cell_cursors.len() {
437                        cell_cursors[cidx] = 0;
438                    }
439                }
440                touched_dense_cells.clear();
441                if cell_counts.len() < grid_cells {
442                    cell_counts.resize(grid_cells, 0);
443                }
444                if cell_offsets.len() < grid_cells {
445                    cell_offsets.resize(grid_cells, 0);
446                }
447                if cell_cursors.len() < grid_cells {
448                    cell_cursors.resize(grid_cells, 0);
449                }
450                for b in body_bounds.iter() {
451                    let rx0: usize = (b.min_cx - grid_min_cx) as usize;
452                    let rx1: usize = (b.max_cx - grid_min_cx) as usize;
453                    let ry0: usize = (b.min_cy - grid_min_cy) as usize;
454                    let ry1: usize = (b.max_cy - grid_min_cy) as usize;
455                    for ry in ry0..=ry1 {
456                        let row_off: usize = ry * grid_w;
457                        for rx in rx0..=rx1 {
458                            let cidx: usize = row_off + rx;
459                            let prev: u32 = cell_counts[cidx];
460                            if prev == 0 {
461                                touched_dense_cells.push(cidx);
462                            }
463                            cell_counts[cidx] = prev + 1;
464                        }
465                    }
466                }
467                active_cells.clear();
468                let mut running: u32 = 0;
469                for &cidx in touched_dense_cells.iter() {
470                    let cnt: u32 = cell_counts[cidx];
471                    cell_offsets[cidx] = running;
472                    cell_cursors[cidx] = running;
473                    running += cnt;
474                    if cnt >= 2 {
475                        let ry: usize = cidx / grid_w;
476                        let rx: usize = cidx - ry * grid_w;
477                        active_cells.push((
478                            cidx,
479                            grid_min_cx + (rx as i32),
480                            grid_min_cy + (ry as i32),
481                        ));
482                    }
483                }
484                if cell_items.len() < (running as usize) {
485                    cell_items.resize(running as usize, 0);
486                }
487                for (slot_idx, b) in body_bounds.iter().enumerate() {
488                    let slot_u32: u32 = slot_idx as u32;
489                    let rx0: usize = (b.min_cx - grid_min_cx) as usize;
490                    let rx1: usize = (b.max_cx - grid_min_cx) as usize;
491                    let ry0: usize = (b.min_cy - grid_min_cy) as usize;
492                    let ry1: usize = (b.max_cy - grid_min_cy) as usize;
493                    for ry in ry0..=ry1 {
494                        let row_off: usize = ry * grid_w;
495                        for rx in rx0..=rx1 {
496                            let cidx: usize = row_off + rx;
497                            let dst: usize = cell_cursors[cidx] as usize;
498                            cell_items[dst] = slot_u32;
499                            cell_cursors[cidx] = (dst + 1) as u32;
500                        }
501                    }
502                }
503                *stored_min_cx = grid_min_cx;
504                *stored_min_cy = grid_min_cy;
505                *stored_grid_w = grid_w;
506                *stored_grid_h = grid_h;
507                *stored_cell_size = cell_size;
508                *grid_dense_valid = true;
509                if body_bounds.len() >= 2 {
510                    for &(cidx, cx, cy) in active_cells.iter() {
511                        let start: usize = cell_offsets[cidx] as usize;
512                        let end: usize = cell_cursors[cidx] as usize;
513                        let bucket: &[u32] = &cell_items[start..end];
514                        let n: usize = bucket.len();
515                        for i in 0..n {
516                            let ba: BodyGridBounds = body_bounds[bucket[i] as usize];
517                            for &sb_u32 in &bucket[(i + 1)..] {
518                                let bb: BodyGridBounds = body_bounds[sb_u32 as usize];
519                                if ba.min_cx.max(bb.min_cx) == cx && ba.min_cy.max(bb.min_cy) == cy
520                                {
521                                    broad_count += 1;
522                                    if (ba.layer & bb.mask) != 0 && (bb.layer & ba.mask) != 0 {
523                                        Self::resolve_pair(
524                                            entities,
525                                            ba.entity_idx as usize,
526                                            bb.entity_idx as usize,
527                                            pos_corr,
528                                            events_scratch,
529                                        );
530                                    }
531                                }
532                            }
533                        }
534                    }
535                }
536            } else if body_bounds.len() >= 2 {
537                let needed_cap: usize = (total_cell_refs.saturating_mul(2).max(64))
538                    .next_power_of_two()
539                    .max(64);
540                let empty_cell: SparseGridCell = SparseGridCell {
541                    key: u64::MAX,
542                    cx: 0,
543                    cy: 0,
544                    head: u32::MAX,
545                    count: 0,
546                };
547                if sparse_table.len() < needed_cap {
548                    sparse_table.resize(needed_cap, empty_cell);
549                    for &slot_idx in touched_sparse_slots.iter() {
550                        if slot_idx < sparse_table.len() {
551                            sparse_table[slot_idx] = empty_cell;
552                        }
553                    }
554                } else {
555                    for &slot_idx in touched_sparse_slots.iter() {
556                        if slot_idx < sparse_table.len() {
557                            sparse_table[slot_idx] = empty_cell;
558                        }
559                    }
560                }
561                touched_sparse_slots.clear();
562                let cap: usize = sparse_table.len();
563                let mask: usize = cap - 1;
564                sparse_nodes.clear();
565                sparse_active.clear();
566                for (slot_idx, b) in body_bounds.iter().enumerate() {
567                    let slot_u32: u32 = slot_idx as u32;
568                    for cy in b.min_cy..=b.max_cy {
569                        for cx in b.min_cx..=b.max_cx {
570                            let key: u64 = Self::pack_cell_key(cx, cy);
571                            let mut h: usize =
572                                (key.wrapping_mul(SPARSE_GRID_HASH_MULT) >> 32) as usize & mask;
573                            loop {
574                                let cell: &mut SparseGridCell = &mut sparse_table[h];
575                                if cell.key == u64::MAX {
576                                    cell.key = key;
577                                    cell.cx = cx;
578                                    cell.cy = cy;
579                                    let node_idx: u32 = sparse_nodes.len() as u32;
580                                    sparse_nodes.push(SparseGridNode {
581                                        body_slot: slot_u32,
582                                        next: u32::MAX,
583                                    });
584                                    cell.head = node_idx;
585                                    cell.count = 1;
586                                    touched_sparse_slots.push(h);
587                                    break;
588                                } else if cell.key == key {
589                                    let prev_head: u32 = cell.head;
590                                    let node_idx: u32 = sparse_nodes.len() as u32;
591                                    sparse_nodes.push(SparseGridNode {
592                                        body_slot: slot_u32,
593                                        next: prev_head,
594                                    });
595                                    cell.head = node_idx;
596                                    cell.count += 1;
597                                    if cell.count == 2 {
598                                        sparse_active.push(h);
599                                    }
600                                    break;
601                                }
602                                h = (h + 1) & mask;
603                            }
604                        }
605                    }
606                }
607                for &table_idx in sparse_active.iter() {
608                    let cell: SparseGridCell = sparse_table[table_idx];
609                    sparse_bucket_scratch.clear();
610                    let mut cur: u32 = cell.head;
611                    while cur != u32::MAX {
612                        let node: SparseGridNode = sparse_nodes[cur as usize];
613                        sparse_bucket_scratch.push(node.body_slot);
614                        cur = node.next;
615                    }
616                    sparse_bucket_scratch.reverse();
617                    let n: usize = sparse_bucket_scratch.len();
618                    for i in 0..n {
619                        let ba: BodyGridBounds = body_bounds[sparse_bucket_scratch[i] as usize];
620                        for &sb_u32 in &sparse_bucket_scratch[(i + 1)..] {
621                            let bb: BodyGridBounds = body_bounds[sb_u32 as usize];
622                            if ba.min_cx.max(bb.min_cx) == cell.cx
623                                && ba.min_cy.max(bb.min_cy) == cell.cy
624                            {
625                                broad_count += 1;
626                                if (ba.layer & bb.mask) != 0 && (bb.layer & ba.mask) != 0 {
627                                    Self::resolve_pair(
628                                        entities,
629                                        ba.entity_idx as usize,
630                                        bb.entity_idx as usize,
631                                        pos_corr,
632                                        events_scratch,
633                                    );
634                                }
635                            }
636                        }
637                    }
638                }
639            }
640        }
641        world.sync_soa_from_entities();
642        let event_count: usize = events_scratch.len();
643        self.set_last_stats(PhysicsStepStats::new(integrated, broad_count, event_count));
644        self.last_events()
645    }
646
647    /// Integrates velocities/positions, resolves flat spatial-grid collisions and arena bounds, and returns contact events.
648    ///
649    /// # Arguments
650    ///
651    /// - `&Self` - Mutable physics world.
652    /// - `&mut GameWorld` - Mutable ECS world containing entities and colliders.
653    /// - `f32` - Fixed physics timestep in seconds.
654    ///
655    /// # Returns
656    ///
657    /// - `Vec<CollisionEvent>` - All solid and trigger contacts detected this step.
658    pub fn step(&mut self, world: &mut GameWorld, dt_secs: f32) -> Vec<CollisionEvent> {
659        let slice: &[CollisionEvent] = self.step_in_place(world, dt_secs);
660        if slice.is_empty() {
661            Vec::new()
662        } else {
663            slice.to_vec()
664        }
665    }
666
667    /// Casts a 2D ray using Amanatides-Woo spatial-grid DDA over the persistent broad-phase grid built by `step` / `step_in_place`.
668    ///
669    /// Falls back automatically to `PhysicsWorld2D::raycast` if the dense grid has not yet been populated.
670    ///
671    /// # Arguments
672    ///
673    /// - `&Self` - Physics world holding the populated spatial grid.
674    /// - `&GameWorld` - Game world to query.
675    /// - `Point` - Ray origin in world units.
676    /// - `Point` - Ray direction vector (normalized automatically).
677    /// - `f32` - Maximum ray distance.
678    /// - `u32` - Layer bitmask filter.
679    ///
680    /// # Returns
681    ///
682    /// - `Option<RaycastHit>` - Closest ray intersection hit, if any.
683    #[must_use]
684    pub fn raycast_grid(
685        &self,
686        world: &GameWorld,
687        origin: Point,
688        direction: Point,
689        max_distance: f32,
690        layer_mask: u32,
691    ) -> Option<RaycastHit> {
692        let Self {
693            body_bounds,
694            cell_offsets,
695            cell_cursors,
696            cell_items,
697            grid_min_cx,
698            grid_min_cy,
699            grid_w,
700            grid_h,
701            grid_cell_size,
702            grid_dense_valid,
703            ..
704        } = self;
705        if !*grid_dense_valid || *grid_w == 0 || *grid_h == 0 || body_bounds.is_empty() {
706            return Self::raycast(world, origin, direction, max_distance, layer_mask);
707        }
708        let len: f32 =
709            (direction.get_x() * direction.get_x() + direction.get_y() * direction.get_y()).sqrt();
710        if len <= 1e-6 || max_distance <= 0.0 {
711            return None;
712        }
713        let dx: f32 = direction.get_x() / len;
714        let dy: f32 = direction.get_y() / len;
715        let cs: f32 = (*grid_cell_size).max(8.0);
716        let inv_cs: f32 = 1.0 / cs;
717        let g_min_x: f32 = (*grid_min_cx as f32) * cs;
718        let g_min_y: f32 = (*grid_min_cy as f32) * cs;
719        let g_max_x: f32 = g_min_x + (*grid_w as f32) * cs;
720        let g_max_y: f32 = g_min_y + (*grid_h as f32) * cs;
721        let mut t_enter: f32 = 0.0;
722        let mut t_exit: f32 = max_distance;
723        if dx.abs() < 1e-7 {
724            if origin.get_x() < g_min_x || origin.get_x() > g_max_x {
725                return None;
726            }
727        } else {
728            let inv_dx: f32 = 1.0 / dx;
729            let tx0: f32 = (g_min_x - origin.get_x()) * inv_dx;
730            let tx1: f32 = (g_max_x - origin.get_x()) * inv_dx;
731            t_enter = t_enter.max(tx0.min(tx1));
732            t_exit = t_exit.min(tx0.max(tx1));
733        }
734        if dy.abs() < 1e-7 {
735            if origin.get_y() < g_min_y || origin.get_y() > g_max_y {
736                return None;
737            }
738        } else {
739            let inv_dy: f32 = 1.0 / dy;
740            let ty0: f32 = (g_min_y - origin.get_y()) * inv_dy;
741            let ty1: f32 = (g_max_y - origin.get_y()) * inv_dy;
742            t_enter = t_enter.max(ty0.min(ty1));
743            t_exit = t_exit.min(ty0.max(ty1));
744        }
745        if t_enter > t_exit {
746            return None;
747        }
748        let start_x: f32 = origin.get_x() + dx * t_enter;
749        let start_y: f32 = origin.get_y() + dy * t_enter;
750        let max_rx: i32 = (*grid_w as i32) - 1;
751        let max_ry: i32 = (*grid_h as i32) - 1;
752        let mut rx: i32 = (((start_x - g_min_x) * inv_cs).floor() as i32).clamp(0, max_rx);
753        let mut ry: i32 = (((start_y - g_min_y) * inv_cs).floor() as i32).clamp(0, max_ry);
754        let (step_x, t_delta_x, mut t_max_x): (i32, f32, f32) = if dx > 1e-7 {
755            let next_x: f32 = g_min_x + ((rx + 1) as f32) * cs;
756            (1, cs / dx, (next_x - origin.get_x()) / dx)
757        } else if dx < -1e-7 {
758            let next_x: f32 = g_min_x + (rx as f32) * cs;
759            (-1, -cs / dx, (next_x - origin.get_x()) / dx)
760        } else {
761            (0, f32::INFINITY, f32::INFINITY)
762        };
763        let (step_y, t_delta_y, mut t_max_y): (i32, f32, f32) = if dy > 1e-7 {
764            let next_y: f32 = g_min_y + ((ry + 1) as f32) * cs;
765            (1, cs / dy, (next_y - origin.get_y()) / dy)
766        } else if dy < -1e-7 {
767            let next_y: f32 = g_min_y + (ry as f32) * cs;
768            (-1, -cs / dy, (next_y - origin.get_y()) / dy)
769        } else {
770            (0, f32::INFINITY, f32::INFINITY)
771        };
772        let entities: &[EntityRecord] = world.get_entities().as_slice();
773        let mut closest: Option<RaycastHit> = None;
774        let mut best_t: f32 = max_distance;
775        let mut cell_t: f32 = t_enter;
776        let gw_usize: usize = *grid_w;
777        while rx >= 0 && rx <= max_rx && ry >= 0 && ry <= max_ry && cell_t <= best_t.min(t_exit) {
778            let cidx: usize = (ry as usize) * gw_usize + (rx as usize);
779            let start: usize = cell_offsets[cidx] as usize;
780            let end: usize = cell_cursors[cidx] as usize;
781            for &body_slot in &cell_items[start..end] {
782                let b: BodyGridBounds = body_bounds[body_slot as usize];
783                if (b.layer & layer_mask) == 0 {
784                    continue;
785                }
786                let Some(ent) = entities.get(b.entity_idx as usize) else {
787                    continue;
788                };
789                if !ent.get_alive() {
790                    continue;
791                }
792                let Some(col) = ent.collider_component() else {
793                    continue;
794                };
795                let pos: Point = ent.get_transform().get_position();
796                let hit_opt: Option<(f32, Point)> = match col.get_shape() {
797                    ColliderShape::Circle { radius } => {
798                        Self::ray_vs_circle(origin, (dx, dy), pos, radius, best_t)
799                    }
800                    ColliderShape::Aabb { width, height } => Self::ray_vs_aabb(
801                        origin,
802                        (dx, dy),
803                        Rect::new(
804                            pos.get_x() - width * 0.5,
805                            pos.get_y() - height * 0.5,
806                            width,
807                            height,
808                        ),
809                        best_t,
810                    ),
811                };
812                if let Some((t, normal)) = hit_opt
813                    && t < best_t
814                {
815                    best_t = t;
816                    let hit_pt: Point =
817                        Point::new(origin.get_x() + dx * t, origin.get_y() + dy * t);
818                    closest = Some(RaycastHit::new(ent.get_id(), hit_pt, normal, t));
819                }
820            }
821            if t_max_x < t_max_y {
822                cell_t = t_max_x;
823                t_max_x += t_delta_x;
824                rx += step_x;
825            } else {
826                cell_t = t_max_y;
827                t_max_y += t_delta_y;
828                ry += step_y;
829            }
830        }
831        closest
832    }
833
834    /// Casts a 2D ray from `origin` along normalized `direction` up to `max_distance` against colliders matching `layer_mask`.
835    ///
836    /// # Arguments
837    ///
838    /// - `&GameWorld` - Game world to query.
839    /// - `Point` - Ray origin in world units.
840    /// - `Point` - Ray direction vector (normalized automatically).
841    /// - `f32` - Maximum ray distance.
842    /// - `u32` - Layer bitmask filter.
843    ///
844    /// # Returns
845    ///
846    /// - `Option<RaycastHit>` - Closest ray intersection hit, if any.
847    #[must_use]
848    pub fn raycast(
849        world: &GameWorld,
850        origin: Point,
851        direction: Point,
852        max_distance: f32,
853        layer_mask: u32,
854    ) -> Option<RaycastHit> {
855        let len: f32 =
856            (direction.get_x() * direction.get_x() + direction.get_y() * direction.get_y()).sqrt();
857        if len <= 1e-6 || max_distance <= 0.0 {
858            return None;
859        }
860        let dx: f32 = direction.get_x() / len;
861        let dy: f32 = direction.get_y() / len;
862        let mut closest: Option<RaycastHit> = None;
863        let mut best_t: f32 = max_distance;
864        for ent in world.get_entities().iter() {
865            if !ent.get_alive() {
866                continue;
867            }
868            let Some(col) = ent.collider_component() else {
869                continue;
870            };
871            if (col.get_layer() & layer_mask) == 0 {
872                continue;
873            }
874            let pos: Point = ent.get_transform().get_position();
875            let hit_opt: Option<(f32, Point)> = match col.get_shape() {
876                ColliderShape::Circle { radius } => {
877                    Self::ray_vs_circle(origin, (dx, dy), pos, radius, best_t)
878                }
879                ColliderShape::Aabb { width, height } => Self::ray_vs_aabb(
880                    origin,
881                    (dx, dy),
882                    Rect::new(
883                        pos.get_x() - width * 0.5,
884                        pos.get_y() - height * 0.5,
885                        width,
886                        height,
887                    ),
888                    best_t,
889                ),
890            };
891            if let Some((t, normal)) = hit_opt
892                && t < best_t
893            {
894                best_t = t;
895                let hit_pt: Point = Point::new(origin.get_x() + dx * t, origin.get_y() + dy * t);
896                closest = Some(RaycastHit::new(ent.get_id(), hit_pt, normal, t));
897            }
898        }
899        closest
900    }
901
902    /// Casts a 2D ray defined by a fluent `RaycastQuery2D` against `world`.
903    ///
904    /// # Arguments
905    ///
906    /// - `&GameWorld` - Game world to query.
907    /// - `&RaycastQuery2D` - Raycast query descriptor.
908    ///
909    /// # Returns
910    ///
911    /// - `Option<RaycastHit>` - Closest ray intersection hit, if any.
912    #[must_use]
913    pub fn raycast_query(world: &GameWorld, query: &RaycastQuery2D) -> Option<RaycastHit> {
914        Self::raycast(
915            world,
916            query.get_origin(),
917            query.get_direction(),
918            query.get_max_distance(),
919            query.get_layer_mask(),
920        )
921    }
922
923    /// Evaluates narrow-phase overlap between two shapes returning `(normal_a_to_b, penetration)`.
924    ///
925    /// # Arguments
926    ///
927    /// - `Point` - Center of shape A.
928    /// - `ColliderShape` - Geometry of shape A.
929    /// - `Point` - Center of shape B.
930    /// - `ColliderShape` - Geometry of shape B.
931    ///
932    /// # Returns
933    ///
934    /// - `Option<(Point, f32)>` - Contact normal and positive penetration depth if overlapping.
935    fn narrow_phase(
936        pos_a: Point,
937        shape_a: ColliderShape,
938        pos_b: Point,
939        shape_b: ColliderShape,
940    ) -> Option<(Point, f32)> {
941        match (shape_a, shape_b) {
942            (ColliderShape::Circle { radius: ra }, ColliderShape::Circle { radius: rb }) => {
943                let dx: f32 = pos_b.get_x() - pos_a.get_x();
944                let dy: f32 = pos_b.get_y() - pos_a.get_y();
945                let r_sum: f32 = ra + rb;
946                let dist_sq: f32 = dx * dx + dy * dy;
947                if dist_sq >= r_sum * r_sum {
948                    return None;
949                }
950                let dist: f32 = dist_sq.sqrt();
951                if dist <= 1e-5 {
952                    Some((Point::new(1.0, 0.0), r_sum))
953                } else {
954                    let inv_dist: f32 = 1.0 / dist;
955                    Some((Point::new(dx * inv_dist, dy * inv_dist), r_sum - dist))
956                }
957            }
958            (
959                ColliderShape::Aabb {
960                    width: wa,
961                    height: ha,
962                },
963                ColliderShape::Aabb {
964                    width: wb,
965                    height: hb,
966                },
967            ) => {
968                let dx: f32 = pos_b.get_x() - pos_a.get_x();
969                let dy: f32 = pos_b.get_y() - pos_a.get_y();
970                let ox: f32 = (wa + wb) * 0.5 - dx.abs();
971                if ox <= 0.0 {
972                    return None;
973                }
974                let oy: f32 = (ha + hb) * 0.5 - dy.abs();
975                if oy <= 0.0 {
976                    return None;
977                }
978                if ox < oy {
979                    let nx: f32 = if dx < 0.0 { -1.0 } else { 1.0 };
980                    Some((Point::new(nx, 0.0), ox))
981                } else {
982                    let ny: f32 = if dy < 0.0 { -1.0 } else { 1.0 };
983                    Some((Point::new(0.0, ny), oy))
984                }
985            }
986            (ColliderShape::Circle { radius }, ColliderShape::Aabb { width, height }) => {
987                Self::circle_vs_aabb(pos_a, radius, pos_b, width, height)
988            }
989            (ColliderShape::Aabb { width, height }, ColliderShape::Circle { radius }) => {
990                Self::circle_vs_aabb(pos_b, radius, pos_a, width, height)
991                    .map(|(n, pen): (Point, f32)| (Point::new(-n.get_x(), -n.get_y()), pen))
992            }
993        }
994    }
995
996    /// Narrow-phase Circle-vs-AABB overlap test returning normal pointing from circle to box.
997    ///
998    /// # Arguments
999    ///
1000    /// - `Point` - Circle center.
1001    /// - `f32` - Circle radius.
1002    /// - `Point` - AABB center.
1003    /// - `f32` - AABB full width.
1004    /// - `f32` - AABB full height.
1005    ///
1006    /// # Returns
1007    ///
1008    /// - `Option<(Point, f32)>` - Contact normal and penetration depth.
1009    fn circle_vs_aabb(
1010        c_pos: Point,
1011        radius: f32,
1012        b_pos: Point,
1013        bw: f32,
1014        bh: f32,
1015    ) -> Option<(Point, f32)> {
1016        let half_w: f32 = bw * 0.5;
1017        let half_h: f32 = bh * 0.5;
1018        let rel_x: f32 = c_pos.get_x() - b_pos.get_x();
1019        let rel_y: f32 = c_pos.get_y() - b_pos.get_y();
1020        let closest_x: f32 = rel_x.clamp(-half_w, half_w);
1021        let closest_y: f32 = rel_y.clamp(-half_h, half_h);
1022        let dx: f32 = rel_x - closest_x;
1023        let dy: f32 = rel_y - closest_y;
1024        let dist_sq: f32 = dx * dx + dy * dy;
1025        if dist_sq >= radius * radius {
1026            return None;
1027        }
1028        let dist: f32 = dist_sq.sqrt();
1029        if dist <= 1e-5 {
1030            let ox: f32 = half_w - rel_x.abs();
1031            let oy: f32 = half_h - rel_y.abs();
1032            if ox < oy {
1033                let nx: f32 = if rel_x < 0.0 { 1.0 } else { -1.0 };
1034                Some((Point::new(nx, 0.0), ox + radius))
1035            } else {
1036                let ny: f32 = if rel_y < 0.0 { 1.0 } else { -1.0 };
1037                Some((Point::new(0.0, ny), oy + radius))
1038            }
1039        } else {
1040            Some((Point::new(-dx / dist, -dy / dist), radius - dist))
1041        }
1042    }
1043
1044    /// Ray-vs-circle analytic intersection test.
1045    ///
1046    /// # Arguments
1047    ///
1048    /// - `Point` - Ray origin.
1049    /// - `(f32, f32)` - Normalized ray direction.
1050    /// - `Point` - Circle center.
1051    /// - `f32` - Circle radius.
1052    /// - `f32` - Maximum distance.
1053    ///
1054    /// # Returns
1055    ///
1056    /// - `Option<(f32, Point)>` - Hit distance and outward surface normal.
1057    fn ray_vs_circle(
1058        origin: Point,
1059        dir: (f32, f32),
1060        center: Point,
1061        radius: f32,
1062        max_dist: f32,
1063    ) -> Option<(f32, Point)> {
1064        let oc_x: f32 = origin.get_x() - center.get_x();
1065        let oc_y: f32 = origin.get_y() - center.get_y();
1066        let b: f32 = oc_x * dir.0 + oc_y * dir.1;
1067        let c: f32 = oc_x * oc_x + oc_y * oc_y - radius * radius;
1068        let disc: f32 = b * b - c;
1069        if disc < 0.0 {
1070            return None;
1071        }
1072        let t: f32 = -b - disc.sqrt();
1073        if t < 0.0 || t > max_dist {
1074            return None;
1075        }
1076        let hx: f32 = origin.get_x() + dir.0 * t;
1077        let hy: f32 = origin.get_y() + dir.1 * t;
1078        let inv_r: f32 = 1.0 / radius.max(1e-5);
1079        Some((
1080            t,
1081            Point::new((hx - center.get_x()) * inv_r, (hy - center.get_y()) * inv_r),
1082        ))
1083    }
1084
1085    /// Ray-vs-AABB slab intersection test.
1086    ///
1087    /// # Arguments
1088    ///
1089    /// - `Point` - Ray origin.
1090    /// - `(f32, f32)` - Normalized ray direction.
1091    /// - `Rect` - Axis-aligned box rectangle.
1092    /// - `f32` - Maximum distance.
1093    ///
1094    /// # Returns
1095    ///
1096    /// - `Option<(f32, Point)>` - Hit distance and outward surface normal.
1097    fn ray_vs_aabb(
1098        origin: Point,
1099        dir: (f32, f32),
1100        rect: Rect,
1101        max_dist: f32,
1102    ) -> Option<(f32, Point)> {
1103        let mut t_min: f32 = 0.0;
1104        let mut t_max: f32 = max_dist;
1105        let mut normal: Point = Point::new(0.0, 0.0);
1106        if dir.0.abs() < 1e-6 {
1107            if origin.get_x() < rect.get_x() || origin.get_x() > rect.right() {
1108                return None;
1109            }
1110        } else {
1111            let inv: f32 = 1.0 / dir.0;
1112            let mut t1: f32 = (rect.get_x() - origin.get_x()) * inv;
1113            let mut t2: f32 = (rect.right() - origin.get_x()) * inv;
1114            let mut nx: f32 = -1.0;
1115            if t1 > t2 {
1116                swap(&mut t1, &mut t2);
1117                nx = 1.0;
1118            }
1119            if t1 > t_min {
1120                t_min = t1;
1121                normal = Point::new(nx, 0.0);
1122            }
1123            t_max = t_max.min(t2);
1124            if t_min > t_max {
1125                return None;
1126            }
1127        }
1128        if dir.1.abs() < 1e-6 {
1129            if origin.get_y() < rect.get_y() || origin.get_y() > rect.bottom() {
1130                return None;
1131            }
1132        } else {
1133            let inv: f32 = 1.0 / dir.1;
1134            let mut t1: f32 = (rect.get_y() - origin.get_y()) * inv;
1135            let mut t2: f32 = (rect.bottom() - origin.get_y()) * inv;
1136            let mut ny: f32 = -1.0;
1137            if t1 > t2 {
1138                swap(&mut t1, &mut t2);
1139                ny = 1.0;
1140            }
1141            if t1 > t_min {
1142                t_min = t1;
1143                normal = Point::new(0.0, ny);
1144            }
1145            t_max = t_max.min(t2);
1146            if t_min > t_max {
1147                return None;
1148            }
1149        }
1150        Some((t_min, normal))
1151    }
1152}