STLLoader.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2018, 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. #ifndef ASSIMP_BUILD_NO_STL_IMPORTER
  36. // internal headers
  37. #include "STLLoader.h"
  38. #include <assimp/ParsingUtils.h>
  39. #include <assimp/fast_atof.h>
  40. #include <memory>
  41. #include <assimp/IOSystem.hpp>
  42. #include <assimp/scene.h>
  43. #include <assimp/DefaultLogger.hpp>
  44. #include <assimp/importerdesc.h>
  45. using namespace Assimp;
  46. namespace {
  47. static const aiImporterDesc desc = {
  48. "Stereolithography (STL) Importer",
  49. "",
  50. "",
  51. "",
  52. aiImporterFlags_SupportTextFlavour | aiImporterFlags_SupportBinaryFlavour,
  53. 0,
  54. 0,
  55. 0,
  56. 0,
  57. "stl"
  58. };
  59. // A valid binary STL buffer should consist of the following elements, in order:
  60. // 1) 80 byte header
  61. // 2) 4 byte face count
  62. // 3) 50 bytes per face
  63. static bool IsBinarySTL(const char* buffer, unsigned int fileSize) {
  64. if( fileSize < 84 ) {
  65. return false;
  66. }
  67. const char *facecount_pos = buffer + 80;
  68. uint32_t faceCount( 0 );
  69. ::memcpy( &faceCount, facecount_pos, sizeof( uint32_t ) );
  70. const uint32_t expectedBinaryFileSize = faceCount * 50 + 84;
  71. return expectedBinaryFileSize == fileSize;
  72. }
  73. // An ascii STL buffer will begin with "solid NAME", where NAME is optional.
  74. // Note: The "solid NAME" check is necessary, but not sufficient, to determine
  75. // if the buffer is ASCII; a binary header could also begin with "solid NAME".
  76. static bool IsAsciiSTL(const char* buffer, unsigned int fileSize) {
  77. if (IsBinarySTL(buffer, fileSize))
  78. return false;
  79. const char* bufferEnd = buffer + fileSize;
  80. if (!SkipSpaces(&buffer))
  81. return false;
  82. if (buffer + 5 >= bufferEnd)
  83. return false;
  84. bool isASCII( strncmp( buffer, "solid", 5 ) == 0 );
  85. if( isASCII ) {
  86. // A lot of importers are write solid even if the file is binary. So we have to check for ASCII-characters.
  87. if( fileSize >= 500 ) {
  88. isASCII = true;
  89. for( unsigned int i = 0; i < 500; i++ ) {
  90. if( buffer[ i ] > 127 ) {
  91. isASCII = false;
  92. break;
  93. }
  94. }
  95. }
  96. }
  97. return isASCII;
  98. }
  99. } // namespace
  100. // ------------------------------------------------------------------------------------------------
  101. // Constructor to be privately used by Importer
  102. STLImporter::STLImporter()
  103. : mBuffer(),
  104. fileSize(),
  105. pScene()
  106. {}
  107. // ------------------------------------------------------------------------------------------------
  108. // Destructor, private as well
  109. STLImporter::~STLImporter()
  110. {}
  111. // ------------------------------------------------------------------------------------------------
  112. // Returns whether the class can handle the format of the given file.
  113. bool STLImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler, bool checkSig) const
  114. {
  115. const std::string extension = GetExtension(pFile);
  116. if( extension == "stl" ) {
  117. return true;
  118. } else if (!extension.length() || checkSig) {
  119. if( !pIOHandler ) {
  120. return true;
  121. }
  122. const char* tokens[] = {"STL","solid"};
  123. return SearchFileHeaderForToken(pIOHandler,pFile,tokens,2);
  124. }
  125. return false;
  126. }
  127. // ------------------------------------------------------------------------------------------------
  128. const aiImporterDesc* STLImporter::GetInfo () const {
  129. return &desc;
  130. }
  131. void addFacesToMesh(aiMesh* pMesh)
  132. {
  133. pMesh->mFaces = new aiFace[pMesh->mNumFaces];
  134. for (unsigned int i = 0, p = 0; i < pMesh->mNumFaces;++i) {
  135. aiFace& face = pMesh->mFaces[i];
  136. face.mIndices = new unsigned int[face.mNumIndices = 3];
  137. for (unsigned int o = 0; o < 3;++o,++p) {
  138. face.mIndices[o] = p;
  139. }
  140. }
  141. }
  142. // ------------------------------------------------------------------------------------------------
  143. // Imports the given file into the given scene structure.
  144. void STLImporter::InternReadFile( const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler )
  145. {
  146. std::unique_ptr<IOStream> file( pIOHandler->Open( pFile, "rb"));
  147. // Check whether we can read from the file
  148. if( file.get() == NULL) {
  149. throw DeadlyImportError( "Failed to open STL file " + pFile + ".");
  150. }
  151. fileSize = (unsigned int)file->FileSize();
  152. // allocate storage and copy the contents of the file to a memory buffer
  153. // (terminate it with zero)
  154. std::vector<char> mBuffer2;
  155. TextFileToBuffer(file.get(),mBuffer2);
  156. this->pScene = pScene;
  157. this->mBuffer = &mBuffer2[0];
  158. // the default vertex color is light gray.
  159. clrColorDefault.r = clrColorDefault.g = clrColorDefault.b = clrColorDefault.a = (ai_real) 0.6;
  160. // allocate a single node
  161. pScene->mRootNode = new aiNode();
  162. bool bMatClr = false;
  163. if (IsBinarySTL(mBuffer, fileSize)) {
  164. bMatClr = LoadBinaryFile();
  165. } else if (IsAsciiSTL(mBuffer, fileSize)) {
  166. LoadASCIIFile( pScene->mRootNode );
  167. } else {
  168. throw DeadlyImportError( "Failed to determine STL storage representation for " + pFile + ".");
  169. }
  170. // create a single default material, using a white diffuse color for consistency with
  171. // other geometric types (e.g., PLY).
  172. aiMaterial* pcMat = new aiMaterial();
  173. aiString s;
  174. s.Set(AI_DEFAULT_MATERIAL_NAME);
  175. pcMat->AddProperty(&s, AI_MATKEY_NAME);
  176. aiColor4D clrDiffuse(ai_real(1.0),ai_real(1.0),ai_real(1.0),ai_real(1.0));
  177. if (bMatClr) {
  178. clrDiffuse = clrColorDefault;
  179. }
  180. pcMat->AddProperty(&clrDiffuse,1,AI_MATKEY_COLOR_DIFFUSE);
  181. pcMat->AddProperty(&clrDiffuse,1,AI_MATKEY_COLOR_SPECULAR);
  182. clrDiffuse = aiColor4D( ai_real(1.0), ai_real(1.0), ai_real(1.0), ai_real(1.0));
  183. pcMat->AddProperty(&clrDiffuse,1,AI_MATKEY_COLOR_AMBIENT);
  184. pScene->mNumMaterials = 1;
  185. pScene->mMaterials = new aiMaterial*[1];
  186. pScene->mMaterials[0] = pcMat;
  187. }
  188. // ------------------------------------------------------------------------------------------------
  189. // Read an ASCII STL file
  190. void STLImporter::LoadASCIIFile( aiNode *root ) {
  191. std::vector<aiMesh*> meshes;
  192. std::vector<aiNode*> nodes;
  193. const char* sz = mBuffer;
  194. const char* bufferEnd = mBuffer + fileSize;
  195. std::vector<aiVector3D> positionBuffer;
  196. std::vector<aiVector3D> normalBuffer;
  197. // try to guess how many vertices we could have
  198. // assume we'll need 160 bytes for each face
  199. size_t sizeEstimate = std::max(1u, fileSize / 160u ) * 3;
  200. positionBuffer.reserve(sizeEstimate);
  201. normalBuffer.reserve(sizeEstimate);
  202. while (IsAsciiSTL(sz, static_cast<unsigned int>(bufferEnd - sz))) {
  203. std::vector<unsigned int> meshIndices;
  204. aiMesh* pMesh = new aiMesh();
  205. pMesh->mMaterialIndex = 0;
  206. meshIndices.push_back((unsigned int) meshes.size() );
  207. meshes.push_back(pMesh);
  208. aiNode *node = new aiNode;
  209. node->mParent = root;
  210. nodes.push_back( node );
  211. SkipSpaces(&sz);
  212. ai_assert(!IsLineEnd(sz));
  213. sz += 5; // skip the "solid"
  214. SkipSpaces(&sz);
  215. const char* szMe = sz;
  216. while (!::IsSpaceOrNewLine(*sz)) {
  217. sz++;
  218. }
  219. size_t temp;
  220. // setup the name of the node
  221. if ((temp = (size_t)(sz-szMe))) {
  222. if (temp >= MAXLEN) {
  223. throw DeadlyImportError( "STL: Node name too long" );
  224. }
  225. std::string name( szMe, temp );
  226. node->mName.Set( name.c_str() );
  227. //pScene->mRootNode->mName.length = temp;
  228. //memcpy(pScene->mRootNode->mName.data,szMe,temp);
  229. //pScene->mRootNode->mName.data[temp] = '\0';
  230. } else {
  231. pScene->mRootNode->mName.Set("<STL_ASCII>");
  232. }
  233. unsigned int faceVertexCounter = 3;
  234. for ( ;; ) {
  235. // go to the next token
  236. if(!SkipSpacesAndLineEnd(&sz))
  237. {
  238. // seems we're finished although there was no end marker
  239. ASSIMP_LOG_WARN("STL: unexpected EOF. \'endsolid\' keyword was expected");
  240. break;
  241. }
  242. // facet normal -0.13 -0.13 -0.98
  243. if (!strncmp(sz,"facet",5) && IsSpaceOrNewLine(*(sz+5)) && *(sz + 5) != '\0') {
  244. if (faceVertexCounter != 3) {
  245. ASSIMP_LOG_WARN("STL: A new facet begins but the old is not yet complete");
  246. }
  247. faceVertexCounter = 0;
  248. normalBuffer.push_back(aiVector3D());
  249. aiVector3D* vn = &normalBuffer.back();
  250. sz += 6;
  251. SkipSpaces(&sz);
  252. if (strncmp(sz,"normal",6)) {
  253. ASSIMP_LOG_WARN("STL: a facet normal vector was expected but not found");
  254. } else {
  255. if (sz[6] == '\0') {
  256. throw DeadlyImportError("STL: unexpected EOF while parsing facet");
  257. }
  258. sz += 7;
  259. SkipSpaces(&sz);
  260. sz = fast_atoreal_move<ai_real>(sz, (ai_real&)vn->x );
  261. SkipSpaces(&sz);
  262. sz = fast_atoreal_move<ai_real>(sz, (ai_real&)vn->y );
  263. SkipSpaces(&sz);
  264. sz = fast_atoreal_move<ai_real>(sz, (ai_real&)vn->z );
  265. normalBuffer.push_back(*vn);
  266. normalBuffer.push_back(*vn);
  267. }
  268. } else if (!strncmp(sz,"vertex",6) && ::IsSpaceOrNewLine(*(sz+6))) { // vertex 1.50000 1.50000 0.00000
  269. if (faceVertexCounter >= 3) {
  270. ASSIMP_LOG_ERROR("STL: a facet with more than 3 vertices has been found");
  271. ++sz;
  272. } else {
  273. if (sz[6] == '\0') {
  274. throw DeadlyImportError("STL: unexpected EOF while parsing facet");
  275. }
  276. sz += 7;
  277. SkipSpaces(&sz);
  278. positionBuffer.push_back(aiVector3D());
  279. aiVector3D* vn = &positionBuffer.back();
  280. sz = fast_atoreal_move<ai_real>(sz, (ai_real&)vn->x );
  281. SkipSpaces(&sz);
  282. sz = fast_atoreal_move<ai_real>(sz, (ai_real&)vn->y );
  283. SkipSpaces(&sz);
  284. sz = fast_atoreal_move<ai_real>(sz, (ai_real&)vn->z );
  285. faceVertexCounter++;
  286. }
  287. } else if (!::strncmp(sz,"endsolid",8)) {
  288. do {
  289. ++sz;
  290. } while (!::IsLineEnd(*sz));
  291. SkipSpacesAndLineEnd(&sz);
  292. // finished!
  293. break;
  294. } else { // else skip the whole identifier
  295. do {
  296. ++sz;
  297. } while (!::IsSpaceOrNewLine(*sz));
  298. }
  299. }
  300. if (positionBuffer.empty()) {
  301. pMesh->mNumFaces = 0;
  302. throw DeadlyImportError("STL: ASCII file is empty or invalid; no data loaded");
  303. }
  304. if (positionBuffer.size() % 3 != 0) {
  305. pMesh->mNumFaces = 0;
  306. throw DeadlyImportError("STL: Invalid number of vertices");
  307. }
  308. if (normalBuffer.size() != positionBuffer.size()) {
  309. pMesh->mNumFaces = 0;
  310. throw DeadlyImportError("Normal buffer size does not match position buffer size");
  311. }
  312. pMesh->mNumFaces = static_cast<unsigned int>(positionBuffer.size() / 3);
  313. pMesh->mNumVertices = static_cast<unsigned int>(positionBuffer.size());
  314. pMesh->mVertices = new aiVector3D[pMesh->mNumVertices];
  315. memcpy(pMesh->mVertices, &positionBuffer[0].x, pMesh->mNumVertices * sizeof(aiVector3D));
  316. positionBuffer.clear();
  317. pMesh->mNormals = new aiVector3D[pMesh->mNumVertices];
  318. memcpy(pMesh->mNormals, &normalBuffer[0].x, pMesh->mNumVertices * sizeof(aiVector3D));
  319. normalBuffer.clear();
  320. // now copy faces
  321. addFacesToMesh(pMesh);
  322. // assign the meshes to the current node
  323. pushMeshesToNode( meshIndices, node );
  324. }
  325. // now add the loaded meshes
  326. pScene->mNumMeshes = (unsigned int)meshes.size();
  327. pScene->mMeshes = new aiMesh*[pScene->mNumMeshes];
  328. for (size_t i = 0; i < meshes.size(); i++) {
  329. pScene->mMeshes[ i ] = meshes[i];
  330. }
  331. root->mNumChildren = (unsigned int) nodes.size();
  332. root->mChildren = new aiNode*[ root->mNumChildren ];
  333. for ( size_t i=0; i<nodes.size(); ++i ) {
  334. root->mChildren[ i ] = nodes[ i ];
  335. }
  336. }
  337. // ------------------------------------------------------------------------------------------------
  338. // Read a binary STL file
  339. bool STLImporter::LoadBinaryFile()
  340. {
  341. // allocate one mesh
  342. pScene->mNumMeshes = 1;
  343. pScene->mMeshes = new aiMesh*[1];
  344. aiMesh* pMesh = pScene->mMeshes[0] = new aiMesh();
  345. pMesh->mMaterialIndex = 0;
  346. // skip the first 80 bytes
  347. if (fileSize < 84) {
  348. throw DeadlyImportError("STL: file is too small for the header");
  349. }
  350. bool bIsMaterialise = false;
  351. // search for an occurrence of "COLOR=" in the header
  352. const unsigned char* sz2 = (const unsigned char*)mBuffer;
  353. const unsigned char* const szEnd = sz2+80;
  354. while (sz2 < szEnd) {
  355. if ('C' == *sz2++ && 'O' == *sz2++ && 'L' == *sz2++ &&
  356. 'O' == *sz2++ && 'R' == *sz2++ && '=' == *sz2++) {
  357. // read the default vertex color for facets
  358. bIsMaterialise = true;
  359. ASSIMP_LOG_INFO("STL: Taking code path for Materialise files");
  360. const ai_real invByte = (ai_real)1.0 / ( ai_real )255.0;
  361. clrColorDefault.r = (*sz2++) * invByte;
  362. clrColorDefault.g = (*sz2++) * invByte;
  363. clrColorDefault.b = (*sz2++) * invByte;
  364. clrColorDefault.a = (*sz2++) * invByte;
  365. break;
  366. }
  367. }
  368. const unsigned char* sz = (const unsigned char*)mBuffer + 80;
  369. // now read the number of facets
  370. pScene->mRootNode->mName.Set("<STL_BINARY>");
  371. pMesh->mNumFaces = *((uint32_t*)sz);
  372. sz += 4;
  373. if (fileSize < 84 + pMesh->mNumFaces*50) {
  374. throw DeadlyImportError("STL: file is too small to hold all facets");
  375. }
  376. if (!pMesh->mNumFaces) {
  377. throw DeadlyImportError("STL: file is empty. There are no facets defined");
  378. }
  379. pMesh->mNumVertices = pMesh->mNumFaces*3;
  380. aiVector3D *vp = pMesh->mVertices = new aiVector3D[pMesh->mNumVertices];
  381. aiVector3D *vn = pMesh->mNormals = new aiVector3D[pMesh->mNumVertices];
  382. typedef aiVector3t<float> aiVector3F;
  383. aiVector3F* theVec;
  384. aiVector3F theVec3F;
  385. for ( unsigned int i = 0; i < pMesh->mNumFaces; ++i ) {
  386. // NOTE: Blender sometimes writes empty normals ... this is not
  387. // our fault ... the RemoveInvalidData helper step should fix that
  388. // There's one normal for the face in the STL; use it three times
  389. // for vertex normals
  390. theVec = (aiVector3F*) sz;
  391. ::memcpy( &theVec3F, theVec, sizeof(aiVector3F) );
  392. vn->x = theVec3F.x; vn->y = theVec3F.y; vn->z = theVec3F.z;
  393. *(vn+1) = *vn;
  394. *(vn+2) = *vn;
  395. ++theVec;
  396. vn += 3;
  397. // vertex 1
  398. ::memcpy( &theVec3F, theVec, sizeof(aiVector3F) );
  399. vp->x = theVec3F.x; vp->y = theVec3F.y; vp->z = theVec3F.z;
  400. ++theVec;
  401. ++vp;
  402. // vertex 2
  403. ::memcpy( &theVec3F, theVec, sizeof(aiVector3F) );
  404. vp->x = theVec3F.x; vp->y = theVec3F.y; vp->z = theVec3F.z;
  405. ++theVec;
  406. ++vp;
  407. // vertex 3
  408. ::memcpy( &theVec3F, theVec, sizeof(aiVector3F) );
  409. vp->x = theVec3F.x; vp->y = theVec3F.y; vp->z = theVec3F.z;
  410. ++theVec;
  411. ++vp;
  412. sz = (const unsigned char*) theVec;
  413. uint16_t color = *((uint16_t*)sz);
  414. sz += 2;
  415. if (color & (1 << 15))
  416. {
  417. // seems we need to take the color
  418. if (!pMesh->mColors[0])
  419. {
  420. pMesh->mColors[0] = new aiColor4D[pMesh->mNumVertices];
  421. for (unsigned int i = 0; i <pMesh->mNumVertices;++i)
  422. *pMesh->mColors[0]++ = this->clrColorDefault;
  423. pMesh->mColors[0] -= pMesh->mNumVertices;
  424. ASSIMP_LOG_INFO("STL: Mesh has vertex colors");
  425. }
  426. aiColor4D* clr = &pMesh->mColors[0][i*3];
  427. clr->a = 1.0;
  428. const ai_real invVal( (ai_real)1.0 / ( ai_real )31.0 );
  429. if (bIsMaterialise) // this is reversed
  430. {
  431. clr->r = (color & 0x31u) *invVal;
  432. clr->g = ((color & (0x31u<<5))>>5u) *invVal;
  433. clr->b = ((color & (0x31u<<10))>>10u) *invVal;
  434. }
  435. else
  436. {
  437. clr->b = (color & 0x31u) *invVal;
  438. clr->g = ((color & (0x31u<<5))>>5u) *invVal;
  439. clr->r = ((color & (0x31u<<10))>>10u) *invVal;
  440. }
  441. // assign the color to all vertices of the face
  442. *(clr+1) = *clr;
  443. *(clr+2) = *clr;
  444. }
  445. }
  446. // now copy faces
  447. addFacesToMesh(pMesh);
  448. // add all created meshes to the single node
  449. pScene->mRootNode->mNumMeshes = pScene->mNumMeshes;
  450. pScene->mRootNode->mMeshes = new unsigned int[pScene->mNumMeshes];
  451. for (unsigned int i = 0; i < pScene->mNumMeshes; i++)
  452. pScene->mRootNode->mMeshes[i] = i;
  453. if (bIsMaterialise && !pMesh->mColors[0])
  454. {
  455. // use the color as diffuse material color
  456. return true;
  457. }
  458. return false;
  459. }
  460. void STLImporter::pushMeshesToNode( std::vector<unsigned int> &meshIndices, aiNode *node ) {
  461. ai_assert( nullptr != node );
  462. if ( meshIndices.empty() ) {
  463. return;
  464. }
  465. node->mNumMeshes = static_cast<unsigned int>( meshIndices.size() );
  466. node->mMeshes = new unsigned int[ meshIndices.size() ];
  467. for ( size_t i=0; i<meshIndices.size(); ++i ) {
  468. node->mMeshes[ i ] = meshIndices[ i ];
  469. }
  470. meshIndices.clear();
  471. }
  472. #endif // !! ASSIMP_BUILD_NO_STL_IMPORTER