STLLoader.cpp 13 KB

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