IFCLoader.cpp 57 KB

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