Package.cpp 35 KB

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