Bundle.cpp 51 KB

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