IRRMeshLoader.cpp 16 KB

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