OgreXmlSerializer.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2018, assimp team
  5. All rights reserved.
  6. Redistribution and use of this software in source and binary forms,
  7. with or without modification, are permitted provided that the
  8. following conditions are met:
  9. * Redistributions of source code must retain the above
  10. copyright notice, this list of conditions and the
  11. following disclaimer.
  12. * Redistributions in binary form must reproduce the above
  13. copyright notice, this list of conditions and the
  14. following disclaimer in the documentation and/or other
  15. materials provided with the distribution.
  16. * Neither the name of the assimp team, nor the names of its
  17. contributors may be used to endorse or promote products
  18. derived from this software without specific prior
  19. written permission of the assimp team.
  20. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. ----------------------------------------------------------------------
  32. */
  33. #include "OgreXmlSerializer.h"
  34. #include "OgreBinarySerializer.h"
  35. #include "OgreParsingUtils.h"
  36. #include <assimp/TinyFormatter.h>
  37. #include <assimp/DefaultLogger.hpp>
  38. #include <memory>
  39. #ifndef ASSIMP_BUILD_NO_OGRE_IMPORTER
  40. // Define as 1 to get verbose logging.
  41. #define OGRE_XML_SERIALIZER_DEBUG 0
  42. namespace Assimp
  43. {
  44. namespace Ogre
  45. {
  46. AI_WONT_RETURN void ThrowAttibuteError(const XmlReader* reader, const std::string &name, const std::string &error = "") AI_WONT_RETURN_SUFFIX;
  47. AI_WONT_RETURN void ThrowAttibuteError(const XmlReader* reader, const std::string &name, const std::string &error)
  48. {
  49. if (!error.empty())
  50. {
  51. throw DeadlyImportError(error + " in node '" + std::string(reader->getNodeName()) + "' and attribute '" + name + "'");
  52. }
  53. else
  54. {
  55. throw DeadlyImportError("Attribute '" + name + "' does not exist in node '" + std::string(reader->getNodeName()) + "'");
  56. }
  57. }
  58. template<>
  59. int32_t OgreXmlSerializer::ReadAttribute<int32_t>(const char *name) const
  60. {
  61. if (HasAttribute(name))
  62. {
  63. return static_cast<int32_t>(m_reader->getAttributeValueAsInt(name));
  64. }
  65. else
  66. {
  67. ThrowAttibuteError(m_reader, name);
  68. return 0;
  69. }
  70. }
  71. template<>
  72. uint32_t OgreXmlSerializer::ReadAttribute<uint32_t>(const char *name) const
  73. {
  74. if (HasAttribute(name))
  75. {
  76. /** @note This is hackish. But we are never expecting unsigned values that go outside the
  77. int32_t range. Just monitor for negative numbers and kill the import. */
  78. int32_t temp = ReadAttribute<int32_t>(name);
  79. if (temp >= 0)
  80. {
  81. return static_cast<uint32_t>(temp);
  82. }
  83. else
  84. {
  85. ThrowAttibuteError(m_reader, name, "Found a negative number value where expecting a uint32_t value");
  86. }
  87. }
  88. else
  89. {
  90. ThrowAttibuteError(m_reader, name);
  91. }
  92. return 0;
  93. }
  94. template<>
  95. uint16_t OgreXmlSerializer::ReadAttribute<uint16_t>(const char *name) const
  96. {
  97. if (HasAttribute(name))
  98. {
  99. return static_cast<uint16_t>(ReadAttribute<uint32_t>(name));
  100. }
  101. else
  102. {
  103. ThrowAttibuteError(m_reader, name);
  104. }
  105. return 0;
  106. }
  107. template<>
  108. float OgreXmlSerializer::ReadAttribute<float>(const char *name) const
  109. {
  110. if (HasAttribute(name))
  111. {
  112. return m_reader->getAttributeValueAsFloat(name);
  113. }
  114. else
  115. {
  116. ThrowAttibuteError(m_reader, name);
  117. return 0;
  118. }
  119. }
  120. template<>
  121. std::string OgreXmlSerializer::ReadAttribute<std::string>(const char *name) const
  122. {
  123. const char* value = m_reader->getAttributeValue(name);
  124. if (value)
  125. {
  126. return std::string(value);
  127. }
  128. else
  129. {
  130. ThrowAttibuteError(m_reader, name);
  131. return "";
  132. }
  133. }
  134. template<>
  135. bool OgreXmlSerializer::ReadAttribute<bool>(const char *name) const
  136. {
  137. std::string value = Ogre::ToLower(ReadAttribute<std::string>(name));
  138. if (ASSIMP_stricmp(value, "true") == 0)
  139. {
  140. return true;
  141. }
  142. else if (ASSIMP_stricmp(value, "false") == 0)
  143. {
  144. return false;
  145. }
  146. else
  147. {
  148. ThrowAttibuteError(m_reader, name, "Boolean value is expected to be 'true' or 'false', encountered '" + value + "'");
  149. return false;
  150. }
  151. }
  152. bool OgreXmlSerializer::HasAttribute(const char *name) const
  153. {
  154. return (m_reader->getAttributeValue(name) != 0);
  155. }
  156. std::string &OgreXmlSerializer::NextNode()
  157. {
  158. do
  159. {
  160. if (!m_reader->read())
  161. {
  162. m_currentNodeName = "";
  163. return m_currentNodeName;
  164. }
  165. }
  166. while(m_reader->getNodeType() != irr::io::EXN_ELEMENT);
  167. CurrentNodeName(true);
  168. #if (OGRE_XML_SERIALIZER_DEBUG == 1)
  169. ASSIMP_LOG_DEBUG"<" + m_currentNodeName + ">");
  170. #endif
  171. return m_currentNodeName;
  172. }
  173. bool OgreXmlSerializer::CurrentNodeNameEquals(const std::string &name) const
  174. {
  175. return (ASSIMP_stricmp(m_currentNodeName, name) == 0);
  176. }
  177. std::string OgreXmlSerializer::CurrentNodeName(bool forceRead)
  178. {
  179. if (forceRead)
  180. m_currentNodeName = std::string(m_reader->getNodeName());
  181. return m_currentNodeName;
  182. }
  183. std::string &OgreXmlSerializer::SkipCurrentNode()
  184. {
  185. #if (OGRE_XML_SERIALIZER_DEBUG == 1)
  186. ASSIMP_LOG_DEBUG("Skipping node <" + m_currentNodeName + ">");
  187. #endif
  188. for(;;) {
  189. if (!m_reader->read()) {
  190. m_currentNodeName = "";
  191. return m_currentNodeName;
  192. }
  193. if ( m_reader->getNodeType() != irr::io::EXN_ELEMENT_END ) {
  194. continue;
  195. } else if ( std::string( m_reader->getNodeName() ) == m_currentNodeName ) {
  196. break;
  197. }
  198. }
  199. return NextNode();
  200. }
  201. // Mesh XML constants
  202. // <mesh>
  203. static const char *nnMesh = "mesh";
  204. static const char *nnSharedGeometry = "sharedgeometry";
  205. static const char *nnSubMeshes = "submeshes";
  206. static const char *nnSubMesh = "submesh";
  207. static const char *nnSubMeshNames = "submeshnames";
  208. static const char *nnSkeletonLink = "skeletonlink";
  209. static const char *nnLOD = "levelofdetail";
  210. static const char *nnExtremes = "extremes";
  211. static const char *nnPoses = "poses";
  212. static const char *nnAnimations = "animations";
  213. // <submesh>
  214. static const char *nnFaces = "faces";
  215. static const char *nnFace = "face";
  216. static const char *nnGeometry = "geometry";
  217. static const char *nnTextures = "textures";
  218. // <mesh/submesh>
  219. static const char *nnBoneAssignments = "boneassignments";
  220. // <sharedgeometry/geometry>
  221. static const char *nnVertexBuffer = "vertexbuffer";
  222. // <vertexbuffer>
  223. static const char *nnVertex = "vertex";
  224. static const char *nnPosition = "position";
  225. static const char *nnNormal = "normal";
  226. static const char *nnTangent = "tangent";
  227. static const char *nnBinormal = "binormal";
  228. static const char *nnTexCoord = "texcoord";
  229. static const char *nnColorDiffuse = "colour_diffuse";
  230. static const char *nnColorSpecular = "colour_specular";
  231. // <boneassignments>
  232. static const char *nnVertexBoneAssignment = "vertexboneassignment";
  233. // Skeleton XML constants
  234. // <skeleton>
  235. static const char *nnSkeleton = "skeleton";
  236. static const char *nnBones = "bones";
  237. static const char *nnBoneHierarchy = "bonehierarchy";
  238. static const char *nnAnimationLinks = "animationlinks";
  239. // <bones>
  240. static const char *nnBone = "bone";
  241. static const char *nnRotation = "rotation";
  242. static const char *nnAxis = "axis";
  243. static const char *nnScale = "scale";
  244. // <bonehierarchy>
  245. static const char *nnBoneParent = "boneparent";
  246. // <animations>
  247. static const char *nnAnimation = "animation";
  248. static const char *nnTracks = "tracks";
  249. // <tracks>
  250. static const char *nnTrack = "track";
  251. static const char *nnKeyFrames = "keyframes";
  252. static const char *nnKeyFrame = "keyframe";
  253. static const char *nnTranslate = "translate";
  254. static const char *nnRotate = "rotate";
  255. // Common XML constants
  256. static const char *anX = "x";
  257. static const char *anY = "y";
  258. static const char *anZ = "z";
  259. // Mesh
  260. MeshXml *OgreXmlSerializer::ImportMesh(XmlReader *reader) {
  261. OgreXmlSerializer serializer(reader);
  262. MeshXml *mesh = new MeshXml();
  263. serializer.ReadMesh(mesh);
  264. return mesh;
  265. }
  266. void OgreXmlSerializer::ReadMesh(MeshXml *mesh) {
  267. if (NextNode() != nnMesh) {
  268. throw DeadlyImportError("Root node is <" + m_currentNodeName + "> expecting <mesh>");
  269. }
  270. ASSIMP_LOG_DEBUG("Reading Mesh");
  271. NextNode();
  272. // Root level nodes
  273. while(m_currentNodeName == nnSharedGeometry ||
  274. m_currentNodeName == nnSubMeshes ||
  275. m_currentNodeName == nnSkeletonLink ||
  276. m_currentNodeName == nnBoneAssignments ||
  277. m_currentNodeName == nnLOD ||
  278. m_currentNodeName == nnSubMeshNames ||
  279. m_currentNodeName == nnExtremes ||
  280. m_currentNodeName == nnPoses ||
  281. m_currentNodeName == nnAnimations)
  282. {
  283. if (m_currentNodeName == nnSharedGeometry)
  284. {
  285. mesh->sharedVertexData = new VertexDataXml();
  286. ReadGeometry(mesh->sharedVertexData);
  287. }
  288. else if (m_currentNodeName == nnSubMeshes)
  289. {
  290. NextNode();
  291. while(m_currentNodeName == nnSubMesh) {
  292. ReadSubMesh(mesh);
  293. }
  294. }
  295. else if (m_currentNodeName == nnBoneAssignments)
  296. {
  297. ReadBoneAssignments(mesh->sharedVertexData);
  298. }
  299. else if (m_currentNodeName == nnSkeletonLink)
  300. {
  301. mesh->skeletonRef = ReadAttribute<std::string>("name");
  302. ASSIMP_LOG_DEBUG_F("Read skeleton link ", mesh->skeletonRef);
  303. NextNode();
  304. }
  305. // Assimp incompatible/ignored nodes
  306. else
  307. SkipCurrentNode();
  308. }
  309. }
  310. void OgreXmlSerializer::ReadGeometry(VertexDataXml *dest)
  311. {
  312. dest->count = ReadAttribute<uint32_t>("vertexcount");
  313. ASSIMP_LOG_DEBUG_F( " - Reading geometry of ", dest->count, " vertices");
  314. NextNode();
  315. while(m_currentNodeName == nnVertexBuffer) {
  316. ReadGeometryVertexBuffer(dest);
  317. }
  318. }
  319. void OgreXmlSerializer::ReadGeometryVertexBuffer(VertexDataXml *dest)
  320. {
  321. bool positions = (HasAttribute("positions") && ReadAttribute<bool>("positions"));
  322. bool normals = (HasAttribute("normals") && ReadAttribute<bool>("normals"));
  323. bool tangents = (HasAttribute("tangents") && ReadAttribute<bool>("tangents"));
  324. uint32_t uvs = (HasAttribute("texture_coords") ? ReadAttribute<uint32_t>("texture_coords") : 0);
  325. // Not having positions is a error only if a previous vertex buffer did not have them.
  326. if (!positions && !dest->HasPositions()) {
  327. throw DeadlyImportError("Vertex buffer does not contain positions!");
  328. }
  329. if (positions)
  330. {
  331. ASSIMP_LOG_DEBUG(" - Contains positions");
  332. dest->positions.reserve(dest->count);
  333. }
  334. if (normals)
  335. {
  336. ASSIMP_LOG_DEBUG(" - Contains normals");
  337. dest->normals.reserve(dest->count);
  338. }
  339. if (tangents)
  340. {
  341. ASSIMP_LOG_DEBUG(" - Contains tangents");
  342. dest->tangents.reserve(dest->count);
  343. }
  344. if (uvs > 0)
  345. {
  346. ASSIMP_LOG_DEBUG_F( " - Contains ", uvs, " texture coords");
  347. dest->uvs.resize(uvs);
  348. for(size_t i=0, len=dest->uvs.size(); i<len; ++i) {
  349. dest->uvs[i].reserve(dest->count);
  350. }
  351. }
  352. bool warnBinormal = true;
  353. bool warnColorDiffuse = true;
  354. bool warnColorSpecular = true;
  355. NextNode();
  356. while(m_currentNodeName == nnVertex ||
  357. m_currentNodeName == nnPosition ||
  358. m_currentNodeName == nnNormal ||
  359. m_currentNodeName == nnTangent ||
  360. m_currentNodeName == nnBinormal ||
  361. m_currentNodeName == nnTexCoord ||
  362. m_currentNodeName == nnColorDiffuse ||
  363. m_currentNodeName == nnColorSpecular)
  364. {
  365. if (m_currentNodeName == nnVertex) {
  366. NextNode();
  367. }
  368. /// @todo Implement nnBinormal, nnColorDiffuse and nnColorSpecular
  369. if (positions && m_currentNodeName == nnPosition)
  370. {
  371. aiVector3D pos;
  372. pos.x = ReadAttribute<float>(anX);
  373. pos.y = ReadAttribute<float>(anY);
  374. pos.z = ReadAttribute<float>(anZ);
  375. dest->positions.push_back(pos);
  376. }
  377. else if (normals && m_currentNodeName == nnNormal)
  378. {
  379. aiVector3D normal;
  380. normal.x = ReadAttribute<float>(anX);
  381. normal.y = ReadAttribute<float>(anY);
  382. normal.z = ReadAttribute<float>(anZ);
  383. dest->normals.push_back(normal);
  384. }
  385. else if (tangents && m_currentNodeName == nnTangent)
  386. {
  387. aiVector3D tangent;
  388. tangent.x = ReadAttribute<float>(anX);
  389. tangent.y = ReadAttribute<float>(anY);
  390. tangent.z = ReadAttribute<float>(anZ);
  391. dest->tangents.push_back(tangent);
  392. }
  393. else if (uvs > 0 && m_currentNodeName == nnTexCoord)
  394. {
  395. for(auto &uvs : dest->uvs)
  396. {
  397. if (m_currentNodeName != nnTexCoord) {
  398. throw DeadlyImportError("Vertex buffer declared more UVs than can be found in a vertex");
  399. }
  400. aiVector3D uv;
  401. uv.x = ReadAttribute<float>("u");
  402. uv.y = (ReadAttribute<float>("v") * -1) + 1; // Flip UV from Ogre to Assimp form
  403. uvs.push_back(uv);
  404. NextNode();
  405. }
  406. // Continue main loop as above already read next node
  407. continue;
  408. }
  409. else
  410. {
  411. /// @todo Remove this stuff once implemented. We only want to log warnings once per element.
  412. bool warn = true;
  413. if (m_currentNodeName == nnBinormal)
  414. {
  415. if (warnBinormal)
  416. {
  417. warnBinormal = false;
  418. }
  419. else
  420. {
  421. warn = false;
  422. }
  423. }
  424. else if (m_currentNodeName == nnColorDiffuse)
  425. {
  426. if (warnColorDiffuse)
  427. {
  428. warnColorDiffuse = false;
  429. }
  430. else
  431. {
  432. warn = false;
  433. }
  434. }
  435. else if (m_currentNodeName == nnColorSpecular)
  436. {
  437. if (warnColorSpecular)
  438. {
  439. warnColorSpecular = false;
  440. }
  441. else
  442. {
  443. warn = false;
  444. }
  445. }
  446. if (warn) {
  447. ASSIMP_LOG_WARN_F("Vertex buffer attribute read not implemented for element: ", m_currentNodeName);
  448. }
  449. }
  450. // Advance
  451. NextNode();
  452. }
  453. // Sanity checks
  454. if (dest->positions.size() != dest->count) {
  455. throw DeadlyImportError(Formatter::format() << "Read only " << dest->positions.size() << " positions when should have read " << dest->count);
  456. }
  457. if (normals && dest->normals.size() != dest->count) {
  458. throw DeadlyImportError(Formatter::format() << "Read only " << dest->normals.size() << " normals when should have read " << dest->count);
  459. }
  460. if (tangents && dest->tangents.size() != dest->count) {
  461. throw DeadlyImportError(Formatter::format() << "Read only " << dest->tangents.size() << " tangents when should have read " << dest->count);
  462. }
  463. for(unsigned int i=0; i<dest->uvs.size(); ++i)
  464. {
  465. if (dest->uvs[i].size() != dest->count) {
  466. throw DeadlyImportError(Formatter::format() << "Read only " << dest->uvs[i].size()
  467. << " uvs for uv index " << i << " when should have read " << dest->count);
  468. }
  469. }
  470. }
  471. void OgreXmlSerializer::ReadSubMesh(MeshXml *mesh)
  472. {
  473. static const char *anMaterial = "material";
  474. static const char *anUseSharedVertices = "usesharedvertices";
  475. static const char *anCount = "count";
  476. static const char *anV1 = "v1";
  477. static const char *anV2 = "v2";
  478. static const char *anV3 = "v3";
  479. static const char *anV4 = "v4";
  480. SubMeshXml* submesh = new SubMeshXml();
  481. if (HasAttribute(anMaterial)) {
  482. submesh->materialRef = ReadAttribute<std::string>(anMaterial);
  483. }
  484. if (HasAttribute(anUseSharedVertices)) {
  485. submesh->usesSharedVertexData = ReadAttribute<bool>(anUseSharedVertices);
  486. }
  487. ASSIMP_LOG_DEBUG_F( "Reading SubMesh ", mesh->subMeshes.size());
  488. ASSIMP_LOG_DEBUG_F( " - Material: '", submesh->materialRef, "'");
  489. ASSIMP_LOG_DEBUG_F( " - Uses shared geometry: ", (submesh->usesSharedVertexData ? "true" : "false"));
  490. // TODO: maybe we have always just 1 faces and 1 geometry and always in this order. this loop will only work correct, when the order
  491. // of faces and geometry changed, and not if we have more than one of one
  492. /// @todo Fix above comment with better read logic below
  493. bool quadWarned = false;
  494. NextNode();
  495. while(m_currentNodeName == nnFaces ||
  496. m_currentNodeName == nnGeometry ||
  497. m_currentNodeName == nnTextures ||
  498. m_currentNodeName == nnBoneAssignments)
  499. {
  500. if (m_currentNodeName == nnFaces)
  501. {
  502. submesh->indexData->faceCount = ReadAttribute<uint32_t>(anCount);
  503. submesh->indexData->faces.reserve(submesh->indexData->faceCount);
  504. NextNode();
  505. while(m_currentNodeName == nnFace)
  506. {
  507. aiFace face;
  508. face.mNumIndices = 3;
  509. face.mIndices = new unsigned int[3];
  510. face.mIndices[0] = ReadAttribute<uint32_t>(anV1);
  511. face.mIndices[1] = ReadAttribute<uint32_t>(anV2);
  512. face.mIndices[2] = ReadAttribute<uint32_t>(anV3);
  513. /// @todo Support quads if Ogre even supports them in XML (I'm not sure but I doubt it)
  514. if (!quadWarned && HasAttribute(anV4)) {
  515. ASSIMP_LOG_WARN("Submesh <face> has quads with <v4>, only triangles are supported at the moment!");
  516. quadWarned = true;
  517. }
  518. submesh->indexData->faces.push_back(face);
  519. // Advance
  520. NextNode();
  521. }
  522. if (submesh->indexData->faces.size() == submesh->indexData->faceCount) {
  523. ASSIMP_LOG_DEBUG_F( " - Faces ", submesh->indexData->faceCount);
  524. } else {
  525. throw DeadlyImportError(Formatter::format() << "Read only " << submesh->indexData->faces.size() << " faces when should have read " << submesh->indexData->faceCount);
  526. }
  527. } else if (m_currentNodeName == nnGeometry) {
  528. if (submesh->usesSharedVertexData) {
  529. throw DeadlyImportError("Found <geometry> in <submesh> when use shared geometry is true. Invalid mesh file.");
  530. }
  531. submesh->vertexData = new VertexDataXml();
  532. ReadGeometry(submesh->vertexData);
  533. } else if (m_currentNodeName == nnBoneAssignments) {
  534. ReadBoneAssignments(submesh->vertexData);
  535. }
  536. // Assimp incompatible/ignored nodes
  537. else {
  538. SkipCurrentNode();
  539. }
  540. }
  541. submesh->index = static_cast<unsigned int>(mesh->subMeshes.size());
  542. mesh->subMeshes.push_back(submesh);
  543. }
  544. void OgreXmlSerializer::ReadBoneAssignments(VertexDataXml *dest)
  545. {
  546. if (!dest) {
  547. throw DeadlyImportError("Cannot read bone assignments, vertex data is null.");
  548. }
  549. static const char *anVertexIndex = "vertexindex";
  550. static const char *anBoneIndex = "boneindex";
  551. static const char *anWeight = "weight";
  552. std::set<uint32_t> influencedVertices;
  553. NextNode();
  554. while(m_currentNodeName == nnVertexBoneAssignment)
  555. {
  556. VertexBoneAssignment ba;
  557. ba.vertexIndex = ReadAttribute<uint32_t>(anVertexIndex);
  558. ba.boneIndex = ReadAttribute<uint16_t>(anBoneIndex);
  559. ba.weight = ReadAttribute<float>(anWeight);
  560. dest->boneAssignments.push_back(ba);
  561. influencedVertices.insert(ba.vertexIndex);
  562. NextNode();
  563. }
  564. /** Normalize bone weights.
  565. Some exporters won't care if the sum of all bone weights
  566. for a single vertex equals 1 or not, so validate here. */
  567. const float epsilon = 0.05f;
  568. for (const uint32_t vertexIndex : influencedVertices)
  569. {
  570. float sum = 0.0f;
  571. for (VertexBoneAssignmentList::const_iterator baIter=dest->boneAssignments.begin(), baEnd=dest->boneAssignments.end(); baIter != baEnd; ++baIter)
  572. {
  573. if (baIter->vertexIndex == vertexIndex)
  574. sum += baIter->weight;
  575. }
  576. if ((sum < (1.0f - epsilon)) || (sum > (1.0f + epsilon)))
  577. {
  578. for (auto &boneAssign : dest->boneAssignments)
  579. {
  580. if (boneAssign.vertexIndex == vertexIndex)
  581. boneAssign.weight /= sum;
  582. }
  583. }
  584. }
  585. ASSIMP_LOG_DEBUG_F( " - ", dest->boneAssignments.size(), " bone assignments");
  586. }
  587. // Skeleton
  588. bool OgreXmlSerializer::ImportSkeleton(Assimp::IOSystem *pIOHandler, MeshXml *mesh)
  589. {
  590. if (!mesh || mesh->skeletonRef.empty())
  591. return false;
  592. // Highly unusual to see in read world cases but support
  593. // XML mesh referencing a binary skeleton file.
  594. if (EndsWith(mesh->skeletonRef, ".skeleton", false))
  595. {
  596. if (OgreBinarySerializer::ImportSkeleton(pIOHandler, mesh))
  597. return true;
  598. /** Last fallback if .skeleton failed to be read. Try reading from
  599. .skeleton.xml even if the XML file referenced a binary skeleton.
  600. @note This logic was in the previous version and I don't want to break
  601. old code that might depends on it. */
  602. mesh->skeletonRef = mesh->skeletonRef + ".xml";
  603. }
  604. XmlReaderPtr reader = OpenReader(pIOHandler, mesh->skeletonRef);
  605. if (!reader.get())
  606. return false;
  607. Skeleton *skeleton = new Skeleton();
  608. OgreXmlSerializer serializer(reader.get());
  609. serializer.ReadSkeleton(skeleton);
  610. mesh->skeleton = skeleton;
  611. return true;
  612. }
  613. bool OgreXmlSerializer::ImportSkeleton(Assimp::IOSystem *pIOHandler, Mesh *mesh)
  614. {
  615. if (!mesh || mesh->skeletonRef.empty())
  616. return false;
  617. XmlReaderPtr reader = OpenReader(pIOHandler, mesh->skeletonRef);
  618. if (!reader.get())
  619. return false;
  620. Skeleton *skeleton = new Skeleton();
  621. OgreXmlSerializer serializer(reader.get());
  622. serializer.ReadSkeleton(skeleton);
  623. mesh->skeleton = skeleton;
  624. return true;
  625. }
  626. XmlReaderPtr OgreXmlSerializer::OpenReader(Assimp::IOSystem *pIOHandler, const std::string &filename)
  627. {
  628. if (!EndsWith(filename, ".skeleton.xml", false))
  629. {
  630. ASSIMP_LOG_ERROR_F("Imported Mesh is referencing to unsupported '", filename, "' skeleton file.");
  631. return XmlReaderPtr();
  632. }
  633. if (!pIOHandler->Exists(filename))
  634. {
  635. ASSIMP_LOG_ERROR_F("Failed to find skeleton file '", filename, "' that is referenced by imported Mesh.");
  636. return XmlReaderPtr();
  637. }
  638. std::unique_ptr<IOStream> file(pIOHandler->Open(filename));
  639. if (!file.get()) {
  640. throw DeadlyImportError("Failed to open skeleton file " + filename);
  641. }
  642. std::unique_ptr<CIrrXML_IOStreamReader> stream(new CIrrXML_IOStreamReader(file.get()));
  643. XmlReaderPtr reader = XmlReaderPtr(irr::io::createIrrXMLReader(stream.get()));
  644. if (!reader.get()) {
  645. throw DeadlyImportError("Failed to create XML reader for skeleton file " + filename);
  646. }
  647. return reader;
  648. }
  649. void OgreXmlSerializer::ReadSkeleton(Skeleton *skeleton)
  650. {
  651. if (NextNode() != nnSkeleton) {
  652. throw DeadlyImportError("Root node is <" + m_currentNodeName + "> expecting <skeleton>");
  653. }
  654. ASSIMP_LOG_DEBUG("Reading Skeleton");
  655. // Optional blend mode from root node
  656. if (HasAttribute("blendmode")) {
  657. skeleton->blendMode = (ToLower(ReadAttribute<std::string>("blendmode")) == "cumulative"
  658. ? Skeleton::ANIMBLEND_CUMULATIVE : Skeleton::ANIMBLEND_AVERAGE);
  659. }
  660. NextNode();
  661. // Root level nodes
  662. while(m_currentNodeName == nnBones ||
  663. m_currentNodeName == nnBoneHierarchy ||
  664. m_currentNodeName == nnAnimations ||
  665. m_currentNodeName == nnAnimationLinks)
  666. {
  667. if (m_currentNodeName == nnBones)
  668. ReadBones(skeleton);
  669. else if (m_currentNodeName == nnBoneHierarchy)
  670. ReadBoneHierarchy(skeleton);
  671. else if (m_currentNodeName == nnAnimations)
  672. ReadAnimations(skeleton);
  673. else
  674. SkipCurrentNode();
  675. }
  676. }
  677. void OgreXmlSerializer::ReadAnimations(Skeleton *skeleton)
  678. {
  679. if (skeleton->bones.empty()) {
  680. throw DeadlyImportError("Cannot read <animations> for a Skeleton without bones");
  681. }
  682. ASSIMP_LOG_DEBUG(" - Animations");
  683. NextNode();
  684. while(m_currentNodeName == nnAnimation)
  685. {
  686. Animation *anim = new Animation(skeleton);
  687. anim->name = ReadAttribute<std::string>("name");
  688. anim->length = ReadAttribute<float>("length");
  689. if (NextNode() != nnTracks) {
  690. throw DeadlyImportError(Formatter::format() << "No <tracks> found in <animation> " << anim->name);
  691. }
  692. ReadAnimationTracks(anim);
  693. skeleton->animations.push_back(anim);
  694. ASSIMP_LOG_DEBUG_F( " ", anim->name, " (", anim->length, " sec, ", anim->tracks.size(), " tracks)");
  695. }
  696. }
  697. void OgreXmlSerializer::ReadAnimationTracks(Animation *dest)
  698. {
  699. NextNode();
  700. while(m_currentNodeName == nnTrack)
  701. {
  702. VertexAnimationTrack track;
  703. track.type = VertexAnimationTrack::VAT_TRANSFORM;
  704. track.boneName = ReadAttribute<std::string>("bone");
  705. if (NextNode() != nnKeyFrames) {
  706. throw DeadlyImportError(Formatter::format() << "No <keyframes> found in <track> " << dest->name);
  707. }
  708. ReadAnimationKeyFrames(dest, &track);
  709. dest->tracks.push_back(track);
  710. }
  711. }
  712. void OgreXmlSerializer::ReadAnimationKeyFrames(Animation *anim, VertexAnimationTrack *dest)
  713. {
  714. const aiVector3D zeroVec(0.f, 0.f, 0.f);
  715. NextNode();
  716. while(m_currentNodeName == nnKeyFrame)
  717. {
  718. TransformKeyFrame keyframe;
  719. keyframe.timePos = ReadAttribute<float>("time");
  720. NextNode();
  721. while(m_currentNodeName == nnTranslate || m_currentNodeName == nnRotate || m_currentNodeName == nnScale)
  722. {
  723. if (m_currentNodeName == nnTranslate)
  724. {
  725. keyframe.position.x = ReadAttribute<float>(anX);
  726. keyframe.position.y = ReadAttribute<float>(anY);
  727. keyframe.position.z = ReadAttribute<float>(anZ);
  728. }
  729. else if (m_currentNodeName == nnRotate)
  730. {
  731. float angle = ReadAttribute<float>("angle");
  732. if (NextNode() != nnAxis) {
  733. throw DeadlyImportError("No axis specified for keyframe rotation in animation " + anim->name);
  734. }
  735. aiVector3D axis;
  736. axis.x = ReadAttribute<float>(anX);
  737. axis.y = ReadAttribute<float>(anY);
  738. axis.z = ReadAttribute<float>(anZ);
  739. if (axis.Equal(zeroVec))
  740. {
  741. axis.x = 1.0f;
  742. if (angle != 0) {
  743. ASSIMP_LOG_WARN_F("Found invalid a key frame with a zero rotation axis in animation: ", anim->name);
  744. }
  745. }
  746. keyframe.rotation = aiQuaternion(axis, angle);
  747. }
  748. else if (m_currentNodeName == nnScale)
  749. {
  750. keyframe.scale.x = ReadAttribute<float>(anX);
  751. keyframe.scale.y = ReadAttribute<float>(anY);
  752. keyframe.scale.z = ReadAttribute<float>(anZ);
  753. }
  754. NextNode();
  755. }
  756. dest->transformKeyFrames.push_back(keyframe);
  757. }
  758. }
  759. void OgreXmlSerializer::ReadBoneHierarchy(Skeleton *skeleton)
  760. {
  761. if (skeleton->bones.empty()) {
  762. throw DeadlyImportError("Cannot read <bonehierarchy> for a Skeleton without bones");
  763. }
  764. while(NextNode() == nnBoneParent)
  765. {
  766. const std::string name = ReadAttribute<std::string>("bone");
  767. const std::string parentName = ReadAttribute<std::string>("parent");
  768. Bone *bone = skeleton->BoneByName(name);
  769. Bone *parent = skeleton->BoneByName(parentName);
  770. if (bone && parent)
  771. parent->AddChild(bone);
  772. else
  773. throw DeadlyImportError("Failed to find bones for parenting: Child " + name + " for parent " + parentName);
  774. }
  775. // Calculate bone matrices for root bones. Recursively calculates their children.
  776. for (size_t i=0, len=skeleton->bones.size(); i<len; ++i)
  777. {
  778. Bone *bone = skeleton->bones[i];
  779. if (!bone->IsParented())
  780. bone->CalculateWorldMatrixAndDefaultPose(skeleton);
  781. }
  782. }
  783. static bool BoneCompare(Bone *a, Bone *b)
  784. {
  785. ai_assert( nullptr != a );
  786. ai_assert( nullptr != b );
  787. return (a->id < b->id);
  788. }
  789. void OgreXmlSerializer::ReadBones(Skeleton *skeleton)
  790. {
  791. ASSIMP_LOG_DEBUG(" - Bones");
  792. NextNode();
  793. while(m_currentNodeName == nnBone)
  794. {
  795. Bone *bone = new Bone();
  796. bone->id = ReadAttribute<uint16_t>("id");
  797. bone->name = ReadAttribute<std::string>("name");
  798. NextNode();
  799. while(m_currentNodeName == nnPosition ||
  800. m_currentNodeName == nnRotation ||
  801. m_currentNodeName == nnScale)
  802. {
  803. if (m_currentNodeName == nnPosition)
  804. {
  805. bone->position.x = ReadAttribute<float>(anX);
  806. bone->position.y = ReadAttribute<float>(anY);
  807. bone->position.z = ReadAttribute<float>(anZ);
  808. }
  809. else if (m_currentNodeName == nnRotation)
  810. {
  811. float angle = ReadAttribute<float>("angle");
  812. if (NextNode() != nnAxis) {
  813. throw DeadlyImportError(Formatter::format() << "No axis specified for bone rotation in bone " << bone->id);
  814. }
  815. aiVector3D axis;
  816. axis.x = ReadAttribute<float>(anX);
  817. axis.y = ReadAttribute<float>(anY);
  818. axis.z = ReadAttribute<float>(anZ);
  819. bone->rotation = aiQuaternion(axis, angle);
  820. }
  821. else if (m_currentNodeName == nnScale)
  822. {
  823. /// @todo Implement taking scale into account in matrix/pose calculations!
  824. if (HasAttribute("factor"))
  825. {
  826. float factor = ReadAttribute<float>("factor");
  827. bone->scale.Set(factor, factor, factor);
  828. }
  829. else
  830. {
  831. if (HasAttribute(anX))
  832. bone->scale.x = ReadAttribute<float>(anX);
  833. if (HasAttribute(anY))
  834. bone->scale.y = ReadAttribute<float>(anY);
  835. if (HasAttribute(anZ))
  836. bone->scale.z = ReadAttribute<float>(anZ);
  837. }
  838. }
  839. NextNode();
  840. }
  841. skeleton->bones.push_back(bone);
  842. }
  843. // Order bones by Id
  844. std::sort(skeleton->bones.begin(), skeleton->bones.end(), BoneCompare);
  845. // Validate that bone indexes are not skipped.
  846. /** @note Left this from original authors code, but not sure if this is strictly necessary
  847. as per the Ogre skeleton spec. It might be more that other (later) code in this imported does not break. */
  848. for (size_t i=0, len=skeleton->bones.size(); i<len; ++i)
  849. {
  850. Bone *b = skeleton->bones[i];
  851. ASSIMP_LOG_DEBUG_F( " ", b->id, " ", b->name);
  852. if (b->id != static_cast<uint16_t>(i)) {
  853. throw DeadlyImportError(Formatter::format() << "Bone ids are not in sequence starting from 0. Missing index " << i);
  854. }
  855. }
  856. }
  857. } // Ogre
  858. } // Assimp
  859. #endif // ASSIMP_BUILD_NO_OGRE_IMPORTER