您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 
 
 

1269 行
37 KiB

  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 STL importer class */
  35. #include "AssimpPCH.h"
  36. #ifndef ASSIMP_BUILD_NO_NFF_IMPORTER
  37. // internal headers
  38. #include "NFFLoader.h"
  39. #include "ParsingUtils.h"
  40. #include "StandardShapes.h"
  41. #include "fast_atof.h"
  42. #include "RemoveComments.h"
  43. using namespace Assimp;
  44. static const aiImporterDesc desc = {
  45. "Neutral File Format Importer",
  46. "",
  47. "",
  48. "",
  49. aiImporterFlags_SupportBinaryFlavour,
  50. 0,
  51. 0,
  52. 0,
  53. 0,
  54. "enff nff"
  55. };
  56. // ------------------------------------------------------------------------------------------------
  57. // Constructor to be privately used by Importer
  58. NFFImporter::NFFImporter()
  59. {}
  60. // ------------------------------------------------------------------------------------------------
  61. // Destructor, private as well
  62. NFFImporter::~NFFImporter()
  63. {}
  64. // ------------------------------------------------------------------------------------------------
  65. // Returns whether the class can handle the format of the given file.
  66. bool NFFImporter::CanRead( const std::string& pFile, IOSystem* /*pIOHandler*/, bool /*checkSig*/) const
  67. {
  68. return SimpleExtensionCheck(pFile,"nff","enff");
  69. }
  70. // ------------------------------------------------------------------------------------------------
  71. // Get the list of all supported file extensions
  72. const aiImporterDesc* NFFImporter::GetInfo () const
  73. {
  74. return &desc;
  75. }
  76. // ------------------------------------------------------------------------------------------------
  77. #define AI_NFF_PARSE_FLOAT(f) \
  78. SkipSpaces(&sz); \
  79. if (!::IsLineEnd(*sz))sz = fast_atoreal_move<float>(sz, (float&)f);
  80. // ------------------------------------------------------------------------------------------------
  81. #define AI_NFF_PARSE_TRIPLE(v) \
  82. AI_NFF_PARSE_FLOAT(v[0]) \
  83. AI_NFF_PARSE_FLOAT(v[1]) \
  84. AI_NFF_PARSE_FLOAT(v[2])
  85. // ------------------------------------------------------------------------------------------------
  86. #define AI_NFF_PARSE_SHAPE_INFORMATION() \
  87. aiVector3D center, radius(1.0f,get_qnan(),get_qnan()); \
  88. AI_NFF_PARSE_TRIPLE(center); \
  89. AI_NFF_PARSE_TRIPLE(radius); \
  90. if (is_qnan(radius.z))radius.z = radius.x; \
  91. if (is_qnan(radius.y))radius.y = radius.x; \
  92. currentMesh.radius = radius; \
  93. currentMesh.center = center;
  94. // ------------------------------------------------------------------------------------------------
  95. #define AI_NFF2_GET_NEXT_TOKEN() \
  96. do \
  97. { \
  98. if (!GetNextLine(buffer,line)) \
  99. {DefaultLogger::get()->warn("NFF2: Unexpected EOF, can't read next token");break;} \
  100. SkipSpaces(line,&sz); \
  101. } \
  102. while(IsLineEnd(*sz))
  103. // ------------------------------------------------------------------------------------------------
  104. // Loads the materail table for the NFF2 file format from an external file
  105. void NFFImporter::LoadNFF2MaterialTable(std::vector<ShadingInfo>& output,
  106. const std::string& path, IOSystem* pIOHandler)
  107. {
  108. boost::scoped_ptr<IOStream> file( pIOHandler->Open( path, "rb"));
  109. // Check whether we can read from the file
  110. if( !file.get()) {
  111. DefaultLogger::get()->error("NFF2: Unable to open material library " + path + ".");
  112. return;
  113. }
  114. // get the size of the file
  115. const unsigned int m = (unsigned int)file->FileSize();
  116. // allocate storage and copy the contents of the file to a memory buffer
  117. // (terminate it with zero)
  118. std::vector<char> mBuffer2(m+1);
  119. TextFileToBuffer(file.get(),mBuffer2);
  120. const char* buffer = &mBuffer2[0];
  121. // First of all: remove all comments from the file
  122. CommentRemover::RemoveLineComments("//",&mBuffer2[0]);
  123. // The file should start with the magic sequence "mat"
  124. if (!TokenMatch(buffer,"mat",3)) {
  125. DefaultLogger::get()->error("NFF2: Not a valid material library " + path + ".");
  126. return;
  127. }
  128. ShadingInfo* curShader = NULL;
  129. // No read the file line per line
  130. char line[4096];
  131. const char* sz;
  132. while (GetNextLine(buffer,line))
  133. {
  134. SkipSpaces(line,&sz);
  135. // 'version' defines the version of the file format
  136. if (TokenMatch(sz,"version",7))
  137. {
  138. DefaultLogger::get()->info("NFF (Sense8) material library file format: " + std::string(sz));
  139. }
  140. // 'matdef' starts a new material in the file
  141. else if (TokenMatch(sz,"matdef",6))
  142. {
  143. // add a new material to the list
  144. output.push_back( ShadingInfo() );
  145. curShader = & output.back();
  146. // parse the name of the material
  147. }
  148. else if (!TokenMatch(sz,"valid",5))
  149. {
  150. // check whether we have an active material at the moment
  151. if (!IsLineEnd(*sz))
  152. {
  153. if (!curShader)
  154. {
  155. DefaultLogger::get()->error(std::string("NFF2 material library: Found element ") +
  156. sz + "but there is no active material");
  157. continue;
  158. }
  159. }
  160. else continue;
  161. // now read the material property and determine its type
  162. aiColor3D c;
  163. if (TokenMatch(sz,"ambient",7))
  164. {
  165. AI_NFF_PARSE_TRIPLE(c);
  166. curShader->ambient = c;
  167. }
  168. else if (TokenMatch(sz,"diffuse",7) || TokenMatch(sz,"ambientdiffuse",14) /* correct? */)
  169. {
  170. AI_NFF_PARSE_TRIPLE(c);
  171. curShader->diffuse = curShader->ambient = c;
  172. }
  173. else if (TokenMatch(sz,"specular",8))
  174. {
  175. AI_NFF_PARSE_TRIPLE(c);
  176. curShader->specular = c;
  177. }
  178. else if (TokenMatch(sz,"emission",8))
  179. {
  180. AI_NFF_PARSE_TRIPLE(c);
  181. curShader->emissive = c;
  182. }
  183. else if (TokenMatch(sz,"shininess",9))
  184. {
  185. AI_NFF_PARSE_FLOAT(curShader->shininess);
  186. }
  187. else if (TokenMatch(sz,"opacity",7))
  188. {
  189. AI_NFF_PARSE_FLOAT(curShader->opacity);
  190. }
  191. }
  192. }
  193. }
  194. // ------------------------------------------------------------------------------------------------
  195. // Imports the given file into the given scene structure.
  196. void NFFImporter::InternReadFile( const std::string& pFile,
  197. aiScene* pScene, IOSystem* pIOHandler)
  198. {
  199. boost::scoped_ptr<IOStream> file( pIOHandler->Open( pFile, "rb"));
  200. // Check whether we can read from the file
  201. if( !file.get())
  202. throw DeadlyImportError( "Failed to open NFF file " + pFile + ".");
  203. unsigned int m = (unsigned int)file->FileSize();
  204. // allocate storage and copy the contents of the file to a memory buffer
  205. // (terminate it with zero)
  206. std::vector<char> mBuffer2;
  207. TextFileToBuffer(file.get(),mBuffer2);
  208. const char* buffer = &mBuffer2[0];
  209. // mesh arrays - separate here to make the handling of the pointers below easier.
  210. std::vector<MeshInfo> meshes;
  211. std::vector<MeshInfo> meshesWithNormals;
  212. std::vector<MeshInfo> meshesWithUVCoords;
  213. std::vector<MeshInfo> meshesLocked;
  214. char line[4096];
  215. const char* sz;
  216. // camera parameters
  217. aiVector3D camPos, camUp(0.f,1.f,0.f), camLookAt(0.f,0.f,1.f);
  218. float angle = 45.f;
  219. aiVector2D resolution;
  220. bool hasCam = false;
  221. MeshInfo* currentMeshWithNormals = NULL;
  222. MeshInfo* currentMesh = NULL;
  223. MeshInfo* currentMeshWithUVCoords = NULL;
  224. ShadingInfo s; // current material info
  225. // degree of tesselation
  226. unsigned int iTesselation = 4;
  227. // some temporary variables we need to parse the file
  228. unsigned int sphere = 0,
  229. cylinder = 0,
  230. cone = 0,
  231. numNamed = 0,
  232. dodecahedron = 0,
  233. octahedron = 0,
  234. tetrahedron = 0,
  235. hexahedron = 0;
  236. // lights imported from the file
  237. std::vector<Light> lights;
  238. // check whether this is the NFF2 file format
  239. if (TokenMatch(buffer,"nff",3))
  240. {
  241. const float qnan = get_qnan();
  242. const aiColor4D cQNAN = aiColor4D (qnan,0.f,0.f,1.f);
  243. const aiVector3D vQNAN = aiVector3D(qnan,0.f,0.f);
  244. // another NFF file format ... just a raw parser has been implemented
  245. // no support for further details, I don't think it is worth the effort
  246. // http://ozviz.wasp.uwa.edu.au/~pbourke/dataformats/nff/nff2.html
  247. // http://www.netghost.narod.ru/gff/graphics/summary/sense8.htm
  248. // First of all: remove all comments from the file
  249. CommentRemover::RemoveLineComments("//",&mBuffer2[0]);
  250. while (GetNextLine(buffer,line))
  251. {
  252. SkipSpaces(line,&sz);
  253. if (TokenMatch(sz,"version",7))
  254. {
  255. DefaultLogger::get()->info("NFF (Sense8) file format: " + std::string(sz));
  256. }
  257. else if (TokenMatch(sz,"viewpos",7))
  258. {
  259. AI_NFF_PARSE_TRIPLE(camPos);
  260. hasCam = true;
  261. }
  262. else if (TokenMatch(sz,"viewdir",7))
  263. {
  264. AI_NFF_PARSE_TRIPLE(camLookAt);
  265. hasCam = true;
  266. }
  267. // This starts a new object section
  268. else if (!IsSpaceOrNewLine(*sz))
  269. {
  270. unsigned int subMeshIdx = 0;
  271. // read the name of the object, skip all spaces
  272. // at the end of it.
  273. const char* sz3 = sz;
  274. while (!IsSpaceOrNewLine(*sz))++sz;
  275. std::string objectName = std::string(sz3,(unsigned int)(sz-sz3));
  276. const unsigned int objStart = (unsigned int)meshes.size();
  277. // There could be a material table in a separate file
  278. std::vector<ShadingInfo> materialTable;
  279. while (true)
  280. {
  281. AI_NFF2_GET_NEXT_TOKEN();
  282. // material table - an external file
  283. if (TokenMatch(sz,"mtable",6))
  284. {
  285. SkipSpaces(&sz);
  286. sz3 = sz;
  287. while (!IsSpaceOrNewLine(*sz))++sz;
  288. const unsigned int diff = (unsigned int)(sz-sz3);
  289. if (!diff)DefaultLogger::get()->warn("NFF2: Found empty mtable token");
  290. else
  291. {
  292. // The material table has the file extension .mat.
  293. // If it is not there, we need to append it
  294. std::string path = std::string(sz3,diff);
  295. if(std::string::npos == path.find_last_of(".mat"))
  296. {
  297. path.append(".mat");
  298. }
  299. // Now extract the working directory from the path to
  300. // this file and append the material library filename
  301. // to it.
  302. std::string::size_type s;
  303. if ((std::string::npos == (s = path.find_last_of('\\')) || !s) &&
  304. (std::string::npos == (s = path.find_last_of('/')) || !s) )
  305. {
  306. s = pFile.find_last_of('\\');
  307. if (std::string::npos == s)s = pFile.find_last_of('/');
  308. if (std::string::npos != s)
  309. {
  310. path = pFile.substr(0,s+1) + path;
  311. }
  312. }
  313. LoadNFF2MaterialTable(materialTable,path,pIOHandler);
  314. }
  315. }
  316. else break;
  317. }
  318. // read the numbr of vertices
  319. unsigned int num = ::strtoul10(sz,&sz);
  320. // temporary storage
  321. std::vector<aiColor4D> tempColors;
  322. std::vector<aiVector3D> tempPositions,tempTextureCoords,tempNormals;
  323. bool hasNormals = false,hasUVs = false,hasColor = false;
  324. tempPositions.reserve (num);
  325. tempColors.reserve (num);
  326. tempNormals.reserve (num);
  327. tempTextureCoords.reserve (num);
  328. for (unsigned int i = 0; i < num; ++i)
  329. {
  330. AI_NFF2_GET_NEXT_TOKEN();
  331. aiVector3D v;
  332. AI_NFF_PARSE_TRIPLE(v);
  333. tempPositions.push_back(v);
  334. // parse all other attributes in the line
  335. while (true)
  336. {
  337. SkipSpaces(&sz);
  338. if (IsLineEnd(*sz))break;
  339. // color definition
  340. if (TokenMatch(sz,"0x",2))
  341. {
  342. hasColor = true;
  343. register unsigned int numIdx = ::strtoul16(sz,&sz);
  344. aiColor4D clr;
  345. clr.a = 1.f;
  346. // 0xRRGGBB
  347. clr.r = ((numIdx >> 16u) & 0xff) / 255.f;
  348. clr.g = ((numIdx >> 8u) & 0xff) / 255.f;
  349. clr.b = ((numIdx) & 0xff) / 255.f;
  350. tempColors.push_back(clr);
  351. }
  352. // normal vector
  353. else if (TokenMatch(sz,"norm",4))
  354. {
  355. hasNormals = true;
  356. AI_NFF_PARSE_TRIPLE(v);
  357. tempNormals.push_back(v);
  358. }
  359. // UV coordinate
  360. else if (TokenMatch(sz,"uv",2))
  361. {
  362. hasUVs = true;
  363. AI_NFF_PARSE_FLOAT(v.x);
  364. AI_NFF_PARSE_FLOAT(v.y);
  365. v.z = 0.f;
  366. tempTextureCoords.push_back(v);
  367. }
  368. }
  369. // fill in dummies for all attributes that have not been set
  370. if (tempNormals.size() != tempPositions.size())
  371. tempNormals.push_back(vQNAN);
  372. if (tempTextureCoords.size() != tempPositions.size())
  373. tempTextureCoords.push_back(vQNAN);
  374. if (tempColors.size() != tempPositions.size())
  375. tempColors.push_back(cQNAN);
  376. }
  377. AI_NFF2_GET_NEXT_TOKEN();
  378. if (!num)throw DeadlyImportError("NFF2: There are zero vertices");
  379. num = ::strtoul10(sz,&sz);
  380. std::vector<unsigned int> tempIdx;
  381. tempIdx.reserve(10);
  382. for (unsigned int i = 0; i < num; ++i)
  383. {
  384. AI_NFF2_GET_NEXT_TOKEN();
  385. SkipSpaces(line,&sz);
  386. unsigned int numIdx = ::strtoul10(sz,&sz);
  387. // read all faces indices
  388. if (numIdx)
  389. {
  390. // mesh.faces.push_back(numIdx);
  391. // tempIdx.erase(tempIdx.begin(),tempIdx.end());
  392. tempIdx.resize(numIdx);
  393. for (unsigned int a = 0; a < numIdx;++a)
  394. {
  395. SkipSpaces(sz,&sz);
  396. m = ::strtoul10(sz,&sz);
  397. if (m >= (unsigned int)tempPositions.size())
  398. {
  399. DefaultLogger::get()->error("NFF2: Vertex index overflow");
  400. m= 0;
  401. }
  402. // mesh.vertices.push_back (tempPositions[idx]);
  403. tempIdx[a] = m;
  404. }
  405. }
  406. // build a temporary shader object for the face.
  407. ShadingInfo shader;
  408. unsigned int matIdx = 0;
  409. // white material color - we have vertex colors
  410. shader.color = aiColor3D(1.f,1.f,1.f);
  411. aiColor4D c = aiColor4D(1.f,1.f,1.f,1.f);
  412. while (true)
  413. {
  414. SkipSpaces(sz,&sz);
  415. if(IsLineEnd(*sz))break;
  416. // per-polygon colors
  417. if (TokenMatch(sz,"0x",2))
  418. {
  419. hasColor = true;
  420. const char* sz2 = sz;
  421. numIdx = ::strtoul16(sz,&sz);
  422. const unsigned int diff = (unsigned int)(sz-sz2);
  423. // 0xRRGGBB
  424. if (diff > 3)
  425. {
  426. c.r = ((numIdx >> 16u) & 0xff) / 255.f;
  427. c.g = ((numIdx >> 8u) & 0xff) / 255.f;
  428. c.b = ((numIdx) & 0xff) / 255.f;
  429. }
  430. // 0xRGB
  431. else
  432. {
  433. c.r = ((numIdx >> 8u) & 0xf) / 16.f;
  434. c.g = ((numIdx >> 4u) & 0xf) / 16.f;
  435. c.b = ((numIdx) & 0xf) / 16.f;
  436. }
  437. }
  438. // TODO - implement texture mapping here
  439. #if 0
  440. // mirror vertex texture coordinate?
  441. else if (TokenMatch(sz,"mirror",6))
  442. {
  443. }
  444. // texture coordinate scaling
  445. else if (TokenMatch(sz,"scale",5))
  446. {
  447. }
  448. // texture coordinate translation
  449. else if (TokenMatch(sz,"trans",5))
  450. {
  451. }
  452. // texture coordinate rotation angle
  453. else if (TokenMatch(sz,"rot",3))
  454. {
  455. }
  456. #endif
  457. // texture file name for this polygon + mapping information
  458. else if ('_' == sz[0])
  459. {
  460. // get mapping information
  461. switch (sz[1])
  462. {
  463. case 'v':
  464. case 'V':
  465. shader.shaded = false;
  466. break;
  467. case 't':
  468. case 'T':
  469. case 'u':
  470. case 'U':
  471. DefaultLogger::get()->warn("Unsupported NFF2 texture attribute: trans");
  472. };
  473. if (!sz[1] || '_' != sz[2])
  474. {
  475. DefaultLogger::get()->warn("NFF2: Expected underscore after texture attributes");
  476. continue;
  477. }
  478. const char* sz2 = sz+3;
  479. while (!IsSpaceOrNewLine( *sz ))++sz;
  480. const unsigned int diff = (unsigned int)(sz-sz2);
  481. if (diff)shader.texFile = std::string(sz2,diff);
  482. }
  483. // Two-sided material?
  484. else if (TokenMatch(sz,"both",4))
  485. {
  486. shader.twoSided = true;
  487. }
  488. // Material ID?
  489. else if (!materialTable.empty() && TokenMatch(sz,"matid",5))
  490. {
  491. SkipSpaces(&sz);
  492. matIdx = ::strtoul10(sz,&sz);
  493. if (matIdx >= materialTable.size())
  494. {
  495. DefaultLogger::get()->error("NFF2: Material index overflow.");
  496. matIdx = 0;
  497. }
  498. // now combine our current shader with the shader we
  499. // read from the material table.
  500. ShadingInfo& mat = materialTable[matIdx];
  501. shader.ambient = mat.ambient;
  502. shader.diffuse = mat.diffuse;
  503. shader.emissive = mat.emissive;
  504. shader.opacity = mat.opacity;
  505. shader.specular = mat.specular;
  506. shader.shininess = mat.shininess;
  507. }
  508. else SkipToken(sz);
  509. }
  510. // search the list of all shaders we have for this object whether
  511. // there is an identical one. In this case, we append our mesh
  512. // data to it.
  513. MeshInfo* mesh = NULL;
  514. for (std::vector<MeshInfo>::iterator it = meshes.begin() + objStart, end = meshes.end();
  515. it != end; ++it)
  516. {
  517. if ((*it).shader == shader && (*it).matIndex == matIdx)
  518. {
  519. // we have one, we can append our data to it
  520. mesh = &(*it);
  521. }
  522. }
  523. if (!mesh)
  524. {
  525. meshes.push_back(MeshInfo(PatchType_Simple,false));
  526. mesh = &meshes.back();
  527. mesh->matIndex = matIdx;
  528. // We need to add a new mesh to the list. We assign
  529. // an unique name to it to make sure the scene will
  530. // pass the validation step for the moment.
  531. // TODO: fix naming of objects in the scenegraph later
  532. if (objectName.length())
  533. {
  534. ::strcpy(mesh->name,objectName.c_str());
  535. ASSIMP_itoa10(&mesh->name[objectName.length()],30,subMeshIdx++);
  536. }
  537. // copy the shader to the mesh.
  538. mesh->shader = shader;
  539. }
  540. // fill the mesh with data
  541. if (!tempIdx.empty())
  542. {
  543. mesh->faces.push_back((unsigned int)tempIdx.size());
  544. for (std::vector<unsigned int>::const_iterator it = tempIdx.begin(), end = tempIdx.end();
  545. it != end;++it)
  546. {
  547. m = *it;
  548. // copy colors -vertex color specifications override polygon color specifications
  549. if (hasColor)
  550. {
  551. const aiColor4D& clr = tempColors[m];
  552. mesh->colors.push_back((is_qnan( clr.r ) ? c : clr));
  553. }
  554. // positions should always be there
  555. mesh->vertices.push_back (tempPositions[m]);
  556. // copy normal vectors
  557. if (hasNormals)
  558. mesh->normals.push_back (tempNormals[m]);
  559. // copy texture coordinates
  560. if (hasUVs)
  561. mesh->uvs.push_back (tempTextureCoords[m]);
  562. }
  563. }
  564. }
  565. if (!num)throw DeadlyImportError("NFF2: There are zero faces");
  566. }
  567. }
  568. camLookAt = camLookAt + camPos;
  569. }
  570. else // "Normal" Neutral file format that is quite more common
  571. {
  572. while (GetNextLine(buffer,line))
  573. {
  574. sz = line;
  575. if ('p' == line[0] || TokenMatch(sz,"tpp",3))
  576. {
  577. MeshInfo* out = NULL;
  578. // 'tpp' - texture polygon patch primitive
  579. if ('t' == line[0])
  580. {
  581. currentMeshWithUVCoords = NULL;
  582. for (std::vector<MeshInfo>::iterator it = meshesWithUVCoords.begin(), end = meshesWithUVCoords.end();
  583. it != end;++it)
  584. {
  585. if ((*it).shader == s)
  586. {
  587. currentMeshWithUVCoords = &(*it);
  588. break;
  589. }
  590. }
  591. if (!currentMeshWithUVCoords)
  592. {
  593. meshesWithUVCoords.push_back(MeshInfo(PatchType_UVAndNormals));
  594. currentMeshWithUVCoords = &meshesWithUVCoords.back();
  595. currentMeshWithUVCoords->shader = s;
  596. }
  597. out = currentMeshWithUVCoords;
  598. }
  599. // 'pp' - polygon patch primitive
  600. else if ('p' == line[1])
  601. {
  602. currentMeshWithNormals = NULL;
  603. for (std::vector<MeshInfo>::iterator it = meshesWithNormals.begin(), end = meshesWithNormals.end();
  604. it != end;++it)
  605. {
  606. if ((*it).shader == s)
  607. {
  608. currentMeshWithNormals = &(*it);
  609. break;
  610. }
  611. }
  612. if (!currentMeshWithNormals)
  613. {
  614. meshesWithNormals.push_back(MeshInfo(PatchType_Normals));
  615. currentMeshWithNormals = &meshesWithNormals.back();
  616. currentMeshWithNormals->shader = s;
  617. }
  618. sz = &line[2];out = currentMeshWithNormals;
  619. }
  620. // 'p' - polygon primitive
  621. else
  622. {
  623. currentMesh = NULL;
  624. for (std::vector<MeshInfo>::iterator it = meshes.begin(), end = meshes.end();
  625. it != end;++it)
  626. {
  627. if ((*it).shader == s)
  628. {
  629. currentMesh = &(*it);
  630. break;
  631. }
  632. }
  633. if (!currentMesh)
  634. {
  635. meshes.push_back(MeshInfo(PatchType_Simple));
  636. currentMesh = &meshes.back();
  637. currentMesh->shader = s;
  638. }
  639. sz = &line[1];out = currentMesh;
  640. }
  641. SkipSpaces(sz,&sz);
  642. m = strtoul10(sz);
  643. // ---- flip the face order
  644. out->vertices.resize(out->vertices.size()+m);
  645. if (out != currentMesh)
  646. {
  647. out->normals.resize(out->vertices.size());
  648. }
  649. if (out == currentMeshWithUVCoords)
  650. {
  651. out->uvs.resize(out->vertices.size());
  652. }
  653. for (unsigned int n = 0; n < m;++n)
  654. {
  655. if(!GetNextLine(buffer,line))
  656. {
  657. DefaultLogger::get()->error("NFF: Unexpected EOF was encountered. Patch definition incomplete");
  658. continue;
  659. }
  660. aiVector3D v; sz = &line[0];
  661. AI_NFF_PARSE_TRIPLE(v);
  662. out->vertices[out->vertices.size()-n-1] = v;
  663. if (out != currentMesh)
  664. {
  665. AI_NFF_PARSE_TRIPLE(v);
  666. out->normals[out->vertices.size()-n-1] = v;
  667. }
  668. if (out == currentMeshWithUVCoords)
  669. {
  670. // FIX: in one test file this wraps over multiple lines
  671. SkipSpaces(&sz);
  672. if (IsLineEnd(*sz))
  673. {
  674. GetNextLine(buffer,line);
  675. sz = line;
  676. }
  677. AI_NFF_PARSE_FLOAT(v.x);
  678. SkipSpaces(&sz);
  679. if (IsLineEnd(*sz))
  680. {
  681. GetNextLine(buffer,line);
  682. sz = line;
  683. }
  684. AI_NFF_PARSE_FLOAT(v.y);
  685. v.y = 1.f - v.y;
  686. out->uvs[out->vertices.size()-n-1] = v;
  687. }
  688. }
  689. out->faces.push_back(m);
  690. }
  691. // 'f' - shading information block
  692. else if (TokenMatch(sz,"f",1))
  693. {
  694. float d;
  695. // read the RGB colors
  696. AI_NFF_PARSE_TRIPLE(s.color);
  697. // read the other properties
  698. AI_NFF_PARSE_FLOAT(s.diffuse.r);
  699. AI_NFF_PARSE_FLOAT(s.specular.r);
  700. AI_NFF_PARSE_FLOAT(d); // skip shininess and transmittance
  701. AI_NFF_PARSE_FLOAT(d);
  702. AI_NFF_PARSE_FLOAT(s.refracti);
  703. // NFF2 uses full colors here so we need to use them too
  704. // although NFF uses simple scaling factors
  705. s.diffuse.g = s.diffuse.b = s.diffuse.r;
  706. s.specular.g = s.specular.b = s.specular.r;
  707. // if the next one is NOT a number we assume it is a texture file name
  708. // this feature is used by some NFF files on the internet and it has
  709. // been implemented as it can be really useful
  710. SkipSpaces(&sz);
  711. if (!IsNumeric(*sz))
  712. {
  713. // TODO: Support full file names with spaces and quotation marks ...
  714. const char* p = sz;
  715. while (!IsSpaceOrNewLine( *sz ))++sz;
  716. unsigned int diff = (unsigned int)(sz-p);
  717. if (diff)
  718. {
  719. s.texFile = std::string(p,diff);
  720. }
  721. }
  722. else
  723. {
  724. AI_NFF_PARSE_FLOAT(s.ambient); // optional
  725. }
  726. }
  727. // 'shader' - other way to specify a texture
  728. else if (TokenMatch(sz,"shader",6))
  729. {
  730. SkipSpaces(&sz);
  731. const char* old = sz;
  732. while (!IsSpaceOrNewLine(*sz))++sz;
  733. s.texFile = std::string(old, (uintptr_t)sz - (uintptr_t)old);
  734. }
  735. // 'l' - light source
  736. else if (TokenMatch(sz,"l",1))
  737. {
  738. lights.push_back(Light());
  739. Light& light = lights.back();
  740. AI_NFF_PARSE_TRIPLE(light.position);
  741. AI_NFF_PARSE_FLOAT (light.intensity);
  742. AI_NFF_PARSE_TRIPLE(light.color);
  743. }
  744. // 's' - sphere
  745. else if (TokenMatch(sz,"s",1))
  746. {
  747. meshesLocked.push_back(MeshInfo(PatchType_Simple,true));
  748. MeshInfo& currentMesh = meshesLocked.back();
  749. currentMesh.shader = s;
  750. currentMesh.shader.mapping = aiTextureMapping_SPHERE;
  751. AI_NFF_PARSE_SHAPE_INFORMATION();
  752. // we don't need scaling or translation here - we do it in the node's transform
  753. StandardShapes::MakeSphere(iTesselation, currentMesh.vertices);
  754. currentMesh.faces.resize(currentMesh.vertices.size()/3,3);
  755. // generate a name for the mesh
  756. ::sprintf(currentMesh.name,"sphere_%i",sphere++);
  757. }
  758. // 'dod' - dodecahedron
  759. else if (TokenMatch(sz,"dod",3))
  760. {
  761. meshesLocked.push_back(MeshInfo(PatchType_Simple,true));
  762. MeshInfo& currentMesh = meshesLocked.back();
  763. currentMesh.shader = s;
  764. currentMesh.shader.mapping = aiTextureMapping_SPHERE;
  765. AI_NFF_PARSE_SHAPE_INFORMATION();
  766. // we don't need scaling or translation here - we do it in the node's transform
  767. StandardShapes::MakeDodecahedron(currentMesh.vertices);
  768. currentMesh.faces.resize(currentMesh.vertices.size()/3,3);
  769. // generate a name for the mesh
  770. ::sprintf(currentMesh.name,"dodecahedron_%i",dodecahedron++);
  771. }
  772. // 'oct' - octahedron
  773. else if (TokenMatch(sz,"oct",3))
  774. {
  775. meshesLocked.push_back(MeshInfo(PatchType_Simple,true));
  776. MeshInfo& currentMesh = meshesLocked.back();
  777. currentMesh.shader = s;
  778. currentMesh.shader.mapping = aiTextureMapping_SPHERE;
  779. AI_NFF_PARSE_SHAPE_INFORMATION();
  780. // we don't need scaling or translation here - we do it in the node's transform
  781. StandardShapes::MakeOctahedron(currentMesh.vertices);
  782. currentMesh.faces.resize(currentMesh.vertices.size()/3,3);
  783. // generate a name for the mesh
  784. ::sprintf(currentMesh.name,"octahedron_%i",octahedron++);
  785. }
  786. // 'tet' - tetrahedron
  787. else if (TokenMatch(sz,"tet",3))
  788. {
  789. meshesLocked.push_back(MeshInfo(PatchType_Simple,true));
  790. MeshInfo& currentMesh = meshesLocked.back();
  791. currentMesh.shader = s;
  792. currentMesh.shader.mapping = aiTextureMapping_SPHERE;
  793. AI_NFF_PARSE_SHAPE_INFORMATION();
  794. // we don't need scaling or translation here - we do it in the node's transform
  795. StandardShapes::MakeTetrahedron(currentMesh.vertices);
  796. currentMesh.faces.resize(currentMesh.vertices.size()/3,3);
  797. // generate a name for the mesh
  798. ::sprintf(currentMesh.name,"tetrahedron_%i",tetrahedron++);
  799. }
  800. // 'hex' - hexahedron
  801. else if (TokenMatch(sz,"hex",3))
  802. {
  803. meshesLocked.push_back(MeshInfo(PatchType_Simple,true));
  804. MeshInfo& currentMesh = meshesLocked.back();
  805. currentMesh.shader = s;
  806. currentMesh.shader.mapping = aiTextureMapping_BOX;
  807. AI_NFF_PARSE_SHAPE_INFORMATION();
  808. // we don't need scaling or translation here - we do it in the node's transform
  809. StandardShapes::MakeHexahedron(currentMesh.vertices);
  810. currentMesh.faces.resize(currentMesh.vertices.size()/3,3);
  811. // generate a name for the mesh
  812. ::sprintf(currentMesh.name,"hexahedron_%i",hexahedron++);
  813. }
  814. // 'c' - cone
  815. else if (TokenMatch(sz,"c",1))
  816. {
  817. meshesLocked.push_back(MeshInfo(PatchType_Simple,true));
  818. MeshInfo& currentMesh = meshesLocked.back();
  819. currentMesh.shader = s;
  820. currentMesh.shader.mapping = aiTextureMapping_CYLINDER;
  821. if(!GetNextLine(buffer,line))
  822. {
  823. DefaultLogger::get()->error("NFF: Unexpected end of file (cone definition not complete)");
  824. break;
  825. }
  826. sz = line;
  827. // read the two center points and the respective radii
  828. aiVector3D center1, center2; float radius1, radius2;
  829. AI_NFF_PARSE_TRIPLE(center1);
  830. AI_NFF_PARSE_FLOAT(radius1);
  831. if(!GetNextLine(buffer,line))
  832. {
  833. DefaultLogger::get()->error("NFF: Unexpected end of file (cone definition not complete)");
  834. break;
  835. }
  836. sz = line;
  837. AI_NFF_PARSE_TRIPLE(center2);
  838. AI_NFF_PARSE_FLOAT(radius2);
  839. // compute the center point of the cone/cylinder -
  840. // it is its local transformation origin
  841. currentMesh.dir = center2-center1;
  842. currentMesh.center = center1+currentMesh.dir/2.f;
  843. float f;
  844. if (( f = currentMesh.dir.Length()) < 10e-3f )
  845. {
  846. DefaultLogger::get()->error("NFF: Cone height is close to zero");
  847. continue;
  848. }
  849. currentMesh.dir /= f; // normalize
  850. // generate the cone - it consists of simple triangles
  851. StandardShapes::MakeCone(f, radius1, radius2,
  852. integer_pow(4, iTesselation), currentMesh.vertices);
  853. // MakeCone() returns tris
  854. currentMesh.faces.resize(currentMesh.vertices.size()/3,3);
  855. // generate a name for the mesh. 'cone' if it a cone,
  856. // 'cylinder' if it is a cylinder. Funny, isn't it?
  857. if (radius1 != radius2)
  858. ::sprintf(currentMesh.name,"cone_%i",cone++);
  859. else ::sprintf(currentMesh.name,"cylinder_%i",cylinder++);
  860. }
  861. // 'tess' - tesselation
  862. else if (TokenMatch(sz,"tess",4))
  863. {
  864. SkipSpaces(&sz);
  865. iTesselation = strtoul10(sz);
  866. }
  867. // 'from' - camera position
  868. else if (TokenMatch(sz,"from",4))
  869. {
  870. AI_NFF_PARSE_TRIPLE(camPos);
  871. hasCam = true;
  872. }
  873. // 'at' - camera look-at vector
  874. else if (TokenMatch(sz,"at",2))
  875. {
  876. AI_NFF_PARSE_TRIPLE(camLookAt);
  877. hasCam = true;
  878. }
  879. // 'up' - camera up vector
  880. else if (TokenMatch(sz,"up",2))
  881. {
  882. AI_NFF_PARSE_TRIPLE(camUp);
  883. hasCam = true;
  884. }
  885. // 'angle' - (half?) camera field of view
  886. else if (TokenMatch(sz,"angle",5))
  887. {
  888. AI_NFF_PARSE_FLOAT(angle);
  889. hasCam = true;
  890. }
  891. // 'resolution' - used to compute the screen aspect
  892. else if (TokenMatch(sz,"resolution",10))
  893. {
  894. AI_NFF_PARSE_FLOAT(resolution.x);
  895. AI_NFF_PARSE_FLOAT(resolution.y);
  896. hasCam = true;
  897. }
  898. // 'pb' - bezier patch. Not supported yet
  899. else if (TokenMatch(sz,"pb",2))
  900. {
  901. DefaultLogger::get()->error("NFF: Encountered unsupported ID: bezier patch");
  902. }
  903. // 'pn' - NURBS. Not supported yet
  904. else if (TokenMatch(sz,"pn",2) || TokenMatch(sz,"pnn",3))
  905. {
  906. DefaultLogger::get()->error("NFF: Encountered unsupported ID: NURBS");
  907. }
  908. // '' - comment
  909. else if ('#' == line[0])
  910. {
  911. const char* sz;SkipSpaces(&line[1],&sz);
  912. if (!IsLineEnd(*sz))DefaultLogger::get()->info(sz);
  913. }
  914. }
  915. }
  916. // copy all arrays into one large
  917. meshes.reserve (meshes.size()+meshesLocked.size()+meshesWithNormals.size()+meshesWithUVCoords.size());
  918. meshes.insert (meshes.end(),meshesLocked.begin(),meshesLocked.end());
  919. meshes.insert (meshes.end(),meshesWithNormals.begin(),meshesWithNormals.end());
  920. meshes.insert (meshes.end(),meshesWithUVCoords.begin(),meshesWithUVCoords.end());
  921. // now generate output meshes. first find out how many meshes we'll need
  922. std::vector<MeshInfo>::const_iterator it = meshes.begin(), end = meshes.end();
  923. for (;it != end;++it)
  924. {
  925. if (!(*it).faces.empty())
  926. {
  927. ++pScene->mNumMeshes;
  928. if ((*it).name[0])++numNamed;
  929. }
  930. }
  931. // generate a dummy root node - assign all unnamed elements such
  932. // as polygons and polygon patches to the root node and generate
  933. // sub nodes for named objects such as spheres and cones.
  934. aiNode* const root = new aiNode();
  935. root->mName.Set("<NFF_Root>");
  936. root->mNumChildren = numNamed + (hasCam ? 1 : 0) + (unsigned int) lights.size();
  937. root->mNumMeshes = pScene->mNumMeshes-numNamed;
  938. aiNode** ppcChildren = NULL;
  939. unsigned int* pMeshes = NULL;
  940. if (root->mNumMeshes)
  941. pMeshes = root->mMeshes = new unsigned int[root->mNumMeshes];
  942. if (root->mNumChildren)
  943. ppcChildren = root->mChildren = new aiNode*[root->mNumChildren];
  944. // generate the camera
  945. if (hasCam)
  946. {
  947. aiNode* nd = *ppcChildren = new aiNode();
  948. nd->mName.Set("<NFF_Camera>");
  949. nd->mParent = root;
  950. // allocate the camera in the scene
  951. pScene->mNumCameras = 1;
  952. pScene->mCameras = new aiCamera*[1];
  953. aiCamera* c = pScene->mCameras[0] = new aiCamera;
  954. c->mName = nd->mName; // make sure the names are identical
  955. c->mHorizontalFOV = AI_DEG_TO_RAD( angle );
  956. c->mLookAt = camLookAt - camPos;
  957. c->mPosition = camPos;
  958. c->mUp = camUp;
  959. // If the resolution is not specified in the file, we
  960. // need to set 1.0 as aspect.
  961. c->mAspect = (!resolution.y ? 0.f : resolution.x / resolution.y);
  962. ++ppcChildren;
  963. }
  964. // generate light sources
  965. if (!lights.empty())
  966. {
  967. pScene->mNumLights = (unsigned int)lights.size();
  968. pScene->mLights = new aiLight*[pScene->mNumLights];
  969. for (unsigned int i = 0; i < pScene->mNumLights;++i,++ppcChildren)
  970. {
  971. const Light& l = lights[i];
  972. aiNode* nd = *ppcChildren = new aiNode();
  973. nd->mParent = root;
  974. nd->mName.length = ::sprintf(nd->mName.data,"<NFF_Light%i>",i);
  975. // allocate the light in the scene data structure
  976. aiLight* out = pScene->mLights[i] = new aiLight();
  977. out->mName = nd->mName; // make sure the names are identical
  978. out->mType = aiLightSource_POINT;
  979. out->mColorDiffuse = out->mColorSpecular = l.color * l.intensity;
  980. out->mPosition = l.position;
  981. }
  982. }
  983. if (!pScene->mNumMeshes)throw DeadlyImportError("NFF: No meshes loaded");
  984. pScene->mMeshes = new aiMesh*[pScene->mNumMeshes];
  985. pScene->mMaterials = new aiMaterial*[pScene->mNumMaterials = pScene->mNumMeshes];
  986. for (it = meshes.begin(), m = 0; it != end;++it)
  987. {
  988. if ((*it).faces.empty())continue;
  989. const MeshInfo& src = *it;
  990. aiMesh* const mesh = pScene->mMeshes[m] = new aiMesh();
  991. mesh->mNumVertices = (unsigned int)src.vertices.size();
  992. mesh->mNumFaces = (unsigned int)src.faces.size();
  993. // Generate sub nodes for named meshes
  994. if (src.name[0])
  995. {
  996. aiNode* const node = *ppcChildren = new aiNode();
  997. node->mParent = root;
  998. node->mNumMeshes = 1;
  999. node->mMeshes = new unsigned int[1];
  1000. node->mMeshes[0] = m;
  1001. node->mName.Set(src.name);
  1002. // setup the transformation matrix of the node
  1003. aiMatrix4x4::FromToMatrix(aiVector3D(0.f,1.f,0.f),
  1004. src.dir,node->mTransformation);
  1005. aiMatrix4x4& mat = node->mTransformation;
  1006. mat.a1 *= src.radius.x; mat.b1 *= src.radius.x; mat.c1 *= src.radius.x;
  1007. mat.a2 *= src.radius.y; mat.b2 *= src.radius.y; mat.c2 *= src.radius.y;
  1008. mat.a3 *= src.radius.z; mat.b3 *= src.radius.z; mat.c3 *= src.radius.z;
  1009. mat.a4 = src.center.x;
  1010. mat.b4 = src.center.y;
  1011. mat.c4 = src.center.z;
  1012. ++ppcChildren;
  1013. }
  1014. else *pMeshes++ = m;
  1015. // copy vertex positions
  1016. mesh->mVertices = new aiVector3D[mesh->mNumVertices];
  1017. ::memcpy(mesh->mVertices,&src.vertices[0],
  1018. sizeof(aiVector3D)*mesh->mNumVertices);
  1019. // NFF2: there could be vertex colors
  1020. if (!src.colors.empty())
  1021. {
  1022. ai_assert(src.colors.size() == src.vertices.size());
  1023. // copy vertex colors
  1024. mesh->mColors[0] = new aiColor4D[mesh->mNumVertices];
  1025. ::memcpy(mesh->mColors[0],&src.colors[0],
  1026. sizeof(aiColor4D)*mesh->mNumVertices);
  1027. }
  1028. if (!src.normals.empty())
  1029. {
  1030. ai_assert(src.normals.size() == src.vertices.size());
  1031. // copy normal vectors
  1032. mesh->mNormals = new aiVector3D[mesh->mNumVertices];
  1033. ::memcpy(mesh->mNormals,&src.normals[0],
  1034. sizeof(aiVector3D)*mesh->mNumVertices);
  1035. }
  1036. if (!src.uvs.empty())
  1037. {
  1038. ai_assert(src.uvs.size() == src.vertices.size());
  1039. // copy texture coordinates
  1040. mesh->mTextureCoords[0] = new aiVector3D[mesh->mNumVertices];
  1041. ::memcpy(mesh->mTextureCoords[0],&src.uvs[0],
  1042. sizeof(aiVector3D)*mesh->mNumVertices);
  1043. }
  1044. // generate faces
  1045. unsigned int p = 0;
  1046. aiFace* pFace = mesh->mFaces = new aiFace[mesh->mNumFaces];
  1047. for (std::vector<unsigned int>::const_iterator it2 = src.faces.begin(),
  1048. end2 = src.faces.end();
  1049. it2 != end2;++it2,++pFace)
  1050. {
  1051. pFace->mIndices = new unsigned int [ pFace->mNumIndices = *it2 ];
  1052. for (unsigned int o = 0; o < pFace->mNumIndices;++o)
  1053. pFace->mIndices[o] = p++;
  1054. }
  1055. // generate a material for the mesh
  1056. aiMaterial* pcMat = (aiMaterial*)(pScene->mMaterials[m] = new aiMaterial());
  1057. mesh->mMaterialIndex = m++;
  1058. aiString s;
  1059. s.Set(AI_DEFAULT_MATERIAL_NAME);
  1060. pcMat->AddProperty(&s, AI_MATKEY_NAME);
  1061. // FIX: Ignore diffuse == 0
  1062. aiColor3D c = src.shader.color * (src.shader.diffuse.r ? src.shader.diffuse : aiColor3D(1.f,1.f,1.f));
  1063. pcMat->AddProperty(&c,1,AI_MATKEY_COLOR_DIFFUSE);
  1064. c = src.shader.color * src.shader.specular;
  1065. pcMat->AddProperty(&c,1,AI_MATKEY_COLOR_SPECULAR);
  1066. // NFF2 - default values for NFF
  1067. pcMat->AddProperty(&src.shader.ambient, 1,AI_MATKEY_COLOR_AMBIENT);
  1068. pcMat->AddProperty(&src.shader.emissive,1,AI_MATKEY_COLOR_EMISSIVE);
  1069. pcMat->AddProperty(&src.shader.opacity, 1,AI_MATKEY_OPACITY);
  1070. // setup the first texture layer, if existing
  1071. if (src.shader.texFile.length())
  1072. {
  1073. s.Set(src.shader.texFile);
  1074. pcMat->AddProperty(&s,AI_MATKEY_TEXTURE_DIFFUSE(0));
  1075. if (aiTextureMapping_UV != src.shader.mapping) {
  1076. aiVector3D v(0.f,-1.f,0.f);
  1077. pcMat->AddProperty(&v, 1,AI_MATKEY_TEXMAP_AXIS_DIFFUSE(0));
  1078. pcMat->AddProperty((int*)&src.shader.mapping, 1,AI_MATKEY_MAPPING_DIFFUSE(0));
  1079. }
  1080. }
  1081. // setup the name of the material
  1082. if (src.shader.name.length())
  1083. {
  1084. s.Set(src.shader.texFile);
  1085. pcMat->AddProperty(&s,AI_MATKEY_NAME);
  1086. }
  1087. // setup some more material properties that are specific to NFF2
  1088. int i;
  1089. if (src.shader.twoSided)
  1090. {
  1091. i = 1;
  1092. pcMat->AddProperty(&i,1,AI_MATKEY_TWOSIDED);
  1093. }
  1094. i = (src.shader.shaded ? aiShadingMode_Gouraud : aiShadingMode_NoShading);
  1095. if (src.shader.shininess)
  1096. {
  1097. i = aiShadingMode_Phong;
  1098. pcMat->AddProperty(&src.shader.shininess,1,AI_MATKEY_SHININESS);
  1099. }
  1100. pcMat->AddProperty(&i,1,AI_MATKEY_SHADING_MODEL);
  1101. }
  1102. pScene->mRootNode = root;
  1103. }
  1104. #endif // !! ASSIMP_BUILD_NO_NFF_IMPORTER