IFCLoader.cpp 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054
  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 <iterator>
  39. #include <boost/tuple/tuple.hpp>
  40. #include "IFCLoader.h"
  41. #include "STEPFileReader.h"
  42. #include "IFCReaderGen.h"
  43. #include "StreamReader.h"
  44. #include "MemoryIOWrapper.h"
  45. #include "ProcessHelper.h"
  46. #include "PolyTools.h"
  47. using namespace Assimp;
  48. using namespace Assimp::Formatter;
  49. namespace EXPRESS = STEP::EXPRESS;
  50. template<> const std::string LogFunctions<IFCImporter>::log_prefix = "IFC: ";
  51. /* DO NOT REMOVE this comment block. The genentitylist.sh script
  52. * just looks for names adhering to the IFC :: IfcSomething naming scheme
  53. * and includes all matches in the whitelist for code-generation. Thus,
  54. * all entity classes that are only indirectly referenced need to be
  55. * mentioned explicitly.
  56. IFC::IfcRepresentationMap
  57. IFC::IfcProductRepresentation
  58. IFC::IfcUnitAssignment
  59. IFC::IfcClosedShell
  60. IFC::IfcDoor
  61. */
  62. namespace {
  63. // helper for std::for_each to delete all heap-allocated items in a container
  64. template<typename T>
  65. struct delete_fun
  66. {
  67. void operator()(T* del) {
  68. delete del;
  69. }
  70. };
  71. // ------------------------------------------------------------------------------------------------
  72. // Temporary representation of an opening in a wall or a floor
  73. // ------------------------------------------------------------------------------------------------
  74. struct TempMesh;
  75. struct TempOpening
  76. {
  77. const IFC::IfcExtrudedAreaSolid* solid;
  78. aiVector3D extrusionDir;
  79. boost::shared_ptr<TempMesh> profileMesh;
  80. // ------------------------------------------------------------------------------
  81. TempOpening(const IFC::IfcExtrudedAreaSolid* solid,aiVector3D extrusionDir,boost::shared_ptr<TempMesh> profileMesh)
  82. : solid(solid)
  83. , extrusionDir(extrusionDir)
  84. , profileMesh(profileMesh)
  85. {
  86. }
  87. // ------------------------------------------------------------------------------
  88. void Transform(const aiMatrix4x4& mat); // defined later since TempMesh is not complete yet
  89. };
  90. // ------------------------------------------------------------------------------------------------
  91. // Intermediate data storage during conversion. Keeps everything and a bit more.
  92. // ------------------------------------------------------------------------------------------------
  93. struct ConversionData
  94. {
  95. ConversionData(const STEP::DB& db, const IFC::IfcProject& proj, aiScene* out,const IFCImporter::Settings& settings)
  96. : len_scale(1.0)
  97. , angle_scale(1.0)
  98. , db(db)
  99. , proj(proj)
  100. , out(out)
  101. , settings(settings)
  102. , apply_openings()
  103. , collect_openings()
  104. {}
  105. ~ConversionData() {
  106. std::for_each(meshes.begin(),meshes.end(),delete_fun<aiMesh>());
  107. std::for_each(materials.begin(),materials.end(),delete_fun<aiMaterial>());
  108. }
  109. float len_scale, angle_scale;
  110. bool plane_angle_in_radians;
  111. const STEP::DB& db;
  112. const IFC::IfcProject& proj;
  113. aiScene* out;
  114. aiMatrix4x4 wcs;
  115. std::vector<aiMesh*> meshes;
  116. std::vector<aiMaterial*> materials;
  117. typedef std::map<const IFC::IfcRepresentationItem*, std::vector<unsigned int> > MeshCache;
  118. MeshCache cached_meshes;
  119. const IFCImporter::Settings& settings;
  120. // Intermediate arrays used to resolve openings in walls: only one of them
  121. // can be given at a time. apply_openings if present if the current element
  122. // is a wall and needs its openings to be poured into its geometry while
  123. // collect_openings is present only if the current element is an
  124. // IfcOpeningElement, for which all the geometry needs to be preserved
  125. // for later processing by a parent, which is a wall.
  126. std::vector<TempOpening>* apply_openings;
  127. std::vector<TempOpening>* collect_openings;
  128. };
  129. // ------------------------------------------------------------------------------------------------
  130. // Helper used during mesh construction. Aids at creating aiMesh'es out of relatively few polygons.
  131. // ------------------------------------------------------------------------------------------------
  132. struct TempMesh
  133. {
  134. std::vector<aiVector3D> verts;
  135. std::vector<unsigned int> vertcnt;
  136. // ------------------------------------------------------------------------------
  137. aiMesh* ToMesh() {
  138. ai_assert(verts.size() == std::accumulate(vertcnt.begin(),vertcnt.end(),0));
  139. if (verts.empty()) {
  140. return NULL;
  141. }
  142. std::auto_ptr<aiMesh> mesh(new aiMesh());
  143. // copy vertices
  144. mesh->mNumVertices = static_cast<unsigned int>(verts.size());
  145. mesh->mVertices = new aiVector3D[mesh->mNumVertices];
  146. std::copy(verts.begin(),verts.end(),mesh->mVertices);
  147. // and build up faces
  148. mesh->mNumFaces = static_cast<unsigned int>(vertcnt.size());
  149. mesh->mFaces = new aiFace[mesh->mNumFaces];
  150. for(unsigned int i = 0, acc = 0; i < mesh->mNumFaces; ++i) {
  151. aiFace& f = mesh->mFaces[i];
  152. f.mNumIndices = vertcnt[i];
  153. f.mIndices = new unsigned int[f.mNumIndices];
  154. for(unsigned int a = 0; a < f.mNumIndices; ++a) {
  155. f.mIndices[a] = acc++;
  156. }
  157. }
  158. return mesh.release();
  159. }
  160. // ------------------------------------------------------------------------------
  161. void Clear() {
  162. verts.clear();
  163. vertcnt.clear();
  164. }
  165. // ------------------------------------------------------------------------------
  166. void Transform(const aiMatrix4x4& mat) {
  167. BOOST_FOREACH(aiVector3D& v, verts) {
  168. v *= mat;
  169. }
  170. }
  171. // ------------------------------------------------------------------------------
  172. aiVector3D Center() {
  173. return std::accumulate(verts.begin(),verts.end(),aiVector3D(0.f,0.f,0.f)) / static_cast<float>(verts.size());
  174. }
  175. };
  176. // ------------------------------------------------------------------------------
  177. void TempOpening::Transform(const aiMatrix4x4& mat)
  178. {
  179. if(profileMesh) {
  180. profileMesh->Transform(mat);
  181. }
  182. extrusionDir *= aiMatrix3x3(mat);
  183. }
  184. // forward declarations
  185. float ConvertSIPrefix(const std::string& prefix);
  186. void SetUnits(ConversionData& conv);
  187. void ConvertAxisPlacement(aiMatrix4x4& out, const IFC::IfcAxis2Placement& in, ConversionData& conv);
  188. void SetCoordinateSpace(ConversionData& conv);
  189. void ProcessSpatialStructures(ConversionData& conv);
  190. aiNode* ProcessSpatialStructure(aiNode* parent, const IFC::IfcProduct& el ,ConversionData& conv);
  191. void ProcessProductRepresentation(const IFC::IfcProduct& el, aiNode* nd, ConversionData& conv);
  192. void MakeTreeRelative(ConversionData& conv);
  193. void ConvertUnit(const EXPRESS::DataType* dt,ConversionData& conv);
  194. void ProcessSweptAreaSolid(const IFC::IfcSweptAreaSolid& swept, TempMesh& meshout, ConversionData& conv);
  195. } // anon
  196. // ------------------------------------------------------------------------------------------------
  197. // Constructor to be privately used by Importer
  198. IFCImporter::IFCImporter()
  199. {}
  200. // ------------------------------------------------------------------------------------------------
  201. // Destructor, private as well
  202. IFCImporter::~IFCImporter()
  203. {
  204. }
  205. // ------------------------------------------------------------------------------------------------
  206. // Returns whether the class can handle the format of the given file.
  207. bool IFCImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler, bool checkSig) const
  208. {
  209. const std::string& extension = GetExtension(pFile);
  210. if (extension == "ifc") {
  211. return true;
  212. }
  213. else if ((!extension.length() || checkSig) && pIOHandler) {
  214. // note: this is the common identification for STEP-encoded files, so
  215. // it is only unambiguous as long as we don't support any further
  216. // file formats with STEP as their encoding.
  217. const char* tokens[] = {"ISO-10303-21"};
  218. return SearchFileHeaderForToken(pIOHandler,pFile,tokens,1);
  219. }
  220. return false;
  221. }
  222. // ------------------------------------------------------------------------------------------------
  223. // List all extensions handled by this loader
  224. void IFCImporter::GetExtensionList(std::set<std::string>& app)
  225. {
  226. app.insert("ifc");
  227. }
  228. // ------------------------------------------------------------------------------------------------
  229. // Setup configuration properties for the loader
  230. void IFCImporter::SetupProperties(const Importer* pImp)
  231. {
  232. settings.skipSpaceRepresentations = pImp->GetPropertyBool(AI_CONFIG_IMPORT_IFC_SKIP_SPACE_REPRESENTATIONS,true);
  233. settings.skipCurveRepresentations = pImp->GetPropertyBool(AI_CONFIG_IMPORT_IFC_SKIP_CURVE_REPRESENTATIONS,true);
  234. }
  235. // ------------------------------------------------------------------------------------------------
  236. // Imports the given file into the given scene structure.
  237. void IFCImporter::InternReadFile( const std::string& pFile,
  238. aiScene* pScene, IOSystem* pIOHandler)
  239. {
  240. boost::shared_ptr<IOStream> stream(pIOHandler->Open(pFile));
  241. if (!stream) {
  242. ThrowException("Could not open file for reading");
  243. }
  244. boost::scoped_ptr<STEP::DB> db(STEP::ReadFileHeader(stream));
  245. const STEP::HeaderInfo& head = const_cast<const STEP::DB&>(*db).GetHeader();
  246. if(!head.fileSchema.size() || head.fileSchema.substr(0,3) != "IFC") {
  247. ThrowException("Unrecognized file schema: " + head.fileSchema);
  248. }
  249. if (!DefaultLogger::isNullLogger()) {
  250. LogDebug("File schema is \'" + head.fileSchema + '\'');
  251. if (head.timestamp.length()) {
  252. LogDebug("Timestamp \'" + head.timestamp + '\'');
  253. }
  254. if (head.app.length()) {
  255. LogDebug("Application/Exporter identline is \'" + head.app + '\'');
  256. }
  257. }
  258. // obtain a copy of the machine-generated IFC scheme
  259. EXPRESS::ConversionSchema schema;
  260. IFC::GetSchema(schema);
  261. // feed the IFC schema into the reader and pre-parse all lines
  262. STEP::ReadFile(*db, schema);
  263. const STEP::LazyObject* proj = db->GetObject("ifcproject");
  264. if (!proj) {
  265. ThrowException("missing IfcProject entity");
  266. }
  267. ConversionData conv(*db,proj->To<IFC::IfcProject>(),pScene,settings);
  268. SetUnits(conv);
  269. SetCoordinateSpace(conv);
  270. ProcessSpatialStructures(conv);
  271. MakeTreeRelative(conv);
  272. // NOTE - this is a stress test for the importer, but it works only
  273. // in a build with no entities disabled. See
  274. // scripts/IFCImporter/CPPGenerator.py
  275. // for more information.
  276. #ifdef ASSIMP_IFC_TEST
  277. db->EvaluateAll();
  278. #endif
  279. // do final data copying
  280. if (conv.meshes.size()) {
  281. pScene->mNumMeshes = static_cast<unsigned int>(conv.meshes.size());
  282. pScene->mMeshes = new aiMesh*[pScene->mNumMeshes]();
  283. std::copy(conv.meshes.begin(),conv.meshes.end(),pScene->mMeshes);
  284. // needed to keep the d'tor from burning us
  285. conv.meshes.clear();
  286. }
  287. if (conv.materials.size()) {
  288. pScene->mNumMaterials = static_cast<unsigned int>(conv.materials.size());
  289. pScene->mMaterials = new aiMaterial*[pScene->mNumMaterials]();
  290. std::copy(conv.materials.begin(),conv.materials.end(),pScene->mMaterials);
  291. // needed to keep the d'tor from burning us
  292. conv.materials.clear();
  293. }
  294. // apply world coordinate system (which includes the scaling to convert to meters and a -90 degrees rotation around x)
  295. aiMatrix4x4 scale, rot;
  296. aiMatrix4x4::Scaling(aiVector3D(conv.len_scale,conv.len_scale,conv.len_scale),scale);
  297. aiMatrix4x4::RotationX(-AI_MATH_HALF_PI_F,rot);
  298. pScene->mRootNode->mTransformation = rot * scale * conv.wcs * pScene->mRootNode->mTransformation;
  299. // this must be last because objects are evaluated lazily as we process them
  300. if ( !DefaultLogger::isNullLogger() ){
  301. LogDebug((Formatter::format(),"STEP: evaluated ",db->GetEvaluatedObjectCount()," object records"));
  302. }
  303. }
  304. namespace {
  305. // ------------------------------------------------------------------------------------------------
  306. bool IsTrue(const EXPRESS::BOOLEAN& in)
  307. {
  308. return (std::string)in == "TRUE" || (std::string)in == "T";
  309. }
  310. // ------------------------------------------------------------------------------------------------
  311. float ConvertSIPrefix(const std::string& prefix)
  312. {
  313. if (prefix == "EXA") {
  314. return 1e18f;
  315. }
  316. else if (prefix == "PETA") {
  317. return 1e15f;
  318. }
  319. else if (prefix == "TERA") {
  320. return 1e12f;
  321. }
  322. else if (prefix == "GIGA") {
  323. return 1e9f;
  324. }
  325. else if (prefix == "MEGA") {
  326. return 1e6f;
  327. }
  328. else if (prefix == "KILO") {
  329. return 1e3f;
  330. }
  331. else if (prefix == "HECTO") {
  332. return 1e2f;
  333. }
  334. else if (prefix == "DECA") {
  335. return 1e-0f;
  336. }
  337. else if (prefix == "DECI") {
  338. return 1e-1f;
  339. }
  340. else if (prefix == "CENTI") {
  341. return 1e-2f;
  342. }
  343. else if (prefix == "MILLI") {
  344. return 1e-3f;
  345. }
  346. else if (prefix == "MICRO") {
  347. return 1e-6f;
  348. }
  349. else if (prefix == "NANO") {
  350. return 1e-9f;
  351. }
  352. else if (prefix == "PICO") {
  353. return 1e-12f;
  354. }
  355. else if (prefix == "FEMTO") {
  356. return 1e-15f;
  357. }
  358. else if (prefix == "ATTO") {
  359. return 1e-18f;
  360. }
  361. else {
  362. IFCImporter::LogError("Unrecognized SI prefix: " + prefix);
  363. return 1;
  364. }
  365. }
  366. // ------------------------------------------------------------------------------------------------
  367. void ConvertUnit(const IFC::IfcNamedUnit& unit,ConversionData& conv)
  368. {
  369. if(const IFC::IfcSIUnit* const si = unit.ToPtr<IFC::IfcSIUnit>()) {
  370. if(si->UnitType == "LENGTHUNIT") {
  371. conv.len_scale = si->Prefix ? ConvertSIPrefix(si->Prefix) : 1.f;
  372. IFCImporter::LogDebug("got units used for lengths");
  373. }
  374. if(si->UnitType == "PLANEANGLEUNIT") {
  375. if (si->Name != "RADIAN") {
  376. IFCImporter::LogWarn("expected base unit for angles to be radian");
  377. }
  378. }
  379. }
  380. else if(const IFC::IfcConversionBasedUnit* const convu = unit.ToPtr<IFC::IfcConversionBasedUnit>()) {
  381. if(convu->UnitType == "PLANEANGLEUNIT") {
  382. try {
  383. conv.angle_scale = convu->ConversionFactor->ValueComponent->To<EXPRESS::REAL>();
  384. ConvertUnit(convu->ConversionFactor->UnitComponent,conv);
  385. IFCImporter::LogDebug("got units used for angles");
  386. }
  387. catch(std::bad_cast&) {
  388. IFCImporter::LogError("skipping unknown IfcConversionBasedUnit.ValueComponent entry - expected REAL");
  389. }
  390. }
  391. }
  392. }
  393. // ------------------------------------------------------------------------------------------------
  394. void ConvertUnit(const EXPRESS::DataType* dt,ConversionData& conv)
  395. {
  396. try {
  397. const EXPRESS::ENTITY& e = dt->To<IFC::ENTITY>();
  398. const IFC::IfcNamedUnit& unit = e.ResolveSelect<IFC::IfcNamedUnit>(conv.db);
  399. if(unit.UnitType != "LENGTHUNIT" && unit.UnitType != "PLANEANGLEUNIT") {
  400. return;
  401. }
  402. ConvertUnit(unit,conv);
  403. }
  404. catch(std::bad_cast&) {
  405. // not entity, somehow
  406. IFCImporter::LogError("skipping unknown IfcUnit entry - expected entity");
  407. }
  408. }
  409. // ------------------------------------------------------------------------------------------------
  410. void SetUnits(ConversionData& conv)
  411. {
  412. // see if we can determine the coordinate space used to express.
  413. for(size_t i = 0; i < conv.proj.UnitsInContext->Units.size(); ++i ) {
  414. ConvertUnit(conv.proj.UnitsInContext->Units[i],conv);
  415. }
  416. }
  417. // ------------------------------------------------------------------------------------------------
  418. void ConvertColor(aiColor4D& out, const IFC::IfcColourRgb& in)
  419. {
  420. out.r = in.Red;
  421. out.g = in.Green;
  422. out.b = in.Blue;
  423. out.a = 1.f;
  424. }
  425. // ------------------------------------------------------------------------------------------------
  426. void ConvertColor(aiColor4D& out, const IFC::IfcColourOrFactor* in,ConversionData& conv,const aiColor4D* base)
  427. {
  428. if (const EXPRESS::REAL* const r = in->ToPtr<EXPRESS::REAL>()) {
  429. out.r = out.g = out.b = *r;
  430. if(base) {
  431. out.r *= base->r;
  432. out.g *= base->g;
  433. out.b *= base->b;
  434. out.a = base->a;
  435. }
  436. else out.a = 1.0;
  437. }
  438. else if (const IFC::IfcColourRgb* const rgb = in->ResolveSelectPtr<IFC::IfcColourRgb>(conv.db)) {
  439. ConvertColor(out,*rgb);
  440. }
  441. else {
  442. IFCImporter::LogWarn("skipping unknown IfcColourOrFactor entity");
  443. }
  444. }
  445. // ------------------------------------------------------------------------------------------------
  446. void ConvertCartesianPoint(aiVector3D& out, const IFC::IfcCartesianPoint& in)
  447. {
  448. out = aiVector3D();
  449. for(size_t i = 0; i < in.Coordinates.size(); ++i) {
  450. out[i] = in.Coordinates[i];
  451. }
  452. }
  453. // ------------------------------------------------------------------------------------------------
  454. void ConvertDirection(aiVector3D& out, const IFC::IfcDirection& in)
  455. {
  456. out = aiVector3D();
  457. for(size_t i = 0; i < in.DirectionRatios.size(); ++i) {
  458. out[i] = in.DirectionRatios[i];
  459. }
  460. const float len = out.Length();
  461. if (len<1e-6) {
  462. IFCImporter::LogWarn("direction vector too small, normalizing would result in a division by zero");
  463. return;
  464. }
  465. out /= len;
  466. }
  467. // ------------------------------------------------------------------------------------------------
  468. void AssignMatrixAxes(aiMatrix4x4& out, const aiVector3D& x, const aiVector3D& y, const aiVector3D& z)
  469. {
  470. out.a1 = x.x;
  471. out.b1 = x.y;
  472. out.c1 = x.z;
  473. out.a2 = y.x;
  474. out.b2 = y.y;
  475. out.c2 = y.z;
  476. out.a3 = z.x;
  477. out.b3 = z.y;
  478. out.c3 = z.z;
  479. }
  480. // ------------------------------------------------------------------------------------------------
  481. void ConvertAxisPlacement(aiMatrix4x4& out, const IFC::IfcAxis2Placement3D& in, ConversionData& conv)
  482. {
  483. aiVector3D loc;
  484. ConvertCartesianPoint(loc,in.Location);
  485. aiVector3D z(0.f,0.f,1.f),r(1.f,0.f,0.f),x;
  486. if (in.Axis) {
  487. ConvertDirection(z,*in.Axis.Get());
  488. }
  489. if (in.RefDirection) {
  490. ConvertDirection(r,*in.RefDirection.Get());
  491. }
  492. aiVector3D v = r.Normalize();
  493. aiVector3D tmpx = z * (v*z);
  494. x = (v-tmpx).Normalize();
  495. aiVector3D y = (z^x);
  496. aiMatrix4x4::Translation(loc,out);
  497. AssignMatrixAxes(out,x,y,z);
  498. }
  499. // ------------------------------------------------------------------------------------------------
  500. void ConvertAxisPlacement(aiMatrix4x4& out, const IFC::IfcAxis2Placement2D& in, ConversionData& conv)
  501. {
  502. aiVector3D loc;
  503. ConvertCartesianPoint(loc,in.Location);
  504. aiVector3D x(1.f,0.f,0.f);
  505. if (in.RefDirection) {
  506. ConvertDirection(x,*in.RefDirection.Get());
  507. }
  508. const aiVector3D y = aiVector3D(x.y,-x.x,0.f);
  509. aiMatrix4x4::Translation(loc,out);
  510. AssignMatrixAxes(out,x,y,aiVector3D(0.f,0.f,1.f));
  511. }
  512. // ------------------------------------------------------------------------------------------------
  513. void ConvertAxisPlacement(aiVector3D& axis, aiVector3D& pos, const IFC::IfcAxis1Placement& in, ConversionData& conv)
  514. {
  515. ConvertCartesianPoint(pos,in.Location);
  516. if (in.Axis) {
  517. ConvertDirection(axis,in.Axis.Get());
  518. }
  519. else {
  520. axis = aiVector3D(0.f,0.f,1.f);
  521. }
  522. }
  523. // ------------------------------------------------------------------------------------------------
  524. void ConvertAxisPlacement(aiMatrix4x4& out, const IFC::IfcAxis2Placement& in, ConversionData& conv)
  525. {
  526. if(const IFC::IfcAxis2Placement3D* pl3 = in.ResolveSelectPtr<IFC::IfcAxis2Placement3D>(conv.db)) {
  527. ConvertAxisPlacement(out,*pl3,conv);
  528. }
  529. else if(const IFC::IfcAxis2Placement2D* pl2 = in.ResolveSelectPtr<IFC::IfcAxis2Placement2D>(conv.db)) {
  530. ConvertAxisPlacement(out,*pl2,conv);
  531. }
  532. else {
  533. IFCImporter::LogWarn("skipping unknown IfcAxis2Placement entity");
  534. }
  535. }
  536. // ------------------------------------------------------------------------------------------------
  537. void SetCoordinateSpace(ConversionData& conv)
  538. {
  539. const IFC::IfcRepresentationContext* fav = NULL;
  540. BOOST_FOREACH(const IFC::IfcRepresentationContext& v, conv.proj.RepresentationContexts) {
  541. fav = &v;
  542. // Model should be the most suitable type of context, hence ignore the others
  543. if (v.ContextType && v.ContextType.Get() == "Model") {
  544. break;
  545. }
  546. }
  547. if (fav) {
  548. if(const IFC::IfcGeometricRepresentationContext* const geo = fav->ToPtr<IFC::IfcGeometricRepresentationContext>()) {
  549. ConvertAxisPlacement(conv.wcs, *geo->WorldCoordinateSystem, conv);
  550. IFCImporter::LogDebug("got world coordinate system");
  551. }
  552. }
  553. }
  554. // ------------------------------------------------------------------------------------------------
  555. void ConvertTransformOperator(aiMatrix4x4& out, const IFC::IfcCartesianTransformationOperator& op)
  556. {
  557. aiVector3D loc;
  558. ConvertCartesianPoint(loc,op.LocalOrigin);
  559. aiVector3D x(1.f,0.f,0.f),y(0.f,1.f,0.f),z(0.f,0.f,1.f);
  560. if (op.Axis1) {
  561. ConvertDirection(x,*op.Axis1.Get());
  562. }
  563. if (op.Axis2) {
  564. ConvertDirection(y,*op.Axis2.Get());
  565. }
  566. if (const IFC::IfcCartesianTransformationOperator3D* op2 = op.ToPtr<IFC::IfcCartesianTransformationOperator3D>()) {
  567. if(op2->Axis3) {
  568. ConvertDirection(z,*op2->Axis3.Get());
  569. }
  570. }
  571. aiMatrix4x4 locm;
  572. aiMatrix4x4::Translation(loc,locm);
  573. AssignMatrixAxes(out,x,y,z);
  574. aiVector3D vscale;
  575. if (const IFC::IfcCartesianTransformationOperator3DnonUniform* nuni = op.ToPtr<IFC::IfcCartesianTransformationOperator3DnonUniform>()) {
  576. vscale.x = nuni->Scale?op.Scale.Get():1.f;
  577. vscale.y = nuni->Scale2?nuni->Scale2.Get():1.f;
  578. vscale.z = nuni->Scale3?nuni->Scale3.Get():1.f;
  579. }
  580. else {
  581. const float sc = op.Scale?op.Scale.Get():1.f;
  582. vscale = aiVector3D(sc,sc,sc);
  583. }
  584. aiMatrix4x4 s;
  585. aiMatrix4x4::Scaling(vscale,s);
  586. out = locm * out * s;
  587. }
  588. // ------------------------------------------------------------------------------------------------
  589. bool ProcessPolyloop(const IFC::IfcPolyLoop& loop, TempMesh& meshout, ConversionData& conv)
  590. {
  591. size_t cnt = 0;
  592. BOOST_FOREACH(const IFC::IfcCartesianPoint& c, loop.Polygon) {
  593. aiVector3D tmp;
  594. ConvertCartesianPoint(tmp,c);
  595. meshout.verts.push_back(tmp);
  596. ++cnt;
  597. }
  598. // zero- or one- vertex polyloops simply ignored
  599. if (cnt >= 1) {
  600. meshout.vertcnt.push_back(cnt);
  601. return true;
  602. }
  603. if (cnt==1) {
  604. meshout.vertcnt.pop_back();
  605. }
  606. return false;
  607. }
  608. // ------------------------------------------------------------------------------------------------
  609. void MergePolygonBoundaries(TempMesh& result, const TempMesh& meshout, size_t master_bounds = -1)
  610. {
  611. // standard case - only one boundary, just copy it to the result vector
  612. result.vertcnt.reserve(meshout.vertcnt.size()+result.vertcnt.size());
  613. if (meshout.vertcnt.size() <= 1) {
  614. result.verts.reserve(meshout.verts.size()+result.verts.size());
  615. std::copy(meshout.verts.begin(),meshout.verts.end(),std::back_inserter(result.verts));
  616. std::copy(meshout.vertcnt.begin(),meshout.vertcnt.end(),std::back_inserter(result.vertcnt));
  617. return;
  618. }
  619. // handle polygons with holes. Our built in triangulation won't handle them as is, but
  620. // the ear cutting algorithm is solid enough to deal with them if we join the inner
  621. // holes with the outer boundaries by dummy connections.
  622. IFCImporter::LogDebug("fixing polygon with holes for triangulation via ear-cutting");
  623. // each hole results in two extra vertices
  624. result.verts.reserve(meshout.verts.size()+meshout.vertcnt.size()*2+result.verts.size());
  625. size_t outer_polygon_start = 0;
  626. // compute proper normals for all polygons
  627. size_t max_vcount = 0;
  628. std::vector<unsigned int>::const_iterator outer_polygon = meshout.vertcnt.end(), begin=meshout.vertcnt.begin(), iit;
  629. for(iit = begin; iit != meshout.vertcnt.end(); ++iit) {
  630. ai_assert(*iit);
  631. max_vcount = std::max(max_vcount,static_cast<size_t>(*iit));
  632. }
  633. std::vector<float> temp((max_vcount+2)*4);
  634. std::vector<aiVector3D> normals;
  635. normals.reserve( meshout.vertcnt.size() );
  636. size_t vidx = 0;
  637. for(iit = begin; iit != meshout.vertcnt.end(); vidx += *iit++) {
  638. for(size_t vofs = 0, cnt = 0; vofs < *iit; ++vofs) {
  639. const aiVector3D& v = meshout.verts[vidx+vofs];
  640. temp[cnt++] = v.x;
  641. temp[cnt++] = v.y;
  642. temp[cnt++] = v.z;
  643. #ifdef _DEBUG
  644. temp[cnt] = std::numeric_limits<float>::quiet_NaN();
  645. #endif
  646. ++cnt;
  647. }
  648. normals.push_back(aiVector3D());
  649. NewellNormal<4,4,4>(normals.back(),*iit,&temp[0],&temp[1],&temp[2]);
  650. }
  651. // see if one of the polygons is a IfcFaceOuterBound - treats this as the outer boundary.
  652. // sadly we can't rely on it, the docs say 'At most one of the bounds shall be of the type IfcFaceOuterBound'
  653. if (master_bounds != -1) {
  654. outer_polygon = begin + master_bounds;
  655. outer_polygon_start = std::accumulate(begin,outer_polygon,0);
  656. BOOST_FOREACH(aiVector3D& n, normals) {
  657. n.Normalize();
  658. }
  659. }
  660. else {
  661. float area_outer_polygon = 1e-10f;
  662. size_t vidx = 0;
  663. for(iit = begin; iit != meshout.vertcnt.end(); vidx += *iit++) {
  664. // find the polygon with the largest area, it must be the outer bound.
  665. aiVector3D& n = normals[std::distance(begin,iit)];
  666. const float area = n.Length();
  667. if (area > area_outer_polygon) {
  668. area_outer_polygon = area;
  669. outer_polygon = iit;
  670. outer_polygon_start = vidx;
  671. }
  672. n /= area;
  673. }
  674. }
  675. ai_assert(outer_polygon != meshout.vertcnt.end());
  676. typedef boost::tuple<std::vector<unsigned int>::const_iterator, unsigned int, unsigned int> InsertionPoint;
  677. std::vector< std::vector<InsertionPoint> > insertions(*outer_polygon, std::vector<InsertionPoint>());
  678. // iterate through all other polyloops and find points in the outer polyloop that are close
  679. vidx = 0;
  680. for(iit = begin; iit != meshout.vertcnt.end(); vidx += *iit++) {
  681. if (iit == outer_polygon) {
  682. continue;
  683. }
  684. size_t best_ofs,best_outer = *outer_polygon;
  685. float best_dist = 1e10;
  686. for(size_t vofs = 0; vofs < *iit; ++vofs) {
  687. const aiVector3D& v = meshout.verts[vidx+vofs];
  688. for(size_t outer = 0; outer < *outer_polygon; ++outer) {
  689. const aiVector3D& o = meshout.verts[outer_polygon_start+outer];
  690. const float d = (o-v).SquareLength();
  691. if (d < best_dist) {
  692. best_dist = d;
  693. best_ofs = vofs;
  694. best_outer = outer;
  695. }
  696. }
  697. }
  698. ai_assert(best_outer != *outer_polygon);
  699. // we will later insert a hidden connection line right after the closest point in the outer polygon
  700. insertions[best_outer].push_back(boost::make_tuple(iit,vidx,best_ofs));
  701. }
  702. // now that we collected all vertex connections to be added, build the output polygon
  703. size_t cnt = *outer_polygon;
  704. for(size_t outer = 0; outer < *outer_polygon; ++outer) {
  705. const aiVector3D& o = meshout.verts[outer_polygon_start+outer];
  706. result.verts.push_back(o);
  707. const std::vector<InsertionPoint>& insvec = insertions[outer];
  708. BOOST_FOREACH(const InsertionPoint& ins,insvec) {
  709. if (!(*ins.get<0>())) {
  710. continue;
  711. }
  712. for(size_t i = ins.get<2>(); i < *ins.get<0>(); ++i) {
  713. result.verts.push_back(meshout.verts[ins.get<1>() + i]);
  714. }
  715. // we need the first vertex of the inner polygon twice as we return to the
  716. // outer loop through the very same connection through which we got there.
  717. for(size_t i = 0; i <= ins.get<2>(); ++i) {
  718. result.verts.push_back(meshout.verts[ins.get<1>() + i]);
  719. }
  720. // reverse face winding if the normal of the sub-polygon points in the
  721. // same direction as the normal of the outer polygonal boundary
  722. if (normals[std::distance(begin,ins.get<0>())] * normals[std::distance(begin,outer_polygon)] > 0) {
  723. std::reverse(result.verts.rbegin(),result.verts.rbegin()+*ins.get<0>()+1);
  724. }
  725. // also append a copy of the initial insertion point to be able to continue the outer polygon
  726. result.verts.push_back(o);
  727. cnt += *ins.get<0>()+2;
  728. }
  729. }
  730. result.vertcnt.push_back(cnt);
  731. }
  732. // ------------------------------------------------------------------------------------------------
  733. void ProcessConnectedFaceSet(const IFC::IfcConnectedFaceSet& fset, TempMesh& result, ConversionData& conv)
  734. {
  735. BOOST_FOREACH(const IFC::IfcFace& face, fset.CfsFaces) {
  736. TempMesh meshout;
  737. size_t ob = -1, cnt = 0;
  738. BOOST_FOREACH(const IFC::IfcFaceBound& bound, face.Bounds) {
  739. if(const IFC::IfcPolyLoop* const polyloop = bound.Bound->ToPtr<IFC::IfcPolyLoop>()) {
  740. if(ProcessPolyloop(*polyloop, meshout, conv)) {
  741. if(bound.ToPtr<IFC::IfcFaceOuterBound>()) {
  742. ob = cnt;
  743. }
  744. ++cnt;
  745. }
  746. }
  747. else {
  748. IFCImporter::LogWarn("skipping unknown IfcFaceBound entity, type is " + bound.Bound->GetClassName());
  749. continue;
  750. }
  751. if(!IsTrue(bound.Orientation)) {
  752. size_t c = 0;
  753. BOOST_FOREACH(unsigned int& i, meshout.vertcnt) {
  754. std::reverse(meshout.verts.begin() + cnt,meshout.verts.begin() + cnt + c);
  755. cnt += c;
  756. }
  757. }
  758. }
  759. MergePolygonBoundaries(result,meshout,ob);
  760. }
  761. }
  762. // ------------------------------------------------------------------------------------------------
  763. void ProcessPolyLine(const IFC::IfcPolyline& def, TempMesh& meshout, ConversionData& conv)
  764. {
  765. // this won't produce a valid mesh, it just spits out a list of vertices
  766. aiVector3D t;
  767. BOOST_FOREACH(const IFC::IfcCartesianPoint& cp, def.Points) {
  768. ConvertCartesianPoint(t,cp);
  769. meshout.verts.push_back(t);
  770. }
  771. }
  772. // ------------------------------------------------------------------------------------------------
  773. bool ProcessCurve(const IFC::IfcCurve& curve, TempMesh& meshout, ConversionData& conv)
  774. {
  775. if(const IFC::IfcPolyline* poly = curve.ToPtr<IFC::IfcPolyline>()) {
  776. ProcessPolyLine(*poly,meshout,conv);
  777. }
  778. else {
  779. IFCImporter::LogWarn("skipping unknown IfcCurve entity, type is " + curve.GetClassName());
  780. return false;
  781. }
  782. return true;
  783. }
  784. // ------------------------------------------------------------------------------------------------
  785. void ProcessClosedProfile(const IFC::IfcArbitraryClosedProfileDef& def, TempMesh& meshout, ConversionData& conv)
  786. {
  787. if(ProcessCurve(def.OuterCurve,meshout,conv)) {
  788. if(meshout.verts.size()>2 && meshout.verts.front() == meshout.verts.back()) {
  789. meshout.verts.pop_back(); // duplicate element, first==last
  790. }
  791. }
  792. }
  793. // ------------------------------------------------------------------------------------------------
  794. void ProcessOpenProfile(const IFC::IfcArbitraryOpenProfileDef& def, TempMesh& meshout, ConversionData& conv)
  795. {
  796. ProcessCurve(def.Curve,meshout,conv);
  797. }
  798. // ------------------------------------------------------------------------------------------------
  799. void ProcessParametrizedProfile(const IFC::IfcParameterizedProfileDef& def, TempMesh& meshout, ConversionData& conv)
  800. {
  801. if(const IFC::IfcRectangleProfileDef* const cprofile = def.ToPtr<IFC::IfcRectangleProfileDef>()) {
  802. const float x = cprofile->XDim*0.5f, y = cprofile->YDim*0.5f;
  803. meshout.verts.reserve(meshout.verts.size()+4);
  804. meshout.verts.push_back( aiVector3D( x, y, 0.f ));
  805. meshout.verts.push_back( aiVector3D(-x, y, 0.f ));
  806. meshout.verts.push_back( aiVector3D(-x,-y, 0.f ));
  807. meshout.verts.push_back( aiVector3D( x,-y, 0.f ));
  808. meshout.vertcnt.push_back(4);
  809. }
  810. else if( const IFC::IfcCircleProfileDef* const circle = def.ToPtr<IFC::IfcCircleProfileDef>()) {
  811. if( const IFC::IfcCircleHollowProfileDef* const hollow = def.ToPtr<IFC::IfcCircleHollowProfileDef>()) {
  812. // TODO
  813. }
  814. const size_t segments = 32;
  815. const float delta = AI_MATH_TWO_PI_F/segments, radius = circle->Radius;
  816. meshout.verts.reserve(segments);
  817. float angle = 0.f;
  818. for(size_t i = 0; i < segments; ++i, angle += delta) {
  819. meshout.verts.push_back( aiVector3D( cos(angle)*radius, sin(angle)*radius, 0.f ));
  820. }
  821. meshout.vertcnt.push_back(segments);
  822. }
  823. else {
  824. IFCImporter::LogWarn("skipping unknown IfcParameterizedProfileDef entity, type is " + def.GetClassName());
  825. return;
  826. }
  827. aiMatrix4x4 trafo;
  828. ConvertAxisPlacement(trafo, *def.Position,conv);
  829. meshout.Transform(trafo);
  830. }
  831. // ------------------------------------------------------------------------------------------------
  832. bool ProcessProfile(const IFC::IfcProfileDef& prof, TempMesh& meshout, ConversionData& conv)
  833. {
  834. if(const IFC::IfcArbitraryClosedProfileDef* const cprofile = prof.ToPtr<IFC::IfcArbitraryClosedProfileDef>()) {
  835. ProcessClosedProfile(*cprofile,meshout,conv);
  836. }
  837. else if(const IFC::IfcArbitraryOpenProfileDef* const copen = prof.ToPtr<IFC::IfcArbitraryOpenProfileDef>()) {
  838. ProcessOpenProfile(*copen,meshout,conv);
  839. }
  840. else if(const IFC::IfcParameterizedProfileDef* const cparam = prof.ToPtr<IFC::IfcParameterizedProfileDef>()) {
  841. ProcessParametrizedProfile(*cparam,meshout,conv);
  842. }
  843. else {
  844. IFCImporter::LogWarn("skipping unknown IfcProfileDef entity, type is " + prof.GetClassName());
  845. return false;
  846. }
  847. return true;
  848. }
  849. // ------------------------------------------------------------------------------------------------
  850. void FixupFaceOrientation(TempMesh& result)
  851. {
  852. aiVector3D vavg;
  853. BOOST_FOREACH(aiVector3D& v, result.verts) {
  854. vavg += v;
  855. }
  856. // fix face orientation - try at least.
  857. vavg /= static_cast<float>( result.verts.size() );
  858. size_t c = 0;
  859. BOOST_FOREACH(unsigned int cnt, result.vertcnt) {
  860. if (cnt>2){
  861. const aiVector3D& thisvert = result.verts[c];
  862. const aiVector3D normal((thisvert-result.verts[c+1])^(thisvert-result.verts[c+2]));
  863. if (normal*(thisvert-vavg) < 0) {
  864. std::reverse(result.verts.begin()+c,result.verts.begin()+cnt+c);
  865. }
  866. }
  867. c += cnt;
  868. }
  869. }
  870. // ------------------------------------------------------------------------------------------------
  871. void ProcessRevolvedAreaSolid(const IFC::IfcRevolvedAreaSolid& solid, TempMesh& result, ConversionData& conv)
  872. {
  873. TempMesh meshout;
  874. // first read the profile description
  875. if(!ProcessProfile(*solid.SweptArea,meshout,conv) || meshout.verts.size()<=1) {
  876. return;
  877. }
  878. aiVector3D axis, pos;
  879. ConvertAxisPlacement(axis,pos,solid.Axis,conv);
  880. aiMatrix4x4 tb0,tb1;
  881. aiMatrix4x4::Translation(pos,tb0);
  882. aiMatrix4x4::Translation(-pos,tb1);
  883. const std::vector<aiVector3D>& in = meshout.verts;
  884. const size_t size=in.size();
  885. bool has_area = solid.SweptArea->ProfileType == "AREA" && size>2;
  886. const float max_angle = solid.Angle*conv.angle_scale;
  887. if(fabs(max_angle) < 1e-3) {
  888. if(has_area) {
  889. result = meshout;
  890. }
  891. return;
  892. }
  893. const unsigned int cnt_segments = std::max(2u,static_cast<unsigned int>(16 * fabs(max_angle)/AI_MATH_HALF_PI_F));
  894. const float delta = max_angle/cnt_segments;
  895. has_area = has_area && fabs(max_angle) < AI_MATH_TWO_PI_F*0.99;
  896. result.verts.reserve(size*((cnt_segments+1)*4+(has_area?2:0)));
  897. result.vertcnt.reserve(size*cnt_segments+2);
  898. aiMatrix4x4 rot;
  899. rot = tb0 * aiMatrix4x4::Rotation(delta,axis,rot) * tb1;
  900. size_t base = 0;
  901. std::vector<aiVector3D>& out = result.verts;
  902. // dummy data to simplify later processing
  903. for(size_t i = 0; i < size; ++i) {
  904. out.insert(out.end(),4,in[i]);
  905. }
  906. for(unsigned int seg = 0; seg < cnt_segments; ++seg) {
  907. for(size_t i = 0; i < size; ++i) {
  908. const size_t next = (i+1)%size;
  909. result.vertcnt.push_back(4);
  910. const aiVector3D& base_0 = out[base+i*4+3],base_1 = out[base+next*4+3];
  911. out.push_back(base_0);
  912. out.push_back(base_1);
  913. out.push_back(rot*base_1);
  914. out.push_back(rot*base_0);
  915. }
  916. base += size*4;
  917. }
  918. out.erase(out.begin(),out.begin()+size*4);
  919. if(has_area) {
  920. // leave the triangulation of the profile area to the ear cutting
  921. // implementation in aiProcess_Triangulate - for now we just
  922. // feed in two huge polygons.
  923. base -= size*8;
  924. for(size_t i = size; i--; ) {
  925. out.push_back(out[base+i*4+3]);
  926. }
  927. for(size_t i = 0; i < size; ++i ) {
  928. out.push_back(out[i*4]);
  929. }
  930. result.vertcnt.push_back(size);
  931. result.vertcnt.push_back(size);
  932. }
  933. aiMatrix4x4 trafo;
  934. ConvertAxisPlacement(trafo, solid.Position,conv);
  935. result.Transform(trafo);
  936. FixupFaceOrientation(result);
  937. IFCImporter::LogDebug("generate mesh procedurally by radial extrusion (IfcRevolvedAreaSolid)");
  938. }
  939. // ------------------------------------------------------------------------------------------------
  940. bool TryAddOpening(const std::vector<TempOpening>& openings,const std::vector<aiVector3D>& nors, TempMesh& curmesh)
  941. {
  942. std::vector<aiVector3D>& out = curmesh.verts;
  943. const size_t s = out.size();
  944. const aiVector3D any_point = out[s-3];
  945. const aiVector3D nor = ((out[s-2]-any_point)^(out[s-1]-any_point)).Normalize();
  946. bool got_openings = false;
  947. size_t c = 0;
  948. BOOST_FOREACH(const TempOpening& t,openings) {
  949. const aiVector3D& outernor = nors[c++];
  950. const float dot = nor * outernor;
  951. if (fabs(dot)<0.98) {
  952. continue;
  953. }
  954. const aiVector3D diff = t.extrusionDir;
  955. const std::vector<aiVector3D>& va = t.profileMesh->verts;
  956. if(va.size() <= 2) {
  957. continue;
  958. }
  959. const float dd = t.extrusionDir*nor;
  960. IFCImporter::LogDebug("apply an IfcOpeningElement linked via IfcRelVoidsElement to this polygon");
  961. got_openings = true;
  962. if ( fabs((any_point-va[0]).Normalize()*nor) > 1e-3f) {
  963. for(size_t i = 0; i < va.size(); ++i) {
  964. out.push_back(va[i]+diff);
  965. }
  966. }
  967. else {
  968. for(size_t i = 0; i < va.size(); ++i) {
  969. out.push_back(va[i]);
  970. }
  971. }
  972. curmesh.vertcnt.push_back(va.size());
  973. TempMesh res;
  974. MergePolygonBoundaries(res,curmesh,0);
  975. curmesh = res;
  976. }
  977. return got_openings;
  978. }
  979. // ------------------------------------------------------------------------------------------------
  980. struct DistanceSorter {
  981. DistanceSorter(const aiVector3D& base) : base(base) {}
  982. bool operator () (const TempOpening& a, const TempOpening& b) const {
  983. return (a.profileMesh->Center()-base).SquareLength() < (b.profileMesh->Center()-base).SquareLength();
  984. }
  985. aiVector3D base;
  986. };
  987. // ------------------------------------------------------------------------------------------------
  988. void ProcessExtrudedAreaSolid(const IFC::IfcExtrudedAreaSolid& solid, TempMesh& result, ConversionData& conv)
  989. {
  990. TempMesh meshout;
  991. // first read the profile description
  992. if(!ProcessProfile(*solid.SweptArea,meshout,conv) || meshout.verts.size()<=1) {
  993. return;
  994. }
  995. aiVector3D dir;
  996. ConvertDirection(dir,solid.ExtrudedDirection);
  997. dir *= solid.Depth;
  998. // assuming that `meshout.verts` is now a list of vertex points forming
  999. // the underlying profile, extrude along the given axis, forming new
  1000. // triangles.
  1001. std::vector<aiVector3D>& in = meshout.verts;
  1002. const size_t size=in.size();
  1003. const bool has_area = solid.SweptArea->ProfileType == "AREA" && size>2;
  1004. if(solid.Depth < 1e-3) {
  1005. if(has_area) {
  1006. meshout = result;
  1007. }
  1008. return;
  1009. }
  1010. result.verts.reserve(size*(has_area?4:2));
  1011. result.vertcnt.reserve(meshout.vertcnt.size()+2);
  1012. // transform to target space
  1013. aiMatrix4x4 trafo;
  1014. ConvertAxisPlacement(trafo, solid.Position,conv);
  1015. BOOST_FOREACH(aiVector3D& v,in) {
  1016. v *= trafo;
  1017. }
  1018. aiVector3D min = in[0];
  1019. dir *= aiMatrix3x3(trafo);
  1020. float cy = 0.f;
  1021. // recompute the normal vectors for all openings
  1022. std::vector<aiVector3D> nors;
  1023. if (conv.apply_openings) {
  1024. // it is essential to apply the openings in the correct spatial order. The direction
  1025. // doesn't matter, but we would screw up if we started with e.g. a door in between
  1026. // two windows.
  1027. std::sort(conv.apply_openings->begin(),conv.apply_openings->end(),DistanceSorter(min));
  1028. nors.reserve(conv.apply_openings->size());
  1029. //std::reverse(conv.apply_openings->begin(),conv.apply_openings->end());
  1030. BOOST_FOREACH(TempOpening& t,*conv.apply_openings) {
  1031. TempMesh& bounds = *t.profileMesh.get();
  1032. //bounds.Transform(trafo);
  1033. if (bounds.verts.size() <= 2) {
  1034. nors.push_back(aiVector3D());
  1035. continue;
  1036. }
  1037. nors.push_back(((bounds.verts[2]-bounds.verts[0])^(bounds.verts[1]-bounds.verts[0]) ).Normalize());
  1038. cy += nors.back().y;
  1039. }
  1040. }
  1041. bool rev = cy<0.f;
  1042. // XXX disable all openings for now
  1043. conv.apply_openings = NULL;
  1044. TempMesh temp;
  1045. TempMesh& curmesh = conv.apply_openings ? temp : result;
  1046. std::vector<aiVector3D>& out = curmesh.verts;
  1047. size_t sides_with_openings = 0;
  1048. for(size_t i = 0; i < size; ++i) {
  1049. const size_t next = (i+1)%size;
  1050. curmesh.vertcnt.push_back(4);
  1051. out.push_back(in[i]);
  1052. out.push_back(in[i]+dir);
  1053. out.push_back(in[next]+dir);
  1054. out.push_back(in[next]);
  1055. if(conv.apply_openings) {
  1056. if(TryAddOpening(*conv.apply_openings,nors,curmesh)) {
  1057. ++sides_with_openings;
  1058. }
  1059. MergePolygonBoundaries(result,temp,0);
  1060. temp.Clear();
  1061. }
  1062. }
  1063. size_t sides_with_v_openings = 0;
  1064. if(has_area) {
  1065. // leave the triangulation of the profile area to the ear cutting
  1066. // implementation in aiProcess_Triangulate - for now we just
  1067. // feed in two huge polygons.
  1068. for(size_t n = 0; n < 2; ++n) {
  1069. for(size_t i = size; i--; ) {
  1070. out.push_back(in[i]+(n?dir:aiVector3D()));
  1071. }
  1072. curmesh.vertcnt.push_back(size);
  1073. if(conv.apply_openings) {
  1074. if(TryAddOpening(*conv.apply_openings,nors,curmesh)) {
  1075. ++sides_with_v_openings;
  1076. }
  1077. MergePolygonBoundaries(result,temp,0);
  1078. temp.Clear();
  1079. }
  1080. }
  1081. }
  1082. // add connection geometry to close the 'holes' for the openings
  1083. if(conv.apply_openings) {
  1084. BOOST_FOREACH(const TempOpening& t,*conv.apply_openings) {
  1085. const std::vector<aiVector3D>& in = t.profileMesh->verts;
  1086. std::vector<aiVector3D>& out = result.verts;
  1087. const aiVector3D dir = t.extrusionDir;
  1088. for(size_t i = 0, size = in.size(); i < size; ++i) {
  1089. const size_t next = (i+1)%size;
  1090. result.vertcnt.push_back(4);
  1091. out.push_back(in[i]);
  1092. out.push_back(in[i]+dir);
  1093. out.push_back(in[next]+dir);
  1094. out.push_back(in[next]-dir);
  1095. }
  1096. }
  1097. }
  1098. if(conv.apply_openings && (sides_with_openings != 2 && sides_with_openings || sides_with_v_openings != 2 && sides_with_v_openings)) {
  1099. IFCImporter::LogWarn("failed to resolve all openings, presumably their topology is not supported by Assimp");
  1100. }
  1101. FixupFaceOrientation(result);
  1102. IFCImporter::LogDebug("generate mesh procedurally by extrusion (IfcExtrudedAreaSolid)");
  1103. }
  1104. // ------------------------------------------------------------------------------------------------
  1105. void ProcessSweptAreaSolid(const IFC::IfcSweptAreaSolid& swept, TempMesh& meshout, ConversionData& conv)
  1106. {
  1107. if(const IFC::IfcExtrudedAreaSolid* const solid = swept.ToPtr<IFC::IfcExtrudedAreaSolid>()) {
  1108. // Do we just collect openings for a parent element (i.e. a wall)?
  1109. // In this case we don't extrude the surface yet, just keep the profile and transform it correctly
  1110. if(conv.collect_openings) {
  1111. boost::shared_ptr<TempMesh> meshtmp(new TempMesh());
  1112. ProcessProfile(swept.SweptArea,*meshtmp,conv);
  1113. aiMatrix4x4 m;
  1114. ConvertAxisPlacement(m,solid->Position,conv);
  1115. meshtmp->Transform(m);
  1116. aiVector3D dir;
  1117. ConvertDirection(dir,solid->ExtrudedDirection);
  1118. conv.collect_openings->push_back(TempOpening(solid, aiMatrix3x3(m) * (dir*solid->Depth),meshtmp));
  1119. return;
  1120. }
  1121. ProcessExtrudedAreaSolid(*solid,meshout,conv);
  1122. }
  1123. else if(const IFC::IfcRevolvedAreaSolid* const rev = swept.ToPtr<IFC::IfcRevolvedAreaSolid>()) {
  1124. ProcessRevolvedAreaSolid(*rev,meshout,conv);
  1125. }
  1126. else {
  1127. IFCImporter::LogWarn("skipping unknown IfcSweptAreaSolid entity, type is " + swept.GetClassName());
  1128. }
  1129. }
  1130. // ------------------------------------------------------------------------------------------------
  1131. enum Intersect {
  1132. Intersect_No,
  1133. Intersect_LiesOnPlane,
  1134. Intersect_Yes
  1135. };
  1136. // ------------------------------------------------------------------------------------------------
  1137. Intersect IntersectSegmentPlane(const aiVector3D& p,const aiVector3D& n, const aiVector3D& e0, const aiVector3D& e1, aiVector3D& out)
  1138. {
  1139. const aiVector3D pdelta = e0 - p, seg = e1-e0;
  1140. const float dotOne = n*seg, dotTwo = -(n*pdelta);
  1141. if (fabs(dotOne) < 1e-6) {
  1142. return fabs(dotTwo) < 1e-6f ? Intersect_LiesOnPlane : Intersect_No;
  1143. }
  1144. const float t = dotTwo/dotOne;
  1145. // t must be in [0..1] if the intersection point is within the given segment
  1146. if (t > 1.f || t < 0.f) {
  1147. return Intersect_No;
  1148. }
  1149. out = e0+t*seg;
  1150. return Intersect_Yes;
  1151. }
  1152. // ------------------------------------------------------------------------------------------------
  1153. void ProcessBoolean(const IFC::IfcBooleanResult& boolean, TempMesh& result, ConversionData& conv)
  1154. {
  1155. if(const IFC::IfcBooleanClippingResult* const clip = boolean.ToPtr<IFC::IfcBooleanClippingResult>()) {
  1156. if(clip->Operator != "DIFFERENCE") {
  1157. IFCImporter::LogWarn("encountered unsupported boolean operator: " + (std::string)clip->Operator);
  1158. return;
  1159. }
  1160. TempMesh meshout;
  1161. const IFC::IfcHalfSpaceSolid* const hs = clip->SecondOperand->ResolveSelectPtr<IFC::IfcHalfSpaceSolid>(conv.db);
  1162. if(!hs) {
  1163. IFCImporter::LogError("expected IfcHalfSpaceSolid as second clipping operand");
  1164. return;
  1165. }
  1166. const IFC::IfcPlane* const plane = hs->BaseSurface->ToPtr<IFC::IfcPlane>();
  1167. if(!plane) {
  1168. IFCImporter::LogError("expected IfcPlane as base surface for the IfcHalfSpaceSolid");
  1169. return;
  1170. }
  1171. if(const IFC::IfcBooleanResult* const op0 = clip->FirstOperand->ResolveSelectPtr<IFC::IfcBooleanResult>(conv.db)) {
  1172. ProcessBoolean(*op0,meshout,conv);
  1173. }
  1174. else if (const IFC::IfcSweptAreaSolid* const swept = clip->FirstOperand->ResolveSelectPtr<IFC::IfcSweptAreaSolid>(conv.db)) {
  1175. ProcessSweptAreaSolid(*swept,meshout,conv);
  1176. }
  1177. else {
  1178. IFCImporter::LogError("expected IfcSweptAreaSolid or IfcBooleanResult as first clipping operand");
  1179. return;
  1180. }
  1181. // extract plane base position vector and normal vector
  1182. aiVector3D p,n(0.f,0.f,1.f);
  1183. if (plane->Position->Axis) {
  1184. ConvertDirection(n,plane->Position->Axis.Get());
  1185. }
  1186. ConvertCartesianPoint(p,plane->Position->Location);
  1187. if(!IsTrue(hs->AgreementFlag)) {
  1188. n *= -1.f;
  1189. }
  1190. // clip the current contents of `meshout` against the plane we obtained from the second operand
  1191. const std::vector<aiVector3D>& in = meshout.verts;
  1192. std::vector<aiVector3D>& outvert = result.verts;
  1193. std::vector<unsigned int>::const_iterator begin=meshout.vertcnt.begin(), end=meshout.vertcnt.end(), iit;
  1194. unsigned int vidx = 0;
  1195. for(iit = begin; iit != end; vidx += *iit++) {
  1196. unsigned int newcount = 0;
  1197. for(unsigned int i = 0; i < *iit; ++i) {
  1198. const aiVector3D& e0 = in[vidx+i], e1 = in[vidx+(i+1)%*iit];
  1199. // does the next segment intersect the plane?
  1200. aiVector3D isectpos;
  1201. const Intersect isect = IntersectSegmentPlane(p,n,e0,e1,isectpos);
  1202. if (isect == Intersect_No || isect == Intersect_LiesOnPlane) {
  1203. if ( (e0-p).Normalize()*n > 0 ) {
  1204. outvert.push_back(e0);
  1205. ++newcount;
  1206. }
  1207. }
  1208. else if (isect == Intersect_Yes) {
  1209. if ( (e0-p).Normalize()*n > 0 ) {
  1210. // e0 is on the right side, so keep it
  1211. outvert.push_back(e0);
  1212. outvert.push_back(isectpos);
  1213. newcount += 2;
  1214. }
  1215. else {
  1216. // e0 is on the wrong side, so drop it and keep e1 instead
  1217. outvert.push_back(isectpos);
  1218. ++newcount;
  1219. }
  1220. }
  1221. }
  1222. if(newcount) {
  1223. result.vertcnt.push_back(newcount);
  1224. }
  1225. }
  1226. IFCImporter::LogDebug("generating CSG geometry by plane clipping (IfcBooleanClippingResult)");
  1227. }
  1228. else {
  1229. IFCImporter::LogWarn("skipping unknown IfcBooleanResult entity, type is " + boolean.GetClassName());
  1230. }
  1231. }
  1232. // ------------------------------------------------------------------------------------------------
  1233. int ConvertShadingMode(const std::string& name)
  1234. {
  1235. if (name == "BLINN") {
  1236. return aiShadingMode_Blinn;
  1237. }
  1238. else if (name == "FLAT" || name == "NOTDEFINED") {
  1239. return aiShadingMode_NoShading;
  1240. }
  1241. else if (name == "PHONG") {
  1242. return aiShadingMode_Phong;
  1243. }
  1244. IFCImporter::LogWarn("shading mode "+name+" not recognized by Assimp, using Phong instead");
  1245. return aiShadingMode_Phong;
  1246. }
  1247. // ------------------------------------------------------------------------------------------------
  1248. void FillMaterial(MaterialHelper* mat,const IFC::IfcSurfaceStyle* surf,ConversionData& conv)
  1249. {
  1250. aiString name;
  1251. name.Set((surf->Name? surf->Name.Get() : "IfcSurfaceStyle_Unnamed"));
  1252. mat->AddProperty(&name,AI_MATKEY_NAME);
  1253. // now see which kinds of surface information are present
  1254. BOOST_FOREACH(const IFC::IfcSurfaceStyleElementSelect* sel2, surf->Styles) {
  1255. if (const IFC::IfcSurfaceStyleShading* shade = sel2->ResolveSelectPtr<IFC::IfcSurfaceStyleShading>(conv.db)) {
  1256. aiColor4D col_base,col;
  1257. ConvertColor(col_base, shade->SurfaceColour);
  1258. mat->AddProperty(&col_base,1, AI_MATKEY_COLOR_DIFFUSE);
  1259. if (const IFC::IfcSurfaceStyleRendering* ren = shade->ToPtr<IFC::IfcSurfaceStyleRendering>()) {
  1260. if (ren->Transparency) {
  1261. const float t = 1.f-ren->Transparency.Get();
  1262. mat->AddProperty(&t,1, AI_MATKEY_OPACITY);
  1263. }
  1264. if (ren->DiffuseColour) {
  1265. ConvertColor(col, ren->DiffuseColour.Get(),conv,&col_base);
  1266. mat->AddProperty(&col,1, AI_MATKEY_COLOR_DIFFUSE);
  1267. }
  1268. if (ren->SpecularColour) {
  1269. ConvertColor(col, ren->SpecularColour.Get(),conv,&col_base);
  1270. mat->AddProperty(&col,1, AI_MATKEY_COLOR_SPECULAR);
  1271. }
  1272. if (ren->TransmissionColour) {
  1273. ConvertColor(col, ren->TransmissionColour.Get(),conv,&col_base);
  1274. mat->AddProperty(&col,1, AI_MATKEY_COLOR_TRANSPARENT);
  1275. }
  1276. if (ren->ReflectionColour) {
  1277. ConvertColor(col, ren->ReflectionColour.Get(),conv,&col_base);
  1278. mat->AddProperty(&col,1, AI_MATKEY_COLOR_REFLECTIVE);
  1279. }
  1280. const int shading = (ren->SpecularHighlight && ren->SpecularColour)?ConvertShadingMode(ren->ReflectanceMethod):aiShadingMode_Gouraud;
  1281. mat->AddProperty(&shading,1, AI_MATKEY_SHADING_MODEL);
  1282. if (ren->SpecularHighlight) {
  1283. if(const EXPRESS::REAL* rt = ren->SpecularHighlight.Get()->ToPtr<EXPRESS::REAL>()) {
  1284. // at this point we don't distinguish between the two distinct ways of
  1285. // specifying highlight intensities. leave this to the user.
  1286. const float e = *rt;
  1287. mat->AddProperty(&e,1,AI_MATKEY_SHININESS);
  1288. }
  1289. else {
  1290. IFCImporter::LogWarn("unexpected type error, SpecularHighlight should be a REAL");
  1291. }
  1292. }
  1293. }
  1294. }
  1295. else if (const IFC::IfcSurfaceStyleWithTextures* tex = sel2->ResolveSelectPtr<IFC::IfcSurfaceStyleWithTextures>(conv.db)) {
  1296. // XXX
  1297. }
  1298. }
  1299. }
  1300. // ------------------------------------------------------------------------------------------------
  1301. unsigned int ProcessMaterials(const IFC::IfcRepresentationItem& item, ConversionData& conv)
  1302. {
  1303. if (conv.materials.empty()) {
  1304. aiString name;
  1305. std::auto_ptr<MaterialHelper> mat(new MaterialHelper());
  1306. name.Set("<IFCDefault>");
  1307. mat->AddProperty(&name,AI_MATKEY_NAME);
  1308. aiColor4D col = aiColor4D(0.6f,0.6f,0.6f,1.0f);
  1309. mat->AddProperty(&col,1, AI_MATKEY_COLOR_DIFFUSE);
  1310. conv.materials.push_back(mat.release());
  1311. }
  1312. STEP::DB::RefMapRange range = conv.db.GetRefs().equal_range(item.GetID());
  1313. for(;range.first != range.second; ++range.first) {
  1314. if(const IFC::IfcStyledItem* const styled = conv.db.GetObject((*range.first).second)->ToPtr<IFC::IfcStyledItem>()) {
  1315. BOOST_FOREACH(const IFC::IfcPresentationStyleAssignment& as, styled->Styles) {
  1316. BOOST_FOREACH(const IFC::IfcPresentationStyleSelect* sel, as.Styles) {
  1317. if (const IFC::IfcSurfaceStyle* const surf = sel->ResolveSelectPtr<IFC::IfcSurfaceStyle>(conv.db)) {
  1318. const std::string side = static_cast<std::string>(surf->Side);
  1319. if (side != "BOTH") {
  1320. IFCImporter::LogWarn("ignoring surface side marker on IFC::IfcSurfaceStyle: " + side);
  1321. }
  1322. std::auto_ptr<MaterialHelper> mat(new MaterialHelper());
  1323. FillMaterial(mat.get(),surf,conv);
  1324. conv.materials.push_back(mat.release());
  1325. return conv.materials.size()-1;
  1326. }
  1327. }
  1328. }
  1329. }
  1330. }
  1331. return 0;
  1332. }
  1333. // ------------------------------------------------------------------------------------------------
  1334. bool ProcessTopologicalItem(const IFC::IfcTopologicalRepresentationItem& topo, std::vector<unsigned int>& mesh_indices, ConversionData& conv)
  1335. {
  1336. TempMesh meshtmp;
  1337. if(const IFC::IfcConnectedFaceSet* fset = topo.ToPtr<IFC::IfcConnectedFaceSet>()) {
  1338. ProcessConnectedFaceSet(*fset,meshtmp,conv);
  1339. }
  1340. else {
  1341. IFCImporter::LogWarn("skipping unknown IfcTopologicalRepresentationItem entity, type is " + topo.GetClassName());
  1342. return false;
  1343. }
  1344. aiMesh* const mesh = meshtmp.ToMesh();
  1345. if(mesh) {
  1346. mesh->mMaterialIndex = ProcessMaterials(topo,conv);
  1347. mesh_indices.push_back(conv.meshes.size());
  1348. conv.meshes.push_back(mesh);
  1349. return true;
  1350. }
  1351. return false;
  1352. }
  1353. // ------------------------------------------------------------------------------------------------
  1354. bool ProcessGeometricItem(const IFC::IfcGeometricRepresentationItem& geo, std::vector<unsigned int>& mesh_indices, ConversionData& conv)
  1355. {
  1356. TempMesh meshtmp;
  1357. if(const IFC::IfcShellBasedSurfaceModel* shellmod = geo.ToPtr<IFC::IfcShellBasedSurfaceModel>()) {
  1358. BOOST_FOREACH(const IFC::IfcShell* shell,shellmod->SbsmBoundary) {
  1359. try {
  1360. const EXPRESS::ENTITY& e = shell->To<IFC::ENTITY>();
  1361. const IFC::IfcConnectedFaceSet& fs = conv.db.MustGetObject(e).To<IFC::IfcConnectedFaceSet>();
  1362. ProcessConnectedFaceSet(fs,meshtmp,conv);
  1363. }
  1364. catch(std::bad_cast&) {
  1365. IFCImporter::LogWarn("unexpected type error, IfcShell ought to inherit from IfcConnectedFaceSet");
  1366. }
  1367. }
  1368. }
  1369. else if(const IFC::IfcSweptAreaSolid* swept = geo.ToPtr<IFC::IfcSweptAreaSolid>()) {
  1370. ProcessSweptAreaSolid(*swept,meshtmp,conv);
  1371. }
  1372. else if(const IFC::IfcManifoldSolidBrep* brep = geo.ToPtr<IFC::IfcManifoldSolidBrep>()) {
  1373. ProcessConnectedFaceSet(brep->Outer,meshtmp,conv);
  1374. }
  1375. else if(const IFC::IfcFaceBasedSurfaceModel* surf = geo.ToPtr<IFC::IfcFaceBasedSurfaceModel>()) {
  1376. BOOST_FOREACH(const IFC::IfcConnectedFaceSet& fc, surf->FbsmFaces) {
  1377. ProcessConnectedFaceSet(fc,meshtmp,conv);
  1378. }
  1379. }
  1380. else if(const IFC::IfcBooleanResult* boolean = geo.ToPtr<IFC::IfcBooleanResult>()) {
  1381. ProcessBoolean(*boolean,meshtmp,conv);
  1382. }
  1383. else if(const IFC::IfcBoundingBox* bb = geo.ToPtr<IFC::IfcBoundingBox>()) {
  1384. // silently skip over bounding boxes
  1385. return false;
  1386. }
  1387. else {
  1388. IFCImporter::LogWarn("skipping unknown IfcGeometricRepresentationItem entity, type is " + geo.GetClassName());
  1389. return false;
  1390. }
  1391. aiMesh* const mesh = meshtmp.ToMesh();
  1392. if(mesh) {
  1393. mesh->mMaterialIndex = ProcessMaterials(geo,conv);
  1394. mesh_indices.push_back(conv.meshes.size());
  1395. conv.meshes.push_back(mesh);
  1396. return true;
  1397. }
  1398. return false;
  1399. }
  1400. // ------------------------------------------------------------------------------------------------
  1401. void AssignAddedMeshes(std::vector<unsigned int>& mesh_indices,aiNode* nd,ConversionData& conv)
  1402. {
  1403. if (!mesh_indices.empty()) {
  1404. // make unique
  1405. std::sort(mesh_indices.begin(),mesh_indices.end());
  1406. std::vector<unsigned int>::iterator it_end = std::unique(mesh_indices.begin(),mesh_indices.end());
  1407. const size_t size = std::distance(mesh_indices.begin(),it_end);
  1408. nd->mNumMeshes = size;
  1409. nd->mMeshes = new unsigned int[nd->mNumMeshes];
  1410. for(unsigned int i = 0; i < nd->mNumMeshes; ++i) {
  1411. nd->mMeshes[i] = mesh_indices[i];
  1412. }
  1413. }
  1414. }
  1415. // ------------------------------------------------------------------------------------------------
  1416. bool TryQueryMeshCache(const IFC::IfcRepresentationItem& item, std::vector<unsigned int>& mesh_indices, ConversionData& conv)
  1417. {
  1418. ConversionData::MeshCache::const_iterator it = conv.cached_meshes.find(&item);
  1419. if (it != conv.cached_meshes.end()) {
  1420. std::copy((*it).second.begin(),(*it).second.end(),std::back_inserter(mesh_indices));
  1421. return true;
  1422. }
  1423. return false;
  1424. }
  1425. // ------------------------------------------------------------------------------------------------
  1426. void PopulateMeshCache(const IFC::IfcRepresentationItem& item, const std::vector<unsigned int>& mesh_indices, ConversionData& conv)
  1427. {
  1428. conv.cached_meshes[&item] = mesh_indices;
  1429. }
  1430. // ------------------------------------------------------------------------------------------------
  1431. bool ProcessRepresentationItem(const IFC::IfcRepresentationItem& item, std::vector<unsigned int>& mesh_indices, ConversionData& conv)
  1432. {
  1433. if(const IFC::IfcTopologicalRepresentationItem* const topo = item.ToPtr<IFC::IfcTopologicalRepresentationItem>()) {
  1434. if (!TryQueryMeshCache(item,mesh_indices,conv)) {
  1435. if(ProcessTopologicalItem(*topo,mesh_indices,conv)) {
  1436. if(mesh_indices.size()) {
  1437. PopulateMeshCache(item,mesh_indices,conv);
  1438. }
  1439. }
  1440. else return false;
  1441. }
  1442. return true;
  1443. }
  1444. else if(const IFC::IfcGeometricRepresentationItem* const geo = item.ToPtr<IFC::IfcGeometricRepresentationItem>()) {
  1445. if (!TryQueryMeshCache(item,mesh_indices,conv)) {
  1446. if(ProcessGeometricItem(*geo,mesh_indices,conv)) {
  1447. if(mesh_indices.size()) {
  1448. PopulateMeshCache(item,mesh_indices,conv);
  1449. }
  1450. }
  1451. else return false;
  1452. }
  1453. return true;
  1454. }
  1455. return false;
  1456. }
  1457. // ------------------------------------------------------------------------------------------------
  1458. void ResolveObjectPlacement(aiMatrix4x4& m, const IFC::IfcObjectPlacement& place, ConversionData& conv)
  1459. {
  1460. if (const IFC::IfcLocalPlacement* const local = place.ToPtr<IFC::IfcLocalPlacement>()){
  1461. ConvertAxisPlacement(m, *local->RelativePlacement, conv);
  1462. if (local->PlacementRelTo) {
  1463. aiMatrix4x4 tmp;
  1464. ResolveObjectPlacement(tmp,local->PlacementRelTo.Get(),conv);
  1465. m = tmp * m;
  1466. }
  1467. }
  1468. else {
  1469. IFCImporter::LogWarn("skipping unknown IfcObjectPlacement entity, type is " + place.GetClassName());
  1470. }
  1471. }
  1472. // ------------------------------------------------------------------------------------------------
  1473. void GetAbsTransform(aiMatrix4x4& out, const aiNode* nd, ConversionData& conv)
  1474. {
  1475. aiMatrix4x4 t;
  1476. if (nd->mParent) {
  1477. GetAbsTransform(t,nd->mParent,conv);
  1478. }
  1479. out = t*nd->mTransformation;
  1480. }
  1481. // ------------------------------------------------------------------------------------------------
  1482. void ProcessMappedItem(const IFC::IfcMappedItem& mapped, aiNode* nd_src, std::vector< aiNode* >& subnodes_src, ConversionData& conv)
  1483. {
  1484. // insert a custom node here, the cartesian transform operator is simply a conventional transformation matrix
  1485. std::auto_ptr<aiNode> nd(new aiNode());
  1486. nd->mName.Set("IfcMappedItem");
  1487. std::vector<unsigned int> meshes;
  1488. const size_t old_openings = conv.collect_openings ? conv.collect_openings->size() : 0;
  1489. const IFC::IfcRepresentation& repr = mapped.MappingSource->MappedRepresentation;
  1490. BOOST_FOREACH(const IFC::IfcRepresentationItem& item, repr.Items) {
  1491. if(!ProcessRepresentationItem(item,meshes,conv)) {
  1492. IFCImporter::LogWarn("skipping unknown mapped entity, type is " + item.GetClassName());
  1493. }
  1494. }
  1495. AssignAddedMeshes(meshes,nd.get(),conv);
  1496. // handle the cartesian operator
  1497. aiMatrix4x4 m;
  1498. ConvertTransformOperator(m, *mapped.MappingTarget);
  1499. aiMatrix4x4 msrc;
  1500. ConvertAxisPlacement(msrc,*mapped.MappingSource->MappingOrigin,conv);
  1501. aiMatrix4x4 minv = msrc;
  1502. minv.Inverse();
  1503. minv = m*msrc;
  1504. if (conv.collect_openings) {
  1505. // if this pass serves us only to collect opening geometry,
  1506. // make sure we transform the TempMesh's which we need to
  1507. // preserve as well.
  1508. if(const size_t diff = conv.collect_openings->size() - old_openings) {
  1509. for(size_t i = 0; i < diff; ++i) {
  1510. (*conv.collect_openings)[old_openings+i].Transform(minv);
  1511. }
  1512. }
  1513. }
  1514. if (conv.apply_openings) {
  1515. BOOST_FOREACH(TempOpening& open,*conv.apply_openings){
  1516. open.Transform(minv);
  1517. }
  1518. }
  1519. nd->mTransformation = nd_src->mTransformation * minv;
  1520. subnodes_src.push_back(nd.release());
  1521. }
  1522. // ------------------------------------------------------------------------------------------------
  1523. void ProcessProductRepresentation(const IFC::IfcProduct& el, aiNode* nd, std::vector< aiNode* >& subnodes, ConversionData& conv)
  1524. {
  1525. if(!el.Representation) {
  1526. return;
  1527. }
  1528. if(conv.settings.skipSpaceRepresentations) {
  1529. if(const IFC::IfcSpace* const space = el.ToPtr<IFC::IfcSpace>()) {
  1530. IFCImporter::LogWarn("skipping IfcSpace entity due to importer settings");
  1531. return;
  1532. }
  1533. }
  1534. std::vector<unsigned int> meshes;
  1535. BOOST_FOREACH(const IFC::IfcRepresentation& repr, el.Representation.Get()->Representations) {
  1536. if (conv.settings.skipCurveRepresentations && repr.RepresentationType && repr.RepresentationType.Get() == "Curve2D") {
  1537. IFCImporter::LogWarn("skipping Curve2D representation item due to importer settings");
  1538. continue;
  1539. }
  1540. BOOST_FOREACH(const IFC::IfcRepresentationItem& item, repr.Items) {
  1541. if(const IFC::IfcMappedItem* const geo = item.ToPtr<IFC::IfcMappedItem>()) {
  1542. ProcessMappedItem(*geo,nd,subnodes,conv);
  1543. }
  1544. else {
  1545. ProcessRepresentationItem(item,meshes,conv);
  1546. }
  1547. }
  1548. }
  1549. AssignAddedMeshes(meshes,nd,conv);
  1550. }
  1551. // ------------------------------------------------------------------------------------------------
  1552. aiNode* ProcessSpatialStructure(aiNode* parent, const IFC::IfcProduct& el, ConversionData& conv, std::vector<TempOpening>* collect_openings = NULL)
  1553. {
  1554. const STEP::DB::RefMap& refs = conv.db.GetRefs();
  1555. // add an output node for this spatial structure
  1556. std::auto_ptr<aiNode> nd(new aiNode());
  1557. nd->mName.Set(el.GetClassName()+"_"+(el.Name?el.Name:el.GlobalId));
  1558. nd->mParent = parent;
  1559. if(el.ObjectPlacement) {
  1560. ResolveObjectPlacement(nd->mTransformation,el.ObjectPlacement.Get(),conv);
  1561. }
  1562. std::vector<TempOpening> openings;
  1563. aiMatrix4x4 myInv;
  1564. bool didinv = false;
  1565. // convert everything contained directly within this structure,
  1566. // this may result in more nodes.
  1567. std::vector< aiNode* > subnodes;
  1568. try {
  1569. // locate aggregates and 'contained-in-here'-elements of this spatial structure and add them in recursively
  1570. // on our way, collect openings in *this* element
  1571. STEP::DB::RefMapRange range = refs.equal_range(el.GetID());
  1572. for(STEP::DB::RefMapRange range2 = range; range2.first != range.second; ++range2.first) {
  1573. const STEP::LazyObject& obj = conv.db.MustGetObject((*range2.first).second);
  1574. // handle regularly-contained elements
  1575. if(const IFC::IfcRelContainedInSpatialStructure* const cont = obj->ToPtr<IFC::IfcRelContainedInSpatialStructure>()) {
  1576. BOOST_FOREACH(const IFC::IfcProduct& pro, cont->RelatedElements) {
  1577. if(const IFC::IfcOpeningElement* const open = pro.ToPtr<IFC::IfcOpeningElement>()) {
  1578. // IfcOpeningElement is handled below. Sadly we can't use it here as is:
  1579. // The docs say that opening elements are USUALLY attached to building storeys
  1580. // but we want them for the building elements to which they belong to.
  1581. continue;
  1582. }
  1583. subnodes.push_back( ProcessSpatialStructure(nd.get(),pro,conv,NULL) );
  1584. }
  1585. }
  1586. // handle openings, which we collect in a list rather than adding them to the node graph
  1587. else if(const IFC::IfcRelVoidsElement* const fills = obj->ToPtr<IFC::IfcRelVoidsElement>()) {
  1588. if(fills->RelatingBuildingElement->GetID() == el.GetID()) {
  1589. const IFC::IfcFeatureElementSubtraction& open = fills->RelatedOpeningElement;
  1590. // move opening elements to a separate node since they are semantically different than elements that are just 'contained'
  1591. std::auto_ptr<aiNode> nd_aggr(new aiNode());
  1592. nd_aggr->mName.Set("$RelVoidsElement");
  1593. nd_aggr->mParent = nd.get();
  1594. nd_aggr->mTransformation = nd->mTransformation;
  1595. nd_aggr->mNumChildren = 1;
  1596. nd_aggr->mChildren = new aiNode*[1]();
  1597. std::vector<TempOpening> openings_local;
  1598. nd_aggr->mChildren[0] = ProcessSpatialStructure( nd_aggr.get(),open, conv,&openings_local);
  1599. if(openings_local.size()) {
  1600. if (!didinv) {
  1601. myInv = aiMatrix4x4(nd->mTransformation ).Inverse();
  1602. didinv = true;
  1603. }
  1604. // we need all openings to be in the local space of *this* node, so transform them
  1605. BOOST_FOREACH(TempOpening& op,openings_local) {
  1606. op.Transform( myInv*nd_aggr->mChildren[0]->mTransformation);
  1607. openings.push_back(op);
  1608. }
  1609. }
  1610. subnodes.push_back( nd_aggr.release() );
  1611. }
  1612. }
  1613. }
  1614. for(;range.first != range.second; ++range.first) {
  1615. if(const IFC::IfcRelAggregates* const aggr = conv.db.GetObject((*range.first).second)->ToPtr<IFC::IfcRelAggregates>()) {
  1616. // move aggregate elements to a separate node since they are semantically different than elements that are just 'contained'
  1617. std::auto_ptr<aiNode> nd_aggr(new aiNode());
  1618. nd_aggr->mName.Set("$RelAggregates");
  1619. nd_aggr->mParent = nd.get();
  1620. nd_aggr->mTransformation = nd->mTransformation;
  1621. nd_aggr->mChildren = new aiNode*[aggr->RelatedObjects.size()]();
  1622. BOOST_FOREACH(const IFC::IfcObjectDefinition& def, aggr->RelatedObjects) {
  1623. if(const IFC::IfcProduct* const prod = def.ToPtr<IFC::IfcProduct>()) {
  1624. nd_aggr->mChildren[nd_aggr->mNumChildren++] = ProcessSpatialStructure(nd_aggr.get(),*prod,conv,NULL);
  1625. }
  1626. }
  1627. subnodes.push_back( nd_aggr.release() );
  1628. }
  1629. }
  1630. conv.collect_openings = collect_openings;
  1631. if(!conv.collect_openings) {
  1632. conv.apply_openings = &openings;
  1633. }
  1634. ProcessProductRepresentation(el,nd.get(),subnodes,conv);
  1635. conv.apply_openings = conv.collect_openings = NULL;
  1636. if (subnodes.size()) {
  1637. nd->mChildren = new aiNode*[subnodes.size()]();
  1638. BOOST_FOREACH(aiNode* nd2, subnodes) {
  1639. nd->mChildren[nd->mNumChildren++] = nd2;
  1640. nd2->mParent = nd.get();
  1641. }
  1642. }
  1643. }
  1644. catch(...) {
  1645. // it hurts, but I don't want to pull boost::ptr_vector into -noboost only for these few spots here
  1646. std::for_each(subnodes.begin(),subnodes.end(),delete_fun<aiNode>());
  1647. throw;
  1648. }
  1649. return nd.release();
  1650. }
  1651. // ------------------------------------------------------------------------------------------------
  1652. void ProcessSpatialStructures(ConversionData& conv)
  1653. {
  1654. // process all products in the file. it is reasonable to assume that a
  1655. // file that is relevant for us contains at least a site or a building.
  1656. const STEP::DB::ObjectMapByType& map = conv.db.GetObjectsByType();
  1657. STEP::DB::ObjectMapRange range = map.equal_range("ifcsite");
  1658. if (range.first == map.end()) {
  1659. range = map.equal_range("ifcbuilding");
  1660. if (range.first == map.end()) {
  1661. // no site, no building - try all ids. this will take ages, but it should rarely happen.
  1662. range = STEP::DB::ObjectMapRange(map.begin(),map.end());
  1663. }
  1664. }
  1665. for(;range.first != range.second; ++range.first) {
  1666. const IFC::IfcSpatialStructureElement* const prod = (*range.first).second->ToPtr<IFC::IfcSpatialStructureElement>();
  1667. if(!prod) {
  1668. continue;
  1669. }
  1670. IFCImporter::LogDebug("looking at spatial structure `" + (prod->Name ? prod->Name.Get() : "unnamed") + "`" + (prod->ObjectType? " which is of type " + prod->ObjectType.Get():""));
  1671. // the primary site is referenced by an IFCRELAGGREGATES element which assigns it to the IFCPRODUCT
  1672. const STEP::DB::RefMap& refs = conv.db.GetRefs();
  1673. STEP::DB::RefMapRange range = refs.equal_range(conv.proj.GetID());
  1674. for(;range.first != range.second; ++range.first) {
  1675. if(const IFC::IfcRelAggregates* const aggr = conv.db.GetObject((*range.first).second)->ToPtr<IFC::IfcRelAggregates>()) {
  1676. BOOST_FOREACH(const IFC::IfcObjectDefinition& def, aggr->RelatedObjects) {
  1677. // comparing pointer values is not sufficient, we would need to cast them to the same type first
  1678. // as there is multiple inheritance in the game.
  1679. if (def.GetID() == prod->GetID()) {
  1680. IFCImporter::LogDebug("selecting this spatial structure as root structure");
  1681. // got it, this is the primary site.
  1682. conv.out->mRootNode = ProcessSpatialStructure(NULL,*prod,conv,NULL);
  1683. return;
  1684. }
  1685. }
  1686. }
  1687. }
  1688. }
  1689. IFCImporter::ThrowException("Failed to determine primary site element");
  1690. }
  1691. // ------------------------------------------------------------------------------------------------
  1692. void MakeTreeRelative(aiNode* start, const aiMatrix4x4& combined)
  1693. {
  1694. // combined is the parent's absolute transformation matrix
  1695. aiMatrix4x4 old = start->mTransformation;
  1696. if (!combined.IsIdentity()) {
  1697. start->mTransformation = aiMatrix4x4(combined).Inverse() * start->mTransformation;
  1698. }
  1699. // All nodes store absolute transformations right now, so we need to make them relative
  1700. for (unsigned int i = 0; i < start->mNumChildren; ++i) {
  1701. MakeTreeRelative(start->mChildren[i],old);
  1702. }
  1703. }
  1704. // ------------------------------------------------------------------------------------------------
  1705. void MakeTreeRelative(ConversionData& conv)
  1706. {
  1707. MakeTreeRelative(conv.out->mRootNode,aiMatrix4x4());
  1708. }
  1709. } // !anon
  1710. #endif