Bundle.cpp 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802
  1. #include "Base.h"
  2. #include "Bundle.h"
  3. #include "FileSystem.h"
  4. #include "MeshPart.h"
  5. #include "Scene.h"
  6. #include "Joint.h"
  7. #define BUNDLE_VERSION_MAJOR 1
  8. #define BUNDLE_VERSION_MINOR 2
  9. #define BUNDLE_TYPE_SCENE 1
  10. #define BUNDLE_TYPE_NODE 2
  11. #define BUNDLE_TYPE_ANIMATIONS 3
  12. #define BUNDLE_TYPE_ANIMATION 4
  13. #define BUNDLE_TYPE_ANIMATION_CHANNEL 5
  14. #define BUNDLE_TYPE_MODEL 10
  15. #define BUNDLE_TYPE_MATERIAL 16
  16. #define BUNDLE_TYPE_EFFECT 18
  17. #define BUNDLE_TYPE_CAMERA 32
  18. #define BUNDLE_TYPE_LIGHT 33
  19. #define BUNDLE_TYPE_MESH 34
  20. #define BUNDLE_TYPE_MESHPART 35
  21. #define BUNDLE_TYPE_MESHSKIN 36
  22. #define BUNDLE_TYPE_FONT 128
  23. // For sanity checking string reads
  24. #define BUNDLE_MAX_STRING_LENGTH 5000
  25. namespace gameplay
  26. {
  27. static std::vector<Bundle*> __bundleCache;
  28. Bundle::Bundle(const char* path) :
  29. _path(path), _referenceCount(0), _references(NULL), _stream(NULL), _trackedNodes(NULL)
  30. {
  31. }
  32. Bundle::~Bundle()
  33. {
  34. clearLoadSession();
  35. // Remove this Bundle from the cache.
  36. std::vector<Bundle*>::iterator itr = std::find(__bundleCache.begin(), __bundleCache.end(), this);
  37. if (itr != __bundleCache.end())
  38. {
  39. __bundleCache.erase(itr);
  40. }
  41. SAFE_DELETE_ARRAY(_references);
  42. if (_stream)
  43. {
  44. SAFE_DELETE(_stream);
  45. }
  46. }
  47. template <class T>
  48. bool Bundle::readArray(unsigned int* length, T** ptr)
  49. {
  50. GP_ASSERT(length);
  51. GP_ASSERT(ptr);
  52. GP_ASSERT(_stream);
  53. if (!read(length))
  54. {
  55. GP_ERROR("Failed to read the length of an array of data (to be read into an array).");
  56. return false;
  57. }
  58. if (*length > 0)
  59. {
  60. *ptr = new T[*length];
  61. if (_stream->read(*ptr, sizeof(T), *length) != *length)
  62. {
  63. GP_ERROR("Failed to read an array of data from bundle (into an array).");
  64. SAFE_DELETE_ARRAY(*ptr);
  65. return false;
  66. }
  67. }
  68. return true;
  69. }
  70. template <class T>
  71. bool Bundle::readArray(unsigned int* length, std::vector<T>* values)
  72. {
  73. GP_ASSERT(length);
  74. GP_ASSERT(_stream);
  75. if (!read(length))
  76. {
  77. GP_ERROR("Failed to read the length of an array of data (to be read into a std::vector).");
  78. return false;
  79. }
  80. if (*length > 0 && values)
  81. {
  82. values->resize(*length);
  83. if (_stream->read(&(*values)[0], sizeof(T), *length) != *length)
  84. {
  85. GP_ERROR("Failed to read an array of data from bundle (into a std::vector).");
  86. return false;
  87. }
  88. }
  89. return true;
  90. }
  91. template <class T>
  92. bool Bundle::readArray(unsigned int* length, std::vector<T>* values, unsigned int readSize)
  93. {
  94. GP_ASSERT(length);
  95. GP_ASSERT(_stream);
  96. GP_ASSERT(sizeof(T) >= readSize);
  97. if (!read(length))
  98. {
  99. GP_ERROR("Failed to read the length of an array of data (to be read into a std::vector with a specified single element read size).");
  100. return false;
  101. }
  102. if (*length > 0 && values)
  103. {
  104. values->resize(*length);
  105. if (_stream->read(&(*values)[0], readSize, *length) != *length)
  106. {
  107. GP_ERROR("Failed to read an array of data from bundle (into a std::vector with a specified single element read size).");
  108. return false;
  109. }
  110. }
  111. return true;
  112. }
  113. static std::string readString(Stream* stream)
  114. {
  115. GP_ASSERT(stream);
  116. unsigned int length;
  117. if (stream->read(&length, 4, 1) != 1)
  118. {
  119. GP_ERROR("Failed to read the length of a string from a bundle.");
  120. return std::string();
  121. }
  122. // Sanity check to detect if string length is far too big.
  123. GP_ASSERT(length < BUNDLE_MAX_STRING_LENGTH);
  124. std::string str;
  125. if (length > 0)
  126. {
  127. str.resize(length);
  128. if (stream->read(&str[0], 1, length) != length)
  129. {
  130. GP_ERROR("Failed to read string from bundle.");
  131. return std::string();
  132. }
  133. }
  134. return str;
  135. }
  136. Bundle* Bundle::create(const char* path)
  137. {
  138. GP_ASSERT(path);
  139. // Search the cache for this bundle.
  140. for (size_t i = 0, count = __bundleCache.size(); i < count; ++i)
  141. {
  142. Bundle* p = __bundleCache[i];
  143. GP_ASSERT(p);
  144. if (p->_path == path)
  145. {
  146. // Found a match
  147. p->addRef();
  148. return p;
  149. }
  150. }
  151. // Open the bundle.
  152. Stream* stream = FileSystem::open(path);
  153. if (!stream)
  154. {
  155. GP_ERROR("Failed to open file '%s'.", path);
  156. return NULL;
  157. }
  158. // Read the GPB header info.
  159. char sig[9];
  160. if (stream->read(sig, 1, 9) != 9 || memcmp(sig, "\xABGPB\xBB\r\n\x1A\n", 9) != 0)
  161. {
  162. SAFE_DELETE(stream);
  163. GP_ERROR("Invalid GPB header for bundle '%s'.", path);
  164. return NULL;
  165. }
  166. // Read version.
  167. unsigned char ver[2];
  168. if (stream->read(ver, 1, 2) != 2)
  169. {
  170. SAFE_DELETE(stream);
  171. GP_ERROR("Failed to read GPB version for bundle '%s'.", path);
  172. return NULL;
  173. }
  174. if (ver[0] != BUNDLE_VERSION_MAJOR || ver[1] != BUNDLE_VERSION_MINOR)
  175. {
  176. SAFE_DELETE(stream);
  177. GP_ERROR("Unsupported version (%d.%d) for bundle '%s' (expected %d.%d).", (int)ver[0], (int)ver[1], path, BUNDLE_VERSION_MAJOR, BUNDLE_VERSION_MINOR);
  178. return NULL;
  179. }
  180. // Read ref table.
  181. unsigned int refCount;
  182. if (stream->read(&refCount, 4, 1) != 1)
  183. {
  184. SAFE_DELETE(stream);
  185. GP_ERROR("Failed to read ref table for bundle '%s'.", path);
  186. return NULL;
  187. }
  188. // Read all refs.
  189. Reference* refs = new Reference[refCount];
  190. for (unsigned int i = 0; i < refCount; ++i)
  191. {
  192. if ((refs[i].id = readString(stream)).empty() ||
  193. stream->read(&refs[i].type, 4, 1) != 1 ||
  194. stream->read(&refs[i].offset, 4, 1) != 1)
  195. {
  196. SAFE_DELETE(stream);
  197. GP_ERROR("Failed to read ref number %d for bundle '%s'.", i, path);
  198. SAFE_DELETE_ARRAY(refs);
  199. return NULL;
  200. }
  201. }
  202. // Keep file open for faster reading later.
  203. Bundle* bundle = new Bundle(path);
  204. bundle->_referenceCount = refCount;
  205. bundle->_references = refs;
  206. bundle->_stream = stream;
  207. return bundle;
  208. }
  209. Bundle::Reference* Bundle::find(const char* id) const
  210. {
  211. GP_ASSERT(id);
  212. GP_ASSERT(_references);
  213. // Search the ref table for the given id (case-sensitive).
  214. for (unsigned int i = 0; i < _referenceCount; ++i)
  215. {
  216. if (_references[i].id == id)
  217. {
  218. // Found a match
  219. return &_references[i];
  220. }
  221. }
  222. return NULL;
  223. }
  224. void Bundle::clearLoadSession()
  225. {
  226. for (size_t i = 0, count = _meshSkins.size(); i < count; ++i)
  227. {
  228. SAFE_DELETE(_meshSkins[i]);
  229. }
  230. _meshSkins.clear();
  231. }
  232. const char* Bundle::getIdFromOffset() const
  233. {
  234. GP_ASSERT(_stream);
  235. return getIdFromOffset((unsigned int) _stream->position());
  236. }
  237. const char* Bundle::getIdFromOffset(unsigned int offset) const
  238. {
  239. // Search the ref table for the given offset.
  240. if (offset > 0)
  241. {
  242. GP_ASSERT(_references);
  243. for (unsigned int i = 0; i < _referenceCount; ++i)
  244. {
  245. if (_references[i].offset == offset && _references[i].id.length() > 0)
  246. {
  247. return _references[i].id.c_str();
  248. }
  249. }
  250. }
  251. return NULL;
  252. }
  253. const std::string& Bundle::getMaterialPath()
  254. {
  255. if (_materialPath.empty())
  256. {
  257. int pos = _path.find_last_of('.');
  258. if (pos > 2)
  259. {
  260. _materialPath = _path.substr(0, pos);
  261. _materialPath.append(".material");
  262. if (!FileSystem::fileExists(_materialPath.c_str()))
  263. {
  264. _materialPath.clear();
  265. }
  266. }
  267. }
  268. return _materialPath;
  269. }
  270. Bundle::Reference* Bundle::seekTo(const char* id, unsigned int type)
  271. {
  272. Reference* ref = find(id);
  273. if (ref == NULL)
  274. {
  275. GP_ERROR("No object with name '%s' in bundle '%s'.", id, _path.c_str());
  276. return NULL;
  277. }
  278. if (ref->type != type)
  279. {
  280. GP_ERROR("Object '%s' in bundle '%s' has type %d (expected type %d).", id, _path.c_str(), (int)ref->type, (int)type);
  281. return NULL;
  282. }
  283. // Seek to the offset of this object.
  284. GP_ASSERT(_stream);
  285. if (_stream->seek(ref->offset, SEEK_SET) == false)
  286. {
  287. GP_ERROR("Failed to seek to object '%s' in bundle '%s'.", id, _path.c_str());
  288. return NULL;
  289. }
  290. return ref;
  291. }
  292. Bundle::Reference* Bundle::seekToFirstType(unsigned int type)
  293. {
  294. GP_ASSERT(_references);
  295. GP_ASSERT(_stream);
  296. for (unsigned int i = 0; i < _referenceCount; ++i)
  297. {
  298. Reference* ref = &_references[i];
  299. if (ref->type == type)
  300. {
  301. // Found a match.
  302. if (_stream->seek(ref->offset, SEEK_SET) == false)
  303. {
  304. GP_ERROR("Failed to seek to object '%s' in bundle '%s'.", ref->id.c_str(), _path.c_str());
  305. return NULL;
  306. }
  307. return ref;
  308. }
  309. }
  310. return NULL;
  311. }
  312. bool Bundle::read(unsigned int* ptr)
  313. {
  314. return _stream->read(ptr, sizeof(unsigned int), 1) == 1;
  315. }
  316. bool Bundle::read(unsigned char* ptr)
  317. {
  318. return _stream->read(ptr, sizeof(unsigned char), 1) == 1;
  319. }
  320. bool Bundle::read(float* ptr)
  321. {
  322. return _stream->read(ptr, sizeof(float), 1) == 1;
  323. }
  324. bool Bundle::readMatrix(float* m)
  325. {
  326. return _stream->read(m, sizeof(float), 16) == 16;
  327. }
  328. Scene* Bundle::loadScene(const char* id)
  329. {
  330. clearLoadSession();
  331. Reference* ref = NULL;
  332. if (id)
  333. {
  334. ref = seekTo(id, BUNDLE_TYPE_SCENE);
  335. if (!ref)
  336. {
  337. GP_ERROR("Failed to load scene with id '%s' from bundle.", id);
  338. return NULL;
  339. }
  340. }
  341. else
  342. {
  343. ref = seekToFirstType(BUNDLE_TYPE_SCENE);
  344. if (!ref)
  345. {
  346. GP_ERROR("Failed to load scene from bundle; bundle contains no scene objects.");
  347. return NULL;
  348. }
  349. }
  350. Scene* scene = Scene::create(getIdFromOffset());
  351. // Read the number of children.
  352. unsigned int childrenCount;
  353. if (!read(&childrenCount))
  354. {
  355. GP_ERROR("Failed to read the scene's number of children.");
  356. SAFE_RELEASE(scene);
  357. return NULL;
  358. }
  359. if (childrenCount > 0)
  360. {
  361. // Read each child directly into the scene.
  362. for (unsigned int i = 0; i < childrenCount; i++)
  363. {
  364. Node* node = readNode(scene, NULL);
  365. if (node)
  366. {
  367. scene->addNode(node);
  368. node->release(); // scene now owns node
  369. }
  370. }
  371. }
  372. // Read active camera.
  373. std::string xref = readString(_stream);
  374. if (xref.length() > 1 && xref[0] == '#') // TODO: Handle full xrefs
  375. {
  376. Node* node = scene->findNode(xref.c_str() + 1, true);
  377. GP_ASSERT(node);
  378. Camera* camera = node->getCamera();
  379. GP_ASSERT(camera);
  380. scene->setActiveCamera(camera);
  381. }
  382. // Read ambient color.
  383. float red, blue, green;
  384. if (!read(&red))
  385. {
  386. GP_ERROR("Failed to read red component of the scene's ambient color in bundle '%s'.", _path.c_str());
  387. SAFE_RELEASE(scene);
  388. return NULL;
  389. }
  390. if (!read(&green))
  391. {
  392. GP_ERROR("Failed to read green component of the scene's ambient color in bundle '%s'.", _path.c_str());
  393. SAFE_RELEASE(scene);
  394. return NULL;
  395. }
  396. if (!read(&blue))
  397. {
  398. GP_ERROR("Failed to read blue component of the scene's ambient color in bundle '%s'.", _path.c_str());
  399. SAFE_RELEASE(scene);
  400. return NULL;
  401. }
  402. scene->setAmbientColor(red, green, blue);
  403. // Parse animations.
  404. GP_ASSERT(_references);
  405. GP_ASSERT(_stream);
  406. for (unsigned int i = 0; i < _referenceCount; ++i)
  407. {
  408. Reference* ref = &_references[i];
  409. if (ref->type == BUNDLE_TYPE_ANIMATIONS)
  410. {
  411. // Found a match.
  412. if (_stream->seek(ref->offset, SEEK_SET) == false)
  413. {
  414. GP_ERROR("Failed to seek to object '%s' in bundle '%s'.", ref->id.c_str(), _path.c_str());
  415. return NULL;
  416. }
  417. readAnimations(scene);
  418. }
  419. }
  420. resolveJointReferences(scene, NULL);
  421. return scene;
  422. }
  423. Node* Bundle::loadNode(const char* id)
  424. {
  425. return loadNode(id, NULL);
  426. }
  427. Node* Bundle::loadNode(const char* id, Scene* sceneContext)
  428. {
  429. GP_ASSERT(id);
  430. GP_ASSERT(_references);
  431. GP_ASSERT(_stream);
  432. clearLoadSession();
  433. // Load the node and any referenced joints with node tracking enabled.
  434. _trackedNodes = new std::map<std::string, Node*>();
  435. Node* node = loadNode(id, sceneContext, NULL);
  436. if (node)
  437. resolveJointReferences(sceneContext, node);
  438. // Load all animations targeting any nodes or mesh skins under this node's hierarchy.
  439. for (unsigned int i = 0; i < _referenceCount; i++)
  440. {
  441. Reference* ref = &_references[i];
  442. if (ref->type == BUNDLE_TYPE_ANIMATIONS)
  443. {
  444. if (_stream->seek(ref->offset, SEEK_SET) == false)
  445. {
  446. GP_ERROR("Failed to seek to object '%s' in bundle '%s'.", ref->id.c_str(), _path.c_str());
  447. SAFE_DELETE(_trackedNodes);
  448. return NULL;
  449. }
  450. // Read the number of animations in this object.
  451. unsigned int animationCount;
  452. if (!read(&animationCount))
  453. {
  454. GP_ERROR("Failed to read the number of animations for object '%s'.", ref->id.c_str());
  455. SAFE_DELETE(_trackedNodes);
  456. return NULL;
  457. }
  458. for (unsigned int j = 0; j < animationCount; j++)
  459. {
  460. const std::string id = readString(_stream);
  461. // Read the number of animation channels in this animation.
  462. unsigned int animationChannelCount;
  463. if (!read(&animationChannelCount))
  464. {
  465. GP_ERROR("Failed to read the number of animation channels for animation '%s'.", "animationChannelCount", id.c_str());
  466. SAFE_DELETE(_trackedNodes);
  467. return NULL;
  468. }
  469. Animation* animation = NULL;
  470. for (unsigned int k = 0; k < animationChannelCount; k++)
  471. {
  472. // Read target id.
  473. std::string targetId = readString(_stream);
  474. if (targetId.empty())
  475. {
  476. GP_ERROR("Failed to read target id for animation '%s'.", id.c_str());
  477. SAFE_DELETE(_trackedNodes);
  478. return NULL;
  479. }
  480. // If the target is one of the loaded nodes/joints, then load the animation.
  481. std::map<std::string, Node*>::iterator iter = _trackedNodes->find(targetId);
  482. if (iter != _trackedNodes->end())
  483. {
  484. // Read target attribute.
  485. unsigned int targetAttribute;
  486. if (!read(&targetAttribute))
  487. {
  488. GP_ERROR("Failed to read target attribute for animation '%s'.", id.c_str());
  489. SAFE_DELETE(_trackedNodes);
  490. return NULL;
  491. }
  492. AnimationTarget* target = iter->second;
  493. if (!target)
  494. {
  495. GP_ERROR("Failed to read %s for %s: %s", "animation target", targetId.c_str(), id.c_str());
  496. SAFE_DELETE(_trackedNodes);
  497. return NULL;
  498. }
  499. animation = readAnimationChannelData(animation, id.c_str(), target, targetAttribute);
  500. }
  501. else
  502. {
  503. // Skip over the target attribute.
  504. unsigned int data;
  505. if (!read(&data))
  506. {
  507. GP_ERROR("Failed to skip over target attribute for animation '%s'.", id.c_str());
  508. SAFE_DELETE(_trackedNodes);
  509. return NULL;
  510. }
  511. // Skip the animation channel (passing a target attribute of
  512. // 0 causes the animation to not be created).
  513. readAnimationChannelData(NULL, id.c_str(), NULL, 0);
  514. }
  515. }
  516. }
  517. }
  518. }
  519. SAFE_DELETE(_trackedNodes);
  520. return node;
  521. }
  522. Node* Bundle::loadNode(const char* id, Scene* sceneContext, Node* nodeContext)
  523. {
  524. GP_ASSERT(id);
  525. Node* node = NULL;
  526. // Search the passed in loading contexts (scene/node) first to see
  527. // if we've already loaded this node during this load session.
  528. if (sceneContext)
  529. {
  530. node = sceneContext->findNode(id, true);
  531. if (node)
  532. node->addRef();
  533. }
  534. if (node == NULL && nodeContext)
  535. {
  536. node = nodeContext->findNode(id, true);
  537. if (node)
  538. node->addRef();
  539. }
  540. if (node == NULL)
  541. {
  542. // If not yet found, search the ref table and read.
  543. Reference* ref = seekTo(id, BUNDLE_TYPE_NODE);
  544. if (ref == NULL)
  545. {
  546. return NULL;
  547. }
  548. node = readNode(sceneContext, nodeContext);
  549. }
  550. return node;
  551. }
  552. bool Bundle::skipNode()
  553. {
  554. const char* id = getIdFromOffset();
  555. GP_ASSERT(id);
  556. GP_ASSERT(_stream);
  557. // Skip the node's type.
  558. unsigned int nodeType;
  559. if (!read(&nodeType))
  560. {
  561. GP_ERROR("Failed to skip node type for node '%s'.", id);
  562. return false;
  563. }
  564. // Skip over the node's transform and parent ID.
  565. if (_stream->seek(sizeof(float) * 16, SEEK_CUR) == false)
  566. {
  567. GP_ERROR("Failed to skip over node transform for node '%s'.", id);
  568. return false;
  569. }
  570. readString(_stream);
  571. // Skip over the node's children.
  572. unsigned int childrenCount;
  573. if (!read(&childrenCount))
  574. {
  575. GP_ERROR("Failed to skip over node's children count for node '%s'.", id);
  576. return false;
  577. }
  578. else if (childrenCount > 0)
  579. {
  580. for (unsigned int i = 0; i < childrenCount; i++)
  581. {
  582. if (!skipNode())
  583. return false;
  584. }
  585. }
  586. // Skip over the node's camera, light, and model attachments.
  587. Camera* camera = readCamera(); SAFE_RELEASE(camera);
  588. Light* light = readLight(); SAFE_RELEASE(light);
  589. Model* model = readModel(id); SAFE_RELEASE(model);
  590. return true;
  591. }
  592. Node* Bundle::readNode(Scene* sceneContext, Node* nodeContext)
  593. {
  594. const char* id = getIdFromOffset();
  595. GP_ASSERT(id);
  596. GP_ASSERT(_stream);
  597. // If we are tracking nodes and it's not in the set yet, add it.
  598. if (_trackedNodes)
  599. {
  600. std::map<std::string, Node*>::iterator iter = _trackedNodes->find(id);
  601. if (iter != _trackedNodes->end())
  602. {
  603. // Skip over this node since we previously read it
  604. if (!skipNode())
  605. return NULL;
  606. iter->second->addRef();
  607. return iter->second;
  608. }
  609. }
  610. // Read node type.
  611. unsigned int nodeType;
  612. if (!read(&nodeType))
  613. {
  614. GP_ERROR("Failed to read node type for node '%s'.", id);
  615. return NULL;
  616. }
  617. Node* node = NULL;
  618. switch (nodeType)
  619. {
  620. case Node::NODE:
  621. node = Node::create(id);
  622. break;
  623. case Node::JOINT:
  624. node = Joint::create(id);
  625. break;
  626. default:
  627. return NULL;
  628. }
  629. if (_trackedNodes)
  630. {
  631. // Add the new node to the list of tracked nodes
  632. _trackedNodes->insert(std::make_pair(id, node));
  633. }
  634. // If no loading context is set, set this node as the loading context.
  635. if (sceneContext == NULL && nodeContext == NULL)
  636. {
  637. nodeContext = node;
  638. }
  639. // Read transform.
  640. float transform[16];
  641. if (_stream->read(transform, sizeof(float), 16) != 16)
  642. {
  643. GP_ERROR("Failed to read transform for node '%s'.", id);
  644. SAFE_RELEASE(node);
  645. return NULL;
  646. }
  647. setTransform(transform, node);
  648. // Skip the parent ID.
  649. readString(_stream);
  650. // Read children.
  651. unsigned int childrenCount;
  652. if (!read(&childrenCount))
  653. {
  654. GP_ERROR("Failed to read children count for node '%s'.", id);
  655. SAFE_RELEASE(node);
  656. return NULL;
  657. }
  658. if (childrenCount > 0)
  659. {
  660. // Read each child.
  661. for (unsigned int i = 0; i < childrenCount; i++)
  662. {
  663. // Search the passed in loading contexts (scene/node) first to see
  664. // if we've already loaded this child node during this load session.
  665. Node* child = NULL;
  666. id = getIdFromOffset();
  667. GP_ASSERT(id);
  668. if (sceneContext)
  669. {
  670. child = sceneContext->findNode(id, true);
  671. }
  672. if (child == NULL && nodeContext)
  673. {
  674. child = nodeContext->findNode(id, true);
  675. }
  676. // If the child was already loaded, skip it, otherwise read it
  677. if (child)
  678. {
  679. skipNode();
  680. }
  681. else
  682. {
  683. child = readNode(sceneContext, nodeContext);
  684. }
  685. if (child)
  686. {
  687. node->addChild(child);
  688. child->release(); // 'node' now owns this child
  689. }
  690. }
  691. }
  692. // Read camera.
  693. Camera* camera = readCamera();
  694. if (camera)
  695. {
  696. node->setCamera(camera);
  697. SAFE_RELEASE(camera);
  698. }
  699. // Read light.
  700. Light* light = readLight();
  701. if (light)
  702. {
  703. node->setLight(light);
  704. SAFE_RELEASE(light);
  705. }
  706. // Read model.
  707. Model* model = readModel(node->getId());
  708. if (model)
  709. {
  710. node->setModel(model);
  711. SAFE_RELEASE(model);
  712. }
  713. return node;
  714. }
  715. Camera* Bundle::readCamera()
  716. {
  717. unsigned char cameraType;
  718. if (!read(&cameraType))
  719. {
  720. GP_ERROR("Failed to load camera type in bundle '%s'.", _path.c_str());
  721. return NULL;
  722. }
  723. // Check if there isn't a camera to load.
  724. if (cameraType == 0)
  725. {
  726. return NULL;
  727. }
  728. float aspectRatio;
  729. if (!read(&aspectRatio))
  730. {
  731. GP_ERROR("Failed to load camera aspect ratio in bundle '%s'.", _path.c_str());
  732. return NULL;
  733. }
  734. float nearPlane;
  735. if (!read(&nearPlane))
  736. {
  737. GP_ERROR("Failed to load camera near plane in bundle '%s'.", _path.c_str());
  738. return NULL;
  739. }
  740. float farPlane;
  741. if (!read(&farPlane))
  742. {
  743. GP_ERROR("Failed to load camera far plane in bundle '%s'.", _path.c_str());
  744. return NULL;
  745. }
  746. Camera* camera = NULL;
  747. if (cameraType == Camera::PERSPECTIVE)
  748. {
  749. float fieldOfView;
  750. if (!read(&fieldOfView))
  751. {
  752. GP_ERROR("Failed to load camera field of view in bundle '%s'.", _path.c_str());
  753. return NULL;
  754. }
  755. camera = Camera::createPerspective(fieldOfView, aspectRatio, nearPlane, farPlane);
  756. }
  757. else if (cameraType == Camera::ORTHOGRAPHIC)
  758. {
  759. float zoomX;
  760. if (!read(&zoomX))
  761. {
  762. GP_ERROR("Failed to load camera zoomX in bundle '%s'.", _path.c_str());
  763. return NULL;
  764. }
  765. float zoomY;
  766. if (!read(&zoomY))
  767. {
  768. GP_ERROR("Failed to load camera zoomY in bundle '%s'.", _path.c_str());
  769. return NULL;
  770. }
  771. camera = Camera::createOrthographic(zoomX, zoomY, aspectRatio, nearPlane, farPlane);
  772. }
  773. else
  774. {
  775. GP_ERROR("Unsupported camera type (%d) in bundle '%s'.", cameraType, _path.c_str());
  776. return NULL;
  777. }
  778. return camera;
  779. }
  780. Light* Bundle::readLight()
  781. {
  782. unsigned char type;
  783. if (!read(&type))
  784. {
  785. GP_ERROR("Failed to load light type in bundle '%s'.", _path.c_str());
  786. return NULL;
  787. }
  788. // Check if there isn't a light to load.
  789. if (type == 0)
  790. {
  791. return NULL;
  792. }
  793. // Read color.
  794. float red, blue, green;
  795. if (!read(&red) || !read(&blue) || !read(&green))
  796. {
  797. GP_ERROR("Failed to load light color in bundle '%s'.", _path.c_str());
  798. return NULL;
  799. }
  800. Vector3 color(red, blue, green);
  801. Light* light = NULL;
  802. if (type == Light::DIRECTIONAL)
  803. {
  804. light = Light::createDirectional(color);
  805. }
  806. else if (type == Light::POINT)
  807. {
  808. float range;
  809. if (!read(&range))
  810. {
  811. GP_ERROR("Failed to load point light range in bundle '%s'.", _path.c_str());
  812. return NULL;
  813. }
  814. light = Light::createPoint(color, range);
  815. }
  816. else if (type == Light::SPOT)
  817. {
  818. float range, innerAngle, outerAngle;
  819. if (!read(&range))
  820. {
  821. GP_ERROR("Failed to load spot light range in bundle '%s'.", _path.c_str());
  822. return NULL;
  823. }
  824. if (!read(&innerAngle))
  825. {
  826. GP_ERROR("Failed to load spot light inner angle in bundle '%s'.", _path.c_str());
  827. return NULL;
  828. }
  829. if (!read(&outerAngle))
  830. {
  831. GP_ERROR("Failed to load spot light outer angle in bundle '%s'.", _path.c_str());
  832. return NULL;
  833. }
  834. light = Light::createSpot(color, range, innerAngle, outerAngle);
  835. }
  836. else
  837. {
  838. GP_ERROR("Unsupported light type (%d) in bundle '%s'.", type, _path.c_str());
  839. return NULL;
  840. }
  841. return light;
  842. }
  843. Model* Bundle::readModel(const char* nodeId)
  844. {
  845. std::string xref = readString(_stream);
  846. if (xref.length() > 1 && xref[0] == '#') // TODO: Handle full xrefs
  847. {
  848. Mesh* mesh = loadMesh(xref.c_str() + 1, nodeId);
  849. if (mesh)
  850. {
  851. Model* model = Model::create(mesh);
  852. SAFE_RELEASE(mesh);
  853. // Read skin.
  854. unsigned char hasSkin;
  855. if (!read(&hasSkin))
  856. {
  857. GP_ERROR("Failed to load whether model with mesh '%s' has a mesh skin in bundle '%s'.", xref.c_str() + 1, _path.c_str());
  858. return NULL;
  859. }
  860. if (hasSkin)
  861. {
  862. MeshSkin* skin = readMeshSkin();
  863. if (skin)
  864. {
  865. model->setSkin(skin);
  866. }
  867. }
  868. // Read material.
  869. unsigned int materialCount;
  870. if (!read(&materialCount))
  871. {
  872. GP_ERROR("Failed to load material count for model with mesh '%s' in bundle '%s'.", xref.c_str() + 1, _path.c_str());
  873. return NULL;
  874. }
  875. if (materialCount > 0)
  876. {
  877. for (unsigned int i = 0; i < materialCount; ++i)
  878. {
  879. std::string materialName = readString(_stream);
  880. std::string materialPath = getMaterialPath();
  881. materialPath.append("#");
  882. materialPath.append(materialName);
  883. Material* material = Material::create(materialPath.c_str());
  884. if (material)
  885. {
  886. int partIndex = model->getMesh()->getPartCount() > 0 ? i : -1;
  887. model->setMaterial(material, partIndex);
  888. SAFE_RELEASE(material);
  889. }
  890. }
  891. }
  892. return model;
  893. }
  894. }
  895. return NULL;
  896. }
  897. MeshSkin* Bundle::readMeshSkin()
  898. {
  899. MeshSkin* meshSkin = new MeshSkin();
  900. // Read bindShape.
  901. float bindShape[16];
  902. if (!readMatrix(bindShape))
  903. {
  904. GP_ERROR("Failed to load bind shape for mesh skin in bundle '%s'.", _path.c_str());
  905. SAFE_DELETE(meshSkin);
  906. return NULL;
  907. }
  908. meshSkin->setBindShape(bindShape);
  909. MeshSkinData* skinData = new MeshSkinData();
  910. skinData->skin = meshSkin;
  911. // Read joint count.
  912. unsigned int jointCount;
  913. if (!read(&jointCount))
  914. {
  915. GP_ERROR("Failed to load joint count for mesh skin in bundle '%s'.", _path.c_str());
  916. SAFE_DELETE(meshSkin);
  917. SAFE_DELETE(skinData);
  918. return NULL;
  919. }
  920. if (jointCount == 0)
  921. {
  922. GP_ERROR("Invalid joint count (must be greater than 0) for mesh skin in bundle '%s'.", _path.c_str());
  923. SAFE_DELETE(meshSkin);
  924. SAFE_DELETE(skinData);
  925. return NULL;
  926. }
  927. meshSkin->setJointCount(jointCount);
  928. // Read joint xref strings for all joints in the list.
  929. for (unsigned int i = 0; i < jointCount; i++)
  930. {
  931. skinData->joints.push_back(readString(_stream));
  932. }
  933. // Read bind poses.
  934. unsigned int jointsBindPosesCount;
  935. if (!read(&jointsBindPosesCount))
  936. {
  937. GP_ERROR("Failed to load number of joint bind poses in bundle '%s'.", _path.c_str());
  938. SAFE_DELETE(meshSkin);
  939. SAFE_DELETE(skinData);
  940. return NULL;
  941. }
  942. if (jointsBindPosesCount > 0)
  943. {
  944. GP_ASSERT(jointCount * 16 == jointsBindPosesCount);
  945. float m[16];
  946. for (unsigned int i = 0; i < jointCount; i++)
  947. {
  948. if (!readMatrix(m))
  949. {
  950. GP_ERROR("Failed to load joint bind pose matrix (for joint with index %d) in bundle '%s'.", i, _path.c_str());
  951. SAFE_DELETE(meshSkin);
  952. SAFE_DELETE(skinData);
  953. return NULL;
  954. }
  955. skinData->inverseBindPoseMatrices.push_back(m);
  956. }
  957. }
  958. // Store the MeshSkinData so we can go back and resolve all joint references later.
  959. _meshSkins.push_back(skinData);
  960. return meshSkin;
  961. }
  962. void Bundle::resolveJointReferences(Scene* sceneContext, Node* nodeContext)
  963. {
  964. GP_ASSERT(_stream);
  965. for (size_t i = 0, skinCount = _meshSkins.size(); i < skinCount; ++i)
  966. {
  967. MeshSkinData* skinData = _meshSkins[i];
  968. GP_ASSERT(skinData);
  969. GP_ASSERT(skinData->skin);
  970. // Resolve all joints in skin joint list.
  971. size_t jointCount = skinData->joints.size();
  972. for (size_t j = 0; j < jointCount; ++j)
  973. {
  974. // TODO: Handle full xrefs (not just local # xrefs).
  975. std::string jointId = skinData->joints[j];
  976. if (jointId.length() > 1 && jointId[0] == '#')
  977. {
  978. jointId = jointId.substr(1, jointId.length() - 1);
  979. Node* n = loadNode(jointId.c_str(), sceneContext, nodeContext);
  980. if (n && n->getType() == Node::JOINT)
  981. {
  982. Joint* joint = static_cast<Joint*>(n);
  983. joint->setInverseBindPose(skinData->inverseBindPoseMatrices[j]);
  984. skinData->skin->setJoint(joint, (unsigned int)j);
  985. SAFE_RELEASE(joint);
  986. }
  987. }
  988. }
  989. // Set the root joint.
  990. if (jointCount > 0)
  991. {
  992. Joint* rootJoint = skinData->skin->getJoint((unsigned int)0);
  993. Node* node = rootJoint;
  994. GP_ASSERT(node);
  995. Node* parent = node->getParent();
  996. std::vector<Node*> loadedNodes;
  997. while (true)
  998. {
  999. if (parent)
  1000. {
  1001. if (skinData->skin->getJointIndex(static_cast<Joint*>(parent)) != -1)
  1002. {
  1003. // Parent is a joint in the MeshSkin, so treat it as the new root.
  1004. rootJoint = static_cast<Joint*>(parent);
  1005. }
  1006. node = parent;
  1007. parent = node->getParent();
  1008. }
  1009. else
  1010. {
  1011. // No parent currently set for this joint.
  1012. // Lookup its parentID in case it references a node that was not yet loaded as part
  1013. // of the mesh skin's joint list.
  1014. std::string nodeId = node->getId();
  1015. while (true)
  1016. {
  1017. // Get the node's type.
  1018. Reference* ref = find(nodeId.c_str());
  1019. if (ref == NULL)
  1020. {
  1021. GP_ERROR("No object with name '%s' in bundle '%s'.", nodeId.c_str(), _path.c_str());
  1022. return;
  1023. }
  1024. // Seek to the current node in the file so we can get it's parent ID.
  1025. seekTo(nodeId.c_str(), ref->type);
  1026. // Skip over the node type (1 unsigned int) and transform (16 floats) and read the parent id.
  1027. if (_stream->seek(sizeof(unsigned int) + sizeof(float)*16, SEEK_CUR) == false)
  1028. {
  1029. GP_ERROR("Failed to skip over node type and transform for node '%s' in bundle '%s'.", nodeId.c_str(), _path.c_str());
  1030. return;
  1031. }
  1032. std::string parentID = readString(_stream);
  1033. if (!parentID.empty())
  1034. nodeId = parentID;
  1035. else
  1036. break;
  1037. }
  1038. if (nodeId != rootJoint->getId())
  1039. loadedNodes.push_back(loadNode(nodeId.c_str(), sceneContext, nodeContext));
  1040. break;
  1041. }
  1042. }
  1043. skinData->skin->setRootJoint(rootJoint);
  1044. // Release all the nodes that we loaded since the nodes are now owned by the mesh skin/joints.
  1045. for (unsigned int i = 0; i < loadedNodes.size(); i++)
  1046. {
  1047. SAFE_RELEASE(loadedNodes[i]);
  1048. }
  1049. }
  1050. // Remove the joint hierarchy from the scene since it is owned by the mesh skin.
  1051. if (sceneContext)
  1052. sceneContext->removeNode(skinData->skin->_rootNode);
  1053. // Done with this MeshSkinData entry.
  1054. SAFE_DELETE(_meshSkins[i]);
  1055. }
  1056. _meshSkins.clear();
  1057. }
  1058. void Bundle::readAnimation(Scene* scene)
  1059. {
  1060. const std::string animationId = readString(_stream);
  1061. // Read the number of animation channels in this animation.
  1062. unsigned int animationChannelCount;
  1063. if (!read(&animationChannelCount))
  1064. {
  1065. GP_ERROR("Failed to read animation channel count for animation '%s'.", animationId.c_str());
  1066. return;
  1067. }
  1068. Animation* animation = NULL;
  1069. for (unsigned int i = 0; i < animationChannelCount; i++)
  1070. {
  1071. animation = readAnimationChannel(scene, animation, animationId.c_str());
  1072. }
  1073. }
  1074. void Bundle::readAnimations(Scene* scene)
  1075. {
  1076. // Read the number of animations in this object.
  1077. unsigned int animationCount;
  1078. if (!read(&animationCount))
  1079. {
  1080. GP_ERROR("Failed to read the number of animations in the scene.");
  1081. return;
  1082. }
  1083. for (unsigned int i = 0; i < animationCount; i++)
  1084. {
  1085. readAnimation(scene);
  1086. }
  1087. }
  1088. Animation* Bundle::readAnimationChannel(Scene* scene, Animation* animation, const char* animationId)
  1089. {
  1090. GP_ASSERT(animationId);
  1091. // Read target id.
  1092. std::string targetId = readString(_stream);
  1093. if (targetId.empty())
  1094. {
  1095. GP_ERROR("Failed to read target id for animation '%s'.", animationId);
  1096. return NULL;
  1097. }
  1098. // Read target attribute.
  1099. unsigned int targetAttribute;
  1100. if (!read(&targetAttribute))
  1101. {
  1102. GP_ERROR("Failed to read target attribute for animation '%s'.", animationId);
  1103. return NULL;
  1104. }
  1105. AnimationTarget* target = NULL;
  1106. // Search for a node that matches the target.
  1107. if (!target)
  1108. {
  1109. target = scene->findNode(targetId.c_str());
  1110. if (!target)
  1111. {
  1112. GP_ERROR("Failed to find the animation target (with id '%s') for animation '%s'.", targetId.c_str(), animationId);
  1113. return NULL;
  1114. }
  1115. }
  1116. return readAnimationChannelData(animation, animationId, target, targetAttribute);
  1117. }
  1118. Animation* Bundle::readAnimationChannelData(Animation* animation, const char* id, AnimationTarget* target, unsigned int targetAttribute)
  1119. {
  1120. GP_ASSERT(id);
  1121. std::vector<unsigned int> keyTimes;
  1122. std::vector<float> values;
  1123. std::vector<float> tangentsIn;
  1124. std::vector<float> tangentsOut;
  1125. std::vector<unsigned int> interpolation;
  1126. // Length of the arrays.
  1127. unsigned int keyTimesCount;
  1128. unsigned int valuesCount;
  1129. unsigned int tangentsInCount;
  1130. unsigned int tangentsOutCount;
  1131. unsigned int interpolationCount;
  1132. // Read key times.
  1133. if (!readArray(&keyTimesCount, &keyTimes, sizeof(unsigned int)))
  1134. {
  1135. GP_ERROR("Failed to read key times for animation '%s'.", id);
  1136. return NULL;
  1137. }
  1138. // Read key values.
  1139. if (!readArray(&valuesCount, &values))
  1140. {
  1141. GP_ERROR("Failed to read key values for animation '%s'.", id);
  1142. return NULL;
  1143. }
  1144. // Read in-tangents.
  1145. if (!readArray(&tangentsInCount, &tangentsIn))
  1146. {
  1147. GP_ERROR("Failed to read in tangents for animation '%s'.", id);
  1148. return NULL;
  1149. }
  1150. // Read out-tangents.
  1151. if (!readArray(&tangentsOutCount, &tangentsOut))
  1152. {
  1153. GP_ERROR("Failed to read out tangents for animation '%s'.", id);
  1154. return NULL;
  1155. }
  1156. // Read interpolations.
  1157. if (!readArray(&interpolationCount, &interpolation, sizeof(unsigned int)))
  1158. {
  1159. GP_ERROR("Failed to read the interpolation values for animation '%s'.", id);
  1160. return NULL;
  1161. }
  1162. if (targetAttribute > 0)
  1163. {
  1164. GP_ASSERT(target);
  1165. GP_ASSERT(keyTimes.size() > 0 && values.size() > 0);
  1166. if (animation == NULL)
  1167. {
  1168. // TODO: This code currently assumes LINEAR only.
  1169. animation = target->createAnimation(id, targetAttribute, keyTimesCount, &keyTimes[0], &values[0], Curve::LINEAR);
  1170. }
  1171. else
  1172. {
  1173. animation->createChannel(target, targetAttribute, keyTimesCount, &keyTimes[0], &values[0], Curve::LINEAR);
  1174. }
  1175. }
  1176. return animation;
  1177. }
  1178. Mesh* Bundle::loadMesh(const char* id)
  1179. {
  1180. return loadMesh(id, NULL);
  1181. }
  1182. Mesh* Bundle::loadMesh(const char* id, const char* nodeId)
  1183. {
  1184. GP_ASSERT(_stream);
  1185. GP_ASSERT(id);
  1186. // Save the file position.
  1187. long position = _stream->position();
  1188. if (position == -1L)
  1189. {
  1190. GP_ERROR("Failed to save the current file position before loading mesh '%s'.", id);
  1191. return NULL;
  1192. }
  1193. // Seek to the specified mesh.
  1194. Reference* ref = seekTo(id, BUNDLE_TYPE_MESH);
  1195. if (ref == NULL)
  1196. {
  1197. GP_ERROR("Failed to locate ref for mesh '%s'.", id);
  1198. return NULL;
  1199. }
  1200. // Read mesh data.
  1201. MeshData* meshData = readMeshData();
  1202. if (meshData == NULL)
  1203. {
  1204. GP_ERROR("Failed to load mesh data for mesh '%s'.", id);
  1205. return NULL;
  1206. }
  1207. // Create mesh.
  1208. Mesh* mesh = Mesh::createMesh(meshData->vertexFormat, meshData->vertexCount, false);
  1209. if (mesh == NULL)
  1210. {
  1211. GP_ERROR("Failed to create mesh '%s'.", id);
  1212. SAFE_DELETE_ARRAY(meshData);
  1213. return NULL;
  1214. }
  1215. mesh->_url = _path;
  1216. mesh->_url += "#";
  1217. mesh->_url += id;
  1218. mesh->setVertexData((float*)meshData->vertexData, 0, meshData->vertexCount);
  1219. mesh->_boundingBox.set(meshData->boundingBox);
  1220. mesh->_boundingSphere.set(meshData->boundingSphere);
  1221. // Create mesh parts.
  1222. for (unsigned int i = 0; i < meshData->parts.size(); ++i)
  1223. {
  1224. MeshPartData* partData = meshData->parts[i];
  1225. GP_ASSERT(partData);
  1226. MeshPart* part = mesh->addPart(partData->primitiveType, partData->indexFormat, partData->indexCount, false);
  1227. if (part == NULL)
  1228. {
  1229. GP_ERROR("Failed to create mesh part (with index %d) for mesh '%s'.", i, id);
  1230. SAFE_DELETE(meshData);
  1231. return NULL;
  1232. }
  1233. part->setIndexData(partData->indexData, 0, partData->indexCount);
  1234. }
  1235. SAFE_DELETE(meshData);
  1236. // Restore file pointer.
  1237. if (_stream->seek(position, SEEK_SET) == false)
  1238. {
  1239. GP_ERROR("Failed to restore file pointer after loading mesh '%s'.", id);
  1240. return NULL;
  1241. }
  1242. return mesh;
  1243. }
  1244. Bundle::MeshData* Bundle::readMeshData()
  1245. {
  1246. // Read vertex format/elements.
  1247. unsigned int vertexElementCount;
  1248. if (_stream->read(&vertexElementCount, 4, 1) != 1)
  1249. {
  1250. GP_ERROR("Failed to load vertex element count.");
  1251. return NULL;
  1252. }
  1253. if (vertexElementCount < 1)
  1254. {
  1255. GP_ERROR("Failed to load mesh data; invalid vertex element count (must be greater than 0).");
  1256. return NULL;
  1257. }
  1258. VertexFormat::Element* vertexElements = new VertexFormat::Element[vertexElementCount];
  1259. for (unsigned int i = 0; i < vertexElementCount; ++i)
  1260. {
  1261. unsigned int vUsage, vSize;
  1262. if (_stream->read(&vUsage, 4, 1) != 1)
  1263. {
  1264. GP_ERROR("Failed to load vertex usage.");
  1265. SAFE_DELETE_ARRAY(vertexElements);
  1266. return NULL;
  1267. }
  1268. if (_stream->read(&vSize, 4, 1) != 1)
  1269. {
  1270. GP_ERROR("Failed to load vertex size.");
  1271. SAFE_DELETE_ARRAY(vertexElements);
  1272. return NULL;
  1273. }
  1274. vertexElements[i].usage = (VertexFormat::Usage)vUsage;
  1275. vertexElements[i].size = vSize;
  1276. }
  1277. MeshData* meshData = new MeshData(VertexFormat(vertexElements, vertexElementCount));
  1278. SAFE_DELETE_ARRAY(vertexElements);
  1279. // Read vertex data.
  1280. unsigned int vertexByteCount;
  1281. if (_stream->read(&vertexByteCount, 4, 1) != 1)
  1282. {
  1283. GP_ERROR("Failed to load vertex byte count.");
  1284. SAFE_DELETE(meshData);
  1285. return NULL;
  1286. }
  1287. if (vertexByteCount == 0)
  1288. {
  1289. GP_ERROR("Failed to load mesh data; invalid vertex byte count of 0.");
  1290. SAFE_DELETE(meshData);
  1291. return NULL;
  1292. }
  1293. GP_ASSERT(meshData->vertexFormat.getVertexSize());
  1294. meshData->vertexCount = vertexByteCount / meshData->vertexFormat.getVertexSize();
  1295. meshData->vertexData = new unsigned char[vertexByteCount];
  1296. if (_stream->read(meshData->vertexData, 1, vertexByteCount) != vertexByteCount)
  1297. {
  1298. GP_ERROR("Failed to load vertex data.");
  1299. SAFE_DELETE(meshData);
  1300. return NULL;
  1301. }
  1302. // Read mesh bounds (bounding box and bounding sphere).
  1303. if (_stream->read(&meshData->boundingBox.min.x, 4, 3) != 3 || _stream->read(&meshData->boundingBox.max.x, 4, 3) != 3)
  1304. {
  1305. GP_ERROR("Failed to load mesh bounding box.");
  1306. SAFE_DELETE(meshData);
  1307. return NULL;
  1308. }
  1309. if (_stream->read(&meshData->boundingSphere.center.x, 4, 3) != 3 || _stream->read(&meshData->boundingSphere.radius, 4, 1) != 1)
  1310. {
  1311. GP_ERROR("Failed to load mesh bounding sphere.");
  1312. SAFE_DELETE(meshData);
  1313. return NULL;
  1314. }
  1315. // Read mesh parts.
  1316. unsigned int meshPartCount;
  1317. if (_stream->read(&meshPartCount, 4, 1) != 1)
  1318. {
  1319. GP_ERROR("Failed to load mesh part count.");
  1320. SAFE_DELETE(meshData);
  1321. return NULL;
  1322. }
  1323. for (unsigned int i = 0; i < meshPartCount; ++i)
  1324. {
  1325. // Read primitive type, index format and index count.
  1326. unsigned int pType, iFormat, iByteCount;
  1327. if (_stream->read(&pType, 4, 1) != 1)
  1328. {
  1329. GP_ERROR("Failed to load primitive type for mesh part with index %d.", i);
  1330. SAFE_DELETE(meshData);
  1331. return NULL;
  1332. }
  1333. if (_stream->read(&iFormat, 4, 1) != 1)
  1334. {
  1335. GP_ERROR("Failed to load index format for mesh part with index %d.", i);
  1336. SAFE_DELETE(meshData);
  1337. return NULL;
  1338. }
  1339. if (_stream->read(&iByteCount, 4, 1) != 1)
  1340. {
  1341. GP_ERROR("Failed to load index byte count for mesh part with index %d.", i);
  1342. SAFE_DELETE(meshData);
  1343. return NULL;
  1344. }
  1345. MeshPartData* partData = new MeshPartData();
  1346. meshData->parts.push_back(partData);
  1347. partData->primitiveType = (Mesh::PrimitiveType)pType;
  1348. partData->indexFormat = (Mesh::IndexFormat)iFormat;
  1349. unsigned int indexSize = 0;
  1350. switch (partData->indexFormat)
  1351. {
  1352. case Mesh::INDEX8:
  1353. indexSize = 1;
  1354. break;
  1355. case Mesh::INDEX16:
  1356. indexSize = 2;
  1357. break;
  1358. case Mesh::INDEX32:
  1359. indexSize = 4;
  1360. break;
  1361. default:
  1362. GP_ERROR("Unsupported index format for mesh part with index %d.", i);
  1363. return NULL;
  1364. }
  1365. GP_ASSERT(indexSize);
  1366. partData->indexCount = iByteCount / indexSize;
  1367. partData->indexData = new unsigned char[iByteCount];
  1368. if (_stream->read(partData->indexData, 1, iByteCount) != iByteCount)
  1369. {
  1370. GP_ERROR("Failed to read index data for mesh part with index %d.", i);
  1371. SAFE_DELETE(meshData);
  1372. return NULL;
  1373. }
  1374. }
  1375. return meshData;
  1376. }
  1377. Bundle::MeshData* Bundle::readMeshData(const char* url)
  1378. {
  1379. GP_ASSERT(url);
  1380. size_t len = strlen(url);
  1381. if (len == 0)
  1382. {
  1383. GP_ERROR("Mesh data URL must be non-empty.");
  1384. return NULL;
  1385. }
  1386. // Parse URL (formatted as 'bundle#id').
  1387. std::string urlstring(url);
  1388. size_t pos = urlstring.find('#');
  1389. if (pos == std::string::npos)
  1390. {
  1391. GP_ERROR("Invalid mesh data URL '%s' (must be of the form 'bundle#id').", url);
  1392. return NULL;
  1393. }
  1394. std::string file = urlstring.substr(0, pos);
  1395. std::string id = urlstring.substr(pos + 1);
  1396. // Load bundle.
  1397. Bundle* bundle = Bundle::create(file.c_str());
  1398. if (bundle == NULL)
  1399. {
  1400. GP_ERROR("Failed to load bundle '%s'.", file.c_str());
  1401. return NULL;
  1402. }
  1403. // Seek to mesh with specified ID in bundle.
  1404. Reference* ref = bundle->seekTo(id.c_str(), BUNDLE_TYPE_MESH);
  1405. if (ref == NULL)
  1406. {
  1407. GP_ERROR("Failed to load ref from bundle '%s' for mesh with id '%s'.", file.c_str(), id.c_str());
  1408. return NULL;
  1409. }
  1410. // Read mesh data from current file position.
  1411. MeshData* meshData = bundle->readMeshData();
  1412. SAFE_RELEASE(bundle);
  1413. return meshData;
  1414. }
  1415. Font* Bundle::loadFont(const char* id)
  1416. {
  1417. GP_ASSERT(id);
  1418. GP_ASSERT(_stream);
  1419. // Seek to the specified font.
  1420. Reference* ref = seekTo(id, BUNDLE_TYPE_FONT);
  1421. if (ref == NULL)
  1422. {
  1423. GP_ERROR("Failed to load ref for font '%s'.", id);
  1424. return NULL;
  1425. }
  1426. // Read font family.
  1427. std::string family = readString(_stream);
  1428. if (family.empty())
  1429. {
  1430. GP_ERROR("Failed to read font family for font '%s'.", id);
  1431. return NULL;
  1432. }
  1433. // Read font style and size.
  1434. unsigned int style, size;
  1435. if (_stream->read(&style, 4, 1) != 1)
  1436. {
  1437. GP_ERROR("Failed to read style for font '%s'.", id);
  1438. return NULL;
  1439. }
  1440. if (_stream->read(&size, 4, 1) != 1)
  1441. {
  1442. GP_ERROR("Failed to read size for font '%s'.", id);
  1443. return NULL;
  1444. }
  1445. // Read character set.
  1446. std::string charset = readString(_stream);
  1447. // Read font glyphs.
  1448. unsigned int glyphCount;
  1449. if (_stream->read(&glyphCount, 4, 1) != 1)
  1450. {
  1451. GP_ERROR("Failed to read glyph count for font '%s'.", id);
  1452. return NULL;
  1453. }
  1454. if (glyphCount == 0)
  1455. {
  1456. GP_ERROR("Invalid glyph count (must be greater than 0) for font '%s'.", id);
  1457. return NULL;
  1458. }
  1459. Font::Glyph* glyphs = new Font::Glyph[glyphCount];
  1460. if (_stream->read(glyphs, sizeof(Font::Glyph), glyphCount) != glyphCount)
  1461. {
  1462. GP_ERROR("Failed to read glyphs for font '%s'.", id);
  1463. SAFE_DELETE_ARRAY(glyphs);
  1464. return NULL;
  1465. }
  1466. // Read texture attributes.
  1467. unsigned int width, height, textureByteCount;
  1468. if (_stream->read(&width, 4, 1) != 1)
  1469. {
  1470. GP_ERROR("Failed to read texture width for font '%s'.", id);
  1471. SAFE_DELETE_ARRAY(glyphs);
  1472. return NULL;
  1473. }
  1474. if (_stream->read(&height, 4, 1) != 1)
  1475. {
  1476. GP_ERROR("Failed to read texture height for font '%s'.", id);
  1477. SAFE_DELETE_ARRAY(glyphs);
  1478. return NULL;
  1479. }
  1480. if (_stream->read(&textureByteCount, 4, 1) != 1)
  1481. {
  1482. GP_ERROR("Failed to read texture byte count for font '%s'.", id);
  1483. SAFE_DELETE_ARRAY(glyphs);
  1484. return NULL;
  1485. }
  1486. if (textureByteCount != (width * height))
  1487. {
  1488. GP_ERROR("Invalid texture byte count for font '%s'.", id);
  1489. SAFE_DELETE_ARRAY(glyphs);
  1490. return NULL;
  1491. }
  1492. // Read texture data.
  1493. unsigned char* textureData = new unsigned char[textureByteCount];
  1494. if (_stream->read(textureData, 1, textureByteCount) != textureByteCount)
  1495. {
  1496. GP_ERROR("Failed to read texture data for font '%s'.", id);
  1497. SAFE_DELETE_ARRAY(glyphs);
  1498. SAFE_DELETE_ARRAY(textureData);
  1499. return NULL;
  1500. }
  1501. // Create the texture for the font.
  1502. Texture* texture = Texture::create(Texture::ALPHA, width, height, textureData, true);
  1503. // Free the texture data (no longer needed).
  1504. SAFE_DELETE_ARRAY(textureData);
  1505. if (texture == NULL)
  1506. {
  1507. GP_ERROR("Failed to create texture for font '%s'.", id);
  1508. SAFE_DELETE_ARRAY(glyphs);
  1509. return NULL;
  1510. }
  1511. // Create the font.
  1512. Font* font = Font::create(family.c_str(), Font::PLAIN, size, glyphs, glyphCount, texture);
  1513. // Free the glyph array.
  1514. SAFE_DELETE_ARRAY(glyphs);
  1515. // Release the texture since the Font now owns it.
  1516. SAFE_RELEASE(texture);
  1517. if (font)
  1518. {
  1519. font->_path = _path;
  1520. font->_id = id;
  1521. }
  1522. return font;
  1523. }
  1524. void Bundle::setTransform(const float* values, Transform* transform)
  1525. {
  1526. GP_ASSERT(transform);
  1527. // Load array into transform.
  1528. Matrix matrix(values);
  1529. Vector3 scale, translation;
  1530. Quaternion rotation;
  1531. matrix.decompose(&scale, &rotation, &translation);
  1532. transform->setScale(scale);
  1533. transform->setTranslation(translation);
  1534. transform->setRotation(rotation);
  1535. }
  1536. bool Bundle::contains(const char* id) const
  1537. {
  1538. return (find(id) != NULL);
  1539. }
  1540. unsigned int Bundle::getObjectCount() const
  1541. {
  1542. return _referenceCount;
  1543. }
  1544. const char* Bundle::getObjectId(unsigned int index) const
  1545. {
  1546. GP_ASSERT(_references);
  1547. return (index >= _referenceCount ? NULL : _references[index].id.c_str());
  1548. }
  1549. Bundle::Reference::Reference()
  1550. : type(0), offset(0)
  1551. {
  1552. }
  1553. Bundle::Reference::~Reference()
  1554. {
  1555. }
  1556. Bundle::MeshPartData::MeshPartData() :
  1557. indexCount(0), indexData(NULL)
  1558. {
  1559. }
  1560. Bundle::MeshPartData::~MeshPartData()
  1561. {
  1562. SAFE_DELETE_ARRAY(indexData);
  1563. }
  1564. Bundle::MeshData::MeshData(const VertexFormat& vertexFormat)
  1565. : vertexFormat(vertexFormat), vertexCount(0), vertexData(NULL)
  1566. {
  1567. }
  1568. Bundle::MeshData::~MeshData()
  1569. {
  1570. SAFE_DELETE_ARRAY(vertexData);
  1571. for (unsigned int i = 0; i < parts.size(); ++i)
  1572. {
  1573. SAFE_DELETE(parts[i]);
  1574. }
  1575. }
  1576. }