DXFLoader.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  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 DXFLoader.cpp
  35. * @brief Implementation of the DXF importer class
  36. */
  37. #include "AssimpPCH.h"
  38. #ifndef ASSIMP_BUILD_NO_DXF_IMPORTER
  39. #include "DXFLoader.h"
  40. #include "ParsingUtils.h"
  41. #include "ConvertToLHProcess.h"
  42. #include "fast_atof.h"
  43. using namespace Assimp;
  44. // AutoCAD Binary DXF<CR><LF><SUB><NULL>
  45. #define AI_DXF_BINARY_IDENT ("AutoCAD Binary DXF\r\n\x1a\0")
  46. #define AI_DXF_BINARY_IDENT_LEN (24)
  47. // color indices for DXF - 16 are supported
  48. static aiColor4D g_aclrDxfIndexColors[] =
  49. {
  50. aiColor4D (0.6f, 0.6f, 0.6f, 1.0f),
  51. aiColor4D (1.0f, 0.0f, 0.0f, 1.0f), // red
  52. aiColor4D (0.0f, 1.0f, 0.0f, 1.0f), // green
  53. aiColor4D (0.0f, 0.0f, 1.0f, 1.0f), // blue
  54. aiColor4D (0.3f, 1.0f, 0.3f, 1.0f), // light green
  55. aiColor4D (0.3f, 0.3f, 1.0f, 1.0f), // light blue
  56. aiColor4D (1.0f, 0.3f, 0.3f, 1.0f), // light red
  57. aiColor4D (1.0f, 0.0f, 1.0f, 1.0f), // pink
  58. aiColor4D (1.0f, 0.6f, 0.0f, 1.0f), // orange
  59. aiColor4D (0.6f, 0.3f, 0.0f, 1.0f), // dark orange
  60. aiColor4D (1.0f, 1.0f, 0.0f, 1.0f), // yellow
  61. aiColor4D (0.3f, 0.3f, 0.3f, 1.0f), // dark gray
  62. aiColor4D (0.8f, 0.8f, 0.8f, 1.0f), // light gray
  63. aiColor4D (0.0f, 00.f, 0.0f, 1.0f), // black
  64. aiColor4D (1.0f, 1.0f, 1.0f, 1.0f), // white
  65. aiColor4D (0.6f, 0.0f, 1.0f, 1.0f) // violet
  66. };
  67. #define AI_DXF_NUM_INDEX_COLORS (sizeof(g_aclrDxfIndexColors)/sizeof(g_aclrDxfIndexColors[0]))
  68. // invalid/unassigned color value
  69. aiColor4D g_clrInvalid = aiColor4D(get_qnan(),0.f,0.f,1.f);
  70. // ------------------------------------------------------------------------------------------------
  71. // Constructor to be privately used by Importer
  72. DXFImporter::DXFImporter()
  73. {}
  74. // ------------------------------------------------------------------------------------------------
  75. // Destructor, private as well
  76. DXFImporter::~DXFImporter()
  77. {}
  78. // ------------------------------------------------------------------------------------------------
  79. // Returns whether the class can handle the format of the given file.
  80. bool DXFImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler, bool checkSig) const
  81. {
  82. return SimpleExtensionCheck(pFile,"dxf");
  83. }
  84. // ------------------------------------------------------------------------------------------------
  85. // Get a list of all supported file extensions
  86. void DXFImporter::GetExtensionList(std::string& append)
  87. {
  88. append.append("*.dxf");
  89. }
  90. // ------------------------------------------------------------------------------------------------
  91. // Get a copy of the next data line, skip strange data
  92. bool DXFImporter::GetNextLine()
  93. {
  94. if(!SkipLine(&buffer))
  95. return false;
  96. if(!SkipSpaces(&buffer))return GetNextLine();
  97. else if (*buffer == '{') {
  98. // some strange meta data ...
  99. while (true)
  100. {
  101. if(!SkipLine(&buffer))
  102. return false;
  103. if(SkipSpaces(&buffer) && *buffer == '}')
  104. break;
  105. }
  106. return GetNextLine();
  107. }
  108. return true;
  109. }
  110. // ------------------------------------------------------------------------------------------------
  111. // Get the next token in the file
  112. bool DXFImporter::GetNextToken()
  113. {
  114. if (bRepeat) {
  115. bRepeat = false;
  116. return true;
  117. }
  118. SkipSpaces(&buffer);
  119. groupCode = strtol10s(buffer,&buffer);
  120. if(!GetNextLine())return false;
  121. // copy the data line to a separate buffer
  122. char* m = cursor, *end = &cursor[4096];
  123. while (!IsLineEnd ( *buffer ) && m < end)
  124. *m++ = *buffer++;
  125. *m = '\0';
  126. GetNextLine();
  127. return true;
  128. }
  129. // ------------------------------------------------------------------------------------------------
  130. // Imports the given file into the given scene structure.
  131. void DXFImporter::InternReadFile( const std::string& pFile,
  132. aiScene* pScene, IOSystem* pIOHandler)
  133. {
  134. boost::scoped_ptr<IOStream> file( pIOHandler->Open( pFile));
  135. // Check whether we can read from the file
  136. if( file.get() == NULL)
  137. throw new ImportErrorException( "Failed to open DXF file " + pFile + "");
  138. // read the contents of the file in a buffer
  139. unsigned int m = (unsigned int)file->FileSize();
  140. std::vector<char> buffer2(m+1);
  141. buffer = &buffer2[0];
  142. file->Read( &buffer2[0], m,1);
  143. buffer2[m] = '\0';
  144. bRepeat = false;
  145. mDefaultLayer = NULL;
  146. // check whether this is a binaray DXF file - we can't read binary DXF files :-(
  147. if (!strncmp(AI_DXF_BINARY_IDENT,buffer,AI_DXF_BINARY_IDENT_LEN))
  148. throw new ImportErrorException("DXF: Binary files are not supported at the moment");
  149. // now get all lines of the file
  150. while (GetNextToken()) {
  151. if (2 == groupCode) {
  152. // ENTITIES and BLOCKS sections - skip the whole rest, no need to waste our time with them
  153. if (!::strcmp(cursor,"ENTITIES") || !::strcmp(cursor,"BLOCKS"))
  154. if (!ParseEntities())break; else bRepeat = true;
  155. // other sections - skip them to make sure there will be no name conflicts
  156. else {
  157. while (GetNextToken()) {
  158. if (!groupCode && !::strcmp(cursor,"ENDSEC"))break;
  159. }
  160. }
  161. }
  162. // print comment strings
  163. else if (999 == groupCode) {
  164. DefaultLogger::get()->info(std::string( cursor ));
  165. }
  166. else if (!groupCode && !::strcmp(cursor,"EOF"))
  167. break;
  168. }
  169. // find out how many valud layers we have
  170. for (std::vector<LayerInfo>::const_iterator it = mLayers.begin(),end = mLayers.end(); it != end;++it) {
  171. if (!(*it).vPositions.empty())++pScene->mNumMeshes;
  172. }
  173. if (!pScene->mNumMeshes)
  174. throw new ImportErrorException("DXF: this file contains no 3d data");
  175. pScene->mMeshes = new aiMesh*[ pScene->mNumMeshes ];
  176. m = 0;
  177. for (std::vector<LayerInfo>::const_iterator it = mLayers.begin(),end = mLayers.end();it != end;++it) {
  178. if ((*it).vPositions.empty()) {
  179. continue;
  180. }
  181. // generate the output mesh
  182. aiMesh* pMesh = pScene->mMeshes[m++] = new aiMesh();
  183. const std::vector<aiVector3D>& vPositions = (*it).vPositions;
  184. const std::vector<aiColor4D>& vColors = (*it).vColors;
  185. // check whether we need vertex colors here
  186. aiColor4D* clrOut = NULL;
  187. const aiColor4D* clr = NULL;
  188. for (std::vector<aiColor4D>::const_iterator it2 = (*it).vColors.begin(), end2 = (*it).vColors.end();it2 != end2; ++it2) {
  189. if ((*it2).r == (*it2).r) /* qnan? */ {
  190. clrOut = pMesh->mColors[0] = new aiColor4D[vPositions.size()];
  191. for (unsigned int i = 0; i < vPositions.size();++i)
  192. clrOut[i] = aiColor4D(0.6f,0.6f,0.6f,1.0f);
  193. clr = &vColors[0];
  194. break;
  195. }
  196. }
  197. pMesh->mNumFaces = (unsigned int)vPositions.size() / 4u;
  198. pMesh->mFaces = new aiFace[pMesh->mNumFaces];
  199. aiVector3D* vpOut = pMesh->mVertices = new aiVector3D[vPositions.size()];
  200. const aiVector3D* vp = &vPositions[0];
  201. for (unsigned int i = 0; i < pMesh->mNumFaces;++i) {
  202. aiFace& face = pMesh->mFaces[i];
  203. // check whether we need four, three or two indices here
  204. if (vp[1] == vp[2]) {
  205. face.mNumIndices = 2;
  206. }
  207. else if (vp[3] == vp[2]) {
  208. face.mNumIndices = 3;
  209. }
  210. else face.mNumIndices = 4;
  211. face.mIndices = new unsigned int[face.mNumIndices];
  212. for (unsigned int a = 0; a < face.mNumIndices;++a) {
  213. *vpOut++ = vp[a];
  214. if (clr) {
  215. if (is_not_qnan( clr[a].r )) {
  216. *clrOut = clr[a];
  217. }
  218. ++clrOut;
  219. }
  220. face.mIndices[a] = pMesh->mNumVertices++;
  221. }
  222. vp += 4;
  223. }
  224. }
  225. // generate the output scene graph
  226. pScene->mRootNode = new aiNode();
  227. pScene->mRootNode->mName.Set("<DXF_ROOT>");
  228. if (1 == pScene->mNumMeshes) {
  229. pScene->mRootNode->mMeshes = new unsigned int[ pScene->mRootNode->mNumMeshes = 1 ];
  230. pScene->mRootNode->mMeshes[0] = 0;
  231. }
  232. else
  233. {
  234. pScene->mRootNode->mChildren = new aiNode*[ pScene->mRootNode->mNumChildren = pScene->mNumMeshes ];
  235. for (m = 0; m < pScene->mRootNode->mNumChildren;++m) {
  236. aiNode* p = pScene->mRootNode->mChildren[m] = new aiNode();
  237. p->mName.length = ::strlen( mLayers[m].name );
  238. ::strcpy(p->mName.data, mLayers[m].name);
  239. p->mMeshes = new unsigned int[p->mNumMeshes = 1];
  240. p->mMeshes[0] = m;
  241. p->mParent = pScene->mRootNode;
  242. }
  243. }
  244. // generate a default material
  245. MaterialHelper* pcMat = new MaterialHelper();
  246. aiString s;
  247. s.Set(AI_DEFAULT_MATERIAL_NAME);
  248. pcMat->AddProperty(&s, AI_MATKEY_NAME);
  249. aiColor4D clrDiffuse(0.6f,0.6f,0.6f,1.0f);
  250. pcMat->AddProperty(&clrDiffuse,1,AI_MATKEY_COLOR_DIFFUSE);
  251. clrDiffuse = aiColor4D(1.0f,1.0f,1.0f,1.0f);
  252. pcMat->AddProperty(&clrDiffuse,1,AI_MATKEY_COLOR_SPECULAR);
  253. clrDiffuse = aiColor4D(0.05f,0.05f,0.05f,1.0f);
  254. pcMat->AddProperty(&clrDiffuse,1,AI_MATKEY_COLOR_AMBIENT);
  255. pScene->mNumMaterials = 1;
  256. pScene->mMaterials = new aiMaterial*[1];
  257. pScene->mMaterials[0] = pcMat;
  258. // flip winding order to be ccw
  259. FlipWindingOrderProcess flipper;
  260. flipper.Execute(pScene);
  261. // --- everything destructs automatically ---
  262. }
  263. // ------------------------------------------------------------------------------------------------
  264. bool DXFImporter::ParseEntities()
  265. {
  266. while (GetNextToken()) {
  267. if (!groupCode) {
  268. if (!::strcmp(cursor,"3DFACE") || !::strcmp(cursor,"LINE") || !::strcmp(cursor,"3DLINE"))
  269. if (!Parse3DFace()) return false; else bRepeat = true;
  270. if (!::strcmp(cursor,"POLYLINE") || !::strcmp(cursor,"LWPOLYLINE"))
  271. if (!ParsePolyLine()) return false; else bRepeat = true;
  272. if (!::strcmp(cursor,"ENDSEC"))
  273. return true;
  274. }
  275. }
  276. return false;
  277. }
  278. // ------------------------------------------------------------------------------------------------
  279. void DXFImporter::SetLayer(LayerInfo*& out)
  280. {
  281. for (std::vector<LayerInfo>::iterator it = mLayers.begin(),end = mLayers.end();it != end;++it) {
  282. if (!::strcmp( (*it).name, cursor )) {
  283. out = &(*it);
  284. break;
  285. }
  286. }
  287. if (!out) {
  288. // we don't have this layer yet
  289. mLayers.push_back(LayerInfo());
  290. out = &mLayers.back();
  291. ::strcpy(out->name,cursor);
  292. }
  293. }
  294. // ------------------------------------------------------------------------------------------------
  295. void DXFImporter::SetDefaultLayer(LayerInfo*& out)
  296. {
  297. if (!mDefaultLayer) {
  298. mLayers.push_back(LayerInfo());
  299. mDefaultLayer = &mLayers.back();
  300. }
  301. out = mDefaultLayer;
  302. }
  303. // ------------------------------------------------------------------------------------------------
  304. bool DXFImporter::ParsePolyLine()
  305. {
  306. bool ret = false;
  307. LayerInfo* out = NULL;
  308. std::vector<aiVector3D> positions;
  309. std::vector<aiColor4D> colors;
  310. std::vector<unsigned int> indices;
  311. unsigned int flags = 0;
  312. while (GetNextToken()) {
  313. switch (groupCode)
  314. {
  315. case 0:
  316. {
  317. if (!::strcmp(cursor,"VERTEX")) {
  318. aiVector3D v;aiColor4D clr(g_clrInvalid);
  319. unsigned int idx[4] = {0xffffffff,0xffffffff,0xffffffff,0xffffffff};
  320. ParsePolyLineVertex(v, clr, idx);
  321. if (0xffffffff == idx[0]) {
  322. positions.push_back(v);
  323. colors.push_back(clr);
  324. }
  325. else {
  326. // check whether we have a fourth coordinate
  327. if (0xffffffff == idx[3]) {
  328. idx[3] = idx[2];
  329. }
  330. indices.reserve(indices.size()+4);
  331. for (unsigned int m = 0; m < 4;++m)
  332. indices.push_back(idx[m]);
  333. }
  334. bRepeat = true;
  335. }
  336. else if (!::strcmp(cursor,"ENDSEQ")) {
  337. ret = true;
  338. }
  339. break;
  340. }
  341. // flags --- important that we know whether it is a polyface mesh
  342. case 70:
  343. {
  344. if (!flags) {
  345. flags = strtol10(cursor);
  346. }
  347. break;
  348. };
  349. // optional number of vertices
  350. case 71:
  351. {
  352. positions.reserve(strtol10(cursor));
  353. break;
  354. }
  355. // optional number of faces
  356. case 72:
  357. {
  358. indices.reserve(strtol10(cursor));
  359. break;
  360. }
  361. // 8 specifies the layer
  362. case 8:
  363. {
  364. SetLayer(out);
  365. break;
  366. }
  367. }
  368. }
  369. if (!(flags & 64)) {
  370. DefaultLogger::get()->warn("DXF: Only polyface meshes are currently supported");
  371. return ret;
  372. }
  373. if (positions.size() < 3 || indices.size() < 3) {
  374. DefaultLogger::get()->warn("DXF: Unable to parse POLYLINE element - not enough vertices");
  375. return ret;
  376. }
  377. // use a default layer if necessary
  378. if (!out) {
  379. SetDefaultLayer(out);
  380. }
  381. flags = (unsigned int)(out->vPositions.size()+indices.size());
  382. out->vPositions.reserve(flags);
  383. out->vColors.reserve(flags);
  384. // generate unique vertices
  385. for (std::vector<unsigned int>::const_iterator it = indices.begin(), end = indices.end();it != end; ++it) {
  386. unsigned int idx = *it;
  387. if (idx > positions.size() || !idx) {
  388. DefaultLogger::get()->error("DXF: Polyface mesh index os out of range");
  389. idx = (unsigned int) positions.size();
  390. }
  391. out->vPositions.push_back(positions[idx-1]); // indices are one-based.
  392. out->vColors.push_back(colors[idx-1]); // indices are one-based.
  393. }
  394. return ret;
  395. }
  396. // ------------------------------------------------------------------------------------------------
  397. bool DXFImporter::ParsePolyLineVertex(aiVector3D& out,aiColor4D& clr, unsigned int* outIdx)
  398. {
  399. bool ret = false;
  400. while (GetNextToken()) {
  401. switch (groupCode)
  402. {
  403. case 0: ret = true;
  404. break;
  405. // todo - handle the correct layer for the vertex
  406. // At the moment it is assumed that all vertices of
  407. // a polyline are placed on the same global layer.
  408. // x position of the first corner
  409. case 10: out.x = fast_atof(cursor);break;
  410. // y position of the first corner
  411. case 20: out.y = -fast_atof(cursor);break;
  412. // z position of the first corner
  413. case 30: out.z = fast_atof(cursor);break;
  414. // POLYFACE vertex indices
  415. case 71: outIdx[0] = strtol10(cursor);break;
  416. case 72: outIdx[1] = strtol10(cursor);break;
  417. case 73: outIdx[2] = strtol10(cursor);break;
  418. // case 74: outIdx[3] = strtol10(cursor);break;
  419. // color
  420. case 62: clr = g_aclrDxfIndexColors[strtol10(cursor) % AI_DXF_NUM_INDEX_COLORS]; break;
  421. };
  422. if (ret) {
  423. break;
  424. }
  425. }
  426. return ret;
  427. }
  428. // ------------------------------------------------------------------------------------------------
  429. bool DXFImporter::Parse3DFace()
  430. {
  431. bool ret = false;
  432. LayerInfo* out = NULL;
  433. aiVector3D vip[4]; // -- vectors are initialized to zero
  434. aiColor4D clr(g_clrInvalid);
  435. // this is also used for for parsing line entities
  436. bool bThird = false;
  437. while (GetNextToken()) {
  438. switch (groupCode) {
  439. case 0: ret = true;break;
  440. // 8 specifies the layer
  441. case 8: {
  442. SetLayer(out);
  443. break;
  444. }
  445. // x position of the first corner
  446. case 10: vip[0].x = fast_atof(cursor);break;
  447. // y position of the first corner
  448. case 20: vip[0].y = -fast_atof(cursor);break;
  449. // z position of the first corner
  450. case 30: vip[0].z = fast_atof(cursor);break;
  451. // x position of the second corner
  452. case 11: vip[1].x = fast_atof(cursor);break;
  453. // y position of the second corner
  454. case 21: vip[1].y = -fast_atof(cursor);break;
  455. // z position of the second corner
  456. case 31: vip[1].z = fast_atof(cursor);break;
  457. // x position of the third corner
  458. case 12: vip[2].x = fast_atof(cursor);
  459. bThird = true;break;
  460. // y position of the third corner
  461. case 22: vip[2].y = -fast_atof(cursor);
  462. bThird = true;break;
  463. // z position of the third corner
  464. case 32: vip[2].z = fast_atof(cursor);
  465. bThird = true;break;
  466. // x position of the fourth corner
  467. case 13: vip[3].x = fast_atof(cursor);
  468. bThird = true;break;
  469. // y position of the fourth corner
  470. case 23: vip[3].y = -fast_atof(cursor);
  471. bThird = true;break;
  472. // z position of the fourth corner
  473. case 33: vip[3].z = fast_atof(cursor);
  474. bThird = true;break;
  475. // color
  476. case 62: clr = g_aclrDxfIndexColors[strtol10(cursor) % AI_DXF_NUM_INDEX_COLORS]; break;
  477. };
  478. if (ret)break;
  479. }
  480. if (!bThird)vip[2] = vip[1];
  481. // use a default layer if necessary
  482. if (!out) {
  483. SetDefaultLayer(out);
  484. }
  485. // add the faces to the face list for this layer
  486. out->vPositions.push_back(vip[0]);
  487. out->vPositions.push_back(vip[1]);
  488. out->vPositions.push_back(vip[2]);
  489. out->vPositions.push_back(vip[3]); // might be equal to the third
  490. for (unsigned int i = 0; i < 4;++i)
  491. out->vColors.push_back(clr);
  492. return ret;
  493. }
  494. #endif // !! ASSIMP_BUILD_NO_DXF_IMPORTER