GPBFile.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  1. #include "Base.h"
  2. #include "GPBFile.h"
  3. #include "Transform.h"
  4. #include "StringUtil.h"
  5. #include "EncoderArguments.h"
  6. #include "Heightmap.h"
  7. #define EPSILON 1.2e-7f;
  8. namespace gameplay
  9. {
  10. static GPBFile* __instance = NULL;
  11. /**
  12. * Returns true if the given value is close to one.
  13. */
  14. static bool isAlmostOne(float value);
  15. /**
  16. * Returns true if the given value is close to zero.
  17. */
  18. static bool isAlmostZero(float value);
  19. /**
  20. * Gets the common node ancestor for the given list of nodes.
  21. * This function assumes that the nodes share a common ancestor.
  22. *
  23. * @param nodes The list of nodes.
  24. *
  25. * @return The common node ancestor or NULL if the list of was empty.
  26. */
  27. static Node* getCommonNodeAncestor(const std::vector<Node*>& nodes);
  28. /**
  29. * Gets the list of node ancestors for the given node.
  30. *
  31. * @param node The node to get the ancestors for.
  32. * @param ancestors The output list of ancestors.
  33. * The first element is the root node and the last element is the direct parent of the node.
  34. */
  35. static void getNodeAncestors(Node* node, std::list<Node*>& ancestors);
  36. GPBFile::GPBFile(void)
  37. : _file(NULL), _animationsAdded(false)
  38. {
  39. __instance = this;
  40. }
  41. GPBFile::~GPBFile(void)
  42. {
  43. }
  44. GPBFile* GPBFile::getInstance()
  45. {
  46. return __instance;
  47. }
  48. bool GPBFile::saveBinary(const std::string& filepath)
  49. {
  50. _file = fopen(filepath.c_str(), "w+b");
  51. if (!_file)
  52. {
  53. return false;
  54. }
  55. size_t n = 0;
  56. // identifier
  57. char identifier[] = { '«', 'G', 'P', 'B', '»', '\r', '\n', '\x1A', '\n' };
  58. n = fwrite(identifier, 1, sizeof(identifier), _file);
  59. if (n != sizeof(identifier))
  60. {
  61. fclose(_file);
  62. return false;
  63. }
  64. // version
  65. n = fwrite(GPB_VERSION, 1, sizeof(GPB_VERSION), _file);
  66. if (n != sizeof(GPB_VERSION))
  67. {
  68. fclose(_file);
  69. return false;
  70. }
  71. // TODO: Check for errors on all file writing.
  72. // write refs
  73. _refTable.writeBinary(_file);
  74. // meshes
  75. write(_geometry.size(), _file);
  76. for (std::list<Mesh*>::const_iterator i = _geometry.begin(); i != _geometry.end(); ++i)
  77. {
  78. (*i)->writeBinary(_file);
  79. }
  80. // Objects
  81. write(_objects.size(), _file);
  82. for (std::list<Object*>::const_iterator i = _objects.begin(); i != _objects.end(); ++i)
  83. {
  84. (*i)->writeBinary(_file);
  85. }
  86. _refTable.updateOffsets(_file);
  87. fclose(_file);
  88. return true;
  89. }
  90. bool GPBFile::saveText(const std::string& filepath)
  91. {
  92. _file = fopen(filepath.c_str(), "w");
  93. if (!_file)
  94. {
  95. return false;
  96. }
  97. if (fprintf(_file, "<root>\n") <= 0)
  98. {
  99. fclose(_file);
  100. return false;
  101. }
  102. // TODO: Check for errors on all file writing.
  103. // write refs
  104. _refTable.writeText(_file);
  105. // meshes
  106. for (std::list<Mesh*>::const_iterator i = _geometry.begin(); i != _geometry.end(); ++i)
  107. {
  108. (*i)->writeText(_file);
  109. }
  110. // Objects
  111. for (std::list<Object*>::const_iterator i = _objects.begin(); i != _objects.end(); ++i)
  112. {
  113. (*i)->writeText(_file);
  114. }
  115. fprintf(_file, "</root>");
  116. fclose(_file);
  117. return true;
  118. }
  119. void GPBFile::add(Object* obj)
  120. {
  121. _objects.push_back(obj);
  122. }
  123. void GPBFile::addScene(Scene* scene)
  124. {
  125. addToRefTable(scene);
  126. _objects.push_back(scene);
  127. }
  128. void GPBFile::addCamera(Camera* camera)
  129. {
  130. addToRefTable(camera);
  131. _cameras.push_back(camera);
  132. }
  133. void GPBFile::addLight(Light* light)
  134. {
  135. addToRefTable(light);
  136. _lights.push_back(light);
  137. }
  138. void GPBFile::addMesh(Mesh* mesh)
  139. {
  140. addToRefTable(mesh);
  141. _geometry.push_back(mesh);
  142. }
  143. void GPBFile::addNode(Node* node)
  144. {
  145. addToRefTable(node);
  146. _nodes.push_back(node);
  147. }
  148. void GPBFile::addScenelessNode(Node* node)
  149. {
  150. addToRefTable(node);
  151. _nodes.push_back(node);
  152. // Nodes are normally written to file as part of a scene.
  153. // Nodes that don't belong to a scene need to be written on their own (outside a scene).
  154. // That is why node is added to the list of objects here.
  155. _objects.push_back(node);
  156. }
  157. void GPBFile::addAnimation(Animation* animation)
  158. {
  159. _animations.add(animation);
  160. if (!_animationsAdded)
  161. {
  162. // The animations container should only be added once and only if the file has at least one animation.
  163. _animationsAdded = true;
  164. addToRefTable(&_animations);
  165. add(&_animations);
  166. }
  167. }
  168. void GPBFile::addToRefTable(Object* obj)
  169. {
  170. if (obj)
  171. {
  172. const std::string& id = obj->getId();
  173. if (id.length() > 0)
  174. {
  175. if (_refTable.get(id) == NULL)
  176. {
  177. _refTable.add(id, obj);
  178. }
  179. }
  180. }
  181. }
  182. Object* GPBFile::getFromRefTable(const std::string& id)
  183. {
  184. return _refTable.get(id);
  185. }
  186. bool GPBFile::idExists(const std::string& id)
  187. {
  188. return _refTable.get(id) != NULL;
  189. }
  190. Camera* GPBFile::getCamera(const char* id)
  191. {
  192. if (!id)
  193. return NULL;
  194. // TODO: O(n) search is not ideal
  195. for (std::list<Camera*>::const_iterator i = _cameras.begin(); i != _cameras.end(); ++i)
  196. {
  197. const std::string& _id = (*i)->getId();
  198. if (_id.length() > 0 && strncmp(id, _id.c_str(), 255) == 0)
  199. {
  200. return *i;
  201. }
  202. }
  203. return NULL;
  204. }
  205. Light* GPBFile::getLight(const char* id)
  206. {
  207. if (!id)
  208. return NULL;
  209. // TODO: O(n) search is not ideal
  210. for (std::list<Light*>::const_iterator i = _lights.begin(); i != _lights.end(); ++i)
  211. {
  212. const std::string& _id = (*i)->getId();
  213. if (_id.length() > 0 && strncmp(id, _id.c_str(), 255) == 0)
  214. {
  215. return *i;
  216. }
  217. }
  218. return NULL;
  219. }
  220. Mesh* GPBFile::getMesh(const char* id)
  221. {
  222. if (!id)
  223. return NULL;
  224. // TODO: O(n) search is not ideal
  225. for (std::list<Mesh*>::const_iterator i = _geometry.begin(); i != _geometry.end(); ++i)
  226. {
  227. const std::string& _id = (*i)->getId();
  228. if (_id.length() > 0 && strncmp(id, _id.c_str(), 255) == 0)
  229. {
  230. return *i;
  231. }
  232. }
  233. return NULL;
  234. }
  235. Node* GPBFile::getNode(const char* id)
  236. {
  237. if (!id)
  238. return NULL;
  239. // TODO: O(n) search is not ideal
  240. for (std::list<Node*>::const_iterator i = _nodes.begin(); i != _nodes.end(); ++i)
  241. {
  242. const std::string& _id = (*i)->getId();
  243. if (_id.length() > 0 && strncmp(id, _id.c_str(), 255) == 0)
  244. {
  245. return *i;
  246. }
  247. }
  248. return NULL;
  249. }
  250. Animations* GPBFile::getAnimations()
  251. {
  252. return &_animations;
  253. }
  254. void GPBFile::adjust()
  255. {
  256. // calculate the ambient color for each scene
  257. for (std::list<Object*>::iterator i = _objects.begin(); i != _objects.end(); ++i)
  258. {
  259. Object* obj = *i;
  260. if (obj->getTypeId() == Object::SCENE_ID)
  261. {
  262. Scene* scene = dynamic_cast<Scene*>(obj);
  263. scene->calcAmbientColor();
  264. }
  265. }
  266. LOG(1, "Computing bounding volumes.\n");
  267. for (std::list<Node*>::const_iterator i = _nodes.begin(); i != _nodes.end(); ++i)
  268. {
  269. computeBounds(*i);
  270. }
  271. if (EncoderArguments::getInstance()->optimizeAnimationsEnabled())
  272. {
  273. LOG(1, "Optimizing animations.\n");
  274. optimizeAnimations();
  275. }
  276. // TODO:
  277. // remove ambient _lights
  278. // for each node
  279. // if node has ambient light
  280. // if node has no camera, mesh or children but 1 ambient light
  281. // delete node and remove from ref table
  282. // delete light and remove from ref table
  283. //
  284. // merge animations if possible
  285. // Search for animations that have the same target and key times and see if they can be merged.
  286. // Blender will output a simple translation animation to 3 separate animations with the same key times but targeting X, Y and Z.
  287. // This can be merged into one animation. Same for scale animations.
  288. // Generate heightmaps
  289. const std::vector<EncoderArguments::HeightmapOption>& heightmaps = EncoderArguments::getInstance()->getHeightmapOptions();
  290. for (unsigned int i = 0, count = heightmaps.size(); i < count; ++i)
  291. {
  292. Heightmap::generate(heightmaps[i].nodeIds, heightmaps[i].filename.c_str(), heightmaps[i].isHighPrecision);
  293. }
  294. }
  295. void GPBFile::groupMeshSkinAnimations()
  296. {
  297. for (std::list<Node*>::iterator it = _nodes.begin(); it != _nodes.end(); ++it)
  298. {
  299. if (Model* model = (*it)->getModel())
  300. {
  301. if (MeshSkin* skin = model->getSkin())
  302. {
  303. const std::vector<Node*>& joints = skin->getJoints();
  304. Node* commonAncestor = getCommonNodeAncestor(joints);
  305. if (commonAncestor)
  306. {
  307. // group the animation channels that target this common ancestor and its child nodes
  308. Animation* animation = new Animation();
  309. animation->setId("animations");
  310. moveAnimationChannels(commonAncestor, animation);
  311. _animations.add(animation);
  312. }
  313. }
  314. }
  315. }
  316. }
  317. void GPBFile::renameAnimations(std::vector<std::string>& animationIds, const char* newId)
  318. {
  319. const unsigned int animationCount = _animations.getAnimationCount();
  320. for (unsigned int animationIndex = 0; animationIndex < animationCount; ++animationIndex)
  321. {
  322. Animation* animation = _animations.getAnimation(animationIndex);
  323. assert(animation);
  324. std::vector<std::string>::const_iterator it = find(animationIds.begin(), animationIds.end(), animation->getId());
  325. if (it != animationIds.end())
  326. {
  327. animation->setId(newId);
  328. }
  329. }
  330. }
  331. void GPBFile::computeBounds(Node* node)
  332. {
  333. assert(node);
  334. if (Model* model = node->getModel())
  335. {
  336. if (Mesh* mesh = model->getMesh())
  337. {
  338. mesh->computeBounds();
  339. }
  340. }
  341. }
  342. void GPBFile::optimizeAnimations()
  343. {
  344. const unsigned int animationCount = _animations.getAnimationCount();
  345. for (unsigned int animationIndex = 0; animationIndex < animationCount; ++animationIndex)
  346. {
  347. Animation* animation = _animations.getAnimation(animationIndex);
  348. assert(animation);
  349. const int channelCount = animation->getAnimationChannelCount();
  350. LOG(2, "Optimizing %d channel(s) in animation '%s'.\n", channelCount, animation->getId().c_str());
  351. // loop backwards because we will be adding and removing channels
  352. for (int channelIndex = channelCount -1; channelIndex >= 0 ; --channelIndex)
  353. {
  354. AnimationChannel* channel = animation->getAnimationChannel(channelIndex);
  355. assert(channel);
  356. // Optimize node animation channels
  357. const Object* obj = _refTable.get(channel->getTargetId());
  358. if (obj && obj->getTypeId() == Object::NODE_ID)
  359. {
  360. if (channel->getTargetAttribute() == Transform::ANIMATE_SCALE_ROTATE_TRANSLATE)
  361. {
  362. decomposeTransformAnimationChannel(animation, channel, channelIndex);
  363. animation->remove(channel);
  364. SAFE_DELETE(channel);
  365. }
  366. }
  367. }
  368. }
  369. }
  370. void GPBFile::decomposeTransformAnimationChannel(Animation* animation, AnimationChannel* channel, int channelIndex)
  371. {
  372. LOG(2, " Optimizing animaton channel %s:%d.\n", animation->getId().c_str(), channelIndex+1);
  373. const std::vector<float>& keyTimes = channel->getKeyTimes();
  374. const std::vector<float>& keyValues = channel->getKeyValues();
  375. const size_t keyTimesSize = keyTimes.size();
  376. const size_t keyValuesSize = keyValues.size();
  377. std::vector<float> scaleKeyValues;
  378. std::vector<float> rotateKeyValues;
  379. std::vector<float> translateKeyValues;
  380. scaleKeyValues.reserve(keyTimesSize * 3);
  381. rotateKeyValues.reserve(keyTimesSize * 4);
  382. translateKeyValues.reserve(keyTimesSize * 3);
  383. for (size_t kv = 0; kv < keyValuesSize; kv += 10)
  384. {
  385. scaleKeyValues.push_back(keyValues[kv]);
  386. scaleKeyValues.push_back(keyValues[kv+1]);
  387. scaleKeyValues.push_back(keyValues[kv+2]);
  388. rotateKeyValues.push_back(keyValues[kv+3]);
  389. rotateKeyValues.push_back(keyValues[kv+4]);
  390. rotateKeyValues.push_back(keyValues[kv+5]);
  391. rotateKeyValues.push_back(keyValues[kv+6]);
  392. translateKeyValues.push_back(keyValues[kv+7]);
  393. translateKeyValues.push_back(keyValues[kv+8]);
  394. translateKeyValues.push_back(keyValues[kv+9]);
  395. }
  396. // replace transform animation channel with translate, rotate and scale animation channels
  397. // Don't add the scale channel if all the key values are close to 1.0
  398. size_t oneCount = (size_t)std::count_if(scaleKeyValues.begin(), scaleKeyValues.end(), isAlmostOne);
  399. if (scaleKeyValues.size() == oneCount)
  400. {
  401. LOG(2, " Discarding scale channel.\n");
  402. }
  403. else
  404. {
  405. LOG(3, " Keeping scale channel.\n");
  406. AnimationChannel* scaleChannel = new AnimationChannel();
  407. scaleChannel->setTargetId(channel->getTargetId());
  408. scaleChannel->setKeyTimes(channel->getKeyTimes());
  409. scaleChannel->setTangentsIn(channel->getTangentsIn());
  410. scaleChannel->setTangentsOut(channel->getTangentsOut());
  411. scaleChannel->setInterpolations(channel->getInterpolationTypes());
  412. scaleChannel->setTargetAttribute(Transform::ANIMATE_SCALE);
  413. scaleChannel->setKeyValues(scaleKeyValues);
  414. scaleChannel->removeDuplicates();
  415. animation->add(scaleChannel);
  416. }
  417. // Don't add the rotation channel if all quaternions are close to identity
  418. oneCount = 0;
  419. for (unsigned int i = 0, count = rotateKeyValues.size(); i < count; i += 4)
  420. {
  421. float x = rotateKeyValues[i];
  422. float y = rotateKeyValues[i+1];
  423. float z = rotateKeyValues[i+2];
  424. float w = rotateKeyValues[i+3];
  425. if (ISZERO(x) && ISZERO(y) && ISZERO(z) && ISONE(w))
  426. ++oneCount;
  427. else
  428. {
  429. LOG(4, "Rotation not identity: %d\n", i);
  430. Quaternion q(x, y, z, w);
  431. Vector3 axis;
  432. float angle = q.toAxisAngle(&axis);
  433. angle = 0;
  434. }
  435. }
  436. if ((rotateKeyValues.size()>>2) == oneCount)
  437. {
  438. LOG(2, " Discarding rotation channel.\n");
  439. }
  440. else
  441. {
  442. LOG(3, " Keeping rotation channel.\n");
  443. AnimationChannel* rotateChannel = new AnimationChannel();
  444. rotateChannel->setTargetId(channel->getTargetId());
  445. rotateChannel->setKeyTimes(channel->getKeyTimes());
  446. rotateChannel->setTangentsIn(channel->getTangentsIn());
  447. rotateChannel->setTangentsOut(channel->getTangentsOut());
  448. rotateChannel->setInterpolations(channel->getInterpolationTypes());
  449. rotateChannel->setTargetAttribute(Transform::ANIMATE_ROTATE);
  450. rotateChannel->setKeyValues(rotateKeyValues);
  451. rotateChannel->removeDuplicates();
  452. animation->add(rotateChannel);
  453. }
  454. // Don't add the translation channel if all values are close to zero
  455. oneCount = (size_t)std::count_if(translateKeyValues.begin(), translateKeyValues.end(), isAlmostZero);
  456. if (translateKeyValues.size() == oneCount)
  457. {
  458. LOG(2, " Discarding translation channel.\n");
  459. }
  460. else
  461. {
  462. LOG(3, " Keeping translation channel.\n");
  463. AnimationChannel* translateChannel = new AnimationChannel();
  464. translateChannel->setTargetId(channel->getTargetId());
  465. translateChannel->setKeyTimes(channel->getKeyTimes());
  466. translateChannel->setTangentsIn(channel->getTangentsIn());
  467. translateChannel->setTangentsOut(channel->getTangentsOut());
  468. translateChannel->setInterpolations(channel->getInterpolationTypes());
  469. translateChannel->setTargetAttribute(Transform::ANIMATE_TRANSLATE);
  470. translateChannel->setKeyValues(translateKeyValues);
  471. translateChannel->removeDuplicates();
  472. animation->add(translateChannel);
  473. }
  474. }
  475. void GPBFile::moveAnimationChannels(Node* node, Animation* dstAnimation)
  476. {
  477. // Loop through the animations and channels backwards because they will be removed when found.
  478. int animationCount = _animations.getAnimationCount();
  479. for (int i = animationCount - 1; i >= 0; --i)
  480. {
  481. Animation* animation = _animations.getAnimation(i);
  482. int channelCount = animation->getAnimationChannelCount();
  483. for (int j = channelCount - 1; j >= 0; --j)
  484. {
  485. AnimationChannel* channel = animation->getAnimationChannel(j);
  486. if (equals(channel->getTargetId(), node->getId()))
  487. {
  488. animation->remove(channel);
  489. dstAnimation->add(channel);
  490. }
  491. }
  492. if (animation->getAnimationChannelCount() == 0)
  493. {
  494. _animations.removeAnimation(i);
  495. }
  496. }
  497. for (Node* child = node->getFirstChild(); child != NULL; child = child->getNextSibling())
  498. {
  499. moveAnimationChannels(child, dstAnimation);
  500. }
  501. }
  502. bool isAlmostOne(float value)
  503. {
  504. return (value - 1.0f) < EPSILON;
  505. }
  506. bool isAlmostZero(float value)
  507. {
  508. return std::fabs(value) < EPSILON;
  509. }
  510. Node* getCommonNodeAncestor(const std::vector<Node*>& nodes)
  511. {
  512. if (nodes.empty())
  513. return NULL;
  514. if (nodes.size() == 1)
  515. return nodes.front();
  516. std::list<Node*> ancestors;
  517. size_t minAncestorCount = INT_MAX;
  518. for (std::vector<Node*>::const_iterator it = nodes.begin(); it != nodes.end(); ++it)
  519. {
  520. Node* node = *it;
  521. getNodeAncestors(node, ancestors);
  522. ancestors.push_back(node);
  523. minAncestorCount = std::min(minAncestorCount, ancestors.size());
  524. }
  525. ancestors.resize(minAncestorCount);
  526. return ancestors.back();
  527. }
  528. void getNodeAncestors(Node* node, std::list<Node*>& ancestors)
  529. {
  530. ancestors.clear();
  531. Node* parent = node->getParent();
  532. while (parent != NULL)
  533. {
  534. ancestors.push_front(parent);
  535. parent = parent->getParent();
  536. }
  537. }
  538. }