IRRMeshLoader.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2020, assimp team
  6. All rights reserved.
  7. Redistribution and use of this software in source and binary forms,
  8. with or without modification, are permitted provided that the following
  9. conditions are met:
  10. * Redistributions of source code must retain the above
  11. copyright notice, this list of conditions and the
  12. following disclaimer.
  13. * Redistributions in binary form must reproduce the above
  14. copyright notice, this list of conditions and the
  15. following disclaimer in the documentation and/or other
  16. materials provided with the distribution.
  17. * Neither the name of the assimp team, nor the names of its
  18. contributors may be used to endorse or promote products
  19. derived from this software without specific prior
  20. written permission of the assimp team.
  21. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  22. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  23. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  24. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  25. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  26. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  27. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  28. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  29. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  30. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  31. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  32. ---------------------------------------------------------------------------
  33. */
  34. /** @file Implementation of the IrrMesh importer class */
  35. #ifndef ASSIMP_BUILD_NO_IRRMESH_IMPORTER
  36. #include "IRRMeshLoader.h"
  37. #include <assimp/ParsingUtils.h>
  38. #include <assimp/fast_atof.h>
  39. #include <memory>
  40. #include <assimp/IOSystem.hpp>
  41. #include <assimp/mesh.h>
  42. #include <assimp/DefaultLogger.hpp>
  43. #include <assimp/material.h>
  44. #include <assimp/scene.h>
  45. #include <assimp/importerdesc.h>
  46. using namespace Assimp;
  47. using namespace irr;
  48. using namespace irr::io;
  49. static const aiImporterDesc desc = {
  50. "Irrlicht Mesh Reader",
  51. "",
  52. "",
  53. "http://irrlicht.sourceforge.net/",
  54. aiImporterFlags_SupportTextFlavour,
  55. 0,
  56. 0,
  57. 0,
  58. 0,
  59. "xml irrmesh"
  60. };
  61. // ------------------------------------------------------------------------------------------------
  62. // Constructor to be privately used by Importer
  63. IRRMeshImporter::IRRMeshImporter()
  64. {}
  65. // ------------------------------------------------------------------------------------------------
  66. // Destructor, private as well
  67. IRRMeshImporter::~IRRMeshImporter()
  68. {}
  69. // ------------------------------------------------------------------------------------------------
  70. // Returns whether the class can handle the format of the given file.
  71. bool IRRMeshImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler, bool checkSig) const
  72. {
  73. /* NOTE: A simple check for the file extension is not enough
  74. * here. Irrmesh and irr are easy, but xml is too generic
  75. * and could be collada, too. So we need to open the file and
  76. * search for typical tokens.
  77. */
  78. const std::string extension = GetExtension(pFile);
  79. if (extension == "irrmesh")return true;
  80. else if (extension == "xml" || checkSig)
  81. {
  82. /* If CanRead() is called to check whether the loader
  83. * supports a specific file extension in general we
  84. * must return true here.
  85. */
  86. if (!pIOHandler)return true;
  87. const char* tokens[] = {"irrmesh"};
  88. return SearchFileHeaderForToken(pIOHandler,pFile,tokens,1);
  89. }
  90. return false;
  91. }
  92. // ------------------------------------------------------------------------------------------------
  93. // Get a list of all file extensions which are handled by this class
  94. const aiImporterDesc* IRRMeshImporter::GetInfo () const
  95. {
  96. return &desc;
  97. }
  98. static void releaseMaterial( aiMaterial **mat ) {
  99. if(*mat!= nullptr) {
  100. delete *mat;
  101. *mat = nullptr;
  102. }
  103. }
  104. static void releaseMesh( aiMesh **mesh ) {
  105. if (*mesh != nullptr){
  106. delete *mesh;
  107. *mesh = nullptr;
  108. }
  109. }
  110. // ------------------------------------------------------------------------------------------------
  111. // Imports the given file into the given scene structure.
  112. void IRRMeshImporter::InternReadFile( const std::string& pFile,
  113. aiScene* pScene, IOSystem* pIOHandler)
  114. {
  115. std::unique_ptr<IOStream> file( pIOHandler->Open( pFile));
  116. // Check whether we can read from the file
  117. if (file.get() == nullptr) {
  118. throw DeadlyImportError("Failed to open IRRMESH file " + pFile + ".");
  119. }
  120. // Construct the irrXML parser
  121. CIrrXML_IOStreamReader st(file.get());
  122. reader = createIrrXMLReader((IFileReadCallBack*) &st);
  123. // final data
  124. std::vector<aiMaterial*> materials;
  125. std::vector<aiMesh*> meshes;
  126. materials.reserve (5);
  127. meshes.reserve(5);
  128. // temporary data - current mesh buffer
  129. aiMaterial* curMat = nullptr;
  130. aiMesh* curMesh = nullptr;
  131. unsigned int curMatFlags = 0;
  132. std::vector<aiVector3D> curVertices,curNormals,curTangents,curBitangents;
  133. std::vector<aiColor4D> curColors;
  134. std::vector<aiVector3D> curUVs,curUV2s;
  135. // some temporary variables
  136. int textMeaning = 0;
  137. int vertexFormat = 0; // 0 = normal; 1 = 2 tcoords, 2 = tangents
  138. bool useColors = false;
  139. // Parse the XML file
  140. while (reader->read()) {
  141. switch (reader->getNodeType()) {
  142. case EXN_ELEMENT:
  143. if (!ASSIMP_stricmp(reader->getNodeName(),"buffer") && (curMat || curMesh)) {
  144. // end of previous buffer. A material and a mesh should be there
  145. if ( !curMat || !curMesh) {
  146. ASSIMP_LOG_ERROR("IRRMESH: A buffer must contain a mesh and a material");
  147. releaseMaterial( &curMat );
  148. releaseMesh( &curMesh );
  149. } else {
  150. materials.push_back(curMat);
  151. meshes.push_back(curMesh);
  152. }
  153. curMat = nullptr;
  154. curMesh = nullptr;
  155. curVertices.clear();
  156. curColors.clear();
  157. curNormals.clear();
  158. curUV2s.clear();
  159. curUVs.clear();
  160. curTangents.clear();
  161. curBitangents.clear();
  162. }
  163. if (!ASSIMP_stricmp(reader->getNodeName(),"material")) {
  164. if (curMat) {
  165. ASSIMP_LOG_WARN("IRRMESH: Only one material description per buffer, please");
  166. releaseMaterial( &curMat );
  167. }
  168. curMat = ParseMaterial(curMatFlags);
  169. }
  170. /* no else here! */ if (!ASSIMP_stricmp(reader->getNodeName(),"vertices"))
  171. {
  172. int num = reader->getAttributeValueAsInt("vertexCount");
  173. if (!num) {
  174. // This is possible ... remove the mesh from the list and skip further reading
  175. ASSIMP_LOG_WARN("IRRMESH: Found mesh with zero vertices");
  176. releaseMaterial( &curMat );
  177. releaseMesh( &curMesh );
  178. textMeaning = 0;
  179. continue;
  180. }
  181. curVertices.reserve(num);
  182. curNormals.reserve(num);
  183. curColors.reserve(num);
  184. curUVs.reserve(num);
  185. // Determine the file format
  186. const char* t = reader->getAttributeValueSafe("type");
  187. if (!ASSIMP_stricmp("2tcoords", t)) {
  188. curUV2s.reserve (num);
  189. vertexFormat = 1;
  190. if (curMatFlags & AI_IRRMESH_EXTRA_2ND_TEXTURE) {
  191. // *********************************************************
  192. // We have a second texture! So use this UV channel
  193. // for it. The 2nd texture can be either a normal
  194. // texture (solid_2layer or lightmap_xxx) or a normal
  195. // map (normal_..., parallax_...)
  196. // *********************************************************
  197. int idx = 1;
  198. aiMaterial* mat = ( aiMaterial* ) curMat;
  199. if (curMatFlags & AI_IRRMESH_MAT_lightmap){
  200. mat->AddProperty(&idx,1,AI_MATKEY_UVWSRC_LIGHTMAP(0));
  201. }
  202. else if (curMatFlags & AI_IRRMESH_MAT_normalmap_solid){
  203. mat->AddProperty(&idx,1,AI_MATKEY_UVWSRC_NORMALS(0));
  204. }
  205. else if (curMatFlags & AI_IRRMESH_MAT_solid_2layer) {
  206. mat->AddProperty(&idx,1,AI_MATKEY_UVWSRC_DIFFUSE(1));
  207. }
  208. }
  209. }
  210. else if (!ASSIMP_stricmp("tangents", t)) {
  211. curTangents.reserve (num);
  212. curBitangents.reserve (num);
  213. vertexFormat = 2;
  214. }
  215. else if (ASSIMP_stricmp("standard", t)) {
  216. releaseMaterial( &curMat );
  217. ASSIMP_LOG_WARN("IRRMESH: Unknown vertex format");
  218. }
  219. else vertexFormat = 0;
  220. textMeaning = 1;
  221. }
  222. else if (!ASSIMP_stricmp(reader->getNodeName(),"indices")) {
  223. if (curVertices.empty() && curMat) {
  224. releaseMaterial( &curMat );
  225. throw DeadlyImportError("IRRMESH: indices must come after vertices");
  226. }
  227. textMeaning = 2;
  228. // start a new mesh
  229. curMesh = new aiMesh();
  230. // allocate storage for all faces
  231. curMesh->mNumVertices = reader->getAttributeValueAsInt("indexCount");
  232. if (!curMesh->mNumVertices) {
  233. // This is possible ... remove the mesh from the list and skip further reading
  234. ASSIMP_LOG_WARN("IRRMESH: Found mesh with zero indices");
  235. // mesh - away
  236. releaseMesh( &curMesh );
  237. // material - away
  238. releaseMaterial( &curMat );
  239. textMeaning = 0;
  240. continue;
  241. }
  242. if (curMesh->mNumVertices % 3) {
  243. ASSIMP_LOG_WARN("IRRMESH: Number if indices isn't divisible by 3");
  244. }
  245. curMesh->mNumFaces = curMesh->mNumVertices / 3;
  246. curMesh->mFaces = new aiFace[curMesh->mNumFaces];
  247. // setup some members
  248. curMesh->mMaterialIndex = (unsigned int)materials.size();
  249. curMesh->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;
  250. // allocate storage for all vertices
  251. curMesh->mVertices = new aiVector3D[curMesh->mNumVertices];
  252. if (curNormals.size() == curVertices.size()) {
  253. curMesh->mNormals = new aiVector3D[curMesh->mNumVertices];
  254. }
  255. if (curTangents.size() == curVertices.size()) {
  256. curMesh->mTangents = new aiVector3D[curMesh->mNumVertices];
  257. }
  258. if (curBitangents.size() == curVertices.size()) {
  259. curMesh->mBitangents = new aiVector3D[curMesh->mNumVertices];
  260. }
  261. if (curColors.size() == curVertices.size() && useColors) {
  262. curMesh->mColors[0] = new aiColor4D[curMesh->mNumVertices];
  263. }
  264. if (curUVs.size() == curVertices.size()) {
  265. curMesh->mTextureCoords[0] = new aiVector3D[curMesh->mNumVertices];
  266. }
  267. if (curUV2s.size() == curVertices.size()) {
  268. curMesh->mTextureCoords[1] = new aiVector3D[curMesh->mNumVertices];
  269. }
  270. }
  271. break;
  272. case EXN_TEXT:
  273. {
  274. const char* sz = reader->getNodeData();
  275. if (textMeaning == 1) {
  276. textMeaning = 0;
  277. // read vertices
  278. do {
  279. SkipSpacesAndLineEnd(&sz);
  280. aiVector3D temp;aiColor4D c;
  281. // Read the vertex position
  282. sz = fast_atoreal_move<float>(sz,(float&)temp.x);
  283. SkipSpaces(&sz);
  284. sz = fast_atoreal_move<float>(sz,(float&)temp.y);
  285. SkipSpaces(&sz);
  286. sz = fast_atoreal_move<float>(sz,(float&)temp.z);
  287. SkipSpaces(&sz);
  288. curVertices.push_back(temp);
  289. // Read the vertex normals
  290. sz = fast_atoreal_move<float>(sz,(float&)temp.x);
  291. SkipSpaces(&sz);
  292. sz = fast_atoreal_move<float>(sz,(float&)temp.y);
  293. SkipSpaces(&sz);
  294. sz = fast_atoreal_move<float>(sz,(float&)temp.z);
  295. SkipSpaces(&sz);
  296. curNormals.push_back(temp);
  297. // read the vertex colors
  298. uint32_t clr = strtoul16(sz,&sz);
  299. ColorFromARGBPacked(clr,c);
  300. if (!curColors.empty() && c != *(curColors.end()-1))
  301. useColors = true;
  302. curColors.push_back(c);
  303. SkipSpaces(&sz);
  304. // read the first UV coordinate set
  305. sz = fast_atoreal_move<float>(sz,(float&)temp.x);
  306. SkipSpaces(&sz);
  307. sz = fast_atoreal_move<float>(sz,(float&)temp.y);
  308. SkipSpaces(&sz);
  309. temp.z = 0.f;
  310. temp.y = 1.f - temp.y; // DX to OGL
  311. curUVs.push_back(temp);
  312. // read the (optional) second UV coordinate set
  313. if (vertexFormat == 1) {
  314. sz = fast_atoreal_move<float>(sz,(float&)temp.x);
  315. SkipSpaces(&sz);
  316. sz = fast_atoreal_move<float>(sz,(float&)temp.y);
  317. temp.y = 1.f - temp.y; // DX to OGL
  318. curUV2s.push_back(temp);
  319. }
  320. // read optional tangent and bitangent vectors
  321. else if (vertexFormat == 2) {
  322. // tangents
  323. sz = fast_atoreal_move<float>(sz,(float&)temp.x);
  324. SkipSpaces(&sz);
  325. sz = fast_atoreal_move<float>(sz,(float&)temp.z);
  326. SkipSpaces(&sz);
  327. sz = fast_atoreal_move<float>(sz,(float&)temp.y);
  328. SkipSpaces(&sz);
  329. temp.y *= -1.0f;
  330. curTangents.push_back(temp);
  331. // bitangents
  332. sz = fast_atoreal_move<float>(sz,(float&)temp.x);
  333. SkipSpaces(&sz);
  334. sz = fast_atoreal_move<float>(sz,(float&)temp.z);
  335. SkipSpaces(&sz);
  336. sz = fast_atoreal_move<float>(sz,(float&)temp.y);
  337. SkipSpaces(&sz);
  338. temp.y *= -1.0f;
  339. curBitangents.push_back(temp);
  340. }
  341. }
  342. /* IMPORTANT: We assume that each vertex is specified in one
  343. line. So we can skip the rest of the line - unknown vertex
  344. elements are ignored.
  345. */
  346. while (SkipLine(&sz));
  347. }
  348. else if (textMeaning == 2) {
  349. textMeaning = 0;
  350. // read indices
  351. aiFace* curFace = curMesh->mFaces;
  352. aiFace* const faceEnd = curMesh->mFaces + curMesh->mNumFaces;
  353. aiVector3D* pcV = curMesh->mVertices;
  354. aiVector3D* pcN = curMesh->mNormals;
  355. aiVector3D* pcT = curMesh->mTangents;
  356. aiVector3D* pcB = curMesh->mBitangents;
  357. aiColor4D* pcC0 = curMesh->mColors[0];
  358. aiVector3D* pcT0 = curMesh->mTextureCoords[0];
  359. aiVector3D* pcT1 = curMesh->mTextureCoords[1];
  360. unsigned int curIdx = 0;
  361. unsigned int total = 0;
  362. while(SkipSpacesAndLineEnd(&sz)) {
  363. if (curFace >= faceEnd) {
  364. ASSIMP_LOG_ERROR("IRRMESH: Too many indices");
  365. break;
  366. }
  367. if (!curIdx) {
  368. curFace->mNumIndices = 3;
  369. curFace->mIndices = new unsigned int[3];
  370. }
  371. unsigned int idx = strtoul10(sz,&sz);
  372. if (idx >= curVertices.size()) {
  373. ASSIMP_LOG_ERROR("IRRMESH: Index out of range");
  374. idx = 0;
  375. }
  376. curFace->mIndices[curIdx] = total++;
  377. *pcV++ = curVertices[idx];
  378. if (pcN)*pcN++ = curNormals[idx];
  379. if (pcT)*pcT++ = curTangents[idx];
  380. if (pcB)*pcB++ = curBitangents[idx];
  381. if (pcC0)*pcC0++ = curColors[idx];
  382. if (pcT0)*pcT0++ = curUVs[idx];
  383. if (pcT1)*pcT1++ = curUV2s[idx];
  384. if (++curIdx == 3) {
  385. ++curFace;
  386. curIdx = 0;
  387. }
  388. }
  389. if (curFace != faceEnd)
  390. ASSIMP_LOG_ERROR("IRRMESH: Not enough indices");
  391. // Finish processing the mesh - do some small material workarounds
  392. if (curMatFlags & AI_IRRMESH_MAT_trans_vertex_alpha && !useColors) {
  393. // Take the opacity value of the current material
  394. // from the common vertex color alpha
  395. aiMaterial* mat = (aiMaterial*)curMat;
  396. mat->AddProperty(&curColors[0].a,1,AI_MATKEY_OPACITY);
  397. }
  398. }}
  399. break;
  400. default:
  401. // GCC complains here ...
  402. break;
  403. };
  404. }
  405. // End of the last buffer. A material and a mesh should be there
  406. if (curMat || curMesh) {
  407. if ( !curMat || !curMesh) {
  408. ASSIMP_LOG_ERROR("IRRMESH: A buffer must contain a mesh and a material");
  409. releaseMaterial( &curMat );
  410. releaseMesh( &curMesh );
  411. }
  412. else {
  413. materials.push_back(curMat);
  414. meshes.push_back(curMesh);
  415. }
  416. }
  417. if (materials.empty())
  418. throw DeadlyImportError("IRRMESH: Unable to read a mesh from this file");
  419. // now generate the output scene
  420. pScene->mNumMeshes = (unsigned int)meshes.size();
  421. pScene->mMeshes = new aiMesh*[pScene->mNumMeshes];
  422. for (unsigned int i = 0; i < pScene->mNumMeshes;++i) {
  423. pScene->mMeshes[i] = meshes[i];
  424. // clean this value ...
  425. pScene->mMeshes[i]->mNumUVComponents[3] = 0;
  426. }
  427. pScene->mNumMaterials = (unsigned int)materials.size();
  428. pScene->mMaterials = new aiMaterial*[pScene->mNumMaterials];
  429. ::memcpy(pScene->mMaterials,&materials[0],sizeof(void*)*pScene->mNumMaterials);
  430. pScene->mRootNode = new aiNode();
  431. pScene->mRootNode->mName.Set("<IRRMesh>");
  432. pScene->mRootNode->mNumMeshes = pScene->mNumMeshes;
  433. pScene->mRootNode->mMeshes = new unsigned int[pScene->mNumMeshes];
  434. for (unsigned int i = 0; i < pScene->mNumMeshes;++i)
  435. pScene->mRootNode->mMeshes[i] = i;
  436. // clean up and return
  437. delete reader;
  438. AI_DEBUG_INVALIDATE_PTR(reader);
  439. }
  440. #endif // !! ASSIMP_BUILD_NO_IRRMESH_IMPORTER