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 event_ref: f32 = body_a.get_restitution().min(body_b.get_restitution());
256            let inner_index: f32 = -(1.0 + event_ref) * vel_along_normal / inv_sum;
257            let imp_x: f32 = inner_index * nx_n;
258            let imp_y: f32 = inner_index * 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 config_spec: PhysicsConfig = self.get_config();
283        let gx_dt: f32 = config_spec.get_gravity().get_x() * dt_secs;
284        let gy_dt: f32 = config_spec.get_gravity().get_y() * dt_secs;
285        let pos_corr: f32 = config_spec.get_position_correction();
286        let cell_size: f32 = config_spec.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, .. } = config_spec;
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::AxisAlignedBox { 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 bounds_rect: Rect = col.world_bounds(ent.get_transform().get_position());
394                let min_cx: i32 = (bounds_rect.get_x() * inv_cell).floor() as i32;
395                let max_cx: i32 = (bounds_rect.right() * inv_cell).floor() as i32;
396                let min_cy: i32 = (bounds_rect.get_y() * inv_cell).floor() as i32;
397                let max_cy: i32 = (bounds_rect.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 blue_val in body_bounds.iter() {
451                    let rx0: usize = (blue_val.min_cx - grid_min_cx) as usize;
452                    let rx1: usize = (blue_val.max_cx - grid_min_cx) as usize;
453                    let ry0: usize = (blue_val.min_cy - grid_min_cy) as usize;
454                    let ry1: usize = (blue_val.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, byte_val) in body_bounds.iter().enumerate() {
488                    let slot_u32: u32 = slot_idx as u32;
489                    let rx0: usize = (byte_val.min_cx - grid_min_cx) as usize;
490                    let rx1: usize = (byte_val.max_cx - grid_min_cx) as usize;
491                    let ry0: usize = (byte_val.min_cy - grid_min_cy) as usize;
492                    let ry1: usize = (byte_val.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 item_count: usize = bucket.len();
515                        for item_index in 0..item_count {
516                            let ba: BodyGridBounds = body_bounds[bucket[item_index] as usize];
517                            for &sb_u32 in &bucket[(item_index + 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, bounds_val) in body_bounds.iter().enumerate() {
567                    let slot_u32: u32 = slot_idx as u32;
568                    for cy in bounds_val.min_cy..=bounds_val.max_cy {
569                        for cx in bounds_val.min_cx..=bounds_val.max_cx {
570                            let key: u64 = Self::pack_cell_key(cx, cy);
571                            let mut height_val: usize =
572                                (key.wrapping_mul(SPARSE_GRID_HASH_MULT) >> 32) as usize & mask;
573                            loop {
574                                let cell: &mut SparseGridCell = &mut sparse_table[height_val];
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(height_val);
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(height_val);
599                                    }
600                                    break;
601                                }
602                                height_val = (height_val + 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 node_entry: usize = sparse_bucket_scratch.len();
618                    for outer_index in 0..node_entry {
619                        let ba: BodyGridBounds =
620                            body_bounds[sparse_bucket_scratch[outer_index] as usize];
621                        for &sb_u32 in &sparse_bucket_scratch[(outer_index + 1)..] {
622                            let bb: BodyGridBounds = body_bounds[sb_u32 as usize];
623                            if ba.min_cx.max(bb.min_cx) == cell.cx
624                                && ba.min_cy.max(bb.min_cy) == cell.cy
625                            {
626                                broad_count += 1;
627                                if (ba.layer & bb.mask) != 0 && (bb.layer & ba.mask) != 0 {
628                                    Self::resolve_pair(
629                                        entities,
630                                        ba.entity_idx as usize,
631                                        bb.entity_idx as usize,
632                                        pos_corr,
633                                        events_scratch,
634                                    );
635                                }
636                            }
637                        }
638                    }
639                }
640            }
641        }
642        world.sync_soa_from_entities();
643        let event_count: usize = events_scratch.len();
644        self.set_last_stats(PhysicsStepStats::new(integrated, broad_count, event_count));
645        self.last_events()
646    }
647
648    /// Integrates velocities/positions, resolves flat spatial-grid collisions and arena bounds, and returns contact events.
649    ///
650    /// # Arguments
651    ///
652    /// - `&Self` - Mutable physics world.
653    /// - `&mut GameWorld` - Mutable ECS world containing entities and colliders.
654    /// - `f32` - Fixed physics timestep in seconds.
655    ///
656    /// # Returns
657    ///
658    /// - `Vec<CollisionEvent>` - All solid and trigger contacts detected this step.
659    pub fn step(&mut self, world: &mut GameWorld, dt_secs: f32) -> Vec<CollisionEvent> {
660        let slice: &[CollisionEvent] = self.step_in_place(world, dt_secs);
661        if slice.is_empty() {
662            Vec::new()
663        } else {
664            slice.to_vec()
665        }
666    }
667
668    /// Casts a 2D ray using Amanatides-Woo spatial-grid DDA over the persistent broad-phase grid built by `step` / `step_in_place`.
669    ///
670    /// Falls back automatically to `PhysicsWorld2D::raycast` if the dense grid has not yet been populated.
671    ///
672    /// # Arguments
673    ///
674    /// - `&Self` - Physics world holding the populated spatial grid.
675    /// - `&GameWorld` - Game world to query.
676    /// - `Point` - Ray origin in world units.
677    /// - `Point` - Ray direction vector (normalized automatically).
678    /// - `f32` - Maximum ray distance.
679    /// - `u32` - Layer bitmask filter.
680    ///
681    /// # Returns
682    ///
683    /// - `Option<RaycastHit>` - Closest ray intersection hit, if any.
684    #[must_use]
685    pub fn raycast_grid(
686        &self,
687        world: &GameWorld,
688        origin: Point,
689        direction: Point,
690        max_distance: f32,
691        layer_mask: u32,
692    ) -> Option<RaycastHit> {
693        let Self {
694            body_bounds,
695            cell_offsets,
696            cell_cursors,
697            cell_items,
698            grid_min_cx,
699            grid_min_cy,
700            grid_w,
701            grid_h,
702            grid_cell_size,
703            grid_dense_valid,
704            ..
705        } = self;
706        if !*grid_dense_valid || *grid_w == 0 || *grid_h == 0 || body_bounds.is_empty() {
707            return Self::raycast(world, origin, direction, max_distance, layer_mask);
708        }
709        let len: f32 =
710            (direction.get_x() * direction.get_x() + direction.get_y() * direction.get_y()).sqrt();
711        if len <= 1e-6 || max_distance <= 0.0 {
712            return None;
713        }
714        let dx: f32 = direction.get_x() / len;
715        let dy: f32 = direction.get_y() / len;
716        let cs: f32 = (*grid_cell_size).max(8.0);
717        let inv_cs: f32 = 1.0 / cs;
718        let g_min_x: f32 = (*grid_min_cx as f32) * cs;
719        let g_min_y: f32 = (*grid_min_cy as f32) * cs;
720        let g_max_x: f32 = g_min_x + (*grid_w as f32) * cs;
721        let g_max_y: f32 = g_min_y + (*grid_h as f32) * cs;
722        let mut t_enter: f32 = 0.0;
723        let mut t_exit: f32 = max_distance;
724        if dx.abs() < 1e-7 {
725            if origin.get_x() < g_min_x || origin.get_x() > g_max_x {
726                return None;
727            }
728        } else {
729            let inv_dx: f32 = 1.0 / dx;
730            let tx0: f32 = (g_min_x - origin.get_x()) * inv_dx;
731            let tx1: f32 = (g_max_x - origin.get_x()) * inv_dx;
732            t_enter = t_enter.max(tx0.min(tx1));
733            t_exit = t_exit.min(tx0.max(tx1));
734        }
735        if dy.abs() < 1e-7 {
736            if origin.get_y() < g_min_y || origin.get_y() > g_max_y {
737                return None;
738            }
739        } else {
740            let inv_dy: f32 = 1.0 / dy;
741            let ty0: f32 = (g_min_y - origin.get_y()) * inv_dy;
742            let ty1: f32 = (g_max_y - origin.get_y()) * inv_dy;
743            t_enter = t_enter.max(ty0.min(ty1));
744            t_exit = t_exit.min(ty0.max(ty1));
745        }
746        if t_enter > t_exit {
747            return None;
748        }
749        let start_x: f32 = origin.get_x() + dx * t_enter;
750        let start_y: f32 = origin.get_y() + dy * t_enter;
751        let max_rx: i32 = (*grid_w as i32) - 1;
752        let max_ry: i32 = (*grid_h as i32) - 1;
753        let mut rx: i32 = (((start_x - g_min_x) * inv_cs).floor() as i32).clamp(0, max_rx);
754        let mut ry: i32 = (((start_y - g_min_y) * inv_cs).floor() as i32).clamp(0, max_ry);
755        let (step_x, t_delta_x, mut t_max_x): (i32, f32, f32) = if dx > 1e-7 {
756            let next_x: f32 = g_min_x + ((rx + 1) as f32) * cs;
757            (1, cs / dx, (next_x - origin.get_x()) / dx)
758        } else if dx < -1e-7 {
759            let next_x: f32 = g_min_x + (rx as f32) * cs;
760            (-1, -cs / dx, (next_x - origin.get_x()) / dx)
761        } else {
762            (0, f32::INFINITY, f32::INFINITY)
763        };
764        let (step_y, t_delta_y, mut t_max_y): (i32, f32, f32) = if dy > 1e-7 {
765            let next_y: f32 = g_min_y + ((ry + 1) as f32) * cs;
766            (1, cs / dy, (next_y - origin.get_y()) / dy)
767        } else if dy < -1e-7 {
768            let next_y: f32 = g_min_y + (ry as f32) * cs;
769            (-1, -cs / dy, (next_y - origin.get_y()) / dy)
770        } else {
771            (0, f32::INFINITY, f32::INFINITY)
772        };
773        let entities: &[EntityRecord] = world.get_entities().as_slice();
774        let mut closest: Option<RaycastHit> = None;
775        let mut best_t: f32 = max_distance;
776        let mut cell_t: f32 = t_enter;
777        let gw_usize: usize = *grid_w;
778        while rx >= 0 && rx <= max_rx && ry >= 0 && ry <= max_ry && cell_t <= best_t.min(t_exit) {
779            let cidx: usize = (ry as usize) * gw_usize + (rx as usize);
780            let start: usize = cell_offsets[cidx] as usize;
781            let end: usize = cell_cursors[cidx] as usize;
782            for &body_slot in &cell_items[start..end] {
783                let blue_val: BodyGridBounds = body_bounds[body_slot as usize];
784                if (blue_val.layer & layer_mask) == 0 {
785                    continue;
786                }
787                let Some(ent) = entities.get(blue_val.entity_idx as usize) else {
788                    continue;
789                };
790                if !ent.get_alive() {
791                    continue;
792                }
793                let Some(col) = ent.collider_component() else {
794                    continue;
795                };
796                let pos: Point = ent.get_transform().get_position();
797                let hit_opt: Option<(f32, Point)> = match col.get_shape() {
798                    ColliderShape::Circle { radius } => {
799                        Self::ray_vs_circle(origin, (dx, dy), pos, radius, best_t)
800                    }
801                    ColliderShape::AxisAlignedBox { width, height } => Self::ray_vs_box(
802                        origin,
803                        (dx, dy),
804                        Rect::new(
805                            pos.get_x() - width * 0.5,
806                            pos.get_y() - height * 0.5,
807                            width,
808                            height,
809                        ),
810                        best_t,
811                    ),
812                };
813                if let Some((blend_factor, normal)) = hit_opt
814                    && blend_factor < best_t
815                {
816                    best_t = blend_factor;
817                    let hit_pt: Point = Point::new(
818                        origin.get_x() + dx * blend_factor,
819                        origin.get_y() + dy * blend_factor,
820                    );
821                    closest = Some(RaycastHit::new(ent.get_id(), hit_pt, normal, blend_factor));
822                }
823            }
824            if t_max_x < t_max_y {
825                cell_t = t_max_x;
826                t_max_x += t_delta_x;
827                rx += step_x;
828            } else {
829                cell_t = t_max_y;
830                t_max_y += t_delta_y;
831                ry += step_y;
832            }
833        }
834        closest
835    }
836
837    /// Casts a 2D ray from `origin` along normalized `direction` up to `max_distance` against colliders matching `layer_mask`.
838    ///
839    /// # Arguments
840    ///
841    /// - `&GameWorld` - Game world to query.
842    /// - `Point` - Ray origin in world units.
843    /// - `Point` - Ray direction vector (normalized automatically).
844    /// - `f32` - Maximum ray distance.
845    /// - `u32` - Layer bitmask filter.
846    ///
847    /// # Returns
848    ///
849    /// - `Option<RaycastHit>` - Closest ray intersection hit, if any.
850    #[must_use]
851    pub fn raycast(
852        world: &GameWorld,
853        origin: Point,
854        direction: Point,
855        max_distance: f32,
856        layer_mask: u32,
857    ) -> Option<RaycastHit> {
858        let len: f32 =
859            (direction.get_x() * direction.get_x() + direction.get_y() * direction.get_y()).sqrt();
860        if len <= 1e-6 || max_distance <= 0.0 {
861            return None;
862        }
863        let dx: f32 = direction.get_x() / len;
864        let dy: f32 = direction.get_y() / len;
865        let mut closest: Option<RaycastHit> = None;
866        let mut best_t: f32 = max_distance;
867        for ent in world.get_entities().iter() {
868            if !ent.get_alive() {
869                continue;
870            }
871            let Some(col) = ent.collider_component() else {
872                continue;
873            };
874            if (col.get_layer() & layer_mask) == 0 {
875                continue;
876            }
877            let pos: Point = ent.get_transform().get_position();
878            let hit_opt: Option<(f32, Point)> = match col.get_shape() {
879                ColliderShape::Circle { radius } => {
880                    Self::ray_vs_circle(origin, (dx, dy), pos, radius, best_t)
881                }
882                ColliderShape::AxisAlignedBox { width, height } => Self::ray_vs_box(
883                    origin,
884                    (dx, dy),
885                    Rect::new(
886                        pos.get_x() - width * 0.5,
887                        pos.get_y() - height * 0.5,
888                        width,
889                        height,
890                    ),
891                    best_t,
892                ),
893            };
894            if let Some((blend_factor, normal)) = hit_opt
895                && blend_factor < best_t
896            {
897                best_t = blend_factor;
898                let hit_pt: Point = Point::new(
899                    origin.get_x() + dx * blend_factor,
900                    origin.get_y() + dy * blend_factor,
901                );
902                closest = Some(RaycastHit::new(ent.get_id(), hit_pt, normal, blend_factor));
903            }
904        }
905        closest
906    }
907
908    /// Casts a 2D ray defined by a fluent `RaycastQuery2D` against `world`.
909    ///
910    /// # Arguments
911    ///
912    /// - `&GameWorld` - Game world to query.
913    /// - `&RaycastQuery2D` - Raycast query descriptor.
914    ///
915    /// # Returns
916    ///
917    /// - `Option<RaycastHit>` - Closest ray intersection hit, if any.
918    #[must_use]
919    pub fn raycast_query(world: &GameWorld, query: &RaycastQuery2D) -> Option<RaycastHit> {
920        Self::raycast(
921            world,
922            query.get_origin(),
923            query.get_direction(),
924            query.get_max_distance(),
925            query.get_layer_mask(),
926        )
927    }
928
929    /// Evaluates narrow-phase overlap between two shapes returning `(normal_a_to_b, penetration)`.
930    ///
931    /// # Arguments
932    ///
933    /// - `Point` - Center of shape A.
934    /// - `ColliderShape` - Geometry of shape A.
935    /// - `Point` - Center of shape B.
936    /// - `ColliderShape` - Geometry of shape B.
937    ///
938    /// # Returns
939    ///
940    /// - `Option<(Point, f32)>` - Contact normal and positive penetration depth if overlapping.
941    fn narrow_phase(
942        pos_a: Point,
943        shape_a: ColliderShape,
944        pos_b: Point,
945        shape_b: ColliderShape,
946    ) -> Option<(Point, f32)> {
947        match (shape_a, shape_b) {
948            (ColliderShape::Circle { radius: ra }, ColliderShape::Circle { radius: rb }) => {
949                let dx: f32 = pos_b.get_x() - pos_a.get_x();
950                let dy: f32 = pos_b.get_y() - pos_a.get_y();
951                let r_sum: f32 = ra + rb;
952                let dist_sq: f32 = dx * dx + dy * dy;
953                if dist_sq >= r_sum * r_sum {
954                    return None;
955                }
956                let dist: f32 = dist_sq.sqrt();
957                if dist <= 1e-5 {
958                    Some((Point::new(1.0, 0.0), r_sum))
959                } else {
960                    let inv_dist: f32 = 1.0 / dist;
961                    Some((Point::new(dx * inv_dist, dy * inv_dist), r_sum - dist))
962                }
963            }
964            (
965                ColliderShape::AxisAlignedBox {
966                    width: wa,
967                    height: ha,
968                },
969                ColliderShape::AxisAlignedBox {
970                    width: wb,
971                    height: hb,
972                },
973            ) => {
974                let dx: f32 = pos_b.get_x() - pos_a.get_x();
975                let dy: f32 = pos_b.get_y() - pos_a.get_y();
976                let ox: f32 = (wa + wb) * 0.5 - dx.abs();
977                if ox <= 0.0 {
978                    return None;
979                }
980                let oy: f32 = (ha + hb) * 0.5 - dy.abs();
981                if oy <= 0.0 {
982                    return None;
983                }
984                if ox < oy {
985                    let nx: f32 = if dx < 0.0 { -1.0 } else { 1.0 };
986                    Some((Point::new(nx, 0.0), ox))
987                } else {
988                    let ny: f32 = if dy < 0.0 { -1.0 } else { 1.0 };
989                    Some((Point::new(0.0, ny), oy))
990                }
991            }
992            (ColliderShape::Circle { radius }, ColliderShape::AxisAlignedBox { width, height }) => {
993                Self::circle_vs_box(pos_a, radius, pos_b, width, height)
994            }
995            (ColliderShape::AxisAlignedBox { width, height }, ColliderShape::Circle { radius }) => {
996                Self::circle_vs_box(pos_b, radius, pos_a, width, height).map(
997                    |(point_coords, pen): (Point, f32)| {
998                        (
999                            Point::new(-point_coords.get_x(), -point_coords.get_y()),
1000                            pen,
1001                        )
1002                    },
1003                )
1004            }
1005        }
1006    }
1007
1008    /// Narrow-phase Circle-vs-axis-aligned bounding box overlap test returning normal pointing from circle to box.
1009    ///
1010    /// # Arguments
1011    ///
1012    /// - `Point` - Circle center.
1013    /// - `f32` - Circle radius.
1014    /// - `Point` - axis-aligned bounding box center.
1015    /// - `f32` - axis-aligned bounding box full width.
1016    /// - `f32` - axis-aligned bounding box full height.
1017    ///
1018    /// # Returns
1019    ///
1020    /// - `Option<(Point, f32)>` - Contact normal and penetration depth.
1021    fn circle_vs_box(
1022        c_pos: Point,
1023        radius: f32,
1024        b_pos: Point,
1025        border_width: f32,
1026        bh: f32,
1027    ) -> Option<(Point, f32)> {
1028        let half_w: f32 = border_width * 0.5;
1029        let half_h: f32 = bh * 0.5;
1030        let rel_x: f32 = c_pos.get_x() - b_pos.get_x();
1031        let rel_y: f32 = c_pos.get_y() - b_pos.get_y();
1032        let closest_x: f32 = rel_x.clamp(-half_w, half_w);
1033        let closest_y: f32 = rel_y.clamp(-half_h, half_h);
1034        let dx: f32 = rel_x - closest_x;
1035        let dy: f32 = rel_y - closest_y;
1036        let dist_sq: f32 = dx * dx + dy * dy;
1037        if dist_sq >= radius * radius {
1038            return None;
1039        }
1040        let dist: f32 = dist_sq.sqrt();
1041        if dist <= 1e-5 {
1042            let ox: f32 = half_w - rel_x.abs();
1043            let oy: f32 = half_h - rel_y.abs();
1044            if ox < oy {
1045                let nx: f32 = if rel_x < 0.0 { 1.0 } else { -1.0 };
1046                Some((Point::new(nx, 0.0), ox + radius))
1047            } else {
1048                let ny: f32 = if rel_y < 0.0 { 1.0 } else { -1.0 };
1049                Some((Point::new(0.0, ny), oy + radius))
1050            }
1051        } else {
1052            Some((Point::new(-dx / dist, -dy / dist), radius - dist))
1053        }
1054    }
1055
1056    /// Ray-vs-circle analytic intersection test.
1057    ///
1058    /// # Arguments
1059    ///
1060    /// - `Point` - Ray origin.
1061    /// - `(f32, f32)` - Normalized ray direction.
1062    /// - `Point` - Circle center.
1063    /// - `f32` - Circle radius.
1064    /// - `f32` - Maximum distance.
1065    ///
1066    /// # Returns
1067    ///
1068    /// - `Option<(f32, Point)>` - Hit distance and outward surface normal.
1069    fn ray_vs_circle(
1070        origin: Point,
1071        dir: (f32, f32),
1072        center: Point,
1073        radius: f32,
1074        max_dist: f32,
1075    ) -> Option<(f32, Point)> {
1076        let oc_x: f32 = origin.get_x() - center.get_x();
1077        let oc_y: f32 = origin.get_y() - center.get_y();
1078        let blue_val: f32 = oc_x * dir.0 + oc_y * dir.1;
1079        let char_item: f32 = oc_x * oc_x + oc_y * oc_y - radius * radius;
1080        let disc: f32 = blue_val * blue_val - char_item;
1081        if disc < 0.0 {
1082            return None;
1083        }
1084        let blend_factor: f32 = -blue_val - disc.sqrt();
1085        if blend_factor < 0.0 || blend_factor > max_dist {
1086            return None;
1087        }
1088        let hx: f32 = origin.get_x() + dir.0 * blend_factor;
1089        let hy: f32 = origin.get_y() + dir.1 * blend_factor;
1090        let inv_r: f32 = 1.0 / radius.max(1e-5);
1091        Some((
1092            blend_factor,
1093            Point::new((hx - center.get_x()) * inv_r, (hy - center.get_y()) * inv_r),
1094        ))
1095    }
1096
1097    /// Ray-vs-axis-aligned bounding box slab intersection test.
1098    ///
1099    /// # Arguments
1100    ///
1101    /// - `Point` - Ray origin.
1102    /// - `(f32, f32)` - Normalized ray direction.
1103    /// - `Rect` - Axis-aligned box rectangle.
1104    /// - `f32` - Maximum distance.
1105    ///
1106    /// # Returns
1107    ///
1108    /// - `Option<(f32, Point)>` - Hit distance and outward surface normal.
1109    fn ray_vs_box(
1110        origin: Point,
1111        dir: (f32, f32),
1112        rect: Rect,
1113        max_dist: f32,
1114    ) -> Option<(f32, Point)> {
1115        let mut t_min: f32 = 0.0;
1116        let mut t_max: f32 = max_dist;
1117        let mut normal: Point = Point::new(0.0, 0.0);
1118        if dir.0.abs() < 1e-6 {
1119            if origin.get_x() < rect.get_x() || origin.get_x() > rect.right() {
1120                return None;
1121            }
1122        } else {
1123            let inv: f32 = 1.0 / dir.0;
1124            let mut t1: f32 = (rect.get_x() - origin.get_x()) * inv;
1125            let mut t2: f32 = (rect.right() - origin.get_x()) * inv;
1126            let mut nx: f32 = -1.0;
1127            if t1 > t2 {
1128                swap(&mut t1, &mut t2);
1129                nx = 1.0;
1130            }
1131            if t1 > t_min {
1132                t_min = t1;
1133                normal = Point::new(nx, 0.0);
1134            }
1135            t_max = t_max.min(t2);
1136            if t_min > t_max {
1137                return None;
1138            }
1139        }
1140        if dir.1.abs() < 1e-6 {
1141            if origin.get_y() < rect.get_y() || origin.get_y() > rect.bottom() {
1142                return None;
1143            }
1144        } else {
1145            let inv: f32 = 1.0 / dir.1;
1146            let mut t1: f32 = (rect.get_y() - origin.get_y()) * inv;
1147            let mut t2: f32 = (rect.bottom() - origin.get_y()) * inv;
1148            let mut ny: f32 = -1.0;
1149            if t1 > t2 {
1150                swap(&mut t1, &mut t2);
1151                ny = 1.0;
1152            }
1153            if t1 > t_min {
1154                t_min = t1;
1155                normal = Point::new(0.0, ny);
1156            }
1157            t_max = t_max.min(t2);
1158            if t_min > t_max {
1159                return None;
1160            }
1161        }
1162        Some((t_min, normal))
1163    }
1164}