SceneLoader.cpp 39 KB

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