pub struct PhysicsWorld {
pub raw: World<RigidBody>,
}Fields§
§raw: World<RigidBody>Implementations§
Source§impl PhysicsWorld
impl PhysicsWorld
pub fn new(gravity: [f32; 2]) -> PhysicsWorld
Sourcepub fn joint_desc_from_world(
&self,
a: RigidBodyHandle,
b: RigidBodyHandle,
desc: impl Into<JointDesc>,
frame: WorldJointFrame,
pose: JointPoseMode,
) -> Result<JointDesc, PhysicsError>
pub fn joint_desc_from_world( &self, a: RigidBodyHandle, b: RigidBodyHandle, desc: impl Into<JointDesc>, frame: WorldJointFrame, pose: JointPoseMode, ) -> Result<JointDesc, PhysicsError>
Derive body-local anchors, hinge axes and reference rotation from current
live body poses. See WorldJointFrame for executable authoring recipes.
Frame anchors replace the description’s local anchors. For hinges, the
finite nonzero world axis is normalized (including tiny/huge scales), then
transformed into each body’s local space; old local axes are replaced.
In 2D only +Z is accepted, within crate::JointDesc::validate’s tolerance.
The axis is ignored for other kinds. Origins are authored body origins,
independent of compound center-of-mass offsets and child collider poses.
JointPoseMode::Preserve captures current relative rotation and the
distance/spring rest length, replacing those description fields. Fixed
and hinge joints require identical world pivots in this mode. It removes
initial geometric/rest error within floating-point rounding; retained
limits, motors, velocities, forces, contacts and later body edits may
still move the bodies on the next tick. It does not freeze simulation.
JointPoseMode::Authored retains the description’s rest length and
explicit reference rotation; None captures relative rotation now.
Checks both generational handles first (InvalidHandle), then distinct
bodies with at least one dynamic endpoint (InvalidJoint), then finite
current positions and unit rotations (InvalidBody). Invalid world
geometry, separated preserve-mode fixed/hinge pivots, or a rejected final
JointDesc::validate returns InvalidJoint. Handles must belong to this
world; they do not encode world identity. No capacity check, mutation,
allocation, wake, cache invalidation or timestep occurs. This reads poses
immediately after setters/teleport without a step or query refresh.
Caller-defined Into<JointDesc> code is outside these guarantees.
The returned description is a snapshot, not a live binding. Insert it
before moving either body, or use Self::insert_joint_from_world.
Sourcepub fn insert_joint_from_world(
&mut self,
a: RigidBodyHandle,
b: RigidBodyHandle,
desc: impl Into<JointDesc>,
frame: WorldJointFrame,
pose: JointPoseMode,
) -> Result<JointHandle, PhysicsError>
pub fn insert_joint_from_world( &mut self, a: RigidBodyHandle, b: RigidBodyHandle, desc: impl Into<JointDesc>, frame: WorldJointFrame, pose: JointPoseMode, ) -> Result<JointHandle, PhysicsError>
Author with Self::joint_desc_from_world and immediately use the
existing joint insertion path. See WorldJointFrame for examples.
Retains insertion’s JointCapacity error, bounded storage, wake/filter
behavior and allocations. Ordinary errors leave the world unchanged;
authoring itself allocates nothing, but successful insertion can grow
the existing arenas/scratch storage. No new solver or stepping policy.
Sourcepub fn try_teleport_body(
&mut self,
body: RigidBodyHandle,
pose: RigidBodyPose,
options: TeleportOptions,
) -> Result<RigidBodyPose, TeleportError>
pub fn try_teleport_body( &mut self, body: RigidBodyHandle, pose: RigidBodyPose, options: TeleportOptions, ) -> Result<RigidBodyPose, TeleportError>
Handle-checked RigidBody::try_teleport, with the same atomic reset,
deferred cache/wake and no-allocation behavior. Checks the handle before
pose fields; a removed handle never edits a replacement in its old slot.
Handles must belong to this world. Works for dynamic, fixed and kinematic
bodies and needs no query refresh. No body/collider/joint is recreated.
This checkpoint recipe updates host interpolation only after success. Replace the two samples with the J400 202 interpolation adapter’s snap operation when composing with that engine feature.
use ferravex_math::{Quat, Vec3};
use ferravex_physics::d3::{
PhysicsWorld, RigidBodyPose, TeleportError, TeleportOptions, VelocityPolicy,
};
let mut world = PhysicsWorld::default();
let ball = world.add_ball([0.; 3], 0.5, true);
let old = RigidBodyPose { translation: Vec3::ZERO, rotation: Quat::IDENTITY };
let mut samples = [old; 2];
let checkpoint = RigidBodyPose {
translation: Vec3::new(4., 2., 0.), rotation: Quat::IDENTITY * 2.,
};
let committed = world.try_teleport_body(
ball, checkpoint, TeleportOptions::new(VelocityPolicy::Clear),
).unwrap();
assert!(committed.rotation.is_normalized());
samples.fill(committed); // Snap previous and current only on success.
assert_eq!(samples[0], samples[1]);
let invalid = RigidBodyPose { translation: Vec3::NAN, ..checkpoint };
assert_eq!(world.try_teleport_body(
ball, invalid, TeleportOptions::new(VelocityPolicy::Preserve),
), Err(TeleportError::Translation));
assert_eq!(world.bodies[ball].translation(), samples[1].translation);
world.step(1. / 60.);
assert_eq!(world.bodies[ball].translation(), committed.translation);pub fn add_ball( &mut self, p: [f32; 2], radius: f32, dynamic: bool, ) -> RigidBodyHandle
pub fn add_box( &mut self, p: [f32; 2], half: [f32; 2], dynamic: bool, ) -> RigidBodyHandle
Sourcepub fn refresh_queries(&mut self)
pub fn refresh_queries(&mut self)
Queries use current body poses directly; no separate broadphase synchronization is needed.
Sourcepub fn spherecast(
&self,
origin: [f32; 2],
direction: [f32; 2],
max_distance: f32,
radius: f32,
mask: u32,
ignore: Option<RigidBodyHandle>,
) -> Option<RayHit>
pub fn spherecast( &self, origin: [f32; 2], direction: [f32; 2], max_distance: f32, radius: f32, mask: u32, ignore: Option<RigidBodyHandle>, ) -> Option<RayHit>
Sweep a ball through current collider poses, filtering sensors, membership
and an optional ignored body (all its compound children). The hit point
is the swept ball center at impact. Invalid inputs return None.
See Self::spherecast_with_options for named filters and sensor policies.
Sourcepub fn raycast(
&self,
origin: [f32; 2],
direction: [f32; 2],
max_distance: f32,
) -> Option<RayHit>
pub fn raycast( &self, origin: [f32; 2], direction: [f32; 2], max_distance: f32, ) -> Option<RayHit>
Cast against solid colliders in all layers using their current poses.
See Self::raycast_with_options to select layers, sensors or an ignored body.
Sourcepub fn raycast_with_options(
&self,
origin: [f32; 2],
direction: [f32; 2],
options: QueryOptions,
) -> Option<RayHit>
pub fn raycast_with_options( &self, origin: [f32; 2], direction: [f32; 2], options: QueryOptions, ) -> Option<RayHit>
Cast a ray with reusable distance and filtering options.
Direction is normalized internally, so distances are world units. The
nearest accepted collider is returned; an initial overlap hits at zero.
Queries see body and child-collider edits immediately, without a physics
step or Self::refresh_queries. Validation and tie behavior match
Self::spherecast_with_options with a zero radius.
See QueryOptions for a complete ray/sphere example.
Sourcepub fn spherecast_with_options(
&self,
origin: [f32; 2],
direction: [f32; 2],
radius: f32,
options: QueryOptions,
) -> Option<RayHit>
pub fn spherecast_with_options( &self, origin: [f32; 2], direction: [f32; 2], radius: f32, options: QueryOptions, ) -> Option<RayHit>
Sweep a ball (a circle in 2D) with named distance and filtering options.
Uses current poses and allocates no query storage. The hit point is the
swept center, the normal points out of the target, and distance is travel
in world units. Initial overlap returns distance zero. Equal-distance
hits select the later collider in the world’s iteration order, matching
the original casts. See QueryOptions for usage.
Returns None for no accepted hit, nonfinite origin/direction/distance/
radius, zero direction, negative distance, radius outside 0..=1000, or
a cast endpoint that overflows. A zero distance still tests initial
overlap and requires a nonzero direction. Like the original casts, this
uses the solver’s finite-iteration convex sweep, so grazing hits may be
missed when its iteration budget is exhausted.
Sourcepub fn raycast_into(
&self,
origin: [f32; 2],
direction: [f32; 2],
options: QueryOptions,
output: &mut [Option<RayHit>],
) -> Result<QueryReport, QueryError>
pub fn raycast_into( &self, origin: [f32; 2], direction: [f32; 2], options: QueryOptions, output: &mut [Option<RayHit>], ) -> Result<QueryReport, QueryError>
Collect ray hits into caller-owned storage without allocating.
This is Self::spherecast_into with radius zero: the nearest hits fit
into output in distance order, and the report counts every accepted
collider hit, even when the buffer is empty or too small. On success,
unused entries are None; on invalid input, the buffer is unchanged.
use ferravex_physics::d2::{PhysicsWorld, QueryOptions};
let mut world = PhysicsWorld::default();
world.add_ball([6., 0.], 0.5, false);
let near = world.add_ball([2., 0.], 0.5, false);
let mut hits = [None; 1];
let report = world.raycast_into([0.; 2], [1., 0.], QueryOptions::new(10.),
&mut hits).unwrap();
assert_eq!((report.written, report.total), (1, 2));
assert!(report.is_truncated());
assert_eq!(hits[0].unwrap().body, Some(near));Sourcepub fn spherecast_into(
&self,
origin: [f32; 2],
direction: [f32; 2],
radius: f32,
options: QueryOptions,
output: &mut [Option<RayHit>],
) -> Result<QueryReport, QueryError>
pub fn spherecast_into( &self, origin: [f32; 2], direction: [f32; 2], radius: f32, options: QueryOptions, output: &mut [Option<RayHit>], ) -> Result<QueryReport, QueryError>
Collect sphere (circle in 2D) hits using current body and child poses.
Uses the same validation, membership layers, ignored body, sensor policy,
normalized direction, swept-center points and initial-overlap behavior
as Self::spherecast_with_options. Each accepted collider contributes
at most one hit, including separate children of a compound body.
Success replaces the buffer with the nearest min(output.len(), total)
hits in ascending distance order, followed by None. Equal distances
place the later collider in world iteration order first, matching the
nearest cast’s tie preference. Every collider is tested over the full
distance, so a full buffer never stops counting farther hits. An empty
buffer is a count-only query. Errors preserve every output entry.
Storage is bounded by the caller’s slice; no query allocation occurs.
Insertion into the sorted buffer takes up to output.len() moves per
hit. For large worlds, use a small buffer when only nearby hits matter.
The existing finite-iteration convex sweep can miss grazing hits; counts
describe hits it finds, not a proof that every geometric hit was found.
Full-distance casts can also round differently from the shrinking-limit
nearest cast. This does not advance simulation or refresh cached poses.
use ferravex_physics::d3::{PhysicsWorld, QueryOptions};
let mut world = PhysicsWorld::default();
world.add_ball([3., 0., 0.], 0.5, false);
let mut hits = [None; 4];
let report = world.spherecast_into([0.; 3], [2., 0., 0.], 0.5,
QueryOptions::new(5.), &mut hits).unwrap();
assert_eq!((report.written, report.total), (1, 1));
assert!(!report.is_truncated());
assert!((hits[0].unwrap().distance - 2.).abs() < 0.001);
assert!(hits[1..].iter().all(Option::is_none));Sourcepub fn overlap_point_with_options(
&self,
point: [f32; 2],
options: QueryOptions,
) -> Option<OverlapHit>
pub fn overlap_point_with_options( &self, point: [f32; 2], options: QueryOptions, ) -> Option<OverlapHit>
Return the point result with the smallest signed separation.
This is Self::overlap_sphere_with_options with radius zero. See
Self::overlap_point_into for a runnable example.
Sourcepub fn overlap_sphere_with_options(
&self,
center: [f32; 2],
radius: f32,
options: QueryOptions,
) -> Option<OverlapHit>
pub fn overlap_sphere_with_options( &self, center: [f32; 2], radius: f32, options: QueryOptions, ) -> Option<OverlapHit>
Return the sphere result with the smallest signed separation.
The deepest penetration wins, then touching, then the closest separated
collider. Equal separations prefer the later collider in world iteration
order. Filtering and geometry match Self::overlap_sphere_into. Invalid
input or no accepted collider returns None; use the buffered method to
distinguish invalid input from a miss. No allocation or world mutation.
Sourcepub fn overlap_point_into(
&self,
point: [f32; 2],
options: QueryOptions,
output: &mut [Option<OverlapHit>],
) -> Result<QueryReport, QueryError>
pub fn overlap_point_into( &self, point: [f32; 2], options: QueryOptions, output: &mut [Option<OverlapHit>], ) -> Result<QueryReport, QueryError>
Collect point overlaps and nearby collider surfaces without a direction.
Equivalent to Self::overlap_sphere_into with radius zero, including
its signed separation, ordering, filtering and failure-atomic buffer.
QueryOptions::new(0.) includes touching and inside points; a positive
maximum distance also includes separated surfaces within that distance.
use ferravex_physics::d2::{PhysicsWorld, QueryOptions};
let mut world = PhysicsWorld::default();
let wall = world.add_box([0.; 2], [1.; 2], false);
let mut hits = [None; 2];
let report = world.overlap_point_into([1.25, 0.], QueryOptions::new(0.5),
&mut hits).unwrap();
assert_eq!((report.written, report.total), (1, 1));
let hit = hits[0].unwrap();
assert_eq!(hit.body, Some(wall));
assert_eq!(hit.separation, 0.25);
assert_eq!(hit.collider_point, [1., 0.]);
assert_eq!(hit.probe_point, [1.25, 0.]);Sourcepub fn overlap_sphere_into(
&self,
center: [f32; 2],
radius: f32,
options: QueryOptions,
output: &mut [Option<OverlapHit>],
) -> Result<QueryReport, QueryError>
pub fn overlap_sphere_into( &self, center: [f32; 2], radius: f32, options: QueryOptions, output: &mut [Option<OverlapHit>], ) -> Result<QueryReport, QueryError>
Collect direction-free sphere (circle in 2D) proximity results.
options.max_distance is the maximum signed surface separation:
zero includes overlaps and exact touches, positive values also include
nearby separated colliders. No solver contact margin is added. A negative
separation means penetration; its negation is the distance to translate
the probe along normal to touch this individual convex child. A compound
produces one result per child, not a combined depenetration solution.
Uses current body/child poses, membership layers, sensor policy and the
generational ignored-body filter shared with casts. No step, refresh,
broadphase, allocation or simulation mutation occurs. All existing target
shapes are supported by the shared signed-distance kernel; probes are
points/balls only. Results that cannot be represented in f32
(including overflowed witnesses) are omitted, as in existing casts.
Results sort by ascending signed separation (deepest penetration first),
with later colliders first on exact ties. The nearest output.len() are
retained; every accepted child counts toward total even after the buffer
fills. Empty output counts only. Success clears unused entries to None.
Insertion costs up to output.len() moves per accepted collider.
Validation checks finite center, finite nonnegative maximum separation,
then finite radius in 0..=1000, even with an empty world/buffer or zero
layer mask. Errors use existing QueryError variants and preserve the
entire buffer. Direction and cast-endpoint validation do not apply.
A placement preview can inspect penetration before committing a body. This recipe resolves a single wall, then rechecks the candidate; several overlapping children require an application-specific placement policy.
use ferravex_physics::d3::{PhysicsWorld, QueryOptions};
let mut world = PhysicsWorld::default();
let wall = world.add_box([0.; 3], [1.; 3], false);
let mut candidate = [1.25, 0., 0.];
let mut hits = [None; 4];
let report = world.overlap_sphere_into(candidate, 0.5, QueryOptions::new(0.),
&mut hits).unwrap();
assert_eq!((report.written, report.total), (1, 1));
let hit = hits[0].unwrap();
assert_eq!(hit.body, Some(wall));
assert_eq!(hit.penetration_depth(), 0.25);
for (coordinate, normal) in candidate.iter_mut().zip(hit.normal) {
*coordinate += normal * hit.penetration_depth();
}
let touching = world.overlap_sphere_with_options(candidate, 0.5,
QueryOptions::new(0.)).unwrap();
assert_eq!(touching.separation, 0.);
assert_eq!(touching.collider_point, touching.probe_point);
// Queries did not move the authored wall or create the preview body.
assert_eq!(world.bodies.len(), 1);