Bundle.cpp 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792
  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. static 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::create();
  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. if (node == NULL && nodeContext)
  535. {
  536. node = nodeContext->findNode(id, true);
  537. if (node)
  538. node->addRef();
  539. }
  540. if (node == NULL)
  541. {
  542. // If not yet found, search the ref table and read.
  543. Reference* ref = seekTo(id, BUNDLE_TYPE_NODE);
  544. if (ref == NULL)
  545. {
  546. return NULL;
  547. }
  548. node = readNode(sceneContext, nodeContext);
  549. }
  550. return node;
  551. }
  552. bool Bundle::skipNode()
  553. {
  554. const char* id = getIdFromOffset();
  555. GP_ASSERT(id);
  556. GP_ASSERT(_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. // If we are tracking nodes and it's not in the set yet, add it.
  598. if (_trackedNodes)
  599. {
  600. std::map<std::string, Node*>::iterator iter = _trackedNodes->find(id);
  601. if (iter != _trackedNodes->end())
  602. {
  603. // Skip over this node since we previously read it
  604. if (!skipNode())
  605. return NULL;
  606. iter->second->addRef();
  607. return iter->second;
  608. }
  609. }
  610. // Read node type.
  611. unsigned int nodeType;
  612. if (!read(&nodeType))
  613. {
  614. GP_ERROR("Failed to read node type for node '%s'.", id);
  615. return NULL;
  616. }
  617. Node* node = NULL;
  618. switch (nodeType)
  619. {
  620. case Node::NODE:
  621. node = Node::create(id);
  622. break;
  623. case Node::JOINT:
  624. node = Joint::create(id);
  625. break;
  626. default:
  627. return NULL;
  628. }
  629. if (_trackedNodes)
  630. {
  631. // Add the new node to the list of tracked nodes
  632. _trackedNodes->insert(std::make_pair(id, node));
  633. }
  634. // If no loading context is set, set this node as the loading context.
  635. if (sceneContext == NULL && nodeContext == NULL)
  636. {
  637. nodeContext = node;
  638. }
  639. // Read transform.
  640. float transform[16];
  641. if (fread(transform, sizeof(float), 16, _file) != 16)
  642. {
  643. GP_ERROR("Failed to read transform for node '%s'.", id);
  644. SAFE_RELEASE(node);
  645. return NULL;
  646. }
  647. setTransform(transform, node);
  648. // Skip the parent ID.
  649. readString(_file);
  650. // Read children.
  651. unsigned int childrenCount;
  652. if (!read(&childrenCount))
  653. {
  654. GP_ERROR("Failed to read children count for node '%s'.", id);
  655. SAFE_RELEASE(node);
  656. return NULL;
  657. }
  658. if (childrenCount > 0)
  659. {
  660. // Read each child.
  661. for (unsigned int i = 0; i < childrenCount; i++)
  662. {
  663. // Search the passed in loading contexts (scene/node) first to see
  664. // if we've already loaded this child node during this load session.
  665. Node* child = NULL;
  666. id = getIdFromOffset();
  667. GP_ASSERT(id);
  668. if (sceneContext)
  669. {
  670. child = sceneContext->findNode(id, true);
  671. }
  672. if (child == NULL && nodeContext)
  673. {
  674. child = nodeContext->findNode(id, true);
  675. }
  676. // If the child was already loaded, skip it, otherwise read it
  677. if (child)
  678. {
  679. skipNode();
  680. }
  681. else
  682. {
  683. child = readNode(sceneContext, nodeContext);
  684. }
  685. if (child)
  686. {
  687. node->addChild(child);
  688. child->release(); // 'node' now owns this child
  689. }
  690. }
  691. }
  692. // Read camera.
  693. Camera* camera = readCamera();
  694. if (camera)
  695. {
  696. node->setCamera(camera);
  697. SAFE_RELEASE(camera);
  698. }
  699. // Read light.
  700. Light* light = readLight();
  701. if (light)
  702. {
  703. node->setLight(light);
  704. SAFE_RELEASE(light);
  705. }
  706. // Read model.
  707. Model* model = readModel(node->getId());
  708. if (model)
  709. {
  710. node->setModel(model);
  711. SAFE_RELEASE(model);
  712. }
  713. return node;
  714. }
  715. Camera* Bundle::readCamera()
  716. {
  717. unsigned char cameraType;
  718. if (!read(&cameraType))
  719. {
  720. GP_ERROR("Failed to load camera type in bundle '%s'.", _path.c_str());
  721. return NULL;
  722. }
  723. // Check if there isn't a camera to load.
  724. if (cameraType == 0)
  725. {
  726. return NULL;
  727. }
  728. float aspectRatio;
  729. if (!read(&aspectRatio))
  730. {
  731. GP_ERROR("Failed to load camera aspect ratio in bundle '%s'.", _path.c_str());
  732. return NULL;
  733. }
  734. float nearPlane;
  735. if (!read(&nearPlane))
  736. {
  737. GP_ERROR("Failed to load camera near plane in bundle '%s'.", _path.c_str());
  738. return NULL;
  739. }
  740. float farPlane;
  741. if (!read(&farPlane))
  742. {
  743. GP_ERROR("Failed to load camera far plane in bundle '%s'.", _path.c_str());
  744. return NULL;
  745. }
  746. Camera* camera = NULL;
  747. if (cameraType == Camera::PERSPECTIVE)
  748. {
  749. float fieldOfView;
  750. if (!read(&fieldOfView))
  751. {
  752. GP_ERROR("Failed to load camera field of view in bundle '%s'.", _path.c_str());
  753. return NULL;
  754. }
  755. camera = Camera::createPerspective(fieldOfView, aspectRatio, nearPlane, farPlane);
  756. }
  757. else if (cameraType == Camera::ORTHOGRAPHIC)
  758. {
  759. float zoomX;
  760. if (!read(&zoomX))
  761. {
  762. GP_ERROR("Failed to load camera zoomX in bundle '%s'.", _path.c_str());
  763. return NULL;
  764. }
  765. float zoomY;
  766. if (!read(&zoomY))
  767. {
  768. GP_ERROR("Failed to load camera zoomY in bundle '%s'.", _path.c_str());
  769. return NULL;
  770. }
  771. camera = Camera::createOrthographic(zoomX, zoomY, aspectRatio, nearPlane, farPlane);
  772. }
  773. else
  774. {
  775. GP_ERROR("Unsupported camera type (%d) in bundle '%s'.", cameraType, _path.c_str());
  776. return NULL;
  777. }
  778. return camera;
  779. }
  780. Light* Bundle::readLight()
  781. {
  782. unsigned char type;
  783. if (!read(&type))
  784. {
  785. GP_ERROR("Failed to load light type in bundle '%s'.", _path.c_str());
  786. return NULL;
  787. }
  788. // Check if there isn't a light to load.
  789. if (type == 0)
  790. {
  791. return NULL;
  792. }
  793. // Read color.
  794. float red, blue, green;
  795. if (!read(&red) || !read(&blue) || !read(&green))
  796. {
  797. GP_ERROR("Failed to load light color in bundle '%s'.", _path.c_str());
  798. return NULL;
  799. }
  800. Vector3 color(red, blue, green);
  801. Light* light = NULL;
  802. if (type == Light::DIRECTIONAL)
  803. {
  804. light = Light::createDirectional(color);
  805. }
  806. else if (type == Light::POINT)
  807. {
  808. float range;
  809. if (!read(&range))
  810. {
  811. GP_ERROR("Failed to load point light range in bundle '%s'.", _path.c_str());
  812. return NULL;
  813. }
  814. light = Light::createPoint(color, range);
  815. }
  816. else if (type == Light::SPOT)
  817. {
  818. float range, innerAngle, outerAngle;
  819. if (!read(&range))
  820. {
  821. GP_ERROR("Failed to load spot light range in bundle '%s'.", _path.c_str());
  822. return NULL;
  823. }
  824. if (!read(&innerAngle))
  825. {
  826. GP_ERROR("Failed to load spot light inner angle in bundle '%s'.", _path.c_str());
  827. return NULL;
  828. }
  829. if (!read(&outerAngle))
  830. {
  831. GP_ERROR("Failed to load spot light outer angle in bundle '%s'.", _path.c_str());
  832. return NULL;
  833. }
  834. light = Light::createSpot(color, range, innerAngle, outerAngle);
  835. }
  836. else
  837. {
  838. GP_ERROR("Unsupported light type (%d) in bundle '%s'.", type, _path.c_str());
  839. return NULL;
  840. }
  841. return light;
  842. }
  843. Model* Bundle::readModel(const char* nodeId)
  844. {
  845. // Read mesh.
  846. Mesh* mesh = NULL;
  847. std::string xref = readString(_file);
  848. if (xref.length() > 1 && xref[0] == '#') // TODO: Handle full xrefs
  849. {
  850. mesh = loadMesh(xref.c_str() + 1, nodeId);
  851. if (mesh)
  852. {
  853. Model* model = Model::create(mesh);
  854. SAFE_RELEASE(mesh);
  855. // Read skin.
  856. unsigned char hasSkin;
  857. if (!read(&hasSkin))
  858. {
  859. GP_ERROR("Failed to load whether model with mesh '%s' has a mesh skin in bundle '%s'.", xref.c_str() + 1, _path.c_str());
  860. return NULL;
  861. }
  862. if (hasSkin)
  863. {
  864. MeshSkin* skin = readMeshSkin();
  865. if (skin)
  866. {
  867. model->setSkin(skin);
  868. }
  869. }
  870. // Read material.
  871. unsigned int materialCount;
  872. if (!read(&materialCount))
  873. {
  874. GP_ERROR("Failed to load material count for model with mesh '%s' in bundle '%s'.", xref.c_str() + 1, _path.c_str());
  875. return NULL;
  876. }
  877. if (materialCount > 0)
  878. {
  879. // TODO: Material loading not supported yet.
  880. GP_WARN("Material loading is not yet supported.");
  881. }
  882. return model;
  883. }
  884. }
  885. return NULL;
  886. }
  887. MeshSkin* Bundle::readMeshSkin()
  888. {
  889. MeshSkin* meshSkin = new MeshSkin();
  890. // Read bindShape.
  891. float bindShape[16];
  892. if (!readMatrix(bindShape))
  893. {
  894. GP_ERROR("Failed to load bind shape for mesh skin in bundle '%s'.", _path.c_str());
  895. SAFE_DELETE(meshSkin);
  896. return NULL;
  897. }
  898. meshSkin->setBindShape(bindShape);
  899. MeshSkinData* skinData = new MeshSkinData();
  900. skinData->skin = meshSkin;
  901. // Read joint count.
  902. unsigned int jointCount;
  903. if (!read(&jointCount))
  904. {
  905. GP_ERROR("Failed to load joint count for mesh skin in bundle '%s'.", _path.c_str());
  906. SAFE_DELETE(meshSkin);
  907. SAFE_DELETE(skinData);
  908. return NULL;
  909. }
  910. if (jointCount == 0)
  911. {
  912. GP_ERROR("Invalid joint count (must be greater than 0) for mesh skin in bundle '%s'.", _path.c_str());
  913. SAFE_DELETE(meshSkin);
  914. SAFE_DELETE(skinData);
  915. return NULL;
  916. }
  917. meshSkin->setJointCount(jointCount);
  918. // Read joint xref strings for all joints in the list.
  919. for (unsigned int i = 0; i < jointCount; i++)
  920. {
  921. skinData->joints.push_back(readString(_file));
  922. }
  923. // Read bind poses.
  924. unsigned int jointsBindPosesCount;
  925. if (!read(&jointsBindPosesCount))
  926. {
  927. GP_ERROR("Failed to load number of joint bind poses in bundle '%s'.", _path.c_str());
  928. SAFE_DELETE(meshSkin);
  929. SAFE_DELETE(skinData);
  930. return NULL;
  931. }
  932. if (jointsBindPosesCount > 0)
  933. {
  934. GP_ASSERT(jointCount * 16 == jointsBindPosesCount);
  935. float m[16];
  936. for (unsigned int i = 0; i < jointCount; i++)
  937. {
  938. if (!readMatrix(m))
  939. {
  940. GP_ERROR("Failed to load joint bind pose matrix (for joint with index %d) in bundle '%s'.", i, _path.c_str());
  941. SAFE_DELETE(meshSkin);
  942. SAFE_DELETE(skinData);
  943. return NULL;
  944. }
  945. skinData->inverseBindPoseMatrices.push_back(m);
  946. }
  947. }
  948. // Store the MeshSkinData so we can go back and resolve all joint references later.
  949. _meshSkins.push_back(skinData);
  950. return meshSkin;
  951. }
  952. void Bundle::resolveJointReferences(Scene* sceneContext, Node* nodeContext)
  953. {
  954. GP_ASSERT(_file);
  955. const unsigned int skinCount = _meshSkins.size();
  956. for (unsigned int i = 0; i < skinCount; ++i)
  957. {
  958. MeshSkinData* skinData = _meshSkins[i];
  959. GP_ASSERT(skinData);
  960. GP_ASSERT(skinData->skin);
  961. // Resolve all joints in skin joint list.
  962. const unsigned int jointCount = skinData->joints.size();
  963. for (unsigned int j = 0; j < jointCount; ++j)
  964. {
  965. // TODO: Handle full xrefs (not just local # xrefs).
  966. std::string jointId = skinData->joints[j];
  967. if (jointId.length() > 1 && jointId[0] == '#')
  968. {
  969. jointId = jointId.substr(1, jointId.length() - 1);
  970. Node* n = loadNode(jointId.c_str(), sceneContext, nodeContext);
  971. if (n && n->getType() == Node::JOINT)
  972. {
  973. Joint* joint = static_cast<Joint*>(n);
  974. joint->setInverseBindPose(skinData->inverseBindPoseMatrices[j]);
  975. skinData->skin->setJoint(joint, j);
  976. SAFE_RELEASE(joint);
  977. }
  978. }
  979. }
  980. // Set the root joint.
  981. if (jointCount > 0)
  982. {
  983. Joint* rootJoint = skinData->skin->getJoint((unsigned int)0);
  984. Node* node = rootJoint;
  985. GP_ASSERT(node);
  986. Node* parent = node->getParent();
  987. std::vector<Node*> loadedNodes;
  988. while (true)
  989. {
  990. if (parent)
  991. {
  992. if (skinData->skin->getJointIndex(static_cast<Joint*>(parent)) != -1)
  993. {
  994. // Parent is a joint in the MeshSkin, so treat it as the new root.
  995. rootJoint = static_cast<Joint*>(parent);
  996. }
  997. node = parent;
  998. parent = node->getParent();
  999. }
  1000. else
  1001. {
  1002. // No parent currently set for this joint.
  1003. // Lookup its parentID in case it references a node that was not yet loaded as part
  1004. // of the mesh skin's joint list.
  1005. std::string nodeId = node->getId();
  1006. while (true)
  1007. {
  1008. // Get the node's type.
  1009. Reference* ref = find(nodeId.c_str());
  1010. if (ref == NULL)
  1011. {
  1012. GP_ERROR("No object with name '%s' in bundle '%s'.", nodeId.c_str(), _path.c_str());
  1013. return;
  1014. }
  1015. // Seek to the current node in the file so we can get it's parent ID.
  1016. seekTo(nodeId.c_str(), ref->type);
  1017. // Skip over the node type (1 unsigned int) and transform (16 floats) and read the parent id.
  1018. if (fseek(_file, sizeof(unsigned int) + sizeof(float)*16, SEEK_CUR) != 0)
  1019. {
  1020. GP_ERROR("Failed to skip over node type and transform for node '%s' in bundle '%s'.", nodeId.c_str(), _path.c_str());
  1021. return;
  1022. }
  1023. std::string parentID = readString(_file);
  1024. if (!parentID.empty())
  1025. nodeId = parentID;
  1026. else
  1027. break;
  1028. }
  1029. if (nodeId != rootJoint->getId())
  1030. loadedNodes.push_back(loadNode(nodeId.c_str(), sceneContext, nodeContext));
  1031. break;
  1032. }
  1033. }
  1034. skinData->skin->setRootJoint(rootJoint);
  1035. // Release all the nodes that we loaded since the nodes are now owned by the mesh skin/joints.
  1036. for (unsigned int i = 0; i < loadedNodes.size(); i++)
  1037. {
  1038. SAFE_RELEASE(loadedNodes[i]);
  1039. }
  1040. }
  1041. // Remove the joint hierarchy from the scene since it is owned by the mesh skin.
  1042. if (sceneContext)
  1043. sceneContext->removeNode(skinData->skin->_rootNode);
  1044. // Done with this MeshSkinData entry.
  1045. SAFE_DELETE(_meshSkins[i]);
  1046. }
  1047. _meshSkins.clear();
  1048. }
  1049. void Bundle::readAnimation(Scene* scene)
  1050. {
  1051. const std::string animationId = readString(_file);
  1052. // Read the number of animation channels in this animation.
  1053. unsigned int animationChannelCount;
  1054. if (!read(&animationChannelCount))
  1055. {
  1056. GP_ERROR("Failed to read animation channel count for animation '%s'.", animationId.c_str());
  1057. return;
  1058. }
  1059. Animation* animation = NULL;
  1060. for (unsigned int i = 0; i < animationChannelCount; i++)
  1061. {
  1062. animation = readAnimationChannel(scene, animation, animationId.c_str());
  1063. }
  1064. }
  1065. void Bundle::readAnimations(Scene* scene)
  1066. {
  1067. // Read the number of animations in this object.
  1068. unsigned int animationCount;
  1069. if (!read(&animationCount))
  1070. {
  1071. GP_ERROR("Failed to read the number of animations in the scene.");
  1072. return;
  1073. }
  1074. for (unsigned int i = 0; i < animationCount; i++)
  1075. {
  1076. readAnimation(scene);
  1077. }
  1078. }
  1079. Animation* Bundle::readAnimationChannel(Scene* scene, Animation* animation, const char* animationId)
  1080. {
  1081. GP_ASSERT(animationId);
  1082. // Read target id.
  1083. std::string targetId = readString(_file);
  1084. if (targetId.empty())
  1085. {
  1086. GP_ERROR("Failed to read target id for animation '%s'.", animationId);
  1087. return NULL;
  1088. }
  1089. // Read target attribute.
  1090. unsigned int targetAttribute;
  1091. if (!read(&targetAttribute))
  1092. {
  1093. GP_ERROR("Failed to read target attribute for animation '%s'.", animationId);
  1094. return NULL;
  1095. }
  1096. AnimationTarget* target = NULL;
  1097. // Search for a node that matches the target.
  1098. if (!target)
  1099. {
  1100. target = scene->findNode(targetId.c_str());
  1101. if (!target)
  1102. {
  1103. GP_ERROR("Failed to find the animation target (with id '%s') for animation '%s'.", targetId.c_str(), animationId);
  1104. return NULL;
  1105. }
  1106. }
  1107. return readAnimationChannelData(animation, animationId, target, targetAttribute);
  1108. }
  1109. Animation* Bundle::readAnimationChannelData(Animation* animation, const char* id, AnimationTarget* target, unsigned int targetAttribute)
  1110. {
  1111. GP_ASSERT(id);
  1112. std::vector<unsigned int> keyTimes;
  1113. std::vector<float> values;
  1114. std::vector<float> tangentsIn;
  1115. std::vector<float> tangentsOut;
  1116. std::vector<unsigned int> interpolation;
  1117. // Length of the arrays.
  1118. unsigned int keyTimesCount;
  1119. unsigned int valuesCount;
  1120. unsigned int tangentsInCount;
  1121. unsigned int tangentsOutCount;
  1122. unsigned int interpolationCount;
  1123. // Read key times.
  1124. if (!readArray(&keyTimesCount, &keyTimes, sizeof(unsigned int)))
  1125. {
  1126. GP_ERROR("Failed to read key times for animation '%s'.", id);
  1127. return NULL;
  1128. }
  1129. // Read key values.
  1130. if (!readArray(&valuesCount, &values))
  1131. {
  1132. GP_ERROR("Failed to read key values for animation '%s'.", id);
  1133. return NULL;
  1134. }
  1135. // Read in-tangents.
  1136. if (!readArray(&tangentsInCount, &tangentsIn))
  1137. {
  1138. GP_ERROR("Failed to read in tangents for animation '%s'.", id);
  1139. return NULL;
  1140. }
  1141. // Read out-tangents.
  1142. if (!readArray(&tangentsOutCount, &tangentsOut))
  1143. {
  1144. GP_ERROR("Failed to read out tangents for animation '%s'.", id);
  1145. return NULL;
  1146. }
  1147. // Read interpolations.
  1148. if (!readArray(&interpolationCount, &interpolation, sizeof(unsigned int)))
  1149. {
  1150. GP_ERROR("Failed to read the interpolation values for animation '%s'.", id);
  1151. return NULL;
  1152. }
  1153. if (targetAttribute > 0)
  1154. {
  1155. GP_ASSERT(target);
  1156. GP_ASSERT(keyTimes.size() > 0 && values.size() > 0);
  1157. if (animation == NULL)
  1158. {
  1159. // TODO: This code currently assumes LINEAR only.
  1160. animation = target->createAnimation(id, targetAttribute, keyTimesCount, &keyTimes[0], &values[0], Curve::LINEAR);
  1161. }
  1162. else
  1163. {
  1164. animation->createChannel(target, targetAttribute, keyTimesCount, &keyTimes[0], &values[0], Curve::LINEAR);
  1165. }
  1166. }
  1167. return animation;
  1168. }
  1169. Mesh* Bundle::loadMesh(const char* id)
  1170. {
  1171. return loadMesh(id, NULL);
  1172. }
  1173. Mesh* Bundle::loadMesh(const char* id, const char* nodeId)
  1174. {
  1175. GP_ASSERT(_file);
  1176. GP_ASSERT(id);
  1177. // Save the file position.
  1178. long position = ftell(_file);
  1179. if (position == -1L)
  1180. {
  1181. GP_ERROR("Failed to save the current file position before loading mesh '%s'.", id);
  1182. return NULL;
  1183. }
  1184. // Seek to the specified mesh.
  1185. Reference* ref = seekTo(id, BUNDLE_TYPE_MESH);
  1186. if (ref == NULL)
  1187. {
  1188. GP_ERROR("Failed to locate ref for mesh '%s'.", id);
  1189. return NULL;
  1190. }
  1191. // Read mesh data.
  1192. MeshData* meshData = readMeshData();
  1193. if (meshData == NULL)
  1194. {
  1195. GP_ERROR("Failed to load mesh data for mesh '%s'.", id);
  1196. return NULL;
  1197. }
  1198. // Create mesh.
  1199. Mesh* mesh = Mesh::createMesh(meshData->vertexFormat, meshData->vertexCount, false);
  1200. if (mesh == NULL)
  1201. {
  1202. GP_ERROR("Failed to create mesh '%s'.", id);
  1203. SAFE_DELETE_ARRAY(meshData);
  1204. return NULL;
  1205. }
  1206. mesh->_url = _path;
  1207. mesh->_url += "#";
  1208. mesh->_url += id;
  1209. mesh->setVertexData((float*)meshData->vertexData, 0, meshData->vertexCount);
  1210. mesh->_boundingBox.set(meshData->boundingBox);
  1211. mesh->_boundingSphere.set(meshData->boundingSphere);
  1212. // Create mesh parts.
  1213. for (unsigned int i = 0; i < meshData->parts.size(); ++i)
  1214. {
  1215. MeshPartData* partData = meshData->parts[i];
  1216. GP_ASSERT(partData);
  1217. MeshPart* part = mesh->addPart(partData->primitiveType, partData->indexFormat, partData->indexCount, false);
  1218. if (part == NULL)
  1219. {
  1220. GP_ERROR("Failed to create mesh part (with index %d) for mesh '%s'.", i, id);
  1221. SAFE_DELETE(meshData);
  1222. return NULL;
  1223. }
  1224. part->setIndexData(partData->indexData, 0, partData->indexCount);
  1225. }
  1226. SAFE_DELETE(meshData);
  1227. // Restore file pointer.
  1228. if (fseek(_file, position, SEEK_SET) != 0)
  1229. {
  1230. GP_ERROR("Failed to restore file pointer after loading mesh '%s'.", id);
  1231. return NULL;
  1232. }
  1233. return mesh;
  1234. }
  1235. Bundle::MeshData* Bundle::readMeshData()
  1236. {
  1237. // Read vertex format/elements.
  1238. unsigned int vertexElementCount;
  1239. if (fread(&vertexElementCount, 4, 1, _file) != 1)
  1240. {
  1241. GP_ERROR("Failed to load vertex element count.");
  1242. return NULL;
  1243. }
  1244. if (vertexElementCount < 1)
  1245. {
  1246. GP_ERROR("Failed to load mesh data; invalid vertex element count (must be greater than 0).");
  1247. return NULL;
  1248. }
  1249. VertexFormat::Element* vertexElements = new VertexFormat::Element[vertexElementCount];
  1250. for (unsigned int i = 0; i < vertexElementCount; ++i)
  1251. {
  1252. unsigned int vUsage, vSize;
  1253. if (fread(&vUsage, 4, 1, _file) != 1)
  1254. {
  1255. GP_ERROR("Failed to load vertex usage.");
  1256. SAFE_DELETE_ARRAY(vertexElements);
  1257. return NULL;
  1258. }
  1259. if (fread(&vSize, 4, 1, _file) != 1)
  1260. {
  1261. GP_ERROR("Failed to load vertex size.");
  1262. SAFE_DELETE_ARRAY(vertexElements);
  1263. return NULL;
  1264. }
  1265. vertexElements[i].usage = (VertexFormat::Usage)vUsage;
  1266. vertexElements[i].size = vSize;
  1267. }
  1268. MeshData* meshData = new MeshData(VertexFormat(vertexElements, vertexElementCount));
  1269. SAFE_DELETE_ARRAY(vertexElements);
  1270. // Read vertex data.
  1271. unsigned int vertexByteCount;
  1272. if (fread(&vertexByteCount, 4, 1, _file) != 1)
  1273. {
  1274. GP_ERROR("Failed to load vertex byte count.");
  1275. SAFE_DELETE(meshData);
  1276. return NULL;
  1277. }
  1278. if (vertexByteCount == 0)
  1279. {
  1280. GP_ERROR("Failed to load mesh data; invalid vertex byte count of 0.");
  1281. SAFE_DELETE(meshData);
  1282. return NULL;
  1283. }
  1284. GP_ASSERT(meshData->vertexFormat.getVertexSize());
  1285. meshData->vertexCount = vertexByteCount / meshData->vertexFormat.getVertexSize();
  1286. meshData->vertexData = new unsigned char[vertexByteCount];
  1287. if (fread(meshData->vertexData, 1, vertexByteCount, _file) != vertexByteCount)
  1288. {
  1289. GP_ERROR("Failed to load vertex data.");
  1290. SAFE_DELETE(meshData);
  1291. return NULL;
  1292. }
  1293. // Read mesh bounds (bounding box and bounding sphere).
  1294. if (fread(&meshData->boundingBox.min.x, 4, 3, _file) != 3 || fread(&meshData->boundingBox.max.x, 4, 3, _file) != 3)
  1295. {
  1296. GP_ERROR("Failed to load mesh bounding box.");
  1297. SAFE_DELETE(meshData);
  1298. return NULL;
  1299. }
  1300. if (fread(&meshData->boundingSphere.center.x, 4, 3, _file) != 3 || fread(&meshData->boundingSphere.radius, 4, 1, _file) != 1)
  1301. {
  1302. GP_ERROR("Failed to load mesh bounding sphere.");
  1303. SAFE_DELETE(meshData);
  1304. return NULL;
  1305. }
  1306. // Read mesh parts.
  1307. unsigned int meshPartCount;
  1308. if (fread(&meshPartCount, 4, 1, _file) != 1)
  1309. {
  1310. GP_ERROR("Failed to load mesh part count.");
  1311. SAFE_DELETE(meshData);
  1312. return NULL;
  1313. }
  1314. for (unsigned int i = 0; i < meshPartCount; ++i)
  1315. {
  1316. // Read primitive type, index format and index count.
  1317. unsigned int pType, iFormat, iByteCount;
  1318. if (fread(&pType, 4, 1, _file) != 1)
  1319. {
  1320. GP_ERROR("Failed to load primitive type for mesh part with index %d.", i);
  1321. SAFE_DELETE(meshData);
  1322. return NULL;
  1323. }
  1324. if (fread(&iFormat, 4, 1, _file) != 1)
  1325. {
  1326. GP_ERROR("Failed to load index format for mesh part with index %d.", i);
  1327. SAFE_DELETE(meshData);
  1328. return NULL;
  1329. }
  1330. if (fread(&iByteCount, 4, 1, _file) != 1)
  1331. {
  1332. GP_ERROR("Failed to load index byte count for mesh part with index %d.", i);
  1333. SAFE_DELETE(meshData);
  1334. return NULL;
  1335. }
  1336. MeshPartData* partData = new MeshPartData();
  1337. meshData->parts.push_back(partData);
  1338. partData->primitiveType = (Mesh::PrimitiveType)pType;
  1339. partData->indexFormat = (Mesh::IndexFormat)iFormat;
  1340. unsigned int indexSize = 0;
  1341. switch (partData->indexFormat)
  1342. {
  1343. case Mesh::INDEX8:
  1344. indexSize = 1;
  1345. break;
  1346. case Mesh::INDEX16:
  1347. indexSize = 2;
  1348. break;
  1349. case Mesh::INDEX32:
  1350. indexSize = 4;
  1351. break;
  1352. default:
  1353. GP_ERROR("Unsupported index format for mesh part with index %d.", i);
  1354. return NULL;
  1355. }
  1356. GP_ASSERT(indexSize);
  1357. partData->indexCount = iByteCount / indexSize;
  1358. partData->indexData = new unsigned char[iByteCount];
  1359. if (fread(partData->indexData, 1, iByteCount, _file) != iByteCount)
  1360. {
  1361. GP_ERROR("Failed to read index data for mesh part with index %d.", i);
  1362. SAFE_DELETE(meshData);
  1363. return NULL;
  1364. }
  1365. }
  1366. return meshData;
  1367. }
  1368. Bundle::MeshData* Bundle::readMeshData(const char* url)
  1369. {
  1370. GP_ASSERT(url);
  1371. unsigned int len = strlen(url);
  1372. if (len == 0)
  1373. {
  1374. GP_ERROR("Mesh data URL must be non-empty.");
  1375. return NULL;
  1376. }
  1377. // Parse URL (formatted as 'bundle#id').
  1378. std::string urlstring(url);
  1379. unsigned int pos = urlstring.find('#');
  1380. if (pos == std::string::npos)
  1381. {
  1382. GP_ERROR("Invalid mesh data URL '%s' (must be of the form 'bundle#id').", url);
  1383. return NULL;
  1384. }
  1385. std::string file = urlstring.substr(0, pos);
  1386. std::string id = urlstring.substr(pos + 1);
  1387. // Load bundle.
  1388. Bundle* bundle = Bundle::create(file.c_str());
  1389. if (bundle == NULL)
  1390. {
  1391. GP_ERROR("Failed to load bundle '%s'.", file.c_str());
  1392. return NULL;
  1393. }
  1394. // Seek to mesh with specified ID in bundle.
  1395. Reference* ref = bundle->seekTo(id.c_str(), BUNDLE_TYPE_MESH);
  1396. if (ref == NULL)
  1397. {
  1398. GP_ERROR("Failed to load ref from bundle '%s' for mesh with id '%s'.", file.c_str(), id.c_str());
  1399. return NULL;
  1400. }
  1401. // Read mesh data from current file position.
  1402. MeshData* meshData = bundle->readMeshData();
  1403. SAFE_RELEASE(bundle);
  1404. return meshData;
  1405. }
  1406. Font* Bundle::loadFont(const char* id)
  1407. {
  1408. GP_ASSERT(id);
  1409. GP_ASSERT(_file);
  1410. // Seek to the specified font.
  1411. Reference* ref = seekTo(id, BUNDLE_TYPE_FONT);
  1412. if (ref == NULL)
  1413. {
  1414. GP_ERROR("Failed to load ref for font '%s'.", id);
  1415. return NULL;
  1416. }
  1417. // Read font family.
  1418. std::string family = readString(_file);
  1419. if (family.empty())
  1420. {
  1421. GP_ERROR("Failed to read font family for font '%s'.", id);
  1422. return NULL;
  1423. }
  1424. // Read font style and size.
  1425. unsigned int style, size;
  1426. if (fread(&style, 4, 1, _file) != 1)
  1427. {
  1428. GP_ERROR("Failed to read style for font '%s'.", id);
  1429. return NULL;
  1430. }
  1431. if (fread(&size, 4, 1, _file) != 1)
  1432. {
  1433. GP_ERROR("Failed to read size for font '%s'.", id);
  1434. return NULL;
  1435. }
  1436. // Read character set.
  1437. std::string charset = readString(_file);
  1438. // Read font glyphs.
  1439. unsigned int glyphCount;
  1440. if (fread(&glyphCount, 4, 1, _file) != 1)
  1441. {
  1442. GP_ERROR("Failed to read glyph count for font '%s'.", id);
  1443. return NULL;
  1444. }
  1445. if (glyphCount == 0)
  1446. {
  1447. GP_ERROR("Invalid glyph count (must be greater than 0) for font '%s'.", id);
  1448. return NULL;
  1449. }
  1450. Font::Glyph* glyphs = new Font::Glyph[glyphCount];
  1451. if (fread(glyphs, sizeof(Font::Glyph), glyphCount, _file) != glyphCount)
  1452. {
  1453. GP_ERROR("Failed to read glyphs for font '%s'.", id);
  1454. SAFE_DELETE_ARRAY(glyphs);
  1455. return NULL;
  1456. }
  1457. // Read texture attributes.
  1458. unsigned int width, height, textureByteCount;
  1459. if (fread(&width, 4, 1, _file) != 1)
  1460. {
  1461. GP_ERROR("Failed to read texture width for font '%s'.", id);
  1462. SAFE_DELETE_ARRAY(glyphs);
  1463. return NULL;
  1464. }
  1465. if (fread(&height, 4, 1, _file) != 1)
  1466. {
  1467. GP_ERROR("Failed to read texture height for font '%s'.", id);
  1468. SAFE_DELETE_ARRAY(glyphs);
  1469. return NULL;
  1470. }
  1471. if (fread(&textureByteCount, 4, 1, _file) != 1)
  1472. {
  1473. GP_ERROR("Failed to read texture byte count for font '%s'.", id);
  1474. SAFE_DELETE_ARRAY(glyphs);
  1475. return NULL;
  1476. }
  1477. if (textureByteCount != (width * height))
  1478. {
  1479. GP_ERROR("Invalid texture byte count for font '%s'.", id);
  1480. SAFE_DELETE_ARRAY(glyphs);
  1481. return NULL;
  1482. }
  1483. // Read texture data.
  1484. unsigned char* textureData = new unsigned char[textureByteCount];
  1485. if (fread(textureData, 1, textureByteCount, _file) != textureByteCount)
  1486. {
  1487. GP_ERROR("Failed to read texture data for font '%s'.", id);
  1488. SAFE_DELETE_ARRAY(glyphs);
  1489. SAFE_DELETE_ARRAY(textureData);
  1490. return NULL;
  1491. }
  1492. // Create the texture for the font.
  1493. Texture* texture = Texture::create(Texture::ALPHA, width, height, textureData, true);
  1494. // Free the texture data (no longer needed).
  1495. SAFE_DELETE_ARRAY(textureData);
  1496. if (texture == NULL)
  1497. {
  1498. GP_ERROR("Failed to create texture for font '%s'.", id);
  1499. SAFE_DELETE_ARRAY(glyphs);
  1500. return NULL;
  1501. }
  1502. // Create the font.
  1503. Font* font = Font::create(family.c_str(), Font::PLAIN, size, glyphs, glyphCount, texture);
  1504. // Free the glyph array.
  1505. SAFE_DELETE_ARRAY(glyphs);
  1506. // Release the texture since the Font now owns it.
  1507. SAFE_RELEASE(texture);
  1508. if (font)
  1509. {
  1510. font->_path = _path;
  1511. font->_id = id;
  1512. }
  1513. return font;
  1514. }
  1515. void Bundle::setTransform(const float* values, Transform* transform)
  1516. {
  1517. GP_ASSERT(transform);
  1518. // Load array into transform.
  1519. Matrix matrix(values);
  1520. Vector3 scale, translation;
  1521. Quaternion rotation;
  1522. matrix.decompose(&scale, &rotation, &translation);
  1523. transform->setScale(scale);
  1524. transform->setTranslation(translation);
  1525. transform->setRotation(rotation);
  1526. }
  1527. bool Bundle::contains(const char* id) const
  1528. {
  1529. return (find(id) != NULL);
  1530. }
  1531. unsigned int Bundle::getObjectCount() const
  1532. {
  1533. return _referenceCount;
  1534. }
  1535. const char* Bundle::getObjectId(unsigned int index) const
  1536. {
  1537. GP_ASSERT(_references);
  1538. return (index >= _referenceCount ? NULL : _references[index].id.c_str());
  1539. }
  1540. Bundle::Reference::Reference()
  1541. : type(0), offset(0)
  1542. {
  1543. }
  1544. Bundle::Reference::~Reference()
  1545. {
  1546. }
  1547. Bundle::MeshPartData::MeshPartData() :
  1548. indexCount(0), indexData(NULL)
  1549. {
  1550. }
  1551. Bundle::MeshPartData::~MeshPartData()
  1552. {
  1553. SAFE_DELETE_ARRAY(indexData);
  1554. }
  1555. Bundle::MeshData::MeshData(const VertexFormat& vertexFormat)
  1556. : vertexFormat(vertexFormat), vertexCount(0), vertexData(NULL)
  1557. {
  1558. }
  1559. Bundle::MeshData::~MeshData()
  1560. {
  1561. SAFE_DELETE_ARRAY(vertexData);
  1562. for (unsigned int i = 0; i < parts.size(); ++i)
  1563. {
  1564. SAFE_DELETE(parts[i]);
  1565. }
  1566. }
  1567. }