Skip to content

Commit

Permalink
Split RapierContext (#585)
Browse files Browse the repository at this point in the history
  • Loading branch information
Vrixyz authored Dec 10, 2024
1 parent 0022583 commit ac4fb03
Show file tree
Hide file tree
Showing 45 changed files with 2,262 additions and 1,312 deletions.
16 changes: 14 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,27 @@

### Modified

- `RapierContext` has been split in multiple `Component`s:
- `RapierContextColliders`
- `RapierContextJoints`
- `RapierContextSimulation`
- `RapierRigidBodySet`
- Renamed `DefaultReadRapierContext` and `DefaultWriteRapierContext`.
- Use `ReadRapierContext` and its associated `single()` method.

## v0.28.0 (09 December 2024)

### Modified

- Update from rapier `0.21` to rapier `0.22`,
see [rapier's changelog](https://github.com/dimforge/rapier/blob/master/CHANGELOG.md).
- Update bevy to 0.15.
- `RapierContext`, `RapierConfiguration` and `RenderToSimulationTime` are now a `Component` instead of resources.
- `RapierContext`, `RapierConfiguration` and `SimulationToRenderTime` are now a `Component` instead of resources.
- Rapier now supports multiple independent physics worlds, see example `multi_world3` for usage details.
- Migration guide:
- `ResMut<mut RapierContext>` -> `WriteDefaultRapierContext`
- `Res<RapierContext>` -> `ReadDefaultRapierContext`
- Access to `RapierConfiguration` and `RenderToSimulationTime` should query for it
- Access to `RapierConfiguration` and `SimulationToRenderTime` should query for it
on the responsible entity owning the `RenderContext`.
- If you are building a library on top of `bevy_rapier` and would want to support multiple independent physics worlds too,
you can check out the details of [#545](https://github.com/dimforge/bevy_rapier/pull/545)
Expand Down
2 changes: 1 addition & 1 deletion bevy_rapier2d/examples/debugdump2.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! Example using bevy_mod_debugdump to output a graph of systems execution order.
//! run with:
//! `cargo run --example debugdump2 > dump.dot && dot -Tsvg dump.dot > dump.svg`
//! `cargo run --example debugdump2 > dump.dot && dot -Tsvg dump.dot > dump.svg`
use bevy::prelude::*;
use bevy_mod_debugdump::{schedule_graph, schedule_graph_dot};
Expand Down
9 changes: 5 additions & 4 deletions bevy_rapier2d/examples/testbed2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -205,11 +205,12 @@ fn main() {
OnExit(Examples::PlayerMovement2),
(
cleanup,
|mut rapier_config: Query<&mut RapierConfiguration>,
ctxt: ReadDefaultRapierContext| {
|mut rapier_config: Query<&mut RapierConfiguration>, ctxt: ReadRapierContext| {
let mut rapier_config = rapier_config.single_mut();
rapier_config.gravity =
RapierConfiguration::new(ctxt.integration_parameters.length_unit).gravity;
rapier_config.gravity = RapierConfiguration::new(
ctxt.single().simulation.integration_parameters.length_unit,
)
.gravity;
},
),
)
Expand Down
4 changes: 2 additions & 2 deletions bevy_rapier3d/examples/joints3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -279,7 +279,7 @@ pub fn setup_physics(mut commands: Commands) {
}

pub fn print_impulse_revolute_joints(
context: ReadDefaultRapierContext,
context: ReadRapierContext,
joints: Query<(Entity, &ImpulseJoint)>,
) {
for (entity, impulse_joint) in joints.iter() {
Expand All @@ -288,7 +288,7 @@ pub fn print_impulse_revolute_joints(
println!(
"angle for {}: {:?}",
entity,
context.impulse_revolute_joint_angle(entity),
context.single().impulse_revolute_joint_angle(entity),
);
}
_ => {}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use bevy::{input::common_conditions::input_just_pressed, prelude::*};
use bevy_rapier3d::prelude::*;

const N_WORLDS: usize = 2;
const N_CONTEXTS: usize = 2;

fn main() {
App::new()
Expand All @@ -18,21 +18,21 @@ fn main() {
))
.add_systems(
Startup,
((create_worlds, setup_physics).chain(), setup_graphics),
((create_contexts, setup_physics).chain(), setup_graphics),
)
.add_systems(Update, move_platforms)
.add_systems(
Update,
change_world.run_if(input_just_pressed(KeyCode::KeyC)),
change_context.run_if(input_just_pressed(KeyCode::KeyC)),
)
.run();
}

fn create_worlds(mut commands: Commands) {
for i in 0..N_WORLDS {
let mut world = commands.spawn((RapierContext::default(), WorldId(i)));
fn create_contexts(mut commands: Commands) {
for i in 0..N_CONTEXTS {
let mut context = commands.spawn((RapierContextSimulation::default(), ContextId(i)));
if i == 0 {
world.insert(DefaultRapierContext);
context.insert((DefaultRapierContext, RapierContextSimulation::default()));
}
}
}
Expand All @@ -45,7 +45,7 @@ fn setup_graphics(mut commands: Commands) {
}

#[derive(Component)]
pub struct WorldId(pub usize);
pub struct ContextId(pub usize);

#[derive(Component)]
struct Platform {
Expand All @@ -58,8 +58,8 @@ fn move_platforms(time: Res<Time>, mut query: Query<(&mut Transform, &Platform)>
}
}

/// Demonstrates how easy it is to move one entity to another world.
fn change_world(
/// Demonstrates how easy it is to move one entity to another context.
fn change_context(
query_context: Query<Entity, With<DefaultRapierContext>>,
mut query_links: Query<(Entity, &mut RapierContextEntityLink)>,
) {
Expand All @@ -69,12 +69,12 @@ fn change_world(
continue;
}
link.0 = default_context;
println!("changing world of {} for world {}", e, link.0);
println!("changing context of {} for context {}", e, link.0);
}
}

pub fn setup_physics(
context: Query<(Entity, &WorldId), With<RapierContext>>,
context: Query<(Entity, &ContextId), With<RapierContextSimulation>>,
mut commands: Commands,
) {
for (context_entity, id) in context.iter() {
Expand Down
62 changes: 62 additions & 0 deletions bevy_rapier3d/examples/rapier_context_component.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
use bevy::prelude::*;
use bevy_rapier3d::prelude::*;

fn main() {
App::new()
.add_plugins((
DefaultPlugins,
RapierPhysicsPlugin::<NoUserData>::default(),
RapierDebugRenderPlugin::default(),
))
.add_systems(Startup, (setup_physics, setup_graphics))
.add_systems(
PostUpdate,
display_nb_colliders.after(PhysicsSet::SyncBackend),
)
.run();
}

/// Demonstrates how to access a more specific component of [`RapierContext`]
fn display_nb_colliders(
query_context: Query<&RapierContextColliders, With<DefaultRapierContext>>,
mut exit: EventWriter<AppExit>,
) {
let nb_colliders = query_context.single().colliders.len();
println!("There are {nb_colliders} colliders.");
assert!(nb_colliders > 0);
exit.send(AppExit::Success);
}

pub fn setup_physics(mut commands: Commands) {
/*
* Ground
*/
let ground_size = 5.1;
let ground_height = 0.1;

let starting_y = -0.5 - ground_height;

commands.spawn((
Transform::from_xyz(0.0, starting_y, 0.0),
Collider::cuboid(ground_size, ground_height, ground_size),
));

for _ in 0..3 {
/*
* Create the cubes
*/

commands.spawn((
Transform::default(),
RigidBody::Dynamic,
Collider::cuboid(0.5, 0.5, 0.5),
));
}
}

fn setup_graphics(mut commands: Commands) {
commands.spawn((
Camera3d::default(),
Transform::from_xyz(0.0, 3.0, -10.0).looking_at(Vec3::new(0.0, 0.0, 0.0), Vec3::Y),
));
}
6 changes: 3 additions & 3 deletions bevy_rapier3d/examples/ray_casting3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ pub fn setup_physics(mut commands: Commands) {
pub fn cast_ray(
mut commands: Commands,
windows: Query<&Window, With<PrimaryWindow>>,
rapier_context: ReadDefaultRapierContext,
rapier_context: ReadRapierContext,
cameras: Query<(&Camera, &GlobalTransform)>,
) {
let window = windows.single();
Expand All @@ -90,9 +90,9 @@ pub fn cast_ray(
let Ok(ray) = camera.viewport_to_world(camera_transform, cursor_position) else {
return;
};

let context = rapier_context.single();
// Then cast the ray.
let hit = rapier_context.cast_ray(
let hit = context.cast_ray(
ray.origin,
ray.direction.into(),
f32::MAX,
Expand Down
4 changes: 2 additions & 2 deletions bevy_rapier_benches3d/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use common::default_app;
use common::wait_app_start;

use bevy::prelude::*;
use bevy_rapier3d::plugin::RapierContext;
use bevy_rapier3d::plugin::context::RapierContextSimulation;

pub fn custom_bencher(steps: usize, setup: impl Fn(&mut App)) {
let mut app = default_app();
Expand All @@ -28,7 +28,7 @@ pub fn custom_bencher(steps: usize, setup: impl Fn(&mut App)) {
let elapsed_time = timer_full_update.time() as f32;
let rc = app
.world_mut()
.query::<&RapierContext>()
.query::<&RapierContextSimulation>()
.single(app.world());
rapier_step_times.push(rc.pipeline.counters.step_time.time() as f32);
total_update_times.push(elapsed_time);
Expand Down
6 changes: 3 additions & 3 deletions src/control/character_controller.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use crate::geometry::{Collider, CollisionGroups, ShapeCastHit};
use crate::math::{Real, Rot, Vect};
use bevy::prelude::*;

use crate::plugin::RapierContext;
use crate::plugin::context::RapierContextColliders;
pub use rapier::control::CharacterAutostep;
pub use rapier::control::CharacterLength;
use rapier::prelude::{ColliderSet, QueryFilterFlags};
Expand All @@ -26,7 +26,7 @@ pub struct CharacterCollision {

impl CharacterCollision {
pub(crate) fn from_raw(
ctxt: &RapierContext,
ctxt: &RapierContextColliders,
c: &rapier::control::CharacterCollision,
) -> Option<Self> {
Self::from_raw_with_set(&ctxt.colliders, c, true)
Expand All @@ -37,7 +37,7 @@ impl CharacterCollision {
c: &rapier::control::CharacterCollision,
details_always_computed: bool,
) -> Option<Self> {
RapierContext::collider_entity_with_set(colliders, c.handle).map(|entity| {
RapierContextColliders::collider_entity_with_set(colliders, c.handle).map(|entity| {
CharacterCollision {
entity,
character_translation: c.character_pos.translation.vector.into(),
Expand Down
17 changes: 10 additions & 7 deletions src/dynamics/revolute_joint.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
use crate::dynamics::{GenericJoint, GenericJointBuilder};
use crate::math::{Real, Vect};
use crate::plugin::RapierContext;
use crate::plugin::context::RapierRigidBodySet;
use bevy::prelude::Entity;
use rapier::dynamics::{
JointAxesMask, JointAxis, JointLimits, JointMotor, MotorModel, RigidBodyHandle, RigidBodySet,
};

#[cfg(doc)]
use crate::prelude::RapierContext;

use super::TypedJoint;

#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]
Expand Down Expand Up @@ -147,7 +150,7 @@ impl RevoluteJoint {
/// Similarly [`RapierContext::impulse_revolute_joint_angle`] only takes a single entity as argument to compute that angle.
///
/// # Parameters
/// - `bodies` : the rigid body set from [`RapierContext`]
/// - `bodies` : the rigid body set from [`RapierRigidBodySet`]
/// - `body1`: the first rigid-body attached to this revolute joint, obtained through [`rapier::dynamics::ImpulseJoint`] or [`rapier::dynamics::MultibodyJoint`].
/// - `body2`: the second rigid-body attached to this revolute joint, obtained through [`rapier::dynamics::ImpulseJoint`] or [`rapier::dynamics::MultibodyJoint`].
pub fn angle_from_handles(
Expand All @@ -167,13 +170,13 @@ impl RevoluteJoint {
/// The angle along the free degree of freedom of this revolute joint in `[-π, π]`.
///
/// # Parameters
/// - `bodies` : the rigid body set from [`RapierContext`]
/// - `bodies` : the rigid body set from [`RapierRigidBodySet`]
/// - `body1`: the first rigid-body attached to this revolute joint.
/// - `body2`: the second rigid-body attached to this revolute joint.
pub fn angle(&self, context: &RapierContext, body1: Entity, body2: Entity) -> f32 {
let rb1 = context.entity2body().get(&body1).unwrap();
let rb2 = context.entity2body().get(&body2).unwrap();
self.angle_from_handles(&context.bodies, *rb1, *rb2)
pub fn angle(&self, rigidbody_set: &RapierRigidBodySet, body1: Entity, body2: Entity) -> f32 {
let rb1 = rigidbody_set.entity2body().get(&body1).unwrap();
let rb2 = rigidbody_set.entity2body().get(&body2).unwrap();
self.angle_from_handles(&rigidbody_set.bodies, *rb1, *rb2)
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/geometry/shape_views/ball.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ pub struct BallViewMut<'a> {

impl_ref_methods!(BallViewMut);

impl<'a> BallViewMut<'a> {
impl BallViewMut<'_> {
/// Set the radius of the ball.
pub fn set_radius(&mut self, radius: Real) {
self.raw.radius = radius;
Expand Down
2 changes: 1 addition & 1 deletion src/geometry/shape_views/capsule.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ pub struct CapsuleViewMut<'a> {

impl_ref_methods!(CapsuleViewMut);

impl<'a> CapsuleViewMut<'a> {
impl CapsuleViewMut<'_> {
/// Set the segment of this capsule.
pub fn set_segment(&mut self, start: Vect, end: Vect) {
self.raw.segment.a = start.into();
Expand Down
2 changes: 1 addition & 1 deletion src/geometry/shape_views/collider_view.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ pub enum ColliderView<'a> {
#[cfg(feature = "dim2")]
RoundConvexPolygon(RoundConvexPolygonView<'a>),
}
impl<'a> fmt::Debug for ColliderView<'a> {
impl fmt::Debug for ColliderView<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ColliderView::Ball(view) => write!(f, "{:?}", view.raw),
Expand Down
2 changes: 1 addition & 1 deletion src/geometry/shape_views/compound.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ pub struct CompoundView<'a> {
pub raw: &'a Compound,
}

impl<'a> CompoundView<'a> {
impl CompoundView<'_> {
/// The shapes of this compound shape.
#[inline]
pub fn shapes(&self) -> impl ExactSizeIterator<Item = (Vect, Rot, ColliderView)> {
Expand Down
2 changes: 1 addition & 1 deletion src/geometry/shape_views/cone.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ pub struct ConeViewMut<'a> {

impl_ref_methods!(ConeViewMut);

impl<'a> ConeViewMut<'a> {
impl ConeViewMut<'_> {
/// Set the half-height of the cone.
pub fn set_half_height(&mut self, half_height: Real) {
self.raw.half_height = half_height;
Expand Down
4 changes: 2 additions & 2 deletions src/geometry/shape_views/convex_polygon.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ pub struct ConvexPolygonView<'a> {
pub raw: &'a ConvexPolygon,
}

impl<'a> ConvexPolygonView<'a> {
impl ConvexPolygonView<'_> {
/// The vertices of this convex polygon.
pub fn points(&self) -> impl ExactSizeIterator<Item = Vect> + '_ {
self.raw.points().iter().map(|pt| (*pt).into())
Expand All @@ -26,7 +26,7 @@ pub struct ConvexPolygonViewMut<'a> {
pub raw: &'a mut ConvexPolygon,
}

impl<'a> ConvexPolygonViewMut<'a> {
impl ConvexPolygonViewMut<'_> {
/// The vertices of this convex polygon.
pub fn points(&self) -> impl ExactSizeIterator<Item = Vect> + '_ {
self.raw.points().iter().map(|pt| (*pt).into())
Expand Down
4 changes: 2 additions & 2 deletions src/geometry/shape_views/convex_polyhedron.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ pub struct ConvexPolyhedronView<'a> {
pub raw: &'a ConvexPolyhedron,
}

impl<'a> ConvexPolyhedronView<'a> {
impl ConvexPolyhedronView<'_> {
/// The vertices of this convex polygon.
pub fn points(&self) -> impl ExactSizeIterator<Item = Vect> + '_ {
self.raw.points().iter().map(|pt| (*pt).into())
Expand All @@ -23,7 +23,7 @@ pub struct ConvexPolyhedronViewMut<'a> {
pub raw: &'a mut ConvexPolyhedron,
}

impl<'a> ConvexPolyhedronViewMut<'a> {
impl ConvexPolyhedronViewMut<'_> {
/// The vertices of this convex polygon.
pub fn points(&self) -> impl ExactSizeIterator<Item = Vect> + '_ {
self.raw.points().iter().map(|pt| (*pt).into())
Expand Down
Loading

0 comments on commit ac4fb03

Please sign in to comment.