IRRMeshLoader.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2016, 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 "ParsingUtils.h"
  38. #include "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 "Macros.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. delete mat;
  100. mat = nullptr;
  101. }
  102. static void releaseMesh( aiMesh *mesh ) {
  103. delete mesh;
  104. mesh = nullptr;
  105. }
  106. // ------------------------------------------------------------------------------------------------
  107. // Imports the given file into the given scene structure.
  108. void IRRMeshImporter::InternReadFile( const std::string& pFile,
  109. aiScene* pScene, IOSystem* pIOHandler)
  110. {
  111. std::unique_ptr<IOStream> file( pIOHandler->Open( pFile));
  112. // Check whether we can read from the file
  113. if( file.get() == NULL)
  114. throw DeadlyImportError( "Failed to open IRRMESH file " + pFile + "");
  115. // Construct the irrXML parser
  116. CIrrXML_IOStreamReader st(file.get());
  117. reader = createIrrXMLReader((IFileReadCallBack*) &st);
  118. // final data
  119. std::vector<aiMaterial*> materials;
  120. std::vector<aiMesh*> meshes;
  121. materials.reserve (5);
  122. meshes.reserve(5);
  123. // temporary data - current mesh buffer
  124. aiMaterial* curMat = NULL;
  125. aiMesh* curMesh = NULL;
  126. unsigned int curMatFlags = 0;
  127. std::vector<aiVector3D> curVertices,curNormals,curTangents,curBitangents;
  128. std::vector<aiColor4D> curColors;
  129. std::vector<aiVector3D> curUVs,curUV2s;
  130. // some temporary variables
  131. int textMeaning = 0;
  132. int vertexFormat = 0; // 0 = normal; 1 = 2 tcoords, 2 = tangents
  133. bool useColors = false;
  134. // Parse the XML file
  135. while (reader->read()) {
  136. switch (reader->getNodeType()) {
  137. case EXN_ELEMENT:
  138. if (!ASSIMP_stricmp(reader->getNodeName(),"buffer") && (curMat || curMesh)) {
  139. // end of previous buffer. A material and a mesh should be there
  140. if ( !curMat || !curMesh) {
  141. DefaultLogger::get()->error("IRRMESH: A buffer must contain a mesh and a material");
  142. releaseMaterial( curMat );
  143. releaseMesh( curMesh );
  144. } else {
  145. materials.push_back(curMat);
  146. meshes.push_back(curMesh);
  147. }
  148. curMat = NULL;
  149. curMesh = NULL;
  150. curVertices.clear();
  151. curColors.clear();
  152. curNormals.clear();
  153. curUV2s.clear();
  154. curUVs.clear();
  155. curTangents.clear();
  156. curBitangents.clear();
  157. }
  158. if (!ASSIMP_stricmp(reader->getNodeName(),"material")) {
  159. if (curMat) {
  160. DefaultLogger::get()->warn("IRRMESH: Only one material description per buffer, please");
  161. releaseMaterial( curMat );
  162. }
  163. curMat = ParseMaterial(curMatFlags);
  164. }
  165. /* no else here! */ if (!ASSIMP_stricmp(reader->getNodeName(),"vertices"))
  166. {
  167. int num = reader->getAttributeValueAsInt("vertexCount");
  168. if (!num) {
  169. // This is possible ... remove the mesh from the list and skip further reading
  170. DefaultLogger::get()->warn("IRRMESH: Found mesh with zero vertices");
  171. releaseMaterial( curMat );
  172. releaseMesh( curMesh );
  173. textMeaning = 0;
  174. continue;
  175. }
  176. curVertices.reserve(num);
  177. curNormals.reserve(num);
  178. curColors.reserve(num);
  179. curUVs.reserve(num);
  180. // Determine the file format
  181. const char* t = reader->getAttributeValueSafe("type");
  182. if (!ASSIMP_stricmp("2tcoords", t)) {
  183. curUV2s.reserve (num);
  184. vertexFormat = 1;
  185. if (curMatFlags & AI_IRRMESH_EXTRA_2ND_TEXTURE) {
  186. // *********************************************************
  187. // We have a second texture! So use this UV channel
  188. // for it. The 2nd texture can be either a normal
  189. // texture (solid_2layer or lightmap_xxx) or a normal
  190. // map (normal_..., parallax_...)
  191. // *********************************************************
  192. int idx = 1;
  193. aiMaterial* mat = ( aiMaterial* ) curMat;
  194. if (curMatFlags & AI_IRRMESH_MAT_lightmap){
  195. mat->AddProperty(&idx,1,AI_MATKEY_UVWSRC_LIGHTMAP(0));
  196. }
  197. else if (curMatFlags & AI_IRRMESH_MAT_normalmap_solid){
  198. mat->AddProperty(&idx,1,AI_MATKEY_UVWSRC_NORMALS(0));
  199. }
  200. else if (curMatFlags & AI_IRRMESH_MAT_solid_2layer) {
  201. mat->AddProperty(&idx,1,AI_MATKEY_UVWSRC_DIFFUSE(1));
  202. }
  203. }
  204. }
  205. else if (!ASSIMP_stricmp("tangents", t)) {
  206. curTangents.reserve (num);
  207. curBitangents.reserve (num);
  208. vertexFormat = 2;
  209. }
  210. else if (ASSIMP_stricmp("standard", t)) {
  211. releaseMaterial( curMat );
  212. DefaultLogger::get()->warn("IRRMESH: Unknown vertex format");
  213. }
  214. else vertexFormat = 0;
  215. textMeaning = 1;
  216. }
  217. else if (!ASSIMP_stricmp(reader->getNodeName(),"indices")) {
  218. if (curVertices.empty() && curMat) {
  219. releaseMaterial( curMat );
  220. throw DeadlyImportError("IRRMESH: indices must come after vertices");
  221. }
  222. textMeaning = 2;
  223. // start a new mesh
  224. curMesh = new aiMesh();
  225. // allocate storage for all faces
  226. curMesh->mNumVertices = reader->getAttributeValueAsInt("indexCount");
  227. if (!curMesh->mNumVertices) {
  228. // This is possible ... remove the mesh from the list and skip further reading
  229. DefaultLogger::get()->warn("IRRMESH: Found mesh with zero indices");
  230. // mesh - away
  231. releaseMesh( curMesh );
  232. // material - away
  233. releaseMaterial( curMat );
  234. textMeaning = 0;
  235. continue;
  236. }
  237. if (curMesh->mNumVertices % 3) {
  238. DefaultLogger::get()->warn("IRRMESH: Number if indices isn't divisible by 3");
  239. }
  240. curMesh->mNumFaces = curMesh->mNumVertices / 3;
  241. curMesh->mFaces = new aiFace[curMesh->mNumFaces];
  242. // setup some members
  243. curMesh->mMaterialIndex = (unsigned int)materials.size();
  244. curMesh->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;
  245. // allocate storage for all vertices
  246. curMesh->mVertices = new aiVector3D[curMesh->mNumVertices];
  247. if (curNormals.size() == curVertices.size()) {
  248. curMesh->mNormals = new aiVector3D[curMesh->mNumVertices];
  249. }
  250. if (curTangents.size() == curVertices.size()) {
  251. curMesh->mTangents = new aiVector3D[curMesh->mNumVertices];
  252. }
  253. if (curBitangents.size() == curVertices.size()) {
  254. curMesh->mBitangents = new aiVector3D[curMesh->mNumVertices];
  255. }
  256. if (curColors.size() == curVertices.size() && useColors) {
  257. curMesh->mColors[0] = new aiColor4D[curMesh->mNumVertices];
  258. }
  259. if (curUVs.size() == curVertices.size()) {
  260. curMesh->mTextureCoords[0] = new aiVector3D[curMesh->mNumVertices];
  261. }
  262. if (curUV2s.size() == curVertices.size()) {
  263. curMesh->mTextureCoords[1] = new aiVector3D[curMesh->mNumVertices];
  264. }
  265. }
  266. break;
  267. case EXN_TEXT:
  268. {
  269. const char* sz = reader->getNodeData();
  270. if (textMeaning == 1) {
  271. textMeaning = 0;
  272. // read vertices
  273. do {
  274. SkipSpacesAndLineEnd(&sz);
  275. aiVector3D temp;aiColor4D c;
  276. // Read the vertex position
  277. sz = fast_atoreal_move<float>(sz,(float&)temp.x);
  278. SkipSpaces(&sz);
  279. sz = fast_atoreal_move<float>(sz,(float&)temp.y);
  280. SkipSpaces(&sz);
  281. sz = fast_atoreal_move<float>(sz,(float&)temp.z);
  282. SkipSpaces(&sz);
  283. curVertices.push_back(temp);
  284. // Read the vertex normals
  285. sz = fast_atoreal_move<float>(sz,(float&)temp.x);
  286. SkipSpaces(&sz);
  287. sz = fast_atoreal_move<float>(sz,(float&)temp.y);
  288. SkipSpaces(&sz);
  289. sz = fast_atoreal_move<float>(sz,(float&)temp.z);
  290. SkipSpaces(&sz);
  291. curNormals.push_back(temp);
  292. // read the vertex colors
  293. uint32_t clr = strtoul16(sz,&sz);
  294. ColorFromARGBPacked(clr,c);
  295. if (!curColors.empty() && c != *(curColors.end()-1))
  296. useColors = true;
  297. curColors.push_back(c);
  298. SkipSpaces(&sz);
  299. // read the first UV coordinate set
  300. sz = fast_atoreal_move<float>(sz,(float&)temp.x);
  301. SkipSpaces(&sz);
  302. sz = fast_atoreal_move<float>(sz,(float&)temp.y);
  303. SkipSpaces(&sz);
  304. temp.z = 0.f;
  305. temp.y = 1.f - temp.y; // DX to OGL
  306. curUVs.push_back(temp);
  307. // read the (optional) second UV coordinate set
  308. if (vertexFormat == 1) {
  309. sz = fast_atoreal_move<float>(sz,(float&)temp.x);
  310. SkipSpaces(&sz);
  311. sz = fast_atoreal_move<float>(sz,(float&)temp.y);
  312. temp.y = 1.f - temp.y; // DX to OGL
  313. curUV2s.push_back(temp);
  314. }
  315. // read optional tangent and bitangent vectors
  316. else if (vertexFormat == 2) {
  317. // tangents
  318. sz = fast_atoreal_move<float>(sz,(float&)temp.x);
  319. SkipSpaces(&sz);
  320. sz = fast_atoreal_move<float>(sz,(float&)temp.z);
  321. SkipSpaces(&sz);
  322. sz = fast_atoreal_move<float>(sz,(float&)temp.y);
  323. SkipSpaces(&sz);
  324. temp.y *= -1.0f;
  325. curTangents.push_back(temp);
  326. // bitangents
  327. sz = fast_atoreal_move<float>(sz,(float&)temp.x);
  328. SkipSpaces(&sz);
  329. sz = fast_atoreal_move<float>(sz,(float&)temp.z);
  330. SkipSpaces(&sz);
  331. sz = fast_atoreal_move<float>(sz,(float&)temp.y);
  332. SkipSpaces(&sz);
  333. temp.y *= -1.0f;
  334. curBitangents.push_back(temp);
  335. }
  336. }
  337. /* IMPORTANT: We assume that each vertex is specified in one
  338. line. So we can skip the rest of the line - unknown vertex
  339. elements are ignored.
  340. */
  341. while (SkipLine(&sz));
  342. }
  343. else if (textMeaning == 2) {
  344. textMeaning = 0;
  345. // read indices
  346. aiFace* curFace = curMesh->mFaces;
  347. aiFace* const faceEnd = curMesh->mFaces + curMesh->mNumFaces;
  348. aiVector3D* pcV = curMesh->mVertices;
  349. aiVector3D* pcN = curMesh->mNormals;
  350. aiVector3D* pcT = curMesh->mTangents;
  351. aiVector3D* pcB = curMesh->mBitangents;
  352. aiColor4D* pcC0 = curMesh->mColors[0];
  353. aiVector3D* pcT0 = curMesh->mTextureCoords[0];
  354. aiVector3D* pcT1 = curMesh->mTextureCoords[1];
  355. unsigned int curIdx = 0;
  356. unsigned int total = 0;
  357. while(SkipSpacesAndLineEnd(&sz)) {
  358. if (curFace >= faceEnd) {
  359. DefaultLogger::get()->error("IRRMESH: Too many indices");
  360. break;
  361. }
  362. if (!curIdx) {
  363. curFace->mNumIndices = 3;
  364. curFace->mIndices = new unsigned int[3];
  365. }
  366. unsigned int idx = strtoul10(sz,&sz);
  367. if (idx >= curVertices.size()) {
  368. DefaultLogger::get()->error("IRRMESH: Index out of range");
  369. idx = 0;
  370. }
  371. curFace->mIndices[curIdx] = total++;
  372. *pcV++ = curVertices[idx];
  373. if (pcN)*pcN++ = curNormals[idx];
  374. if (pcT)*pcT++ = curTangents[idx];
  375. if (pcB)*pcB++ = curBitangents[idx];
  376. if (pcC0)*pcC0++ = curColors[idx];
  377. if (pcT0)*pcT0++ = curUVs[idx];
  378. if (pcT1)*pcT1++ = curUV2s[idx];
  379. if (++curIdx == 3) {
  380. ++curFace;
  381. curIdx = 0;
  382. }
  383. }
  384. if (curFace != faceEnd)
  385. DefaultLogger::get()->error("IRRMESH: Not enough indices");
  386. // Finish processing the mesh - do some small material workarounds
  387. if (curMatFlags & AI_IRRMESH_MAT_trans_vertex_alpha && !useColors) {
  388. // Take the opacity value of the current material
  389. // from the common vertex color alpha
  390. aiMaterial* mat = (aiMaterial*)curMat;
  391. mat->AddProperty(&curColors[0].a,1,AI_MATKEY_OPACITY);
  392. }
  393. }}
  394. break;
  395. default:
  396. // GCC complains here ...
  397. break;
  398. };
  399. }
  400. // End of the last buffer. A material and a mesh should be there
  401. if (curMat || curMesh) {
  402. if ( !curMat || !curMesh) {
  403. DefaultLogger::get()->error("IRRMESH: A buffer must contain a mesh and a material");
  404. releaseMaterial( curMat );
  405. releaseMesh( curMesh );
  406. }
  407. else {
  408. materials.push_back(curMat);
  409. meshes.push_back(curMesh);
  410. }
  411. }
  412. if (materials.empty())
  413. throw DeadlyImportError("IRRMESH: Unable to read a mesh from this file");
  414. // now generate the output scene
  415. pScene->mNumMeshes = (unsigned int)meshes.size();
  416. pScene->mMeshes = new aiMesh*[pScene->mNumMeshes];
  417. for (unsigned int i = 0; i < pScene->mNumMeshes;++i) {
  418. pScene->mMeshes[i] = meshes[i];
  419. // clean this value ...
  420. pScene->mMeshes[i]->mNumUVComponents[3] = 0;
  421. }
  422. pScene->mNumMaterials = (unsigned int)materials.size();
  423. pScene->mMaterials = new aiMaterial*[pScene->mNumMaterials];
  424. ::memcpy(pScene->mMaterials,&materials[0],sizeof(void*)*pScene->mNumMaterials);
  425. pScene->mRootNode = new aiNode();
  426. pScene->mRootNode->mName.Set("<IRRMesh>");
  427. pScene->mRootNode->mNumMeshes = pScene->mNumMeshes;
  428. pScene->mRootNode->mMeshes = new unsigned int[pScene->mNumMeshes];
  429. for (unsigned int i = 0; i < pScene->mNumMeshes;++i)
  430. pScene->mRootNode->mMeshes[i] = i;
  431. // clean up and return
  432. delete reader;
  433. AI_DEBUG_INVALIDATE_PTR(reader);
  434. }
  435. #endif // !! ASSIMP_BUILD_NO_IRRMESH_IMPORTER