Giter Club home page Giter Club logo

travesim's Introduction

🥅 TraveSim

IEEE Very Small Size Soccer simulation project with ROS and Gazebo

Para a versão em PT-BR 🇧🇷 desse documento, veja aqui

📷 Screenshots

🎈 Intro

It is necessary to clone the project inside a catkin workspace. To create a workspace, refer to this link

To run the simulation with one controllable robot

roslaunch travesim simulation_robot.launch

To run the simulation with the entire team

roslaunch travesim simulation_team.launch

To run the simulation of a match

roslaunch travesim simulation_match.launch

🌎 Worlds

TraveSim can handle simulating games with 3 or 5 robots per team. The number of robots per team will be inferred from the chosen simulation world. The worlds currently supported are as follows:

  • vss_field.world - Base world for 3x3 matches
  • vss_field_camera.world - World for 3x3 matches with camera and spotlights
  • vss_field_5.world - Base world for 5x5 matches

So, for example, to run the simulation with a single team of 5 robots, run:

roslaunch travesim simulation_team.launch world_name:=vss_field_5.world

For more information about roslaunch parameters, see the 🚀 Roslaunch section.

📣 ROS topics

⬅ Input

The simulation can work using 2 input interfaces, differential drive control (default) or direct motor control. It is important to notice that is not possible to use both interfaces to control different robots at the same time.

Differential drive control (default)

By default, the simulation receives commands of type geometry_msgs/Twist, representing the desired velocity of the robot in two components: linear and angular.

# This expresses velocity in free space broken into its linear and angular parts.
Vector3  linear
Vector3  angular

The ROS topics follow the naming convention:

  • /yellow_team/robot_[0..2|0..4]/diff_drive_controller/cmd_vel
  • /blue_team/robot_[0..2|0..4]/diff_drive_controller/cmd_vel

The control of the robot is performed by the diff_driver_controller from the library ros_control. The controller represents the behavior of the embedded system of the robot and will send torque commands to the motors in order to follow the received set point.

The parameters of this controller are specified in the file ./config/motor_diff_drive.yml.

Direct motor control

The simulation also accepts control directly over angular velocity commands (in rad/s) for both robot's motors (through the interface velocity_controller from ros_control). This interface mimics a controller interface more coupled to the robots characteristics than differential drive control.

The commands are read from topics of type std_msgs/Float64, representing each motor's speed in rad/s

  • /yellow_team/robot_[0..2|0..4]/left_controller/command
  • /yellow_team/robot_[0..2|0..4]/right_controller/command
  • /blue_team/robot_[0..2|0..4]/left_controller/command
  • /blue_team/robot_[0..2|0..4]/right_controller/command

In order to enable this control interface, one should send the parameter twist_interface as false in roslaunch parameters

The parameters of this controller are specified in the file ./config/motor_direct_drive.yml.

➡ Output

By default, Gazebo publishes in the topic /gazebo/model_states of type gazebo_msgs/ModelStates, with an array of informations about each model in the simulation.

# broadcast all model states in world frame
string[] name                 # model names
geometry_msgs/Pose[] pose     # desired pose in world frame
geometry_msgs/Twist[] twist   # desired twist in world frame

For convenience, this package have a script (vision_proxy.py) that subscribes this topic and republishes the information at different topics of type gazebo_msgs/ModelState for each entity (3 yellow team robots, 3 blue team robots and 1 ball, 7 in total).

# Set Gazebo Model pose and twist
string model_name           # model to set state (pose and twist)
geometry_msgs/Pose pose     # desired pose in reference frame
geometry_msgs/Twist twist   # desired twist in reference frame
string reference_frame      # set pose/twist relative to the frame of this entity (Body/Model)
                            # leave empty or "world" or "map" defaults to world-frame

The republished topics are

  • /vision/yellow_team/robot_[0..2|0..4] - Yellow team robots's topics
  • /vision/blue_team/robot_[0..2|0..4] - Blue team robots's topics
  • /vision/ball - Ball's topic

All units are SI, distances are measured in meters, angles in radians, linear velocity in m/s and angular velocity in rad/s.

📏 Used models

The simulation is build upon a generic vss robot (more details here), inspired by VSS SDK model.

As support, models were created for the VSS field and ball, both build from Robocore's rules for IEEE VSS.

© Create your own model

To create a model for your project, refer to:

  • Phobos - Generate urdf files from Blender
  • SW2URDF - Generate urdf files from SolidWorks
  • fusion2urdf - Generate urdf files from Fusion 360
  • ROS wiki - How build a urdf model from scratch

To use your custom model, change the value of the model parameter when launching the simulation.

🔧 Parameters

🚀 Roslaunch

  • world_name - Name of world file inside ./worlds folder, default "vss_field.world"
  • model - Path of simulated robot model, default "./urdf/vss_robot.xacro"
  • controller_config_file - Path of simulated robot controllers config file, default "./config/motor_diff_drive.yml" if twist_interface is true, "./config/motor_direct_drive.yml" otherwise
  • ros_control_config_file - Path of gazebo_ros_control config file, default "./config/ros_control_config.yml"
  • debug - Enable debug messages in terminal, default "false"
  • gui - Enable Gazebo's GUI window, default "true"
  • paused - Init simulation paused, default "true"
  • use_sim_time - Use simulated time as reference in messages, default "true"
  • recording - Enable Gazebo's state log, default "false"
  • keyboard - Enable joystick/keyboard control node, default "false"
  • twist_interface - Enable geometry_msgs/Twist interface if true, 2 std_msgs/Float64 control interface otherwise. Default "true". See the docs for more info.

To pass a parameter to the simulation, just write the parameter name and its new value with :=

For example, to change the parameter keyboard to true:

roslaunch travesim simulation_team.launch keyboard:=true

📷 Virtual camera

The simulation has a virtual camera that record images from the top of the field, in the same way as a real VSS match. To enable it, one should use the world file vss_field_camera.world

roslaunch travesim simulation_team.launch world_name:=vss_field_camera.world

The images are published in the topic /camera/image_raw

It is possible to watch the footage with the package image_view

rosrun image_view image_view image:=/camera/image_raw

📁 Folder structure

  • bagfiles/ - Folder to store recorded bagfiles

  • docs/ - Documentation files

  • launch/ - Roslaunch files written in ROS XML syntax

  • meshes/ - .stl files for vss_generic_robot, created with SolidWorks SW2URDF extension

  • models/ - Custom Gazebo models used inside the simulation, as the field and the VSS ball

  • scripts/ - Python scripts used in the project

  • urdf/ - Robot description files in .urdf and .xacro format. The .urdf files were generated with SolidWorks SW2URDF extension

  • worlds/ - World files in SDL format

➕ Dependencies

The simulation is develop for ROS and Gazebo, it is recommend to install both with:

sudo apt install ros-noetic-desktop-full

The project depends on the package velocity_controllers and effort_controllers in the library ros_controllers and the python library pygame. It is possible to install both with apt-get

sudo apt install ros-noetic-velocity-controllers ros-noetic-effort-controllers python3-pygame

Or using rosdep

rosdep install travesim

🐍 Python virtual environment

One may want to run the project inside a python virtualenv, after all this is a good practice in the python development book

You can create a python environment with the command

python3 -m venv venv

Then you should run source in the virtual environment

source ./venv/bin/activate

To install the dependencies, run the command

pip install -r requirements.txt

Some external libraries may be missing to build pygame package. You can install then with

sudo apt-get install
  subversion \
  ffmpeg \
  libsdl1.2-dev \
  libsdl-image1.2-dev \
  libsdl-mixer1.2-dev \
  libsdl-ttf2.0-dev \
  libavcodec-dev \
  libavformat-dev \
  libportmidi-dev \
  libsmpeg-dev \
  libswscale-dev \

🎨 Gazebo colors

For a list of default available color in Gazebo, refer to the config file in the oficial repo. We have also 2 OGRE scripts team blue and team yellow for custom colors definition (Gazebo ref and OGRE ref)

📝 Contributing

Any help in the development of robotics is welcome, we encourage you to contribute to the project! To learn how, see the contribution guidelines here.

✨ Contributors

Thanks goes to these wonderful people (emoji key):


Felipe Gomes de Melo

📖 👀 💻 🌍

Lucas Haug

👀 💻 🌍 📖

tocoquinho

🤔 📖

Bernardo Coutinho

👀 💻 📖

Lucas Schneider

👀 💻 🌍 📖

Júlia Mello

🎨 🔣

ThallesCarneiro

🎨 🔣

TetsuoTakahashi

🤔

Gabriel Cosme Barbosa

👀

RicardoHonda

👀

leticiakimoto

👀

This project follows the all-contributors specification. Contributions of any kind welcome!

travesim's People

Contributors

berbardo avatar d-nery avatar felipegdm avatar lucas-pvg avatar lucashaug avatar lucastrschneider avatar ricardohonda avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

travesim's Issues

Dependências do script do dongle

Sobre isso: https://github.com/ThundeRatz/vss_simulation/blob/8db4829085f2700ca1255c4610759212b4e25ed2/scripts/usb_dongle.py#L14

Tava conversando com o @d-nery e aí ele falou algumas coisas sobre as dependências do script. Bom, primeiro seria necessário instalar python3-venv. Então seria necessário criar um ambiente virtual pra rodar o script, estando no diretório que está o script, fazendo:

python3 - m venv venv

O segundo venv, é o nome da pasta onde tudo do ambiente será guardado, ela tem que ir pro .gitignore.

Então é necessário "ativar" o ambiente virtual com:

source venv/bin/activate

Se estiver usando fish tem que usar o activate.fish.

Dá primeira vez é necessário instalar todos as dependências na mão com o pip, por exemplo:

pip install numpy

Isso vai instalar as dependências no seu ambiente virtual.

Fazendo pip freeze no terminal, você consegue ver as dependências do seu script. Então é possível guardar isso em um arquivo, por exemplo requirements.txt, esse arquivo tem que ir pro GitHub. Com esse arquivo é possível instalar facilmente todas as dependências com:

pip install -r requirements.txt

Para desativar o ambiente virtual é só fazer deactivate no terminal.

A vantagem de fazer isso é que se facilita a instalação de dependências do script e também mantém um registro de qual versão de cada dependência se está utilizando no projeto, isso é bom também porque se tiver uma atualização não compatível das dependências se sabe qual a versão que é compatível.

Migrar ROS pra python 3

Pra quem não sabe, o python 2 foi oficialmente descontinuado no começo desse ano. O @d-nery deu a dica de como podemos atualizar os nossos scripts para python 3, usando esse guia como referência.

De certa forma essa é uma tarefa relacionada com a issue #1, dependendo da minha facilidade em resolver esse problema eu já emendo e faço o upgrade

[flood]
O ROS vai lançar uma nova versão em Maio/2020, então se pá que se eu enrolar o suficiente os próprios desenvolvedores do ROS vão resolver esse BO pra mim
[/flood]

Cor das laterais dos modelos

Esses dias, abri o simulation_match e fiquei muito confuso quando percebi que as cores das laterais dos robôs não corresponderem com as cores do time, mas sim com a de um dos robôs.

image

Acho que seria bom mudar o verde da lateral para amarelo, e o vermelho para azul, ai fica mais fácil de entender o que ta acontecendo durante a partida.

Image Compression Error

Ao rodar a simulação na branch feature/camera e tentar gerar uma bagfile com todos os tópicos que estavam sendo publicados, ocorreu um problema com tópicos realcionados à câmera, aparentemente devido ao formato da imagem. O erro era mostrado pelo gazebo e não pelo rosbag, sendo o seguinte:

[ERROR] [1601755303.697558886, 24.779000000]: Compressed Depth Image Transport - Compression requires sing
le-channel 32bit-floating point or 16bit raw depth images (input format is: rgb8).                        

Tentei desabilitar a parte de compressão da imagem como é feito aqui, tentei mexer em alguns parâmetros que estavam disponíveis no servidor de parâmetros do ros e também tentei mudar o formato da imagem que era publicada pela câmera, mas nenhuma dessa coisas resolveu.

A única forma de "resolver" que encontrei foi excluindo os tópicos que se relacionavam a parte de compressão da imagem na hora de gerar a bagfile, fazendo do seuinte jeito:

rosbag record -a -x "(.*)/compressed(.*)"

Refatorar spawn de 1 robô

Vou deixar a issue aqui pra deixar no banco de tarefas, é bem de boas, teria q refatorar o lanchfile de dar spawn de 1 robô pra usar o spawn_robots.py. Pra isso teria q mudar algumas coisinhas no spawn_robots.py pra ele suportar 1 robô só e pra isso ao invés de usar posições pré definidas, usar valores passados pelo usuário.

Instabilidade no modelo do robô genérico

Não sei exatamente se isso é um bug mesmo, mas só pra deixar aqui, eu fui testar algumas coisinhas usando o rqt_steering_topic, e percebi que tem uns omportamentos estranhos as vezes.

A primeira coisa foi esse balanço quando eu colocava só uma velocidade angular.

angular_bug

Ele fica balançando pra frente e pra tras, e fica travando as vezes.

Outra coisa que aconteceu bastante foi dele ficar bastante descontrolado e não consegui seguir nem de perto uma linha reta quando eu colocava uma velocidade linear.

linear_bug_1

linear_bug_2

Não sei, pra mim parece que é um problema no modelo que ta causando esses comportamentos, mas posso estar errado. Vocês perceberam algo assim também? Aqui acontece quase sempre algo do tipo.

O mais estranho é que não lembro desse tipo de coisa acontecer tão frequentemente quando a gente usava o nosso modelo mesmo, por isso acredito que esse seja o problema, mas não tenho certeza.

Documentação do README

Falei isso em alguma PR pra não esquecer, mas achei melhor documentar numa issue, a parte de estrutura das pastas nos READMEs ficou incompleta depois que a gente adicionou umas coisas, então precisamos completar.

Script de controle com o teclado/joystick

Vou criar essa issue aqui pra gente ver isso depois de dar merge na PR #16.

Do jeito que tá agora, o script de controle com o teclado/joystick ficou pra só poder controlar no modo "diff drive", aí acho que seria legal a gente poder permitir os dois jeitos, porque usar esse script é uma forma básica da gente testar se as coisas tão andando certinho no simulador e não conseguir testar as coisas de um jeito fácil complica por exemplo revisar mudanças que afetem o modo "direct drive".

Do jeito que tá, por exemplo, se a gente tentar rodar esse comando:

roslaunch vss_simulation simulation_robot.launch twist_interface:=false keyboard:=true

O simulador não vai funcionar, porque tem opções que são exclusivas.

A gente já passa ali a opção se usa twist ou não, então daria pra só passar isso como argumento na hora de executar o script do keyboard ou algo do gênero.

Retirar suporte ao diff_driver_controller

O tutorial oficial do ROS pra criar modelos de simulação no Gazebo utiliza um pacote de controle dos motores chamado http://wiki.ros.org/diff_drive_controller.

A primeira versão da simulação do VSS usava o diff_drive_controller, pois foi desenvolvida seguindo o tutorial oficial do ROS. Esse controlador recebe uma msg do tipo Twist e realiza o acionamento dos motores do robô. Para o histórico do uso desse controlador, veja o histórico do arquivo de configuração diffdrive.yaml

A principal vantagem em controlar o robô dessa forma é a facilidade na documentação (uso no tutorial oficial do ROS) e a existência da ferramenta gráfica rqt_robot_steering que permite o controle da simulação pela interface do computador.

No entanto, esse controlador abstrai coisas demais, o nosso projeto retorna a velocidade das rodas, não a velocidade do robô em si, e o controlador se mostrou instável durante as simulações.

Versões futuras do projeto deverão utilizar duas instâncias do velocity_controllers, uma para cada motor do robô. Esse controlador recebe uma mensagem do tipo std_msgs/Float64 que representa a velocidade angular desejada para o motor.

No momento em que escrevo, a migração está parcialmente concluída, as dependências lógicas do diff_driver_controller ainda não foram totalmente removidas na simulação de um robô. Um script python ainda deve ser desenvolvido para transformar msgs do tipo Twist em duas msgs Float64 (cada uma representado a velocidade angular de um motor), de modo a ainda ser possível utilizar a ferramenta gráfica rqt_robot_steering.

A priori, serei eu, @FelipeGdM quem vai fazer isso. Se alguém demonstrar interesse, essa tarefa será prontamente terceirizada. Estou abrindo essa issue para fins de documentação.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.