Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 
 
 

453 rindas
13 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_STL_IMPORTER
  37. // internal headers
  38. #include "STLLoader.h"
  39. #include "ParsingUtils.h"
  40. #include "fast_atof.h"
  41. using namespace Assimp;
  42. namespace {
  43. static const aiImporterDesc desc = {
  44. "Stereolithography (STL) Importer",
  45. "",
  46. "",
  47. "",
  48. aiImporterFlags_SupportTextFlavour | aiImporterFlags_SupportBinaryFlavour,
  49. 0,
  50. 0,
  51. 0,
  52. 0,
  53. "stl"
  54. };
  55. // A valid binary STL buffer should consist of the following elements, in order:
  56. // 1) 80 byte header
  57. // 2) 4 byte face count
  58. // 3) 50 bytes per face
  59. bool IsBinarySTL(const char* buffer, unsigned int fileSize) {
  60. if (fileSize < 84)
  61. return false;
  62. const uint32_t faceCount = *reinterpret_cast<const uint32_t*>(buffer + 80);
  63. const uint32_t expectedBinaryFileSize = faceCount * 50 + 84;
  64. return expectedBinaryFileSize == fileSize;
  65. }
  66. // An ascii STL buffer will begin with "solid NAME", where NAME is optional.
  67. // Note: The "solid NAME" check is necessary, but not sufficient, to determine
  68. // if the buffer is ASCII; a binary header could also begin with "solid NAME".
  69. bool IsAsciiSTL(const char* buffer, unsigned int fileSize) {
  70. if (IsBinarySTL(buffer, fileSize))
  71. return false;
  72. const char* bufferEnd = buffer + fileSize;
  73. if (!SkipSpaces(&buffer))
  74. return false;
  75. if (buffer + 5 >= bufferEnd)
  76. return false;
  77. return strncmp(buffer, "solid", 5) == 0;
  78. }
  79. } // namespace
  80. // ------------------------------------------------------------------------------------------------
  81. // Constructor to be privately used by Importer
  82. STLImporter::STLImporter()
  83. {}
  84. // ------------------------------------------------------------------------------------------------
  85. // Destructor, private as well
  86. STLImporter::~STLImporter()
  87. {}
  88. // ------------------------------------------------------------------------------------------------
  89. // Returns whether the class can handle the format of the given file.
  90. bool STLImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler, bool checkSig) const
  91. {
  92. const std::string extension = GetExtension(pFile);
  93. if (extension == "stl")
  94. return true;
  95. else if (!extension.length() || checkSig) {
  96. if (!pIOHandler)
  97. return true;
  98. const char* tokens[] = {"STL","solid"};
  99. return SearchFileHeaderForToken(pIOHandler,pFile,tokens,2);
  100. }
  101. return false;
  102. }
  103. // ------------------------------------------------------------------------------------------------
  104. const aiImporterDesc* STLImporter::GetInfo () const
  105. {
  106. return &desc;
  107. }
  108. // ------------------------------------------------------------------------------------------------
  109. // Imports the given file into the given scene structure.
  110. void STLImporter::InternReadFile( const std::string& pFile,
  111. aiScene* pScene, IOSystem* pIOHandler)
  112. {
  113. boost::scoped_ptr<IOStream> file( pIOHandler->Open( pFile, "rb"));
  114. // Check whether we can read from the file
  115. if( file.get() == NULL) {
  116. throw DeadlyImportError( "Failed to open STL file " + pFile + ".");
  117. }
  118. fileSize = (unsigned int)file->FileSize();
  119. // allocate storage and copy the contents of the file to a memory buffer
  120. // (terminate it with zero)
  121. std::vector<char> mBuffer2;
  122. TextFileToBuffer(file.get(),mBuffer2);
  123. this->pScene = pScene;
  124. this->mBuffer = &mBuffer2[0];
  125. // the default vertex color is light gray.
  126. clrColorDefault.r = clrColorDefault.g = clrColorDefault.b = clrColorDefault.a = 0.6f;
  127. // allocate one mesh
  128. pScene->mNumMeshes = 1;
  129. pScene->mMeshes = new aiMesh*[1];
  130. aiMesh* pMesh = pScene->mMeshes[0] = new aiMesh();
  131. pMesh->mMaterialIndex = 0;
  132. // allocate a single node
  133. pScene->mRootNode = new aiNode();
  134. pScene->mRootNode->mNumMeshes = 1;
  135. pScene->mRootNode->mMeshes = new unsigned int[1];
  136. pScene->mRootNode->mMeshes[0] = 0;
  137. bool bMatClr = false;
  138. if (IsBinarySTL(mBuffer, fileSize)) {
  139. bMatClr = LoadBinaryFile();
  140. } else if (IsAsciiSTL(mBuffer, fileSize)) {
  141. LoadASCIIFile();
  142. } else {
  143. throw DeadlyImportError( "Failed to determine STL storage representation for " + pFile + ".");
  144. }
  145. // now copy faces
  146. pMesh->mFaces = new aiFace[pMesh->mNumFaces];
  147. for (unsigned int i = 0, p = 0; i < pMesh->mNumFaces;++i) {
  148. aiFace& face = pMesh->mFaces[i];
  149. face.mIndices = new unsigned int[face.mNumIndices = 3];
  150. for (unsigned int o = 0; o < 3;++o,++p) {
  151. face.mIndices[o] = p;
  152. }
  153. }
  154. // create a single default material, using a light gray diffuse color for consistency with
  155. // other geometric types (e.g., PLY).
  156. aiMaterial* pcMat = new aiMaterial();
  157. aiString s;
  158. s.Set(AI_DEFAULT_MATERIAL_NAME);
  159. pcMat->AddProperty(&s, AI_MATKEY_NAME);
  160. aiColor4D clrDiffuse(0.6f,0.6f,0.6f,1.0f);
  161. if (bMatClr) {
  162. clrDiffuse = clrColorDefault;
  163. }
  164. pcMat->AddProperty(&clrDiffuse,1,AI_MATKEY_COLOR_DIFFUSE);
  165. pcMat->AddProperty(&clrDiffuse,1,AI_MATKEY_COLOR_SPECULAR);
  166. clrDiffuse = aiColor4D(0.05f,0.05f,0.05f,1.0f);
  167. pcMat->AddProperty(&clrDiffuse,1,AI_MATKEY_COLOR_AMBIENT);
  168. pScene->mNumMaterials = 1;
  169. pScene->mMaterials = new aiMaterial*[1];
  170. pScene->mMaterials[0] = pcMat;
  171. }
  172. // ------------------------------------------------------------------------------------------------
  173. // Read an ASCII STL file
  174. void STLImporter::LoadASCIIFile()
  175. {
  176. aiMesh* pMesh = pScene->mMeshes[0];
  177. const char* sz = mBuffer;
  178. SkipSpaces(&sz);
  179. ai_assert(!IsLineEnd(sz));
  180. sz += 5; // skip the "solid"
  181. SkipSpaces(&sz);
  182. const char* szMe = sz;
  183. while (!::IsSpaceOrNewLine(*sz)) {
  184. sz++;
  185. }
  186. size_t temp;
  187. // setup the name of the node
  188. if ((temp = (size_t)(sz-szMe))) {
  189. pScene->mRootNode->mName.length = temp;
  190. memcpy(pScene->mRootNode->mName.data,szMe,temp);
  191. pScene->mRootNode->mName.data[temp] = '\0';
  192. }
  193. else pScene->mRootNode->mName.Set("<STL_ASCII>");
  194. // try to guess how many vertices we could have
  195. // assume we'll need 160 bytes for each face
  196. pMesh->mNumVertices = ( pMesh->mNumFaces = std::max(1u,fileSize / 160u )) * 3;
  197. pMesh->mVertices = new aiVector3D[pMesh->mNumVertices];
  198. pMesh->mNormals = new aiVector3D[pMesh->mNumVertices];
  199. unsigned int curFace = 0, curVertex = 3;
  200. for ( ;; )
  201. {
  202. // go to the next token
  203. if(!SkipSpacesAndLineEnd(&sz))
  204. {
  205. // seems we're finished although there was no end marker
  206. DefaultLogger::get()->warn("STL: unexpected EOF. \'endsolid\' keyword was expected");
  207. break;
  208. }
  209. // facet normal -0.13 -0.13 -0.98
  210. if (!strncmp(sz,"facet",5) && IsSpaceOrNewLine(*(sz+5))) {
  211. if (3 != curVertex) {
  212. DefaultLogger::get()->warn("STL: A new facet begins but the old is not yet complete");
  213. }
  214. if (pMesh->mNumFaces == curFace) {
  215. ai_assert(pMesh->mNumFaces != 0);
  216. // need to resize the arrays, our size estimate was wrong
  217. unsigned int iNeededSize = (unsigned int)(sz-mBuffer) / pMesh->mNumFaces;
  218. if (iNeededSize <= 160)iNeededSize >>= 1; // prevent endless looping
  219. unsigned int add = (unsigned int)((mBuffer+fileSize)-sz) / iNeededSize;
  220. add += add >> 3; // add 12.5% as buffer
  221. iNeededSize = (pMesh->mNumFaces + add)*3;
  222. aiVector3D* pv = new aiVector3D[iNeededSize];
  223. memcpy(pv,pMesh->mVertices,pMesh->mNumVertices*sizeof(aiVector3D));
  224. delete[] pMesh->mVertices;
  225. pMesh->mVertices = pv;
  226. pv = new aiVector3D[iNeededSize];
  227. memcpy(pv,pMesh->mNormals,pMesh->mNumVertices*sizeof(aiVector3D));
  228. delete[] pMesh->mNormals;
  229. pMesh->mNormals = pv;
  230. pMesh->mNumVertices = iNeededSize;
  231. pMesh->mNumFaces += add;
  232. }
  233. aiVector3D* vn = &pMesh->mNormals[curFace++*3];
  234. sz += 6;
  235. curVertex = 0;
  236. SkipSpaces(&sz);
  237. if (strncmp(sz,"normal",6)) {
  238. DefaultLogger::get()->warn("STL: a facet normal vector was expected but not found");
  239. }
  240. else
  241. {
  242. sz += 7;
  243. SkipSpaces(&sz);
  244. sz = fast_atoreal_move<float>(sz, (float&)vn->x );
  245. SkipSpaces(&sz);
  246. sz = fast_atoreal_move<float>(sz, (float&)vn->y );
  247. SkipSpaces(&sz);
  248. sz = fast_atoreal_move<float>(sz, (float&)vn->z );
  249. *(vn+1) = *vn;
  250. *(vn+2) = *vn;
  251. }
  252. }
  253. // vertex 1.50000 1.50000 0.00000
  254. else if (!strncmp(sz,"vertex",6) && ::IsSpaceOrNewLine(*(sz+6)))
  255. {
  256. if (3 == curVertex) {
  257. DefaultLogger::get()->error("STL: a facet with more than 3 vertices has been found");
  258. }
  259. else
  260. {
  261. sz += 7;
  262. SkipSpaces(&sz);
  263. aiVector3D* vn = &pMesh->mVertices[(curFace-1)*3 + curVertex++];
  264. sz = fast_atoreal_move<float>(sz, (float&)vn->x );
  265. SkipSpaces(&sz);
  266. sz = fast_atoreal_move<float>(sz, (float&)vn->y );
  267. SkipSpaces(&sz);
  268. sz = fast_atoreal_move<float>(sz, (float&)vn->z );
  269. }
  270. }
  271. else if (!::strncmp(sz,"endsolid",8)) {
  272. // finished!
  273. break;
  274. }
  275. // else skip the whole identifier
  276. else while (!::IsSpaceOrNewLine(*sz)) {
  277. ++sz;
  278. }
  279. }
  280. if (!curFace) {
  281. pMesh->mNumFaces = 0;
  282. throw DeadlyImportError("STL: ASCII file is empty or invalid; no data loaded");
  283. }
  284. pMesh->mNumFaces = curFace;
  285. pMesh->mNumVertices = curFace*3;
  286. // we are finished!
  287. }
  288. // ------------------------------------------------------------------------------------------------
  289. // Read a binary STL file
  290. bool STLImporter::LoadBinaryFile()
  291. {
  292. // skip the first 80 bytes
  293. if (fileSize < 84) {
  294. throw DeadlyImportError("STL: file is too small for the header");
  295. }
  296. bool bIsMaterialise = false;
  297. // search for an occurence of "COLOR=" in the header
  298. const char* sz2 = (const char*)mBuffer;
  299. const char* const szEnd = sz2+80;
  300. while (sz2 < szEnd) {
  301. if ('C' == *sz2++ && 'O' == *sz2++ && 'L' == *sz2++ &&
  302. 'O' == *sz2++ && 'R' == *sz2++ && '=' == *sz2++) {
  303. // read the default vertex color for facets
  304. bIsMaterialise = true;
  305. DefaultLogger::get()->info("STL: Taking code path for Materialise files");
  306. clrColorDefault.r = (*sz2++) / 255.0f;
  307. clrColorDefault.g = (*sz2++) / 255.0f;
  308. clrColorDefault.b = (*sz2++) / 255.0f;
  309. clrColorDefault.a = (*sz2++) / 255.0f;
  310. break;
  311. }
  312. }
  313. const unsigned char* sz = (const unsigned char*)mBuffer + 80;
  314. // now read the number of facets
  315. aiMesh* pMesh = pScene->mMeshes[0];
  316. pScene->mRootNode->mName.Set("<STL_BINARY>");
  317. pMesh->mNumFaces = *((uint32_t*)sz);
  318. sz += 4;
  319. if (fileSize < 84 + pMesh->mNumFaces*50) {
  320. throw DeadlyImportError("STL: file is too small to hold all facets");
  321. }
  322. if (!pMesh->mNumFaces) {
  323. throw DeadlyImportError("STL: file is empty. There are no facets defined");
  324. }
  325. pMesh->mNumVertices = pMesh->mNumFaces*3;
  326. aiVector3D* vp,*vn;
  327. vp = pMesh->mVertices = new aiVector3D[pMesh->mNumVertices];
  328. vn = pMesh->mNormals = new aiVector3D[pMesh->mNumVertices];
  329. for (unsigned int i = 0; i < pMesh->mNumFaces;++i) {
  330. // NOTE: Blender sometimes writes empty normals ... this is not
  331. // our fault ... the RemoveInvalidData helper step should fix that
  332. *vn = *((aiVector3D*)sz);
  333. sz += sizeof(aiVector3D);
  334. *(vn+1) = *vn;
  335. *(vn+2) = *vn;
  336. vn += 3;
  337. *vp++ = *((aiVector3D*)sz);
  338. sz += sizeof(aiVector3D);
  339. *vp++ = *((aiVector3D*)sz);
  340. sz += sizeof(aiVector3D);
  341. *vp++ = *((aiVector3D*)sz);
  342. sz += sizeof(aiVector3D);
  343. uint16_t color = *((uint16_t*)sz);
  344. sz += 2;
  345. if (color & (1 << 15))
  346. {
  347. // seems we need to take the color
  348. if (!pMesh->mColors[0])
  349. {
  350. pMesh->mColors[0] = new aiColor4D[pMesh->mNumVertices];
  351. for (unsigned int i = 0; i <pMesh->mNumVertices;++i)
  352. *pMesh->mColors[0]++ = this->clrColorDefault;
  353. pMesh->mColors[0] -= pMesh->mNumVertices;
  354. DefaultLogger::get()->info("STL: Mesh has vertex colors");
  355. }
  356. aiColor4D* clr = &pMesh->mColors[0][i*3];
  357. clr->a = 1.0f;
  358. if (bIsMaterialise) // this is reversed
  359. {
  360. clr->r = (color & 0x31u) / 31.0f;
  361. clr->g = ((color & (0x31u<<5))>>5u) / 31.0f;
  362. clr->b = ((color & (0x31u<<10))>>10u) / 31.0f;
  363. }
  364. else
  365. {
  366. clr->b = (color & 0x31u) / 31.0f;
  367. clr->g = ((color & (0x31u<<5))>>5u) / 31.0f;
  368. clr->r = ((color & (0x31u<<10))>>10u) / 31.0f;
  369. }
  370. // assign the color to all vertices of the face
  371. *(clr+1) = *clr;
  372. *(clr+2) = *clr;
  373. }
  374. }
  375. if (bIsMaterialise && !pMesh->mColors[0])
  376. {
  377. // use the color as diffuse material color
  378. return true;
  379. }
  380. return false;
  381. }
  382. #endif // !! ASSIMP_BUILD_NO_STL_IMPORTER