When running Gazebo as a library, I want to insert a robot model. I have the model as an SDF string (which I converted from a URDF file).
I want to be able to insert this model and get the corresponding ModelPtr. I am able to do this if the world is not running when inserting the model, as follows:
// Assume the world is not running at this point.
std::string modelString; // this contains a valid SDF model
gazebo::physics::ModelPtr insertedModel;
int modelCountBefore = world->GetModelCount();
world->InsertModelString(modelString);
// need to advange the physics engine in order for the model count to increase
world->RunBlocking(1);
if(world->GetModelCount() == modelCountBefore+1)
{
// sucess
insertedModel = world->GetModel(modelCountBefore);
}
else
{
// failure
}
This works, but it's not necessarily very pretty.
I would like to be able to insert a model into a running world. If the world is already running, the above won't work. The code below inserts a model when the world is already running.
// Assume the world is running at this point.
std::string modelString; // this contains a valid SDF model
gazebo::physics::ModelPtr insertedModel;
world->InsertModelString(result);
// need to wait several iterations until models are loaded into Gazebo
int timer = 0;
while(world->GetModelCount() == modelCountBefore)
{
gazebo::common::Time::MSleep(100);
timer++;
if(timer > 1000)
{
break;
}
}
if(world->GetModelCount() == modelCountBefore+1)
{
// sucess
insertedModel = world->GetModel(modelCountBefore);
}
else
{
// failure
}
This is even more cumbersome. In addition, I have some severe problems when I insert the model with the second method. The model does not behave as it should at all when I use my controller on it. Sometimes the joints just move around arbitrarily, sometimes the joints appear to be fixed to some wrong locations, which causes the robot's links to fly apart when moving the joints. Sometimes it behaves fine. This behavior is not deterministic, something different happens every time I execute the same identical code.
What is the best way to reliably insert a model into a running simulation and get the corresponding ModelPtr?
Originally posted by NickDP on Gazebo Answers with karma: 186 on 2014-12-10
Post score: 3
Original comments
Comment by djou07 on 2015-06-17:
hi, I just want to know if you figured out why you have the non deterministic behavior, because I have the same issue
Comment by NickDP on 2015-06-18:
Unfortunately I no longer have access to the code. But I believe I followed nkoenigs advice below and paused the simulation, then proceeded as in the first code snippet in the OP and then unpaused.