IRRMeshLoader.cpp 16 KB

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