SceneLoader.cpp 43 KB

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