2
0

STLLoader.cpp 13 KB

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