Package.cpp 33 KB

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