ferravex_physics/
api.rs

1pub use crate::{ColliderHandle, RigidBodyHandle};
2pub use body::{ColliderShapeError, TeleportError, TeleportOptions, VelocityPolicy};
3
4/// Authored body-origin pose in world units, independent of center-of-mass offset.
5/// A teleport accepts non-unit 3D rotations when they can be normalized. Its
6/// returned pose contains the actual committed rotation (wrapped in 2D).
7/// See [`RigidBody::try_teleport`] and [`PhysicsWorld::try_teleport_body`] for
8/// runnable reset and host interpolation recipes.
9#[derive(Clone, Copy, Debug, PartialEq)]
10pub struct RigidBodyPose {
11    pub translation: Vector,
12    pub rotation: Rotation,
13}
14
15/// Rigid body state. Waking requests activation of its contact island on the next step.
16#[derive(Clone, Debug)]
17pub struct RigidBody {
18    core: body::Core,
19}
20impl body::Access for RigidBody {
21    fn core(&self) -> &body::Core {
22        &self.core
23    }
24    fn core_mut(&mut self) -> &mut body::Core {
25        &mut self.core
26    }
27}
28impl RigidBody {
29    pub fn translation(&self) -> Vector {
30        from3(self.core.position)
31    }
32    pub fn rotation(&self) -> &Rotation {
33        rotation(&self.core)
34    }
35    pub fn linvel(&self) -> Vector {
36        from3(self.core.velocity)
37    }
38    pub fn angvel(&self) -> Angular {
39        angular_from3(self.core.angular_velocity)
40    }
41    pub fn center_of_mass(&self) -> Vector {
42        from3(self.core.world_com())
43    }
44    pub fn local_center_of_mass(&self) -> Vector {
45        from3(self.core.local_com)
46    }
47    pub fn velocity_at_point(&self, p: Vector) -> Vector {
48        from3(self.core.point_velocity(to3(p)))
49    }
50    pub fn mass(&self) -> f32 {
51        self.core.mass
52    }
53    pub fn colliders(&self) -> &[ColliderHandle] {
54        &self.core.colliders
55    }
56    pub fn is_ccd_enabled(&self) -> bool {
57        self.core.ccd
58    }
59    pub fn enable_ccd(&mut self, enabled: bool) {
60        self.core.ccd = enabled;
61    }
62    pub fn is_sleeping(&self) -> bool {
63        self.core.sleeping
64    }
65    pub fn wake_up(&mut self, _strong: bool) {
66        self.core.wake();
67    }
68    /// Atomically set the body-origin pose and apply independent reset policies.
69    ///
70    /// Rejects non-finite translation, invalid rotation and exhausted contact
71    /// revision before changing anything. Rotation uses the math crate's checked
72    /// normalization (zero and non-finite quaternions are rejected). Success
73    /// always invalidates cached contact/joint impulses and wakes this body,
74    /// including an identical-pose reset. Old/new solid contact and enabled-joint
75    /// islands wake on the next valid world step, using existing revision flags.
76    /// Sensors do not connect wake islands. No simulation tick is executed here.
77    ///
78    /// Identity, children, joint anchors/configuration, mass, CCD, gravity scale
79    /// and damping are retained. `Preserve` retains stored world-space COM and
80    /// angular velocities, not origin-point velocity or angular momentum. A
81    /// kinematic body's next step still derives its velocities from any retained
82    /// targets (or zero with no targets). Retained targets can move it away from
83    /// the new pose on that step; clearing targets prevents this snap back.
84    /// Forces/torque retained by policy apply on the next step as usual.
85    ///
86    /// The returned committed pose lets hosts snap both interpolation samples.
87    /// Last-step contacts/manifolds/events remain snapshots until the next valid
88    /// step; their impulses cannot be reused after this revision change. This
89    /// operation performs no destination search or overlap rejection and allocates
90    /// no storage. Existing joints may correct the pose or break on a later step.
91    ///
92    /// ```
93    /// # #[cfg(feature = "dim2")] {
94    /// use ferravex_math::Vec2;
95    /// use ferravex_physics::{Rotation2, d2::{
96    ///     ColliderBuilder, PhysicsWorld, RigidBodyBuilder, RigidBodyPose,
97    ///     TeleportOptions, VelocityPolicy,
98    /// }};
99    /// let mut world = PhysicsWorld::default();
100    /// let (ball, child) = world.insert(
101    ///     RigidBodyBuilder::dynamic().linvel(Vec2::X), ColliderBuilder::ball(0.5),
102    /// );
103    /// world.bodies[ball].add_force(Vec2::Y * 20., true);
104    /// let committed = world.bodies[ball].try_teleport(
105    ///     RigidBodyPose { translation: Vec2::new(2., 3.), rotation: Rotation2::default() },
106    ///     TeleportOptions::new(VelocityPolicy::Clear),
107    /// ).unwrap();
108    /// world.step(1. / 60.);
109    /// assert_eq!(world.bodies[ball].translation(), committed.translation);
110    /// assert_eq!(world.bodies[ball].linvel(), Vec2::ZERO);
111    /// assert_eq!(world.bodies[ball].colliders(), &[child]);
112    /// # }
113    /// ```
114    pub fn try_teleport(
115        &mut self,
116        pose: RigidBodyPose,
117        options: TeleportOptions,
118    ) -> Result<RigidBodyPose, TeleportError> {
119        self.core
120            .try_teleport(to3(pose.translation), rotation_to3(pose.rotation), options)?;
121        Ok(RigidBodyPose {
122            translation: self.translation(),
123            rotation: *self.rotation(),
124        })
125    }
126    pub fn set_translation(&mut self, p: Vector, wake: bool) {
127        assert!(p.is_finite());
128        if self.core.position != to3(p) {
129            self.core.invalidate_contacts();
130        }
131        self.core.position = to3(p);
132        if wake {
133            self.core.wake();
134        }
135    }
136    pub fn set_rotation(&mut self, q: Rotation, wake: bool) {
137        self.core.invalidate_contacts();
138        self.core.set_rotation(rotation_to3(q));
139        if wake {
140            self.core.wake();
141        }
142    }
143    pub fn set_linvel(&mut self, v: Vector, wake: bool) {
144        assert!(v.is_finite());
145        self.core.velocity = to3(v);
146        if wake {
147            self.core.wake();
148        }
149    }
150    pub fn set_angvel(&mut self, v: Angular, wake: bool) {
151        let v = angular_to3(v);
152        assert!(v.is_finite());
153        self.core.angular_velocity = v;
154        if wake {
155            self.core.wake();
156        }
157    }
158    pub fn set_gravity_scale(&mut self, scale: f32, wake: bool) {
159        assert!(scale.is_finite());
160        if self.core.gravity_scale != scale {
161            self.core.invalidate_contacts();
162        }
163        self.core.gravity_scale = scale;
164        if wake {
165            self.core.wake();
166        }
167    }
168    pub fn apply_impulse(&mut self, impulse: Vector, wake: bool) {
169        let v = to3(impulse);
170        assert!(v.is_finite());
171        self.core.velocity += v * self.core.inv_mass;
172        if wake {
173            self.core.wake();
174        }
175    }
176    pub fn apply_impulse_at_point(&mut self, impulse: Vector, point: Vector, wake: bool) {
177        let j = to3(impulse);
178        let p = to3(point);
179        assert!(j.is_finite() && p.is_finite());
180        let torque = (p - self.core.world_com()).cross(j);
181        self.core.velocity += j * self.core.inv_mass;
182        self.core.angular_velocity += self.core.inverse_inertia(torque);
183        if wake {
184            self.core.wake();
185        }
186    }
187    pub fn apply_torque_impulse(&mut self, impulse: Angular, wake: bool) {
188        let v = angular_to3(impulse);
189        assert!(v.is_finite());
190        self.core.angular_velocity += self.core.inverse_inertia(v);
191        if wake {
192            self.core.wake();
193        }
194    }
195    pub fn add_force(&mut self, force: Vector, wake: bool) {
196        let f = to3(force);
197        assert!(f.is_finite());
198        self.core.force += f;
199        if wake {
200            self.core.wake();
201        }
202    }
203    pub fn add_torque(&mut self, torque: Angular, wake: bool) {
204        let t = angular_to3(torque);
205        assert!(t.is_finite());
206        self.core.torque += t;
207        if wake {
208            self.core.wake();
209        }
210    }
211    pub fn set_next_kinematic_translation(&mut self, p: Vector) {
212        assert!(p.is_finite());
213        self.core.next_position = Some(to3(p));
214    }
215    pub fn set_next_kinematic_rotation(&mut self, q: Rotation) {
216        self.core.next_rotation = Some(rotation_to3(q));
217    }
218}
219#[derive(Clone, Debug)]
220pub struct RigidBodyBuilder {
221    core: body::Core,
222}
223impl RigidBodyBuilder {
224    pub fn dynamic() -> Self {
225        Self {
226            core: body::Core::new(body::Kind::Dynamic, PLANAR),
227        }
228    }
229    pub fn fixed() -> Self {
230        Self {
231            core: body::Core::new(body::Kind::Fixed, PLANAR),
232        }
233    }
234    pub fn kinematic_position_based() -> Self {
235        Self {
236            core: body::Core::new(body::Kind::Kinematic, PLANAR),
237        }
238    }
239    pub fn translation(mut self, p: Vector) -> Self {
240        assert!(p.is_finite());
241        self.core.position = to3(p);
242        self
243    }
244    pub fn rotation(mut self, r: Angular) -> Self {
245        self.core
246            .set_rotation(Quat::from_scaled_axis(angular_to3(r)));
247        self
248    }
249    pub fn linvel(mut self, v: Vector) -> Self {
250        assert!(v.is_finite());
251        self.core.velocity = to3(v);
252        self
253    }
254    pub fn angvel(mut self, v: Angular) -> Self {
255        let v = angular_to3(v);
256        assert!(v.is_finite());
257        self.core.angular_velocity = v;
258        self
259    }
260    pub fn linear_damping(mut self, v: f32) -> Self {
261        assert!(v.is_finite() && v >= 0.);
262        self.core.linear_damping = v;
263        self
264    }
265    pub fn angular_damping(mut self, v: f32) -> Self {
266        assert!(v.is_finite() && v >= 0.);
267        self.core.angular_damping = v;
268        self
269    }
270    pub fn gravity_scale(mut self, v: f32) -> Self {
271        assert!(v.is_finite());
272        self.core.gravity_scale = v;
273        self
274    }
275    pub fn ccd_enabled(mut self, v: bool) -> Self {
276        self.core.ccd = v;
277        self
278    }
279    pub fn build(self) -> RigidBody {
280        self.into()
281    }
282}
283impl From<RigidBodyBuilder> for RigidBody {
284    fn from(b: RigidBodyBuilder) -> Self {
285        Self { core: b.core }
286    }
287}
288#[derive(Clone, Debug)]
289pub struct ColliderBuilder {
290    collider: Collider,
291}
292impl ColliderBuilder {
293    fn shape(shape: body::Shape) -> Self {
294        shape.validate();
295        Self {
296            collider: Collider::new(shape),
297        }
298    }
299    pub fn translation(mut self, offset: Vector) -> Self {
300        assert!(offset.is_finite());
301        self.collider.local_translation = to3(offset);
302        self
303    }
304    pub fn rotation(mut self, rotation: Rotation) -> Self {
305        let q = rotation_to3(rotation);
306        assert!(q.is_finite() && q.length_squared() > 1e-12);
307        self.collider.local_rotation = q.normalize();
308        self
309    }
310    pub fn ball(radius: f32) -> Self {
311        Self::shape(body::Shape::Ball(radius))
312    }
313    pub fn density(mut self, v: f32) -> Self {
314        assert!(v.is_finite() && (0. ..=1e6).contains(&v));
315        self.collider.density = v;
316        self
317    }
318    pub fn friction(mut self, v: f32) -> Self {
319        assert!(v.is_finite() && v >= 0.);
320        self.collider.set_friction(v);
321        self
322    }
323    pub fn material(mut self, v: crate::PhysicsMaterial) -> Self {
324        self.collider.set_material(v).expect("valid material");
325        self
326    }
327    pub fn restitution(mut self, v: f32) -> Self {
328        self.collider.set_restitution(v);
329        self
330    }
331    pub fn sensor(mut self, v: bool) -> Self {
332        self.collider.sensor = v;
333        self
334    }
335    /// Collision layers match when each collider's membership intersects the other's filter.
336    pub fn collision_layers(mut self, membership: u32, filter: u32) -> Self {
337        self.collider.membership = membership;
338        self.collider.filter = filter;
339        self
340    }
341    pub fn build(self) -> Collider {
342        self.into()
343    }
344}
345impl From<ColliderBuilder> for Collider {
346    fn from(b: ColliderBuilder) -> Self {
347        b.collider
348    }
349}
350
351/// Which colliders participate in a query. Layers and the ignored body still
352/// apply to every policy. See [`QueryOptions::sensors`] for usage.
353#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
354pub enum SensorPolicy {
355    /// Query solid colliders only, matching the original cast methods.
356    #[default]
357    Exclude,
358    /// Query both solid colliders and sensors.
359    Include,
360    /// Query sensors only, useful for selecting trigger volumes.
361    Only,
362}
363
364/// Reusable distance and filtering options for casts and direct overlap queries.
365///
366/// Construct with an explicit maximum distance; the initial policy queries all
367/// membership layers, excludes sensors, and ignores no body. Builder methods
368/// can be chained, or the named fields can be edited directly. Invalid numeric
369/// inputs are rejected without changing the world: nearest casts return `None`,
370/// while caller-buffer casts return [`QueryError`].
371///
372/// ```
373/// # #[cfg(feature = "dim3")] {
374/// use ferravex_physics::d3::{PhysicsWorld, QueryOptions};
375/// let mut world = PhysicsWorld::default();
376/// let player = world.add_ball([0.; 3], 0.5, true);
377/// let wall = world.add_box([5., 0., 0.], [0.5; 3], false);
378/// let options = QueryOptions::new(10.).layers(0b10).ignore_body(player);
379/// let hit = world.raycast_with_options([0.; 3], [1., 0., 0.], options).unwrap();
380/// assert_eq!(hit.body, Some(wall));
381/// // Reuse the same filters for a camera-volume sweep.
382/// let camera = world.spherecast_with_options([0.; 3], [1., 0., 0.], 0.25, options)
383///     .unwrap();
384/// assert!(camera.distance < hit.distance);
385/// # }
386/// ```
387#[derive(Clone, Copy, Debug, PartialEq)]
388#[must_use]
389pub struct QueryOptions {
390    /// Maximum travel distance for casts, or maximum signed separation for
391    /// direct overlap queries, in world units. Finite and nonnegative.
392    pub max_distance: f32,
393    /// A collider participates when its membership intersects these bits.
394    /// Its collision-response filter is not consulted. Zero matches nothing.
395    pub layers: u32,
396    /// Exclude all compound children of this body. A removed handle does not
397    /// exclude a new body that later reuses the same slot.
398    pub ignored_body: Option<RigidBodyHandle>,
399    /// Whether sensors, solid colliders, or both can be hit.
400    pub sensors: SensorPolicy,
401}
402impl QueryOptions {
403    /// Query up to `max_distance` world units with all layers and no sensors.
404    /// The query validates the distance, so construction does not panic.
405    pub const fn new(max_distance: f32) -> Self {
406        Self {
407            max_distance,
408            layers: u32::MAX,
409            ignored_body: None,
410            sensors: SensorPolicy::Exclude,
411        }
412    }
413
414    // All current-pose queries share membership, sensor and generational exclusions.
415    fn accepts(self, collider: &Collider) -> bool {
416        let sensor = match self.sensors {
417            SensorPolicy::Exclude => !collider.sensor,
418            SensorPolicy::Include => true,
419            SensorPolicy::Only => collider.sensor,
420        };
421        sensor && collider.membership & self.layers != 0 && collider.parent != self.ignored_body
422    }
423
424    /// Select collider membership bits; this has the same meaning as the
425    /// original [`PhysicsWorld::spherecast`] `mask` argument.
426    pub const fn layers(mut self, mask: u32) -> Self {
427        self.layers = mask;
428        self
429    }
430
431    /// Exclude a body and all its compound children. Handles must come from
432    /// the queried world; they do not encode a world identity.
433    pub const fn ignore_body(mut self, body: RigidBodyHandle) -> Self {
434        self.ignored_body = Some(body);
435        self
436    }
437
438    /// Select sensors independently of the layer and body filters.
439    ///
440    /// ```
441    /// # #[cfg(feature = "dim2")] {
442    /// use ferravex_physics::d2::{
443    ///     ColliderBuilder, PhysicsWorld, QueryOptions, RigidBodyBuilder, SensorPolicy,
444    /// };
445    /// let mut world = PhysicsWorld::default();
446    /// let (trigger, _) = world.insert(
447    ///     RigidBodyBuilder::fixed(), ColliderBuilder::ball(1.).sensor(true),
448    /// );
449    /// let options = QueryOptions::new(5.).sensors(SensorPolicy::Only);
450    /// let hit = world.raycast_with_options([-3., 0.], [1., 0.], options).unwrap();
451    /// assert_eq!(hit.body, Some(trigger));
452    /// # }
453    /// ```
454    pub const fn sensors(mut self, policy: SensorPolicy) -> Self {
455        self.sensors = policy;
456        self
457    }
458}
459
460/// Counts returned by caller-buffer casts and direct overlap queries.
461/// See [`PhysicsWorld::spherecast_into`] and [`PhysicsWorld::overlap_sphere_into`].
462#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
463#[must_use]
464pub struct QueryReport {
465    /// Number of `Some` hits written to the start of the output slice.
466    pub written: usize,
467    /// Total accepted collider hits, including those that did not fit.
468    /// Compound children count separately; this is not a unique-body count.
469    pub total: usize,
470}
471impl QueryReport {
472    /// Whether the output omitted any accepted hits. An exactly full buffer
473    /// is not truncated if every hit fit; an empty buffer can be truncated.
474    pub const fn is_truncated(self) -> bool {
475        self.total > self.written
476    }
477}
478
479/// Invalid input to a caller-buffer query. Errors leave its buffer unchanged.
480/// Validation runs even for empty buffers, empty worlds or a zero layer mask,
481/// in the order of these variants (direct overlaps omit direction/endpoint
482/// checks). A valid miss returns `Ok(QueryReport)`.
483///
484/// ```
485/// # #[cfg(feature = "dim2")] {
486/// use ferravex_physics::d2::{PhysicsWorld, QueryError, QueryOptions};
487/// let world = PhysicsWorld::default();
488/// let error = world.raycast_into([0.; 2], [0.; 2], QueryOptions::new(5.), &mut [])
489///     .unwrap_err();
490/// assert_eq!(error, QueryError::ZeroDirection);
491/// # }
492/// ```
493#[derive(Clone, Copy, Debug, PartialEq, Eq)]
494pub enum QueryError {
495    /// At least one origin component is not finite.
496    NonFiniteOrigin,
497    /// At least one direction component is not finite.
498    NonFiniteDirection,
499    /// Maximum distance is negative or not finite.
500    InvalidMaxDistance,
501    /// Sphere radius is not finite or outside `0..=1000`.
502    InvalidRadius,
503    /// Cast direction has zero length, including for a zero-distance cast.
504    ZeroDirection,
505    /// The endpoint computed from the normalized direction is not finite.
506    NonFiniteEndpoint,
507}
508impl std::fmt::Display for QueryError {
509    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
510        f.write_str(match self {
511            Self::NonFiniteOrigin => "query origin must be finite",
512            Self::NonFiniteDirection => "query direction must be finite",
513            Self::InvalidMaxDistance => "query maximum distance must be finite and nonnegative",
514            Self::InvalidRadius => "query radius must be finite and in 0..=1000",
515            Self::ZeroDirection => "query direction must be nonzero",
516            Self::NonFiniteEndpoint => "query endpoint must be finite",
517        })
518    }
519}
520impl std::error::Error for QueryError {}
521
522// Shared validation, filtering and geometry keep nearest and buffered queries
523// on the same current-pose path. Nearest queries retain their shrinking limit.
524struct PreparedQuery {
525    origin: Vec3,
526    direction: Vec3,
527    radius: f32,
528    options: QueryOptions,
529}
530impl PreparedQuery {
531    fn new(
532        origin: [f32; DIM],
533        direction: [f32; DIM],
534        radius: f32,
535        options: QueryOptions,
536    ) -> Result<Self, QueryError> {
537        let origin = to3(Vector::from_array(origin));
538        let direction = to3(Vector::from_array(direction));
539        if !origin.is_finite() {
540            return Err(QueryError::NonFiniteOrigin);
541        }
542        if !direction.is_finite() {
543            return Err(QueryError::NonFiniteDirection);
544        }
545        if !options.max_distance.is_finite() || options.max_distance < 0. {
546            return Err(QueryError::InvalidMaxDistance);
547        }
548        if !radius.is_finite() || !(0. ..=1000.).contains(&radius) {
549            return Err(QueryError::InvalidRadius);
550        }
551        let direction = direction.try_normalize().ok_or(QueryError::ZeroDirection)?;
552        if !(origin + direction * options.max_distance).is_finite() {
553            return Err(QueryError::NonFiniteEndpoint);
554        }
555        Ok(Self {
556            origin,
557            direction,
558            radius,
559            options,
560        })
561    }
562
563    fn cast(
564        &self,
565        world: &PhysicsWorld,
566        id: ColliderHandle,
567        collider: &Collider,
568        limit: f32,
569    ) -> Option<RayHit> {
570        if !self.options.accepts(collider) {
571            return None;
572        }
573        let body = collider.parent?;
574        let pose = collider.pose(&world.raw.bodies[body].core);
575        let (distance, normal) = geometry::distance(
576            collider.shape,
577            pose.position,
578            pose.rotation,
579            self.origin,
580            PLANAR,
581        );
582        let (distance, normal) = if distance <= self.radius {
583            (0., normal)
584        } else {
585            let (time, normal) = geometry::sweep_ball(
586                self.origin,
587                self.origin + self.direction * limit,
588                self.radius,
589                collider.shape,
590                pose.position,
591                pose.rotation,
592                PLANAR,
593            )?;
594            (time * limit, normal)
595        };
596        let point = self.origin + self.direction * distance;
597        if !distance.is_finite() || !point.is_finite() || !normal.is_finite() {
598            return None;
599        }
600        Some(RayHit {
601            body: Some(body),
602            collider: id,
603            distance,
604            point: from3(point).to_array(),
605            normal: from3(normal).to_array(),
606        })
607    }
608}
609
610// Direct probes reuse the signed-distance kernel, without a sweep or direction.
611struct PreparedOverlap {
612    center: Vec3,
613    radius: f32,
614    options: QueryOptions,
615}
616impl PreparedOverlap {
617    fn new(center: [f32; DIM], radius: f32, options: QueryOptions) -> Result<Self, QueryError> {
618        let center = to3(Vector::from_array(center));
619        if !center.is_finite() {
620            return Err(QueryError::NonFiniteOrigin);
621        }
622        if !options.max_distance.is_finite() || options.max_distance < 0. {
623            return Err(QueryError::InvalidMaxDistance);
624        }
625        if !radius.is_finite() || !(0. ..=1000.).contains(&radius) {
626            return Err(QueryError::InvalidRadius);
627        }
628        Ok(Self {
629            center,
630            radius,
631            options,
632        })
633    }
634
635    fn hit(
636        &self,
637        world: &PhysicsWorld,
638        id: ColliderHandle,
639        collider: &Collider,
640    ) -> Option<OverlapHit> {
641        if !self.options.accepts(collider) {
642            return None;
643        }
644        let body = collider.parent?;
645        let pose = collider.pose(&world.raw.bodies.get(body)?.core);
646        let (distance, normal) = geometry::distance(
647            collider.shape,
648            pose.position,
649            pose.rotation,
650            self.center,
651            PLANAR,
652        );
653        let separation = distance - self.radius;
654        let collider_point = self.center - normal * distance;
655        let probe_point = self.center - normal * self.radius;
656        if !separation.is_finite()
657            || separation > self.options.max_distance
658            || !normal.is_finite()
659            || !collider_point.is_finite()
660            || !probe_point.is_finite()
661        {
662            return None;
663        }
664        Some(OverlapHit {
665            body: Some(body),
666            collider: id,
667            separation,
668            collider_point: from3(collider_point).to_array(),
669            probe_point: from3(probe_point).to_array(),
670            normal: from3(normal).to_array(),
671        })
672    }
673}
674
675pub type RawPhysicsWorld = world::World<RigidBody>;
676pub struct PhysicsWorld {
677    pub raw: RawPhysicsWorld,
678}
679impl Default for PhysicsWorld {
680    fn default() -> Self {
681        Self::new([0.; DIM])
682    }
683}
684impl std::ops::Deref for PhysicsWorld {
685    type Target = RawPhysicsWorld;
686    fn deref(&self) -> &Self::Target {
687        &self.raw
688    }
689}
690impl std::ops::DerefMut for PhysicsWorld {
691    fn deref_mut(&mut self) -> &mut Self::Target {
692        &mut self.raw
693    }
694}
695const DIM: usize = if PLANAR { 2 } else { 3 };
696impl PhysicsWorld {
697    pub fn new(gravity: [f32; DIM]) -> Self {
698        Self {
699            raw: world::World::new(to3(Vector::from_array(gravity)), PLANAR),
700        }
701    }
702    /// Derive body-local anchors, hinge axes and reference rotation from current
703    /// live body poses. See [`WorldJointFrame`] for executable authoring recipes.
704    ///
705    /// Frame anchors replace the description's local anchors. For hinges, the
706    /// finite nonzero world axis is normalized (including tiny/huge scales), then
707    /// transformed into each body's local space; old local axes are replaced.
708    /// In 2D only +Z is accepted, within [`crate::JointDesc::validate`]'s tolerance.
709    /// The axis is ignored for other kinds. Origins are authored body origins,
710    /// independent of compound center-of-mass offsets and child collider poses.
711    ///
712    /// [`JointPoseMode::Preserve`] captures current relative rotation and the
713    /// distance/spring rest length, replacing those description fields. Fixed
714    /// and hinge joints require identical world pivots in this mode. It removes
715    /// initial geometric/rest error within floating-point rounding; retained
716    /// limits, motors, velocities, forces, contacts and later body edits may
717    /// still move the bodies on the next tick. It does not freeze simulation.
718    /// [`JointPoseMode::Authored`] retains the description's rest length and
719    /// explicit reference rotation; `None` captures relative rotation **now**.
720    ///
721    /// Checks both generational handles first (`InvalidHandle`), then distinct
722    /// bodies with at least one dynamic endpoint (`InvalidJoint`), then finite
723    /// current positions and unit rotations (`InvalidBody`). Invalid world
724    /// geometry, separated preserve-mode fixed/hinge pivots, or a rejected final
725    /// `JointDesc::validate` returns `InvalidJoint`. Handles must belong to this
726    /// world; they do not encode world identity. No capacity check, mutation,
727    /// allocation, wake, cache invalidation or timestep occurs. This reads poses
728    /// immediately after setters/teleport without a step or query refresh.
729    /// Caller-defined `Into<JointDesc>` code is outside these guarantees.
730    ///
731    /// The returned description is a snapshot, not a live binding. Insert it
732    /// before moving either body, or use [`Self::insert_joint_from_world`].
733    pub fn joint_desc_from_world(
734        &self,
735        a: RigidBodyHandle,
736        b: RigidBodyHandle,
737        desc: impl Into<crate::JointDesc>,
738        frame: WorldJointFrame,
739        pose: JointPoseMode,
740    ) -> Result<crate::JointDesc, crate::PhysicsError> {
741        self.raw.joint_desc_from_world(
742            a,
743            b,
744            desc.into(),
745            frame.anchors.map(to3),
746            frame.axis,
747            matches!(pose, JointPoseMode::Preserve),
748        )
749    }
750
751    /// Author with [`Self::joint_desc_from_world`] and immediately use the
752    /// existing joint insertion path. See [`WorldJointFrame`] for examples.
753    ///
754    /// Retains insertion's `JointCapacity` error, bounded storage, wake/filter
755    /// behavior and allocations. Ordinary errors leave the world unchanged;
756    /// authoring itself allocates nothing, but successful insertion can grow
757    /// the existing arenas/scratch storage. No new solver or stepping policy.
758    pub fn insert_joint_from_world(
759        &mut self,
760        a: RigidBodyHandle,
761        b: RigidBodyHandle,
762        desc: impl Into<crate::JointDesc>,
763        frame: WorldJointFrame,
764        pose: JointPoseMode,
765    ) -> Result<crate::JointHandle, crate::PhysicsError> {
766        let desc = self.joint_desc_from_world(a, b, desc, frame, pose)?;
767        self.raw.insert_joint(a, b, desc)
768    }
769    /// Handle-checked [`RigidBody::try_teleport`], with the same atomic reset,
770    /// deferred cache/wake and no-allocation behavior. Checks the handle before
771    /// pose fields; a removed handle never edits a replacement in its old slot.
772    /// Handles must belong to this world. Works for dynamic, fixed and kinematic
773    /// bodies and needs no query refresh. No body/collider/joint is recreated.
774    ///
775    /// This checkpoint recipe updates host interpolation only after success.
776    /// Replace the two samples with the J400 202 interpolation adapter's snap
777    /// operation when composing with that engine feature.
778    ///
779    /// ```
780    /// # #[cfg(feature = "dim3")] {
781    /// use ferravex_math::{Quat, Vec3};
782    /// use ferravex_physics::d3::{
783    ///     PhysicsWorld, RigidBodyPose, TeleportError, TeleportOptions, VelocityPolicy,
784    /// };
785    /// let mut world = PhysicsWorld::default();
786    /// let ball = world.add_ball([0.; 3], 0.5, true);
787    /// let old = RigidBodyPose { translation: Vec3::ZERO, rotation: Quat::IDENTITY };
788    /// let mut samples = [old; 2];
789    /// let checkpoint = RigidBodyPose {
790    ///     translation: Vec3::new(4., 2., 0.), rotation: Quat::IDENTITY * 2.,
791    /// };
792    /// let committed = world.try_teleport_body(
793    ///     ball, checkpoint, TeleportOptions::new(VelocityPolicy::Clear),
794    /// ).unwrap();
795    /// assert!(committed.rotation.is_normalized());
796    /// samples.fill(committed); // Snap previous and current only on success.
797    /// assert_eq!(samples[0], samples[1]);
798    /// let invalid = RigidBodyPose { translation: Vec3::NAN, ..checkpoint };
799    /// assert_eq!(world.try_teleport_body(
800    ///     ball, invalid, TeleportOptions::new(VelocityPolicy::Preserve),
801    /// ), Err(TeleportError::Translation));
802    /// assert_eq!(world.bodies[ball].translation(), samples[1].translation);
803    /// world.step(1. / 60.);
804    /// assert_eq!(world.bodies[ball].translation(), committed.translation);
805    /// # }
806    /// ```
807    pub fn try_teleport_body(
808        &mut self,
809        body: RigidBodyHandle,
810        pose: RigidBodyPose,
811        options: TeleportOptions,
812    ) -> Result<RigidBodyPose, TeleportError> {
813        self.raw
814            .bodies
815            .get_mut(body)
816            .ok_or(TeleportError::InvalidHandle)?
817            .try_teleport(pose, options)
818    }
819    pub fn add_ball(&mut self, p: [f32; DIM], radius: f32, dynamic: bool) -> RigidBodyHandle {
820        let b = if dynamic {
821            RigidBodyBuilder::dynamic()
822        } else {
823            RigidBodyBuilder::fixed()
824        };
825        self.raw
826            .insert(
827                b.translation(Vector::from_array(p)),
828                ColliderBuilder::ball(radius),
829            )
830            .0
831    }
832    pub fn add_box(&mut self, p: [f32; DIM], half: [f32; DIM], dynamic: bool) -> RigidBodyHandle {
833        let b = if dynamic {
834            RigidBodyBuilder::dynamic()
835        } else {
836            RigidBodyBuilder::fixed()
837        };
838        let h = if PLANAR {
839            Vec3::new(half[0], half[1], 0.5)
840        } else {
841            Vec3::new(half[0], half[1], half.get(2).copied().unwrap_or(0.5))
842        };
843        self.raw
844            .insert(
845                b.translation(Vector::from_array(p)),
846                ColliderBuilder::shape(body::Shape::Box(h)),
847            )
848            .0
849    }
850    /// Queries use current body poses directly; no separate broadphase synchronization is needed.
851    pub fn refresh_queries(&mut self) {}
852    /// Sweep a ball through current collider poses, filtering sensors, membership
853    /// and an optional ignored body (all its compound children). The hit point
854    /// is the swept ball center at impact. Invalid inputs return None.
855    /// See [`Self::spherecast_with_options`] for named filters and sensor policies.
856    pub fn spherecast(
857        &self,
858        origin: [f32; DIM],
859        direction: [f32; DIM],
860        max_distance: f32,
861        radius: f32,
862        mask: u32,
863        ignore: Option<RigidBodyHandle>,
864    ) -> Option<RayHit> {
865        self.raw
866            .cast_sphere(
867                to3(Vector::from_array(origin)),
868                to3(Vector::from_array(direction)),
869                max_distance,
870                radius,
871                mask,
872                ignore,
873            )
874            .map(|h| RayHit {
875                body: Some(h.0),
876                collider: h.1,
877                distance: h.2,
878                point: from3(h.3).to_array(),
879                normal: from3(h.4).to_array(),
880            })
881    }
882    /// Cast against solid colliders in all layers using their current poses.
883    /// See [`Self::raycast_with_options`] to select layers, sensors or an ignored body.
884    pub fn raycast(
885        &self,
886        origin: [f32; DIM],
887        direction: [f32; DIM],
888        max_distance: f32,
889    ) -> Option<RayHit> {
890        self.raw
891            .cast_ray(
892                to3(Vector::from_array(origin)),
893                to3(Vector::from_array(direction)),
894                max_distance,
895            )
896            .map(|h| RayHit {
897                body: Some(h.0),
898                collider: h.1,
899                distance: h.2,
900                point: from3(h.3).to_array(),
901                normal: from3(h.4).to_array(),
902            })
903    }
904
905    /// Cast a ray with reusable distance and filtering options.
906    ///
907    /// Direction is normalized internally, so distances are world units. The
908    /// nearest accepted collider is returned; an initial overlap hits at zero.
909    /// Queries see body and child-collider edits immediately, without a physics
910    /// step or [`Self::refresh_queries`]. Validation and tie behavior match
911    /// [`Self::spherecast_with_options`] with a zero radius.
912    /// See [`QueryOptions`] for a complete ray/sphere example.
913    pub fn raycast_with_options(
914        &self,
915        origin: [f32; DIM],
916        direction: [f32; DIM],
917        options: QueryOptions,
918    ) -> Option<RayHit> {
919        self.spherecast_with_options(origin, direction, 0., options)
920    }
921
922    /// Sweep a ball (a circle in 2D) with named distance and filtering options.
923    ///
924    /// Uses current poses and allocates no query storage. The hit point is the
925    /// swept center, the normal points out of the target, and distance is travel
926    /// in world units. Initial overlap returns distance zero. Equal-distance
927    /// hits select the later collider in the world's iteration order, matching
928    /// the original casts. See [`QueryOptions`] for usage.
929    ///
930    /// Returns `None` for no accepted hit, nonfinite origin/direction/distance/
931    /// radius, zero direction, negative distance, radius outside `0..=1000`, or
932    /// a cast endpoint that overflows. A zero distance still tests initial
933    /// overlap and requires a nonzero direction. Like the original casts, this
934    /// uses the solver's finite-iteration convex sweep, so grazing hits may be
935    /// missed when its iteration budget is exhausted.
936    pub fn spherecast_with_options(
937        &self,
938        origin: [f32; DIM],
939        direction: [f32; DIM],
940        radius: f32,
941        options: QueryOptions,
942    ) -> Option<RayHit> {
943        let query = PreparedQuery::new(origin, direction, radius, options).ok()?;
944        let mut best = None;
945        let mut limit = options.max_distance;
946        for (id, collider) in self.raw.colliders.iter() {
947            if let Some(hit) = query.cast(self, id, collider, limit) {
948                limit = hit.distance;
949                best = Some(hit);
950            }
951        }
952        best
953    }
954
955    /// Collect ray hits into caller-owned storage without allocating.
956    ///
957    /// This is [`Self::spherecast_into`] with radius zero: the nearest hits fit
958    /// into `output` in distance order, and the report counts every accepted
959    /// collider hit, even when the buffer is empty or too small. On success,
960    /// unused entries are `None`; on invalid input, the buffer is unchanged.
961    ///
962    /// ```
963    /// # #[cfg(feature = "dim2")] {
964    /// use ferravex_physics::d2::{PhysicsWorld, QueryOptions};
965    /// let mut world = PhysicsWorld::default();
966    /// world.add_ball([6., 0.], 0.5, false);
967    /// let near = world.add_ball([2., 0.], 0.5, false);
968    /// let mut hits = [None; 1];
969    /// let report = world.raycast_into([0.; 2], [1., 0.], QueryOptions::new(10.),
970    ///     &mut hits).unwrap();
971    /// assert_eq!((report.written, report.total), (1, 2));
972    /// assert!(report.is_truncated());
973    /// assert_eq!(hits[0].unwrap().body, Some(near));
974    /// # }
975    /// ```
976    pub fn raycast_into(
977        &self,
978        origin: [f32; DIM],
979        direction: [f32; DIM],
980        options: QueryOptions,
981        output: &mut [Option<RayHit>],
982    ) -> Result<QueryReport, QueryError> {
983        self.spherecast_into(origin, direction, 0., options, output)
984    }
985
986    /// Collect sphere (circle in 2D) hits using current body and child poses.
987    ///
988    /// Uses the same validation, membership layers, ignored body, sensor policy,
989    /// normalized direction, swept-center points and initial-overlap behavior
990    /// as [`Self::spherecast_with_options`]. Each accepted collider contributes
991    /// at most one hit, including separate children of a compound body.
992    ///
993    /// Success replaces the buffer with the nearest `min(output.len(), total)`
994    /// hits in ascending distance order, followed by `None`. Equal distances
995    /// place the later collider in world iteration order first, matching the
996    /// nearest cast's tie preference. Every collider is tested over the full
997    /// distance, so a full buffer never stops counting farther hits. An empty
998    /// buffer is a count-only query. Errors preserve every output entry.
999    ///
1000    /// Storage is bounded by the caller's slice; no query allocation occurs.
1001    /// Insertion into the sorted buffer takes up to `output.len()` moves per
1002    /// hit. For large worlds, use a small buffer when only nearby hits matter.
1003    /// The existing finite-iteration convex sweep can miss grazing hits; counts
1004    /// describe hits it finds, not a proof that every geometric hit was found.
1005    /// Full-distance casts can also round differently from the shrinking-limit
1006    /// nearest cast. This does not advance simulation or refresh cached poses.
1007    ///
1008    /// ```
1009    /// # #[cfg(feature = "dim3")] {
1010    /// use ferravex_physics::d3::{PhysicsWorld, QueryOptions};
1011    /// let mut world = PhysicsWorld::default();
1012    /// world.add_ball([3., 0., 0.], 0.5, false);
1013    /// let mut hits = [None; 4];
1014    /// let report = world.spherecast_into([0.; 3], [2., 0., 0.], 0.5,
1015    ///     QueryOptions::new(5.), &mut hits).unwrap();
1016    /// assert_eq!((report.written, report.total), (1, 1));
1017    /// assert!(!report.is_truncated());
1018    /// assert!((hits[0].unwrap().distance - 2.).abs() < 0.001);
1019    /// assert!(hits[1..].iter().all(Option::is_none));
1020    /// # }
1021    /// ```
1022    pub fn spherecast_into(
1023        &self,
1024        origin: [f32; DIM],
1025        direction: [f32; DIM],
1026        radius: f32,
1027        options: QueryOptions,
1028        output: &mut [Option<RayHit>],
1029    ) -> Result<QueryReport, QueryError> {
1030        let query = PreparedQuery::new(origin, direction, radius, options)?;
1031        output.fill(None);
1032        let mut report = QueryReport::default();
1033        for (id, collider) in self.raw.colliders.iter() {
1034            let Some(hit) = query.cast(self, id, collider, options.max_distance) else {
1035                continue;
1036            };
1037            report.total += 1;
1038            // Insert before existing ties, so later colliders win even when
1039            // the buffer is full. The prefix contains only initialized hits.
1040            let index = output[..report.written]
1041                .partition_point(|entry| entry.as_ref().unwrap().distance < hit.distance);
1042            if index < output.len() {
1043                let end = report.written.min(output.len() - 1);
1044                output.copy_within(index..end, index + 1);
1045                output[index] = Some(hit);
1046                report.written = (report.written + 1).min(output.len());
1047            }
1048        }
1049        Ok(report)
1050    }
1051
1052    /// Return the point result with the smallest signed separation.
1053    ///
1054    /// This is [`Self::overlap_sphere_with_options`] with radius zero. See
1055    /// [`Self::overlap_point_into`] for a runnable example.
1056    pub fn overlap_point_with_options(
1057        &self,
1058        point: [f32; DIM],
1059        options: QueryOptions,
1060    ) -> Option<OverlapHit> {
1061        self.overlap_sphere_with_options(point, 0., options)
1062    }
1063
1064    /// Return the sphere result with the smallest signed separation.
1065    ///
1066    /// The deepest penetration wins, then touching, then the closest separated
1067    /// collider. Equal separations prefer the later collider in world iteration
1068    /// order. Filtering and geometry match [`Self::overlap_sphere_into`]. Invalid
1069    /// input or no accepted collider returns `None`; use the buffered method to
1070    /// distinguish invalid input from a miss. No allocation or world mutation.
1071    pub fn overlap_sphere_with_options(
1072        &self,
1073        center: [f32; DIM],
1074        radius: f32,
1075        options: QueryOptions,
1076    ) -> Option<OverlapHit> {
1077        let mut output = [None];
1078        let _ = self
1079            .overlap_sphere_into(center, radius, options, &mut output)
1080            .ok()?;
1081        output[0]
1082    }
1083
1084    /// Collect point overlaps and nearby collider surfaces without a direction.
1085    ///
1086    /// Equivalent to [`Self::overlap_sphere_into`] with radius zero, including
1087    /// its signed separation, ordering, filtering and failure-atomic buffer.
1088    /// `QueryOptions::new(0.)` includes touching and inside points; a positive
1089    /// maximum distance also includes separated surfaces within that distance.
1090    ///
1091    /// ```
1092    /// # #[cfg(feature = "dim2")] {
1093    /// use ferravex_physics::d2::{PhysicsWorld, QueryOptions};
1094    /// let mut world = PhysicsWorld::default();
1095    /// let wall = world.add_box([0.; 2], [1.; 2], false);
1096    /// let mut hits = [None; 2];
1097    /// let report = world.overlap_point_into([1.25, 0.], QueryOptions::new(0.5),
1098    ///     &mut hits).unwrap();
1099    /// assert_eq!((report.written, report.total), (1, 1));
1100    /// let hit = hits[0].unwrap();
1101    /// assert_eq!(hit.body, Some(wall));
1102    /// assert_eq!(hit.separation, 0.25);
1103    /// assert_eq!(hit.collider_point, [1., 0.]);
1104    /// assert_eq!(hit.probe_point, [1.25, 0.]);
1105    /// # }
1106    /// ```
1107    pub fn overlap_point_into(
1108        &self,
1109        point: [f32; DIM],
1110        options: QueryOptions,
1111        output: &mut [Option<OverlapHit>],
1112    ) -> Result<QueryReport, QueryError> {
1113        self.overlap_sphere_into(point, 0., options, output)
1114    }
1115
1116    /// Collect direction-free sphere (circle in 2D) proximity results.
1117    ///
1118    /// `options.max_distance` is the maximum **signed surface separation**:
1119    /// zero includes overlaps and exact touches, positive values also include
1120    /// nearby separated colliders. No solver contact margin is added. A negative
1121    /// separation means penetration; its negation is the distance to translate
1122    /// the probe along `normal` to touch this individual convex child. A compound
1123    /// produces one result per child, not a combined depenetration solution.
1124    ///
1125    /// Uses current body/child poses, membership layers, sensor policy and the
1126    /// generational ignored-body filter shared with casts. No step, refresh,
1127    /// broadphase, allocation or simulation mutation occurs. All existing target
1128    /// shapes are supported by the shared signed-distance kernel; probes are
1129    /// points/balls only. Results that cannot be represented in `f32`
1130    /// (including overflowed witnesses) are omitted, as in existing casts.
1131    ///
1132    /// Results sort by ascending signed separation (deepest penetration first),
1133    /// with later colliders first on exact ties. The nearest `output.len()` are
1134    /// retained; every accepted child counts toward `total` even after the buffer
1135    /// fills. Empty output counts only. Success clears unused entries to `None`.
1136    /// Insertion costs up to `output.len()` moves per accepted collider.
1137    ///
1138    /// Validation checks finite center, finite nonnegative maximum separation,
1139    /// then finite radius in `0..=1000`, even with an empty world/buffer or zero
1140    /// layer mask. Errors use existing [`QueryError`] variants and preserve the
1141    /// entire buffer. Direction and cast-endpoint validation do not apply.
1142    ///
1143    /// A placement preview can inspect penetration before committing a body.
1144    /// This recipe resolves a single wall, then rechecks the candidate; several
1145    /// overlapping children require an application-specific placement policy.
1146    ///
1147    /// ```
1148    /// # #[cfg(feature = "dim3")] {
1149    /// use ferravex_physics::d3::{PhysicsWorld, QueryOptions};
1150    /// let mut world = PhysicsWorld::default();
1151    /// let wall = world.add_box([0.; 3], [1.; 3], false);
1152    /// let mut candidate = [1.25, 0., 0.];
1153    /// let mut hits = [None; 4];
1154    /// let report = world.overlap_sphere_into(candidate, 0.5, QueryOptions::new(0.),
1155    ///     &mut hits).unwrap();
1156    /// assert_eq!((report.written, report.total), (1, 1));
1157    /// let hit = hits[0].unwrap();
1158    /// assert_eq!(hit.body, Some(wall));
1159    /// assert_eq!(hit.penetration_depth(), 0.25);
1160    /// for (coordinate, normal) in candidate.iter_mut().zip(hit.normal) {
1161    ///     *coordinate += normal * hit.penetration_depth();
1162    /// }
1163    /// let touching = world.overlap_sphere_with_options(candidate, 0.5,
1164    ///     QueryOptions::new(0.)).unwrap();
1165    /// assert_eq!(touching.separation, 0.);
1166    /// assert_eq!(touching.collider_point, touching.probe_point);
1167    /// // Queries did not move the authored wall or create the preview body.
1168    /// assert_eq!(world.bodies.len(), 1);
1169    /// # }
1170    /// ```
1171    pub fn overlap_sphere_into(
1172        &self,
1173        center: [f32; DIM],
1174        radius: f32,
1175        options: QueryOptions,
1176        output: &mut [Option<OverlapHit>],
1177    ) -> Result<QueryReport, QueryError> {
1178        let query = PreparedOverlap::new(center, radius, options)?;
1179        output.fill(None);
1180        let mut report = QueryReport::default();
1181        for (id, collider) in self.raw.colliders.iter() {
1182            let Some(hit) = query.hit(self, id, collider) else {
1183                continue;
1184            };
1185            report.total += 1;
1186            let index = output[..report.written]
1187                .partition_point(|entry| entry.as_ref().unwrap().separation < hit.separation);
1188            if index < output.len() {
1189                let end = report.written.min(output.len() - 1);
1190                output.copy_within(index..end, index + 1);
1191                output[index] = Some(hit);
1192                report.written = (report.written + 1).min(output.len());
1193            }
1194        }
1195        Ok(report)
1196    }
1197}
1198#[derive(Clone, Copy, Debug)]
1199pub struct RayHit {
1200    pub body: Option<RigidBodyHandle>,
1201    pub collider: ColliderHandle,
1202    pub distance: f32,
1203    pub point: [f32; DIM],
1204    pub normal: [f32; DIM],
1205}
1206
1207/// Signed point/ball proximity to one convex collider child.
1208///
1209/// See [`PhysicsWorld::overlap_sphere_into`] for a runnable placement recipe.
1210/// Witnesses satisfy `probe_point - collider_point = normal * separation`,
1211/// within floating-point rounding, including when the center is inside the
1212/// collider. For penetration these are opposing support witnesses, rather than
1213/// closest points of the intersecting volumes. At centers/edges where the
1214/// nearest exit is not unique the kernel chooses a deterministic outward normal;
1215/// it is a valid exit direction, not a uniquely defined surface gradient.
1216#[derive(Clone, Copy, Debug, PartialEq)]
1217pub struct OverlapHit {
1218    /// Parent body, matching `RayHit`; attached children always return `Some`.
1219    pub body: Option<RigidBodyHandle>,
1220    /// Exact child identity; compound siblings count separately.
1221    pub collider: ColliderHandle,
1222    /// Positive gap, zero touch, or negative penetration, in world units.
1223    pub separation: f32,
1224    /// Boundary witness on the target collider in world coordinates.
1225    pub collider_point: [f32; DIM],
1226    /// Boundary witness on the probe (its center for point queries).
1227    pub probe_point: [f32; DIM],
1228    /// Unit outward target normal, pointing along the probe's exit direction.
1229    pub normal: [f32; DIM],
1230}
1231impl OverlapHit {
1232    /// Distance to translate the probe along `normal` to touch this child.
1233    /// Zero for touching or separated results. See the placement recipe on
1234    /// [`PhysicsWorld::overlap_sphere_into`].
1235    pub fn penetration_depth(self) -> f32 {
1236        (-self.separation).max(0.)
1237    }
1238}
1239
1240impl crate::character::Terrain for PhysicsWorld {
1241    fn visit(
1242        &self,
1243        bounds: crate::character::QueryBounds,
1244        visitor: &mut dyn FnMut(crate::character::Obstacle),
1245    ) {
1246        crate::character::Terrain::visit(&self.raw, bounds, visitor);
1247    }
1248    fn obstacle(&self, id: u64) -> Option<crate::character::Obstacle> {
1249        crate::character::Terrain::obstacle(&self.raw, id)
1250    }
1251}
1252
1253/// Select which rest fields world-space authoring captures.
1254/// See [`WorldJointFrame`] and [`PhysicsWorld::joint_desc_from_world`].
1255#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1256pub enum JointPoseMode {
1257    /// Capture current relative rotation and distance/spring rest length.
1258    /// Fixed/hinge world pivots must coincide. Controls remain authored.
1259    Preserve,
1260    /// Retain explicit reference rotation and rest length. A missing reference
1261    /// captures current relative rotation, matching ordinary insertion defaults.
1262    Authored,
1263}
1264
1265/// World-space pivots and hinge axis, sampled against two live body poses.
1266///
1267/// `anchors[0]` belongs to body A, `anchors[1]` to body B. `axis` is a world
1268/// direction (`Vec3` in either dimension); hinges normalize/check it at use.
1269/// Other joint kinds ignore it. No local frame rotation is stored: the existing
1270/// solver uses local axes and a body-relative reference quaternion instead.
1271///
1272/// This 2D recipe attaches a rotated, translated rotor without initial snap.
1273/// It uses the existing insertion path, then executes an ordinary fixed tick.
1274///
1275/// ```
1276/// # #[cfg(feature = "dim2")] {
1277/// use ferravex_math::Vec2;
1278/// use ferravex_physics::d2::{
1279///     ColliderBuilder, JointBuilder, JointPoseMode, PhysicsWorld,
1280///     RigidBodyBuilder, WorldJointFrame,
1281/// };
1282/// let mut world = PhysicsWorld::default();
1283/// let support = world.insert_body(RigidBodyBuilder::fixed()
1284///     .translation(Vec2::new(2., 3.)).rotation(0.4)).unwrap();
1285/// let (rotor, _) = world.insert(RigidBodyBuilder::dynamic()
1286///     .translation(Vec2::new(4., 3.)).rotation(-0.7), ColliderBuilder::ball(0.2));
1287/// let joint = world.insert_joint_from_world(support, rotor,
1288///     JointBuilder::hinge().limits(-0.5, 0.5),
1289///     WorldJointFrame::at_pivot(Vec2::new(3., 3.)), JointPoseMode::Preserve).unwrap();
1290/// assert!(world.joint_angle(joint).unwrap().abs() < 0.00001);
1291/// world.step(1. / 120.);
1292/// assert!((world.bodies[rotor].translation() - Vec2::new(4., 3.)).length() < 0.0001);
1293/// # }
1294/// ```
1295///
1296/// In 3D, a visible world axis becomes two different local hinge axes. A
1297/// distance/spring can instead use `at_anchors` with two separated pivots.
1298/// `Authored` retains an intentional rest length; `Preserve` captures separation.
1299///
1300/// ```
1301/// # #[cfg(feature = "dim3")] {
1302/// use ferravex_math::Vec3;
1303/// use ferravex_physics::{JointKind, d3::{
1304///     ColliderBuilder, JointBuilder, JointPoseMode, PhysicsWorld,
1305///     RigidBodyBuilder, WorldJointFrame,
1306/// }};
1307/// let mut world = PhysicsWorld::default();
1308/// let support = world.insert_body(RigidBodyBuilder::fixed()
1309///     .translation(Vec3::new(2., 3., 1.)).rotation(Vec3::X * 0.6)).unwrap();
1310/// let (rotor, _) = world.insert(RigidBodyBuilder::dynamic()
1311///     .translation(Vec3::new(4., 3., 1.)).rotation(Vec3::Z * -0.7),
1312///     ColliderBuilder::ball(0.2));
1313/// let pivot = WorldJointFrame::at_pivot(Vec3::new(3., 3., 1.)).with_axis(Vec3::Y * 4.);
1314/// let desc = world.joint_desc_from_world(support, rotor, JointBuilder::hinge(),
1315///     pivot, JointPoseMode::Preserve).unwrap();
1316/// let joint = world.insert_joint(support, rotor, desc).unwrap();
1317/// world.step(1. / 120.);
1318/// assert!((world.bodies[rotor].translation() - Vec3::new(4., 3., 1.)).length() < 0.0001);
1319/// assert!(world.remove_joint(joint));
1320/// let anchors = WorldJointFrame::at_anchors([Vec3::new(2., 3., 1.), Vec3::new(4., 3., 1.)]);
1321/// let spring = world.joint_desc_from_world(support, rotor, JointBuilder::spring(0., 20., 2.),
1322///     anchors, JointPoseMode::Preserve).unwrap();
1323/// assert_eq!(spring.kind, JointKind::Spring { length: 2., stiffness: 20., damping: 2. });
1324/// world.insert_joint(support, rotor, spring).unwrap();
1325/// # }
1326/// ```
1327#[derive(Clone, Copy, Debug, PartialEq)]
1328pub struct WorldJointFrame {
1329    pub anchors: [Vector; 2],
1330    pub axis: Vec3,
1331}
1332impl WorldJointFrame {
1333    /// A shared pivot with the usual +Z (2D) or +Y (3D) world hinge axis.
1334    /// See this type's examples; this only stores inputs, checked at use.
1335    pub fn at_pivot(pivot: Vector) -> Self {
1336        Self::at_anchors([pivot; 2])
1337    }
1338    /// Two world pivots, normally used by distance/spring joints.
1339    /// See this type's examples; validation occurs when sampled against bodies.
1340    pub fn at_anchors(anchors: [Vector; 2]) -> Self {
1341        Self {
1342            anchors,
1343            axis: if PLANAR { Vec3::Z } else { Vec3::Y },
1344        }
1345    }
1346    /// Set an unnormalized world hinge axis; non-hinges ignore it.
1347    /// Zero/nonfinite axes fail at use. 2D requires normalized +Z.
1348    /// See this type's 3D example.
1349    pub fn with_axis(mut self, axis: Vec3) -> Self {
1350        self.axis = axis;
1351        self
1352    }
1353}
1354
1355/// Connections use local anchors relative to each body's authored origin.
1356#[derive(Clone, Copy, Debug)]
1357pub struct JointBuilder {
1358    desc: crate::JointDesc,
1359}
1360impl JointBuilder {
1361    pub fn fixed() -> Self {
1362        Self {
1363            desc: crate::JointDesc::new(crate::JointKind::Fixed),
1364        }
1365    }
1366    pub fn hinge() -> Self {
1367        Self {
1368            desc: crate::JointDesc::new(crate::JointKind::Hinge {
1369                axis1: if PLANAR { Vec3::Z } else { Vec3::Y },
1370                axis2: if PLANAR { Vec3::Z } else { Vec3::Y },
1371            }),
1372        }
1373    }
1374    pub fn distance(length: f32) -> Self {
1375        Self {
1376            desc: crate::JointDesc::new(crate::JointKind::Distance { length }),
1377        }
1378    }
1379    pub fn spring(length: f32, stiffness: f32, damping: f32) -> Self {
1380        Self {
1381            desc: crate::JointDesc::new(crate::JointKind::Spring {
1382                length,
1383                stiffness,
1384                damping,
1385            }),
1386        }
1387    }
1388    pub fn local_anchor1(mut self, anchor: Vector) -> Self {
1389        self.desc.local_anchor1 = to3(anchor);
1390        self
1391    }
1392    pub fn local_anchor2(mut self, anchor: Vector) -> Self {
1393        self.desc.local_anchor2 = to3(anchor);
1394        self
1395    }
1396    pub fn reference_rotation(mut self, rotation: Rotation) -> Self {
1397        self.desc.reference_rotation = Some(rotation_to3(rotation));
1398        self
1399    }
1400    pub fn limits(mut self, lower: f32, upper: f32) -> Self {
1401        self.desc.limits = Some([lower, upper]);
1402        self
1403    }
1404    pub fn motor(mut self, motor: crate::JointMotor) -> Self {
1405        self.desc.motor = Some(motor);
1406        self
1407    }
1408    pub fn break_limits(mut self, force: f32, torque: f32) -> Self {
1409        self.desc.break_limits = Some(crate::BreakLimits { force, torque });
1410        self
1411    }
1412    pub fn contacts_enabled(mut self, enabled: bool) -> Self {
1413        self.desc.contacts_enabled = enabled;
1414        self
1415    }
1416    pub fn build(self) -> crate::JointDesc {
1417        self.desc
1418    }
1419}
1420impl From<JointBuilder> for crate::JointDesc {
1421    fn from(b: JointBuilder) -> Self {
1422        b.desc
1423    }
1424}
1425
1426#[cfg(test)]
1427// api.rs is included before the dimension-specific impls in lib.rs.
1428#[allow(clippy::items_after_test_module)]
1429mod journey200_032 {
1430    use super::*;
1431
1432    fn point(x: f32, y: f32) -> [f32; DIM] {
1433        let mut point = [0.; DIM];
1434        point[0] = x;
1435        point[1] = y;
1436        point
1437    }
1438
1439    fn assert_hit(actual: Option<RayHit>, expected: Option<RayHit>) {
1440        let fields = |hit: RayHit| (hit.body, hit.collider, hit.distance, hit.point, hit.normal);
1441        assert_eq!(actual.map(fields), expected.map(fields));
1442    }
1443
1444    #[test]
1445    fn buffered_queries_keep_nearest_hits_and_count_all_colliders_at_every_capacity() {
1446        let mut world = PhysicsWorld::default();
1447        let far = world.add_ball(point(8., 0.), 0.5, false);
1448        let early = world.add_ball(point(2., 0.), 0.5, false);
1449        let middle = world.add_ball(point(5., 0.), 0.5, false);
1450        let late = world.add_ball(point(2., 0.), 0.5, false);
1451        let options = QueryOptions::new(10.);
1452        for radius in [0., 0.25] {
1453            let mut all = [None; 6];
1454            let report = world
1455                .spherecast_into(point(0., 0.), point(1., 0.), radius, options, &mut all)
1456                .unwrap();
1457            assert_eq!(
1458                report,
1459                QueryReport {
1460                    written: 4,
1461                    total: 4
1462                }
1463            );
1464            assert!(!report.is_truncated());
1465            for (hit, body) in all.iter().zip([late, early, middle, far]) {
1466                assert_eq!(hit.unwrap().body, Some(body));
1467            }
1468            assert!(all[4..].iter().all(Option::is_none));
1469            assert_hit(
1470                all[0],
1471                world.spherecast_with_options(point(0., 0.), point(1., 0.), radius, options),
1472            );
1473            for capacity in 0..=6 {
1474                let mut buffer = [all[0]; 6];
1475                let report = world
1476                    .spherecast_into(
1477                        point(0., 0.),
1478                        point(1., 0.),
1479                        radius,
1480                        options,
1481                        &mut buffer[..capacity],
1482                    )
1483                    .unwrap();
1484                assert_eq!(report.written, capacity.min(4));
1485                assert_eq!(report.total, 4);
1486                assert_eq!(report.is_truncated(), capacity < 4);
1487                for index in 0..capacity {
1488                    assert_hit(buffer[index], all[index]);
1489                }
1490                for untouched in &buffer[capacity..] {
1491                    assert_hit(*untouched, all[0]);
1492                }
1493            }
1494            let report = world
1495                .spherecast_into(point(0., 0.), point(-1., 0.), radius, options, &mut all)
1496                .unwrap();
1497            assert_eq!(report, QueryReport::default());
1498            assert!(all.iter().all(Option::is_none));
1499        }
1500    }
1501
1502    #[test]
1503    fn buffered_filters_compose_and_compound_children_count_separately() {
1504        let mut world = PhysicsWorld::default();
1505        let ignored = world
1506            .insert_compound(
1507                RigidBodyBuilder::fixed(),
1508                [4., 5.].map(|x| {
1509                    ColliderBuilder::ball(0.25)
1510                        .translation(Vector::from_array(point(x, 0.)))
1511                        .collision_layers(0b11, 0)
1512                }),
1513            )
1514            .unwrap();
1515        let (sensor, sensor_collider) = world.insert(
1516            RigidBodyBuilder::fixed().translation(Vector::from_array(point(1., 0.))),
1517            ColliderBuilder::ball(0.25)
1518                .sensor(true)
1519                .collision_layers(0b10, 0),
1520        );
1521        let (solid, solid_collider) = world.insert(
1522            RigidBodyBuilder::fixed().translation(Vector::from_array(point(2., 0.))),
1523            ColliderBuilder::ball(0.25).collision_layers(0b01, 0),
1524        );
1525        world.insert(
1526            RigidBodyBuilder::fixed().translation(Vector::from_array(point(3., 0.))),
1527            ColliderBuilder::ball(0.25).collision_layers(0b100, 0),
1528        );
1529        let options = QueryOptions::new(10.).layers(0b11).ignore_body(ignored);
1530        let mut hits = [None; 8];
1531        for radius in [0., 0.1] {
1532            for (policy, expected) in [
1533                (SensorPolicy::Exclude, vec![solid]),
1534                (SensorPolicy::Include, vec![sensor, solid]),
1535                (SensorPolicy::Only, vec![sensor]),
1536            ] {
1537                let report = world
1538                    .spherecast_into(
1539                        point(0., 0.),
1540                        point(1., 0.),
1541                        radius,
1542                        options.sensors(policy),
1543                        &mut hits,
1544                    )
1545                    .unwrap();
1546                assert_eq!(report.total, expected.len());
1547                assert_eq!(report.written, expected.len());
1548                assert_eq!(
1549                    hits.iter()
1550                        .flatten()
1551                        .map(|hit| hit.body.unwrap())
1552                        .collect::<Vec<_>>(),
1553                    expected
1554                );
1555            }
1556            let report = world
1557                .spherecast_into(
1558                    point(0., 0.),
1559                    point(1., 0.),
1560                    radius,
1561                    QueryOptions {
1562                        ignored_body: None,
1563                        ..options
1564                    },
1565                    &mut hits,
1566                )
1567                .unwrap();
1568            assert_eq!(report.total, 3);
1569            assert_eq!(hits[1].unwrap().body, Some(ignored));
1570            assert_eq!(hits[2].unwrap().body, Some(ignored));
1571            assert_ne!(hits[1].unwrap().collider, hits[2].unwrap().collider);
1572        }
1573        world.colliders[sensor_collider].set_sensor(false);
1574        world.colliders[solid_collider].set_collision_layers(0b100, 0);
1575        let report = world
1576            .raycast_into(point(0., 0.), point(1., 0.), options, &mut hits)
1577            .unwrap();
1578        assert_eq!(report.total, 1);
1579        assert_eq!(hits[0].unwrap().body, Some(sensor));
1580        for options in [options.sensors(SensorPolicy::Only), options.layers(0)] {
1581            let report = world
1582                .raycast_into(point(0., 0.), point(1., 0.), options, &mut hits)
1583                .unwrap();
1584            assert_eq!(report, QueryReport::default());
1585            assert!(hits.iter().all(Option::is_none));
1586        }
1587    }
1588
1589    #[test]
1590    fn buffered_queries_read_current_body_and_child_poses_without_stepping() {
1591        let mut world = PhysicsWorld::default();
1592        let (body, child) = world.insert(
1593            RigidBodyBuilder::fixed().translation(Vector::from_array(point(4., 0.))),
1594            ColliderBuilder::ball(0.5).translation(Vector::from_array(point(0., 2.))),
1595        );
1596        let options = QueryOptions::new(20.);
1597        let mut hits = [None; 2];
1598        assert_eq!(
1599            world
1600                .raycast_into(point(0., 0.), point(1., 0.), options, &mut hits)
1601                .unwrap()
1602                .total,
1603            0
1604        );
1605        let rotated = RigidBodyBuilder::fixed()
1606            .rotation(angular_from3(Vec3::Z * -std::f32::consts::FRAC_PI_2))
1607            .build();
1608        world.bodies[body].set_rotation(*rotated.rotation(), false);
1609        let report = world
1610            .raycast_into(point(0., 0.), point(1., 0.), options, &mut hits)
1611            .unwrap();
1612        assert_eq!(report.total, 1);
1613        assert!((hits[0].unwrap().distance - 5.5).abs() < 0.001);
1614        world.bodies[body].set_translation(Vector::from_array(point(8., 0.)), false);
1615        world
1616            .set_collider_pose(child, Vec3::new(0., 3., 0.), Quat::IDENTITY)
1617            .unwrap();
1618        let report = world
1619            .spherecast_into(point(0., 0.), point(1., 0.), 0.25, options, &mut hits)
1620            .unwrap();
1621        assert_eq!(report.total, 1);
1622        assert_eq!(hits[0].unwrap().collider, child);
1623        assert!((hits[0].unwrap().distance - 10.25).abs() < 0.001);
1624
1625        let mut half = [0.1; DIM];
1626        half[0] = 2.;
1627        let box_body = world.add_box(point(4., 0.), half, false);
1628        let box_child = world.bodies[box_body].colliders()[0];
1629        world
1630            .set_collider_pose(
1631                box_child,
1632                Vec3::ZERO,
1633                Quat::from_rotation_z(std::f32::consts::FRAC_PI_2),
1634            )
1635            .unwrap();
1636        let report = world
1637            .raycast_into(point(0., 0.), point(1., 0.), options, &mut hits)
1638            .unwrap();
1639        assert_eq!(report.total, 2);
1640        assert_eq!(hits[0].unwrap().collider, box_child);
1641        assert!((hits[0].unwrap().distance - 3.9).abs() < 0.001);
1642        assert!(world.contact_events().is_empty());
1643    }
1644
1645    #[test]
1646    fn buffered_queries_handle_removed_and_reused_handles() {
1647        let mut world = PhysicsWorld::default();
1648        let removed = world.add_ball(point(1., 0.), 0.25, false);
1649        let other = world.add_ball(point(2., 0.), 0.25, false);
1650        let options = QueryOptions::new(5.).ignore_body(removed);
1651        let mut hits = [None; 3];
1652        assert!(world.remove_body(removed));
1653        let replacement = world.add_ball(point(2., 0.), 0.25, false);
1654        assert_ne!(replacement, removed);
1655        let report = world
1656            .raycast_into(point(0., 0.), point(1., 0.), options, &mut hits)
1657            .unwrap();
1658        assert_eq!(report.total, 2);
1659        // Reuse filled an earlier slot: ties follow iteration, not creation time.
1660        assert_eq!(hits[0].unwrap().body, Some(other));
1661        assert_eq!(hits[1].unwrap().body, Some(replacement));
1662        let child = world.bodies[other].colliders()[0];
1663        world.remove_collider(child).unwrap();
1664        let report = world
1665            .raycast_into(point(0., 0.), point(1., 0.), options, &mut hits)
1666            .unwrap();
1667        assert_eq!(report.total, 1);
1668        assert_eq!(hits[0].unwrap().body, Some(replacement));
1669        assert!(hits[1..].iter().all(Option::is_none));
1670    }
1671
1672    #[test]
1673    fn buffered_queries_preserve_overlap_distance_and_normalization_rules() {
1674        let mut world = PhysicsWorld::default();
1675        world.add_ball(point(3., 0.), 0.5, false);
1676        let options = QueryOptions::new(2.5);
1677        for speed in [f32::from_bits(1), 0.01, 1., 30., f32::MAX] {
1678            let mut ray = [None; 2];
1679            let report = world
1680                .raycast_into(point(0., 0.), point(speed, 0.), options, &mut ray)
1681                .unwrap();
1682            assert_eq!(report.total, 1);
1683            let hit = ray[0].unwrap();
1684            assert_eq!(hit.distance, 2.5);
1685            assert_eq!(hit.point, point(2.5, 0.));
1686            assert_eq!(hit.normal, point(-1., 0.));
1687            let mut sphere = [None; 2];
1688            assert_eq!(
1689                world
1690                    .spherecast_into(point(0., 0.), point(speed, 0.), 0., options, &mut sphere)
1691                    .unwrap(),
1692                report
1693            );
1694            assert_hit(ray[0], sphere[0]);
1695            assert_eq!(
1696                world
1697                    .raycast_into(
1698                        point(0., 0.),
1699                        point(speed, 0.),
1700                        QueryOptions::new(2.4),
1701                        &mut ray
1702                    )
1703                    .unwrap()
1704                    .total,
1705                0
1706            );
1707        }
1708        for radius in [0., 0.25, 1000.] {
1709            let mut hits = [None; 1];
1710            let report = world
1711                .spherecast_into(
1712                    point(3., 0.),
1713                    point(1., 0.),
1714                    radius,
1715                    QueryOptions::new(0.),
1716                    &mut hits,
1717                )
1718                .unwrap();
1719            assert_eq!(report.total, 1);
1720            let hit = hits[0].unwrap();
1721            assert_eq!(hit.distance, 0.);
1722            assert_eq!(hit.point, point(3., 0.));
1723            assert!(hit.normal.iter().all(|value| value.is_finite()));
1724        }
1725        let mut off_axis = PhysicsWorld::default();
1726        off_axis.add_ball(point(3., 1.), 0.5, false);
1727        let mut hits = [None; 1];
1728        assert_eq!(
1729            off_axis
1730                .raycast_into(point(0., 0.), point(1., 0.), options, &mut hits)
1731                .unwrap()
1732                .total,
1733            0
1734        );
1735        assert_eq!(
1736            off_axis
1737                .spherecast_into(point(0., 0.), point(1., 0.), 0.75, options, &mut hits)
1738                .unwrap()
1739                .total,
1740            1
1741        );
1742        assert!((hits[0].unwrap().distance - 2.25).abs() < 0.001);
1743    }
1744
1745    #[test]
1746    fn buffered_query_errors_are_field_specific_and_preserve_the_buffer() {
1747        let mut world = PhysicsWorld::default();
1748        let body = world.add_ball(point(3., 0.), 0.5, false);
1749        let origin = point(0., 0.);
1750        let direction = point(1., 0.);
1751        let options = QueryOptions::new(10.);
1752        let previous = world.raycast_with_options(origin, direction, options);
1753        let mut buffer = [previous, None, previous];
1754        let before = buffer;
1755        let mut check = |origin, direction, radius, options, expected| {
1756            assert_eq!(
1757                world.spherecast_into(origin, direction, radius, options, &mut buffer),
1758                Err(expected)
1759            );
1760            for (actual, expected) in buffer.into_iter().zip(before) {
1761                assert_hit(actual, expected);
1762            }
1763        };
1764        for bad in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
1765            for axis in 0..DIM {
1766                let mut bad_origin = origin;
1767                bad_origin[axis] = bad;
1768                check(
1769                    bad_origin,
1770                    direction,
1771                    0.25,
1772                    options,
1773                    QueryError::NonFiniteOrigin,
1774                );
1775                let mut bad_direction = direction;
1776                bad_direction[axis] = bad;
1777                check(
1778                    origin,
1779                    bad_direction,
1780                    0.25,
1781                    options,
1782                    QueryError::NonFiniteDirection,
1783                );
1784            }
1785        }
1786        for bad in [-1., f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
1787            check(
1788                origin,
1789                direction,
1790                0.25,
1791                QueryOptions::new(bad),
1792                QueryError::InvalidMaxDistance,
1793            );
1794        }
1795        for bad in [-1., 1000.1, f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
1796            check(origin, direction, bad, options, QueryError::InvalidRadius);
1797        }
1798        check(origin, [0.; DIM], 0.25, options, QueryError::ZeroDirection);
1799        check(
1800            point(f32::MAX, 0.),
1801            direction,
1802            0.25,
1803            QueryOptions::new(f32::MAX),
1804            QueryError::NonFiniteEndpoint,
1805        );
1806        let empty = PhysicsWorld::default();
1807        assert_eq!(
1808            empty.raycast_into(origin, [0.; DIM], options.layers(0), &mut []),
1809            Err(QueryError::ZeroDirection)
1810        );
1811        assert_hit(
1812            world.raycast_with_options(origin, direction, options),
1813            previous,
1814        );
1815        assert_eq!(
1816            world.bodies[body].translation(),
1817            Vector::from_array(point(3., 0.))
1818        );
1819        assert!(world.contact_events().is_empty());
1820    }
1821}