SceneLoader.cpp 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009
  1. #include "Base.h"
  2. #include "Game.h"
  3. #include "Bundle.h"
  4. #include "SceneLoader.h"
  5. namespace gameplay
  6. {
  7. // Utility functions (shared with Properties).
  8. extern void calculateNamespacePath(const std::string& urlString, std::string& fileString, std::vector<std::string>& namespacePath);
  9. extern Properties* getPropertiesFromNamespacePath(Properties* properties, const std::vector<std::string>& namespacePath);
  10. std::map<std::string, Properties*> SceneLoader::_propertiesFromFile;
  11. std::map<std::string, Properties*> SceneLoader::_properties;
  12. std::vector<SceneLoader::SceneAnimation> SceneLoader::_animations;
  13. std::vector<SceneLoader::SceneNode> SceneLoader::_sceneNodes;
  14. std::string SceneLoader::_gpbPath;
  15. std::string SceneLoader::_path;
  16. Scene* SceneLoader::load(const char* url)
  17. {
  18. // Get the file part of the url that we are loading the scene from.
  19. std::string urlStr = url ? url : "";
  20. std::string id;
  21. splitURL(urlStr, &_path, &id);
  22. // Load the scene properties from file.
  23. Properties* properties = Properties::create(url);
  24. if (properties == NULL)
  25. {
  26. GP_ERROR("Failed to load scene file '%s'.", url);
  27. return NULL;
  28. }
  29. // Check if the properties object is valid and has a valid namespace.
  30. Properties* sceneProperties = (strlen(properties->getNamespace()) > 0) ? properties : properties->getNextNamespace();
  31. if (!sceneProperties || !(strcmp(sceneProperties->getNamespace(), "scene") == 0))
  32. {
  33. GP_ERROR("Failed to load scene from properties object: must be non-null object and have namespace equal to 'scene'.");
  34. SAFE_DELETE(properties);
  35. return NULL;
  36. }
  37. // Get the path to the main GPB.
  38. _gpbPath = sceneProperties->getString("path");
  39. // Build the node URL/property and animation reference tables and load the referenced files/store the inline properties objects.
  40. buildReferenceTables(sceneProperties);
  41. loadReferencedFiles();
  42. // Load the main scene data from GPB and apply the global scene properties.
  43. Scene* scene = loadMainSceneData(sceneProperties);
  44. if (!scene)
  45. {
  46. GP_ERROR("Failed to load main scene from bundle.");
  47. SAFE_DELETE(properties);
  48. return NULL;
  49. }
  50. // First apply the node url properties. Following that,
  51. // apply the normal node properties and create the animations.
  52. // We apply physics properties after all other node properties
  53. // so that the transform (SRT) properties get applied before
  54. // processing physics collision objects.
  55. applyNodeUrls(scene);
  56. applyNodeProperties(scene, sceneProperties,
  57. SceneNodeProperty::AUDIO |
  58. SceneNodeProperty::MATERIAL |
  59. SceneNodeProperty::PARTICLE |
  60. SceneNodeProperty::ROTATE |
  61. SceneNodeProperty::SCALE |
  62. SceneNodeProperty::TRANSLATE |
  63. SceneNodeProperty::TRANSPARENT |
  64. SceneNodeProperty::DYNAMIC);
  65. applyNodeProperties(scene, sceneProperties, SceneNodeProperty::COLLISION_OBJECT);
  66. createAnimations(scene);
  67. // Find the physics properties object.
  68. Properties* physics = NULL;
  69. Properties* ns = NULL;
  70. sceneProperties->rewind();
  71. while (true)
  72. {
  73. Properties* ns = sceneProperties->getNextNamespace();
  74. if (ns == NULL || strcmp(ns->getNamespace(), "physics") == 0)
  75. {
  76. physics = ns;
  77. break;
  78. }
  79. }
  80. // Load physics properties and constraints.
  81. if (physics)
  82. loadPhysics(physics, scene);
  83. // Clean up all loaded properties objects.
  84. _properties.clear();
  85. std::map<std::string, Properties*>::iterator iter = _propertiesFromFile.begin();
  86. for (; iter != _propertiesFromFile.end(); iter++)
  87. {
  88. SAFE_DELETE(iter->second);
  89. }
  90. // Clean up the .scene file's properties object.
  91. SAFE_DELETE(properties);
  92. // Clear all temporary data stores.
  93. _properties.clear();
  94. _animations.clear();
  95. _sceneNodes.clear();
  96. return scene;
  97. }
  98. void SceneLoader::addSceneAnimation(const char* animationID, const char* targetID, const char* url)
  99. {
  100. std::string urlStr = url ? url : "";
  101. // If there is a file that needs to be loaded later, add an
  102. // empty entry to the properties table to signify it.
  103. if (urlStr.length() > 0 && _properties.count(urlStr) == 0)
  104. _properties[urlStr] = NULL;
  105. // Add the animation to the list of animations to be resolved later.
  106. _animations.push_back(SceneAnimation(animationID, targetID, urlStr));
  107. }
  108. void SceneLoader::addSceneNodeProperty(SceneNode& sceneNode, SceneNodeProperty::Type type, const char* url, int index)
  109. {
  110. std::string urlStr = url ? url : "";
  111. // If there is a non-GPB file that needs to be loaded later, add an
  112. // empty entry to the properties table to signify it.
  113. if (urlStr.length() > 0 && urlStr.find(".") != urlStr.npos && urlStr.find(".gpb") == urlStr.npos && _properties.count(urlStr) == 0)
  114. _properties[urlStr] = NULL;
  115. // Add the node property to the list of node properties to be resolved later.
  116. sceneNode._properties.push_back(SceneNodeProperty(type, urlStr, index));
  117. }
  118. void SceneLoader::applyNodeProperties(const Scene* scene, const Properties* sceneProperties, unsigned int typeFlags)
  119. {
  120. for (unsigned int i = 0, ncount = _sceneNodes.size(); i < ncount; ++i)
  121. {
  122. SceneNode& sceneNode = _sceneNodes[i];
  123. GP_ASSERT(sceneNode._nodeID);
  124. // Find the node matching the specified ID.
  125. Node* node = scene->findNode(sceneNode._nodeID);
  126. if (!node)
  127. {
  128. GP_ERROR("Failed to set property for node '%s', which does not exist in the scene.", sceneNode._nodeID);
  129. continue;
  130. }
  131. for (unsigned int j = 0, pcount = sceneNode._properties.size(); j < pcount; ++j)
  132. {
  133. SceneNodeProperty& snp = sceneNode._properties[j];
  134. if (typeFlags & snp._type)
  135. applyNodeProperty(sceneNode, node, sceneProperties, snp, scene);
  136. }
  137. }
  138. }
  139. void SceneLoader::applyNodeProperty(SceneNode& sceneNode, Node* node, const Properties* sceneProperties, const SceneNodeProperty& snp, const Scene* scene)
  140. {
  141. if (snp._type == SceneNodeProperty::AUDIO ||
  142. snp._type == SceneNodeProperty::MATERIAL ||
  143. snp._type == SceneNodeProperty::PARTICLE ||
  144. snp._type == SceneNodeProperty::COLLISION_OBJECT)
  145. {
  146. // Check to make sure the referenced properties object was loaded properly.
  147. Properties* p = _properties[snp._url];
  148. if (!p)
  149. {
  150. GP_ERROR("The referenced node data at url '%s' failed to load.", snp._url.c_str());
  151. return;
  152. }
  153. // If the URL didn't specify a particular namespace within the file, pick the first one.
  154. p = (strlen(p->getNamespace()) > 0) ? p : p->getNextNamespace();
  155. switch (snp._type)
  156. {
  157. case SceneNodeProperty::AUDIO:
  158. {
  159. AudioSource* audioSource = AudioSource::create(p);
  160. node->setAudioSource(audioSource);
  161. SAFE_RELEASE(audioSource);
  162. break;
  163. }
  164. case SceneNodeProperty::MATERIAL:
  165. if (!node->getModel())
  166. {
  167. GP_ERROR("Attempting to set a material on node '%s', which has no model.", sceneNode._nodeID);
  168. return;
  169. }
  170. else
  171. {
  172. Material* material = Material::create(p);
  173. node->getModel()->setMaterial(material, snp._index);
  174. SAFE_RELEASE(material);
  175. }
  176. break;
  177. case SceneNodeProperty::PARTICLE:
  178. {
  179. ParticleEmitter* particleEmitter = ParticleEmitter::create(p);
  180. node->setParticleEmitter(particleEmitter);
  181. SAFE_RELEASE(particleEmitter);
  182. break;
  183. }
  184. case SceneNodeProperty::COLLISION_OBJECT:
  185. {
  186. // Check to make sure the type of the namespace used to load the physics collision object is correct.
  187. if (snp._type == SceneNodeProperty::COLLISION_OBJECT && strcmp(p->getNamespace(), "collisionObject") != 0)
  188. {
  189. GP_ERROR("Attempting to set a physics collision object on a node using a '%s' definition.", p->getNamespace());
  190. return;
  191. }
  192. else
  193. {
  194. // If the scene file specifies a rigid body model, use it for creating the collision object.
  195. Properties* np = sceneProperties->getNamespace(sceneNode._nodeID);
  196. const char* name = NULL;
  197. if (np && (name = np->getString("rigidBodyModel")))
  198. {
  199. GP_ASSERT(scene);
  200. Node* modelNode = scene->findNode(name);
  201. if (!modelNode)
  202. {
  203. GP_ERROR("Node '%s' does not exist; attempting to use its model for collision object creation.", name);
  204. return;
  205. }
  206. else
  207. {
  208. if (!modelNode->getModel())
  209. {
  210. GP_ERROR("Node '%s' does not have a model; attempting to use its model for collision object creation.", name);
  211. }
  212. else
  213. {
  214. // Temporarily set rigidBody model on model so it's used during collision object creation.
  215. Model* model = node->getModel();
  216. // Up ref count to prevent node from releasing the model when we swap it.
  217. if (model)
  218. model->addRef();
  219. // Create collision object with new rigidBodyModel set.
  220. node->setModel(modelNode->getModel());
  221. node->setCollisionObject(p);
  222. // Restore original model.
  223. node->setModel(model);
  224. // Decrement temporarily added reference.
  225. if (model)
  226. model->release();
  227. }
  228. }
  229. }
  230. else
  231. node->setCollisionObject(p);
  232. }
  233. break;
  234. }
  235. default:
  236. GP_ERROR("Unsupported node property type (%d).", snp._type);
  237. break;
  238. }
  239. }
  240. else
  241. {
  242. // Handle scale, rotate and translate.
  243. Properties* np = sceneProperties->getNamespace(sceneNode._nodeID);
  244. const char* name = NULL;
  245. switch (snp._type)
  246. {
  247. case SceneNodeProperty::TRANSLATE:
  248. {
  249. Vector3 t;
  250. if (np && np->getVector3("translate", &t))
  251. node->setTranslation(t);
  252. break;
  253. }
  254. case SceneNodeProperty::ROTATE:
  255. {
  256. Quaternion r;
  257. if (np && np->getQuaternionFromAxisAngle("rotate", &r))
  258. node->setRotation(r);
  259. break;
  260. }
  261. case SceneNodeProperty::SCALE:
  262. {
  263. Vector3 s;
  264. if (np && np->getVector3("scale", &s))
  265. node->setScale(s);
  266. break;
  267. }
  268. case SceneNodeProperty::TRANSPARENT:
  269. {
  270. node->setTransparent(true);
  271. break;
  272. }
  273. case SceneNodeProperty::DYNAMIC:
  274. {
  275. node->setDynamic(true);
  276. break;
  277. }
  278. default:
  279. GP_ERROR("Unsupported node property type (%d).", snp._type);
  280. break;
  281. }
  282. }
  283. }
  284. void SceneLoader::applyNodeUrls(Scene* scene)
  285. {
  286. GP_ASSERT(scene);
  287. // Apply all URL node properties so that when we go to apply
  288. // the other node properties, the node is in the scene.
  289. for (unsigned int i = 0, ncount = _sceneNodes.size(); i < ncount; ++i)
  290. {
  291. SceneNode& sceneNode = _sceneNodes[i];
  292. // Iterate backwards over the properties list so we can remove properties as we go
  293. // without danger of indexing out of bounds.
  294. for (int j = sceneNode._properties.size() - 1; j >= 0; --j)
  295. {
  296. SceneNodeProperty& snp = sceneNode._properties[j];
  297. if (snp._type != SceneNodeProperty::URL)
  298. continue;
  299. std::string file;
  300. std::string id;
  301. splitURL(snp._url, &file, &id);
  302. if (file.empty())
  303. {
  304. // The node is from the main GPB and should just be renamed.
  305. // TODO: Should we do all nodes with this case first to allow users to stitch in nodes with
  306. // IDs equal to IDs that were in the original GPB file but were changed in the scene file?
  307. Node* node = scene->findNode(id.c_str());
  308. if (node)
  309. {
  310. node->setId(sceneNode._nodeID);
  311. }
  312. else
  313. {
  314. GP_ERROR("Could not find node '%s' in main scene GPB file.", id.c_str());
  315. }
  316. }
  317. else
  318. {
  319. // An external file was referenced, so load the node from file and then insert it into the scene with the new ID.
  320. // TODO: Revisit this to determine if we should cache Bundle objects for the duration of the scene
  321. // load to prevent constantly creating/destroying the same externally referenced bundles each time
  322. // a url with a file is encountered.
  323. Bundle* tmpBundle = Bundle::create(file.c_str());
  324. if (tmpBundle)
  325. {
  326. Node* node = tmpBundle->loadNode(id.c_str(), scene);
  327. if (node)
  328. {
  329. node->setId(sceneNode._nodeID);
  330. scene->addNode(node);
  331. SAFE_RELEASE(node);
  332. }
  333. else
  334. {
  335. GP_ERROR("Could not load node '%s' from GPB file '%s'.", id.c_str(), file.c_str());
  336. }
  337. SAFE_RELEASE(tmpBundle);
  338. }
  339. else
  340. {
  341. GP_ERROR("Failed to load GPB file '%s' for node stitching.", file.c_str());
  342. }
  343. }
  344. // Remove the node property since we are done applying it.
  345. sceneNode._properties.erase(sceneNode._properties.begin() + j);
  346. }
  347. }
  348. }
  349. void SceneLoader::buildReferenceTables(Properties* sceneProperties)
  350. {
  351. // Go through the child namespaces of the scene.
  352. Properties* ns;
  353. const char* name = NULL;
  354. while ((ns = sceneProperties->getNextNamespace()) != NULL)
  355. {
  356. if (strcmp(ns->getNamespace(), "node") == 0)
  357. {
  358. if (strlen(ns->getId()) == 0)
  359. {
  360. GP_ERROR("Attempting to load a node without an ID.");
  361. continue;
  362. }
  363. // Add a SceneNode to the end of the list.
  364. _sceneNodes.resize(_sceneNodes.size() + 1);
  365. SceneNode& sceneNode = _sceneNodes[_sceneNodes.size()-1];
  366. sceneNode._nodeID = ns->getId();
  367. // Parse the node's sub-namespaces.
  368. Properties* subns;
  369. std::string propertyUrl = _path + "#" + ns->getId() + "/";
  370. while ((subns = ns->getNextNamespace()) != NULL)
  371. {
  372. if (strcmp(subns->getNamespace(), "audio") == 0)
  373. {
  374. propertyUrl += "audio/" + std::string(subns->getId());
  375. addSceneNodeProperty(sceneNode, SceneNodeProperty::AUDIO, propertyUrl.c_str());
  376. _properties[propertyUrl] = subns;
  377. }
  378. else if (strcmp(subns->getNamespace(), "material") == 0)
  379. {
  380. propertyUrl += "material/" + std::string(subns->getId());
  381. addSceneNodeProperty(sceneNode, SceneNodeProperty::MATERIAL, propertyUrl.c_str());
  382. _properties[propertyUrl] = subns;
  383. }
  384. else if (strcmp(subns->getNamespace(), "particle") == 0)
  385. {
  386. propertyUrl += "particle/" + std::string(subns->getId());
  387. addSceneNodeProperty(sceneNode, SceneNodeProperty::PARTICLE, propertyUrl.c_str());
  388. _properties[propertyUrl] = subns;
  389. }
  390. else if (strcmp(subns->getNamespace(), "collisionObject") == 0)
  391. {
  392. propertyUrl += "collisionObject/" + std::string(subns->getId());
  393. addSceneNodeProperty(sceneNode, SceneNodeProperty::COLLISION_OBJECT, propertyUrl.c_str());
  394. _properties[propertyUrl] = subns;
  395. }
  396. else
  397. {
  398. GP_ERROR("Unsupported child namespace '%s' of 'node' namespace.", subns->getNamespace());
  399. }
  400. }
  401. // Parse the node's attributes.
  402. while ((name = ns->getNextProperty()) != NULL)
  403. {
  404. if (strcmp(name, "url") == 0)
  405. {
  406. addSceneNodeProperty(sceneNode, SceneNodeProperty::URL, ns->getString());
  407. }
  408. else if (strcmp(name, "audio") == 0)
  409. {
  410. addSceneNodeProperty(sceneNode, SceneNodeProperty::AUDIO, ns->getString());
  411. }
  412. else if (strncmp(name, "material", 8) == 0)
  413. {
  414. int materialIndex = -1;
  415. name = strchr(name, '[');
  416. if (name && strlen(name) >= 3)
  417. {
  418. std::string indexString(name);
  419. indexString = indexString.substr(1, indexString.size()-2);
  420. materialIndex = (unsigned int)atoi(indexString.c_str());
  421. }
  422. addSceneNodeProperty(sceneNode, SceneNodeProperty::MATERIAL, ns->getString(), materialIndex);
  423. }
  424. else if (strcmp(name, "particle") == 0)
  425. {
  426. addSceneNodeProperty(sceneNode, SceneNodeProperty::PARTICLE, ns->getString());
  427. }
  428. else if (strcmp(name, "collisionObject") == 0)
  429. {
  430. addSceneNodeProperty(sceneNode, SceneNodeProperty::COLLISION_OBJECT, ns->getString());
  431. }
  432. else if (strcmp(name, "rigidBodyModel") == 0)
  433. {
  434. // Ignore this for now. We process this when we do rigid body creation.
  435. }
  436. else if (strcmp(name, "translate") == 0)
  437. {
  438. addSceneNodeProperty(sceneNode, SceneNodeProperty::TRANSLATE);
  439. }
  440. else if (strcmp(name, "rotate") == 0)
  441. {
  442. addSceneNodeProperty(sceneNode, SceneNodeProperty::ROTATE);
  443. }
  444. else if (strcmp(name, "scale") == 0)
  445. {
  446. addSceneNodeProperty(sceneNode, SceneNodeProperty::SCALE);
  447. }
  448. else if (strcmp(name, "transparent") == 0)
  449. {
  450. addSceneNodeProperty(sceneNode, SceneNodeProperty::TRANSPARENT);
  451. }
  452. else if (strcmp(name, "dynamic") == 0)
  453. {
  454. addSceneNodeProperty(sceneNode, SceneNodeProperty::DYNAMIC);
  455. }
  456. else
  457. {
  458. GP_ERROR("Unsupported node property: %s = %s", name, ns->getString());
  459. }
  460. }
  461. }
  462. else if (strcmp(ns->getNamespace(), "animations") == 0)
  463. {
  464. // Load all the animations.
  465. Properties* animation;
  466. while ((animation = ns->getNextNamespace()) != NULL)
  467. {
  468. if (strcmp(animation->getNamespace(), "animation") == 0)
  469. {
  470. const char* animationID = animation->getId();
  471. if (strlen(animationID) == 0)
  472. {
  473. GP_ERROR("Attempting to load an animation without an ID.");
  474. continue;
  475. }
  476. const char* url = animation->getString("url");
  477. if (!url)
  478. {
  479. GP_ERROR("Attempting to load animation '%s' without a URL.", animationID);
  480. continue;
  481. }
  482. const char* targetID = animation->getString("target");
  483. if (!targetID)
  484. {
  485. GP_ERROR("Attempting to load animation '%s' without a target.", animationID);
  486. continue;
  487. }
  488. addSceneAnimation(animationID, targetID, url);
  489. }
  490. else
  491. {
  492. GP_ERROR("Unsupported child namespace (of 'animations'): %s", ns->getNamespace());
  493. }
  494. }
  495. }
  496. else if (strcmp(ns->getNamespace(), "physics") == 0)
  497. {
  498. // Note: we don't load physics until the whole scene file has been
  499. // loaded so that all node references (i.e. for constraints) can be resolved.
  500. }
  501. else
  502. {
  503. // TODO: Should we ignore these items? They could be used for generic properties file inheritance.
  504. GP_ERROR("Unsupported child namespace (of 'scene'): %s", ns->getNamespace());
  505. }
  506. }
  507. }
  508. void SceneLoader::createAnimations(const Scene* scene)
  509. {
  510. // Create the scene animations.
  511. for (unsigned int i = 0, count = _animations.size(); i < count; i++)
  512. {
  513. // If the target node doesn't exist in the scene, then we
  514. // can't do anything so we skip to the next animation.
  515. Node* node = scene->findNode(_animations[i]._targetID);
  516. if (!node)
  517. {
  518. GP_ERROR("Attempting to create an animation targeting node '%s', which does not exist in the scene.", _animations[i]._targetID);
  519. continue;
  520. }
  521. // Check to make sure the referenced properties object was loaded properly.
  522. Properties* p = _properties[_animations[i]._url];
  523. if (!p)
  524. {
  525. GP_ERROR("The referenced animation data at url '%s' failed to load.", _animations[i]._url.c_str());
  526. continue;
  527. }
  528. node->createAnimation(_animations[i]._animationID, p);
  529. }
  530. }
  531. PhysicsConstraint* SceneLoader::loadGenericConstraint(const Properties* constraint, PhysicsRigidBody* rbA, PhysicsRigidBody* rbB)
  532. {
  533. GP_ASSERT(rbA);
  534. GP_ASSERT(constraint);
  535. GP_ASSERT(Game::getInstance()->getPhysicsController());
  536. PhysicsGenericConstraint* physicsConstraint = NULL;
  537. // Create the constraint from the specified properties.
  538. Quaternion roA;
  539. Vector3 toA;
  540. bool offsetSpecified = constraint->getQuaternionFromAxisAngle("rotationOffsetA", &roA);
  541. offsetSpecified |= constraint->getVector3("translationOffsetA", &toA);
  542. if (offsetSpecified)
  543. {
  544. if (rbB)
  545. {
  546. Quaternion roB;
  547. Vector3 toB;
  548. constraint->getQuaternionFromAxisAngle("rotationOffsetB", &roB);
  549. constraint->getVector3("translationOffsetB", &toB);
  550. physicsConstraint = Game::getInstance()->getPhysicsController()->createGenericConstraint(rbA, roA, toB, rbB, roB, toB);
  551. }
  552. else
  553. {
  554. physicsConstraint = Game::getInstance()->getPhysicsController()->createGenericConstraint(rbA, roA, toA);
  555. }
  556. }
  557. else
  558. {
  559. physicsConstraint = Game::getInstance()->getPhysicsController()->createGenericConstraint(rbA, rbB);
  560. }
  561. GP_ASSERT(physicsConstraint);
  562. // Set the optional parameters that were specified.
  563. Vector3 v;
  564. if (constraint->getVector3("angularLowerLimit", &v))
  565. physicsConstraint->setAngularLowerLimit(v);
  566. if (constraint->getVector3("angularUpperLimit", &v))
  567. physicsConstraint->setAngularUpperLimit(v);
  568. if (constraint->getVector3("linearLowerLimit", &v))
  569. physicsConstraint->setLinearLowerLimit(v);
  570. if (constraint->getVector3("linearUpperLimit", &v))
  571. physicsConstraint->setLinearUpperLimit(v);
  572. return physicsConstraint;
  573. }
  574. PhysicsConstraint* SceneLoader::loadHingeConstraint(const Properties* constraint, PhysicsRigidBody* rbA, PhysicsRigidBody* rbB)
  575. {
  576. GP_ASSERT(rbA);
  577. GP_ASSERT(constraint);
  578. GP_ASSERT(Game::getInstance()->getPhysicsController());
  579. PhysicsHingeConstraint* physicsConstraint = NULL;
  580. // Create the constraint from the specified properties.
  581. Quaternion roA;
  582. Vector3 toA;
  583. constraint->getQuaternionFromAxisAngle("rotationOffsetA", &roA);
  584. constraint->getVector3("translationOffsetA", &toA);
  585. if (rbB)
  586. {
  587. Quaternion roB;
  588. Vector3 toB;
  589. constraint->getQuaternionFromAxisAngle("rotationOffsetB", &roB);
  590. constraint->getVector3("translationOffsetB", &toB);
  591. physicsConstraint = Game::getInstance()->getPhysicsController()->createHingeConstraint(rbA, roA, toB, rbB, roB, toB);
  592. }
  593. else
  594. {
  595. physicsConstraint = Game::getInstance()->getPhysicsController()->createHingeConstraint(rbA, roA, toA);
  596. }
  597. // Load the hinge angle limits (lower and upper) and the hinge bounciness (if specified).
  598. const char* limitsString = constraint->getString("limits");
  599. if (limitsString)
  600. {
  601. float lowerLimit, upperLimit;
  602. int scanned;
  603. scanned = sscanf(limitsString, "%f,%f", &lowerLimit, &upperLimit);
  604. if (scanned == 2)
  605. {
  606. physicsConstraint->setLimits(MATH_DEG_TO_RAD(lowerLimit), MATH_DEG_TO_RAD(upperLimit));
  607. }
  608. else
  609. {
  610. float bounciness;
  611. scanned = sscanf(limitsString, "%f,%f,%f", &lowerLimit, &upperLimit, &bounciness);
  612. if (scanned == 3)
  613. {
  614. physicsConstraint->setLimits(MATH_DEG_TO_RAD(lowerLimit), MATH_DEG_TO_RAD(upperLimit), bounciness);
  615. }
  616. else
  617. {
  618. GP_ERROR("Failed to parse 'limits' attribute for hinge constraint '%s'.", constraint->getId());
  619. }
  620. }
  621. }
  622. return physicsConstraint;
  623. }
  624. Scene* SceneLoader::loadMainSceneData(const Properties* sceneProperties)
  625. {
  626. GP_ASSERT(sceneProperties);
  627. // Load the main scene from the specified path.
  628. Bundle* bundle = Bundle::create(_gpbPath.c_str());
  629. if (!bundle)
  630. {
  631. GP_ERROR("Failed to load scene GPB file '%s'.", _gpbPath.c_str());
  632. return NULL;
  633. }
  634. // TODO: Support loading a specific scene from a GPB file using the URL syntax (i.e. "res/scene.gpb#myscene").
  635. Scene* scene = bundle->loadScene(NULL);
  636. if (!scene)
  637. {
  638. GP_ERROR("Failed to load scene from '%s'.", _gpbPath.c_str());
  639. SAFE_RELEASE(bundle);
  640. return NULL;
  641. }
  642. // Go through the supported scene properties and apply them to the scene.
  643. const char* name = sceneProperties->getString("activeCamera");
  644. if (name)
  645. {
  646. Node* camera = scene->findNode(name);
  647. if (camera && camera->getCamera())
  648. scene->setActiveCamera(camera->getCamera());
  649. }
  650. SAFE_RELEASE(bundle);
  651. return scene;
  652. }
  653. void SceneLoader::loadPhysics(Properties* physics, Scene* scene)
  654. {
  655. GP_ASSERT(physics);
  656. GP_ASSERT(scene);
  657. GP_ASSERT(Game::getInstance()->getPhysicsController());
  658. // Go through the supported global physics properties and apply them.
  659. Vector3 gravity;
  660. if (physics->getVector3("gravity", &gravity))
  661. Game::getInstance()->getPhysicsController()->setGravity(gravity);
  662. Properties* constraint;
  663. const char* name;
  664. while ((constraint = physics->getNextNamespace()) != NULL)
  665. {
  666. if (strcmp(constraint->getNamespace(), "constraint") == 0)
  667. {
  668. // Get the constraint type.
  669. std::string type = constraint->getString("type");
  670. // Attempt to load the first rigid body. If the first rigid body cannot
  671. // be loaded or found, then continue to the next constraint (error).
  672. name = constraint->getString("rigidBodyA");
  673. if (!name)
  674. {
  675. GP_ERROR("Missing property 'rigidBodyA' for constraint '%s'.", constraint->getId());
  676. continue;
  677. }
  678. Node* rbANode = scene->findNode(name);
  679. if (!rbANode)
  680. {
  681. GP_ERROR("Node '%s' to be used as 'rigidBodyA' for constraint '%s' cannot be found.", name, constraint->getId());
  682. continue;
  683. }
  684. if (!rbANode->getCollisionObject() || rbANode->getCollisionObject()->getType() != PhysicsCollisionObject::RIGID_BODY)
  685. {
  686. GP_ERROR("Node '%s' to be used as 'rigidBodyA' does not have a rigid body.", name);
  687. continue;
  688. }
  689. PhysicsRigidBody* rbA = static_cast<PhysicsRigidBody*>(rbANode->getCollisionObject());
  690. // Attempt to load the second rigid body. If the second rigid body is not
  691. // specified, that is usually okay (only spring constraints require both and
  692. // we check that below), but if the second rigid body is specified and it doesn't
  693. // load properly, then continue to the next constraint (error).
  694. name = constraint->getString("rigidBodyB");
  695. PhysicsRigidBody* rbB = NULL;
  696. if (name)
  697. {
  698. Node* rbBNode = scene->findNode(name);
  699. if (!rbBNode)
  700. {
  701. GP_ERROR("Node '%s' to be used as 'rigidBodyB' for constraint '%s' cannot be found.", name, constraint->getId());
  702. continue;
  703. }
  704. if (!rbBNode->getCollisionObject() || rbBNode->getCollisionObject()->getType() != PhysicsCollisionObject::RIGID_BODY)
  705. {
  706. GP_ERROR("Node '%s' to be used as 'rigidBodyB' does not have a rigid body.", name);
  707. continue;
  708. }
  709. rbB = static_cast<PhysicsRigidBody*>(rbBNode->getCollisionObject());
  710. }
  711. PhysicsConstraint* physicsConstraint = NULL;
  712. // Load the constraint based on its type.
  713. if (type == "FIXED")
  714. {
  715. physicsConstraint = Game::getInstance()->getPhysicsController()->createFixedConstraint(rbA, rbB);
  716. }
  717. else if (type == "GENERIC")
  718. {
  719. physicsConstraint = loadGenericConstraint(constraint, rbA, rbB);
  720. }
  721. else if (type == "HINGE")
  722. {
  723. physicsConstraint = loadHingeConstraint(constraint, rbA, rbB);
  724. }
  725. else if (type == "SOCKET")
  726. {
  727. physicsConstraint = loadSocketConstraint(constraint, rbA, rbB);
  728. }
  729. else if (type == "SPRING")
  730. {
  731. physicsConstraint = loadSpringConstraint(constraint, rbA, rbB);
  732. }
  733. else
  734. {
  735. GP_ERROR("Unsupported physics constraint type '%s'.", type.c_str());
  736. }
  737. // If the constraint failed to load, continue on to the next one.
  738. if (!physicsConstraint)
  739. {
  740. GP_ERROR("Failed to create physics constraint.");
  741. continue;
  742. }
  743. // If the breaking impulse was specified, apply it to the constraint.
  744. if (constraint->exists("breakingImpulse"))
  745. physicsConstraint->setBreakingImpulse(constraint->getFloat("breakingImpulse"));
  746. }
  747. else
  748. {
  749. GP_ERROR("Unsupported 'physics' child namespace '%s'.", physics->getNamespace());
  750. }
  751. }
  752. }
  753. void SceneLoader::loadReferencedFiles()
  754. {
  755. // Load all referenced properties files.
  756. std::map<std::string, Properties*>::iterator iter = _properties.begin();
  757. for (; iter != _properties.end(); iter++)
  758. {
  759. if (iter->second == NULL)
  760. {
  761. std::string fileString;
  762. std::vector<std::string> namespacePath;
  763. calculateNamespacePath(iter->first, fileString, namespacePath);
  764. // Check if the referenced properties file has already been loaded.
  765. Properties* properties = NULL;
  766. std::map<std::string, Properties*>::iterator pffIter = _propertiesFromFile.find(fileString);
  767. if (pffIter != _propertiesFromFile.end())
  768. {
  769. properties = pffIter->second;
  770. }
  771. else
  772. {
  773. properties = Properties::create(fileString.c_str());
  774. if (properties == NULL)
  775. {
  776. GP_ERROR("Failed to load referenced properties file '%s'.", fileString.c_str());
  777. continue;
  778. }
  779. // Add the properties object to the cache.
  780. _propertiesFromFile.insert(std::make_pair(fileString, properties));
  781. }
  782. Properties* p = getPropertiesFromNamespacePath(properties, namespacePath);
  783. if (!p)
  784. {
  785. GP_ERROR("Failed to load referenced properties from url '%s'.", iter->first.c_str());
  786. continue;
  787. }
  788. iter->second = p;
  789. }
  790. }
  791. }
  792. PhysicsConstraint* SceneLoader::loadSocketConstraint(const Properties* constraint, PhysicsRigidBody* rbA, PhysicsRigidBody* rbB)
  793. {
  794. GP_ASSERT(rbA);
  795. GP_ASSERT(constraint);
  796. GP_ASSERT(Game::getInstance()->getPhysicsController());
  797. PhysicsSocketConstraint* physicsConstraint = NULL;
  798. Vector3 toA;
  799. bool offsetSpecified = constraint->getVector3("translationOffsetA", &toA);
  800. if (offsetSpecified)
  801. {
  802. if (rbB)
  803. {
  804. Vector3 toB;
  805. constraint->getVector3("translationOffsetB", &toB);
  806. physicsConstraint = Game::getInstance()->getPhysicsController()->createSocketConstraint(rbA, toA, rbB, toB);
  807. }
  808. else
  809. {
  810. physicsConstraint = Game::getInstance()->getPhysicsController()->createSocketConstraint(rbA, toA);
  811. }
  812. }
  813. else
  814. {
  815. physicsConstraint = Game::getInstance()->getPhysicsController()->createSocketConstraint(rbA, rbB);
  816. }
  817. return physicsConstraint;
  818. }
  819. PhysicsConstraint* SceneLoader::loadSpringConstraint(const Properties* constraint, PhysicsRigidBody* rbA, PhysicsRigidBody* rbB)
  820. {
  821. GP_ASSERT(rbA);
  822. GP_ASSERT(constraint);
  823. GP_ASSERT(Game::getInstance()->getPhysicsController());
  824. if (!rbB)
  825. {
  826. GP_ERROR("Spring constraints require two rigid bodies.");
  827. return NULL;
  828. }
  829. PhysicsSpringConstraint* physicsConstraint = NULL;
  830. // Create the constraint from the specified properties.
  831. Quaternion roA, roB;
  832. Vector3 toA, toB;
  833. bool offsetsSpecified = constraint->getQuaternionFromAxisAngle("rotationOffsetA", &roA);
  834. offsetsSpecified |= constraint->getVector3("translationOffsetA", &toA);
  835. offsetsSpecified |= constraint->getQuaternionFromAxisAngle("rotationOffsetB", &roB);
  836. offsetsSpecified |= constraint->getVector3("translationOffsetB", &toB);
  837. if (offsetsSpecified)
  838. {
  839. physicsConstraint = Game::getInstance()->getPhysicsController()->createSpringConstraint(rbA, roA, toB, rbB, roB, toB);
  840. }
  841. else
  842. {
  843. physicsConstraint = Game::getInstance()->getPhysicsController()->createSpringConstraint(rbA, rbB);
  844. }
  845. GP_ASSERT(physicsConstraint);
  846. // Set the optional parameters that were specified.
  847. Vector3 v;
  848. if (constraint->getVector3("angularLowerLimit", &v))
  849. physicsConstraint->setAngularLowerLimit(v);
  850. if (constraint->getVector3("angularUpperLimit", &v))
  851. physicsConstraint->setAngularUpperLimit(v);
  852. if (constraint->getVector3("linearLowerLimit", &v))
  853. physicsConstraint->setLinearLowerLimit(v);
  854. if (constraint->getVector3("linearUpperLimit", &v))
  855. physicsConstraint->setLinearUpperLimit(v);
  856. if (constraint->getString("angularDampingX"))
  857. physicsConstraint->setAngularDampingX(constraint->getFloat("angularDampingX"));
  858. if (constraint->getString("angularDampingY"))
  859. physicsConstraint->setAngularDampingY(constraint->getFloat("angularDampingY"));
  860. if (constraint->getString("angularDampingZ"))
  861. physicsConstraint->setAngularDampingZ(constraint->getFloat("angularDampingZ"));
  862. if (constraint->getString("angularStrengthX"))
  863. physicsConstraint->setAngularStrengthX(constraint->getFloat("angularStrengthX"));
  864. if (constraint->getString("angularStrengthY"))
  865. physicsConstraint->setAngularStrengthY(constraint->getFloat("angularStrengthY"));
  866. if (constraint->getString("angularStrengthZ"))
  867. physicsConstraint->setAngularStrengthZ(constraint->getFloat("angularStrengthZ"));
  868. if (constraint->getString("linearDampingX"))
  869. physicsConstraint->setLinearDampingX(constraint->getFloat("linearDampingX"));
  870. if (constraint->getString("linearDampingY"))
  871. physicsConstraint->setLinearDampingY(constraint->getFloat("linearDampingY"));
  872. if (constraint->getString("linearDampingZ"))
  873. physicsConstraint->setLinearDampingZ(constraint->getFloat("linearDampingZ"));
  874. if (constraint->getString("linearStrengthX"))
  875. physicsConstraint->setLinearStrengthX(constraint->getFloat("linearStrengthX"));
  876. if (constraint->getString("linearStrengthY"))
  877. physicsConstraint->setLinearStrengthY(constraint->getFloat("linearStrengthY"));
  878. if (constraint->getString("linearStrengthZ"))
  879. physicsConstraint->setLinearStrengthZ(constraint->getFloat("linearStrengthZ"));
  880. return physicsConstraint;
  881. }
  882. void SceneLoader::splitURL(const std::string& url, std::string* file, std::string* id)
  883. {
  884. if (url.empty())
  885. {
  886. // This is allowed since many scene node properties do not use the URL.
  887. return;
  888. }
  889. // Check if the url references a file (otherwise, it only references a node within the main GPB).
  890. unsigned int loc = url.rfind(".");
  891. if (loc != url.npos)
  892. {
  893. // If the url references a specific namespace within the file,
  894. // set the id out parameter appropriately. Otherwise, set the id out
  895. // parameter to the empty string so we know to load the first namespace.
  896. loc = url.rfind("#");
  897. if (loc != url.npos)
  898. {
  899. *file = url.substr(0, loc);
  900. *id = url.substr(loc + 1);
  901. }
  902. else
  903. {
  904. *file = url;
  905. *id = std::string();
  906. }
  907. }
  908. else
  909. {
  910. *file = std::string();
  911. *id = url;
  912. }
  913. }
  914. }