# Revision history [back]

### Insert model programmatically and get its model pointer

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?