Skip to main content

sim_logic/logic/
collision.rs

1//! Basic collision shapes and live overlap queries.
2
3use std::{error::Error, fmt};
4
5use bevy_ecs::{
6    entity::Entity,
7    entity_disabling::Disabled,
8    prelude::{Component, Res},
9    query::{Allow, QueryFilter, With, Without},
10    system::{Query as BevyQuery, SystemParam},
11};
12use sim_engine::Vec2;
13
14use crate::{
15    identity::{LogicEntity, ManagedEntity, WorldIdentityState},
16    query::QueryEntityError,
17    visual::{CircleVisual, RectangleVisual, Transform2d},
18};
19
20type CircleColliderData = (
21    Entity,
22    &'static ManagedEntity,
23    &'static Transform2d,
24    &'static CircleCollider2d,
25);
26type RectangleColliderData = (
27    Entity,
28    &'static ManagedEntity,
29    &'static Transform2d,
30    &'static RectangleCollider2d,
31);
32type EnabledManaged = (Allow<Disabled>, Without<Disabled>, With<ManagedEntity>);
33type EnabledManagedWith<F> = (F, Allow<Disabled>, Without<Disabled>, With<ManagedEntity>);
34
35/// A circular collision area centered on an entity's [`Transform2d`].
36///
37/// This component describes overlap geometry only. It does not apply forces,
38/// move entities, emit events, or automatically inherit and track a radius
39/// from [`crate::visual::CircleVisual`]. [`Self::from_visual`] can explicitly
40/// copy the initial radius once; it does not copy a transform or synchronize
41/// later changes. Keeping logic and presentation separate permits invisible
42/// triggers and hit areas that differ from their visuals.
43/// Spawning this component without a [`Transform2d`] automatically inserts a
44/// default transform at the world origin. The canonical translation of a
45/// transform supplied in the same bundle takes precedence; normal spawn
46/// snapping may reset its previous interpolation endpoint to that translation.
47/// To exclude an initially spawned collider from standard overlap queries,
48/// attach the automatically approved
49/// [`bevy_ecs::entity_disabling::Disabled`], or use
50/// [`crate::commands::LogicCommands::disable`] at runtime.
51#[derive(Debug, Clone, Copy, PartialEq, Component)]
52#[require(Transform2d)]
53pub struct CircleCollider2d {
54    radius: f32,
55}
56
57impl CircleCollider2d {
58    /// Creates a collider with a finite, strictly positive world-space radius.
59    pub fn new(radius: f32) -> Result<Self, CircleColliderError> {
60        validate_radius(radius)?;
61        Ok(Self { radius })
62    }
63
64    /// Copies the initial radius of a circle visual into a new collider.
65    ///
66    /// This is a one-time snapshot, not synchronization, and it does not copy
67    /// a transform. Later radius changes on either value do not affect the
68    /// other. Use [`Self::new`] when the hit area should intentionally differ
69    /// from the visual.
70    pub const fn from_visual(visual: &CircleVisual) -> Self {
71        // CircleVisual's safe API enforces the same positive-finite invariant.
72        Self {
73            radius: visual.radius(),
74        }
75    }
76
77    /// Returns the radius in caller-defined world units.
78    pub const fn radius(&self) -> f32 {
79        self.radius
80    }
81
82    /// Replaces the radius after validation.
83    ///
84    /// A rejected value leaves the previous radius unchanged.
85    pub fn set_radius(&mut self, radius: f32) -> Result<(), CircleColliderError> {
86        validate_radius(radius)?;
87        self.radius = radius;
88        Ok(())
89    }
90
91    /// Reports whether two colliders overlap at their canonical transforms.
92    ///
93    /// Tangent circles count as overlapping. Calculation widens coordinates
94    /// and radii to `f64` before arithmetic, so subtraction and squaring do not
95    /// overflow for finite `f32` values. Interpolated render positions are not
96    /// involved.
97    pub fn overlaps(
98        &self,
99        transform: &Transform2d,
100        other: &Self,
101        other_transform: &Transform2d,
102    ) -> bool {
103        circles_overlap(
104            transform.translation(),
105            self.radius,
106            other_transform.translation(),
107            other.radius,
108        )
109    }
110
111    /// Reports whether this circle overlaps an axis-aligned rectangle.
112    ///
113    /// The rectangle uses its full size and the center supplied by
114    /// `rectangle_transform`. Circle center containment plus face or corner
115    /// contact count as overlap. Every coordinate and geometry value widens
116    /// to `f64` before arithmetic; render interpolation, visual corner radius,
117    /// rotation, and scale are not involved.
118    pub fn overlaps_rectangle(
119        &self,
120        transform: &Transform2d,
121        rectangle: &RectangleCollider2d,
122        rectangle_transform: &Transform2d,
123    ) -> bool {
124        circle_rectangle_overlap(
125            transform.translation(),
126            self.radius,
127            rectangle_transform.translation(),
128            rectangle.size,
129        )
130    }
131}
132
133impl CircleVisual {
134    /// Returns `(visual, collider)` as a spawnable pair matching this radius.
135    ///
136    /// The collider is a one-time geometry snapshot produced by
137    /// [`CircleCollider2d::from_visual`]. Later changes to either returned
138    /// value remain independent. The tuple can be nested directly in a larger
139    /// spawn bundle.
140    pub const fn with_matching_collider(self) -> (Self, CircleCollider2d) {
141        let collider = CircleCollider2d::from_visual(&self);
142        (self, collider)
143    }
144}
145
146/// Invalid radius supplied to [`CircleCollider2d`].
147#[derive(Debug, Clone, Copy, PartialEq)]
148pub enum CircleColliderError {
149    /// A circle radius was non-finite or not strictly positive.
150    InvalidRadius {
151        /// Rejected radius in world units.
152        value: f32,
153    },
154}
155
156impl fmt::Display for CircleColliderError {
157    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
158        match self {
159            Self::InvalidRadius { value } => write!(
160                formatter,
161                "collider radius must be positive and finite, got {value}"
162            ),
163        }
164    }
165}
166
167impl Error for CircleColliderError {}
168
169/// An axis-aligned rectangular collision area centered on an entity's
170/// [`Transform2d`].
171///
172/// `size` is the full width and height in caller-defined world units. This
173/// component describes overlap geometry only: it does not automatically
174/// inherit or track geometry from [`crate::visual::RectangleVisual`], move
175/// entities, or resolve collisions. [`Self::from_visual`] can explicitly copy
176/// the initial full size once, but it ignores rounded corners, does not copy a
177/// transform, and does not synchronize later changes. Keeping geometry
178/// independent permits invisible hit areas and visuals whose shape differs
179/// from gameplay. Spawning this component without a [`Transform2d`]
180/// automatically inserts a default transform at the world origin. The
181/// canonical translation of a transform supplied in the same bundle takes
182/// precedence; normal spawn snapping may reset its previous interpolation
183/// endpoint to that translation.
184#[derive(Debug, Clone, Copy, PartialEq, Component)]
185#[require(Transform2d)]
186pub struct RectangleCollider2d {
187    size: Vec2,
188}
189
190impl RectangleCollider2d {
191    /// Creates a collider with finite, strictly positive full width and height.
192    pub fn new(size: Vec2) -> Result<Self, RectangleColliderError> {
193        validate_rectangle_size(size)?;
194        Ok(Self { size })
195    }
196
197    /// Copies the initial full size of a rectangle visual into a new collider.
198    ///
199    /// Corner radius and presentation properties are not collision geometry
200    /// and are ignored. This is a one-time snapshot, not synchronization, and
201    /// it does not copy a transform. Later size changes on either value do not
202    /// affect the other. Use [`Self::new`] for deliberately different or
203    /// invisible hit areas.
204    pub const fn from_visual(visual: &RectangleVisual) -> Self {
205        // RectangleVisual's safe API enforces the same positive-finite invariant.
206        Self {
207            size: visual.size(),
208        }
209    }
210
211    /// Returns the full width and height in caller-defined world units.
212    pub const fn size(&self) -> Vec2 {
213        self.size
214    }
215
216    /// Replaces the full width and height after validation.
217    ///
218    /// A rejected value leaves the complete previous size unchanged.
219    pub fn set_size(&mut self, size: Vec2) -> Result<(), RectangleColliderError> {
220        validate_rectangle_size(size)?;
221        self.size = size;
222        Ok(())
223    }
224
225    /// Reports whether two colliders overlap at their canonical transforms.
226    ///
227    /// Rectangles are axis-aligned and edge or corner contact counts as
228    /// overlap. Calculation widens positions and sizes to `f64` before
229    /// arithmetic, preventing overflow for finite `f32` values. Render
230    /// interpolation, visual corner radius, rotation, and scale are not
231    /// involved.
232    pub fn overlaps(
233        &self,
234        transform: &Transform2d,
235        other: &Self,
236        other_transform: &Transform2d,
237    ) -> bool {
238        rectangles_overlap(
239            transform.translation(),
240            self.size,
241            other_transform.translation(),
242            other.size,
243        )
244    }
245
246    /// Reports whether this axis-aligned rectangle overlaps a circle.
247    ///
248    /// This is the symmetric orientation of
249    /// [`CircleCollider2d::overlaps_rectangle`] and delegates to the same
250    /// widened closed-contact predicate.
251    pub fn overlaps_circle(
252        &self,
253        transform: &Transform2d,
254        circle: &CircleCollider2d,
255        circle_transform: &Transform2d,
256    ) -> bool {
257        circle_rectangle_overlap(
258            circle_transform.translation(),
259            circle.radius,
260            transform.translation(),
261            self.size,
262        )
263    }
264}
265
266impl RectangleVisual {
267    /// Returns `(visual, collider)` as a spawnable pair matching this full size.
268    ///
269    /// The collider is a one-time geometry snapshot produced by
270    /// [`RectangleCollider2d::from_visual`]. Corner radius and all other
271    /// presentation properties are ignored. Later changes to either returned
272    /// value remain independent. The tuple can be nested directly in a larger
273    /// spawn bundle.
274    pub const fn with_matching_collider(self) -> (Self, RectangleCollider2d) {
275        let collider = RectangleCollider2d::from_visual(&self);
276        (self, collider)
277    }
278}
279
280/// Invalid geometry supplied to [`RectangleCollider2d`].
281#[derive(Debug, Clone, Copy, PartialEq)]
282pub enum RectangleColliderError {
283    /// A full size contained a non-finite or non-positive component.
284    InvalidSize {
285        /// Rejected full width and height.
286        value: Vec2,
287    },
288}
289
290impl fmt::Display for RectangleColliderError {
291    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
292        match self {
293            Self::InvalidSize { value } => write!(
294                formatter,
295                "collider size components must be positive and finite, got {value:?}"
296            ),
297        }
298    }
299}
300
301impl Error for RectangleColliderError {}
302
303/// Live read-only search for enabled circular colliders in the active World.
304///
305/// `F` is a Bevy query filter applied only to candidate entities, such as
306/// `With<Coin>` or `(With<Target>, Without<Projectile>)`. The source entity
307/// need not match `F`, but it must still be an enabled managed entity. The
308/// supplied source transform and collider define the tested geometry. The
309/// runtime validates the source handle, but their association with that handle
310/// is caller-enforced; ordinary use borrows both from the same source entity.
311///
312/// Each call to [`CircleOverlapEntities::iter_overlapping`] performs an
313/// allocation-free linear scan over ECS rows visited after archetype pruning
314/// by `F`. Row-level filters may inspect rows that they do not yield. Results
315/// exclude the source entity and have no stable iteration order. Direct
316/// component changes made by an earlier System in the same stage are visible;
317/// structural [`crate::commands::LogicCommands`] remain deferred until the
318/// stage barrier.
319/// This is an overlap query, not a spatial index or physics solver.
320///
321/// The source transform and collider are explicit method arguments rather
322/// than hidden reads. A separate mutable query for `Transform2d` or
323/// `CircleCollider2d` must still be archetype-disjoint from this parameter's
324/// candidate filter `F`; passing a source handle or proposed transform does
325/// not establish disjointness for Bevy. Splitting movement and collision into
326/// ordered Systems is the simplest general pattern.
327#[derive(SystemParam)]
328pub struct CircleOverlapEntities<'w, 's, F: QueryFilter + 'static = ()> {
329    sources: BevyQuery<'w, 's, &'static ManagedEntity, EnabledManaged>,
330    candidates: BevyQuery<'w, 's, CircleColliderData, EnabledManagedWith<F>>,
331    identity: Res<'w, WorldIdentityState>,
332}
333
334/// Live read-only search for enabled rectangular colliders in the active World.
335///
336/// `F` is a Bevy query filter applied only to candidate entities, such as
337/// `With<Wall>` or `(With<Target>, Without<Player>)`. The source entity need
338/// not match `F`, but it must still be an enabled managed entity. The supplied
339/// source transform and collider define the tested geometry. The runtime
340/// validates the source handle, but their association with that handle is
341/// caller-enforced; ordinary use borrows the collider from that entity while a
342/// tentative movement check may pass a copied proposed transform.
343///
344/// Each call to [`RectangleOverlapEntities::iter_overlapping`] performs an
345/// allocation-free linear scan over ECS rows visited after archetype pruning
346/// by `F`. Row-level filters may inspect rows that they do not yield. Results
347/// exclude the source entity and have no stable iteration order. Direct
348/// component changes made by an earlier System in the same stage are visible;
349/// structural [`crate::commands::LogicCommands`] remain deferred until the
350/// stage barrier. This is an overlap query, not a spatial index or physics
351/// solver.
352///
353/// The candidate query reads [`Transform2d`] and [`RectangleCollider2d`]. A
354/// separate mutable query for either value must be archetype-disjoint from this
355/// parameter's candidate filter `F`; passing a source handle or proposed
356/// transform does not establish disjointness for Bevy.
357#[derive(SystemParam)]
358pub struct RectangleOverlapEntities<'w, 's, F: QueryFilter + 'static = ()> {
359    sources: BevyQuery<'w, 's, &'static ManagedEntity, EnabledManaged>,
360    candidates: BevyQuery<'w, 's, RectangleColliderData, EnabledManagedWith<F>>,
361    identity: Res<'w, WorldIdentityState>,
362}
363
364impl<'s, F: QueryFilter + 'static> RectangleOverlapEntities<'_, 's, F> {
365    /// Reports whether at least one candidate overlaps `source` right now.
366    ///
367    /// This is an early-exit boolean convenience over
368    /// [`Self::iter_overlapping`]. It preserves the same source validation,
369    /// filtering, caller-supplied geometry, and closed-contact semantics, but
370    /// does not expose which unordered candidate matched. The worst case
371    /// remains a linear candidate scan.
372    pub fn has_overlap(
373        &self,
374        source: LogicEntity,
375        source_transform: &Transform2d,
376        source_collider: &RectangleCollider2d,
377    ) -> Result<bool, QueryEntityError> {
378        let mut overlaps = self.iter_overlapping(source, source_transform, source_collider)?;
379        Ok(overlaps.next().is_some())
380    }
381
382    /// Iterates over candidate identities overlapping `source` right now.
383    ///
384    /// A foreign or retired handle is rejected before ECS lookup. A handle
385    /// that is absent, unmanaged, or disabled produces
386    /// [`QueryEntityError::DoesNotMatch`]. The supplied geometry is used by
387    /// value. Its association with `source` is caller-enforced.
388    pub fn iter_overlapping(
389        &self,
390        source: LogicEntity,
391        source_transform: &Transform2d,
392        source_collider: &RectangleCollider2d,
393    ) -> Result<impl Iterator<Item = LogicEntity> + '_, QueryEntityError> {
394        if !self.identity.owns(source) {
395            return Err(QueryEntityError::ForeignWorld {
396                entity: source,
397                active: self.identity.generation(),
398            });
399        }
400
401        let managed = self
402            .sources
403            .get(source.entity())
404            .map_err(|_| QueryEntityError::DoesNotMatch { entity: source })?;
405        if managed.handle(source.entity()) != source {
406            return Err(QueryEntityError::DoesNotMatch { entity: source });
407        }
408        let source_position = source_transform.translation();
409        let source_size = source_collider.size;
410
411        Ok(self
412            .candidates
413            .iter()
414            .filter_map(move |(raw, candidate, transform, collider)| {
415                let candidate = candidate.handle(raw);
416                (candidate != source
417                    && rectangles_overlap(
418                        source_position,
419                        source_size,
420                        transform.translation(),
421                        collider.size,
422                    ))
423                .then_some(candidate)
424            }))
425    }
426
427    /// Reports whether at least one rectangular candidate overlaps a circular source.
428    ///
429    /// This is exact early-exit sugar over
430    /// [`Self::iter_overlapping_with_circle`]. The source geometry is supplied
431    /// by the caller; the candidate filter and all ordinary managed-query
432    /// validation remain unchanged.
433    pub fn has_overlap_with_circle(
434        &self,
435        source: LogicEntity,
436        source_transform: &Transform2d,
437        source_collider: &CircleCollider2d,
438    ) -> Result<bool, QueryEntityError> {
439        let mut overlaps =
440            self.iter_overlapping_with_circle(source, source_transform, source_collider)?;
441        Ok(overlaps.next().is_some())
442    }
443
444    /// Iterates over rectangular candidates overlapping a circular source.
445    ///
446    /// Tangent face and corner contact count as overlap. A foreign or retired
447    /// handle is rejected before lookup; absent, unmanaged, disabled, or
448    /// private-marker-mismatched sources produce
449    /// [`QueryEntityError::DoesNotMatch`]. The supplied geometry is used by
450    /// value and its association with `source` is caller-enforced. `F` applies
451    /// only to rectangular candidates; the source and disabled candidates are
452    /// excluded. This is an allocation-free linear scan with no stable order.
453    pub fn iter_overlapping_with_circle(
454        &self,
455        source: LogicEntity,
456        source_transform: &Transform2d,
457        source_collider: &CircleCollider2d,
458    ) -> Result<impl Iterator<Item = LogicEntity> + '_, QueryEntityError> {
459        if !self.identity.owns(source) {
460            return Err(QueryEntityError::ForeignWorld {
461                entity: source,
462                active: self.identity.generation(),
463            });
464        }
465
466        let managed = self
467            .sources
468            .get(source.entity())
469            .map_err(|_| QueryEntityError::DoesNotMatch { entity: source })?;
470        if managed.handle(source.entity()) != source {
471            return Err(QueryEntityError::DoesNotMatch { entity: source });
472        }
473        let source_position = source_transform.translation();
474        let source_radius = source_collider.radius;
475
476        Ok(self
477            .candidates
478            .iter()
479            .filter_map(move |(raw, candidate, transform, collider)| {
480                let candidate = candidate.handle(raw);
481                (candidate != source
482                    && circle_rectangle_overlap(
483                        source_position,
484                        source_radius,
485                        transform.translation(),
486                        collider.size,
487                    ))
488                .then_some(candidate)
489            }))
490    }
491}
492
493impl<'s, F: QueryFilter + 'static> CircleOverlapEntities<'_, 's, F> {
494    /// Reports whether at least one candidate overlaps `source` right now.
495    ///
496    /// This is an early-exit boolean convenience over
497    /// [`Self::iter_overlapping`]. It preserves the same source validation,
498    /// filtering, caller-supplied geometry, and tangent-contact semantics, but
499    /// does not expose which unordered candidate matched. The worst case
500    /// remains a linear candidate scan.
501    pub fn has_overlap(
502        &self,
503        source: LogicEntity,
504        source_transform: &Transform2d,
505        source_collider: &CircleCollider2d,
506    ) -> Result<bool, QueryEntityError> {
507        let mut overlaps = self.iter_overlapping(source, source_transform, source_collider)?;
508        Ok(overlaps.next().is_some())
509    }
510
511    /// Iterates over candidate identities overlapping `source` right now.
512    ///
513    /// A foreign or retired handle is rejected before ECS lookup. A handle
514    /// that is absent, unmanaged, or disabled produces
515    /// [`QueryEntityError::DoesNotMatch`]. The supplied geometry is used by
516    /// value. Its association with `source` is caller-enforced; callers should
517    /// borrow it from that entity in the same System.
518    pub fn iter_overlapping(
519        &self,
520        source: LogicEntity,
521        source_transform: &Transform2d,
522        source_collider: &CircleCollider2d,
523    ) -> Result<impl Iterator<Item = LogicEntity> + '_, QueryEntityError> {
524        if !self.identity.owns(source) {
525            return Err(QueryEntityError::ForeignWorld {
526                entity: source,
527                active: self.identity.generation(),
528            });
529        }
530
531        let managed = self
532            .sources
533            .get(source.entity())
534            .map_err(|_| QueryEntityError::DoesNotMatch { entity: source })?;
535        if managed.handle(source.entity()) != source {
536            return Err(QueryEntityError::DoesNotMatch { entity: source });
537        }
538        let source_position = source_transform.translation();
539        let source_radius = source_collider.radius;
540
541        Ok(self
542            .candidates
543            .iter()
544            .filter_map(move |(raw, candidate, transform, collider)| {
545                let candidate = candidate.handle(raw);
546                (candidate != source
547                    && circles_overlap(
548                        source_position,
549                        source_radius,
550                        transform.translation(),
551                        collider.radius,
552                    ))
553                .then_some(candidate)
554            }))
555    }
556
557    /// Reports whether at least one circular candidate overlaps a rectangular source.
558    ///
559    /// This is exact early-exit sugar over
560    /// [`Self::iter_overlapping_with_rectangle`]. The source geometry is
561    /// supplied by the caller; filtering and source validation are identical
562    /// to the same-shape path.
563    pub fn has_overlap_with_rectangle(
564        &self,
565        source: LogicEntity,
566        source_transform: &Transform2d,
567        source_collider: &RectangleCollider2d,
568    ) -> Result<bool, QueryEntityError> {
569        let mut overlaps =
570            self.iter_overlapping_with_rectangle(source, source_transform, source_collider)?;
571        Ok(overlaps.next().is_some())
572    }
573
574    /// Iterates over circular candidates overlapping a rectangular source.
575    ///
576    /// Tangent face and corner contact count as overlap. A foreign or retired
577    /// handle is rejected before lookup; absent, unmanaged, disabled, or
578    /// private-marker-mismatched sources produce
579    /// [`QueryEntityError::DoesNotMatch`]. The supplied geometry is used by
580    /// value and its association with `source` is caller-enforced. `F` applies
581    /// only to circular candidates; the source and disabled candidates are
582    /// excluded. This is an allocation-free linear scan with no stable order.
583    pub fn iter_overlapping_with_rectangle(
584        &self,
585        source: LogicEntity,
586        source_transform: &Transform2d,
587        source_collider: &RectangleCollider2d,
588    ) -> Result<impl Iterator<Item = LogicEntity> + '_, QueryEntityError> {
589        if !self.identity.owns(source) {
590            return Err(QueryEntityError::ForeignWorld {
591                entity: source,
592                active: self.identity.generation(),
593            });
594        }
595
596        let managed = self
597            .sources
598            .get(source.entity())
599            .map_err(|_| QueryEntityError::DoesNotMatch { entity: source })?;
600        if managed.handle(source.entity()) != source {
601            return Err(QueryEntityError::DoesNotMatch { entity: source });
602        }
603        let source_position = source_transform.translation();
604        let source_size = source_collider.size;
605
606        Ok(self
607            .candidates
608            .iter()
609            .filter_map(move |(raw, candidate, transform, collider)| {
610                let candidate = candidate.handle(raw);
611                (candidate != source
612                    && circle_rectangle_overlap(
613                        transform.translation(),
614                        collider.radius,
615                        source_position,
616                        source_size,
617                    ))
618                .then_some(candidate)
619            }))
620    }
621}
622
623fn validate_radius(value: f32) -> Result<(), CircleColliderError> {
624    (value.is_finite() && value > 0.0)
625        .then_some(())
626        .ok_or(CircleColliderError::InvalidRadius { value })
627}
628
629fn validate_rectangle_size(value: Vec2) -> Result<(), RectangleColliderError> {
630    (value.is_finite() && value.x() > 0.0 && value.y() > 0.0)
631        .then_some(())
632        .ok_or(RectangleColliderError::InvalidSize { value })
633}
634
635fn circles_overlap(first: Vec2, first_radius: f32, second: Vec2, second_radius: f32) -> bool {
636    let radius = f64::from(first_radius) + f64::from(second_radius);
637    let radius_squared = radius * radius;
638    let x = f64::from(first.x()) - f64::from(second.x());
639    let y = f64::from(first.y()) - f64::from(second.y());
640    let y_squared = y * y;
641    let approximate_distance_squared = x * x + y_squared;
642
643    // For validated `f32` geometry, `x*x`, `y*y`, their sum, and the squared
644    // radius are non-negative finite `f64`s; every nonzero squared term is
645    // normal at this widened precision. Rounding `x*x` before a non-cancelling
646    // addition can therefore move the result by at most one adjacent `f64`
647    // versus the fused form. If the comparisons could disagree, the squared
648    // radius must lie between those adjacent results. This conservative
649    // two-step band catches that region and preserves the original boundary.
650    if approximate_distance_squared
651        .to_bits()
652        .abs_diff(radius_squared.to_bits())
653        <= 2
654    {
655        return x.mul_add(x, y_squared) <= radius_squared;
656    }
657
658    approximate_distance_squared <= radius_squared
659}
660
661fn rectangles_overlap(first: Vec2, first_size: Vec2, second: Vec2, second_size: Vec2) -> bool {
662    let x_distance = (f64::from(first.x()) - f64::from(second.x())).abs();
663    let x_reach = (f64::from(first_size.x()) + f64::from(second_size.x())) * 0.5;
664    if x_distance > x_reach {
665        return false;
666    }
667
668    let y_distance = (f64::from(first.y()) - f64::from(second.y())).abs();
669    let y_reach = (f64::from(first_size.y()) + f64::from(second_size.y())) * 0.5;
670    y_distance <= y_reach
671}
672
673fn circle_rectangle_overlap(
674    circle: Vec2,
675    circle_radius: f32,
676    rectangle: Vec2,
677    rectangle_size: Vec2,
678) -> bool {
679    let x_distance = (f64::from(circle.x()) - f64::from(rectangle.x())).abs();
680    let y_distance = (f64::from(circle.y()) - f64::from(rectangle.y())).abs();
681    let half_width = f64::from(rectangle_size.x()) * 0.5;
682    let half_height = f64::from(rectangle_size.y()) * 0.5;
683    let outside_x = (x_distance - half_width).max(0.0);
684    let outside_y = (y_distance - half_height).max(0.0);
685    let radius = f64::from(circle_radius);
686    outside_x.mul_add(outside_x, outside_y * outside_y) <= radius * radius
687}
688
689#[cfg(test)]
690mod tests {
691    use super::*;
692    use crate::{
693        identity::{ApplicationId, WorldGeneration},
694        system::{Stage, StageFactories},
695    };
696    use bevy_ecs::{
697        prelude::{Res, ResMut, Resource},
698        world::World,
699    };
700    use sim_engine::Color;
701
702    #[derive(Resource, Clone, Copy)]
703    struct CorruptedSource(LogicEntity);
704
705    #[derive(Resource, Clone, Copy)]
706    struct CorruptedSourceGeometry {
707        transform: Transform2d,
708        circle: CircleCollider2d,
709        rectangle: RectangleCollider2d,
710    }
711
712    #[derive(Resource, Default)]
713    struct CorruptedSourceObservation {
714        circle_iterator: Option<QueryEntityError>,
715        circle_boolean: Option<QueryEntityError>,
716        circle_with_rectangle_iterator: Option<QueryEntityError>,
717        circle_with_rectangle_boolean: Option<QueryEntityError>,
718        rectangle_iterator: Option<QueryEntityError>,
719        rectangle_boolean: Option<QueryEntityError>,
720        rectangle_with_circle_iterator: Option<QueryEntityError>,
721        rectangle_with_circle_boolean: Option<QueryEntityError>,
722    }
723
724    fn observe_corrupted_overlap_source(
725        source: Res<CorruptedSource>,
726        geometry: Res<CorruptedSourceGeometry>,
727        circles: CircleOverlapEntities,
728        rectangles: RectangleOverlapEntities,
729        mut observation: ResMut<CorruptedSourceObservation>,
730    ) {
731        observation.circle_iterator = circles
732            .iter_overlapping(source.0, &geometry.transform, &geometry.circle)
733            .err();
734        observation.circle_boolean = circles
735            .has_overlap(source.0, &geometry.transform, &geometry.circle)
736            .err();
737        observation.circle_with_rectangle_iterator = circles
738            .iter_overlapping_with_rectangle(source.0, &geometry.transform, &geometry.rectangle)
739            .err();
740        observation.circle_with_rectangle_boolean = circles
741            .has_overlap_with_rectangle(source.0, &geometry.transform, &geometry.rectangle)
742            .err();
743        observation.rectangle_iterator = rectangles
744            .iter_overlapping(source.0, &geometry.transform, &geometry.rectangle)
745            .err();
746        observation.rectangle_boolean = rectangles
747            .has_overlap(source.0, &geometry.transform, &geometry.rectangle)
748            .err();
749        observation.rectangle_with_circle_iterator = rectangles
750            .iter_overlapping_with_circle(source.0, &geometry.transform, &geometry.circle)
751            .err();
752        observation.rectangle_with_circle_boolean = rectangles
753            .has_overlap_with_circle(source.0, &geometry.transform, &geometry.circle)
754            .err();
755    }
756
757    fn transform(x: f32, y: f32) -> Transform2d {
758        Transform2d::new(Vec2::new(x, y)).expect("test translation should be finite")
759    }
760
761    #[test]
762    fn overlap_source_lookups_reject_mismatched_private_provenance() {
763        let application = ApplicationId::from_raw(1);
764        let active = WorldGeneration::new(application, 1);
765        let corrupted = WorldGeneration::new(application, 99);
766        let circle = CircleCollider2d::new(1.0).expect("test radius should be valid");
767        let rectangle =
768            RectangleCollider2d::new(Vec2::splat(2.0)).expect("test rectangle should be valid");
769        let mut world = World::new();
770        world.insert_resource(WorldIdentityState::new(application, active));
771        world.insert_resource(CorruptedSourceGeometry {
772            transform: Transform2d::default(),
773            circle,
774            rectangle,
775        });
776        world.insert_resource(CorruptedSourceObservation::default());
777        let raw = world
778            .spawn((
779                Transform2d::default(),
780                circle,
781                rectangle,
782                ManagedEntity::for_generation(corrupted),
783            ))
784            .id();
785        let source = LogicEntity::new(application, active, raw);
786        world.insert_resource(CorruptedSource(source));
787        world.spawn((
788            Transform2d::default(),
789            circle,
790            rectangle,
791            ManagedEntity::for_generation(active),
792        ));
793        let mut factories = StageFactories::default();
794        factories.add(observe_corrupted_overlap_source);
795        let mut stage = factories
796            .instantiate(&mut world, Stage::FixedUpdate)
797            .expect("overlap corruption System should initialize");
798
799        stage
800            .run(&mut world)
801            .expect("overlap corruption System should run");
802
803        let expected = Some(QueryEntityError::DoesNotMatch { entity: source });
804        let observation = world.resource::<CorruptedSourceObservation>();
805        assert_eq!(observation.circle_iterator, expected);
806        assert_eq!(observation.circle_boolean, expected);
807        assert_eq!(observation.circle_with_rectangle_iterator, expected);
808        assert_eq!(observation.circle_with_rectangle_boolean, expected);
809        assert_eq!(observation.rectangle_iterator, expected);
810        assert_eq!(observation.rectangle_boolean, expected);
811        assert_eq!(observation.rectangle_with_circle_iterator, expected);
812        assert_eq!(observation.rectangle_with_circle_boolean, expected);
813    }
814
815    #[test]
816    fn radius_validation_and_mutation_are_atomic() {
817        for invalid in [0.0, -0.0, -1.0, f32::INFINITY, f32::NEG_INFINITY, f32::NAN] {
818            assert!(matches!(
819                CircleCollider2d::new(invalid),
820                Err(CircleColliderError::InvalidRadius { value }) if value.to_bits() == invalid.to_bits()
821            ));
822        }
823
824        let mut collider = CircleCollider2d::new(2.0).expect("initial radius should be valid");
825        assert!(collider.set_radius(f32::NAN).is_err());
826        assert_eq!(collider.radius(), 2.0);
827        assert!(collider.set_radius(3.0).is_ok());
828        assert_eq!(collider.radius(), 3.0);
829    }
830
831    #[test]
832    fn circle_collider_copies_visual_radius_once_and_preserves_bits() {
833        let color = Color::rgb8(68, 144, 255);
834        for radius in [f32::from_bits(1), 1.25, f32::MAX] {
835            let visual = CircleVisual::new(radius, color).expect("visual radius should be valid");
836            let collider = CircleCollider2d::from_visual(&visual);
837            let (paired_visual, paired_collider) = visual.with_matching_collider();
838            let validated = CircleCollider2d::new(visual.radius())
839                .expect("visual geometry must satisfy collider invariants");
840
841            assert_eq!(collider, validated);
842            assert_eq!(paired_visual, visual);
843            assert_eq!(paired_collider, collider);
844            assert_eq!(collider.radius().to_bits(), radius.to_bits());
845        }
846
847        let initial = CircleVisual::new(2.0, color).expect("visual should be valid");
848        let (mut visual, mut collider) = initial.with_matching_collider();
849        visual.set_radius(3.0).expect("new visual radius is valid");
850        assert_eq!(collider.radius(), 2.0);
851        collider
852            .set_radius(4.0)
853            .expect("new collider radius is valid");
854        assert_eq!(visual.radius(), 3.0);
855        assert_eq!(collider.radius(), 4.0);
856    }
857
858    #[test]
859    fn overlap_includes_tangent_contained_and_same_center_circles() {
860        let first = CircleCollider2d::new(2.0).expect("radius should be valid");
861        let second = CircleCollider2d::new(1.0).expect("radius should be valid");
862        let origin = transform(0.0, 0.0);
863
864        assert!(first.overlaps(&origin, &second, &transform(3.0, 0.0)));
865        assert!(!first.overlaps(&origin, &second, &transform(3.001, 0.0)));
866        assert!(first.overlaps(&origin, &second, &transform(0.5, 0.0)));
867        assert!(first.overlaps(&origin, &second, &origin));
868    }
869
870    #[test]
871    fn circle_overlap_preserves_closed_radial_bounds() {
872        let first = CircleCollider2d::new(2.0).expect("radius should be valid");
873        let second = CircleCollider2d::new(3.0).expect("radius should be valid");
874        let origin = transform(0.0, 0.0);
875        let next_after_four = f32::from_bits(4.0_f32.to_bits() + 1);
876        let next_after_five = f32::from_bits(5.0_f32.to_bits() + 1);
877
878        let diagonal_tangent = transform(3.0, 4.0);
879        assert!(first.overlaps(&origin, &second, &diagonal_tangent));
880        assert!(second.overlaps(&diagonal_tangent, &first, &origin));
881
882        let diagonal_miss_inside_axis_bounds = transform(3.0, next_after_four);
883        assert!(!first.overlaps(&origin, &second, &diagonal_miss_inside_axis_bounds));
884        assert!(!second.overlaps(&diagonal_miss_inside_axis_bounds, &first, &origin));
885
886        for axis_tangent in [transform(5.0, 0.0), transform(0.0, 5.0)] {
887            assert!(first.overlaps(&origin, &second, &axis_tangent));
888            assert!(second.overlaps(&axis_tangent, &first, &origin));
889        }
890        for axis_miss in [
891            transform(next_after_five, 0.0),
892            transform(0.0, next_after_five),
893        ] {
894            assert!(!first.overlaps(&origin, &second, &axis_miss));
895            assert!(!second.overlaps(&axis_miss, &first, &origin));
896        }
897    }
898
899    #[test]
900    fn circle_overlap_widens_subnormal_values_before_arithmetic() {
901        let minimum = f32::from_bits(1);
902        let combined = f32::from_bits(2);
903        let outside = f32::from_bits(3);
904        let collider =
905            CircleCollider2d::new(minimum).expect("positive subnormal radius should be valid");
906        let origin = transform(-0.0, 0.0);
907
908        assert!(collider.overlaps(&origin, &collider, &transform(combined, -0.0)));
909        assert!(!collider.overlaps(&origin, &collider, &transform(outside, 0.0)));
910        assert!(!collider.overlaps(&origin, &collider, &transform(combined, combined)));
911        assert!(collider.overlaps(&origin, &collider, &transform(0.0, -0.0)));
912    }
913
914    #[test]
915    fn circle_overlap_keeps_fused_precision_at_the_closed_boundary() {
916        let delta = 2.0_f32.powi(-26);
917        let first = CircleCollider2d::new(5.0).expect("radius should be valid");
918        let second = CircleCollider2d::new(delta).expect("radius should be valid");
919        let first_transform = transform(3.0, 4.0);
920        let second_transform = transform(-3.0 * delta, delta);
921
922        // Exact squared distance exceeds squared reach by `9 * delta^2`.
923        // Separately rounding `x*x` before adding `y*y` loses that difference
924        // and produces a false positive at this boundary.
925        assert!(!first.overlaps(&first_transform, &second, &second_transform));
926        assert!(!second.overlaps(&second_transform, &first, &first_transform));
927    }
928
929    #[test]
930    fn circle_overlap_fast_path_matches_the_fused_reference() {
931        fn reference(first: Vec2, first_radius: f32, second: Vec2, second_radius: f32) -> bool {
932            let x = f64::from(first.x()) - f64::from(second.x());
933            let y = f64::from(first.y()) - f64::from(second.y());
934            let radius = f64::from(first_radius) + f64::from(second_radius);
935            x.mul_add(x, y * y) <= radius * radius
936        }
937
938        let mut state = 0x8d26_4e05_u32;
939        let mut checked = 0_usize;
940        while checked < 100_000 {
941            let mut next = || {
942                state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
943                f32::from_bits(state)
944            };
945            let first = Vec2::new(next(), next());
946            let second = Vec2::new(next(), next());
947            let first_radius = f32::from_bits(next().to_bits() & 0x7fff_ffff);
948            let second_radius = f32::from_bits(next().to_bits() & 0x7fff_ffff);
949            if !first.is_finite()
950                || !second.is_finite()
951                || !first_radius.is_finite()
952                || !second_radius.is_finite()
953                || first_radius <= 0.0
954                || second_radius <= 0.0
955            {
956                continue;
957            }
958
959            assert_eq!(
960                circles_overlap(first, first_radius, second, second_radius),
961                reference(first, first_radius, second, second_radius),
962                "mismatch for {first:?}/{first_radius:?} and {second:?}/{second_radius:?}"
963            );
964            checked += 1;
965        }
966    }
967
968    #[test]
969    fn extreme_finite_coordinates_do_not_create_an_infinity_false_positive() {
970        let collider = CircleCollider2d::new(f32::MAX).expect("finite radius should be valid");
971        let negative = transform(-f32::MAX, -f32::MAX);
972        let positive = transform(f32::MAX, f32::MAX);
973        let axis_tangent = transform(f32::MAX, -f32::MAX);
974
975        assert!(!collider.overlaps(&negative, &collider, &positive));
976        assert!(collider.overlaps(&negative, &collider, &axis_tangent));
977    }
978
979    #[test]
980    fn mixed_overlap_has_symmetric_closed_face_and_corner_bounds() {
981        let circle = CircleCollider2d::new(5.0).expect("circle should be valid");
982        let rectangle =
983            RectangleCollider2d::new(Vec2::splat(2.0)).expect("rectangle should be valid");
984        let rectangle_transform = transform(0.0, 0.0);
985        let before_four = f32::from_bits(4.0_f32.to_bits() - 1);
986        let after_four = f32::from_bits(4.0_f32.to_bits() + 1);
987
988        for (circle_transform, expected) in [
989            (transform(0.0, 0.0), true),
990            (transform(-0.0, 0.0), true),
991            (transform(6.0, 0.0), true),
992            (transform(5.0, 4.0), true),
993            (transform(5.0, before_four), true),
994            (transform(5.0, after_four), false),
995            (transform(f32::from_bits(6.0_f32.to_bits() + 1), 0.0), false),
996            (transform(0.0, f32::from_bits(6.0_f32.to_bits() + 1)), false),
997        ] {
998            assert_eq!(
999                circle.overlaps_rectangle(&circle_transform, &rectangle, &rectangle_transform),
1000                expected
1001            );
1002            assert_eq!(
1003                rectangle.overlaps_circle(&rectangle_transform, &circle, &circle_transform),
1004                expected
1005            );
1006        }
1007
1008        let containing_circle =
1009            CircleCollider2d::new(20.0).expect("containing circle should be valid");
1010        assert!(containing_circle.overlaps_rectangle(
1011            &rectangle_transform,
1012            &rectangle,
1013            &rectangle_transform
1014        ));
1015    }
1016
1017    #[test]
1018    fn mixed_overlap_widens_subnormal_and_extreme_geometry_before_arithmetic() {
1019        let minimum = f32::from_bits(1);
1020        let subnormal_circle =
1021            CircleCollider2d::new(minimum).expect("subnormal radius should be valid");
1022        let subnormal_rectangle =
1023            RectangleCollider2d::new(Vec2::splat(minimum)).expect("subnormal size should be valid");
1024        let origin = transform(-0.0, 0.0);
1025        let touching = transform(minimum, -0.0);
1026        let missing = transform(f32::from_bits(2), 0.0);
1027        assert!(subnormal_circle.overlaps_rectangle(&touching, &subnormal_rectangle, &origin));
1028        assert!(!subnormal_circle.overlaps_rectangle(&missing, &subnormal_rectangle, &origin));
1029        assert_eq!(
1030            subnormal_circle.overlaps_rectangle(&touching, &subnormal_rectangle, &origin),
1031            subnormal_rectangle.overlaps_circle(&origin, &subnormal_circle, &touching)
1032        );
1033
1034        let maximum_circle =
1035            CircleCollider2d::new(f32::MAX).expect("maximum radius should be valid");
1036        let maximum_rectangle =
1037            RectangleCollider2d::new(Vec2::splat(f32::MAX)).expect("maximum size should be valid");
1038        let negative = transform(-f32::MAX, -f32::MAX);
1039        let positive = transform(f32::MAX, f32::MAX);
1040        assert!(maximum_circle.overlaps_rectangle(&positive, &maximum_rectangle, &positive));
1041        assert!(!maximum_circle.overlaps_rectangle(&negative, &maximum_rectangle, &positive));
1042        assert_eq!(
1043            maximum_circle.overlaps_rectangle(&negative, &maximum_rectangle, &positive),
1044            maximum_rectangle.overlaps_circle(&positive, &maximum_circle, &negative)
1045        );
1046    }
1047
1048    #[test]
1049    fn rectangle_size_validation_and_mutation_are_atomic() {
1050        let invalid_sizes = [
1051            Vec2::new(0.0, 1.0),
1052            Vec2::new(-0.0, 1.0),
1053            Vec2::new(-1.0, 1.0),
1054            Vec2::new(1.0, 0.0),
1055            Vec2::new(1.0, -0.0),
1056            Vec2::new(1.0, -1.0),
1057            Vec2::new(f32::NAN, 1.0),
1058            Vec2::new(1.0, f32::NAN),
1059            Vec2::new(f32::INFINITY, 1.0),
1060            Vec2::new(1.0, f32::NEG_INFINITY),
1061        ];
1062        for invalid in invalid_sizes {
1063            assert!(matches!(
1064                RectangleCollider2d::new(invalid),
1065                Err(RectangleColliderError::InvalidSize { value }) if value.x().to_bits() == invalid.x().to_bits()
1066                    && value.y().to_bits() == invalid.y().to_bits()
1067            ));
1068        }
1069
1070        let initial = Vec2::new(2.0, 4.0);
1071        let mut collider = RectangleCollider2d::new(initial).expect("initial size should be valid");
1072        assert!(collider.set_size(Vec2::new(3.0, f32::NAN)).is_err());
1073        assert_eq!(collider.size(), initial);
1074        assert!(collider.set_size(Vec2::new(3.0, 5.0)).is_ok());
1075        assert_eq!(collider.size(), Vec2::new(3.0, 5.0));
1076    }
1077
1078    #[test]
1079    fn rectangle_collider_copies_only_visual_size_once_and_preserves_bits() {
1080        let color = Color::rgb8(54, 68, 92);
1081        for size in [
1082            Vec2::new(f32::from_bits(1), f32::MAX),
1083            Vec2::new(2.5, 7.25),
1084            Vec2::new(f32::MAX, f32::from_bits(1)),
1085        ] {
1086            let visual = RectangleVisual::new(size, color).expect("visual size should be valid");
1087            let collider = RectangleCollider2d::from_visual(&visual);
1088            let (paired_visual, paired_collider) = visual.with_matching_collider();
1089            let validated = RectangleCollider2d::new(visual.size())
1090                .expect("visual geometry must satisfy collider invariants");
1091
1092            assert_eq!(collider, validated);
1093            assert_eq!(paired_visual, visual);
1094            assert_eq!(paired_collider, collider);
1095            assert_eq!(collider.size().x().to_bits(), size.x().to_bits());
1096            assert_eq!(collider.size().y().to_bits(), size.y().to_bits());
1097        }
1098
1099        let size = Vec2::new(4.0, 2.0);
1100        let square = RectangleVisual::new(size, color).expect("visual should be valid");
1101        let rounded =
1102            RectangleVisual::rounded(size, color, 20.0).expect("rounded visual should be valid");
1103        assert_eq!(rounded.corner_radius(), 20.0);
1104        assert_eq!(
1105            RectangleCollider2d::from_visual(&rounded),
1106            RectangleCollider2d::from_visual(&square)
1107        );
1108        assert_eq!(
1109            rounded.with_matching_collider().1,
1110            square.with_matching_collider().1
1111        );
1112
1113        let (mut visual, mut collider) = rounded.with_matching_collider();
1114        visual
1115            .set_size(Vec2::new(8.0, 6.0))
1116            .expect("new visual size is valid");
1117        assert_eq!(collider.size(), size);
1118        collider
1119            .set_size(Vec2::new(3.0, 5.0))
1120            .expect("new collider size is valid");
1121        assert_eq!(visual.size(), Vec2::new(8.0, 6.0));
1122        assert_eq!(collider.size(), Vec2::new(3.0, 5.0));
1123    }
1124
1125    #[test]
1126    fn rectangle_overlap_has_closed_symmetric_axis_aligned_bounds() {
1127        let first =
1128            RectangleCollider2d::new(Vec2::new(2.0, 4.0)).expect("first size should be valid");
1129        let second =
1130            RectangleCollider2d::new(Vec2::new(4.0, 2.0)).expect("second size should be valid");
1131        let origin = transform(0.0, 0.0);
1132
1133        for touching in [
1134            transform(3.0, 0.0),
1135            transform(0.0, 3.0),
1136            transform(3.0, 3.0),
1137        ] {
1138            assert!(first.overlaps(&origin, &second, &touching));
1139            assert!(second.overlaps(&touching, &first, &origin));
1140        }
1141        assert!(first.overlaps(&origin, &second, &origin));
1142        assert!(first.overlaps(&origin, &second, &transform(0.5, 0.5)));
1143        assert!(!first.overlaps(&origin, &second, &transform(3.001, 0.0)));
1144        assert!(!first.overlaps(&origin, &second, &transform(0.0, 3.001)));
1145    }
1146
1147    #[test]
1148    fn rectangle_overlap_widens_extreme_and_subnormal_values_before_arithmetic() {
1149        let maximum = RectangleCollider2d::new(Vec2::splat(f32::MAX))
1150            .expect("maximum finite size should be valid");
1151        let negative = transform(-f32::MAX, -f32::MAX);
1152        let positive = transform(f32::MAX, f32::MAX);
1153        assert!(!maximum.overlaps(&negative, &maximum, &positive));
1154        assert!(maximum.overlaps(&negative, &maximum, &negative));
1155
1156        let subnormal_value = f32::from_bits(1);
1157        let subnormal = RectangleCollider2d::new(Vec2::splat(subnormal_value))
1158            .expect("positive subnormal size should be valid");
1159        assert!(subnormal.overlaps(
1160            &transform(0.0, 0.0),
1161            &subnormal,
1162            &transform(subnormal_value, subnormal_value)
1163        ));
1164
1165        let wider_subnormal = RectangleCollider2d::new(Vec2::splat(f32::from_bits(2)))
1166            .expect("wider positive subnormal size should be valid");
1167        assert!(!subnormal.overlaps(
1168            &transform(0.0, 0.0),
1169            &wider_subnormal,
1170            &transform(f32::from_bits(2), f32::from_bits(2))
1171        ));
1172    }
1173}