Bundle.cpp 51 KB

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