NFFLoader.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  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 STL importer class */
  35. // internal headers
  36. #include "NFFLoader.h"
  37. #include "MaterialSystem.h"
  38. #include "ParsingUtils.h"
  39. #include "StandardShapes.h"
  40. #include "fast_atof.h"
  41. #include "qnan.h"
  42. // public assimp headers
  43. #include "../include/IOStream.h"
  44. #include "../include/IOSystem.h"
  45. #include "../include/aiScene.h"
  46. #include "../include/aiAssert.h"
  47. #include "../include/DefaultLogger.h"
  48. // boost headers
  49. #include <boost/scoped_ptr.hpp>
  50. using namespace Assimp;
  51. // ------------------------------------------------------------------------------------------------
  52. // Constructor to be privately used by Importer
  53. NFFImporter::NFFImporter()
  54. {
  55. }
  56. // ------------------------------------------------------------------------------------------------
  57. // Destructor, private as well
  58. NFFImporter::~NFFImporter()
  59. {
  60. }
  61. // ------------------------------------------------------------------------------------------------
  62. // Returns whether the class can handle the format of the given file.
  63. bool NFFImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler) const
  64. {
  65. // simple check of file extension is enough for the moment
  66. std::string::size_type pos = pFile.find_last_of('.');
  67. // no file extension - can't read
  68. if( pos == std::string::npos)return false;
  69. std::string extension = pFile.substr( pos);
  70. return !(extension.length() != 4 || extension[0] != '.' ||
  71. extension[1] != 'n' && extension[1] != 'N' ||
  72. extension[2] != 'f' && extension[2] != 'F' ||
  73. extension[3] != 'f' && extension[3] != 'F');
  74. }
  75. // ------------------------------------------------------------------------------------------------
  76. bool GetNextLine(const char*& buffer, char out[4096])
  77. {
  78. if ('\0' == *buffer)return false;
  79. char* _out = out;
  80. char* const end = _out+4096;
  81. while (!IsLineEnd( *buffer ) && _out < end)
  82. *_out++ = *buffer++;
  83. *_out = '\0';
  84. if ('\0' != *buffer)while (IsLineEnd( *buffer ))++buffer;
  85. return true;
  86. }
  87. // ------------------------------------------------------------------------------------------------
  88. #define AI_NFF_PARSE_FLOAT(f) \
  89. SkipSpaces(&sz); \
  90. if (!::IsLineEnd(*sz))sz = fast_atof_move(sz, (float&)f);
  91. // ------------------------------------------------------------------------------------------------
  92. #define AI_NFF_PARSE_TRIPLE(v) \
  93. AI_NFF_PARSE_FLOAT(v.x) \
  94. AI_NFF_PARSE_FLOAT(v.y) \
  95. AI_NFF_PARSE_FLOAT(v.z)
  96. // ------------------------------------------------------------------------------------------------
  97. #define AI_NFF_PARSE_SHAPE_INFORMATION() \
  98. aiVector3D center, radius(1.0f,std::numeric_limits<float>::quiet_NaN(),std::numeric_limits<float>::quiet_NaN()); \
  99. AI_NFF_PARSE_TRIPLE(center); \
  100. AI_NFF_PARSE_TRIPLE(radius); \
  101. if (is_qnan(radius.z))radius.z = radius.x; \
  102. if (is_qnan(radius.y))radius.y = radius.x; \
  103. currentMesh.radius = radius; \
  104. currentMesh.center = center;
  105. // ------------------------------------------------------------------------------------------------
  106. // Imports the given file into the given scene structure.
  107. void NFFImporter::InternReadFile( const std::string& pFile,
  108. aiScene* pScene, IOSystem* pIOHandler)
  109. {
  110. boost::scoped_ptr<IOStream> file( pIOHandler->Open( pFile, "rb"));
  111. // Check whether we can read from the file
  112. if( file.get() == NULL)
  113. throw new ImportErrorException( "Failed to open NFF file " + pFile + ".");
  114. unsigned int m = (unsigned int)file->FileSize();
  115. // allocate storage and copy the contents of the file to a memory buffer
  116. // (terminate it with zero)
  117. std::vector<char> mBuffer2(m+1);
  118. file->Read(&mBuffer2[0],m,1);
  119. const char* buffer = &mBuffer2[0];
  120. mBuffer2[m] = '\0';
  121. // mesh arrays - separate here to make the handling of
  122. // the pointers below easier.
  123. std::vector<MeshInfo> meshes;
  124. std::vector<MeshInfo> meshesWithNormals;
  125. std::vector<MeshInfo> meshesLocked;
  126. MeshInfo* currentMeshWithNormals = NULL;
  127. MeshInfo* currentMesh = NULL;
  128. ShadingInfo s; // current material info
  129. // degree of tesselation
  130. unsigned int iTesselation = 4;
  131. char line[4096];
  132. const char* sz;
  133. unsigned int sphere = 0,cylinder = 0,cone = 0,numNamed = 0,
  134. dodecahedron = 0,octahedron = 0,tetrahedron = 0, hexahedron = 0;
  135. while (GetNextLine(buffer,line))
  136. {
  137. if ('p' == line[0])
  138. {
  139. MeshInfo* out = NULL;
  140. // 'pp' - polygon patch primitive
  141. if ('p' == line[1])
  142. {
  143. if (meshesWithNormals.empty())
  144. {
  145. meshesWithNormals.push_back(MeshInfo(true));
  146. currentMeshWithNormals = &meshesWithNormals.back();
  147. }
  148. sz = &line[2];out = currentMeshWithNormals;
  149. }
  150. // 'p' - polygon primitive
  151. else
  152. {
  153. if (meshes.empty())
  154. {
  155. meshes.push_back(MeshInfo(false));
  156. currentMesh = &meshes.back();
  157. }
  158. sz = &line[1];out = currentMesh;
  159. }
  160. SkipSpaces(sz,&sz);
  161. m = strtol10(sz);
  162. // ---- flip the face order
  163. out->vertices.resize(out->vertices.size()+m);
  164. if (out == currentMeshWithNormals)
  165. {
  166. out->normals.resize(out->vertices.size());
  167. }
  168. for (unsigned int n = 0; n < m;++n)
  169. {
  170. if(!GetNextLine(buffer,line))
  171. {
  172. DefaultLogger::get()->error("NFF: Unexpected EOF was encountered");
  173. continue;
  174. }
  175. aiVector3D v; sz = &line[0];
  176. AI_NFF_PARSE_TRIPLE(v);
  177. out->vertices[out->vertices.size()-n-1] = v;
  178. if (out == currentMeshWithNormals)
  179. {
  180. AI_NFF_PARSE_TRIPLE(v);
  181. out->normals[out->vertices.size()-n-1] = v;
  182. }
  183. }
  184. out->faces.push_back(m);
  185. }
  186. // 'f' - shading information block
  187. else if ('f' == line[0] && IsSpace(line[1]))
  188. {
  189. SkipSpaces(&line[1],&sz);
  190. // read just the RGB colors, the rest is ignored for the moment
  191. sz = fast_atof_move(sz, (float&)s.color.r);
  192. SkipSpaces(&sz);
  193. sz = fast_atof_move(sz, (float&)s.color.g);
  194. SkipSpaces(&sz);
  195. sz = fast_atof_move(sz, (float&)s.color.b);
  196. // check whether we have this material already -
  197. // although we have the RRM-Step, this is necessary here.
  198. // otherwise we would generate hundreds of small meshes
  199. // with just a few faces - this is surely never wanted.
  200. currentMesh = currentMeshWithNormals = NULL;
  201. for (std::vector<MeshInfo>::iterator it = meshes.begin(), end = meshes.end();
  202. it != end;++it)
  203. {
  204. if ((*it).bLocked)continue;
  205. if ((*it).shader == s)
  206. {
  207. if ((*it).bHasNormals)currentMeshWithNormals = &(*it);
  208. else currentMesh = &(*it);
  209. }
  210. }
  211. if (!currentMesh)
  212. {
  213. meshes.push_back(MeshInfo(false));
  214. currentMesh = &meshes.back();
  215. currentMesh->shader = s;
  216. }
  217. if (!currentMeshWithNormals)
  218. {
  219. meshesWithNormals.push_back(MeshInfo(true));
  220. currentMeshWithNormals = &meshesWithNormals.back();
  221. currentMeshWithNormals->shader = s;
  222. }
  223. }
  224. // 's' - sphere
  225. else if ('s' == line[0] && IsSpace(line[1]))
  226. {
  227. meshesLocked.push_back(MeshInfo(false,true));
  228. MeshInfo& currentMesh = meshesLocked.back();
  229. currentMesh.shader = s;
  230. sz = &line[1];
  231. AI_NFF_PARSE_SHAPE_INFORMATION();
  232. // we don't need scaling or translation here - we do it in the node's transform
  233. StandardShapes::MakeSphere(iTesselation, currentMesh.vertices);
  234. currentMesh.faces.resize(currentMesh.vertices.size()/3,3);
  235. // generate a name for the mesh
  236. ::sprintf(currentMesh.name,"sphere_%i",sphere++);
  237. }
  238. // 'dod' - dodecahedron
  239. else if (!strncmp(line,"dod",3) && IsSpace(line[3]))
  240. {
  241. meshesLocked.push_back(MeshInfo(false,true));
  242. MeshInfo& currentMesh = meshesLocked.back();
  243. currentMesh.shader = s;
  244. sz = &line[4];
  245. AI_NFF_PARSE_SHAPE_INFORMATION();
  246. // we don't need scaling or translation here - we do it in the node's transform
  247. StandardShapes::MakeDodecahedron(currentMesh.vertices);
  248. currentMesh.faces.resize(currentMesh.vertices.size()/3,3);
  249. // generate a name for the mesh
  250. ::sprintf(currentMesh.name,"dodecahedron_%i",dodecahedron++);
  251. }
  252. // 'oct' - octahedron
  253. else if (!strncmp(line,"oct",3) && IsSpace(line[3]))
  254. {
  255. meshesLocked.push_back(MeshInfo(false,true));
  256. MeshInfo& currentMesh = meshesLocked.back();
  257. currentMesh.shader = s;
  258. sz = &line[4];
  259. AI_NFF_PARSE_SHAPE_INFORMATION();
  260. // we don't need scaling or translation here - we do it in the node's transform
  261. StandardShapes::MakeOctahedron(currentMesh.vertices);
  262. currentMesh.faces.resize(currentMesh.vertices.size()/3,3);
  263. // generate a name for the mesh
  264. ::sprintf(currentMesh.name,"octahedron_%i",octahedron++);
  265. }
  266. // 'tet' - tetrahedron
  267. else if (!strncmp(line,"tet",3) && IsSpace(line[3]))
  268. {
  269. meshesLocked.push_back(MeshInfo(false,true));
  270. MeshInfo& currentMesh = meshesLocked.back();
  271. currentMesh.shader = s;
  272. sz = &line[4];
  273. AI_NFF_PARSE_SHAPE_INFORMATION();
  274. // we don't need scaling or translation here - we do it in the node's transform
  275. StandardShapes::MakeTetrahedron(currentMesh.vertices);
  276. currentMesh.faces.resize(currentMesh.vertices.size()/3,3);
  277. // generate a name for the mesh
  278. ::sprintf(currentMesh.name,"tetrahedron_%i",tetrahedron++);
  279. }
  280. // 'hex' - hexahedron
  281. else if (!strncmp(line,"hex",3) && IsSpace(line[3]))
  282. {
  283. meshesLocked.push_back(MeshInfo(false,true));
  284. MeshInfo& currentMesh = meshesLocked.back();
  285. currentMesh.shader = s;
  286. sz = &line[4];
  287. AI_NFF_PARSE_SHAPE_INFORMATION();
  288. // we don't need scaling or translation here - we do it in the node's transform
  289. StandardShapes::MakeHexahedron(currentMesh.vertices);
  290. currentMesh.faces.resize(currentMesh.vertices.size()/3,3);
  291. // generate a name for the mesh
  292. ::sprintf(currentMesh.name,"hexahedron_%i",hexahedron++);
  293. }
  294. // 'tess' - tesselation
  295. else if (!strncmp(line,"tess",4) && IsSpace(line[4]))
  296. {
  297. sz = &line[5];SkipSpaces(&sz);
  298. iTesselation = strtol10(sz);
  299. }
  300. // 'c' - cone
  301. else if ('c' == line[0] && IsSpace(line[1]))
  302. {
  303. meshesLocked.push_back(MeshInfo(false,true));
  304. MeshInfo& currentMesh = meshes.back();
  305. currentMesh.shader = s;
  306. sz = &line[1];
  307. aiVector3D center1, center2; float radius1, radius2;
  308. AI_NFF_PARSE_TRIPLE(center1);
  309. AI_NFF_PARSE_FLOAT(radius1);
  310. AI_NFF_PARSE_TRIPLE(center2);
  311. AI_NFF_PARSE_FLOAT(radius2);
  312. // compute the center point of the cone/cylinder
  313. center2 = (center2-center1)/2.f;
  314. currentMesh.center = center1+center2;
  315. center1 = -center2;
  316. // generate the cone - it consists of simple triangles
  317. StandardShapes::MakeCone(center1, radius1, center2, radius2, iTesselation, currentMesh.vertices);
  318. currentMesh.faces.resize(currentMesh.vertices.size()/3,3);
  319. // generate a name for the mesh
  320. if (radius1 != radius2)
  321. ::sprintf(currentMesh.name,"cone_%i",cone++);
  322. else ::sprintf(currentMesh.name,"cylinder_%i",cylinder++);
  323. }
  324. // '#' - comment
  325. else if ('#' == line[0])
  326. {
  327. const char* sz;SkipSpaces(&line[1],&sz);
  328. if (!IsLineEnd(*sz))DefaultLogger::get()->info(sz);
  329. }
  330. }
  331. // copy all arrays into one large
  332. meshes.reserve(meshes.size()+meshesLocked.size()+meshesWithNormals.size());
  333. meshes.insert(meshes.end(),meshesLocked.begin(),meshesLocked.end());
  334. meshes.insert(meshes.end(),meshesWithNormals.begin(),meshesWithNormals.end());
  335. // now generate output meshes. first find out how many meshes we'll need
  336. std::vector<MeshInfo>::const_iterator it = meshes.begin(), end = meshes.end();
  337. for (;it != end;++it)
  338. {
  339. if (!(*it).faces.empty())
  340. {
  341. ++pScene->mNumMeshes;
  342. if ((*it).name[0])++numNamed;
  343. }
  344. }
  345. // generate a dummy root node - assign all unnamed elements such
  346. // as polygons and polygon patches to the root node and generate
  347. // sub nodes for named objects such as spheres and cones.
  348. aiNode* const root = new aiNode();
  349. root->mName.Set("<NFF_Root>");
  350. root->mNumChildren = numNamed;
  351. root->mNumMeshes = pScene->mNumMeshes-numNamed;
  352. aiNode** ppcChildren;
  353. unsigned int* pMeshes;
  354. if (root->mNumMeshes)
  355. pMeshes = root->mMeshes = new unsigned int[root->mNumMeshes];
  356. if (root->mNumChildren)
  357. ppcChildren = root->mChildren = new aiNode*[root->mNumChildren];
  358. if (!pScene->mNumMeshes)throw new ImportErrorException("NFF: No meshes loaded");
  359. pScene->mMeshes = new aiMesh*[pScene->mNumMeshes];
  360. pScene->mMaterials = new aiMaterial*[pScene->mNumMaterials = pScene->mNumMeshes];
  361. for (it = meshes.begin(), m = 0; it != end;++it)
  362. {
  363. if ((*it).faces.empty())continue;
  364. const MeshInfo& src = *it;
  365. aiMesh* const mesh = pScene->mMeshes[m] = new aiMesh();
  366. mesh->mNumVertices = (unsigned int)src.vertices.size();
  367. mesh->mNumFaces = (unsigned int)src.faces.size();
  368. // generate sub nodes for named meshes
  369. if (src.name[0])
  370. {
  371. aiNode* const node = *ppcChildren = new aiNode();
  372. node->mParent = root;
  373. node->mNumMeshes = 1;
  374. node->mMeshes = new unsigned int[1];
  375. node->mMeshes[0] = m;
  376. node->mName.Set(src.name);
  377. // setup the transformation matrix of the node
  378. node->mTransformation.a4 = src.center.x;
  379. node->mTransformation.b4 = src.center.y;
  380. node->mTransformation.c4 = src.center.z;
  381. node->mTransformation.a1 = src.radius.x;
  382. node->mTransformation.b2 = src.radius.y;
  383. node->mTransformation.c3 = src.radius.z;
  384. ++ppcChildren;
  385. }
  386. else *pMeshes++ = m;
  387. // copy vertex positions
  388. mesh->mVertices = new aiVector3D[mesh->mNumVertices];
  389. ::memcpy(mesh->mVertices,&src.vertices[0],sizeof(aiVector3D)*mesh->mNumVertices);
  390. if (src.bHasNormals)
  391. {
  392. ai_assert(src.normals.size() == src.vertices.size());
  393. // copy normal vectors
  394. mesh->mNormals = new aiVector3D[mesh->mNumVertices];
  395. ::memcpy(mesh->mNormals,&src.normals[0],sizeof(aiVector3D)*mesh->mNumVertices);
  396. }
  397. // generate faces
  398. unsigned int p = 0;
  399. aiFace* pFace = mesh->mFaces = new aiFace[mesh->mNumFaces];
  400. for (std::vector<unsigned int>::const_iterator it2 = src.faces.begin(),
  401. end2 = src.faces.end();
  402. it2 != end2;++it2,++pFace)
  403. {
  404. pFace->mIndices = new unsigned int [ pFace->mNumIndices = *it2 ];
  405. for (unsigned int o = 0; o < pFace->mNumIndices;++o)
  406. pFace->mIndices[o] = p++;
  407. }
  408. // generate a material for the mesh
  409. MaterialHelper* pcMat = (MaterialHelper*)(pScene->
  410. mMaterials[m] = new MaterialHelper());
  411. mesh->mMaterialIndex = m++;
  412. aiString s;
  413. s.Set(AI_DEFAULT_MATERIAL_NAME);
  414. pcMat->AddProperty(&s, AI_MATKEY_NAME);
  415. pcMat->AddProperty(&src.shader.color,1,AI_MATKEY_COLOR_DIFFUSE);
  416. pcMat->AddProperty(&src.shader.color,1,AI_MATKEY_COLOR_SPECULAR);
  417. }
  418. pScene->mRootNode = root;
  419. }