Scene queries
Scene queries are geometric queries that take all the colliders of the physics world into account. These queries are available through the QueryPipeline.
The QueryPipeline is a temporary object obtained from the physics world with PhysicsWorld::query_pipeline (or
PhysicsWorld::query_pipeline_with_filter). It reuses the acceleration data-structure (BVH) of the broad-phase, which
is automatically updated by the physics stepping function. Therefore the scene queries take into account the positions
of the colliders at the end of the last timestep:
- Example 2D
- Example 3D
// Game loop.
for _ in 0..10 {
// Stepping the simulation updates the broad-phase the scene queries rely on.
world.step();
// The scene queries take into account the positions of the colliders at the end of
// the last timestep.
let query_pipeline = world.query_pipeline();
// Run the scene queries with `query_pipeline` here.
}
// Game loop.
for _ in 0..10 {
// Stepping the simulation updates the broad-phase the scene queries rely on.
world.step();
// The scene queries take into account the positions of the colliders at the end of
// the last timestep.
let query_pipeline = world.query_pipeline();
// Run the scene queries with `query_pipeline` here.
}
Ray-casting
Ray-casting is a geometric query that finds one or several colliders intersecting a half-line. Ray-casting is an extremely common operation that covers a wide variety of use-cases: firing bullets, character controllers, rendering (for ray-tracing), etc.
A ray is defined by its origin and its direction: it can be interpreted as a single point moving in a straight line towards the ray direction.
In addition to the ray geometric information, ray-casting method allow additional control over the behavior of the ray cast like limiting the length of the ray and ignoring some colliders. See the detailed ray-cast arguments description after the next example.
There are multiple ray-casting methods yielding more or less detailed results (see example below). The more results you get, the more computationally expensive the ray-cast will be.
- Example 2D
- Example 3D
let ray = Ray::new(Vector::new(1.0, 2.0), Vector::new(0.0, 1.0));
let max_toi = 4.0;
let solid = true;
let filter = QueryFilter::default();
let query_pipeline = world.query_pipeline_with_filter(filter);
if let Some((handle, toi)) = query_pipeline.cast_ray(
&ray, max_toi, solid
) {
// The first collider hit has the handle `handle` and it hit after
// the ray travelled a distance equal to `ray.dir * toi`.
let hit_point = ray.point_at(toi); // Same as: `ray.origin + ray.dir * toi`
println!("Collider {:?} hit at point {}", handle, hit_point);
}
if let Some((handle, intersection)) = query_pipeline.cast_ray_and_get_normal(
&ray, max_toi, solid
) {
// This is similar to `QueryPipeline::cast_ray` illustrated above except
// that it also returns the normal of the collider shape at the hit point.
let hit_point = ray.point_at(intersection.time_of_impact);
let hit_normal = intersection.normal;
println!("Collider {:?} hit at point {} with normal {}", handle, hit_point, hit_normal);
}
for (handle, _, intersection) in query_pipeline.intersect_ray(ray, max_toi, solid) {
// Callback called on each collider hit by the ray.
let hit_point = ray.point_at(intersection.time_of_impact);
let hit_normal = intersection.normal;
println!("Collider {:?} hit at point {} with normal {}", handle, hit_point, hit_normal);
}
let ray = Ray::new(Vector::new(1.0, 2.0, 3.0), Vector::new(0.0, 1.0, 0.0));
let max_toi = 4.0;
let solid = true;
let filter = QueryFilter::default();
let query_pipeline = world.query_pipeline_with_filter(filter);
if let Some((handle, toi)) = query_pipeline.cast_ray(
&ray, max_toi, solid
) {
// The first collider hit has the handle `handle` and it hit after
// the ray travelled a distance equal to `ray.dir * toi`.
let hit_point = ray.point_at(toi); // Same as: `ray.origin + ray.dir * toi`
println!("Collider {:?} hit at point {}", handle, hit_point);
}
if let Some((handle, intersection)) = query_pipeline.cast_ray_and_get_normal(
&ray, max_toi, solid
) {
// This is similar to `QueryPipeline::cast_ray` illustrated above except
// that it also returns the normal of the collider shape at the hit point.
let hit_point = ray.point_at(intersection.time_of_impact);
let hit_normal = intersection.normal;
println!("Collider {:?} hit at point {} with normal {}", handle, hit_point, hit_normal);
}
for (handle, _, intersection) in query_pipeline.intersect_ray(ray, max_toi, solid) {
// Callback called on each collider hit by the ray.
let hit_point = ray.point_at(intersection.time_of_impact);
let hit_normal = intersection.normal;
println!("Collider {:?} hit at point {} with normal {}", handle, hit_point, hit_normal);
}
Aside from the ray being cast, all these ray-casting methods take a few extra parameters for controlling the behavior of the ray-cast:
max_toi: is the maximum "time-of-impact" that can be reported by the ray-cast. The notion of "time-of-impact" refer to the fact that a ray can be seen as a point starting atray.originmoving at a linear velocity equal toray.dir. Therefore,max_toilimits the ray-cast to the segment:[ray.origin, ray.origin + ray.dir * max_toi].solid: this argument controls the behavior of the ray-cast ifray.originis inside of a shape: ifsolidistruethen the hit point will be the ray origin itself (toi = 0.0) because the interior of the shape will be assumed to be filled with material. Ifsolidisfalsethen the shape will be assumed to have an empty interior and the hit point will be the first time the ray hits the shape's boundary. The following 2D example illustrates the difference between the two scenarios. The ray is in green and the resulting hit point circled in red:
In addition, it is possible to only apply the scene query to a subsets of the colliders using a query filter.
Shape-casting
Shape-casting (aka. sweep tests) is the big brother of ray-casting. The only difference with ray-cast is that instead of being a point travelling along a straight line, we have a complete shape travelling along a straight line. This is typically used for character controllers in games to determine by how much the player can move before it hits the environment.
Just like ray-casting, it is possible to control the behavior of the shape-casting like limiting the distance
travelled by the shape cast, and ignoring some colliders. See the details about the
max_toi and filter arguments in the ray-casting section.
The shape-casting along a straight line is performed by QueryPipeline::cast_shape.
This method has similar arguments as QueryPipeline::cast_ray except
that the ray is replaced by three arguments: the shape being cast, the initial position of the shape (this is analog to ray.origin) and
the linear velocity the shape is travelling at (this is analog to ray.dir):
- Example 2D
- Example 3D
let shape = Cuboid::new(Vector::new(1.0, 2.0));
let shape_pos = Pose::new(Vector::new(0.0, 1.0), 0.2);
let shape_vel = Vector::new(0.1, 0.4);
let max_toi = 4.0;
let filter = QueryFilter::default();
let options = ShapeCastOptions {
max_time_of_impact: 4.0,
target_distance: 0.0,
stop_at_penetration: false,
compute_impact_geometry_on_penetration: false,
};
let query_pipeline = world.query_pipeline_with_filter(filter);
if let Some((handle, hit)) = query_pipeline.cast_shape(
&shape_pos, shape_vel, &shape, options
) {
// The first collider hit has the handle `handle`. The `hit` is a
// structure containing details about the hit configuration.
println!("Hit the collider {:?} with the configuration: {:?}", handle, hit);
}
let shape = Cuboid::new(Vector::new(1.0, 2.0, 3.0));
let shape_pos = Pose::new(Vector::new(0.0, 1.0, 0.0), Vector::new(0.2, 0.7, 0.1));
let shape_vel = Vector::new(0.1, 0.4, 0.2);
let max_toi = 4.0;
let filter = QueryFilter::default();
let options = ShapeCastOptions {
max_time_of_impact: 4.0,
target_distance: 0.0,
stop_at_penetration: false,
compute_impact_geometry_on_penetration: false,
};
let query_pipeline = world.query_pipeline_with_filter(filter);
if let Some((handle, hit)) = query_pipeline.cast_shape(
&shape_pos, shape_vel, &shape, options
) {
// The first collider hit has the handle `handle`. The `hit` is a
// structure containing details about the hit configuration.
println!("Hit the collider {:?} with the configuration: {:?}", handle, hit);
}
The result of the shape-casting includes the handle of the first collider being hit, as well as detailed information about the geometry of the hit:
hit.time_of_impact: indicates the time of impact between the shape and the collider hit. This means that after travelling a distance ofshape_vel * hit.time_of_impactthe collider and the cast shape are exactly touching. Ifhit.time_of_impact == 0.0then the shape is already intersecting a collider at its initial position.hit.witness1: indicates the contact point on the collider hit when the cast shape and the collider are touching, expressed in world-space.hit.witness2: indicates the contact point on the cast shape when the cast shape and the collider are touching, expressed in the local-space of the cast shape.hit.normal1: indicates the outward normal of the collider hit at the contact pointhit.witness1, expressed in world-space.hit.normal2: indicates the outward normal of the cast shape at the contact pointhit.witness2, expressed in the local-space of the cast shape.
Because the cast shape moved, hit.witness2 and hit.normal2 can be converted to world-space by applying the pose of
the cast shape at the time of impact, i.e., its initial pose translated by shape_vel * hit.time_of_impact.
If the shape was already intersecting a collider at its initial position, the witness points and normals are only
reliable if ShapeCastOptions::compute_impact_geometry_on_penetration is set to true.
Nonlinear shape-casting
The shape-casting above only moves the shape along a straight line: its orientation doesn't change during the cast.
If the rotation of the shape matters, QueryPipeline::cast_shape_nonlinear performs a
nonlinear shape-casting: the shape follows a rigid motion combining a constant linear velocity and a constant
angular velocity. This motion is described by a NonlinearRigidMotion which contains the initial pose of the
shape, its linear and angular velocities, and the local-space point around which the shape rotates. At time , the
shape is rotated by the angular velocity times around that point, and translated by the linear velocity times .
The first impact is searched for between the start_time and end_time arguments. This is typically useful to
predict if a rotating object (e.g. a spinning blade, a swinging door, or the collider of a rigid-body with a non-zero
angular velocity) will hit something during a timestep.
If the shape is already intersecting a collider at start_time, setting stop_at_penetration to true makes the cast
report that collider with a time of impact equal to start_time. If it is false, that penetration is ignored when the
motion is separating the shapes, and the cast searches for a later impact that would result in tunnelling. The result
has the same form as for cast_shape (with hit.witness1 and hit.normal1 in world-space, and hit.witness2 and
hit.normal2 in the local-space of the cast shape, whose pose at the time of impact is given by
NonlinearRigidMotion::position_at_time). Nonlinear shape-casting is more expensive than the linear one, so it is recommended to
use cast_shape whenever the shape doesn't rotate.
Point projection
Point projection will either project a point on the closest collider of the scene (QueryPipeline::project_point),
or will enumerate every collider containing given point (QueryPipeline::intersect_point).
- Example 2D
- Example 3D
let point = Vector::new(1.0, 2.0);
let solid = true;
let max_dist = 12.0;
let filter = QueryFilter::default();
let query_pipeline = world.query_pipeline_with_filter(filter);
if let Some((handle, projection)) = query_pipeline.project_point(
point, max_dist, solid
) {
// The collider closest to the point has this `handle`.
println!("Projected point on collider {:?}. Point projection: {}", handle, projection.point);
println!("Point was inside of the collider shape: {}", projection.is_inside);
}
for (handle, _) in query_pipeline.intersect_point(point) {
// Callback called on each collider with a shape containing the point.
println!("The collider {:?} contains the point.", handle);
}
let point = Vector::new(1.0, 2.0, 3.0);
let solid = true;
let max_dist = 12.0;
let filter = QueryFilter::default();
let query_pipeline = world.query_pipeline_with_filter(filter);
if let Some((handle, projection)) = query_pipeline.project_point(
point, max_dist, solid
) {
// The collider closest to the point has this `handle`.
println!("Projected point on collider {:?}. Point projection: {}", handle, projection.point);
println!("Point was inside of the collider shape: {}", projection.is_inside);
}
for (handle, _) in query_pipeline.intersect_point(point) {
// Callback called on each collider with a shape containing the point.
println!("The collider {:?} contains the point.", handle);
}
It is possible to only apply the scene query to a subsets of the colliders using a query filter
Intersection test
Intersection tests will find all the colliders with a shape intersecting a given shape. This can be useful for, e.g., selecting all the objects that intersect a given area. There are two kind of intersection tests:
- The exact intersection test
QueryPipeline::intersect_shapesearches for all the colliders with shapes intersecting the given shape. - The approximate intersection test
QueryPipeline::intersect_aabb_conservativesearches for all the colliders with an AABB intersecting the given AABB. This does not check if the actual shapes of these colliders intersect the AABB. Note that the AABB taken into account is the one currently stored in the BVH of the broad-phase: it isn't recomputed from the latest collider positions.
See the ray-casting section for details about intersection tests between a ray and the colliders on the scene. And see the point projection section for details about the intersection test between the colliders and a point.
- Example 2D
- Example 3D
let shape = Cuboid::new(Vector::new(1.0, 2.0));
let shape_pos = Pose::new(Vector::new(0.0, 1.0), 0.2);
let filter = QueryFilter::default();
let query_pipeline = world.query_pipeline_with_filter(filter);
for (handle, _) in query_pipeline.intersect_shape(shape_pos, &shape) {
println!("The collider {:?} intersects our shape.", handle);
}
let aabb = Aabb::new(Vector::new(-1.0, -2.0), Vector::new(1.0, 2.0));
for (handle, _) in query_pipeline.intersect_aabb_conservative(aabb) {
println!("The collider {:?} has an AABB intersecting our test AABB", handle);
}
let shape = Cuboid::new(Vector::new(1.0, 2.0, 3.0));
let shape_pos = Pose::new(Vector::new(0.0, 1.0, 0.0), Vector::new(0.2, 0.7, 0.1));
let filter = QueryFilter::default();
let query_pipeline = world.query_pipeline_with_filter(filter);
for (handle, _) in query_pipeline.intersect_shape(shape_pos, &shape) {
println!("The collider {:?} intersects our shape.", handle);
}
let aabb = Aabb::new(Vector::new(-1.0, -2.0, -3.0), Vector::new(1.0, 2.0, 3.0));
for (handle, _) in query_pipeline.intersect_aabb_conservative(aabb) {
println!("The collider {:?} has an AABB intersecting our test AABB", handle);
}
It is possible to only apply the scene query to a subsets of the colliders using a query filter
Query filters
It is common to exclude some colliders from being considered by a scene query. For example, a ray-cast performed for a
character controller will usually want to skip the character itself. Sometimes, we may even want it to ignore both the
character and any collider attached to a dynamic rigid-body, and ignore all sensors. To allow this filtering, most
scene queries take a QueryFilter argument that lets you describe what needs to be excluded. In particular
its fields:
flagsallows you to discard whole families of colliders based on their types or their parent types (e.g. exclude all sensors and all the colliders attached to a dynamic rigid-body).groupsis used to apply the collision group rules for the scene query. The scene query will only consider hits with colliders with collision groups compatible with this collision group (using the bitwise test described in the collision groups section).exclude_collideris the handle of one collider the query must ignore.exclude_rigid_bodyis the handle of one rigid-body with attached colliders the query must ignore.predicateis a user-defined closure to apply any filtering rule. This can be used if the other filtering options above are not flexible enough.
Here is an an example of usage of the query filters with ray-casting:
let ray = Ray::new(Vector::new(1.0, 2.0), Vector::new(0.0, 1.0));
let max_toi = 4.0;
let solid = true;
let filter = QueryFilter::exclude_dynamic()
.exclude_sensors()
.exclude_rigid_body(player_handle)
.groups(InteractionGroups::new(
Group::GROUP_1 | Group::GROUP_2,
Group::GROUP_1,
InteractionTestMode::And,
))
.predicate(&|handle, collider| collider.user_data == 10);
let query_pipeline = world.query_pipeline_with_filter(filter);
if let Some((handle, toi)) = query_pipeline.cast_ray(&ray, max_toi, solid) {
// Handle the hit.
}