gazebo / gazebo / physics / World.cc

The branch 'logging_gui' does not exist.
   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
/*
 * Copyright 2012 Open Source Robotics Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
*/
/* Desc: The world; all models are collected here
 * Author: Andrew Howard and Nate Koenig
 */

#include <time.h>

#include <tbb/parallel_for.h>
#include <tbb/blocked_range.h>

#include <boost/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/recursive_mutex.hpp>

#include "gazebo/sensors/SensorManager.hh"
#include "gazebo/math/Rand.hh"

#include "gazebo/sdf/sdf.hh"
#include "gazebo/transport/Node.hh"
#include "gazebo/transport/Transport.hh"
#include "gazebo/transport/Publisher.hh"
#include "gazebo/transport/Subscriber.hh"

#include "gazebo/common/LogPlay.hh"
#include "gazebo/common/LogRecord.hh"
#include "gazebo/common/ModelDatabase.hh"
#include "gazebo/common/Common.hh"
#include "gazebo/common/Diagnostics.hh"
#include "gazebo/common/Events.hh"
#include "gazebo/common/Exception.hh"
#include "gazebo/common/Console.hh"
#include "gazebo/common/Plugin.hh"

#include "gazebo/physics/Road.hh"
#include "gazebo/physics/RayShape.hh"
#include "gazebo/physics/Link.hh"
#include "gazebo/physics/PhysicsEngine.hh"
#include "gazebo/physics/PhysicsFactory.hh"
#include "gazebo/physics/Model.hh"
#include "gazebo/physics/Actor.hh"
#include "gazebo/physics/World.hh"

#include "physics/Collision.hh"
#include "physics/ContactManager.hh"

using namespace gazebo;
using namespace physics;


class ModelUpdate_TBB
{
  public: ModelUpdate_TBB(Model_V *_models) : models(_models) {}
  public: void operator() (const tbb::blocked_range<size_t> &_r) const
  {
    for (size_t i = _r.begin(); i != _r.end(); i++)
    {
      (*models)[i]->Update();
    }
  }

  private: Model_V *models;
};

//////////////////////////////////////////////////
World::World(const std::string &_name)
{
  this->sdf.reset(new sdf::Element);
  sdf::initFile("world.sdf", this->sdf);

  this->factorySDF.reset(new sdf::SDF);
  sdf::initFile("root.sdf", this->factorySDF);

  this->logPlayStateSDF.reset(new sdf::Element);
  sdf::initFile("state.sdf", this->logPlayStateSDF);

  this->receiveMutex = new boost::recursive_mutex();
  this->loadModelMutex = new boost::mutex();

  this->initialized = false;
  this->loaded = false;
  this->stepInc = 0;
  this->pause = false;
  this->thread = NULL;
  this->stop = false;

  this->stateToggle = 0;

  this->pluginsLoaded = false;

  this->name = _name;

  this->needsReset = false;
  this->resetAll = true;
  this->resetTimeOnly = false;
  this->resetModelOnly = false;
  this->enablePhysicsEngine = true;
  this->setWorldPoseMutex = new boost::mutex();
  this->worldUpdateMutex = new boost::recursive_mutex();

  this->sleepOffset = common::Time(0);

  this->prevStatTime = common::Time::GetWallTime();
  this->prevProcessMsgsTime = common::Time::GetWallTime();

  this->connections.push_back(
     event::Events::ConnectStep(boost::bind(&World::OnStep, this)));
  this->connections.push_back(
     event::Events::ConnectSetSelectedEntity(
       boost::bind(&World::SetSelectedEntityCB, this, _1)));
}

//////////////////////////////////////////////////
World::~World()
{
  delete this->receiveMutex;
  this->receiveMutex = NULL;
  delete this->loadModelMutex;
  this->loadModelMutex = NULL;
  delete this->setWorldPoseMutex;
  this->setWorldPoseMutex = NULL;
  delete this->worldUpdateMutex;
  this->worldUpdateMutex = NULL;

  this->connections.clear();
  this->Fini();

  this->sdf->Reset();
  this->rootElement.reset();
  this->node.reset();

  this->testRay.reset();
}

//////////////////////////////////////////////////
void World::Load(sdf::ElementPtr _sdf)
{
  this->loaded = false;
  this->sdf = _sdf;

  if (this->sdf->GetValueString("name").empty())
    gzwarn << "create_world(world_name =["
           << this->name << "]) overwrites sdf world name\n!";
  else
    this->name = this->sdf->GetValueString("name");

  this->sceneMsg.CopyFrom(msgs::SceneFromSDF(this->sdf->GetElement("scene")));
  this->sceneMsg.set_name(this->GetName());

  // The period at which statistics about the world are published
  this->statPeriod = common::Time(0, 200000000);

  // The period at which messages are processed
  this->processMsgsPeriod = common::Time(0, 200000000);

  this->node = transport::NodePtr(new transport::Node());
  this->node->Init(this->GetName());

  this->posePub = this->node->Advertise<msgs::Pose_V>("~/pose/info", 10, 60.0);

  this->guiPub = this->node->Advertise<msgs::GUI>("~/gui");
  if (this->sdf->HasElement("gui"))
    this->guiPub->Publish(msgs::GUIFromSDF(this->sdf->GetElement("gui")));

  this->factorySub = this->node->Subscribe("~/factory",
                                           &World::OnFactoryMsg, this);
  this->controlSub = this->node->Subscribe("~/world_control",
                                           &World::OnControl, this);

  this->logControlSub = this->node->Subscribe("~/log/control",
                                              &World::OnLogControl, this);
  this->logStatusPub = this->node->Advertise<msgs::LogStatus>("~/log/status");

  this->requestSub = this->node->Subscribe("~/request",
                                           &World::OnRequest, this, true);
  this->jointSub = this->node->Subscribe("~/joint", &World::JointLog, this);
  this->modelSub = this->node->Subscribe<msgs::Model>("~/model/modify",
      &World::OnModelMsg, this);

  this->responsePub = this->node->Advertise<msgs::Response>("~/response");
  this->statPub =
    this->node->Advertise<msgs::WorldStatistics>("~/world_stats");
  this->selectionPub = this->node->Advertise<msgs::Selection>("~/selection", 1);
  this->modelPub = this->node->Advertise<msgs::Model>("~/model/info");
  this->lightPub = this->node->Advertise<msgs::Light>("~/light");

  std::string type = this->sdf->GetElement("physics")->GetValueString("type");
  this->physicsEngine = PhysicsFactory::NewPhysicsEngine(type,
      shared_from_this());

  if (this->physicsEngine == NULL)
    gzthrow("Unable to create physics engine\n");

  // This should come before loading of entities
  this->physicsEngine->Load(this->sdf->GetElement("physics"));

  this->rootElement.reset(new Base(BasePtr()));
  this->rootElement->SetName(this->GetName());
  this->rootElement->SetWorld(shared_from_this());

  // A special order is necessary when loading a world that contains state
  // information. The joints must be created last, otherwise they get
  // initialized improperly.
  {
    // Create all the entities
    this->LoadEntities(this->sdf, this->rootElement);

    // Set the state of the entities
    if (this->sdf->HasElement("state"))
    {
      sdf::ElementPtr childElem = this->sdf->GetElement("state");

      while (childElem)
      {
        WorldState myState;
        myState.Load(childElem);
        this->SetState(myState);

        childElem = childElem->GetNextElement("state");

        // TODO: We currently load just the first state data. Need to
        // implement a better mechanism for handling multiple states
        break;
      }
    }

    for (unsigned int i = 0; i < this->GetModelCount(); ++i)
      this->GetModel(i)->LoadJoints();
  }

  // TODO: Performance test to see if TBB model updating is necessary
  // Choose threaded or unthreaded model updating depending on the number of
  // models in the scene
  // if (this->GetModelCount() < 20)
  this->modelUpdateFunc = &World::ModelUpdateSingleLoop;
  // else
  // this->modelUpdateFunc = &World::ModelUpdateTBB;

  event::Events::worldCreated(this->GetName());

  this->loaded = true;
}

//////////////////////////////////////////////////
void World::Save(const std::string &_filename)
{
  this->UpdateStateSDF();
  std::string data;
  data = "<?xml version ='1.0'?>\n";
  data += "<sdf version='" +
          boost::lexical_cast<std::string>(SDF_VERSION) + "'>\n";
  data += this->sdf->ToString("");
  data += "</sdf>\n";

  std::ofstream out(_filename.c_str(), std::ios::out);
  if (!out)
    gzerr << "Unable to open file[" << _filename << "]\n";
  else
    out << data;

  out.close();
}

//////////////////////////////////////////////////
void World::Init()
{
  // Initialize all the entities
  for (unsigned int i = 0; i < this->rootElement->GetChildCount(); i++)
    this->rootElement->GetChild(i)->Init();

  // Initialize the physics engine
  this->physicsEngine->Init();

  this->testRay = boost::shared_dynamic_cast<RayShape>(
      this->GetPhysicsEngine()->CreateShape("ray", CollisionPtr()));

  common::LogRecord::Instance()->Add(this->GetName(), "state.log",
      boost::bind(&World::OnLog, this, _1));

  this->prevStates[0].SetWorld(shared_from_this());
  this->prevStates[1].SetWorld(shared_from_this());

  this->prevStates[0].SetName(this->GetName());
  this->prevStates[1].SetName(this->GetName());

  this->initialized = true;

  this->updateInfo.worldName = this->GetName();

  this->iterations = 0;

  // Mark the world initialization
  gzlog << "World::Init" << std::endl;
}

//////////////////////////////////////////////////
void World::Run()
{
  this->stop = false;
  this->thread = new boost::thread(
      boost::bind(&World::RunLoop, this));
}

//////////////////////////////////////////////////
void World::Stop()
{
  this->stop = true;
  if (this->thread)
  {
    this->thread->join();
    delete this->thread;
    this->thread = NULL;
  }
}

//////////////////////////////////////////////////
void World::RunLoop()
{
  this->physicsEngine->InitForThread();

  this->startTime = common::Time::GetWallTime();

  // This fixes a minor issue when the world is paused before it's started
  if (this->IsPaused())
    this->pauseStartTime = this->startTime;

  this->prevStepWallTime = common::Time::GetWallTime();

  // Get the first state
  this->prevStates[0] = WorldState(shared_from_this());
  this->stateToggle = 0;

  if (!common::LogPlay::Instance()->IsOpen())
  {
    while (!this->stop)
      this->Step();
  }
  else
  {
    this->enablePhysicsEngine = false;
    while (!this->stop)
      this->LogStep();
  }
}

//////////////////////////////////////////////////
void World::LogStep()
{
  if (!this->IsPaused() || this->stepInc > 0)
  {
    std::string data;
    if (!common::LogPlay::Instance()->Step(data))
    {
      this->SetPaused(true);
    }
    else
    {
      this->logPlayStateSDF->ClearElements();
      sdf::readString(data, this->logPlayStateSDF);

      this->logPlayState.Load(this->logPlayStateSDF);

      // Process insertions
      if (this->logPlayStateSDF->HasElement("insertions"))
      {
        sdf::ElementPtr modelElem =
          this->logPlayStateSDF->GetElement("insertions")->GetElement("model");

        while (modelElem)
        {
          ModelPtr model = this->LoadModel(modelElem, this->rootElement);
          model->Init();
          model->LoadPlugins();

          modelElem = modelElem->GetNextElement("model");
        }
      }

      // Process deletions
      if (this->logPlayStateSDF->HasElement("deletions"))
      {
        sdf::ElementPtr nameElem =
          this->logPlayStateSDF->GetElement("deletions")->GetElement("name");
        while (nameElem)
        {
          transport::requestNoReply(this->GetName(), "entity_delete",
                                    nameElem->GetValueString());
          nameElem = nameElem->GetNextElement("name");
        }
      }

      WorldState state = WorldState(shared_from_this()) + this->logPlayState;
      this->SetState(state);

      this->Update();
      this->iterations++;
    }

    if (this->stepInc > 0)
      this->stepInc--;
  }

  this->PublishWorldStats();

  this->ProcessMessages();
}

//////////////////////////////////////////////////
void World::Step()
{
  /// need this because ODE does not call dxReallocateWorldProcessContext()
  /// until dWorld.*Step
  /// Plugins that manipulate joints (and probably other properties) require
  /// one iteration of the physics engine. Do not remove this.
  if (!this->pluginsLoaded &&
      sensors::SensorManager::Instance()->SensorsInitialized())
  {
    this->LoadPlugins();
    this->pluginsLoaded = true;
  }

  // Send statistics about the world simulation
  if (common::Time::GetWallTime() - this->prevStatTime > this->statPeriod)
  {
    this->PublishWorldStats();
  }

  // sleep here to get the correct update rate
  common::Time tmpTime = common::Time::GetWallTime();
  common::Time sleepTime = this->prevStepWallTime +
    common::Time(this->physicsEngine->GetUpdatePeriod()) -
    tmpTime - this->sleepOffset;

  if (sleepTime > 0)
    common::Time::NSleep(sleepTime);
  else
    sleepTime = 0;

  common::Time actualSleep = common::Time::GetWallTime() - tmpTime;

  // exponentially avg out
  this->sleepOffset = (actualSleep - sleepTime) * 0.01 +
                      this->sleepOffset * 0.99;

  // throttling update rate, with sleepOffset as tolerance
  // the tolerance is needed as the sleep time is not exact
  if (common::Time::GetWallTime() - this->prevStepWallTime + this->sleepOffset
         >= common::Time(this->physicsEngine->GetUpdatePeriod()))
  {
    boost::recursive_mutex::scoped_lock lock(*this->worldUpdateMutex);

    this->prevStepWallTime = common::Time::GetWallTime();

    if (!this->IsPaused() || this->stepInc > 0)
    {
      // query timestep to allow dynamic time step size updates
      this->simTime += this->physicsEngine->GetStepTime();
      this->iterations++;
      this->Update();

      if (this->IsPaused() && this->stepInc > 0)
        this->stepInc--;
    }
    else
      this->pauseTime += this->physicsEngine->GetStepTime();
  }

  this->ProcessMessages();
}

//////////////////////////////////////////////////
void World::StepWorld(int _steps)
{
  if (!this->IsPaused())
  {
    gzwarn << "Calling World::StepWorld(steps) while world is not paused\n";
    this->SetPaused(true);
  }

  {
    boost::recursive_mutex::scoped_lock lock(*this->worldUpdateMutex);
    this->stepInc = _steps;
  }

  // block on completion
  bool wait = true;
  while (wait)
  {
    common::Time::MSleep(1);
    boost::recursive_mutex::scoped_lock lock(*this->worldUpdateMutex);
    if (this->stepInc == 0 || this->stop)
      wait = false;
  }
}

//////////////////////////////////////////////////
void World::Update()
{
  if (this->needsReset)
  {
    if (this->resetAll)
      this->Reset();
    else if (this->resetTimeOnly)
      this->ResetTime();
    else if (this->resetModelOnly)
      this->ResetEntities(Base::MODEL);
    this->needsReset = false;
  }

  event::Events::worldUpdateStart();
  this->updateInfo.simTime = this->GetSimTime();
  this->updateInfo.realTime = this->GetRealTime();
  event::Events::worldUpdateBegin(this->updateInfo);

  // Update all the models
  (*this.*modelUpdateFunc)();

  // This must be called before PhysicsEngine::UpdatePhysics.
  this->physicsEngine->UpdateCollision();

  // Update the physics engine
  if (this->enablePhysicsEngine && this->physicsEngine)
  {
    // This must be called directly after PhysicsEngine::UpdateCollision.
    this->physicsEngine->UpdatePhysics();

    // do this after physics update as
    //   ode --> MoveCallback sets the dirtyPoses
    //           and we need to propagate it into Entity::worldPose
    for (std::list<Entity*>::iterator iter = this->dirtyPoses.begin();
        iter != this->dirtyPoses.end(); ++iter)
    {
      (*iter)->SetWorldPose((*iter)->GetDirtyPose(), false);
    }

    this->dirtyPoses.clear();
  }

  // Output the contact information
  this->physicsEngine->GetContactManager()->PublishContacts();

  // Only update state informatin if logging data.
  if (common::LogRecord::Instance()->GetRunning())
  {
    int currState = (this->stateToggle + 1) % 2;
    this->prevStates[currState] = WorldState(shared_from_this());

    WorldState diffState = this->prevStates[currState] -
      this->prevStates[this->stateToggle];

    if (!diffState.IsZero())
    {
      this->stateToggle = currState;
      this->states.push_back(diffState);
      if (this->states.size() > 1000)
        this->states.pop_front();

      /// Publish a log status message if the logger is running.
      this->PublishLogStatus();
    }
  }

  event::Events::worldUpdateEnd();
}

//////////////////////////////////////////////////
void World::Fini()
{
  this->Stop();
  this->plugins.clear();

  this->node->Fini();

  if (this->rootElement)
  {
    this->rootElement->Fini();
    this->rootElement.reset();
  }

  if (this->physicsEngine)
  {
    this->physicsEngine->Fini();
    this->physicsEngine.reset();
  }

  this->prevStates[0].SetWorld(WorldPtr());
  this->prevStates[1].SetWorld(WorldPtr());
}

//////////////////////////////////////////////////
void World::Clear()
{
  // TODO: Implement this
}

//////////////////////////////////////////////////
std::string World::GetName() const
{
  return this->name;
}

//////////////////////////////////////////////////
PhysicsEnginePtr World::GetPhysicsEngine() const
{
  return this->physicsEngine;
}

//////////////////////////////////////////////////
BasePtr World::GetByName(const std::string &_name)
{
  return this->rootElement->GetByName(_name);
}

/////////////////////////////////////////////////
ModelPtr World::GetModelById(unsigned int _id)
{
  return boost::shared_dynamic_cast<Model>(this->rootElement->GetById(_id));
}

//////////////////////////////////////////////////
ModelPtr World::GetModel(const std::string &_name)
{
  boost::mutex::scoped_lock lock(*this->loadModelMutex);
  return boost::shared_dynamic_cast<Model>(this->GetByName(_name));
}

//////////////////////////////////////////////////
EntityPtr World::GetEntity(const std::string &_name)
{
  return boost::shared_dynamic_cast<Entity>(this->GetByName(_name));
}

//////////////////////////////////////////////////
ModelPtr World::LoadModel(sdf::ElementPtr _sdf , BasePtr _parent)
{
  boost::mutex::scoped_lock lock(*this->loadModelMutex);
  ModelPtr model;

  if (_sdf->GetName() == "model")
  {
    model.reset(new Model(_parent));
    model->SetWorld(shared_from_this());
    model->Load(_sdf);

    event::Events::addEntity(model->GetScopedName());

    msgs::Model msg;
    model->FillMsg(msg);
    this->modelPub->Publish(msg);

    this->EnableAllModels();
  }
  else
  {
    gzerr << "SDF is missing the <model> tag:\n";
    _sdf->PrintValues("  ");
  }

  this->PublishModelPose(model->GetName());
  return model;
}

//////////////////////////////////////////////////
ActorPtr World::LoadActor(sdf::ElementPtr _sdf , BasePtr _parent)
{
  ActorPtr actor(new Actor(_parent));
  actor->SetWorld(shared_from_this());
  actor->Load(_sdf);

  event::Events::addEntity(actor->GetScopedName());

  msgs::Model msg;
  actor->FillMsg(msg);
  this->modelPub->Publish(msg);

  return actor;
}

//////////////////////////////////////////////////
RoadPtr World::LoadRoad(sdf::ElementPtr _sdf , BasePtr _parent)
{
  RoadPtr road(new Road(_parent));
  road->Load(_sdf);
  return road;
}

//////////////////////////////////////////////////
void World::LoadEntities(sdf::ElementPtr _sdf, BasePtr _parent)
{
  if (_sdf->HasElement("light"))
  {
    sdf::ElementPtr childElem = _sdf->GetElement("light");
    while (childElem)
    {
      msgs::Light *lm = this->sceneMsg.add_light();
      lm->CopyFrom(msgs::LightFromSDF(childElem));

      childElem = childElem->GetNextElement("light");
    }
  }

  if (_sdf->HasElement("model"))
  {
    sdf::ElementPtr childElem = _sdf->GetElement("model");

    while (childElem)
    {
      this->LoadModel(childElem, _parent);

      // TODO : Put back in the ability to nest models. We should do this
      // without requiring a joint.

      childElem = childElem->GetNextElement("model");
    }
  }

  if (_sdf->HasElement("actor"))
  {
    sdf::ElementPtr childElem = _sdf->GetElement("actor");

    while (childElem)
    {
      this->LoadActor(childElem, _parent);

      childElem = childElem->GetNextElement("actor");
    }
  }

  if (_sdf->HasElement("road"))
  {
    sdf::ElementPtr childElem = _sdf->GetElement("road");
    while (childElem)
    {
      this->LoadRoad(childElem, _parent);
      childElem = childElem->GetNextElement("road");
    }
  }
}

//////////////////////////////////////////////////
unsigned int World::GetModelCount() const
{
  // Not all children of the root element are models. We have to iterate
  // through the children and count only the models.
  unsigned int result = 0;
  for (unsigned int i = 0; i < this->rootElement->GetChildCount(); i++)
    result += this->rootElement->GetChild(i)->HasType(Base::MODEL) ? 1 : 0;
  return result;
}

//////////////////////////////////////////////////
ModelPtr World::GetModel(unsigned int _index) const
{
  ModelPtr model;

  if (_index < this->rootElement->GetChildCount())
  {
    // Not all children of the root element are models. We have to iterate
    // through the children and count only the models.
    for (unsigned int i = 0, count = 0;
         i < this->rootElement->GetChildCount(); i++)
    {
      if (this->rootElement->GetChild(i)->HasType(Base::MODEL))
      {
        if (count == _index)
        {
          model = boost::shared_static_cast<Model>(
              this->rootElement->GetChild(i));
          break;
        }
        count++;
      }
    }

    if (!model)
      gzerr << "Unable to get model with index[" << _index << "]\n";
  }
  else
  {
    gzerr << "Given model index[" << _index << "] is out of range[0.."
          << this->rootElement->GetChildCount() << "]\n";
  }

  return model;
}

//////////////////////////////////////////////////
Model_V World::GetModels() const
{
  Model_V models;
  for (unsigned int i = 0; i < this->GetModelCount(); ++i)
    models.push_back(this->GetModel(i));

  return models;
}

//////////////////////////////////////////////////
void World::ResetTime()
{
  this->simTime = common::Time(0);
  this->pauseTime = common::Time(0);
  this->startTime = common::Time::GetWallTime();
  this->realTimeOffset = common::Time(0);
  this->iterations = 0;
}

//////////////////////////////////////////////////
void World::ResetEntities(Base::EntityType _type)
{
  this->rootElement->Reset(_type);
}

//////////////////////////////////////////////////
void World::Reset()
{
  bool currently_paused = this->IsPaused();
  this->SetPaused(true);

  {
    boost::recursive_mutex::scoped_lock(*this->worldUpdateMutex);

    this->ResetTime();
    this->ResetEntities(Base::BASE);
    for (std::vector<WorldPluginPtr>::iterator iter = this->plugins.begin();
        iter != this->plugins.end(); ++iter)
      (*iter)->Reset();
    this->physicsEngine->Reset();
  }

  this->SetPaused(currently_paused);
}

//////////////////////////////////////////////////
void World::OnStep()
{
  this->stepInc = 1;
}

//////////////////////////////////////////////////
void World::SetSelectedEntityCB(const std::string &_name)
{
  msgs::Selection msg;
  BasePtr base = this->GetByName(_name);
  EntityPtr ent = boost::shared_dynamic_cast<Entity>(base);

  // unselect selectedEntity
  if (this->selectedEntity)
  {
    msg.set_id(this->selectedEntity->GetId());
    msg.set_name(this->selectedEntity->GetScopedName());
    msg.set_selected(false);
    this->selectionPub->Publish(msg);

    this->selectedEntity->SetSelected(false);
  }

  // if a different entity is selected, show bounding box and SetSelected(true)
  if (ent && this->selectedEntity != ent)
  {
    // set selected entity to ent
    this->selectedEntity = ent;
    this->selectedEntity->SetSelected(true);

    msg.set_id(this->selectedEntity->GetId());
    msg.set_name(this->selectedEntity->GetScopedName());
    msg.set_selected(true);

    this->selectionPub->Publish(msg);
  }
  else
    this->selectedEntity.reset();
}

//////////////////////////////////////////////////
EntityPtr World::GetSelectedEntity() const
{
  return this->selectedEntity;
}

//////////////////////////////////////////////////
void World::PrintEntityTree()
{
  // Initialize all the entities
  for (unsigned int i = 0; i < this->rootElement->GetChildCount(); i++)
    this->rootElement->GetChild(i)->Print("");
}

//////////////////////////////////////////////////
gazebo::common::Time World::GetSimTime() const
{
  return this->simTime;
}

//////////////////////////////////////////////////
void World::SetSimTime(const common::Time &_t)
{
  this->simTime = _t;
}

//////////////////////////////////////////////////
gazebo::common::Time World::GetPauseTime() const
{
  return this->pauseTime;
}

//////////////////////////////////////////////////
gazebo::common::Time World::GetStartTime() const
{
  return this->startTime;
}

//////////////////////////////////////////////////
common::Time World::GetRealTime() const
{
  if (this->pause)
    return (this->pauseStartTime - this->startTime) - this->realTimeOffset;
  else
    return (common::Time::GetWallTime() - this->startTime) -
             this->realTimeOffset;
}

//////////////////////////////////////////////////
bool World::IsPaused() const
{
  return this->pause;
}

//////////////////////////////////////////////////
void World::SetPaused(bool _p)
{
  if (this->pause == _p)
    return;

  {
    boost::recursive_mutex::scoped_lock(*this->worldUpdateMutex);
    this->pause = _p;
  }

  if (_p)
    this->pauseStartTime = common::Time::GetWallTime();
  else
    this->realTimeOffset += common::Time::GetWallTime() - this->pauseStartTime;

  event::Events::pause(_p);
}

//////////////////////////////////////////////////
void World::OnFactoryMsg(ConstFactoryPtr &_msg)
{
  boost::recursive_mutex::scoped_lock lock(*this->receiveMutex);
  this->factoryMsgs.push_back(*_msg);
}

//////////////////////////////////////////////////
void World::OnLogControl(ConstLogControlPtr &_data)
{
  if (_data->has_base_path() && !_data->base_path().empty())
    common::LogRecord::Instance()->SetBasePath(_data->base_path());

  if (_data->has_start() && _data->start())
  {
    if (common::LogRecord::Instance()->GetPaused())
    {
      common::LogRecord::Instance()->Start("bz2");
    }
    else
    {
      common::LogRecord::Instance()->Start("bz2");
      common::LogRecord::Instance()->Add(this->GetName(), "state.log",
          boost::bind(&World::OnLog, this, _1));
    }
  }
  else if (_data->has_stop() && _data->stop())
  {
    common::LogRecord::Instance()->Stop();
  }
  else if (_data->has_paused())
  {
    common::LogRecord::Instance()->SetPaused(_data->paused());
  }

  // Output the new log status
  this->PublishLogStatus();
}

//////////////////////////////////////////////////
void World::OnControl(ConstWorldControlPtr &_data)
{
  if (_data->has_pause())
    this->SetPaused(_data->pause());

  if (_data->has_step())
    this->OnStep();

  if (_data->has_seed())
  {
    math::Rand::SetSeed(_data->seed());
    this->physicsEngine->SetSeed(_data->seed());
  }

  if (_data->has_reset())
  {
    this->needsReset = true;

    if (_data->reset().has_all() && _data->reset().all())
    {
        this->resetAll = true;
    }
    else
    {
      this->resetAll = false;

      if (_data->reset().has_time_only() && _data->reset().time_only())
        this->resetTimeOnly = true;

      if (_data->reset().has_model_only() && _data->reset().model_only())
        this->resetModelOnly = true;
    }
  }
}

//////////////////////////////////////////////////
void World::OnRequest(ConstRequestPtr &_msg)
{
  boost::recursive_mutex::scoped_lock lock(*this->receiveMutex);
  this->requestMsgs.push_back(*_msg);
}

//////////////////////////////////////////////////
void World::JointLog(ConstJointPtr &_msg)
{
  boost::recursive_mutex::scoped_lock lock(*this->receiveMutex);
  int i = 0;
  for (; i < this->sceneMsg.joint_size(); i++)
  {
    if (this->sceneMsg.joint(i).name() == _msg->name())
    {
      this->sceneMsg.mutable_joint(i)->CopyFrom(*_msg);
      break;
    }
  }

  if (i >= this->sceneMsg.joint_size())
  {
    msgs::Joint *newJoint = this->sceneMsg.add_joint();
    newJoint->CopyFrom(*_msg);
  }
}

//////////////////////////////////////////////////
void World::OnModelMsg(ConstModelPtr &_msg)
{
  boost::recursive_mutex::scoped_lock lock(*this->receiveMutex);
  this->modelMsgs.push_back(*_msg);
}

//////////////////////////////////////////////////
void World::BuildSceneMsg(msgs::Scene &_scene, BasePtr _entity)
{
  if (_entity)
  {
    if (_entity->HasType(Entity::MODEL))
    {
      msgs::Model *modelMsg = _scene.add_model();
      boost::shared_static_cast<Model>(_entity)->FillMsg(*modelMsg);
    }

    for (unsigned int i = 0; i < _entity->GetChildCount(); ++i)
    {
      this->BuildSceneMsg(_scene, _entity->GetChild(i));
    }
  }
}


//////////////////////////////////////////////////
/*void World::ModelUpdateTBB()
{
  tbb::parallel_for(tbb::blocked_range<size_t>(0, this->models.size(), 10),
      ModelUpdate_TBB(&this->models));
}*/

//////////////////////////////////////////////////
void World::ModelUpdateSingleLoop()
{
  // Update all the models
  for (unsigned int i = 0; i < this->rootElement->GetChildCount(); i++)
    this->rootElement->GetChild(i)->Update();
}


//////////////////////////////////////////////////
void World::LoadPlugins()
{
  // Load the plugins
  if (this->sdf->HasElement("plugin"))
  {
    sdf::ElementPtr pluginElem = this->sdf->GetElement("plugin");
    while (pluginElem)
    {
      this->LoadPlugin(pluginElem);
      pluginElem = pluginElem->GetNextElement("plugin");
    }
  }

  // Load the plugins for all the models
  for (unsigned int i = 0; i < this->rootElement->GetChildCount(); i++)
  {
    if (this->rootElement->GetChild(i)->HasType(Base::MODEL))
    {
      ModelPtr model = boost::shared_static_cast<Model>(
          this->rootElement->GetChild(i));
      model->LoadPlugins();
    }
  }

  for (std::vector<WorldPluginPtr>::iterator iter = this->plugins.begin();
       iter != this->plugins.end(); ++iter)
  {
    (*iter)->Init();
  }
}

//////////////////////////////////////////////////
void World::LoadPlugin(const std::string &_filename,
                       const std::string &_name,
                       sdf::ElementPtr _sdf)
{
  gazebo::WorldPluginPtr plugin = gazebo::WorldPlugin::Create(_filename,
                                                              _name);

  if (plugin)
  {
    if (plugin->GetType() != WORLD_PLUGIN)
    {
      gzerr << "World[" << this->GetName() << "] is attempting to load "
            << "a plugin, but detected an incorrect plugin type. "
            << "Plugin filename[" << _filename << "] name[" << _name << "]\n";
      return;
    }
    plugin->Load(shared_from_this(), _sdf);
    this->plugins.push_back(plugin);

    if (this->initialized)
      plugin->Init();
  }
}

//////////////////////////////////////////////////
void World::RemovePlugin(const std::string &_name)
{
  std::vector<WorldPluginPtr>::iterator iter;
  for (iter = this->plugins.begin(); iter != this->plugins.end(); ++iter)
  {
    if ((*iter)->GetHandle() == _name)
    {
      this->plugins.erase(iter);
      break;
    }
  }
}

//////////////////////////////////////////////////
void World::LoadPlugin(sdf::ElementPtr _sdf)
{
  std::string pluginName = _sdf->GetValueString("name");
  std::string filename = _sdf->GetValueString("filename");
  this->LoadPlugin(filename, pluginName, _sdf);
}

//////////////////////////////////////////////////
void World::ProcessEntityMsgs()
{
  std::list<std::string>::iterator iter;
  for (iter = this->deleteEntity.begin();
       iter != this->deleteEntity.end(); ++iter)
  {
    // Remove all the dirty poses from the delete entity.
    for (std::list<Entity*>::iterator iter2 = this->dirtyPoses.begin();
         iter2 != this->dirtyPoses.end();)
    {
      if ((*iter2)->GetName() == *iter ||
          (*iter2)->GetParent()->GetName() == *iter)
      {
        this->dirtyPoses.erase(iter2++);
      }
      else
        ++iter2;
    }

    if (this->sdf->HasElement("model"))
    {
      sdf::ElementPtr childElem = this->sdf->GetElement("model");
      while (childElem && childElem->GetValueString("name") != (*iter))
        childElem = childElem->GetNextElement("model");
      if (childElem)
        this->sdf->RemoveChild(childElem);
    }

    this->rootElement->RemoveChild((*iter));
  }

  if (this->deleteEntity.size() > 0)
  {
    this->EnableAllModels();
    this->deleteEntity.clear();
  }
}

//////////////////////////////////////////////////
void World::ProcessRequestMsgs()
{
  msgs::Response response;

  std::list<msgs::Request>::iterator iter;
  for (iter = this->requestMsgs.begin();
       iter != this->requestMsgs.end(); ++iter)
  {
    bool send = true;
    response.set_id((*iter).id());
    response.set_request((*iter).request());
    response.set_response("success");

    if ((*iter).request() == "entity_list")
    {
      msgs::Model_V modelVMsg;

      for (unsigned int i = 0; i < this->rootElement->GetChildCount(); ++i)
      {
        BasePtr entity = this->rootElement->GetChild(i);
        if (entity->HasType(Base::MODEL))
        {
          msgs::Model *modelMsg = modelVMsg.add_models();
          ModelPtr model = boost::shared_dynamic_cast<Model>(entity);
          model->FillMsg(*modelMsg);
        }
      }

      response.set_type(modelVMsg.GetTypeName());
      std::string *serializedData = response.mutable_serialized_data();
      modelVMsg.SerializeToString(serializedData);
    }
    else if ((*iter).request() == "entity_delete")
    {
      this->deleteEntity.push_back((*iter).data());
    }
    else if ((*iter).request() == "entity_info")
    {
      BasePtr entity = this->rootElement->GetByName((*iter).data());
      if (entity)
      {
        if (entity->HasType(Base::MODEL))
        {
          msgs::Model modelMsg;
          ModelPtr model = boost::shared_dynamic_cast<Model>(entity);
          model->FillMsg(modelMsg);

          std::string *serializedData = response.mutable_serialized_data();
          modelMsg.SerializeToString(serializedData);
          response.set_type(modelMsg.GetTypeName());
        }
        else if (entity->HasType(Base::LINK))
        {
          msgs::Link linkMsg;
          LinkPtr link = boost::shared_dynamic_cast<Link>(entity);
          link->FillMsg(linkMsg);

          std::string *serializedData = response.mutable_serialized_data();
          linkMsg.SerializeToString(serializedData);
          response.set_type(linkMsg.GetTypeName());
        }
        else if (entity->HasType(Base::COLLISION))
        {
          msgs::Collision collisionMsg;
          CollisionPtr collision =
            boost::shared_dynamic_cast<Collision>(entity);
          collision->FillMsg(collisionMsg);

          std::string *serializedData = response.mutable_serialized_data();
          collisionMsg.SerializeToString(serializedData);
          response.set_type(collisionMsg.GetTypeName());
        }
        else if (entity->HasType(Base::JOINT))
        {
          msgs::Joint jointMsg;
          JointPtr joint = boost::shared_dynamic_cast<Joint>(entity);
          joint->FillMsg(jointMsg);

          std::string *serializedData = response.mutable_serialized_data();
          jointMsg.SerializeToString(serializedData);
          response.set_type(jointMsg.GetTypeName());
        }
      }
      else
      {
        response.set_type("error");
        response.set_response("nonexistant");
      }
    }
    else if ((*iter).request() == "world_sdf")
    {
      msgs::GzString msg;
      this->UpdateStateSDF();
      std::ostringstream stream;
      stream << "<?xml version='1.0'?>\n"
             << "<sdf version='" << SDF_VERSION << "'>\n"
             << this->sdf->ToString("")
             << "</sdf>";

      msg.set_data(stream.str());

      std::string *serializedData = response.mutable_serialized_data();
      msg.SerializeToString(serializedData);
      response.set_type(msg.GetTypeName());
    }
    else if ((*iter).request() == "scene_info")
    {
      this->sceneMsg.clear_model();
      this->BuildSceneMsg(this->sceneMsg, this->rootElement);

      std::string *serializedData = response.mutable_serialized_data();
      this->sceneMsg.SerializeToString(serializedData);
      response.set_type(sceneMsg.GetTypeName());
    }
    else
      send = false;

    if (send)
    {
      this->responsePub->Publish(response);
    }
  }

  this->requestMsgs.clear();
}

//////////////////////////////////////////////////
void World::ProcessModelMsgs()
{
  std::list<msgs::Model>::iterator iter;
  for (iter = this->modelMsgs.begin();
       iter != this->modelMsgs.end(); ++iter)
  {
    ModelPtr model;
    if ((*iter).has_id())
      model = this->GetModelById((*iter).id());
    else
      model = this->GetModel((*iter).name());

    if (!model)
      gzerr << "Unable to find model["
            << (*iter).name() << "] Id[" << (*iter).id() << "]\n";
    else
    {
      model->ProcessMsg(*iter);

      // Let all other subscribers know about the change
      msgs::Model msg;
      model->FillMsg(msg);
      this->modelPub->Publish(msg);
    }
  }
  if (this->modelMsgs.size())
  {
    this->EnableAllModels();
    this->modelMsgs.clear();
  }
}

//////////////////////////////////////////////////
void World::ProcessFactoryMsgs()
{
  std::list<msgs::Factory>::iterator iter;

  for (iter = this->factoryMsgs.begin();
       iter != this->factoryMsgs.end(); ++iter)
  {
    this->factorySDF->root->ClearElements();

    if ((*iter).has_sdf() && !(*iter).sdf().empty())
    {
      // SDF Parsing happens here
      if (!sdf::readString((*iter).sdf(), factorySDF))
      {
        gzerr << "Unable to read sdf string[" << (*iter).sdf() << "]\n";
        continue;
      }
    }
    else if ((*iter).has_sdf_filename() && !(*iter).sdf_filename().empty())
    {
      std::string filename = common::ModelDatabase::Instance()->GetModelFile(
          (*iter).sdf_filename());

      if (!sdf::readFile(filename, factorySDF))
      {
        gzerr << "Unable to read sdf file.\n";
        continue;
      }
    }
    else if ((*iter).has_clone_model_name())
    {
      ModelPtr model = this->GetModel((*iter).clone_model_name());
      if (!model)
      {
        gzerr << "Unable to clone model[" << (*iter).clone_model_name()
              << "]. Model not found.\n";
        continue;
      }

      factorySDF->root->InsertElement(model->GetSDF()->Clone());

      std::string newName = model->GetName() + "_clone";
      int i = 0;
      while (this->GetModel(newName))
      {
        newName = model->GetName() + "_clone_" +
                  boost::lexical_cast<std::string>(i);
        i++;
      }

      factorySDF->root->GetElement("model")->GetAttribute("name")->Set(newName);
    }
    else
    {
      gzerr << "Unable to load sdf from factory message."
            << "No SDF or SDF filename specified.\n";
      continue;
    }

    if ((*iter).has_edit_name())
    {
      BasePtr base = this->rootElement->GetByName((*iter).edit_name());
      if (base)
      {
        sdf::ElementPtr elem;
        if (factorySDF->root->GetName() == "sdf")
          elem = factorySDF->root->GetFirstElement();
        else
          elem = factorySDF->root;

        base->UpdateParameters(elem);
      }
    }
    else
    {
      bool isActor = false;
      bool isModel = false;
      bool isLight = false;

      sdf::ElementPtr elem = factorySDF->root;

      if (elem->HasElement("world"))
        elem = elem->GetElement("world");

      if (elem->HasElement("model"))
      {
        elem = elem->GetElement("model");
        isModel = true;
      }
      else if (elem->HasElement("light"))
      {
        elem = elem->GetElement("light");
        isLight = true;
      }
      else if (elem->HasElement("actor"))
      {
        elem = elem->GetElement("actor");
        isActor = true;
      }
      else
      {
        gzerr << "Unable to find a model, light, or actor in:\n";
        factorySDF->root->PrintValues("");
        continue;
      }

      if (!elem)
      {
        gzerr << "Invalid SDF:";
        factorySDF->root->PrintValues("");
        continue;
      }

      elem->SetParent(this->sdf);
      elem->GetParent()->InsertElement(elem);
      if ((*iter).has_pose())
        elem->GetElement("pose")->Set(msgs::Convert((*iter).pose()));

      if (isActor)
      {
        ActorPtr actor = this->LoadActor(elem, this->rootElement);
        actor->Init();
      }
      else if (isModel)
      {
        ModelPtr model = this->LoadModel(elem, this->rootElement);
        model->Init();

        model->LoadPlugins();
      }
      else if (isLight)
      {
        /// \TODO: Current broken. See Issue #67.
        msgs::Light *lm = this->sceneMsg.add_light();
        lm->CopyFrom(msgs::LightFromSDF(elem));

        this->lightPub->Publish(*lm);
      }
    }
  }

  this->factoryMsgs.clear();
}

//////////////////////////////////////////////////
ModelPtr World::GetModelBelowPoint(const math::Vector3 &_pt)
{
  ModelPtr model;
  EntityPtr entity = this->GetEntityBelowPoint(_pt);

  if (entity)
    model = entity->GetParentModel();
  else
    gzerr << "Unable to find entity below point[" << _pt << "]\n";

  return model;
}

//////////////////////////////////////////////////
EntityPtr World::GetEntityBelowPoint(const math::Vector3 &_pt)
{
  std::string entityName;
  double dist;
  math::Vector3 end;

  end = _pt;
  end.z -= 1000;

  this->physicsEngine->InitForThread();
  this->testRay->SetPoints(_pt, end);
  this->testRay->GetIntersection(dist, entityName);
  return this->GetEntity(entityName);
}

//////////////////////////////////////////////////
void World::SetState(const WorldState &_state)
{
  this->SetSimTime(_state.GetSimTime());

  for (unsigned int i = 0; i < _state.GetModelStateCount(); ++i)
  {
    ModelState modelState = _state.GetModelState(i);
    ModelPtr model = this->GetModel(modelState.GetName());
    if (model)
      model->SetState(modelState);
    else
      gzerr << "Unable to find model[" << modelState.GetName() << "]\n";
  }
}

//////////////////////////////////////////////////
void World::InsertModelFile(const std::string &_sdfFilename)
{
  boost::recursive_mutex::scoped_lock lock(*this->receiveMutex);
  msgs::Factory msg;
  msg.set_sdf_filename(_sdfFilename);
  this->factoryMsgs.push_back(msg);
}

//////////////////////////////////////////////////
void World::InsertModelSDF(const sdf::SDF &_sdf)
{
  boost::recursive_mutex::scoped_lock lock(*this->receiveMutex);
  msgs::Factory msg;
  msg.set_sdf(_sdf.ToString());
  this->factoryMsgs.push_back(msg);
}

//////////////////////////////////////////////////
void World::InsertModelString(const std::string &_sdfString)
{
  boost::recursive_mutex::scoped_lock lock(*this->receiveMutex);
  msgs::Factory msg;
  msg.set_sdf(_sdfString);
  this->factoryMsgs.push_back(msg);
}

//////////////////////////////////////////////////
std::string World::StripWorldName(const std::string &_name) const
{
  if (_name.find(this->GetName() + "::") == 0)
    return _name.substr(this->GetName().size() + 2);
  else
    return _name;
}

//////////////////////////////////////////////////
void World::EnableAllModels()
{
  for (unsigned int i = 0; i < this->GetModelCount(); ++i)
    this->GetModel(i)->SetEnabled(true);
}

//////////////////////////////////////////////////
void World::DisableAllModels()
{
  for (unsigned int i = 0; i < this->GetModelCount(); ++i)
    this->GetModel(i)->SetEnabled(false);
}

//////////////////////////////////////////////////
void World::UpdateStateSDF()
{
  this->sdf->Update();
  sdf::ElementPtr stateElem = this->sdf->GetElement("state");
  stateElem->ClearElements();

  this->prevStates[(this->stateToggle + 1) % 2].FillSDF(stateElem);
}

//////////////////////////////////////////////////
bool World::OnLog(std::ostringstream &_stream)
{
  // Save the entire state when its the first call to OnLog.
  if (common::LogRecord::Instance()->GetFirstUpdate())
  {
    this->UpdateStateSDF();
    _stream << "<sdf version ='";
    _stream << SDF_VERSION;
    _stream << "'>\n";
    _stream << this->sdf->ToString("");
    _stream << "</sdf>\n";
  }
  else if (this->states.size() >= 1)
  {
    // Get the difference from the previous state.
    _stream << "<sdf version='" << SDF_VERSION << "'>";
    _stream << this->states[0];
    _stream << "</sdf>";
    this->states.pop_front();
  }

  return true;
}

//////////////////////////////////////////////////
void World::ProcessMessages()
{
  boost::recursive_mutex::scoped_lock lock(*this->receiveMutex);
  msgs::Pose *poseMsg;

  if (this->posePub && this->posePub->HasConnections() &&
      this->publishModelPoses.size() > 0)
  {
    msgs::Pose_V msg;

    for (std::set<std::string>::iterator iter =
         this->publishModelPoses.begin();
         iter != this->publishModelPoses.end(); ++iter)
    {
      ModelPtr model = this->GetModel(*iter);

      // It's possible that the model was deleted somewhere along the line.
      // So check to make sure we get a valid model pointer.
      if (!model)
        continue;

      poseMsg = msg.add_pose();

      // Publish the model's relative pose
      poseMsg->set_name(model->GetScopedName());
      msgs::Set(poseMsg, model->GetRelativePose());

      // Publish each of the model's children relative poses
      Link_V links = model->GetLinks();
      for (Link_V::iterator linkIter = links.begin();
           linkIter != links.end(); ++linkIter)
      {
        poseMsg = msg.add_pose();
        poseMsg->set_name((*linkIter)->GetScopedName());
        msgs::Set(poseMsg, (*linkIter)->GetRelativePose());
      }
    }
    this->posePub->Publish(msg);
  }
  this->publishModelPoses.clear();

  if (common::Time::GetWallTime() - this->prevProcessMsgsTime >
      this->processMsgsPeriod)
  {
    this->ProcessEntityMsgs();
    this->ProcessRequestMsgs();
    this->ProcessFactoryMsgs();
    this->ProcessModelMsgs();
    this->prevProcessMsgsTime = common::Time::GetWallTime();
  }
}

//////////////////////////////////////////////////
void World::PublishWorldStats()
{
  msgs::Set(this->worldStatsMsg.mutable_sim_time(), this->GetSimTime());
  msgs::Set(this->worldStatsMsg.mutable_real_time(), this->GetRealTime());
  msgs::Set(this->worldStatsMsg.mutable_pause_time(), this->GetPauseTime());
  this->worldStatsMsg.set_iterations(this->iterations);
  this->worldStatsMsg.set_paused(this->IsPaused());

  this->statPub->Publish(this->worldStatsMsg);
  this->prevStatTime = common::Time::GetWallTime();
}

//////////////////////////////////////////////////
bool World::IsLoaded() const
{
  return this->loaded;
}

//////////////////////////////////////////////////
void World::PublishModelPose(const std::string &_modelName)
{
  boost::recursive_mutex::scoped_lock lock(*this->receiveMutex);

  // Only add if the model name is not in the list
  this->publishModelPoses.insert(_modelName);
}

//////////////////////////////////////////////////
void World::PublishLogStatus()
{
  msgs::LogStatus msg;
  unsigned int size = 0;

  // Set the time of the status message
  msgs::Set(msg.mutable_sim_time(),
            common::LogRecord::Instance()->GetRunTime());

  // Set the log recording base path name
  msg.mutable_log_file()->set_base_path(
      common::LogRecord::Instance()->GetBasePath());

  // Get the full name of the log file
  msg.mutable_log_file()->set_full_path(
    common::LogRecord::Instance()->GetFilename(this->GetName()));

  // Set the URI of th log file
  msg.mutable_log_file()->set_uri(transport::Connection::GetLocalHostname());

  // Get the size of the log file
  size = common::LogRecord::Instance()->GetFileSize(this->GetName());

  if (size < 1000)
    msg.mutable_log_file()->set_size_units(msgs::LogStatus::LogFile::BYTES);
  else if (size < 1e6)
  {
    msg.mutable_log_file()->set_size(size / 1.0e3);
    msg.mutable_log_file()->set_size_units(msgs::LogStatus::LogFile::K_BYTES);
  }
  else if (size < 1e9)
  {
    msg.mutable_log_file()->set_size(size / 1.0e6);
    msg.mutable_log_file()->set_size_units(msgs::LogStatus::LogFile::M_BYTES);
  }
  else
  {
    msg.mutable_log_file()->set_size(size / 1.0e9);
    msg.mutable_log_file()->set_size_units(msgs::LogStatus::LogFile::G_BYTES);
  }

  this->logStatusPub->Publish(msg);
}
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.