Bundle.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344
  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 1
  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)
  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. if (!read(length))
  52. {
  53. return false;
  54. }
  55. if (*length > 0)
  56. {
  57. *ptr = new T[*length];
  58. if (fread(*ptr, sizeof(T), *length, _file) != *length)
  59. {
  60. SAFE_DELETE_ARRAY(*ptr);
  61. return false;
  62. }
  63. }
  64. return true;
  65. }
  66. template <class T>
  67. bool Bundle::readArray(unsigned int* length, std::vector<T>* values)
  68. {
  69. if (!read(length))
  70. {
  71. return false;
  72. }
  73. if (*length > 0 && values)
  74. {
  75. values->resize(*length);
  76. if (fread(&(*values)[0], sizeof(T), *length, _file) != *length)
  77. {
  78. return false;
  79. }
  80. }
  81. return true;
  82. }
  83. template <class T>
  84. bool Bundle::readArray(unsigned int* length, std::vector<T>* values, unsigned int readSize)
  85. {
  86. assert(sizeof(T) >= readSize);
  87. if (!read(length))
  88. {
  89. return false;
  90. }
  91. if (*length > 0 && values)
  92. {
  93. values->resize(*length);
  94. if (fread(&(*values)[0], readSize, *length, _file) != *length)
  95. {
  96. return false;
  97. }
  98. }
  99. return true;
  100. }
  101. std::string readString(FILE* fp)
  102. {
  103. unsigned int length;
  104. if (fread(&length, 4, 1, fp) != 1)
  105. {
  106. return std::string();
  107. }
  108. // Sanity check to detect if string length is far too big
  109. assert(length < BUNDLE_MAX_STRING_LENGTH);
  110. std::string str;
  111. if (length > 0)
  112. {
  113. str.resize(length);
  114. if (fread(&str[0], 1, length, fp) != length)
  115. {
  116. return std::string();
  117. }
  118. }
  119. return str;
  120. }
  121. Bundle* Bundle::create(const char* path)
  122. {
  123. // Search the cache for this bundle
  124. for (unsigned int i = 0, count = __bundleCache.size(); i < count; ++i)
  125. {
  126. Bundle* p = __bundleCache[i];
  127. if (p->_path == path)
  128. {
  129. // Found a match
  130. p->addRef();
  131. return p;
  132. }
  133. }
  134. // Open the bundle
  135. FILE* fp = FileSystem::openFile(path, "rb");
  136. if (!fp)
  137. {
  138. WARN_VARG("Failed to open file: '%s'.", path);
  139. return NULL;
  140. }
  141. // Read the GPG header info
  142. char sig[9];
  143. if (fread(sig, 1, 9, fp) != 9 || memcmp(sig, "«GPB»\r\n\x1A\n", 9) != 0)
  144. {
  145. LOG_ERROR_VARG("Invalid bundle header: %s", path);
  146. fclose(fp);
  147. return NULL;
  148. }
  149. // Read version
  150. unsigned char ver[2];
  151. if (fread(ver, 1, 2, fp) != 2 || ver[0] != BUNDLE_VERSION_MAJOR || ver[1] != BUNDLE_VERSION_MINOR)
  152. {
  153. LOG_ERROR_VARG("Unsupported version (%d.%d) for bundle: %s (expected %d.%d)", (int)ver[0], (int)ver[1], path, BUNDLE_VERSION_MAJOR, BUNDLE_VERSION_MINOR);
  154. fclose(fp);
  155. return NULL;
  156. }
  157. // Read ref table
  158. unsigned int refCount;
  159. if (fread(&refCount, 4, 1, fp) != 1)
  160. {
  161. fclose(fp);
  162. return NULL;
  163. }
  164. // Read all refs
  165. Reference* refs = new Reference[refCount];
  166. for (unsigned int i = 0; i < refCount; ++i)
  167. {
  168. if ((refs[i].id = readString(fp)).empty() ||
  169. fread(&refs[i].type, 4, 1, fp) != 1 ||
  170. fread(&refs[i].offset, 4, 1, fp) != 1)
  171. {
  172. fclose(fp);
  173. SAFE_DELETE_ARRAY(refs);
  174. return NULL;
  175. }
  176. }
  177. // Keep file open for faster reading later
  178. Bundle* bundle = new Bundle(path);
  179. bundle->_referenceCount = refCount;
  180. bundle->_references = refs;
  181. bundle->_file = fp;
  182. return bundle;
  183. }
  184. Bundle::Reference* Bundle::find(const char* id) const
  185. {
  186. // Search the ref table for the given id (case-sensitive)
  187. for (unsigned int i = 0; i < _referenceCount; ++i)
  188. {
  189. if (_references[i].id == id)
  190. {
  191. // Found a match
  192. return &_references[i];
  193. }
  194. }
  195. return NULL;
  196. }
  197. void Bundle::clearLoadSession()
  198. {
  199. for (unsigned int i = 0, count = _meshSkins.size(); i < count; ++i)
  200. {
  201. SAFE_DELETE(_meshSkins[i]);
  202. }
  203. _meshSkins.clear();
  204. }
  205. const char* Bundle::getIdFromOffset() const
  206. {
  207. return getIdFromOffset((unsigned int) ftell(_file));
  208. }
  209. const char* Bundle::getIdFromOffset(unsigned int offset) const
  210. {
  211. // Search the ref table for the given offset
  212. if (offset > 0)
  213. {
  214. for (unsigned int i = 0; i < _referenceCount; ++i)
  215. {
  216. if (_references[i].offset == offset && _references[i].id.length() > 0)
  217. {
  218. return _references[i].id.c_str();
  219. }
  220. }
  221. }
  222. return NULL;
  223. }
  224. Bundle::Reference* Bundle::seekTo(const char* id, unsigned int type)
  225. {
  226. Reference* ref = find(id);
  227. if (ref == NULL)
  228. {
  229. LOG_ERROR_VARG("No object with name '%s' in bundle '%s'.", id, _path.c_str());
  230. return NULL;
  231. }
  232. if (ref->type != type)
  233. {
  234. LOG_ERROR_VARG("Object '%s' in bundle '%s' has type %d (expected type %d).", id, _path.c_str(), (int)ref->type, (int)type);
  235. return NULL;
  236. }
  237. // Seek to the offset of this object
  238. if (fseek(_file, ref->offset, SEEK_SET) != 0)
  239. {
  240. LOG_ERROR_VARG("Failed to seek to object '%s' in bundle '%s'.", id, _path.c_str());
  241. return NULL;
  242. }
  243. return ref;
  244. }
  245. Bundle::Reference* Bundle::seekToFirstType(unsigned int type)
  246. {
  247. // for each Reference
  248. for (unsigned int i = 0; i < _referenceCount; ++i)
  249. {
  250. Reference* ref = &_references[i];
  251. if (ref->type == type)
  252. {
  253. // Found a match
  254. if (fseek(_file, ref->offset, SEEK_SET) != 0)
  255. {
  256. LOG_ERROR_VARG("Failed to seek to object '%s' in bundle '%s'.", ref->id.c_str(), _path.c_str());
  257. return NULL;
  258. }
  259. return ref;
  260. }
  261. }
  262. return NULL;
  263. }
  264. bool Bundle::read(unsigned int* ptr)
  265. {
  266. return fread(ptr, sizeof(unsigned int), 1, _file) == 1;
  267. }
  268. bool Bundle::read(unsigned char* ptr)
  269. {
  270. return fread(ptr, sizeof(unsigned char), 1, _file) == 1;
  271. }
  272. bool Bundle::read(float* ptr)
  273. {
  274. return fread(ptr, sizeof(float), 1, _file) == 1;
  275. }
  276. bool Bundle::readMatrix(float* m)
  277. {
  278. return (fread(m, sizeof(float), 16, _file) == 16);
  279. }
  280. Scene* Bundle::loadScene(const char* id)
  281. {
  282. clearLoadSession();
  283. Reference* ref = NULL;
  284. if (id)
  285. {
  286. ref = seekTo(id, BUNDLE_TYPE_SCENE);
  287. }
  288. else
  289. {
  290. ref = seekToFirstType(BUNDLE_TYPE_SCENE);
  291. }
  292. if (!ref)
  293. {
  294. return NULL;
  295. }
  296. Scene* scene = Scene::createScene();
  297. scene->setId(getIdFromOffset());
  298. // Read the number of children
  299. unsigned int childrenCount;
  300. if (!read(&childrenCount))
  301. {
  302. SAFE_RELEASE(scene);
  303. return NULL;
  304. }
  305. if (childrenCount > 0)
  306. {
  307. // Read each child directly into the scene
  308. for (unsigned int i = 0; i < childrenCount; i++)
  309. {
  310. Node* node = readNode(scene, NULL);
  311. if (node)
  312. {
  313. scene->addNode(node);
  314. node->release(); // scene now owns node
  315. }
  316. }
  317. }
  318. // Read active camera
  319. std::string xref = readString(_file);
  320. if (xref.length() > 1 && xref[0] == '#') // TODO: Handle full xrefs
  321. {
  322. Node* node = scene->findNode(xref.c_str() + 1, true);
  323. Camera* camera = node->getCamera();
  324. assert(camera);
  325. scene->setActiveCamera(camera);
  326. }
  327. // Read ambient color
  328. float red, blue, green;
  329. if (!read(&red))
  330. {
  331. SAFE_RELEASE(scene);
  332. LOG_ERROR_VARG("Failed to read scene ambient %s color in pakcage %s", "red", _path.c_str());
  333. return NULL;
  334. }
  335. if (!read(&green))
  336. {
  337. SAFE_RELEASE(scene);
  338. LOG_ERROR_VARG("Failed to read scene ambient %s color in pakcage %s", "green", _path.c_str());
  339. return NULL;
  340. }
  341. if (!read(&blue))
  342. {
  343. SAFE_RELEASE(scene);
  344. LOG_ERROR_VARG("Failed to read scene ambient %s color in pakcage %s", "blue", _path.c_str());
  345. return NULL;
  346. }
  347. scene->setAmbientColor(red, green, blue);
  348. // parse animations
  349. for (unsigned int i = 0; i < _referenceCount; ++i)
  350. {
  351. Reference* ref = &_references[i];
  352. if (ref->type == BUNDLE_TYPE_ANIMATIONS)
  353. {
  354. // Found a match
  355. if (fseek(_file, ref->offset, SEEK_SET) != 0)
  356. {
  357. LOG_ERROR_VARG("Failed to seek to object '%s' in bundle '%s'.", ref->id.c_str(), _path.c_str());
  358. return NULL;
  359. }
  360. readAnimations(scene);
  361. }
  362. }
  363. resolveJointReferences(scene, NULL);
  364. return scene;
  365. }
  366. Node* Bundle::loadNode(const char* id)
  367. {
  368. assert(id);
  369. clearLoadSession();
  370. Node* node = loadNode(id, NULL, NULL);
  371. if (node)
  372. {
  373. resolveJointReferences(NULL, node);
  374. }
  375. return node;
  376. }
  377. Node* Bundle::loadNode(const char* id, Scene* sceneContext, Node* nodeContext)
  378. {
  379. assert(id);
  380. Node* node = NULL;
  381. // Search the passed in loading contexts (scene/node) first to see
  382. // if we've already loaded this node during this load session
  383. if (sceneContext)
  384. {
  385. node = sceneContext->findNode(id, true);
  386. }
  387. else if (nodeContext)
  388. {
  389. node = nodeContext->findNode(id, true);
  390. }
  391. if (node == NULL)
  392. {
  393. // If not yet found, search the ref table and read
  394. Reference* ref = seekTo(id, BUNDLE_TYPE_NODE);
  395. if (ref == NULL)
  396. {
  397. return NULL;
  398. }
  399. node = readNode(sceneContext, nodeContext);
  400. }
  401. return node;
  402. }
  403. Node* Bundle::readNode(Scene* sceneContext, Node* nodeContext)
  404. {
  405. const char* id = getIdFromOffset();
  406. // Read node type
  407. unsigned int nodeType;
  408. if (!read(&nodeType))
  409. {
  410. return NULL;
  411. }
  412. Node* node = NULL;
  413. switch (nodeType)
  414. {
  415. case Node::NODE:
  416. node = Node::create(id);
  417. break;
  418. case Node::JOINT:
  419. node = Joint::create(id);
  420. break;
  421. default:
  422. return NULL;
  423. }
  424. // If no loading context is set, set this node to the loading context
  425. if (sceneContext == NULL && nodeContext == NULL)
  426. {
  427. nodeContext = node;
  428. }
  429. // Read transform
  430. float transform[16];
  431. if (fread(transform, sizeof(float), 16, _file) != 16)
  432. {
  433. SAFE_RELEASE(node);
  434. return NULL;
  435. }
  436. setTransform(transform, node);
  437. // Read children
  438. unsigned int childrenCount;
  439. if (!read(&childrenCount))
  440. {
  441. SAFE_RELEASE(node);
  442. return NULL;
  443. }
  444. if (childrenCount > 0)
  445. {
  446. // Read each child
  447. for (unsigned int i = 0; i < childrenCount; i++)
  448. {
  449. Node* child = readNode(sceneContext, nodeContext);
  450. if (child)
  451. {
  452. node->addChild(child);
  453. child->release(); // 'node' now owns this child
  454. }
  455. }
  456. }
  457. // Read camera
  458. Camera* camera = readCamera();
  459. if (camera)
  460. {
  461. node->setCamera(camera);
  462. SAFE_RELEASE(camera);
  463. }
  464. // Read light
  465. Light* light = readLight();
  466. if (light)
  467. {
  468. node->setLight(light);
  469. SAFE_RELEASE(light);
  470. }
  471. // Read model
  472. Model* model = readModel(sceneContext, nodeContext, node->getId());
  473. if (model)
  474. {
  475. node->setModel(model);
  476. SAFE_RELEASE(model);
  477. }
  478. return node;
  479. }
  480. Camera* Bundle::readCamera()
  481. {
  482. unsigned char cameraType;
  483. if (!read(&cameraType))
  484. {
  485. LOG_ERROR_VARG("Failed to load camera type in bundle '%s'.", _path.c_str());
  486. }
  487. if (cameraType == 0)
  488. {
  489. return NULL;
  490. }
  491. // aspect ratio
  492. float aspectRatio;
  493. if (!read(&aspectRatio))
  494. {
  495. LOG_ERROR_VARG("Failed to load camera aspectRatio in bundle '%s'.", _path.c_str());
  496. }
  497. // near plane
  498. float nearPlane;
  499. if (!read(&nearPlane))
  500. {
  501. LOG_ERROR_VARG("Failed to load camera near plane in bundle '%s'.", _path.c_str());
  502. }
  503. // far plane
  504. float farPlane;
  505. if (!read(&farPlane))
  506. {
  507. LOG_ERROR_VARG("Failed to load camera far plane in bundle '%s'.", _path.c_str());
  508. }
  509. Camera* camera = NULL;
  510. if (cameraType == Camera::PERSPECTIVE)
  511. {
  512. // field of view
  513. float fieldOfView;
  514. if (!read(&fieldOfView))
  515. {
  516. LOG_ERROR_VARG("Failed to load camera field of view in bundle '%s'.", _path.c_str());
  517. }
  518. camera = Camera::createPerspective(fieldOfView, aspectRatio, nearPlane, farPlane);
  519. }
  520. else if (cameraType == Camera::ORTHOGRAPHIC)
  521. {
  522. // magnification
  523. float zoomX;
  524. if (!read(&zoomX))
  525. {
  526. LOG_ERROR_VARG("Failed to load camera zoomX in bundle '%s'.", _path.c_str());
  527. }
  528. float zoomY;
  529. if (!read(&zoomY))
  530. {
  531. LOG_ERROR_VARG("Failed to load camera zoomY in bundle '%s'.", _path.c_str());
  532. }
  533. camera = Camera::createOrthographic(zoomX, zoomY, aspectRatio, nearPlane, farPlane);
  534. }
  535. else
  536. {
  537. LOG_ERROR_VARG("Failed to load camera type in bundle '%s'. Invalid camera type.", _path.c_str());
  538. }
  539. return camera;
  540. }
  541. Light* Bundle::readLight()
  542. {
  543. unsigned char type;
  544. if (!read(&type))
  545. {
  546. LOG_ERROR_VARG("Failed to load light %s in bundle '%s'.", "type", _path.c_str());
  547. }
  548. if (type == 0)
  549. {
  550. return NULL;
  551. }
  552. // read color
  553. float red, blue, green;
  554. if (!read(&red) || !read(&blue) || !read(&green))
  555. {
  556. LOG_ERROR_VARG("Failed to load light %s in bundle '%s'.", "color", _path.c_str());
  557. }
  558. Vector3 color(red, blue, green);
  559. Light* light = NULL;
  560. if (type == Light::DIRECTIONAL)
  561. {
  562. light = Light::createDirectional(color);
  563. }
  564. else if (type == Light::POINT)
  565. {
  566. float range;
  567. if (!read(&range))
  568. {
  569. LOG_ERROR_VARG("Failed to load point light %s in bundle '%s'.", "point", _path.c_str());
  570. }
  571. light = Light::createPoint(color, range);
  572. }
  573. else if (type == Light::SPOT)
  574. {
  575. float range, innerAngle, outerAngle;
  576. if (!read(&range) || !read(&innerAngle) || !read(&outerAngle))
  577. {
  578. LOG_ERROR_VARG("Failed to load spot light %s in bundle '%s'.", "spot", _path.c_str());
  579. }
  580. light = Light::createSpot(color, range, innerAngle, outerAngle);
  581. }
  582. else
  583. {
  584. LOG_ERROR_VARG("Failed to load light %s in bundle '%s'.", "type", _path.c_str());
  585. }
  586. return light;
  587. }
  588. Model* Bundle::readModel(Scene* sceneContext, Node* nodeContext, const char* nodeId)
  589. {
  590. // Read mesh
  591. Mesh* mesh = NULL;
  592. std::string xref = readString(_file);
  593. if (xref.length() > 1 && xref[0] == '#') // TODO: Handle full xrefs
  594. {
  595. mesh = loadMesh(xref.c_str() + 1, nodeId);
  596. if (mesh)
  597. {
  598. Model* model = Model::create(mesh);
  599. SAFE_RELEASE(mesh);
  600. // Read skin
  601. unsigned char hasSkin;
  602. if (!read(&hasSkin))
  603. {
  604. LOG_ERROR_VARG("Failed to load hasSkin in bundle '%s'.", _path.c_str());
  605. return NULL;
  606. }
  607. if (hasSkin)
  608. {
  609. MeshSkin* skin = readMeshSkin(sceneContext, nodeContext);
  610. if (skin)
  611. {
  612. model->setSkin(skin);
  613. }
  614. }
  615. // Read material
  616. unsigned int materialCount;
  617. if (!read(&materialCount))
  618. {
  619. LOG_ERROR_VARG("Failed to load materialCount in bundle '%s'.", _path.c_str());
  620. return NULL;
  621. }
  622. if (materialCount > 0)
  623. {
  624. // TODO: Material loading not supported yet
  625. }
  626. return model;
  627. }
  628. }
  629. return NULL;
  630. }
  631. MeshSkin* Bundle::readMeshSkin(Scene* sceneContext, Node* nodeContext)
  632. {
  633. MeshSkin* meshSkin = new MeshSkin();
  634. // Read bindShape
  635. float bindShape[16];
  636. if (!readMatrix(bindShape))
  637. {
  638. LOG_ERROR_VARG("Failed to load MeshSkin in bundle '%s'.", _path.c_str());
  639. SAFE_DELETE(meshSkin);
  640. return NULL;
  641. }
  642. meshSkin->setBindShape(bindShape);
  643. MeshSkinData* skinData = new MeshSkinData();
  644. skinData->skin = meshSkin;
  645. // Read joint count
  646. unsigned int jointCount;
  647. if (!read(&jointCount))
  648. {
  649. LOG_ERROR_VARG("Failed to load MeshSkin in bundle '%s'.", _path.c_str());
  650. SAFE_DELETE(meshSkin);
  651. SAFE_DELETE(skinData);
  652. return NULL;
  653. }
  654. if (jointCount == 0)
  655. {
  656. SAFE_DELETE(meshSkin);
  657. SAFE_DELETE(skinData);
  658. return NULL;
  659. }
  660. meshSkin->setJointCount(jointCount);
  661. // Read joint xref strings for all joints in the list
  662. for (unsigned int i = 0; i < jointCount; i++)
  663. {
  664. skinData->joints.push_back(readString(_file));
  665. }
  666. // read bindposes
  667. unsigned int jointsBindPosesCount;
  668. if (!read(&jointsBindPosesCount))
  669. {
  670. LOG_ERROR_VARG("Failed to load MeshSkin in bundle '%s'.", _path.c_str());
  671. SAFE_DELETE(meshSkin);
  672. SAFE_DELETE(skinData);
  673. return NULL;
  674. }
  675. if (jointsBindPosesCount > 0)
  676. {
  677. assert(jointCount * 16 == jointsBindPosesCount);
  678. float m[16];
  679. for (unsigned int i = 0; i < jointCount; i++)
  680. {
  681. if (!readMatrix(m))
  682. {
  683. LOG_ERROR_VARG("Failed to load MeshSkin in bundle '%s'.", _path.c_str());
  684. SAFE_DELETE(meshSkin);
  685. SAFE_DELETE(skinData);
  686. return NULL;
  687. }
  688. skinData->inverseBindPoseMatrices.push_back(m);
  689. }
  690. }
  691. // Store the MeshSkinData so we can go back and resolve all joint references later
  692. _meshSkins.push_back(skinData);
  693. return meshSkin;
  694. }
  695. void Bundle::resolveJointReferences(Scene* sceneContext, Node* nodeContext)
  696. {
  697. const unsigned int skinCount = _meshSkins.size();
  698. for (unsigned int i = 0; i < skinCount; ++i)
  699. {
  700. MeshSkinData* skinData = _meshSkins[i];
  701. // Resolve all joints in skin joint list
  702. const unsigned int jointCount = skinData->joints.size();
  703. for (unsigned int j = 0; j < jointCount; ++j)
  704. {
  705. // TODO: Handle full xrefs (not just local # xrefs)
  706. std::string jointId = skinData->joints[j];
  707. if (jointId.length() > 1 && jointId[0] == '#')
  708. {
  709. jointId = jointId.substr(1, jointId.length() - 1);
  710. Node* n = loadNode(jointId.c_str(), sceneContext, nodeContext);
  711. if (n && n->getType() == Node::JOINT)
  712. {
  713. Joint* joint = static_cast<Joint*>(n);
  714. joint->setInverseBindPose(skinData->inverseBindPoseMatrices[j]);
  715. skinData->skin->setJoint(joint, j);
  716. }
  717. }
  718. }
  719. // Set the root joint
  720. if (jointCount > 0)
  721. {
  722. Joint* rootJoint = skinData->skin->getJoint((unsigned int)0);
  723. Node* parent = rootJoint->getParent();
  724. while (parent)
  725. {
  726. if (skinData->skin->getJointIndex(static_cast<Joint*>(parent)) != -1)
  727. {
  728. // Parent is a joint in the MeshSkin, so treat it as the new root
  729. rootJoint = static_cast<Joint*>(parent);
  730. }
  731. parent = parent->getParent();
  732. }
  733. skinData->skin->setRootJoint(rootJoint);
  734. }
  735. // Done with this MeshSkinData entry
  736. SAFE_DELETE(_meshSkins[i]);
  737. }
  738. _meshSkins.clear();
  739. }
  740. void Bundle::readAnimation(Scene* scene)
  741. {
  742. const std::string animationId = readString(_file);
  743. // read the number of animation channels in this animation
  744. unsigned int animationChannelCount;
  745. if (!read(&animationChannelCount))
  746. {
  747. LOG_ERROR_VARG("Failed to read %s for %s: %s", "animationChannelCount", "animation", animationId.c_str());
  748. return;
  749. }
  750. Animation* animation = NULL;
  751. for (unsigned int i = 0; i < animationChannelCount; i++)
  752. {
  753. animation = readAnimationChannel(scene, animation, animationId.c_str());
  754. }
  755. }
  756. void Bundle::readAnimations(Scene* scene)
  757. {
  758. // read the number of animations in this object
  759. unsigned int animationCount;
  760. if (!read(&animationCount))
  761. {
  762. LOG_ERROR_VARG("Failed to read %s for %s: %s", "animationCount", "Animations");
  763. return;
  764. }
  765. for (unsigned int i = 0; i < animationCount; i++)
  766. {
  767. readAnimation(scene);
  768. }
  769. }
  770. Animation* Bundle::readAnimationChannel(Scene* scene, Animation* animation, const char* animationId)
  771. {
  772. const char* id = animationId;
  773. // read targetId
  774. std::string targetId = readString(_file);
  775. if (targetId.empty())
  776. {
  777. LOG_ERROR_VARG("Failed to read %s for %s: %s", "targetId", "animation", id);
  778. return NULL;
  779. }
  780. // read target attribute
  781. unsigned int targetAttribute;
  782. if (!read(&targetAttribute))
  783. {
  784. LOG_ERROR_VARG("Failed to read %s for %s: %s", "targetAttribute", "animation", id);
  785. return NULL;
  786. }
  787. //long position = ftell(_file);
  788. //fseek(_file, position, SEEK_SET);
  789. AnimationTarget* target = NULL;
  790. // Search for a node that matches target
  791. if (!target)
  792. {
  793. target = scene->findNode(targetId.c_str());
  794. if (!target)
  795. {
  796. LOG_ERROR_VARG("Failed to read %s for %s: %s", "animation target", targetId.c_str(), id);
  797. return NULL;
  798. }
  799. }
  800. std::vector<unsigned long> keyTimes;
  801. std::vector<float> values;
  802. std::vector<float> tangentsIn;
  803. std::vector<float> tangentsOut;
  804. std::vector<unsigned long> interpolation;
  805. // length of the arrays
  806. unsigned int keyTimesCount;
  807. unsigned int valuesCount;
  808. unsigned int tangentsInCount;
  809. unsigned int tangentsOutCount;
  810. unsigned int interpolationCount;
  811. // read key times
  812. if (!readArray(&keyTimesCount, &keyTimes, sizeof(unsigned int)))
  813. {
  814. LOG_ERROR_VARG("Failed to read %s for %s: %s", "keyTimes", "animation", id);
  815. return NULL;
  816. }
  817. // read key values
  818. if (!readArray(&valuesCount, &values))
  819. {
  820. LOG_ERROR_VARG("Failed to read %s for %s: %s", "values", "animation", id);
  821. return NULL;
  822. }
  823. // read tangentsIn
  824. if (!readArray(&tangentsInCount, &tangentsIn))
  825. {
  826. LOG_ERROR_VARG("Failed to read %s for %s: %s", "tangentsIn", "animation", id);
  827. return NULL;
  828. }
  829. // read tangent_out
  830. if (!readArray(&tangentsOutCount, &tangentsOut))
  831. {
  832. LOG_ERROR_VARG("Failed to read %s for %s: %s", "tangentsOut", "animation", id);
  833. return NULL;
  834. }
  835. // read interpolations
  836. if (!readArray(&interpolationCount, &interpolation, sizeof(unsigned int)))
  837. {
  838. LOG_ERROR_VARG("Failed to read %s for %s: %s", "interpolation", "animation", id);
  839. return NULL;
  840. }
  841. Game* game = Game::getInstance();
  842. AnimationController* controller = game->getAnimationController();
  843. // TODO: Handle other target attributes later.
  844. if (targetAttribute > 0)
  845. {
  846. assert(keyTimes.size() > 0 && values.size() > 0);
  847. if (animation == NULL)
  848. {
  849. // TODO: This code currently assumes LINEAR only
  850. animation = target->createAnimation(animationId, targetAttribute, keyTimesCount, &keyTimes[0], &values[0], Curve::LINEAR);
  851. }
  852. else
  853. {
  854. animation->createChannel(target, targetAttribute, keyTimesCount, &keyTimes[0], &values[0], Curve::LINEAR);
  855. }
  856. }
  857. return animation;
  858. }
  859. Mesh* Bundle::loadMesh(const char* id)
  860. {
  861. return loadMesh(id, false);
  862. }
  863. Mesh* Bundle::loadMesh(const char* id, const char* nodeId)
  864. {
  865. // Save the file position
  866. long position = ftell(_file);
  867. // Seek to the specified Mesh
  868. Reference* ref = seekTo(id, BUNDLE_TYPE_MESH);
  869. if (ref == NULL)
  870. {
  871. return NULL;
  872. }
  873. // Read mesh data
  874. MeshData* meshData = readMeshData();
  875. if (meshData == NULL)
  876. {
  877. return NULL;
  878. }
  879. // Create Mesh
  880. Mesh* mesh = Mesh::createMesh(meshData->vertexFormat, meshData->vertexCount, false);
  881. if (mesh == NULL)
  882. {
  883. LOG_ERROR_VARG("Failed to create mesh: %s", id);
  884. SAFE_DELETE_ARRAY(meshData);
  885. return NULL;
  886. }
  887. mesh->_url = _path;
  888. mesh->_url += "#";
  889. mesh->_url += id;
  890. mesh->setVertexData(meshData->vertexData, 0, meshData->vertexCount);
  891. mesh->_boundingBox.set(meshData->boundingBox);
  892. mesh->_boundingSphere.set(meshData->boundingSphere);
  893. // Create mesh parts
  894. for (unsigned int i = 0; i < meshData->parts.size(); ++i)
  895. {
  896. MeshPartData* partData = meshData->parts[i];
  897. MeshPart* part = mesh->addPart(partData->primitiveType, partData->indexFormat, partData->indexCount, false);
  898. if (part == NULL)
  899. {
  900. LOG_ERROR_VARG("Failed to create mesh part (i=%d): %s", i, id);
  901. SAFE_DELETE(meshData);
  902. return NULL;
  903. }
  904. part->setIndexData(partData->indexData, 0, partData->indexCount);
  905. }
  906. SAFE_DELETE(meshData);
  907. // Restore file pointer
  908. fseek(_file, position, SEEK_SET);
  909. return mesh;
  910. }
  911. Bundle::MeshData* Bundle::readMeshData()
  912. {
  913. // Read vertex format/elements
  914. unsigned int vertexElementCount;
  915. if (fread(&vertexElementCount, 4, 1, _file) != 1 || vertexElementCount < 1)
  916. {
  917. return NULL;
  918. }
  919. VertexFormat::Element* vertexElements = new VertexFormat::Element[vertexElementCount];
  920. for (unsigned int i = 0; i < vertexElementCount; ++i)
  921. {
  922. unsigned int vUsage, vSize;
  923. if (fread(&vUsage, 4, 1, _file) != 1 || fread(&vSize, 4, 1, _file) != 1)
  924. {
  925. SAFE_DELETE_ARRAY(vertexElements);
  926. return NULL;
  927. }
  928. vertexElements[i].usage = (VertexFormat::Usage)vUsage;
  929. vertexElements[i].size = vSize;
  930. }
  931. MeshData* meshData = new MeshData(VertexFormat(vertexElements, vertexElementCount));
  932. SAFE_DELETE_ARRAY(vertexElements);
  933. // Read vertex data
  934. unsigned int vertexByteCount;
  935. if (fread(&vertexByteCount, 4, 1, _file) != 1 || vertexByteCount == 0)
  936. {
  937. SAFE_DELETE(meshData);
  938. return NULL;
  939. }
  940. meshData->vertexCount = vertexByteCount / meshData->vertexFormat.getVertexSize();
  941. meshData->vertexData = new unsigned char[vertexByteCount];
  942. if (fread(meshData->vertexData, 1, vertexByteCount, _file) != vertexByteCount)
  943. {
  944. SAFE_DELETE(meshData);
  945. return NULL;
  946. }
  947. // Read mesh bounds (bounding box and bounding sphere)
  948. if (fread(&meshData->boundingBox.min.x, 4, 3, _file) != 3 || fread(&meshData->boundingBox.max.x, 4, 3, _file) != 3)
  949. {
  950. SAFE_DELETE(meshData);
  951. return NULL;
  952. }
  953. if (fread(&meshData->boundingSphere.center.x, 4, 3, _file) != 3 || fread(&meshData->boundingSphere.radius, 4, 1, _file) != 1)
  954. {
  955. SAFE_DELETE(meshData);
  956. return NULL;
  957. }
  958. // Read mesh parts
  959. unsigned int meshPartCount;
  960. if (fread(&meshPartCount, 4, 1, _file) != 1)
  961. {
  962. SAFE_DELETE(meshData);
  963. return NULL;
  964. }
  965. for (unsigned int i = 0; i < meshPartCount; ++i)
  966. {
  967. // Read primitive type, index format and index count
  968. unsigned int pType, iFormat, iByteCount;
  969. if (fread(&pType, 4, 1, _file) != 1 ||
  970. fread(&iFormat, 4, 1, _file) != 1 ||
  971. fread(&iByteCount, 4, 1, _file) != 1)
  972. {
  973. SAFE_DELETE(meshData);
  974. return NULL;
  975. }
  976. MeshPartData* partData = new MeshPartData();
  977. meshData->parts.push_back(partData);
  978. partData->primitiveType = (Mesh::PrimitiveType)pType;
  979. partData->indexFormat = (Mesh::IndexFormat)iFormat;
  980. unsigned int indexSize = 0;
  981. switch (partData->indexFormat)
  982. {
  983. case Mesh::INDEX8:
  984. indexSize = 1;
  985. break;
  986. case Mesh::INDEX16:
  987. indexSize = 2;
  988. break;
  989. case Mesh::INDEX32:
  990. indexSize = 4;
  991. break;
  992. }
  993. partData->indexCount = iByteCount / indexSize;
  994. partData->indexData = new unsigned char[iByteCount];
  995. if (fread(partData->indexData, 1, iByteCount, _file) != iByteCount)
  996. {
  997. SAFE_DELETE(meshData);
  998. return NULL;
  999. }
  1000. }
  1001. return meshData;
  1002. }
  1003. Bundle::MeshData* Bundle::readMeshData(const char* url)
  1004. {
  1005. assert(url);
  1006. unsigned int len = strlen(url);
  1007. if (len == 0)
  1008. return NULL;
  1009. // Parse URL (formatted as 'bundle#id')
  1010. std::string urlstring(url);
  1011. unsigned int pos = urlstring.find('#');
  1012. if (pos == std::string::npos)
  1013. return NULL;
  1014. std::string file = urlstring.substr(0, pos);
  1015. std::string id = urlstring.substr(pos + 1);
  1016. // Load bundle
  1017. Bundle* bundle = Bundle::create(file.c_str());
  1018. if (bundle == NULL)
  1019. return NULL;
  1020. // Seek to mesh with specified ID in bundle
  1021. Reference* ref = bundle->seekTo(id.c_str(), BUNDLE_TYPE_MESH);
  1022. if (ref == NULL)
  1023. return NULL;
  1024. // Read mesh data from current file position
  1025. MeshData* meshData = bundle->readMeshData();
  1026. SAFE_RELEASE(bundle);
  1027. return meshData;
  1028. }
  1029. Font* Bundle::loadFont(const char* id)
  1030. {
  1031. // Seek to the specified Font
  1032. Reference* ref = seekTo(id, BUNDLE_TYPE_FONT);
  1033. if (ref == NULL)
  1034. {
  1035. return NULL;
  1036. }
  1037. // Read font family
  1038. std::string family = readString(_file);
  1039. if (family.empty())
  1040. {
  1041. LOG_ERROR_VARG("Failed to read font family for font: %s", id);
  1042. return NULL;
  1043. }
  1044. // Read font style and size
  1045. unsigned int style, size;
  1046. if (fread(&style, 4, 1, _file) != 1 ||
  1047. fread(&size, 4, 1, _file) != 1)
  1048. {
  1049. LOG_ERROR_VARG("Failed to read style and/or size for font: %s", id);
  1050. return NULL;
  1051. }
  1052. // Read character set
  1053. std::string charset = readString(_file);
  1054. // Read font glyphs
  1055. unsigned int glyphCount;
  1056. if (fread(&glyphCount, 4, 1, _file) != 1 || glyphCount == 0)
  1057. {
  1058. LOG_ERROR_VARG("Failed to read glyph count for font: %s", id);
  1059. return NULL;
  1060. }
  1061. Font::Glyph* glyphs = new Font::Glyph[glyphCount];
  1062. if (fread(glyphs, sizeof(Font::Glyph), glyphCount, _file) != glyphCount)
  1063. {
  1064. LOG_ERROR_VARG("Failed to read %d glyphs for font: %s", glyphCount, id);
  1065. SAFE_DELETE_ARRAY(glyphs);
  1066. return NULL;
  1067. }
  1068. // Read texture
  1069. unsigned int width, height, textureByteCount;
  1070. if (fread(&width, 4, 1, _file) != 1 ||
  1071. fread(&height, 4, 1, _file) != 1 ||
  1072. fread(&textureByteCount, 4, 1, _file) != 1)
  1073. {
  1074. LOG_ERROR_VARG("Failed to read texture attributes for font: %s", id);
  1075. SAFE_DELETE_ARRAY(glyphs);
  1076. return NULL;
  1077. }
  1078. if (textureByteCount != (width * height))
  1079. {
  1080. LOG_ERROR_VARG("Invalid texture byte for font: %s", id);
  1081. SAFE_DELETE_ARRAY(glyphs);
  1082. return NULL;
  1083. }
  1084. unsigned char* textureData = new unsigned char[textureByteCount];
  1085. if (fread(textureData, 1, textureByteCount, _file) != textureByteCount)
  1086. {
  1087. LOG_ERROR_VARG("Failed to read %d texture bytes for font: %s", textureByteCount, id);
  1088. SAFE_DELETE_ARRAY(glyphs);
  1089. SAFE_DELETE_ARRAY(textureData);
  1090. return NULL;
  1091. }
  1092. // Load the texture for the font
  1093. Texture* texture = Texture::create(Texture::ALPHA, width, height, textureData, true);
  1094. // Free the texture data (no longer needed)
  1095. SAFE_DELETE_ARRAY(textureData);
  1096. if (texture == NULL)
  1097. {
  1098. LOG_ERROR_VARG("Failed to create texture for font: %s", id);
  1099. SAFE_DELETE_ARRAY(glyphs);
  1100. return NULL;
  1101. }
  1102. // Create the font
  1103. Font* font = Font::create(family.c_str(), Font::PLAIN, size, glyphs, glyphCount, texture);
  1104. // Free the glyph array
  1105. SAFE_DELETE_ARRAY(glyphs);
  1106. // Release the texture since the Font now owns it
  1107. SAFE_RELEASE(texture);
  1108. if (font)
  1109. {
  1110. font->_path = _path;
  1111. font->_id = id;
  1112. }
  1113. return font;
  1114. }
  1115. void Bundle::setTransform(const float* values, Transform* transform)
  1116. {
  1117. // Load array into transform
  1118. Matrix matrix(values);
  1119. Vector3 scale, translation;
  1120. Quaternion rotation;
  1121. matrix.decompose(&scale, &rotation, &translation);
  1122. transform->setScale(scale);
  1123. transform->setTranslation(translation);
  1124. transform->setRotation(rotation);
  1125. }
  1126. bool Bundle::contains(const char* id) const
  1127. {
  1128. return (find(id) != NULL);
  1129. }
  1130. unsigned int Bundle::getObjectCount() const
  1131. {
  1132. return _referenceCount;
  1133. }
  1134. const char* Bundle::getObjectID(unsigned int index) const
  1135. {
  1136. return (index >= _referenceCount ? NULL : _references[index].id.c_str());
  1137. }
  1138. Bundle::Reference::Reference()
  1139. : type(0), offset(0)
  1140. {
  1141. }
  1142. Bundle::Reference::~Reference()
  1143. {
  1144. }
  1145. Bundle::MeshPartData::MeshPartData() :
  1146. indexCount(0), indexData(NULL)
  1147. {
  1148. }
  1149. Bundle::MeshPartData::~MeshPartData()
  1150. {
  1151. SAFE_DELETE_ARRAY(indexData);
  1152. }
  1153. Bundle::MeshData::MeshData(const VertexFormat& vertexFormat)
  1154. : vertexFormat(vertexFormat), vertexCount(0), vertexData(NULL)
  1155. {
  1156. }
  1157. Bundle::MeshData::~MeshData()
  1158. {
  1159. SAFE_DELETE_ARRAY(vertexData);
  1160. for (unsigned int i = 0; i < parts.size(); ++i)
  1161. {
  1162. SAFE_DELETE(parts[i]);
  1163. }
  1164. }
  1165. }