IFCLoader.cpp 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413
  1. /*
  2. Open Asset Import Library (ASSIMP)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2010, ASSIMP Development Team
  5. All rights reserved.
  6. Redistribution and use of this software in source and binary forms,
  7. with or without modification, are permitted provided that the
  8. following conditions are met:
  9. * Redistributions of source code must retain the above
  10. copyright notice, this list of conditions and the
  11. following disclaimer.
  12. * Redistributions in binary form must reproduce the above
  13. copyright notice, this list of conditions and the
  14. following disclaimer in the documentation and/or other
  15. materials provided with the distribution.
  16. * Neither the name of the ASSIMP team, nor the names of its
  17. contributors may be used to endorse or promote products
  18. derived from this software without specific prior
  19. written permission of the ASSIMP Development Team.
  20. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. ----------------------------------------------------------------------
  32. */
  33. /** @file IFC.cpp
  34. * @brief Implementation of the Industry Foundation Classes loader
  35. */
  36. #include "AssimpPCH.h"
  37. #ifndef ASSIMP_BUILD_NO_IFC_IMPORTER
  38. #include "IFCLoader.h"
  39. #include "STEPFileReader.h"
  40. #include "IFCReaderGen.h"
  41. #include "StreamReader.h"
  42. #include "MemoryIOWrapper.h"
  43. #include "ProcessHelper.h"
  44. #include <boost/tuple/tuple.hpp>
  45. using namespace Assimp;
  46. using namespace Assimp::Formatter;
  47. namespace EXPRESS = STEP::EXPRESS;
  48. const std::string LogFunctions<IFCImporter>::log_prefix = "IFC: ";
  49. /* DO NOT REMOVE this comment block. The genentitylist.sh script
  50. * just looks for names adhering to the IFC :: IfcSomething naming scheme
  51. * and includes all matches in the whitelist for code-generation. Thus,
  52. * all entity classes that are only indirectly referenced need to be
  53. * mentioned explicitly.
  54. IFC::IfcRepresentationMap
  55. IFC::IfcProductRepresentation
  56. IFC::IfcUnitAssignment
  57. IFC::IfcClosedShell
  58. IFC::IfcDoor
  59. */
  60. namespace {
  61. // helper for std::for_each to delete all heap-allocated items in a container
  62. template<typename T>
  63. struct delete_fun
  64. {
  65. void operator()(T* del) {
  66. delete del;
  67. }
  68. };
  69. // intermediate data dump during conversion
  70. struct ConversionData
  71. {
  72. ConversionData(const STEP::DB& db, const IFC::IfcProject& proj, aiScene* out,const IFCImporter::Settings& settings)
  73. : len_scale(1.0)
  74. , db(db)
  75. , proj(proj)
  76. , out(out)
  77. , settings(settings)
  78. {}
  79. ~ConversionData() {
  80. std::for_each(meshes.begin(),meshes.end(),delete_fun<aiMesh>());
  81. std::for_each(materials.begin(),materials.end(),delete_fun<aiMaterial>());
  82. }
  83. float len_scale;
  84. const STEP::DB& db;
  85. const IFC::IfcProject& proj;
  86. aiScene* out;
  87. aiMatrix4x4 wcs;
  88. std::vector<aiMesh*> meshes;
  89. std::vector<aiMaterial*> materials;
  90. typedef std::map<const IFC::IfcRepresentationItem*, std::vector<unsigned int> > MeshCache;
  91. MeshCache cached_meshes;
  92. const IFCImporter::Settings& settings;
  93. };
  94. // helper used during mesh construction
  95. struct TempMesh
  96. {
  97. std::vector<aiVector3D> verts;
  98. std::vector<unsigned int> vertcnt;
  99. std::vector<unsigned int> mat_idx;
  100. aiMesh* ToMesh() {
  101. ai_assert(verts.size() == std::accumulate(vertcnt.begin(),vertcnt.end(),0));
  102. if (verts.empty()) {
  103. return NULL;
  104. }
  105. std::auto_ptr<aiMesh> mesh(new aiMesh());
  106. // copy vertices
  107. mesh->mNumVertices = static_cast<unsigned int>(verts.size());
  108. mesh->mVertices = new aiVector3D[mesh->mNumVertices];
  109. std::copy(verts.begin(),verts.end(),mesh->mVertices);
  110. // and build up faces
  111. mesh->mNumFaces = static_cast<unsigned int>(vertcnt.size());
  112. mesh->mFaces = new aiFace[mesh->mNumFaces];
  113. for(unsigned int i = 0, acc = 0; i < mesh->mNumFaces; ++i) {
  114. aiFace& f = mesh->mFaces[i];
  115. f.mNumIndices = vertcnt[i];
  116. f.mIndices = new unsigned int[f.mNumIndices];
  117. for(unsigned int a = 0; a < f.mNumIndices; ++a) {
  118. f.mIndices[a] = acc++;
  119. }
  120. }
  121. // XXX materials
  122. mesh->mMaterialIndex = UINT_MAX;
  123. return mesh.release();
  124. }
  125. };
  126. // forward declarations
  127. float ConvertSIPrefix(const std::string& prefix);
  128. void SetUnits(ConversionData& conv);
  129. void ConvertAxisPlacement(aiMatrix4x4& out, const IFC::IfcAxis2Placement& in, ConversionData& conv);
  130. void SetCoordinateSpace(ConversionData& conv);
  131. void ProcessSpatialStructures(ConversionData& conv);
  132. aiNode* ProcessSpatialStructure(aiNode* parent, const IFC::IfcProduct& el ,ConversionData& conv);
  133. void ProcessProductRepresentation(const IFC::IfcProduct& el, aiNode* nd, ConversionData& conv);
  134. void MakeTreeRelative(ConversionData& conv);
  135. } // anon
  136. // ------------------------------------------------------------------------------------------------
  137. // Constructor to be privately used by Importer
  138. IFCImporter::IFCImporter()
  139. {}
  140. // ------------------------------------------------------------------------------------------------
  141. // Destructor, private as well
  142. IFCImporter::~IFCImporter()
  143. {
  144. }
  145. // ------------------------------------------------------------------------------------------------
  146. // Returns whether the class can handle the format of the given file.
  147. bool IFCImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler, bool checkSig) const
  148. {
  149. const std::string& extension = GetExtension(pFile);
  150. if (extension == "ifc") {
  151. return true;
  152. }
  153. else if ((!extension.length() || checkSig) && pIOHandler) {
  154. // note: this is the common identification for STEP-encoded files, so
  155. // it is only unambiguous as long as we don't support any further
  156. // file formats with STEP as their encoding.
  157. const char* tokens[] = {"ISO-10303-21"};
  158. return SearchFileHeaderForToken(pIOHandler,pFile,tokens,1);
  159. }
  160. return false;
  161. }
  162. // ------------------------------------------------------------------------------------------------
  163. // List all extensions handled by this loader
  164. void IFCImporter::GetExtensionList(std::set<std::string>& app)
  165. {
  166. app.insert("ifc");
  167. }
  168. // ------------------------------------------------------------------------------------------------
  169. // Setup configuration properties for the loader
  170. void IFCImporter::SetupProperties(const Importer* pImp)
  171. {
  172. settings.skipSpaceRepresentations = pImp->GetPropertyBool(AI_CONFIG_IMPORT_IFC_SKIP_SPACE_REPRESENTATIONS,true);
  173. settings.skipCurveRepresentations = pImp->GetPropertyBool(AI_CONFIG_IMPORT_IFC_SKIP_CURVE_REPRESENTATIONS,false);
  174. }
  175. // ------------------------------------------------------------------------------------------------
  176. // Imports the given file into the given scene structure.
  177. void IFCImporter::InternReadFile( const std::string& pFile,
  178. aiScene* pScene, IOSystem* pIOHandler)
  179. {
  180. boost::shared_ptr<IOStream> stream(pIOHandler->Open(pFile));
  181. if (!stream) {
  182. ThrowException("Could not open file for reading");
  183. }
  184. boost::scoped_ptr<STEP::DB> db(STEP::ReadFileHeader(stream));
  185. const STEP::HeaderInfo& head = const_cast<const STEP::DB&>(*db).GetHeader();
  186. if(!head.fileSchema.size() || head.fileSchema.substr(0,3) != "IFC") {
  187. ThrowException("Unrecognized file schema: " + head.fileSchema);
  188. }
  189. if (!DefaultLogger::isNullLogger()) {
  190. LogDebug("File schema is \'" + head.fileSchema + '\'');
  191. if (head.timestamp.length()) {
  192. LogDebug("Timestamp \'" + head.timestamp + '\'');
  193. }
  194. if (head.app.length()) {
  195. LogDebug("Application/Exporter identline is \'" + head.app + '\'');
  196. }
  197. }
  198. // obtain a copy of the machine-generated IFC scheme
  199. EXPRESS::ConversionSchema schema;
  200. IFC::GetSchema(schema);
  201. // feed the IFC schema into the reader and pre-parse all lines
  202. STEP::ReadFile(*db, schema);
  203. const STEP::LazyObject* proj = db->GetObject("ifcproject");
  204. if (!proj) {
  205. ThrowException("missing IfcProject entity");
  206. }
  207. ConversionData conv(*db,proj->To<IFC::IfcProject>(),pScene,settings);
  208. SetUnits(conv);
  209. SetCoordinateSpace(conv);
  210. ProcessSpatialStructures(conv);
  211. MakeTreeRelative(conv);
  212. #ifdef ASSIMP_IFC_TEST
  213. db->EvaluateAll();
  214. #endif
  215. // do final data copying
  216. if (conv.meshes.size()) {
  217. pScene->mNumMeshes = static_cast<unsigned int>(conv.meshes.size());
  218. pScene->mMeshes = new aiMesh*[pScene->mNumMeshes]();
  219. std::copy(conv.meshes.begin(),conv.meshes.end(),pScene->mMeshes);
  220. // needed to keep the d'tor from burning us
  221. conv.meshes.clear();
  222. }
  223. if (conv.materials.size()) {
  224. pScene->mNumMaterials = static_cast<unsigned int>(conv.materials.size());
  225. pScene->mMaterials = new aiMaterial*[pScene->mNumMaterials]();
  226. std::copy(conv.materials.begin(),conv.materials.end(),pScene->mMaterials);
  227. // needed to keep the d'tor from burning us
  228. conv.materials.clear();
  229. }
  230. // apply world coordinate system (which includes the scaling to convert to meters and a -90 degrees rotation around x)
  231. aiMatrix4x4 scale, rot;
  232. aiMatrix4x4::Scaling(aiVector3D(conv.len_scale,conv.len_scale,conv.len_scale),scale);
  233. aiMatrix4x4::RotationX(-AI_MATH_HALF_PI_F,rot);
  234. pScene->mRootNode->mTransformation = rot * scale * conv.wcs * pScene->mRootNode->mTransformation;
  235. // this must be last because objects are evaluated lazily as we process them
  236. if ( !DefaultLogger::isNullLogger() ){
  237. LogDebug((Formatter::format(),"STEP: evaluated ",db->GetEvaluatedObjectCount()," object records"));
  238. }
  239. }
  240. namespace {
  241. // ------------------------------------------------------------------------------------------------
  242. bool IsTrue(const EXPRESS::BOOLEAN& in)
  243. {
  244. return (std::string)in == "TRUE" || (std::string)in == "T";
  245. }
  246. // ------------------------------------------------------------------------------------------------
  247. float ConvertSIPrefix(const std::string& prefix)
  248. {
  249. if (prefix == "EXA") {
  250. return 1e18f;
  251. }
  252. else if (prefix == "PETA") {
  253. return 1e15f;
  254. }
  255. else if (prefix == "TERA") {
  256. return 1e12f;
  257. }
  258. else if (prefix == "GIGA") {
  259. return 1e9f;
  260. }
  261. else if (prefix == "MEGA") {
  262. return 1e6f;
  263. }
  264. else if (prefix == "KILO") {
  265. return 1e3f;
  266. }
  267. else if (prefix == "HECTO") {
  268. return 1e2f;
  269. }
  270. else if (prefix == "DECA") {
  271. return 1e-0f;
  272. }
  273. else if (prefix == "DECI") {
  274. return 1e-1f;
  275. }
  276. else if (prefix == "CENTI") {
  277. return 1e-2f;
  278. }
  279. else if (prefix == "MILLI") {
  280. return 1e-3f;
  281. }
  282. else if (prefix == "MICRO") {
  283. return 1e-6f;
  284. }
  285. else if (prefix == "NANO") {
  286. return 1e-9f;
  287. }
  288. else if (prefix == "PICO") {
  289. return 1e-12f;
  290. }
  291. else if (prefix == "FEMTO") {
  292. return 1e-15f;
  293. }
  294. else if (prefix == "ATTO") {
  295. return 1e-18f;
  296. }
  297. else {
  298. IFCImporter::LogError("Unrecognized SI prefix: " + prefix);
  299. return 1;
  300. }
  301. }
  302. // ------------------------------------------------------------------------------------------------
  303. void SetUnits(ConversionData& conv)
  304. {
  305. // see if we can determine the coordinate space used to express
  306. for(size_t i = 0; i < conv.proj.UnitsInContext->Units.size(); ++i ) {
  307. try {
  308. const EXPRESS::ENTITY& e = conv.proj.UnitsInContext->Units[i]->To<IFC::ENTITY>();
  309. const IFC::IfcSIUnit& si = conv.db.MustGetObject(e).To<IFC::IfcSIUnit>();
  310. if(si.UnitType == "LENGTHUNIT" && si.Prefix) {
  311. conv.len_scale = ConvertSIPrefix(si.Prefix);
  312. IFCImporter::LogDebug("got units used for lengths");
  313. }
  314. }
  315. catch(std::bad_cast&) {
  316. // not SI unit, not implemented
  317. continue;
  318. }
  319. }
  320. }
  321. // ------------------------------------------------------------------------------------------------
  322. void ConvertColor(aiColor4D& out, const IFC::IfcColourRgb& in)
  323. {
  324. out.r = in.Red;
  325. out.g = in.Green;
  326. out.b = in.Blue;
  327. out.a = 1.f;
  328. }
  329. // ------------------------------------------------------------------------------------------------
  330. void ConvertColor(aiColor4D& out, const IFC::IfcColourOrFactor* in,ConversionData& conv,const aiColor4D* base)
  331. {
  332. if (const EXPRESS::REAL* const r = in->ToPtr<EXPRESS::REAL>()) {
  333. out.r = out.g = out.b = *r;
  334. if(base) {
  335. out.r *= base->r;
  336. out.g *= base->g;
  337. out.b *= base->b;
  338. out.a = base->a;
  339. }
  340. else out.a = 1.0;
  341. }
  342. else if (const IFC::IfcColourRgb* const rgb = in->ResolveSelectPtr<IFC::IfcColourRgb>(conv.db)) {
  343. ConvertColor(out,*rgb);
  344. }
  345. else {
  346. IFCImporter::LogWarn("skipping unknown IfcColourOrFactor entity");
  347. }
  348. }
  349. // ------------------------------------------------------------------------------------------------
  350. void ConvertCartesianPoint(aiVector3D& out, const IFC::IfcCartesianPoint& in)
  351. {
  352. out = aiVector3D();
  353. for(size_t i = 0; i < in.Coordinates.size(); ++i) {
  354. out[i] = in.Coordinates[i];
  355. }
  356. }
  357. // ------------------------------------------------------------------------------------------------
  358. void ConvertDirection(aiVector3D& out, const IFC::IfcDirection& in)
  359. {
  360. out = aiVector3D();
  361. for(size_t i = 0; i < in.DirectionRatios.size(); ++i) {
  362. out[i] = in.DirectionRatios[i];
  363. }
  364. const float len = out.Length();
  365. if (len<1e-6) {
  366. IFCImporter::LogWarn("direction vector too small, normalizing would result in a division by zero");
  367. return;
  368. }
  369. out /= len;
  370. }
  371. // ------------------------------------------------------------------------------------------------
  372. void AssignMatrixAxes(aiMatrix4x4& out, const aiVector3D& x, const aiVector3D& y, const aiVector3D& z)
  373. {
  374. out.a1 = x.x;
  375. out.b1 = x.y;
  376. out.c1 = x.z;
  377. out.a2 = y.x;
  378. out.b2 = y.y;
  379. out.c2 = y.z;
  380. out.a3 = z.x;
  381. out.b3 = z.y;
  382. out.c3 = z.z;
  383. }
  384. // ------------------------------------------------------------------------------------------------
  385. void ConvertAxisPlacement(aiMatrix4x4& out, const IFC::IfcAxis2Placement3D& in, ConversionData& conv)
  386. {
  387. aiVector3D loc;
  388. ConvertCartesianPoint(loc,in.Location);
  389. aiVector3D z(0.f,0.f,1.f),r(0.f,1.f,0.f),x;
  390. if (in.Axis) {
  391. ConvertDirection(z,*in.Axis.Get());
  392. }
  393. if (in.RefDirection) {
  394. ConvertDirection(r,*in.RefDirection.Get());
  395. }
  396. aiVector3D v = r.Normalize();
  397. aiVector3D tmpx = z * (v*z);
  398. x = (v-tmpx).Normalize();
  399. aiVector3D y = (z^x);
  400. aiMatrix4x4::Translation(loc,out);
  401. AssignMatrixAxes(out,x,y,z);
  402. }
  403. // ------------------------------------------------------------------------------------------------
  404. void ConvertAxisPlacement(aiMatrix4x4& out, const IFC::IfcAxis2Placement2D& in, ConversionData& conv)
  405. {
  406. aiVector3D loc;
  407. ConvertCartesianPoint(loc,in.Location);
  408. aiVector3D x(1.f,0.f,1.f);
  409. if (in.RefDirection) {
  410. ConvertDirection(x,*in.RefDirection.Get());
  411. }
  412. const aiVector3D y = aiVector3D(x.y,-x.x,0.f);
  413. aiMatrix4x4::Translation(loc,out);
  414. AssignMatrixAxes(out,x,y,aiVector3D(0.f,0.f,1.f));
  415. }
  416. // ------------------------------------------------------------------------------------------------
  417. void ConvertAxisPlacement(aiMatrix4x4& out, const IFC::IfcAxis2Placement& in, ConversionData& conv)
  418. {
  419. if(const IFC::IfcAxis2Placement3D* pl3 = in.ResolveSelectPtr<IFC::IfcAxis2Placement3D>(conv.db)) {
  420. ConvertAxisPlacement(out,*pl3,conv);
  421. }
  422. else if(const IFC::IfcAxis2Placement2D* pl2 = in.ResolveSelectPtr<IFC::IfcAxis2Placement2D>(conv.db)) {
  423. ConvertAxisPlacement(out,*pl2,conv);
  424. }
  425. else {
  426. IFCImporter::LogWarn("skipping unknown IfcAxis2Placement entity");
  427. }
  428. }
  429. // ------------------------------------------------------------------------------------------------
  430. void SetCoordinateSpace(ConversionData& conv)
  431. {
  432. const IFC::IfcRepresentationContext* fav = NULL;
  433. BOOST_FOREACH(const IFC::IfcRepresentationContext& v, conv.proj.RepresentationContexts) {
  434. fav = &v;
  435. // Model should be the most suitable type of context, hence ignore the others
  436. if (v.ContextType && v.ContextType.Get() == "Model") {
  437. break;
  438. }
  439. }
  440. if (fav) {
  441. if(const IFC::IfcGeometricRepresentationContext* const geo = fav->ToPtr<IFC::IfcGeometricRepresentationContext>()) {
  442. ConvertAxisPlacement(conv.wcs, *geo->WorldCoordinateSystem, conv);
  443. IFCImporter::LogDebug("got world coordinate system");
  444. }
  445. }
  446. }
  447. // ------------------------------------------------------------------------------------------------
  448. void ConvertTransformOperator(aiMatrix4x4& out, const IFC::IfcCartesianTransformationOperator& op)
  449. {
  450. aiVector3D loc;
  451. ConvertCartesianPoint(loc,op.LocalOrigin);
  452. aiVector3D x(1.f,0.f,0.f),y(0.f,1.f,0.f),z(0.f,0.f,1.f);
  453. if (op.Axis1) {
  454. ConvertDirection(x,*op.Axis1.Get());
  455. }
  456. if (op.Axis2) {
  457. ConvertDirection(y,*op.Axis2.Get());
  458. }
  459. if (const IFC::IfcCartesianTransformationOperator3D* op2 = op.ToPtr<IFC::IfcCartesianTransformationOperator3D>()) {
  460. if(op2->Axis3) {
  461. ConvertDirection(z,*op2->Axis3.Get());
  462. }
  463. }
  464. aiMatrix4x4 locm;
  465. aiMatrix4x4::Translation(loc,locm);
  466. AssignMatrixAxes(out,x,y,z);
  467. const float sc = op.Scale?op.Scale.Get():1.f;
  468. aiMatrix4x4 s;
  469. aiMatrix4x4::Scaling(aiVector3D(sc,sc,sc),s);
  470. out = locm * out * s;
  471. }
  472. // ------------------------------------------------------------------------------------------------
  473. bool ProcessPolyloop(const IFC::IfcPolyLoop& loop, TempMesh& meshout, ConversionData& conv)
  474. {
  475. size_t cnt = 0;
  476. BOOST_FOREACH(const IFC::IfcCartesianPoint& c, loop.Polygon) {
  477. aiVector3D tmp;
  478. ConvertCartesianPoint(tmp,c);
  479. meshout.verts.push_back(tmp);
  480. ++cnt;
  481. }
  482. // zero- or one- vertex polyloops simply ignored
  483. if (cnt >= 1) {
  484. meshout.vertcnt.push_back(cnt);
  485. return true;
  486. }
  487. if (cnt==1) {
  488. meshout.vertcnt.pop_back();
  489. }
  490. return false;
  491. }
  492. // ------------------------------------------------------------------------------------------------
  493. void ProcessConnectedFaceSet(const IFC::IfcConnectedFaceSet& fset, TempMesh& result, ConversionData& conv)
  494. {
  495. BOOST_FOREACH(const IFC::IfcFace& face, fset.CfsFaces) {
  496. TempMesh meshout;
  497. size_t ob = face.Bounds.size(), cnt = 0;
  498. BOOST_FOREACH(const IFC::IfcFaceBound& bound, face.Bounds) {
  499. if(const IFC::IfcPolyLoop* const polyloop = bound.Bound->ToPtr<IFC::IfcPolyLoop>()) {
  500. if(ProcessPolyloop(*polyloop, meshout, conv)) {
  501. if(bound.ToPtr<IFC::IfcFaceOuterBound>()) {
  502. ob = cnt;
  503. }
  504. ++cnt;
  505. }
  506. }
  507. else {
  508. IFCImporter::LogWarn("skipping unknown IfcFaceBound entity, type is " + bound.Bound->GetClassName());
  509. continue;
  510. }
  511. if(!IsTrue(bound.Orientation)) {
  512. size_t c = 0;
  513. BOOST_FOREACH(unsigned int& i, meshout.vertcnt) {
  514. std::reverse(meshout.verts.begin() + cnt,meshout.verts.begin() + cnt + c);
  515. cnt += c;
  516. }
  517. }
  518. }
  519. result.vertcnt.reserve(meshout.vertcnt.size()+result.vertcnt.size());
  520. if (meshout.vertcnt.size() <= 1) {
  521. result.verts.reserve(meshout.verts.size()+result.verts.size());
  522. std::copy(meshout.verts.begin(),meshout.verts.end(),std::back_inserter(result.verts));
  523. std::copy(meshout.vertcnt.begin(),meshout.vertcnt.end(),std::back_inserter(result.vertcnt));
  524. continue;
  525. }
  526. IFCImporter::LogDebug("fixing polygon with holes for triangulation via ear-cutting");
  527. // each hole results in two extra vertices
  528. result.verts.reserve(meshout.verts.size()+cnt*2+result.verts.size());
  529. // handle polygons with holes. our built in triangulation won't handle them as is, but
  530. // the ear cutting algorithm is solid enough to deal with them if we join the inner
  531. // holes with the outer boundaries by dummy connections.
  532. size_t outer_polygon_start = 0;
  533. // see if one of the polygons is a IfcFaceOuterBound - treats this as the outer boundary.
  534. // sadly we can't rely on it, the docs say 'At most one of the bounds shall be of the type IfcFaceOuterBound'
  535. std::vector<unsigned int>::iterator outer_polygon = meshout.vertcnt.end(), begin=meshout.vertcnt.begin(), iit;
  536. if (ob < face.Bounds.size()) {
  537. outer_polygon = begin + ob;
  538. outer_polygon_start = std::accumulate(begin,outer_polygon,0);
  539. }
  540. else {
  541. float area_outer_polygon = 1e-10f;
  542. // find the polygon with the largest area, it must be the outer bound.
  543. size_t max_vcount = 0;
  544. for(iit = begin; iit != meshout.vertcnt.end(); ++iit) {
  545. ai_assert(*iit);
  546. max_vcount = std::max(max_vcount,static_cast<size_t>(*iit));
  547. }
  548. std::vector<float> temp((max_vcount+2)*4);
  549. size_t vidx = 0;
  550. for(iit = begin; iit != meshout.vertcnt.end(); vidx += *iit++) {
  551. for(size_t vofs = 0, cnt = 0; vofs < *iit; ++vofs) {
  552. const aiVector3D& v = meshout.verts[vidx+vofs];
  553. temp[cnt++] = v.x;
  554. temp[cnt++] = v.y;
  555. temp[cnt++] = v.z;
  556. #ifdef _DEBUG
  557. temp[cnt] = std::numeric_limits<float>::quiet_NaN();
  558. #endif
  559. ++cnt;
  560. }
  561. aiVector3D nor;
  562. NewellNormal<4,4,4>(nor,*iit,&temp[0],&temp[1],&temp[2]);
  563. const float area = nor.SquareLength();
  564. if (area > area_outer_polygon) {
  565. area_outer_polygon = area;
  566. outer_polygon = iit;
  567. outer_polygon_start = vidx;
  568. }
  569. }
  570. }
  571. ai_assert(outer_polygon != meshout.vertcnt.end());
  572. typedef boost::tuple<unsigned int, unsigned int, unsigned int> InsertionPoint;
  573. std::vector< InsertionPoint > insertions(*outer_polygon,boost::make_tuple(0u,0u,0u));
  574. // iterate through all other polyloops and find points in the outer polyloop that are close
  575. size_t vidx = 0;
  576. for(iit = begin; iit != meshout.vertcnt.end(); vidx += *iit++) {
  577. if (iit == outer_polygon) {
  578. continue;
  579. }
  580. size_t best_ofs,best_outer;
  581. float best_dist = 1e10;
  582. for(size_t vofs = 0; vofs < *iit; ++vofs) {
  583. const aiVector3D& v = meshout.verts[vidx+vofs];
  584. for(size_t outer = 0; outer < *outer_polygon; ++outer) {
  585. if (insertions[outer].get<0>()) {
  586. continue;
  587. }
  588. const aiVector3D& o = meshout.verts[outer_polygon_start+outer];
  589. const float d = (o-v).SquareLength();
  590. if (d < best_dist) {
  591. best_dist = d;
  592. best_ofs = vofs;
  593. best_outer = outer;
  594. }
  595. }
  596. }
  597. // we will later insert a hidden connection line right after the closest point in the outer polygon
  598. insertions[best_outer] = boost::make_tuple(*iit,vidx,best_ofs);
  599. }
  600. // now that we collected all vertex connections to be added, build the output polygon
  601. cnt = *outer_polygon;
  602. for(size_t outer = 0; outer < *outer_polygon; ++outer) {
  603. const aiVector3D& o = meshout.verts[outer_polygon_start+outer];
  604. result.verts.push_back(o);
  605. const InsertionPoint& ins = insertions[outer];
  606. if (!ins.get<0>()) {
  607. continue;
  608. }
  609. for(size_t i = ins.get<2>(); i < ins.get<0>(); ++i) {
  610. result.verts.push_back(meshout.verts[ins.get<1>() + i]);
  611. }
  612. for(size_t i = 0; i < ins.get<2>(); ++i) {
  613. result.verts.push_back(meshout.verts[ins.get<1>() + i]);
  614. }
  615. // we need the first vertex of the inner polygon twice as we return to the
  616. // outer loop through the very same connection through which we got there.
  617. result.verts.push_back(meshout.verts[ins.get<1>() + ins.get<2>()]);
  618. // also append a copy of the initial insertion point to be able to continue the outer polygon
  619. result.verts.push_back(o);
  620. cnt += ins.get<0>()+2;
  621. }
  622. result.vertcnt.push_back(cnt);
  623. }
  624. }
  625. // ------------------------------------------------------------------------------------------------
  626. void ProcessPolyLine(const IFC::IfcPolyline& def, TempMesh& meshout, ConversionData& conv)
  627. {
  628. // this won't produce a valid mesh, it just spits out a list of vertices
  629. aiVector3D t;
  630. BOOST_FOREACH(const IFC::IfcCartesianPoint& cp, def.Points) {
  631. ConvertCartesianPoint(t,cp);
  632. meshout.verts.push_back(t);
  633. }
  634. }
  635. // ------------------------------------------------------------------------------------------------
  636. void ProcessClosedProfile(const IFC::IfcArbitraryClosedProfileDef& def, TempMesh& meshout, ConversionData& conv)
  637. {
  638. if(const IFC::IfcPolyline* poly = def.OuterCurve->ToPtr<IFC::IfcPolyline>()) {
  639. ProcessPolyLine(*poly,meshout,conv);
  640. if(meshout.verts.size()>2 && meshout.verts.front() == meshout.verts.back()) {
  641. meshout.verts.pop_back(); // duplicate element, first==last
  642. }
  643. }
  644. else {
  645. IFCImporter::LogWarn("skipping unknown IfcArbitraryClosedProfileDef entity, type is " + def.GetClassName());
  646. return;
  647. }
  648. }
  649. // ------------------------------------------------------------------------------------------------
  650. void ProcessOpenProfile(const IFC::IfcArbitraryOpenProfileDef& def, TempMesh& meshout, ConversionData& conv)
  651. {
  652. if(const IFC::IfcPolyline* poly = def.Curve->ToPtr<IFC::IfcPolyline>()) {
  653. ProcessPolyLine(*poly,meshout,conv);
  654. }
  655. else {
  656. IFCImporter::LogWarn("skipping unknown IfcArbitraryClosedProfileDef entity, type is " + def.GetClassName());
  657. return;
  658. }
  659. }
  660. // ------------------------------------------------------------------------------------------------
  661. void ProcessParametrizedProfile(const IFC::IfcParameterizedProfileDef& def, TempMesh& meshout, ConversionData& conv)
  662. {
  663. if(const IFC::IfcRectangleProfileDef* cprofile = def.ToPtr<IFC::IfcRectangleProfileDef>()) {
  664. const float x = cprofile->XDim*0.5f, y = cprofile->YDim*0.5f;
  665. meshout.verts.reserve(meshout.verts.size()+4);
  666. meshout.verts.push_back( aiVector3D( x, y, 0.f ));
  667. meshout.verts.push_back( aiVector3D(-x, y, 0.f ));
  668. meshout.verts.push_back( aiVector3D(-x,-y, 0.f ));
  669. meshout.verts.push_back( aiVector3D( x,-y, 0.f ));
  670. meshout.vertcnt.push_back(4);
  671. }
  672. else {
  673. IFCImporter::LogWarn("skipping unknown IfcParameterizedProfileDef entity, type is " + def.GetClassName());
  674. return;
  675. }
  676. aiMatrix4x4 trafo;
  677. ConvertAxisPlacement(trafo, *def.Position,conv);
  678. BOOST_FOREACH(aiVector3D& v, meshout.verts) {
  679. v *= trafo;
  680. }
  681. }
  682. // ------------------------------------------------------------------------------------------------
  683. void ProcessExtrudedAreaSolid(const IFC::IfcExtrudedAreaSolid& solid, TempMesh& result, ConversionData& conv)
  684. {
  685. TempMesh meshout;
  686. if(const IFC::IfcArbitraryClosedProfileDef* cprofile = solid.SweptArea->ToPtr<IFC::IfcArbitraryClosedProfileDef>()) {
  687. ProcessClosedProfile(*cprofile,meshout,conv);
  688. }
  689. else if(const IFC::IfcArbitraryOpenProfileDef* copen = solid.SweptArea->ToPtr<IFC::IfcArbitraryOpenProfileDef>()) {
  690. ProcessOpenProfile(*copen,meshout,conv);
  691. }
  692. else if(const IFC::IfcParameterizedProfileDef* cparam = solid.SweptArea->ToPtr<IFC::IfcParameterizedProfileDef>()) {
  693. ProcessParametrizedProfile(*cparam,meshout,conv);
  694. }
  695. else {
  696. IFCImporter::LogWarn("skipping unknown IfcProfileDef entity, type is " + solid.SweptArea->GetClassName());
  697. return;
  698. }
  699. if(meshout.verts.size()<=1) {
  700. return;
  701. }
  702. aiVector3D dir;
  703. ConvertDirection(dir,solid.ExtrudedDirection);
  704. dir *= solid.Depth;
  705. // assuming that `meshout.verts` is now a list of vertex points forming
  706. // the underlying profile, extrude along the given axis, forming new
  707. // triangles.
  708. const std::vector<aiVector3D>& in = meshout.verts;
  709. const size_t size=in.size();
  710. const bool has_area = solid.SweptArea->ProfileType == "AREA" && size>2;
  711. result.verts.reserve(size*(has_area?4:2));
  712. result.vertcnt.reserve(meshout.vertcnt.size()+2);
  713. for(size_t i = 0; i < size; ++i) {
  714. const size_t next = (i+1)%size;
  715. result.vertcnt.push_back(4);
  716. result.verts.push_back(in[i]);
  717. result.verts.push_back(in[next]);
  718. result.verts.push_back(in[next]+dir);
  719. result.verts.push_back(in[i]+dir);
  720. }
  721. if(has_area) {
  722. // leave the triangulation of the profile area to the ear cutting
  723. // implementation in aiProcess_Triangulate - for now we just
  724. // feed in a possibly huge polygon.
  725. for(size_t i = size; i--; ) {
  726. result.verts.push_back(in[i]+dir);
  727. }
  728. for(size_t i = 0; i < size; ++i ) {
  729. result.verts.push_back(in[i]);
  730. }
  731. result.vertcnt.push_back(size);
  732. result.vertcnt.push_back(size);
  733. }
  734. aiMatrix4x4 trafo;
  735. ConvertAxisPlacement(trafo, solid.Position,conv);
  736. aiVector3D vavg;
  737. BOOST_FOREACH(aiVector3D& v, result.verts) {
  738. v *= trafo;
  739. vavg += v;
  740. }
  741. // fixup face orientation.
  742. vavg /= static_cast<float>( result.verts.size() );
  743. size_t c = 0;
  744. BOOST_FOREACH(unsigned int cnt, result.vertcnt) {
  745. if (cnt>2){
  746. const aiVector3D& thisvert = result.verts[c];
  747. const aiVector3D normal((thisvert-result.verts[c+1])^(thisvert-result.verts[c+2]));
  748. if (normal*(thisvert-vavg) < 0) {
  749. std::reverse(result.verts.begin()+c,result.verts.begin()+cnt+c);
  750. }
  751. }
  752. c += cnt;
  753. }
  754. IFCImporter::LogDebug("generate mesh procedurally by extrusion (IfcExtrudedAreaSolid)");
  755. }
  756. // ------------------------------------------------------------------------------------------------
  757. void ProcessSweptAreaSolid(const IFC::IfcSweptAreaSolid& swept, TempMesh& meshout, ConversionData& conv)
  758. {
  759. if(const IFC::IfcExtrudedAreaSolid* solid = swept.ToPtr<IFC::IfcExtrudedAreaSolid>()) {
  760. ProcessExtrudedAreaSolid(*solid,meshout,conv);
  761. }
  762. else {
  763. IFCImporter::LogWarn("skipping unknown IfcSweptAreaSolid entity, type is " + swept.GetClassName());
  764. }
  765. }
  766. // ------------------------------------------------------------------------------------------------
  767. void ProcessBoolean(const IFC::IfcBooleanResult& boolean, TempMesh& meshout, ConversionData& conv)
  768. {
  769. if(const IFC::IfcBooleanClippingResult* const clip = boolean.ToPtr<IFC::IfcBooleanClippingResult>()) {
  770. if(const IFC::IfcBooleanResult* const op0 = clip->FirstOperand->ResolveSelectPtr<IFC::IfcBooleanResult>(conv.db)) {
  771. ProcessBoolean(*op0,meshout,conv);
  772. }
  773. else if (const IFC::IfcSweptAreaSolid* const swept = clip->FirstOperand->ResolveSelectPtr<IFC::IfcSweptAreaSolid>(conv.db)) {
  774. //ProcessSweptAreaSolid(*swept,meshout,conv);
  775. // XXX
  776. }
  777. }
  778. else {
  779. IFCImporter::LogWarn("skipping unknown IfcBooleanResult entity, type is " + boolean.GetClassName());
  780. }
  781. }
  782. // ------------------------------------------------------------------------------------------------
  783. int ConvertShadingMode(const std::string& name)
  784. {
  785. if (name == "BLINN") {
  786. return aiShadingMode_Blinn;
  787. }
  788. else if (name == "FLAT" || name == "NOTDEFINED") {
  789. return aiShadingMode_NoShading;
  790. }
  791. else if (name == "PHONG") {
  792. return aiShadingMode_Phong;
  793. }
  794. IFCImporter::LogWarn("shading mode "+name+" not recognized by Assimp, using Phong instead");
  795. return aiShadingMode_Phong;
  796. }
  797. // ------------------------------------------------------------------------------------------------
  798. unsigned int ProcessMaterials(const IFC::IfcRepresentationItem& item, ConversionData& conv)
  799. {
  800. aiString name;
  801. aiColor4D col;
  802. if (conv.materials.empty()) {
  803. std::auto_ptr<MaterialHelper> mat(new MaterialHelper());
  804. name.Set("<IFCDefault>");
  805. mat->AddProperty(&name,AI_MATKEY_NAME);
  806. col = aiColor4D(0.6f,0.6f,0.6f,1.0f);
  807. mat->AddProperty(&col,1, AI_MATKEY_COLOR_DIFFUSE);
  808. conv.materials.push_back(mat.release());
  809. }
  810. STEP::DB::RefMapRange range = conv.db.GetRefs().equal_range(item.GetID());
  811. for(;range.first != range.second; ++range.first) {
  812. if(const IFC::IfcStyledItem* const styled = conv.db.GetObject((*range.first).second)->ToPtr<IFC::IfcStyledItem>()) {
  813. BOOST_FOREACH(const IFC::IfcPresentationStyleAssignment& as, styled->Styles) {
  814. BOOST_FOREACH(const IFC::IfcPresentationStyleSelect* sel, as.Styles) {
  815. if (const IFC::IfcSurfaceStyle* surf = sel->ResolveSelectPtr<IFC::IfcSurfaceStyle>(conv.db)) {
  816. const std::string side = static_cast<std::string>(surf->Side);
  817. if (side != "BOTH") {
  818. IFCImporter::LogWarn("ignoring surface side marker on IFC::IfcSurfaceStyle: " + side);
  819. }
  820. std::auto_ptr<MaterialHelper> mat(new MaterialHelper());
  821. name.Set((surf->Name? surf->Name.Get() : "IfcSurfaceStyle_Unnamed"));
  822. mat->AddProperty(&name,AI_MATKEY_NAME);
  823. // now see which kinds of surface information are present
  824. BOOST_FOREACH(const IFC::IfcSurfaceStyleElementSelect* sel2, surf->Styles) {
  825. if (const IFC::IfcSurfaceStyleShading* shade = sel2->ResolveSelectPtr<IFC::IfcSurfaceStyleShading>(conv.db)) {
  826. aiColor4D col_base;
  827. ConvertColor(col_base, shade->SurfaceColour);
  828. mat->AddProperty(&col,1, AI_MATKEY_COLOR_DIFFUSE);
  829. if (const IFC::IfcSurfaceStyleRendering* ren = shade->ToPtr<IFC::IfcSurfaceStyleRendering>()) {
  830. if (ren->DiffuseColour) {
  831. ConvertColor(col, ren->DiffuseColour.Get(),conv,&col_base);
  832. mat->AddProperty(&col,1, AI_MATKEY_COLOR_DIFFUSE);
  833. }
  834. if (ren->SpecularColour) {
  835. ConvertColor(col, ren->SpecularColour.Get(),conv,&col_base);
  836. mat->AddProperty(&col,1, AI_MATKEY_COLOR_SPECULAR);
  837. }
  838. if (ren->TransmissionColour) {
  839. ConvertColor(col, ren->TransmissionColour.Get(),conv,&col_base);
  840. mat->AddProperty(&col,1, AI_MATKEY_COLOR_TRANSPARENT);
  841. }
  842. if (ren->ReflectionColour) {
  843. ConvertColor(col, ren->ReflectionColour.Get(),conv,&col_base);
  844. mat->AddProperty(&col,1, AI_MATKEY_COLOR_REFLECTIVE);
  845. }
  846. const int shading = (ren->SpecularHighlight && ren->SpecularColour)?ConvertShadingMode(ren->ReflectanceMethod):aiShadingMode_Gouraud;
  847. mat->AddProperty(&shading,1, AI_MATKEY_SHADING_MODEL);
  848. if (ren->SpecularHighlight) {
  849. if(const EXPRESS::REAL* rt = ren->SpecularHighlight.Get()->ToPtr<EXPRESS::REAL>()) {
  850. // at this point we don't distinguish between the two distinct ways of
  851. // specifying highlight intensities. leave this to the user.
  852. const float e = *rt;
  853. mat->AddProperty(&e,1,AI_MATKEY_SHININESS);
  854. }
  855. else {
  856. IFCImporter::LogWarn("unexpected type error, SpecularHighlight should be a REAL");
  857. }
  858. }
  859. }
  860. }
  861. else if (const IFC::IfcSurfaceStyleWithTextures* tex = sel2->ResolveSelectPtr<IFC::IfcSurfaceStyleWithTextures>(conv.db)) {
  862. // XXX
  863. }
  864. }
  865. conv.materials.push_back(mat.release());
  866. return conv.materials.size()-1;
  867. }
  868. }
  869. }
  870. }
  871. }
  872. return 0;
  873. }
  874. // ------------------------------------------------------------------------------------------------
  875. void ProcessTopologicalItem(const IFC::IfcTopologicalRepresentationItem& topo, std::vector<unsigned int>& mesh_indices, ConversionData& conv)
  876. {
  877. TempMesh meshtmp;
  878. if(const IFC::IfcConnectedFaceSet* fset = topo.ToPtr<IFC::IfcConnectedFaceSet>()) {
  879. ProcessConnectedFaceSet(*fset,meshtmp,conv);
  880. }
  881. else {
  882. IFCImporter::LogWarn("skipping unknown IfcTopologicalRepresentationItem entity, type is " + topo.GetClassName());
  883. return;
  884. }
  885. aiMesh* const mesh = meshtmp.ToMesh();
  886. if(mesh) {
  887. mesh->mMaterialIndex = ProcessMaterials(topo,conv);
  888. mesh_indices.push_back(conv.meshes.size());
  889. conv.meshes.push_back(mesh);
  890. }
  891. }
  892. // ------------------------------------------------------------------------------------------------
  893. void ProcessGeometricItem(const IFC::IfcGeometricRepresentationItem& geo, std::vector<unsigned int>& mesh_indices, ConversionData& conv)
  894. {
  895. TempMesh meshtmp;
  896. if(const IFC::IfcShellBasedSurfaceModel* shellmod = geo.ToPtr<IFC::IfcShellBasedSurfaceModel>()) {
  897. BOOST_FOREACH(const IFC::IfcShell* shell,shellmod->SbsmBoundary) {
  898. try {
  899. const EXPRESS::ENTITY& e = shell->To<IFC::ENTITY>();
  900. const IFC::IfcConnectedFaceSet& fs = conv.db.MustGetObject(e).To<IFC::IfcConnectedFaceSet>();
  901. ProcessConnectedFaceSet(fs,meshtmp,conv);
  902. }
  903. catch(std::bad_cast&) {
  904. IFCImporter::LogWarn("unexpected type error, IfcShell ought to inherit from IfcConnectedFaceSet");
  905. continue;
  906. }
  907. }
  908. }
  909. else if(const IFC::IfcSweptAreaSolid* swept = geo.ToPtr<IFC::IfcSweptAreaSolid>()) {
  910. ProcessSweptAreaSolid(*swept,meshtmp,conv);
  911. }
  912. else if(const IFC::IfcManifoldSolidBrep* brep = geo.ToPtr<IFC::IfcManifoldSolidBrep>()) {
  913. ProcessConnectedFaceSet(brep->Outer,meshtmp,conv);
  914. }
  915. else if(const IFC::IfcBooleanResult* boolean = geo.ToPtr<IFC::IfcBooleanResult>()) {
  916. ProcessBoolean(*boolean,meshtmp,conv);
  917. }
  918. else {
  919. IFCImporter::LogWarn("skipping unknown IfcGeometricRepresentationItem entity, type is " + geo.GetClassName());
  920. return;
  921. }
  922. aiMesh* const mesh = meshtmp.ToMesh();
  923. if(mesh) {
  924. mesh->mMaterialIndex = ProcessMaterials(geo,conv);
  925. mesh_indices.push_back(conv.meshes.size());
  926. conv.meshes.push_back(mesh);
  927. }
  928. }
  929. // ------------------------------------------------------------------------------------------------
  930. void AssignAddedMeshes(std::vector<unsigned int>& mesh_indices,aiNode* nd,ConversionData& conv)
  931. {
  932. if (!mesh_indices.empty()) {
  933. // make unique
  934. std::sort(mesh_indices.begin(),mesh_indices.end());
  935. std::vector<unsigned int>::iterator it_end = std::unique(mesh_indices.begin(),mesh_indices.end());
  936. const size_t size = std::distance(mesh_indices.begin(),it_end);
  937. nd->mNumMeshes = size;
  938. nd->mMeshes = new unsigned int[nd->mNumMeshes];
  939. for(unsigned int i = 0; i < nd->mNumMeshes; ++i) {
  940. nd->mMeshes[i] = mesh_indices[i];
  941. }
  942. }
  943. }
  944. // ------------------------------------------------------------------------------------------------
  945. bool TryQueryMeshCache(const IFC::IfcRepresentationItem& item, std::vector<unsigned int>& mesh_indices, ConversionData& conv)
  946. {
  947. ConversionData::MeshCache::const_iterator it = conv.cached_meshes.find(&item);
  948. if (it != conv.cached_meshes.end()) {
  949. std::copy((*it).second.begin(),(*it).second.end(),std::back_inserter(mesh_indices));
  950. return true;
  951. }
  952. return false;
  953. }
  954. // ------------------------------------------------------------------------------------------------
  955. void PopulateMeshCache(const IFC::IfcRepresentationItem& item, const std::vector<unsigned int>& mesh_indices, ConversionData& conv)
  956. {
  957. conv.cached_meshes[&item] = mesh_indices;
  958. }
  959. // ------------------------------------------------------------------------------------------------
  960. bool ProcessRepresentationItem(const IFC::IfcRepresentationItem& item, std::vector<unsigned int>& mesh_indices, ConversionData& conv)
  961. {
  962. // XXX should we make a choice? handle only one of them?
  963. if(const IFC::IfcTopologicalRepresentationItem* const topo = item.ToPtr<IFC::IfcTopologicalRepresentationItem>()) {
  964. if (!TryQueryMeshCache(item,mesh_indices,conv)) {
  965. ProcessTopologicalItem(*topo,mesh_indices,conv);
  966. PopulateMeshCache(item,mesh_indices,conv);
  967. }
  968. }
  969. else if(const IFC::IfcGeometricRepresentationItem* const geo = item.ToPtr<IFC::IfcGeometricRepresentationItem>()) {
  970. if (!TryQueryMeshCache(item,mesh_indices,conv)) {
  971. ProcessGeometricItem(*geo,mesh_indices,conv);
  972. PopulateMeshCache(item,mesh_indices,conv);
  973. }
  974. }
  975. else {
  976. return false;
  977. }
  978. return true;
  979. }
  980. // ------------------------------------------------------------------------------------------------
  981. void ResolveObjectPlacement(aiMatrix4x4& m, const IFC::IfcObjectPlacement& place, ConversionData& conv)
  982. {
  983. if (const IFC::IfcLocalPlacement* const local = place.ToPtr<IFC::IfcLocalPlacement>()){
  984. ConvertAxisPlacement(m, *local->RelativePlacement, conv);
  985. if (local->PlacementRelTo) {
  986. aiMatrix4x4 tmp;
  987. ResolveObjectPlacement(tmp,local->PlacementRelTo.Get(),conv);
  988. m = tmp * m;
  989. }
  990. }
  991. else {
  992. IFCImporter::LogWarn("skipping unknown IfcObjectPlacement entity, type is " + place.GetClassName());
  993. }
  994. }
  995. // ------------------------------------------------------------------------------------------------
  996. void GetAbsTransform(aiMatrix4x4& out, const aiNode* nd, ConversionData& conv)
  997. {
  998. aiMatrix4x4 t;
  999. if (nd->mParent) {
  1000. GetAbsTransform(t,nd->mParent,conv);
  1001. }
  1002. out = t*nd->mTransformation;
  1003. }
  1004. // ------------------------------------------------------------------------------------------------
  1005. void ProcessMappedItem(const IFC::IfcMappedItem& mapped, aiNode* nd_src, std::vector< aiNode* >& subnodes_src, ConversionData& conv)
  1006. {
  1007. // insert a custom node here, the cartesian transform operator is simply a conventional transformation matrix
  1008. std::auto_ptr<aiNode> nd(new aiNode());
  1009. nd->mName.Set("MappedItem");
  1010. std::vector<unsigned int> meshes;
  1011. const IFC::IfcRepresentation& repr = mapped.MappingSource->MappedRepresentation;
  1012. BOOST_FOREACH(const IFC::IfcRepresentationItem& item, repr.Items) {
  1013. if(!ProcessRepresentationItem(item,meshes,conv)) {
  1014. IFCImporter::LogWarn("skipping unknown IfcMappedItem entity, type is " + item.GetClassName());
  1015. }
  1016. }
  1017. AssignAddedMeshes(meshes,nd.get(),conv);
  1018. // handle the cartesian operator
  1019. aiMatrix4x4 m;
  1020. ConvertTransformOperator(m, *mapped.MappingTarget);
  1021. aiMatrix4x4 msrc;
  1022. ConvertAxisPlacement(msrc,*mapped.MappingSource->MappingOrigin,conv);
  1023. aiMatrix4x4 minv = msrc;
  1024. minv.Inverse();
  1025. //aiMatrix4x4 correct;
  1026. //GetAbsTransform(correct,nd_src,conv);
  1027. nd->mTransformation = nd_src->mTransformation * minv * m * msrc;
  1028. subnodes_src.push_back(nd.release());
  1029. }
  1030. // ------------------------------------------------------------------------------------------------
  1031. void ProcessProductRepresentation(const IFC::IfcProduct& el, aiNode* nd, std::vector< aiNode* >& subnodes, ConversionData& conv)
  1032. {
  1033. if(!el.Representation) {
  1034. return;
  1035. }
  1036. if(conv.settings.skipSpaceRepresentations) {
  1037. if(const IFC::IfcSpace* const space = el.ToPtr<IFC::IfcSpace>()) {
  1038. IFCImporter::LogWarn("skipping space representation due to importer settings");
  1039. return;
  1040. }
  1041. }
  1042. std::vector<unsigned int> meshes;
  1043. BOOST_FOREACH(const IFC::IfcRepresentation& repr, el.Representation.Get()->Representations) {
  1044. if (conv.settings.skipCurveRepresentations && repr.RepresentationType && repr.RepresentationType.Get() == "Curve2D") {
  1045. IFCImporter::LogWarn("skipping Curve2D representation item due to importer settings");
  1046. return;
  1047. }
  1048. BOOST_FOREACH(const IFC::IfcRepresentationItem& item, repr.Items) {
  1049. if(!ProcessRepresentationItem(item,meshes,conv)) {
  1050. if(const IFC::IfcMappedItem* const geo = item.ToPtr<IFC::IfcMappedItem>()) {
  1051. ProcessMappedItem(*geo,nd,subnodes,conv);
  1052. }
  1053. else {
  1054. IFCImporter::LogWarn("skipping unknown IfcRepresentationItem entity, type is " + item.GetClassName());
  1055. }
  1056. }
  1057. }
  1058. }
  1059. AssignAddedMeshes(meshes,nd,conv);
  1060. }
  1061. // ------------------------------------------------------------------------------------------------
  1062. aiNode* ProcessSpatialStructure(aiNode* parent, const IFC::IfcProduct& el, ConversionData& conv)
  1063. {
  1064. const STEP::DB::RefMap& refs = conv.db.GetRefs();
  1065. // add an output node for this spatial structure
  1066. std::auto_ptr<aiNode> nd(new aiNode());
  1067. nd->mName.Set(el.GetClassName()+"_"+(el.Name?el.Name:el.GlobalId));
  1068. nd->mParent = parent;
  1069. if(el.ObjectPlacement) {
  1070. ResolveObjectPlacement(nd->mTransformation,el.ObjectPlacement.Get(),conv);
  1071. }
  1072. // convert everything contained directly within this structure,
  1073. // this may result in more nodes.
  1074. std::vector< aiNode* > subnodes;
  1075. try {
  1076. ProcessProductRepresentation(el,nd.get(),subnodes,conv);
  1077. // locate aggregates and 'contained-in-here'-elements of this spatial structure and add them in recursively
  1078. STEP::DB::RefMapRange range = refs.equal_range(el.GetID());
  1079. for(STEP::DB::RefMapRange range2=range;range2.first != range.second; ++range2.first) {
  1080. if(const IFC::IfcRelContainedInSpatialStructure* const cont = conv.db.GetObject((*range2.first).second)->
  1081. ToPtr<IFC::IfcRelContainedInSpatialStructure>()) {
  1082. BOOST_FOREACH(const IFC::IfcProduct& pro, cont->RelatedElements) {
  1083. subnodes.push_back( ProcessSpatialStructure(nd.get(),pro,conv) );
  1084. }
  1085. break;
  1086. }
  1087. }
  1088. for(;range.first != range.second; ++range.first) {
  1089. if(const IFC::IfcRelAggregates* const aggr = conv.db.GetObject((*range.first).second)->ToPtr<IFC::IfcRelAggregates>()) {
  1090. // move aggregate elements to a separate node since they are semantically different than elements that are merely 'contained'
  1091. std::auto_ptr<aiNode> nd_aggr(new aiNode());
  1092. nd_aggr->mName.Set("$Aggregates");
  1093. nd_aggr->mParent = nd.get();
  1094. nd_aggr->mChildren = new aiNode*[aggr->RelatedObjects.size()]();
  1095. BOOST_FOREACH(const IFC::IfcObjectDefinition& def, aggr->RelatedObjects) {
  1096. if(const IFC::IfcProduct* const prod = def.ToPtr<IFC::IfcProduct>()) {
  1097. nd_aggr->mChildren[nd_aggr->mNumChildren++] = ProcessSpatialStructure(nd_aggr.get(),*prod,conv);
  1098. }
  1099. }
  1100. subnodes.push_back( nd_aggr.release() );
  1101. break;
  1102. }
  1103. }
  1104. if (subnodes.size()) {
  1105. nd->mChildren = new aiNode*[subnodes.size()]();
  1106. BOOST_FOREACH(aiNode* nd2, subnodes) {
  1107. nd->mChildren[nd->mNumChildren++] = nd2;
  1108. nd2->mParent = nd.get();
  1109. }
  1110. }
  1111. }
  1112. catch(...) {
  1113. // it hurts, but I don't want to pull boost::ptr_vector into -noboost only for these few spots here
  1114. std::for_each(subnodes.begin(),subnodes.end(),delete_fun<aiNode>());
  1115. throw;
  1116. }
  1117. return nd.release();
  1118. }
  1119. // ------------------------------------------------------------------------------------------------
  1120. void ProcessSpatialStructures(ConversionData& conv)
  1121. {
  1122. // process all products in the file. it is reasonable to assume that a
  1123. // file that is relevant for us contains at least a site or a building.
  1124. const STEP::DB::ObjectMapByType& map = conv.db.GetObjectsByType();
  1125. STEP::DB::ObjectMapRange range = map.equal_range("ifcsite");
  1126. if (range.first == map.end()) {
  1127. range = map.equal_range("ifcbuilding");
  1128. if (range.first == map.end()) {
  1129. // no site, no building - try all ids. this will take ages, but it should rarely happen.
  1130. range = STEP::DB::ObjectMapRange(map.begin(),map.end());
  1131. }
  1132. }
  1133. for(;range.first != range.second; ++range.first) {
  1134. const IFC::IfcSpatialStructureElement* const prod = (*range.first).second->ToPtr<IFC::IfcSpatialStructureElement>();
  1135. if(!prod) {
  1136. continue;
  1137. }
  1138. IFCImporter::LogDebug("looking at spatial structure `" + (prod->Name ? prod->Name.Get() : "unnamed") + "`" + (prod->ObjectType? " which is of type " + prod->ObjectType.Get():""));
  1139. // the primary site is referenced by an IFCRELAGGREGATES element which assigns it to the IFCPRODUCT
  1140. const STEP::DB::RefMap& refs = conv.db.GetRefs();
  1141. STEP::DB::RefMapRange range = refs.equal_range(conv.proj.GetID());
  1142. for(;range.first != range.second; ++range.first) {
  1143. if(const IFC::IfcRelAggregates* const aggr = conv.db.GetObject((*range.first).second)->ToPtr<IFC::IfcRelAggregates>()) {
  1144. BOOST_FOREACH(const IFC::IfcObjectDefinition& def, aggr->RelatedObjects) {
  1145. // comparing pointer values is not sufficient, we would need to cast them to the same type first
  1146. // as there is multiple inheritance in the game.
  1147. if (def.GlobalId == prod->GlobalId) {
  1148. IFCImporter::LogDebug("selecting this spatial structure as root structure");
  1149. // got it, this is the primary site.
  1150. conv.out->mRootNode = ProcessSpatialStructure(NULL,*prod,conv);
  1151. return;
  1152. }
  1153. }
  1154. }
  1155. }
  1156. }
  1157. IFCImporter::ThrowException("Failed to determine primary site element");
  1158. }
  1159. // ------------------------------------------------------------------------------------------------
  1160. void MakeTreeRelative(aiNode* start, const aiMatrix4x4& combined)
  1161. {
  1162. // combined is the parent's absolute transformation matrix
  1163. aiMatrix4x4 old = start->mTransformation;
  1164. if (!combined.IsIdentity()) {
  1165. start->mTransformation = aiMatrix4x4(combined).Inverse() * start->mTransformation;
  1166. }
  1167. // All nodes store absolute transformations right now, so we need to make them relative
  1168. for (unsigned int i = 0; i < start->mNumChildren; ++i) {
  1169. MakeTreeRelative(start->mChildren[i],old);
  1170. }
  1171. }
  1172. // ------------------------------------------------------------------------------------------------
  1173. void MakeTreeRelative(ConversionData& conv)
  1174. {
  1175. MakeTreeRelative(conv.out->mRootNode,aiMatrix4x4());
  1176. }
  1177. } // !anon
  1178. #endif