Skip to content

Commit 04bb6ce

Browse files
committed
Add clamping for more robust system
1 parent b8a0156 commit 04bb6ce

File tree

1 file changed

+15
-1
lines changed

1 file changed

+15
-1
lines changed

mujoco_ros2_control/src/mujoco_ros2_control_node.cpp

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,14 +86,28 @@ int main(int argc, const char **argv)
8686
double sim_time_accumulator = 0.0;
8787
auto last_frame_wall_time = std::chrono::steady_clock::now();
8888

89+
// Define a maximum number of physics steps per rendering frame to prevent "spiral of death"
90+
// This limits how much simulation time can be processed if rendering lags significantly.
91+
// (1.0 / 30.0) / physics_dt would mean capping catch-up to what a 30Hz loop would do.
92+
const int max_physics_steps_per_render_frame = static_cast<int>((1.0 / 30.0) / physics_dt) + 1;
93+
8994
while (rclcpp::ok() && !rendering->is_close_flag_raised())
9095
{
9196
auto current_frame_wall_time = std::chrono::steady_clock::now();
9297
std::chrono::duration<double> elapsed_wall_since_last_frame = current_frame_wall_time - last_frame_wall_time;
9398
last_frame_wall_time = current_frame_wall_time;
94-
99+
95100
sim_time_accumulator += elapsed_wall_since_last_frame.count();
96101

102+
// Clamp accumulator to prevent excessive catch-up if rendering is slow
103+
if (sim_time_accumulator > max_physics_steps_per_render_frame * physics_dt) {
104+
RCLCPP_WARN_THROTTLE(
105+
node->get_logger(), *node->get_clock(), 1000, // Log once per second if this happens
106+
"Simulation is lagging; clamping accumulated time. Accumulator: %f, Max allowed: %f",
107+
sim_time_accumulator, max_physics_steps_per_render_frame * physics_dt);
108+
sim_time_accumulator = max_physics_steps_per_render_frame * physics_dt;
109+
}
110+
97111
// Perform physics steps
98112
while (sim_time_accumulator >= physics_dt)
99113
{

0 commit comments

Comments
 (0)