Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
172 changes: 172 additions & 0 deletions crates/rapier3d/tests/pipeline_counters.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,43 @@

use rapier3d::prelude::*;

#[cfg(feature = "profiler")]
use rapier3d::counters::{Counters, Timer};
#[cfg(feature = "profiler")]
use std::sync::Arc;
#[cfg(feature = "profiler")]
use std::sync::atomic::{AtomicUsize, Ordering};
#[cfg(feature = "profiler")]
use std::time::Duration;

#[cfg(feature = "profiler")]
fn timers(counters: &mut Counters) -> Vec<&mut Timer> {
vec![
&mut counters.step_time,
&mut counters.custom,
&mut counters.stages.update_time,
&mut counters.stages.collision_detection_time,
&mut counters.stages.island_construction_time,
&mut counters.stages.island_constraints_collection_time,
&mut counters.stages.solver_time,
&mut counters.stages.ccd_time,
&mut counters.stages.user_changes,
&mut counters.cd.broad_phase_time,
&mut counters.cd.final_broad_phase_time,
&mut counters.cd.narrow_phase_time,
&mut counters.solver.velocity_resolution_time,
&mut counters.solver.velocity_assembly_time,
&mut counters.solver.velocity_assembly_time_solver_bodies,
&mut counters.solver.velocity_assembly_time_constraints_init,
&mut counters.solver.velocity_update_time,
&mut counters.solver.velocity_writeback_time,
&mut counters.ccd.toi_computation_time,
&mut counters.ccd.solver_time,
&mut counters.ccd.broad_phase_time,
&mut counters.ccd.narrow_phase_time,
]
}

fn world_with_ground() -> PhysicsWorld {
let mut world = PhysicsWorld::new();
world.insert(
Expand Down Expand Up @@ -78,3 +115,138 @@ fn ccd_substeps_counter() {
assert!(world.physics_pipeline.counters.ccd.num_substeps >= 1);
assert!(world.bodies[slow].translation().y > -0.5);
}

#[cfg(feature = "profiler")]
#[test]
fn disabled_counters_freeze_direct_timers() {
let mut counters = Counters::new(false);
for timer in timers(&mut counters) {
// Both entry points must be inert while their parent counters are disabled.
timer.start();
timer.resume();
}
std::thread::sleep(Duration::from_millis(2));
for timer in timers(&mut counters) {
timer.pause();
assert_eq!(timer.time(), Duration::ZERO);
}

counters.enable();
for timer in timers(&mut counters) {
timer.start();
}
std::thread::sleep(Duration::from_millis(2));
let measured: Vec<_> = timers(&mut counters)
.into_iter()
.map(|timer| {
timer.pause();
assert!(timer.time() > Duration::ZERO);
timer.resume();
timer.time()
})
.collect();

counters.disable();
std::thread::sleep(Duration::from_millis(2));
counters.enable();
for (timer, expected) in timers(&mut counters).into_iter().zip(measured) {
timer.pause();
assert_eq!(timer.time(), expected);
}
}

#[cfg(feature = "profiler")]
#[test]
fn direct_enabled_flag_changes_apply_at_the_next_step() {
let mut world = world_with_ground();
world.insert(
RigidBodyBuilder::dynamic().translation(Vector::new(0.0, 0.55, 0.0)),
ColliderBuilder::ball(0.5),
);
world.physics_pipeline.counters.enable();
world.step();
assert!(world.physics_pipeline.counters.step_time() > Duration::ZERO);
let measured: Vec<_> = timers(&mut world.physics_pipeline.counters)
.into_iter()
.map(|timer| timer.time())
.collect();

world.physics_pipeline.counters.enabled = false;
for _ in 0..3 {
world.step();
}
for (timer, expected) in timers(&mut world.physics_pipeline.counters)
.into_iter()
.zip(measured)
{
assert_eq!(timer.time(), expected);
}

world.physics_pipeline.counters.enabled = true;
world.step();
assert!(world.physics_pipeline.counters.step_time() > Duration::ZERO);
assert!(world.physics_pipeline.counters.cd.narrow_phase_time.time() > Duration::ZERO);
}

#[cfg(feature = "profiler")]
#[derive(Clone, Default)]
struct SlowContactHooks(Arc<AtomicUsize>);

#[cfg(feature = "profiler")]
const HOOK_DELAY: Duration = Duration::from_millis(2);
#[cfg(feature = "profiler")]
const MIN_CLAMP_PASSES: usize = 2;

#[cfg(feature = "profiler")]
impl PhysicsHooks for SlowContactHooks {
fn filter_contact_pair(&self, _: &PairFilterContext<'_>) -> Option<SolverFlags> {
self.0.fetch_add(1, Ordering::Relaxed);
std::thread::sleep(HOOK_DELAY);
Some(SolverFlags::COMPUTE_RIGID_IMPULSES)
}
}

#[cfg(feature = "profiler")]
#[test]
fn ccd_timer_accumulates_work_from_multiple_clamp_passes() {
let mut world = PhysicsWorld::new();
world.gravity = Vector::ZERO;
world.integration_parameters.max_ccd_substeps = 4;
for (y, x) in [(0.0, -0.3), (2.0, -0.8)] {
world.insert(
RigidBodyBuilder::fixed().translation(Vector::new(0.0, y, 0.0)),
ColliderBuilder::cuboid(0.05, 0.4, 0.4),
);
world.insert(
RigidBodyBuilder::dynamic()
.translation(Vector::new(x, y, 0.0))
.linvel(Vector::new(60.0, 0.0, 0.0))
.ccd_enabled(true),
ColliderBuilder::cuboid(0.05, 0.05, 0.05)
.active_hooks(ActiveHooks::FILTER_CONTACT_PAIRS),
);
}

let hooks = SlowContactHooks::default();
world.step_with_events(&hooks, &());

assert!(
world.physics_pipeline.counters.ccd.num_substeps >= MIN_CLAMP_PASSES,
"fixture must execute multiple CCD clamp passes"
);
assert!(
hooks.0.load(Ordering::Relaxed) >= MIN_CLAMP_PASSES,
"fixture must inject work into multiple contact-filter calls"
);
let minimum_accumulated_time = HOOK_DELAY * MIN_CLAMP_PASSES as u32;
assert!(
world
.physics_pipeline
.counters
.ccd
.toi_computation_time
.time()
>= minimum_accumulated_time,
"CCD timing must include at least two injected clamp-pass delays"
);
}
43 changes: 42 additions & 1 deletion src/counters/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,20 +37,25 @@ pub struct Counters {
impl Counters {
/// Create a new set of counters initialized to zero.
pub fn new(enabled: bool) -> Self {
Counters {
let mut counters = Counters {
enabled,
step_time: Timer::new(),
custom: Timer::new(),
stages: StagesCounters::new(),
cd: CollisionDetectionCounters::new(),
solver: SolverCounters::new(),
ccd: CCDCounters::new(),
};
if !enabled {
counters.disable();
}
counters
}

/// Enable all the counters.
pub fn enable(&mut self) {
self.enabled = true;
self.set_timers_enabled(true);
}

/// Return `true` if the counters are enabled.
Expand All @@ -61,6 +66,36 @@ impl Counters {
/// Disable all the counters.
pub fn disable(&mut self) {
self.enabled = false;
self.set_timers_enabled(false);
}

fn set_timers_enabled(&mut self, enabled: bool) {
for timer in [
&mut self.step_time,
&mut self.custom,
&mut self.stages.update_time,
&mut self.stages.collision_detection_time,
&mut self.stages.island_construction_time,
&mut self.stages.island_constraints_collection_time,
&mut self.stages.solver_time,
&mut self.stages.ccd_time,
&mut self.stages.user_changes,
&mut self.cd.broad_phase_time,
&mut self.cd.final_broad_phase_time,
&mut self.cd.narrow_phase_time,
&mut self.solver.velocity_resolution_time,
&mut self.solver.velocity_assembly_time,
&mut self.solver.velocity_assembly_time_solver_bodies,
&mut self.solver.velocity_assembly_time_constraints_init,
&mut self.solver.velocity_update_time,
&mut self.solver.velocity_writeback_time,
&mut self.ccd.toi_computation_time,
&mut self.ccd.solver_time,
&mut self.ccd.broad_phase_time,
&mut self.ccd.narrow_phase_time,
] {
timer.set_enabled(enabled);
}
}

/// Notify that the time-step has started.
Expand Down Expand Up @@ -128,6 +163,12 @@ impl Counters {

/// Resets all the counters and timers.
pub fn reset(&mut self) {
// Preserve the public `enabled` field's behavior for callers assigning it
// directly: synchronize timer state before a pipeline step starts timing.
#[cfg(feature = "profiler")]
if self.step_time.is_enabled() != self.enabled {
self.set_timers_enabled(self.enabled);
}
if self.enabled {
self.step_time.reset();
self.custom.reset();
Expand Down
53 changes: 46 additions & 7 deletions src/counters/timer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,20 @@ use core::{
#[cfg(feature = "profiler")]
use web_time::Instant;

#[cfg(feature = "profiler")]
#[derive(Copy, Clone, Debug)]
enum TimerState {
Disabled,
Stopped,
Running(Instant),
}

/// A timer.
#[derive(Copy, Clone, Debug, Default)]
#[derive(Copy, Clone, Debug)]
pub struct Timer {
time: Duration,
#[cfg(feature = "profiler")]
start: Option<Instant>,
state: TimerState,
}

impl Timer {
Expand All @@ -20,8 +28,28 @@ impl Timer {
Timer {
time: Duration::from_secs(0),
#[cfg(feature = "profiler")]
start: None,
state: TimerState::Stopped,
}
}

pub(crate) fn set_enabled(&mut self, enabled: bool) {
#[cfg(feature = "profiler")]
{
if !enabled {
// Discard an open interval without reading the clock. Re-enabling must
// never charge time spent with profiling disabled to the next pause.
self.state = TimerState::Disabled;
} else if matches!(self.state, TimerState::Disabled) {
self.state = TimerState::Stopped;
}
}
#[cfg(not(feature = "profiler"))]
let _ = enabled;
}

#[cfg(feature = "profiler")]
pub(crate) fn is_enabled(&self) -> bool {
!matches!(self.state, TimerState::Disabled)
}

/// Resets the timer to 0.
Expand All @@ -33,27 +61,32 @@ impl Timer {
pub fn start(&mut self) {
#[cfg(feature = "profiler")]
{
if !self.is_enabled() {
return;
}
self.time = Duration::from_secs(0);
self.start = Some(Instant::now());
self.state = TimerState::Running(Instant::now());
}
}

/// Pause the timer.
pub fn pause(&mut self) {
#[cfg(feature = "profiler")]
{
if let Some(start) = self.start {
if let TimerState::Running(start) = self.state {
self.time += Instant::now().duration_since(start);
self.state = TimerState::Stopped;
}
self.start = None;
}
}

/// Resume the timer.
pub fn resume(&mut self) {
#[cfg(feature = "profiler")]
{
self.start = Some(Instant::now());
if self.is_enabled() {
self.state = TimerState::Running(Instant::now());
}
}
}

Expand All @@ -68,6 +101,12 @@ impl Timer {
}
}

impl Default for Timer {
fn default() -> Self {
Self::new()
}
}

impl Display for Timer {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
write!(f, "{}ms", self.time_ms())
Expand Down
3 changes: 2 additions & 1 deletion src/pipeline/physics_pipeline/substep.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,8 @@ impl PhysicsPipeline {
hooks: &dyn PhysicsHooks,
events: &dyn EventHandler,
) {
self.counters.ccd.toi_computation_time.start();
// Counters::reset clears the whole step; accumulate every internal pass.
self.counters.ccd.toi_computation_time.resume();
// Handle CCD: sweep the fast bodies and clamp their `next_position` to their
// earliest time of impact (velocities are preserved).
ccd_solver.solve_continuous(
Expand Down
Loading