diff --git a/docs/assets/simulation_usage/05_real_time_factor.png b/docs/assets/simulation_usage/05_real_time_factor.png new file mode 100644 index 00000000..7dcc084e Binary files /dev/null and b/docs/assets/simulation_usage/05_real_time_factor.png differ diff --git a/docs/assets/simulation_usage/06_gazebo_px4_launcher.png b/docs/assets/simulation_usage/06_gazebo_px4_launcher.png new file mode 100644 index 00000000..b081fc3c Binary files /dev/null and b/docs/assets/simulation_usage/06_gazebo_px4_launcher.png differ diff --git a/docs/en/simulation_usage.md b/docs/en/simulation_usage.md index 84ecb778..e50f4974 100644 --- a/docs/en/simulation_usage.md +++ b/docs/en/simulation_usage.md @@ -47,3 +47,43 @@ If you wish to add additional sensors or change their placement, you will have t ### Changing the default world Gazebo plugins for the drone currently require the `real_time_update_rate` world parameter to be 250, and `max_step_size` to be 0.004. Using other values will not work. Consider using `~/catkin_ws/src/clover/clover_simulation/resources/worlds/clover.world` as a base. + +## Performance suggestions + +Gazebo simulation environment is resource-intensive, and requires a fast CPU and a decent GPU for real-time execution. However, the simulation may still work on less powerful systems at slower-than-realtime rate. Below are some suggestions for running Gazebo on hardware that does not allow realtime execution. + +### Use `throttling_camera` plugin + +By default, Gazebo does not slow simulation down for visual sensors. This can be remedied by using the `throttling_camera` plugin from `clover_simulation`. + +You can enable it for the drone by changing the `maintain_camera_rate` argument to `true` in `clover_description/launch/spawn_drone.launch`: + +```xml + + +``` + +The plugin will collect publishing rate statistics and slow the simulation down so that the camera publishing rate is no less than requested. However, large slowdowns may negatively affect non-ROS software that connects to PX4. If your simulation is being slowed down to values lower than 0.5 of realtime, consider using the next suggestion. + +### Set simulation speed + +Since v1.9 the PX4 SITL setup supports [setting the simulation speed](https://dev.px4.io/v1.9.0/en/simulation/#simulation_speed) by setting the `PX4_SIM_SPEED_FACTOR` environment variable. Its value is picked up by PX4 startup scripts, which in turn reconfigure it to expect a certain speedup/slowdown. + +You should set its value to the actual real time factor that you get with `throttling_camera`. The real time factor may be found in the Gazebo GUI window at the bottom: + +![Real Time Factor](../assets/simulation_usage/05_real_time_factor.png) + +In this example you should set `PX4_SIM_SPEED_FACTOR` to `0.42` when launching the simulation: + +```bash +PX4_SIM_SPEED_FACTOR=0.42 roslaunch clover_simulation simulator.launch +``` + +> **Note** If you are using the VM, it may be convenient to put the value in the Gazebo desktop shortcut. Right-click on the Gazebo icon, select "Properties..." and add `PX4_SIM_SPEED_FACTOR=0.42` to the Command field as follows: +![Gazebo PX4 launcher command](../assets/simulation_usage/06_gazebo_px4_launcher.png) + +### Allocate more resources to the VM + +The virtual machine may benefit from several CPU cores, especially if the cores are not very performant. In our tests, a four-core machine with only a single core allocated to the VM was unable to run the simulation, with constant interface freezes and dropped ROS messages. The same machine with all four cores available to the VM was able to run the simulation at 0.25 real-time speed. + +Do note that you should not allocate more resources than you have on your host hardware. diff --git a/docs/ru/simulation_usage.md b/docs/ru/simulation_usage.md index ba611324..1778a6a7 100644 --- a/docs/ru/simulation_usage.md +++ b/docs/ru/simulation_usage.md @@ -47,3 +47,43 @@ roslaunch clover_simulation simulator.launch ### Изменение мира по умолчанию Плагины Gazebo для дрона на данный момент требуют, чтобы значение параметра мира `real_time_update_rate` было равно 250, а значение `max_step_size` было равно 0.004. С другими параметрами симулятор не заработает. Используйте файл `~/catkin_ws/src/clover/clover_simulation/resources/worlds/clover.world` как шаблон. + +## Повышение производительности + +Симуляция с использованием Gazebo требовательна к ресурсам, и для нормальной скорости работы требуются мощный процессор и видеокарта. При этом симуляции можно запускать и на менее мощном оборудовании, жертвуя при этом скоростью работы. Ниже приведены рекомендации для компьютеров, на которых симуляция не может работать в реальном времени. + +### Использование плагина `throttling_camera` + +По умолчанию Gazebo не замедляет симуляцию для достижения требуемой частоты работы визуальных сенсоров. Это можно исправить с помощью плагина `throttling_camera` из пакета `clover_simulation`. + +Включение этого плагина происходит путём выставления параметра `maintain_camera_rate` в значение `true` в файле `clover_description/launch/spawn_drone.launch`: + +```xml + + +``` + +Этот плагин будет собирать статистику по частоте публикации изображений, и будет замедлять симуляцию до тех пор, пока частота публикации не станет соответствовать или превышать требуемую. При этом значительные замедления симуляции могут негативно сказаться на программном обеспечении, которое подключается к PX4 (например, QGroundControl). Если скорость симуляции опускается ниже, чем 0.5 от реального времени, следует воспользоваться следующей рекомендацией. + +### Выставление скорости симуляции + +PX4, начиная с версии 1.9, поддерживает [принудительную установку скорости симуляции](https://dev.px4.io/v1.9.0/en/simulation/#simulation_speed) с помощью переменной окружения `PX4_SIM_SPEED_FACTOR`. Выставление этой переменной подготавливает все компоненты симулятора к соответствующему ускорению/замедлению. + +Значение этой переменной должно соответствовать величине Real Time Factor (скорости симуляции по отношению к реальному времени), получаемой при использовании `throttling_camera`. Величина Real Time Factor отображается в окне Gazebo на нижней панели: + +![Real Time Factor](../assets/simulation_usage/05_real_time_factor.png) + +В данном случае `PX4_SIM_SPEED_FACTOR` следует выставить в значение `0.42` перед запуском симулятора: + +```bash +PX4_SIM_SPEED_FACTOR=0.42 roslaunch clover_simulation simulator.launch +``` + +> **Note** При использовании виртуальной машины удобнее добавить эту переменную в ярлык запуска Gazebo на рабочем столе. Нажмите правой кнопкой на значок Gazebo, выберите "Properties..." и добавьте `PX4_SIM_SPEED_FACTOR=0.42` в поле Command, как показано на иллюстрации: +![Gazebo PX4 launcher command](../assets/simulation_usage/06_gazebo_px4_launcher.png) + +### Выделение ресурсов для виртуальной машины + +Выделение нескольких процессорных ядер для виртуальной машины может значительно повысить производительность симуляции. В наших испытаниях виртуальная машина, для которой было выделено одно ядро, не позволяла работать в симуляторе: окно Gazebo не реагировало на пользовательский ввод, сообщения ROS терялись. После выделения четырёх ядер для этой же виртуальной машины симуляция стала работать со скоростью 0.25 от реального времени. + +При этом не следует пытаться выделить для виртуальной машины больше ресурсов, чем доступно на основной системе.