Merge branch 'master' into split_geom

# Conflicts:
#	examples2d/sensor2.rs
#	examples3d/sensor3.rs
#	src/dynamics/integration_parameters.rs
#	src/dynamics/solver/parallel_island_solver.rs
#	src/dynamics/solver/velocity_constraint.rs
#	src/dynamics/solver/velocity_ground_constraint.rs
#	src_testbed/nphysics_backend.rs
#	src_testbed/physx_backend.rs
#	src_testbed/testbed.rs
This commit is contained in:
Crozet Sébastien
2021-01-22 16:10:24 +01:00
24 changed files with 359 additions and 356 deletions

View File

@@ -3,7 +3,7 @@ name: Rapier CI bench
on: on:
push: push:
branches: [ master ] branches: [ master ]
pull_request: pull_request_target:
branches: [ master ] branches: [ master ]
workflow_dispatch: workflow_dispatch:
@@ -14,21 +14,23 @@ jobs:
BENCHBOT_AMQP_PASS: ${{ secrets.BENCHBOT_AMQP_PASS }} BENCHBOT_AMQP_PASS: ${{ secrets.BENCHBOT_AMQP_PASS }}
BENCHBOT_AMQP_VHOST: ${{ secrets.BENCHBOT_AMQP_VHOST }} BENCHBOT_AMQP_VHOST: ${{ secrets.BENCHBOT_AMQP_VHOST }}
BENCHBOT_AMQP_HOST: ${{ secrets.BENCHBOT_AMQP_HOST }} BENCHBOT_AMQP_HOST: ${{ secrets.BENCHBOT_AMQP_HOST }}
BENCHBOT_TARGET_REPO: ${{ github.repository }} BENCHBOT_TARGET_REPO: ${{ github.event.pull_request.head.repo.clone_url }}
BENCHBOT_TARGET_COMMIT: ${{ github.event.pull_request.head.sha }} BENCHBOT_TARGET_COMMIT: ${{ github.event.pull_request.head.sha }}
BENCHBOT_SHA: ${{ github.sha }} BENCHBOT_SHA: ${{ github.sha }}
BENCHBOT_HEAD_REF: ${{github.head_ref}} BENCHBOT_HEAD_REF: ${{ github.head_ref }}
BENCHBOT_OTHER_BACKENDS: false BENCHBOT_OTHER_BACKENDS: false
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Find commit SHA - name: Set env on master
if: github.ref == 'refs/heads/master' if: github.head_ref == ''
run: | run: |
echo "BENCHBOT_TARGET_COMMIT=$BENCHBOT_SHA" >> $GITHUB_ENV echo "BENCHBOT_TARGET_COMMIT=$BENCHBOT_SHA" >> $GITHUB_ENV
echo "BENCHBOT_TARGET_REPO=https://github.com/dimforge/rapier" >> $GITHUB_ENV
echo "BENCHBOT_HEAD_REF=master" >> $GITHUB_ENV
echo "BENCHBOT_OTHER_BACKENDS=true" >> $GITHUB_ENV echo "BENCHBOT_OTHER_BACKENDS=true" >> $GITHUB_ENV
- name: Send 3D bench message - name: Send 3D bench message
shell: bash shell: bash
run: curl -u $BENCHBOT_AMQP_USER:$BENCHBOT_AMQP_PASS run: curl -u $BENCHBOT_AMQP_USER:$BENCHBOT_AMQP_PASS
-i -H "content-type:application/json" -X POST -i -H "content-type:application/json" -X POST
https://$BENCHBOT_AMQP_HOST/api/exchanges/$BENCHBOT_AMQP_VHOST//publish https://$BENCHBOT_AMQP_HOST/api/exchanges/$BENCHBOT_AMQP_VHOST//publish
-d'{"properties":{},"routing_key":"benchmark","payload":"{ \"repository\":\"https://github.com/'$BENCHBOT_TARGET_REPO'\", \"branch\":\"'$GITHUB_REF'\", \"commit\":\"'$BENCHBOT_TARGET_COMMIT'\", \"other_backends\":'$BENCHBOT_OTHER_BACKENDS' }","payload_encoding":"string"}' -d'{"properties":{},"routing_key":"benchmark","payload":"{ \"repository\":\"'$BENCHBOT_TARGET_REPO'\", \"branch\":\"'$BENCHBOT_HEAD_REF'\", \"commit\":\"'$BENCHBOT_TARGET_COMMIT'\", \"other_backends\":'$BENCHBOT_OTHER_BACKENDS' }","payload_encoding":"string"}'

View File

@@ -10,7 +10,7 @@ pub fn init_world(testbed: &mut Testbed) {
let rad = 0.5; let rad = 0.5;
// Callback that will be executed on the main loop to handle proximities. // Callback that will be executed on the main loop to handle proximities.
testbed.add_callback(move |window, physics, _, graphics, _| { testbed.add_callback(move |mut window, mut graphics, physics, _, _| {
let rigid_body = RigidBodyBuilder::new_dynamic() let rigid_body = RigidBodyBuilder::new_dynamic()
.translation(0.0, 10.0) .translation(0.0, 10.0)
.build(); .build();
@@ -19,7 +19,10 @@ pub fn init_world(testbed: &mut Testbed) {
physics physics
.colliders .colliders
.insert(collider, handle, &mut physics.bodies); .insert(collider, handle, &mut physics.bodies);
graphics.add(window, handle, &physics.bodies, &physics.colliders);
if let (Some(graphics), Some(window)) = (&mut graphics, &mut window) {
graphics.add(*window, handle, &physics.bodies, &physics.colliders);
}
let to_remove: Vec<_> = physics let to_remove: Vec<_> = physics
.bodies .bodies
@@ -31,7 +34,10 @@ pub fn init_world(testbed: &mut Testbed) {
physics physics
.bodies .bodies
.remove(handle, &mut physics.colliders, &mut physics.joints); .remove(handle, &mut physics.colliders, &mut physics.joints);
graphics.remove_body_nodes(window, handle);
if let (Some(graphics), Some(window)) = (&mut graphics, &mut window) {
graphics.remove_body_nodes(*window, handle);
}
} }
}); });

View File

@@ -60,13 +60,13 @@ pub fn init_world(testbed: &mut Testbed) {
/* /*
* Setup a callback to control the platform. * Setup a callback to control the platform.
*/ */
testbed.add_callback(move |_, physics, _, _, time| { testbed.add_callback(move |_, _, physics, _, run_state| {
let platform = physics.bodies.get_mut(platform_handle).unwrap(); let platform = physics.bodies.get_mut(platform_handle).unwrap();
let mut next_pos = *platform.position(); let mut next_pos = *platform.position();
let dt = 0.016; let dt = 0.016;
next_pos.translation.vector.y += (time * 5.0).sin() * dt; next_pos.translation.vector.y += (run_state.time * 5.0).sin() * dt;
next_pos.translation.vector.x += time.sin() * 5.0 * dt; next_pos.translation.vector.x += run_state.time.sin() * 5.0 * dt;
if next_pos.translation.vector.x >= rad * 10.0 { if next_pos.translation.vector.x >= rad * 10.0 {
next_pos.translation.vector.x -= dt; next_pos.translation.vector.x -= dt;

View File

@@ -69,7 +69,7 @@ pub fn init_world(testbed: &mut Testbed) {
testbed.set_body_color(sensor_handle, Point3::new(0.5, 1.0, 1.0)); testbed.set_body_color(sensor_handle, Point3::new(0.5, 1.0, 1.0));
// Callback that will be executed on the main loop to handle proximities. // Callback that will be executed on the main loop to handle proximities.
testbed.add_callback(move |_, physics, events, graphics, _| { testbed.add_callback(move |_, mut graphics, physics, events, _| {
while let Ok(prox) = events.intersection_events.try_recv() { while let Ok(prox) = events.intersection_events.try_recv() {
let color = if prox.intersecting { let color = if prox.intersecting {
Point3::new(1.0, 1.0, 0.0) Point3::new(1.0, 1.0, 0.0)
@@ -79,12 +79,13 @@ pub fn init_world(testbed: &mut Testbed) {
let parent_handle1 = physics.colliders.get(prox.collider1).unwrap().parent(); let parent_handle1 = physics.colliders.get(prox.collider1).unwrap().parent();
let parent_handle2 = physics.colliders.get(prox.collider2).unwrap().parent(); let parent_handle2 = physics.colliders.get(prox.collider2).unwrap().parent();
if let Some(graphics) = &mut graphics {
if parent_handle1 != ground_handle && parent_handle1 != sensor_handle { if parent_handle1 != ground_handle && parent_handle1 != sensor_handle {
graphics.set_body_color(parent_handle1, color); graphics.set_body_color(parent_handle1, color);
} }
if parent_handle2 != ground_handle && parent_handle2 != sensor_handle { if parent_handle2 != ground_handle && parent_handle2 != sensor_handle {
graphics.set_body_color(parent_handle2, color); graphics.set_body_color(parent_handle2, color);
}
} }
} }
}); });

View File

@@ -34,7 +34,7 @@ pub fn init_world(testbed: &mut Testbed) {
let collider = ColliderBuilder::ball(ball_rad).density(100.0).build(); let collider = ColliderBuilder::ball(ball_rad).density(100.0).build();
colliders.insert(collider, ball_handle, &mut bodies); colliders.insert(collider, ball_handle, &mut bodies);
testbed.add_callback(move |window, physics, _, graphics, _| { testbed.add_callback(move |mut window, mut graphics, physics, _, _| {
// Remove then re-add the ground collider. // Remove then re-add the ground collider.
let coll = physics let coll = physics
.colliders .colliders
@@ -43,7 +43,10 @@ pub fn init_world(testbed: &mut Testbed) {
ground_collider_handle = physics ground_collider_handle = physics
.colliders .colliders
.insert(coll, ground_handle, &mut physics.bodies); .insert(coll, ground_handle, &mut physics.bodies);
graphics.add_collider(window, ground_collider_handle, &physics.colliders);
if let (Some(graphics), Some(window)) = (&mut graphics, &mut window) {
graphics.add_collider(window, ground_collider_handle, &physics.colliders);
}
}); });
/* /*

View File

@@ -45,7 +45,7 @@ pub fn init_world(testbed: &mut Testbed) {
let mut extra_colliders = Vec::new(); let mut extra_colliders = Vec::new();
let snapped_frame = 51; let snapped_frame = 51;
testbed.add_callback(move |window, physics, _, graphics, _| { testbed.add_callback(move |mut window, mut graphics, physics, _, _| {
step += 1; step += 1;
// Add a bigger ball collider // Add a bigger ball collider
@@ -56,7 +56,11 @@ pub fn init_world(testbed: &mut Testbed) {
physics physics
.colliders .colliders
.insert(collider, ball_handle, &mut physics.bodies); .insert(collider, ball_handle, &mut physics.bodies);
graphics.add_collider(window, new_ball_collider_handle, &physics.colliders);
if let (Some(graphics), Some(window)) = (&mut graphics, &mut window) {
graphics.add_collider(window, new_ball_collider_handle, &physics.colliders);
}
extra_colliders.push(new_ball_collider_handle); extra_colliders.push(new_ball_collider_handle);
// Snap the ball velocity or restore it. // Snap the ball velocity or restore it.
@@ -95,7 +99,11 @@ pub fn init_world(testbed: &mut Testbed) {
physics physics
.colliders .colliders
.insert(coll, ground_handle, &mut physics.bodies); .insert(coll, ground_handle, &mut physics.bodies);
graphics.add_collider(window, new_ground_collider_handle, &physics.colliders);
if let (Some(graphics), Some(window)) = (&mut graphics, &mut window) {
graphics.add_collider(window, new_ground_collider_handle, &physics.colliders);
}
extra_colliders.push(new_ground_collider_handle); extra_colliders.push(new_ground_collider_handle);
}); });

View File

@@ -44,7 +44,7 @@ pub fn init_world(testbed: &mut Testbed) {
let mut step = 0; let mut step = 0;
let snapped_frame = 51; let snapped_frame = 51;
testbed.add_callback(move |_, physics, _, _, _| { testbed.add_callback(move |_, _, physics, _, _| {
step += 1; step += 1;
// Snap the ball velocity or restore it. // Snap the ball velocity or restore it.

View File

@@ -26,7 +26,7 @@ pub fn init_world(testbed: &mut Testbed) {
let mut k = 0; let mut k = 0;
// Callback that will be executed on the main loop to handle proximities. // Callback that will be executed on the main loop to handle proximities.
testbed.add_callback(move |window, physics, _, graphics, _| { testbed.add_callback(move |mut window, mut graphics, physics, _, _| {
k += 1; k += 1;
let rigid_body = RigidBodyBuilder::new_dynamic() let rigid_body = RigidBodyBuilder::new_dynamic()
.translation(0.0, 10.0, 0.0) .translation(0.0, 10.0, 0.0)
@@ -41,7 +41,10 @@ pub fn init_world(testbed: &mut Testbed) {
physics physics
.colliders .colliders
.insert(collider, handle, &mut physics.bodies); .insert(collider, handle, &mut physics.bodies);
graphics.add(window, handle, &physics.bodies, &physics.colliders);
if let (Some(graphics), Some(window)) = (&mut graphics, &mut window) {
graphics.add(window, handle, &physics.bodies, &physics.colliders);
}
if physics.bodies.len() > MAX_NUMBER_OF_BODIES { if physics.bodies.len() > MAX_NUMBER_OF_BODIES {
let mut to_remove: Vec<_> = physics let mut to_remove: Vec<_> = physics
@@ -67,7 +70,10 @@ pub fn init_world(testbed: &mut Testbed) {
physics physics
.narrow_phase .narrow_phase
.maintain(&mut physics.colliders, &mut physics.bodies); .maintain(&mut physics.colliders, &mut physics.bodies);
graphics.remove_body_nodes(window, *handle);
if let (Some(graphics), Some(window)) = (&mut graphics, &mut window) {
graphics.remove_body_nodes(window, *handle);
}
} }
} }
}); });

View File

@@ -65,7 +65,7 @@ pub fn init_world(testbed: &mut Testbed) {
* Setup a callback to control the platform. * Setup a callback to control the platform.
*/ */
let mut count = 0; let mut count = 0;
testbed.add_callback(move |_, physics, _, _, time| { testbed.add_callback(move |_, _, physics, _, run_state| {
count += 1; count += 1;
if count % 100 > 50 { if count % 100 > 50 {
return; return;
@@ -75,8 +75,8 @@ pub fn init_world(testbed: &mut Testbed) {
let mut next_pos = *platform.position(); let mut next_pos = *platform.position();
let dt = 0.016; let dt = 0.016;
next_pos.translation.vector.y += (time * 5.0).sin() * dt; next_pos.translation.vector.y += (run_state.time * 5.0).sin() * dt;
next_pos.translation.vector.z += time.sin() * 5.0 * dt; next_pos.translation.vector.z += run_state.time.sin() * 5.0 * dt;
if next_pos.translation.vector.z >= rad * 10.0 { if next_pos.translation.vector.z >= rad * 10.0 {
next_pos.translation.vector.z -= dt; next_pos.translation.vector.z -= dt;

View File

@@ -73,7 +73,7 @@ pub fn init_world(testbed: &mut Testbed) {
testbed.set_body_color(sensor_handle, Point3::new(0.5, 1.0, 1.0)); testbed.set_body_color(sensor_handle, Point3::new(0.5, 1.0, 1.0));
// Callback that will be executed on the main loop to handle proximities. // Callback that will be executed on the main loop to handle proximities.
testbed.add_callback(move |_, physics, events, graphics, _| { testbed.add_callback(move |_, mut graphics, physics, events, _| {
while let Ok(prox) = events.intersection_events.try_recv() { while let Ok(prox) = events.intersection_events.try_recv() {
let color = if prox.intersecting { let color = if prox.intersecting {
Point3::new(1.0, 1.0, 0.0) Point3::new(1.0, 1.0, 0.0)
@@ -84,11 +84,13 @@ pub fn init_world(testbed: &mut Testbed) {
let parent_handle1 = physics.colliders.get(prox.collider1).unwrap().parent(); let parent_handle1 = physics.colliders.get(prox.collider1).unwrap().parent();
let parent_handle2 = physics.colliders.get(prox.collider2).unwrap().parent(); let parent_handle2 = physics.colliders.get(prox.collider2).unwrap().parent();
if parent_handle1 != ground_handle && parent_handle1 != sensor_handle { if let Some(graphics) = &mut graphics {
graphics.set_body_color(parent_handle1, color); if parent_handle1 != ground_handle && parent_handle1 != sensor_handle {
} graphics.set_body_color(parent_handle1, color);
if parent_handle2 != ground_handle && parent_handle2 != sensor_handle { }
graphics.set_body_color(parent_handle2, color); if parent_handle2 != ground_handle && parent_handle2 != sensor_handle {
graphics.set_body_color(parent_handle2, color);
}
} }
} }
}); });

View File

@@ -5,9 +5,8 @@ use crate::math::Real;
#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))] #[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]
pub struct IntegrationParameters { pub struct IntegrationParameters {
/// The timestep length (default: `1.0 / 60.0`) /// The timestep length (default: `1.0 / 60.0`)
dt: Real, pub dt: Real,
/// The inverse of `dt`.
inv_dt: Real,
// /// If `true` and if rapier is compiled with the `parallel` feature, this will enable rayon-based multithreading (default: `true`). // /// If `true` and if rapier is compiled with the `parallel` feature, this will enable rayon-based multithreading (default: `true`).
// /// // ///
// /// This parameter is ignored if rapier is not compiled with is `parallel` feature. // /// This parameter is ignored if rapier is not compiled with is `parallel` feature.
@@ -31,7 +30,7 @@ pub struct IntegrationParameters {
/// Contacts at points where the involved bodies have a relative /// Contacts at points where the involved bodies have a relative
/// velocity smaller than this threshold wont be affected by the restitution force (default: `1.0`). /// velocity smaller than this threshold wont be affected by the restitution force (default: `1.0`).
pub restitution_velocity_threshold: Real, pub restitution_velocity_threshold: Real,
/// Amount of penetration the engine wont attempt to correct (default: `0.001m`). /// Amount of penetration the engine wont attempt to correct (default: `0.005m`).
pub allowed_linear_error: Real, pub allowed_linear_error: Real,
/// The maximal distance separating two objects that will generate predictive contacts (default: `0.002`). /// The maximal distance separating two objects that will generate predictive contacts (default: `0.002`).
pub prediction_distance: Real, pub prediction_distance: Real,
@@ -89,6 +88,7 @@ pub struct IntegrationParameters {
impl IntegrationParameters { impl IntegrationParameters {
/// Creates a set of integration parameters with the given values. /// Creates a set of integration parameters with the given values.
#[deprecated = "Use `IntegrationParameters { dt: 60.0, ..Default::default() }` instead"]
pub fn new( pub fn new(
dt: Real, dt: Real,
// multithreading_enabled: bool, // multithreading_enabled: bool,
@@ -112,7 +112,6 @@ impl IntegrationParameters {
) -> Self { ) -> Self {
IntegrationParameters { IntegrationParameters {
dt, dt,
inv_dt: if dt == 0.0 { 0.0 } else { 1.0 / dt },
// multithreading_enabled, // multithreading_enabled,
erp, erp,
joint_erp, joint_erp,
@@ -142,30 +141,29 @@ impl IntegrationParameters {
/// The current time-stepping length. /// The current time-stepping length.
#[inline(always)] #[inline(always)]
#[deprecated = "You can just read the `IntegrationParams::dt` value directly"]
pub fn dt(&self) -> Real { pub fn dt(&self) -> Real {
self.dt self.dt
} }
/// The inverse of the time-stepping length. /// The inverse of the time-stepping length, i.e. the steps per seconds (Hz).
/// ///
/// This is zero if `self.dt` is zero. /// This is zero if `self.dt` is zero.
#[inline(always)] #[inline(always)]
pub fn inv_dt(&self) -> Real { pub fn inv_dt(&self) -> Real {
self.inv_dt if self.dt == 0.0 {
0.0
} else {
1.0 / self.dt
}
} }
/// Sets the time-stepping length. /// Sets the time-stepping length.
///
/// This automatically recompute `self.inv_dt`.
#[inline] #[inline]
#[deprecated = "You can just set the `IntegrationParams::dt` value directly"]
pub fn set_dt(&mut self, dt: Real) { pub fn set_dt(&mut self, dt: Real) {
assert!(dt >= 0.0, "The time-stepping length cannot be negative."); assert!(dt >= 0.0, "The time-stepping length cannot be negative.");
self.dt = dt; self.dt = dt;
if dt == 0.0 {
self.inv_dt = 0.0
} else {
self.inv_dt = 1.0 / dt
}
} }
/// Sets the inverse time-stepping length (i.e. the frequency). /// Sets the inverse time-stepping length (i.e. the frequency).
@@ -173,7 +171,6 @@ impl IntegrationParameters {
/// This automatically recompute `self.dt`. /// This automatically recompute `self.dt`.
#[inline] #[inline]
pub fn set_inv_dt(&mut self, inv_dt: Real) { pub fn set_inv_dt(&mut self, inv_dt: Real) {
self.inv_dt = inv_dt;
if inv_dt == 0.0 { if inv_dt == 0.0 {
self.dt = 0.0 self.dt = 0.0
} else { } else {
@@ -184,26 +181,32 @@ impl IntegrationParameters {
impl Default for IntegrationParameters { impl Default for IntegrationParameters {
fn default() -> Self { fn default() -> Self {
Self::new( Self {
1.0 / 60.0, dt: 1.0 / 60.0,
// true, // multithreading_enabled: true,
0.2, return_after_ccd_substep: false,
0.2, erp: 0.2,
1.0, joint_erp: 0.2,
1.0, warmstart_coeff: 1.0,
0.005, restitution_velocity_threshold: 1.0,
0.001, allowed_linear_error: 0.005,
0.2, prediction_distance: 0.002,
0.2, allowed_angular_error: 0.001,
0.002, max_linear_correction: 0.2,
0.2, max_angular_correction: 0.2,
4, max_stabilization_multiplier: 0.2,
1, max_velocity_iterations: 4,
10, max_position_iterations: 1,
1, // FIXME: what is the optimal value for min_island_size?
false, // It should not be too big so that we don't end up with
false, // huge islands that don't fit in cache.
false, // However we don't want it to be too small and end up with
) // tons of islands, reducing SIMD parallelism opportunities.
min_island_size: 128,
max_ccd_position_iterations: 10,
max_ccd_substeps: 1,
multiple_ccd_substep_sensor_events_enabled: false,
ccd_on_penetration_enabled: false,
}
} }
} }

View File

@@ -57,8 +57,7 @@ impl IslandSolver {
} }
counters.solver.velocity_update_time.resume(); counters.solver.velocity_update_time.resume();
bodies bodies.foreach_active_island_body_mut_internal(island_id, |_, rb| rb.integrate(params.dt));
.foreach_active_island_body_mut_internal(island_id, |_, rb| rb.integrate(params.dt()));
counters.solver.velocity_update_time.pause(); counters.solver.velocity_update_time.pause();
if manifold_indices.len() != 0 || joint_indices.len() != 0 { if manifold_indices.len() != 0 || joint_indices.len() != 0 {

View File

@@ -251,7 +251,7 @@ impl ParallelIslandSolver {
let dvel = mj_lambdas[rb.active_set_offset]; let dvel = mj_lambdas[rb.active_set_offset];
rb.linvel += dvel.linear; rb.linvel += dvel.linear;
rb.angvel += rb.effective_world_inv_inertia_sqrt.transform_vector(dvel.angular); rb.angvel += rb.effective_world_inv_inertia_sqrt.transform_vector(dvel.angular);
rb.integrate(params.dt()); rb.integrate(params.dt));
positions[rb.active_set_offset] = rb.position; positions[rb.active_set_offset] = rb.position;
} }
} }

View File

@@ -144,6 +144,7 @@ impl VelocityConstraint {
out_constraints: &mut Vec<AnyVelocityConstraint>, out_constraints: &mut Vec<AnyVelocityConstraint>,
push: bool, push: bool,
) { ) {
let inv_dt = params.inv_dt();
let rb1 = &bodies[manifold.data.body_pair.body1]; let rb1 = &bodies[manifold.data.body_pair.body1];
let rb2 = &bodies[manifold.data.body_pair.body2]; let rb2 = &bodies[manifold.data.body_pair.body2];
let mj_lambda1 = rb1.active_set_offset; let mj_lambda1 = rb1.active_set_offset;
@@ -244,7 +245,7 @@ impl VelocityConstraint {
rhs += manifold_point.restitution * rhs rhs += manifold_point.restitution * rhs
} }
rhs += manifold_point.dist.max(0.0) * params.inv_dt(); rhs += manifold_point.dist.max(0.0) * inv_dt;
let impulse = manifold_point.data.impulse * warmstart_coeff; let impulse = manifold_point.data.impulse * warmstart_coeff;

View File

@@ -63,6 +63,7 @@ impl VelocityGroundConstraint {
out_constraints: &mut Vec<AnyVelocityConstraint>, out_constraints: &mut Vec<AnyVelocityConstraint>,
push: bool, push: bool,
) { ) {
let inv_dt = params.inv_dt();
let mut rb1 = &bodies[manifold.data.body_pair.body1]; let mut rb1 = &bodies[manifold.data.body_pair.body1];
let mut rb2 = &bodies[manifold.data.body_pair.body2]; let mut rb2 = &bodies[manifold.data.body_pair.body2];
let flipped = !rb2.is_dynamic(); let flipped = !rb2.is_dynamic();
@@ -159,7 +160,7 @@ impl VelocityGroundConstraint {
rhs += manifold_point.restitution * rhs rhs += manifold_point.restitution * rhs
} }
rhs += manifold_point.dist.max(0.0) * params.inv_dt(); rhs += manifold_point.dist.max(0.0) * inv_dt;
let impulse = manifold_points[k].data.impulse * warmstart_coeff; let impulse = manifold_points[k].data.impulse * warmstart_coeff;

View File

@@ -154,7 +154,7 @@ impl PhysicsPipeline {
self.counters.stages.update_time.start(); self.counters.stages.update_time.start();
bodies.foreach_active_dynamic_body_mut_internal(|_, b| { bodies.foreach_active_dynamic_body_mut_internal(|_, b| {
b.update_world_mass_properties(); b.update_world_mass_properties();
b.integrate_accelerations(integration_parameters.dt(), *gravity) b.integrate_accelerations(integration_parameters.dt, *gravity)
}); });
self.counters.stages.update_time.pause(); self.counters.stages.update_time.pause();
@@ -233,7 +233,7 @@ impl PhysicsPipeline {
rb.linvel = na::zero(); rb.linvel = na::zero();
rb.angvel = na::zero(); rb.angvel = na::zero();
} else { } else {
rb.update_predicted_position(integration_parameters.dt()); rb.update_predicted_position(integration_parameters.dt);
} }
rb.update_colliders_positions(colliders); rb.update_colliders_positions(colliders);
@@ -330,6 +330,7 @@ mod test {
); );
} }
#[cfg(feature = "serde")]
#[test] #[test]
fn rigid_body_removal_snapshot_handle_determinism() { fn rigid_body_removal_snapshot_handle_determinism() {
let mut colliders = ColliderSet::new(); let mut colliders = ColliderSet::new();

View File

@@ -219,7 +219,7 @@ impl Box2dWorld {
counters.step_started(); counters.step_started();
self.world.step( self.world.step(
params.dt(), params.dt,
params.max_velocity_iterations as i32, params.max_velocity_iterations as i32,
params.max_position_iterations as i32, params.max_position_iterations as i32,
); );

View File

@@ -1,4 +1,8 @@
use crate::physics::{PhysicsEvents, PhysicsState}; use crate::{
physics::{PhysicsEvents, PhysicsState},
GraphicsManager,
};
use kiss3d::window::Window;
use plugin::HarnessPlugin; use plugin::HarnessPlugin;
use rapier::dynamics::{IntegrationParameters, JointSet, RigidBodySet}; use rapier::dynamics::{IntegrationParameters, JointSet, RigidBodySet};
use rapier::geometry::{BroadPhase, ColliderSet, NarrowPhase}; use rapier::geometry::{BroadPhase, ColliderSet, NarrowPhase};
@@ -7,24 +11,58 @@ use rapier::pipeline::{ChannelEventCollector, PhysicsPipeline, QueryPipeline};
pub mod plugin; pub mod plugin;
pub struct HarnessState { pub struct RunState {
#[cfg(feature = "parallel")] #[cfg(feature = "parallel")]
pub thread_pool: rapier::rayon::ThreadPool, pub thread_pool: rapier::rayon::ThreadPool,
#[cfg(feature = "parallel")]
pub num_threads: usize,
pub timestep_id: usize, pub timestep_id: usize,
pub time: f32,
}
impl RunState {
pub fn new() -> Self {
#[cfg(feature = "parallel")]
let num_threads = num_cpus::get_physical();
#[cfg(feature = "parallel")]
let thread_pool = rapier::rayon::ThreadPoolBuilder::new()
.num_threads(num_threads)
.build()
.unwrap();
Self {
#[cfg(feature = "parallel")]
thread_pool: thread_pool,
#[cfg(feature = "parallel")]
num_threads,
timestep_id: 0,
time: 0.0,
}
}
} }
pub struct Harness { pub struct Harness {
physics: PhysicsState, pub physics: PhysicsState,
max_steps: usize, max_steps: usize,
callbacks: Callbacks, callbacks: Callbacks,
plugins: Vec<Box<dyn HarnessPlugin>>, plugins: Vec<Box<dyn HarnessPlugin>>,
time: f32,
events: PhysicsEvents, events: PhysicsEvents,
event_handler: ChannelEventCollector, event_handler: ChannelEventCollector,
pub state: HarnessState, pub state: RunState,
} }
type Callbacks = Vec<Box<dyn FnMut(&mut PhysicsState, &PhysicsEvents, &HarnessState, f32)>>; type Callbacks = Vec<
Box<
dyn FnMut(
Option<&mut Window>,
Option<&mut GraphicsManager>,
&mut PhysicsState,
&PhysicsEvents,
&RunState,
),
>,
>;
#[allow(dead_code)] #[allow(dead_code)]
impl Harness { impl Harness {
@@ -46,18 +84,13 @@ impl Harness {
intersection_events: proximity_channel.1, intersection_events: proximity_channel.1,
}; };
let physics = PhysicsState::new(); let physics = PhysicsState::new();
let state = HarnessState { let state = RunState::new();
#[cfg(feature = "parallel")]
thread_pool,
timestep_id: 0,
};
Self { Self {
physics, physics,
max_steps: 1000, max_steps: 1000,
callbacks: Vec::new(), callbacks: Vec::new(),
plugins: Vec::new(), plugins: Vec::new(),
time: 0.0,
events, events,
event_handler, event_handler,
state, state,
@@ -101,7 +134,6 @@ impl Harness {
self.physics.joints = joints; self.physics.joints = joints;
self.physics.broad_phase = BroadPhase::new(); self.physics.broad_phase = BroadPhase::new();
self.physics.narrow_phase = NarrowPhase::new(); self.physics.narrow_phase = NarrowPhase::new();
self.time = 0.0;
self.state.timestep_id = 0; self.state.timestep_id = 0;
self.physics.query_pipeline = QueryPipeline::new(); self.physics.query_pipeline = QueryPipeline::new();
self.physics.pipeline = PhysicsPipeline::new(); self.physics.pipeline = PhysicsPipeline::new();
@@ -113,7 +145,13 @@ impl Harness {
} }
pub fn add_callback< pub fn add_callback<
F: FnMut(&mut PhysicsState, &PhysicsEvents, &HarnessState, f32) + 'static, F: FnMut(
Option<&mut Window>,
Option<&mut GraphicsManager>,
&mut PhysicsState,
&PhysicsEvents,
&RunState,
) + 'static,
>( >(
&mut self, &mut self,
callback: F, callback: F,
@@ -122,6 +160,14 @@ impl Harness {
} }
pub fn step(&mut self) { pub fn step(&mut self) {
self.step_with_graphics(None, None);
}
pub fn step_with_graphics(
&mut self,
window: Option<&mut Window>,
graphics: Option<&mut GraphicsManager>,
) {
#[cfg(feature = "parallel")] #[cfg(feature = "parallel")]
{ {
let physics = &mut self.physics; let physics = &mut self.physics;
@@ -161,26 +207,44 @@ impl Harness {
.update(&self.physics.bodies, &self.physics.colliders); .update(&self.physics.bodies, &self.physics.colliders);
for plugin in &mut self.plugins { for plugin in &mut self.plugins {
plugin.step(&mut self.physics) plugin.step(&mut self.physics, &self.state)
} }
for f in &mut self.callbacks { // FIXME: This assumes either window & graphics are Some, or they are all None
f(&mut self.physics, &self.events, &self.state, self.time) // this is required as we cannot pass Option<&mut Window> & Option<&mut GraphicsManager directly in a loop
// there must be a better way of doing this?
match (window, graphics) {
(Some(window), Some(graphics)) => {
for f in &mut self.callbacks {
f(
Some(window),
Some(graphics),
&mut self.physics,
&self.events,
&self.state,
);
}
}
_ => {
for f in &mut self.callbacks {
f(None, None, &mut self.physics, &self.events, &self.state);
}
}
} }
for plugin in &mut self.plugins { for plugin in &mut self.plugins {
plugin.run_callbacks(&mut self.physics, &self.events, &self.state, self.time) plugin.run_callbacks(&mut self.physics, &self.events, &self.state)
} }
self.events.poll_all(); self.events.poll_all();
self.time += self.physics.integration_parameters.dt(); self.state.time += self.physics.integration_parameters.dt;
self.state.timestep_id += 1;
} }
pub fn run(&mut self) { pub fn run(&mut self) {
for _ in 0..self.max_steps { for _ in 0..self.max_steps {
self.step(); self.step();
self.state.timestep_id += 1;
} }
} }
} }

View File

@@ -1,4 +1,4 @@
use crate::harness::HarnessState; use crate::harness::RunState;
use crate::physics::PhysicsEvents; use crate::physics::PhysicsEvents;
use crate::PhysicsState; use crate::PhysicsState;
@@ -7,9 +7,8 @@ pub trait HarnessPlugin {
&mut self, &mut self,
physics: &mut PhysicsState, physics: &mut PhysicsState,
events: &PhysicsEvents, events: &PhysicsEvents,
harness_state: &HarnessState, harness_state: &RunState,
t: f32,
); );
fn step(&mut self, physics: &mut PhysicsState); fn step(&mut self, physics: &mut PhysicsState, run_state: &RunState);
fn profiling_string(&self) -> String; fn profiling_string(&self) -> String;
} }

View File

@@ -145,7 +145,7 @@ impl NPhysicsWorld {
.max_velocity_iterations = params.max_velocity_iterations; .max_velocity_iterations = params.max_velocity_iterations;
self.mechanical_world self.mechanical_world
.integration_parameters .integration_parameters
.set_dt(params.dt()); .set_dt(params.dt);
self.mechanical_world.integration_parameters.warmstart_coeff = params.warmstart_coeff; self.mechanical_world.integration_parameters.warmstart_coeff = params.warmstart_coeff;
counters.step_started(); counters.step_started();

View File

@@ -434,7 +434,7 @@ impl PhysxWorld {
.as_mut() .as_mut()
.unwrap() .unwrap()
.step( .step(
params.dt(), params.dt,
None::<&mut physx_sys::PxBaseTask>, None::<&mut physx_sys::PxBaseTask>,
Some(&mut scratch), Some(&mut scratch),
true, true,

View File

@@ -1,3 +1,4 @@
use crate::harness::RunState;
use crate::physics::PhysicsState; use crate::physics::PhysicsState;
use kiss3d::window::Window; use kiss3d::window::Window;
use na::Point3; use na::Point3;
@@ -5,7 +6,12 @@ use na::Point3;
pub trait TestbedPlugin { pub trait TestbedPlugin {
fn init_graphics(&mut self, window: &mut Window, gen_color: &mut dyn FnMut() -> Point3<f32>); fn init_graphics(&mut self, window: &mut Window, gen_color: &mut dyn FnMut() -> Point3<f32>);
fn clear_graphics(&mut self, window: &mut Window); fn clear_graphics(&mut self, window: &mut Window);
fn run_callbacks(&mut self, window: &mut Window, physics: &mut PhysicsState, t: f32); fn run_callbacks(
&mut self,
window: &mut Window,
physics: &mut PhysicsState,
run_state: &RunState,
);
fn step(&mut self, physics: &mut PhysicsState); fn step(&mut self, physics: &mut PhysicsState);
fn draw(&mut self); fn draw(&mut self);
fn profiling_string(&self) -> String; fn profiling_string(&self) -> String;

View File

@@ -3,10 +3,10 @@ use std::mem;
use std::path::Path; use std::path::Path;
use std::rc::Rc; use std::rc::Rc;
use crate::engine::GraphicsManager;
use crate::physics::{PhysicsEvents, PhysicsSnapshot, PhysicsState}; use crate::physics::{PhysicsEvents, PhysicsSnapshot, PhysicsState};
use crate::plugin::TestbedPlugin; use crate::plugin::TestbedPlugin;
use crate::ui::TestbedUi; use crate::ui::TestbedUi;
use crate::{engine::GraphicsManager, harness::RunState};
use kiss3d::camera::Camera; use kiss3d::camera::Camera;
use kiss3d::event::Event; use kiss3d::event::Event;
@@ -21,7 +21,7 @@ use na::{self, Point2, Point3, Vector3};
use rapier::dynamics::{ use rapier::dynamics::{
ActivationStatus, IntegrationParameters, JointSet, RigidBodyHandle, RigidBodySet, ActivationStatus, IntegrationParameters, JointSet, RigidBodyHandle, RigidBodySet,
}; };
use rapier::geometry::{BroadPhase, ColliderHandle, ColliderSet, NarrowPhase}; use rapier::geometry::{ColliderHandle, ColliderSet, NarrowPhase};
#[cfg(feature = "dim3")] #[cfg(feature = "dim3")]
use rapier::geometry::{InteractionGroups, Ray}; use rapier::geometry::{InteractionGroups, Ray};
use rapier::math::{Isometry, Vector}; use rapier::math::{Isometry, Vector};
@@ -29,6 +29,7 @@ use rapier::pipeline::{ChannelEventCollector, PhysicsPipeline, QueryPipeline};
#[cfg(all(feature = "dim2", feature = "other-backends"))] #[cfg(all(feature = "dim2", feature = "other-backends"))]
use crate::box2d_backend::Box2dWorld; use crate::box2d_backend::Box2dWorld;
use crate::harness::Harness;
#[cfg(feature = "other-backends")] #[cfg(feature = "other-backends")]
use crate::nphysics_backend::NPhysicsWorld; use crate::nphysics_backend::NPhysicsWorld;
#[cfg(all(feature = "dim3", feature = "other-backends"))] #[cfg(all(feature = "dim3", feature = "other-backends"))]
@@ -114,30 +115,22 @@ pub struct TestbedState {
pub selected_example: usize, pub selected_example: usize,
pub selected_backend: usize, pub selected_backend: usize,
pub physx_use_two_friction_directions: bool, pub physx_use_two_friction_directions: bool,
pub num_threads: usize,
pub snapshot: Option<PhysicsSnapshot>, pub snapshot: Option<PhysicsSnapshot>,
#[cfg(feature = "parallel")]
pub thread_pool: rapier::rayon::ThreadPool,
pub timestep_id: usize,
} }
pub struct Testbed { pub struct Testbed {
builders: Vec<(&'static str, fn(&mut Testbed))>, builders: Vec<(&'static str, fn(&mut Testbed))>,
physics: PhysicsState,
graphics: GraphicsManager, graphics: GraphicsManager,
nsteps: usize, nsteps: usize,
camera_locked: bool, // Used so that the camera can remain the same before and after we change backend or press the restart button. camera_locked: bool, // Used so that the camera can remain the same before and after we change backend or press the restart button.
callbacks: Callbacks,
plugins: Vec<Box<dyn TestbedPlugin>>, plugins: Vec<Box<dyn TestbedPlugin>>,
time: f32,
hide_counters: bool, hide_counters: bool,
// persistant_contacts: HashMap<ContactId, bool>, // persistant_contacts: HashMap<ContactId, bool>,
font: Rc<Font>, font: Rc<Font>,
cursor_pos: Point2<f32>, cursor_pos: Point2<f32>,
events: PhysicsEvents,
event_handler: ChannelEventCollector,
ui: Option<TestbedUi>, ui: Option<TestbedUi>,
state: TestbedState, state: TestbedState,
harness: Harness,
#[cfg(all(feature = "dim2", feature = "other-backends"))] #[cfg(all(feature = "dim2", feature = "other-backends"))]
box2d: Option<Box2dWorld>, box2d: Option<Box2dWorld>,
#[cfg(all(feature = "dim3", feature = "other-backends"))] #[cfg(all(feature = "dim3", feature = "other-backends"))]
@@ -146,9 +139,6 @@ pub struct Testbed {
nphysics: Option<NPhysicsWorld>, nphysics: Option<NPhysicsWorld>,
} }
type Callbacks =
Vec<Box<dyn FnMut(&mut Window, &mut PhysicsState, &PhysicsEvents, &mut GraphicsManager, f32)>>;
impl Testbed { impl Testbed {
pub fn new_empty() -> Testbed { pub fn new_empty() -> Testbed {
let graphics = GraphicsManager::new(); let graphics = GraphicsManager::new();
@@ -166,17 +156,6 @@ impl Testbed {
#[cfg(all(feature = "dim3", feature = "other-backends"))] #[cfg(all(feature = "dim3", feature = "other-backends"))]
backend_names.push("physx (two friction dir)"); backend_names.push("physx (two friction dir)");
#[cfg(feature = "parallel")]
let num_threads = num_cpus::get_physical();
#[cfg(not(feature = "parallel"))]
let num_threads = 1;
#[cfg(feature = "parallel")]
let thread_pool = rapier::rayon::ThreadPoolBuilder::new()
.num_threads(num_threads)
.build()
.unwrap();
let state = TestbedState { let state = TestbedState {
running: RunMode::Running, running: RunMode::Running,
draw_colls: false, draw_colls: false,
@@ -193,40 +172,25 @@ impl Testbed {
backend_names, backend_names,
example_names: Vec::new(), example_names: Vec::new(),
selected_example: 0, selected_example: 0,
timestep_id: 0,
selected_backend: RAPIER_BACKEND, selected_backend: RAPIER_BACKEND,
physx_use_two_friction_directions: true, physx_use_two_friction_directions: true,
num_threads,
#[cfg(feature = "parallel")]
thread_pool,
}; };
let contact_channel = crossbeam::channel::unbounded(); let harness = Harness::new_empty();
let intersection_channel = crossbeam::channel::unbounded();
let event_handler = ChannelEventCollector::new(intersection_channel.0, contact_channel.0);
let events = PhysicsEvents {
contact_events: contact_channel.1,
intersection_events: intersection_channel.1,
};
let physics = PhysicsState::new();
Testbed { Testbed {
builders: Vec::new(), builders: Vec::new(),
physics,
callbacks: Vec::new(),
plugins: Vec::new(), plugins: Vec::new(),
graphics, graphics,
nsteps: 1, nsteps: 1,
camera_locked: false, camera_locked: false,
time: 0.0,
hide_counters: true, hide_counters: true,
// persistant_contacts: HashMap::new(), // persistant_contacts: HashMap::new(),
font: Font::default(), font: Font::default(),
cursor_pos: Point2::new(0.0f32, 0.0), cursor_pos: Point2::new(0.0f32, 0.0),
ui, ui,
event_handler,
events,
state, state,
harness,
#[cfg(all(feature = "dim2", feature = "other-backends"))] #[cfg(all(feature = "dim2", feature = "other-backends"))]
box2d: None, box2d: None,
#[cfg(all(feature = "dim3", feature = "other-backends"))] #[cfg(all(feature = "dim3", feature = "other-backends"))]
@@ -238,7 +202,7 @@ impl Testbed {
pub fn new(bodies: RigidBodySet, colliders: ColliderSet, joints: JointSet) -> Self { pub fn new(bodies: RigidBodySet, colliders: ColliderSet, joints: JointSet) -> Self {
let mut res = Self::new_empty(); let mut res = Self::new_empty();
res.set_world(bodies, colliders, joints); res.harness.set_world(bodies, colliders, joints);
res res
} }
@@ -269,11 +233,15 @@ impl Testbed {
} }
pub fn integration_parameters_mut(&mut self) -> &mut IntegrationParameters { pub fn integration_parameters_mut(&mut self) -> &mut IntegrationParameters {
&mut self.physics.integration_parameters &mut self.harness.physics.integration_parameters
} }
pub fn physics_state_mut(&mut self) -> &mut PhysicsState { pub fn physics_state_mut(&mut self) -> &mut PhysicsState {
&mut self.physics &mut self.harness.physics
}
pub fn harness_mut(&mut self) -> &mut Harness {
&mut self.harness
} }
pub fn set_world(&mut self, bodies: RigidBodySet, colliders: ColliderSet, joints: JointSet) { pub fn set_world(&mut self, bodies: RigidBodySet, colliders: ColliderSet, joints: JointSet) {
@@ -289,30 +257,23 @@ impl Testbed {
) { ) {
println!("Num bodies: {}", bodies.len()); println!("Num bodies: {}", bodies.len());
println!("Num joints: {}", joints.len()); println!("Num joints: {}", joints.len());
self.physics.gravity = gravity; self.harness
self.physics.bodies = bodies; .set_world_with_gravity(bodies, colliders, joints, gravity);
self.physics.colliders = colliders;
self.physics.joints = joints;
self.physics.broad_phase = BroadPhase::new();
self.physics.narrow_phase = NarrowPhase::new();
self.state self.state
.action_flags .action_flags
.set(TestbedActionFlags::RESET_WORLD_GRAPHICS, true); .set(TestbedActionFlags::RESET_WORLD_GRAPHICS, true);
self.time = 0.0;
self.state.timestep_id = 0;
self.state.highlighted_body = None; self.state.highlighted_body = None;
self.physics.query_pipeline = QueryPipeline::new();
self.physics.pipeline = PhysicsPipeline::new();
self.physics.pipeline.counters.enable();
#[cfg(all(feature = "dim2", feature = "other-backends"))] #[cfg(all(feature = "dim2", feature = "other-backends"))]
{ {
if self.state.selected_backend == BOX2D_BACKEND { if self.state.selected_backend == BOX2D_BACKEND {
self.box2d = Some(Box2dWorld::from_rapier( self.box2d = Some(Box2dWorld::from_rapier(
self.physics.gravity, physics.gravity,
&self.physics.bodies, &physics.bodies,
&self.physics.colliders, &physics.colliders,
&self.physics.joints, &physics.joints,
)); ));
} }
} }
@@ -323,13 +284,13 @@ impl Testbed {
|| self.state.selected_backend == PHYSX_BACKEND_TWO_FRICTION_DIR || self.state.selected_backend == PHYSX_BACKEND_TWO_FRICTION_DIR
{ {
self.physx = Some(PhysxWorld::from_rapier( self.physx = Some(PhysxWorld::from_rapier(
self.physics.gravity, physics.gravity,
&self.physics.integration_parameters, &physics.integration_parameters,
&self.physics.bodies, &physics.bodies,
&self.physics.colliders, &physics.colliders,
&self.physics.joints, &physics.joints,
self.state.selected_backend == PHYSX_BACKEND_TWO_FRICTION_DIR, self.state.selected_backend == PHYSX_BACKEND_TWO_FRICTION_DIR,
self.state.num_threads, self.harness.state.num_threads,
)); ));
} }
} }
@@ -338,10 +299,10 @@ impl Testbed {
{ {
if self.state.selected_backend == NPHYSICS_BACKEND { if self.state.selected_backend == NPHYSICS_BACKEND {
self.nphysics = Some(NPhysicsWorld::from_rapier( self.nphysics = Some(NPhysicsWorld::from_rapier(
self.physics.gravity, physics.gravity,
&self.physics.bodies, &physics.bodies,
&self.physics.colliders, &physics.colliders,
&self.physics.joints, &physics.joints,
)); ));
} }
} }
@@ -419,7 +380,6 @@ impl Testbed {
} }
fn clear(&mut self, window: &mut Window) { fn clear(&mut self, window: &mut Window) {
self.callbacks.clear();
// self.persistant_contacts.clear(); // self.persistant_contacts.clear();
// self.state.grabbed_object = None; // self.state.grabbed_object = None;
// self.state.grabbed_object_constraint = None; // self.state.grabbed_object_constraint = None;
@@ -433,17 +393,23 @@ impl Testbed {
self.plugins.clear(); self.plugins.clear();
} }
pub fn add_plugin(&mut self, plugin: impl TestbedPlugin + 'static) {
self.plugins.push(Box::new(plugin));
}
pub fn add_callback< pub fn add_callback<
F: FnMut(&mut Window, &mut PhysicsState, &PhysicsEvents, &mut GraphicsManager, f32) + 'static, F: FnMut(
Option<&mut Window>,
Option<&mut GraphicsManager>,
&mut PhysicsState,
&PhysicsEvents,
&RunState,
) + 'static,
>( >(
&mut self, &mut self,
callback: F, callback: F,
) { ) {
self.callbacks.push(Box::new(callback)); self.harness.add_callback(callback);
}
pub fn add_plugin(&mut self, plugin: impl TestbedPlugin + 'static) {
self.plugins.push(Box::new(plugin));
} }
pub fn run(mut self) { pub fn run(mut self) {
@@ -464,6 +430,7 @@ impl Testbed {
} }
} }
// TODO: move this to dedicated benchmarking code
if benchmark_mode { if benchmark_mode {
use std::fs::File; use std::fs::File;
use std::io::{BufWriter, Write}; use std::io::{BufWriter, Write};
@@ -484,11 +451,23 @@ impl Testbed {
&& (backend_id == PHYSX_BACKEND_PATCH_FRICTION && (backend_id == PHYSX_BACKEND_PATCH_FRICTION
|| backend_id == PHYSX_BACKEND_TWO_FRICTION_DIR) || backend_id == PHYSX_BACKEND_TWO_FRICTION_DIR)
{ {
self.physics.integration_parameters.max_velocity_iterations = 1; self.harness
self.physics.integration_parameters.max_position_iterations = 4; .physics
.integration_parameters
.max_velocity_iterations = 1;
self.harness
.physics
.integration_parameters
.max_position_iterations = 4;
} else { } else {
self.physics.integration_parameters.max_velocity_iterations = 4; self.harness
self.physics.integration_parameters.max_position_iterations = 1; .physics
.integration_parameters
.max_velocity_iterations = 4;
self.harness
.physics
.integration_parameters
.max_position_iterations = 1;
} }
// Init world. // Init world.
(builder.1)(&mut self); (builder.1)(&mut self);
@@ -496,57 +475,20 @@ impl Testbed {
let mut timings = Vec::new(); let mut timings = Vec::new();
for k in 0..=NUM_ITERS { for k in 0..=NUM_ITERS {
{ {
// FIXME: code duplicated from self.step()
if self.state.selected_backend == RAPIER_BACKEND { if self.state.selected_backend == RAPIER_BACKEND {
#[cfg(feature = "parallel")] self.harness.step();
{
let physics = &mut self.physics;
let event_handler = &self.event_handler;
self.state.thread_pool.install(|| {
physics.pipeline.step(
&physics.gravity,
&physics.integration_parameters,
&mut physics.broad_phase,
&mut physics.narrow_phase,
&mut physics.bodies,
&mut physics.colliders,
&mut physics.joints,
None,
None,
event_handler,
);
});
}
#[cfg(not(feature = "parallel"))]
self.physics.pipeline.step(
&self.physics.gravity,
&self.physics.integration_parameters,
&mut self.physics.broad_phase,
&mut self.physics.narrow_phase,
&mut self.physics.bodies,
&mut self.physics.colliders,
&mut self.physics.joints,
None,
None,
&self.event_handler,
);
self.physics
.query_pipeline
.update(&self.physics.bodies, &self.physics.colliders);
} }
#[cfg(all(feature = "dim2", feature = "other-backends"))] #[cfg(all(feature = "dim2", feature = "other-backends"))]
{ {
if self.state.selected_backend == BOX2D_BACKEND { if self.state.selected_backend == BOX2D_BACKEND {
self.box2d.as_mut().unwrap().step( self.box2d.as_mut().unwrap().step(
&mut self.physics.pipeline.counters, &mut self.harness.physics.pipeline.counters,
&self.physics.integration_parameters, &physics.integration_parameters,
); );
self.box2d.as_mut().unwrap().sync( self.box2d.as_mut().unwrap().sync(
&mut self.physics.bodies, &mut self.harness.physics.bodies,
&mut self.physics.colliders, &mut self.harness.physics.colliders,
); );
} }
} }
@@ -558,12 +500,12 @@ impl Testbed {
{ {
// println!("Step"); // println!("Step");
self.physx.as_mut().unwrap().step( self.physx.as_mut().unwrap().step(
&mut self.physics.pipeline.counters, &mut self.harness.physics.pipeline.counters,
&self.physics.integration_parameters, &physics.integration_parameters,
); );
self.physx.as_mut().unwrap().sync( self.physx.as_mut().unwrap().sync(
&mut self.physics.bodies, &mut self.harness.physics.bodies,
&mut self.physics.colliders, &mut self.harness.physics.colliders,
); );
} }
} }
@@ -572,12 +514,12 @@ impl Testbed {
{ {
if self.state.selected_backend == NPHYSICS_BACKEND { if self.state.selected_backend == NPHYSICS_BACKEND {
self.nphysics.as_mut().unwrap().step( self.nphysics.as_mut().unwrap().step(
&mut self.physics.pipeline.counters, &mut self.harness.physics.pipeline.counters,
&self.physics.integration_parameters, &physics.integration_parameters,
); );
self.nphysics.as_mut().unwrap().sync( self.nphysics.as_mut().unwrap().sync(
&mut self.physics.bodies, &mut self.harness.physics.bodies,
&mut self.physics.colliders, &mut self.harness.physics.colliders,
); );
} }
} }
@@ -585,7 +527,7 @@ impl Testbed {
// Skip the first update. // Skip the first update.
if k > 0 { if k > 0 {
timings.push(self.physics.pipeline.counters.step_time.time()); timings.push(self.harness.physics.pipeline.counters.step_time.time());
} }
} }
results.push(timings); results.push(timings);
@@ -640,6 +582,7 @@ impl Testbed {
WindowEvent::Key(Key::C, Action::Release, _) => { WindowEvent::Key(Key::C, Action::Release, _) => {
// Delete 1 collider of 10% of the remaining dynamic bodies. // Delete 1 collider of 10% of the remaining dynamic bodies.
let mut colliders: Vec<_> = self let mut colliders: Vec<_> = self
.harness
.physics .physics
.bodies .bodies
.iter() .iter()
@@ -651,14 +594,17 @@ impl Testbed {
let num_to_delete = (colliders.len() / 10).max(1); let num_to_delete = (colliders.len() / 10).max(1);
for to_delete in &colliders[..num_to_delete] { for to_delete in &colliders[..num_to_delete] {
self.physics self.harness.physics.colliders.remove(
.colliders to_delete[0],
.remove(to_delete[0], &mut self.physics.bodies, true); &mut self.harness.physics.bodies,
true,
);
} }
} }
WindowEvent::Key(Key::D, Action::Release, _) => { WindowEvent::Key(Key::D, Action::Release, _) => {
// Delete 10% of the remaining dynamic bodies. // Delete 10% of the remaining dynamic bodies.
let dynamic_bodies: Vec<_> = self let dynamic_bodies: Vec<_> = self
.harness
.physics .physics
.bodies .bodies
.iter() .iter()
@@ -667,21 +613,23 @@ impl Testbed {
.collect(); .collect();
let num_to_delete = (dynamic_bodies.len() / 10).max(1); let num_to_delete = (dynamic_bodies.len() / 10).max(1);
for to_delete in &dynamic_bodies[..num_to_delete] { for to_delete in &dynamic_bodies[..num_to_delete] {
self.physics.bodies.remove( self.harness.physics.bodies.remove(
*to_delete, *to_delete,
&mut self.physics.colliders, &mut self.harness.physics.colliders,
&mut self.physics.joints, &mut self.harness.physics.joints,
); );
} }
} }
WindowEvent::Key(Key::J, Action::Release, _) => { WindowEvent::Key(Key::J, Action::Release, _) => {
// Delete 10% of the remaining joints. // Delete 10% of the remaining joints.
let joints: Vec<_> = self.physics.joints.iter().map(|e| e.0).collect(); let joints: Vec<_> = self.harness.physics.joints.iter().map(|e| e.0).collect();
let num_to_delete = (joints.len() / 10).max(1); let num_to_delete = (joints.len() / 10).max(1);
for to_delete in &joints[..num_to_delete] { for to_delete in &joints[..num_to_delete] {
self.physics self.harness.physics.joints.remove(
.joints *to_delete,
.remove(*to_delete, &mut self.physics.bodies, true); &mut self.harness.physics.bodies,
true,
);
} }
} }
WindowEvent::CursorPos(x, y, _) => { WindowEvent::CursorPos(x, y, _) => {
@@ -1028,8 +976,9 @@ impl Testbed {
.camera() .camera()
.unproject(&self.cursor_pos, &na::convert(size)); .unproject(&self.cursor_pos, &na::convert(size));
let ray = Ray::new(pos, dir); let ray = Ray::new(pos, dir);
let hit = self.physics.query_pipeline.cast_ray( let physics = &self.harness.physics;
&self.physics.colliders, let hit = physics.query_pipeline.cast_ray(
&physics.colliders,
&ray, &ray,
f32::MAX, f32::MAX,
true, true,
@@ -1038,7 +987,7 @@ impl Testbed {
if let Some((handle, _)) = hit { if let Some((handle, _)) = hit {
let collider = &self.physics.colliders[handle]; let collider = &self.physics.colliders[handle];
if self.physics.bodies[collider.parent()].is_dynamic() { if physics.bodies[collider.parent()].is_dynamic() {
self.state.highlighted_body = Some(collider.parent()); self.state.highlighted_body = Some(collider.parent());
for node in self.graphics.body_nodes_mut(collider.parent()).unwrap() { for node in self.graphics.body_nodes_mut(collider.parent()).unwrap() {
node.select() node.select()
@@ -1077,8 +1026,9 @@ impl State for Testbed {
if let Some(ui) = &mut self.ui { if let Some(ui) = &mut self.ui {
ui.update( ui.update(
window, window,
&mut self.physics.integration_parameters, &mut self.harness.physics.integration_parameters,
&mut self.state, &mut self.state,
&mut self.harness.state,
); );
} }
@@ -1125,16 +1075,7 @@ impl State for Testbed {
self.clear(window); self.clear(window);
if self.state.selected_example != prev_example { if self.state.selected_example != prev_example {
self.physics.integration_parameters = IntegrationParameters::default(); self.harness.physics.integration_parameters = IntegrationParameters::default();
if cfg!(feature = "dim3")
&& (self.state.selected_backend == PHYSX_BACKEND_PATCH_FRICTION
|| self.state.selected_backend == PHYSX_BACKEND_TWO_FRICTION_DIR)
{
std::mem::swap(
&mut self.physics.integration_parameters.max_velocity_iterations,
&mut self.physics.integration_parameters.max_position_iterations,
)
}
} }
self.builders[self.state.selected_example].1(self); self.builders[self.state.selected_example].1(self);
@@ -1151,12 +1092,12 @@ impl State for Testbed {
.action_flags .action_flags
.set(TestbedActionFlags::TAKE_SNAPSHOT, false); .set(TestbedActionFlags::TAKE_SNAPSHOT, false);
self.state.snapshot = PhysicsSnapshot::new( self.state.snapshot = PhysicsSnapshot::new(
self.state.timestep_id, self.harness.state.timestep_id,
&self.physics.broad_phase, &self.harness.physics.broad_phase,
&self.physics.narrow_phase, &self.harness.physics.narrow_phase,
&self.physics.bodies, &self.harness.physics.bodies,
&self.physics.colliders, &self.harness.physics.colliders,
&self.physics.joints, &self.harness.physics.joints,
) )
.ok(); .ok();
@@ -1183,9 +1124,9 @@ impl State for Testbed {
} }
self.set_world(w.3, w.4, w.5); self.set_world(w.3, w.4, w.5);
self.physics.broad_phase = w.1; self.harness.physics.broad_phase = w.1;
self.physics.narrow_phase = w.2; self.harness.physics.narrow_phase = w.2;
self.state.timestep_id = w.0; self.harness.state.timestep_id = w.0;
} }
} }
} }
@@ -1198,12 +1139,12 @@ impl State for Testbed {
self.state self.state
.action_flags .action_flags
.set(TestbedActionFlags::RESET_WORLD_GRAPHICS, false); .set(TestbedActionFlags::RESET_WORLD_GRAPHICS, false);
for (handle, _) in self.physics.bodies.iter() { for (handle, _) in self.harness.physics.bodies.iter() {
self.graphics.add( self.graphics.add(
window, window,
handle, handle,
&self.physics.bodies, &self.harness.physics.bodies,
&self.physics.colliders, &self.harness.physics.colliders,
); );
} }
@@ -1218,7 +1159,7 @@ impl State for Testbed {
!= self.state.flags.contains(TestbedStateFlags::WIREFRAME) != self.state.flags.contains(TestbedStateFlags::WIREFRAME)
{ {
self.graphics.toggle_wireframe_mode( self.graphics.toggle_wireframe_mode(
&self.physics.colliders, &self.harness.physics.colliders,
self.state.flags.contains(TestbedStateFlags::WIREFRAME), self.state.flags.contains(TestbedStateFlags::WIREFRAME),
) )
} }
@@ -1227,11 +1168,11 @@ impl State for Testbed {
!= self.state.flags.contains(TestbedStateFlags::SLEEP) != self.state.flags.contains(TestbedStateFlags::SLEEP)
{ {
if self.state.flags.contains(TestbedStateFlags::SLEEP) { if self.state.flags.contains(TestbedStateFlags::SLEEP) {
for (_, mut body) in self.physics.bodies.iter_mut() { for (_, mut body) in self.harness.physics.bodies.iter_mut() {
body.activation.threshold = ActivationStatus::default_threshold(); body.activation.threshold = ActivationStatus::default_threshold();
} }
} else { } else {
for (_, mut body) in self.physics.bodies.iter_mut() { for (_, mut body) in self.harness.physics.bodies.iter_mut() {
body.wake_up(true); body.wake_up(true);
body.activation.threshold = -1.0; body.activation.threshold = -1.0;
} }
@@ -1244,7 +1185,10 @@ impl State for Testbed {
.contains(TestbedStateFlags::SUB_STEPPING) .contains(TestbedStateFlags::SUB_STEPPING)
!= self.state.flags.contains(TestbedStateFlags::SUB_STEPPING) != self.state.flags.contains(TestbedStateFlags::SUB_STEPPING)
{ {
self.physics.integration_parameters.return_after_ccd_substep = self.harness
.physics
.integration_parameters
.return_after_ccd_substep =
self.state.flags.contains(TestbedStateFlags::SUB_STEPPING); self.state.flags.contains(TestbedStateFlags::SUB_STEPPING);
} }
@@ -1294,48 +1238,13 @@ impl State for Testbed {
if self.state.running != RunMode::Stop { if self.state.running != RunMode::Stop {
for _ in 0..self.nsteps { for _ in 0..self.nsteps {
self.state.timestep_id += 1;
if self.state.selected_backend == RAPIER_BACKEND { if self.state.selected_backend == RAPIER_BACKEND {
#[cfg(feature = "parallel")] let graphics = &mut self.graphics;
{ self.harness
let physics = &mut self.physics; .step_with_graphics(Some(window), Some(graphics));
let event_handler = &self.event_handler;
self.state.thread_pool.install(|| {
physics.pipeline.step(
&physics.gravity,
&physics.integration_parameters,
&mut physics.broad_phase,
&mut physics.narrow_phase,
&mut physics.bodies,
&mut physics.colliders,
&mut physics.joints,
None,
None,
event_handler,
);
});
}
#[cfg(not(feature = "parallel"))]
self.physics.pipeline.step(
&self.physics.gravity,
&self.physics.integration_parameters,
&mut self.physics.broad_phase,
&mut self.physics.narrow_phase,
&mut self.physics.bodies,
&mut self.physics.colliders,
&mut self.physics.joints,
None,
None,
&self.event_handler,
);
self.physics
.query_pipeline
.update(&self.physics.bodies, &self.physics.colliders);
for plugin in &mut self.plugins { for plugin in &mut self.plugins {
plugin.step(&mut self.physics) plugin.step(&mut self.harness.physics)
} }
} }
@@ -1343,13 +1252,13 @@ impl State for Testbed {
{ {
if self.state.selected_backend == BOX2D_BACKEND { if self.state.selected_backend == BOX2D_BACKEND {
self.box2d.as_mut().unwrap().step( self.box2d.as_mut().unwrap().step(
&mut self.physics.pipeline.counters, &mut physics.pipeline.counters,
&self.physics.integration_parameters, &physics.integration_parameters,
); );
self.box2d self.box2d
.as_mut() .as_mut()
.unwrap() .unwrap()
.sync(&mut self.physics.bodies, &mut self.physics.colliders); .sync(&mut physics.bodies, &mut physics.colliders);
} }
} }
@@ -1360,13 +1269,13 @@ impl State for Testbed {
{ {
// println!("Step"); // println!("Step");
self.physx.as_mut().unwrap().step( self.physx.as_mut().unwrap().step(
&mut self.physics.pipeline.counters, &mut physics.pipeline.counters,
&self.physics.integration_parameters, &physics.integration_parameters,
); );
self.physx self.physx
.as_mut() .as_mut()
.unwrap() .unwrap()
.sync(&mut self.physics.bodies, &mut self.physics.colliders); .sync(&mut physics.bodies, &mut physics.colliders);
} }
} }
@@ -1374,32 +1283,20 @@ impl State for Testbed {
{ {
if self.state.selected_backend == NPHYSICS_BACKEND { if self.state.selected_backend == NPHYSICS_BACKEND {
self.nphysics.as_mut().unwrap().step( self.nphysics.as_mut().unwrap().step(
&mut self.physics.pipeline.counters, &mut physics.pipeline.counters,
&self.physics.integration_parameters, &physics.integration_parameters,
); );
self.nphysics self.nphysics
.as_mut() .as_mut()
.unwrap() .unwrap()
.sync(&mut self.physics.bodies, &mut self.physics.colliders); .sync(&mut physics.bodies, &mut physics.colliders);
} }
} }
for f in &mut self.callbacks {
f(
window,
&mut self.physics,
&self.events,
&mut self.graphics,
self.time,
)
}
for plugin in &mut self.plugins { for plugin in &mut self.plugins {
plugin.run_callbacks(window, &mut self.physics, self.time) plugin.run_callbacks(window, &mut self.harness.physics, &self.harness.state);
} }
self.events.poll_all();
// if true { // if true {
// // !self.hide_counters { // // !self.hide_counters {
// #[cfg(not(feature = "log"))] // #[cfg(not(feature = "log"))]
@@ -1407,20 +1304,21 @@ impl State for Testbed {
// #[cfg(feature = "log")] // #[cfg(feature = "log")]
// debug!("{}", self.world.counters); // debug!("{}", self.world.counters);
// } // }
self.time += self.physics.integration_parameters.dt();
} }
} }
self.highlight_hovered_body(window); self.highlight_hovered_body(window);
let physics = &self.harness.physics;
self.graphics self.graphics
.draw(&self.physics.bodies, &self.physics.colliders, window); .draw(&physics.bodies, &physics.colliders, window);
for plugin in &mut self.plugins { for plugin in &mut self.plugins {
plugin.draw(); plugin.draw();
} }
if self.state.flags.contains(TestbedStateFlags::CONTACT_POINTS) { if self.state.flags.contains(TestbedStateFlags::CONTACT_POINTS) {
draw_contacts(window, &self.physics.narrow_phase, &self.physics.colliders); draw_contacts(window, &physics.narrow_phase, &physics.colliders);
} }
if self.state.running == RunMode::Step { if self.state.running == RunMode::Step {
@@ -1432,7 +1330,7 @@ impl State for Testbed {
} }
let color = Point3::new(0.0, 0.0, 0.0); let color = Point3::new(0.0, 0.0, 0.0);
let counters = self.physics.pipeline.counters; let counters = physics.pipeline.counters;
let mut profile = String::new(); let mut profile = String::new();
if self.state.flags.contains(TestbedStateFlags::PROFILE) { if self.state.flags.contains(TestbedStateFlags::PROFILE) {
@@ -1483,11 +1381,12 @@ CCD: {:.2}ms
if self.state.flags.contains(TestbedStateFlags::DEBUG) { if self.state.flags.contains(TestbedStateFlags::DEBUG) {
let t = instant::now(); let t = instant::now();
let bf = bincode::serialize(&self.physics.broad_phase).unwrap(); let physics = &self.harness.physics;
let nf = bincode::serialize(&self.physics.narrow_phase).unwrap(); let bf = bincode::serialize(&physics.broad_phase).unwrap();
let bs = bincode::serialize(&self.physics.bodies).unwrap(); let nf = bincode::serialize(&physics.narrow_phase).unwrap();
let cs = bincode::serialize(&self.physics.colliders).unwrap(); let bs = bincode::serialize(&physics.bodies).unwrap();
let js = bincode::serialize(&self.physics.joints).unwrap(); let cs = bincode::serialize(&physics.colliders).unwrap();
let js = bincode::serialize(&physics.joints).unwrap();
let serialization_time = instant::now() - t; let serialization_time = instant::now() - t;
let hash_bf = md5::compute(&bf); let hash_bf = md5::compute(&bf);
let hash_nf = md5::compute(&nf); let hash_nf = md5::compute(&nf);
@@ -1505,7 +1404,7 @@ Hashes at frame: {}
|_ Joints [{:.1}KB]: {:?}"#, |_ Joints [{:.1}KB]: {:?}"#,
profile, profile,
serialization_time, serialization_time,
self.state.timestep_id, self.harness.state.timestep_id,
bf.len() as f32 / 1000.0, bf.len() as f32 / 1000.0,
hash_bf, hash_bf,
nf.len() as f32 / 1000.0, nf.len() as f32 / 1000.0,

View File

@@ -2,6 +2,7 @@ use kiss3d::conrod::{self, Borderable, Colorable, Labelable, Positionable, Sizea
use kiss3d::window::Window; use kiss3d::window::Window;
use rapier::dynamics::IntegrationParameters; use rapier::dynamics::IntegrationParameters;
use crate::harness::RunState;
use crate::testbed::{RunMode, TestbedActionFlags, TestbedState, TestbedStateFlags}; use crate::testbed::{RunMode, TestbedActionFlags, TestbedState, TestbedStateFlags};
const SIDEBAR_W: f64 = 200.0; const SIDEBAR_W: f64 = 200.0;
@@ -98,6 +99,7 @@ impl TestbedUi {
window: &mut Window, window: &mut Window,
integration_parameters: &mut IntegrationParameters, integration_parameters: &mut IntegrationParameters,
state: &mut TestbedState, state: &mut TestbedState,
run_state: &mut RunState,
) { ) {
let ui_root = window.conrod_ui().window; let ui_root = window.conrod_ui().window;
let mut ui = window.conrod_ui_mut().set_widgets(); let mut ui = window.conrod_ui_mut().set_widgets();
@@ -254,7 +256,7 @@ impl TestbedUi {
let curr_vel_iters = integration_parameters.max_velocity_iterations; let curr_vel_iters = integration_parameters.max_velocity_iterations;
let curr_pos_iters = integration_parameters.max_position_iterations; let curr_pos_iters = integration_parameters.max_position_iterations;
#[cfg(feature = "parallel")] #[cfg(feature = "parallel")]
let curr_num_threads = state.num_threads; let curr_num_threads = run_state.num_threads;
let curr_max_ccd_substeps = integration_parameters.max_ccd_substeps; let curr_max_ccd_substeps = integration_parameters.max_ccd_substeps;
let curr_min_island_size = integration_parameters.min_island_size; let curr_min_island_size = integration_parameters.min_island_size;
let curr_warmstart_coeff = integration_parameters.warmstart_coeff; let curr_warmstart_coeff = integration_parameters.warmstart_coeff;
@@ -305,10 +307,10 @@ impl TestbedUi {
.w_h(ELEMENT_W, ELEMENT_H) .w_h(ELEMENT_W, ELEMENT_H)
.set(self.ids.slider_num_threads, &mut ui) .set(self.ids.slider_num_threads, &mut ui)
{ {
if state.num_threads != val as usize { if run_state.num_threads != val as usize {
state.num_threads = val as usize; run_state.num_threads = val as usize;
state.thread_pool = rapier::rayon::ThreadPoolBuilder::new() run_state.thread_pool = rapier::rayon::ThreadPoolBuilder::new()
.num_threads(state.num_threads) .num_threads(run_state.num_threads)
.build() .build()
.unwrap(); .unwrap();
} }