IFCGeometry.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2022, assimp 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 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 IFCGeometry.cpp
  34. /// @brief Geometry conversion and synthesis for IFC
  35. #ifndef ASSIMP_BUILD_NO_IFC_IMPORTER
  36. #include "IFCUtil.h"
  37. #include "Common/PolyTools.h"
  38. #include "PostProcessing/ProcessHelper.h"
  39. #include "contrib/poly2tri/poly2tri/poly2tri.h"
  40. #include "contrib/clipper/clipper.hpp"
  41. #include <iterator>
  42. #include <memory>
  43. #include <utility>
  44. namespace Assimp {
  45. namespace IFC {
  46. // ------------------------------------------------------------------------------------------------
  47. bool ProcessPolyloop(const Schema_2x3::IfcPolyLoop& loop, TempMesh& meshout, ConversionData& /*conv*/) {
  48. size_t cnt = 0;
  49. for(const Schema_2x3::IfcCartesianPoint& c : loop.Polygon) {
  50. IfcVector3 tmp;
  51. ConvertCartesianPoint(tmp,c);
  52. meshout.mVerts.push_back(tmp);
  53. ++cnt;
  54. }
  55. meshout.mVertcnt.push_back(static_cast<unsigned int>(cnt));
  56. // zero- or one- vertex polyloops simply ignored
  57. if (meshout.mVertcnt.back() > 1) {
  58. return true;
  59. }
  60. if (meshout.mVertcnt.back()==1) {
  61. meshout.mVertcnt.pop_back();
  62. meshout.mVerts.pop_back();
  63. }
  64. return false;
  65. }
  66. // ------------------------------------------------------------------------------------------------
  67. void ProcessPolygonBoundaries(TempMesh& result, const TempMesh& inmesh, size_t master_bounds = (size_t)-1) {
  68. // handle all trivial cases
  69. if(inmesh.mVertcnt.empty()) {
  70. return;
  71. }
  72. if(inmesh.mVertcnt.size() == 1) {
  73. result.Append(inmesh);
  74. return;
  75. }
  76. ai_assert(std::count(inmesh.mVertcnt.begin(), inmesh.mVertcnt.end(), 0u) == 0);
  77. typedef std::vector<unsigned int>::const_iterator face_iter;
  78. face_iter begin = inmesh.mVertcnt.begin(), end = inmesh.mVertcnt.end(), iit;
  79. std::vector<unsigned int>::const_iterator outer_polygon_it = end;
  80. // major task here: given a list of nested polygon boundaries (one of which
  81. // is the outer contour), reduce the triangulation task arising here to
  82. // one that can be solved using the "quadrulation" algorithm which we use
  83. // for pouring windows out of walls. The algorithm does not handle all
  84. // cases but at least it is numerically stable and gives "nice" triangles.
  85. // first compute normals for all polygons using Newell's algorithm
  86. // do not normalize 'normals', we need the original length for computing the polygon area
  87. std::vector<IfcVector3> normals;
  88. inmesh.ComputePolygonNormals(normals,false);
  89. // One of the polygons might be a IfcFaceOuterBound (in which case `master_bounds`
  90. // is its index). Sadly we can't rely on it, the docs say 'At most one of the bounds
  91. // shall be of the type IfcFaceOuterBound'
  92. IfcFloat area_outer_polygon = 1e-10f;
  93. if (master_bounds != (size_t)-1) {
  94. ai_assert(master_bounds < inmesh.mVertcnt.size());
  95. outer_polygon_it = begin + master_bounds;
  96. } else {
  97. for(iit = begin; iit != end; ++iit) {
  98. // find the polygon with the largest area and take it as the outer bound.
  99. IfcVector3& n = normals[std::distance(begin,iit)];
  100. const IfcFloat area = n.SquareLength();
  101. if (area > area_outer_polygon) {
  102. area_outer_polygon = area;
  103. outer_polygon_it = iit;
  104. }
  105. }
  106. }
  107. if (outer_polygon_it == end) {
  108. return;
  109. }
  110. const size_t outer_polygon_size = *outer_polygon_it;
  111. const IfcVector3& master_normal = normals[std::distance(begin, outer_polygon_it)];
  112. // Generate fake openings to meet the interface for the quadrulate
  113. // algorithm. It boils down to generating small boxes given the
  114. // inner polygon and the surface normal of the outer contour.
  115. // It is important that we use the outer contour's normal because
  116. // this is the plane onto which the quadrulate algorithm will
  117. // project the entire mesh.
  118. std::vector<TempOpening> fake_openings;
  119. fake_openings.reserve(inmesh.mVertcnt.size()-1);
  120. std::vector<IfcVector3>::const_iterator vit = inmesh.mVerts.begin(), outer_vit;
  121. for(iit = begin; iit != end; vit += *iit++) {
  122. if (iit == outer_polygon_it) {
  123. outer_vit = vit;
  124. continue;
  125. }
  126. // Filter degenerate polygons to keep them from causing trouble later on
  127. IfcVector3& n = normals[std::distance(begin,iit)];
  128. const IfcFloat area = n.SquareLength();
  129. if (area < 1e-5f) {
  130. IFCImporter::LogWarn("skipping degenerate polygon (ProcessPolygonBoundaries)");
  131. continue;
  132. }
  133. fake_openings.emplace_back();
  134. TempOpening& opening = fake_openings.back();
  135. opening.extrusionDir = master_normal;
  136. opening.solid = nullptr;
  137. opening.profileMesh = std::make_shared<TempMesh>();
  138. opening.profileMesh->mVerts.reserve(*iit);
  139. opening.profileMesh->mVertcnt.push_back(*iit);
  140. std::copy(vit, vit + *iit, std::back_inserter(opening.profileMesh->mVerts));
  141. }
  142. // fill a mesh with ONLY the main polygon
  143. TempMesh temp;
  144. temp.mVerts.reserve(outer_polygon_size);
  145. temp.mVertcnt.push_back(static_cast<unsigned int>(outer_polygon_size));
  146. std::copy(outer_vit, outer_vit+outer_polygon_size,
  147. std::back_inserter(temp.mVerts));
  148. GenerateOpenings(fake_openings, temp, false, false);
  149. result.Append(temp);
  150. }
  151. // ------------------------------------------------------------------------------------------------
  152. void ProcessConnectedFaceSet(const Schema_2x3::IfcConnectedFaceSet& fset, TempMesh& result, ConversionData& conv)
  153. {
  154. for(const Schema_2x3::IfcFace& face : fset.CfsFaces) {
  155. // size_t ob = -1, cnt = 0;
  156. TempMesh meshout;
  157. for(const Schema_2x3::IfcFaceBound& bound : face.Bounds) {
  158. if(const Schema_2x3::IfcPolyLoop* const polyloop = bound.Bound->ToPtr<Schema_2x3::IfcPolyLoop>()) {
  159. if(ProcessPolyloop(*polyloop, meshout,conv)) {
  160. // The outer boundary is better determined by checking which
  161. // polygon covers the largest area.
  162. }
  163. } else {
  164. IFCImporter::LogWarn("skipping unknown IfcFaceBound entity, type is ", bound.Bound->GetClassName());
  165. continue;
  166. }
  167. }
  168. ProcessPolygonBoundaries(result, meshout);
  169. }
  170. }
  171. // ------------------------------------------------------------------------------------------------
  172. void ProcessRevolvedAreaSolid(const Schema_2x3::IfcRevolvedAreaSolid& solid, TempMesh& result, ConversionData& conv) {
  173. TempMesh meshout;
  174. // first read the profile description
  175. if(!ProcessProfile(*solid.SweptArea,meshout,conv) || meshout.mVerts.size()<=1) {
  176. return;
  177. }
  178. IfcVector3 axis, pos;
  179. ConvertAxisPlacement(axis,pos,solid.Axis);
  180. IfcMatrix4 tb0,tb1;
  181. IfcMatrix4::Translation(pos,tb0);
  182. IfcMatrix4::Translation(-pos,tb1);
  183. const std::vector<IfcVector3>& in = meshout.mVerts;
  184. const size_t size=in.size();
  185. bool has_area = solid.SweptArea->ProfileType == "AREA" && size>2;
  186. const IfcFloat max_angle = solid.Angle*conv.angle_scale;
  187. if(std::fabs(max_angle) < 1e-3) {
  188. if(has_area) {
  189. result = meshout;
  190. }
  191. return;
  192. }
  193. const unsigned int cnt_segments =
  194. std::max(2u,static_cast<unsigned int>(conv.settings.cylindricalTessellation * std::fabs(max_angle)/AI_MATH_HALF_PI_F));
  195. const IfcFloat delta = max_angle/cnt_segments;
  196. has_area = has_area && std::fabs(max_angle) < AI_MATH_TWO_PI_F*0.99;
  197. result.mVerts.reserve(size*((cnt_segments+1)*4+(has_area?2:0)));
  198. result.mVertcnt.reserve(size*cnt_segments+2);
  199. IfcMatrix4 rot;
  200. rot = tb0 * IfcMatrix4::Rotation(delta,axis,rot) * tb1;
  201. size_t base = 0;
  202. std::vector<IfcVector3>& out = result.mVerts;
  203. // dummy data to simplify later processing
  204. for(size_t i = 0; i < size; ++i) {
  205. out.insert(out.end(),4,in[i]);
  206. }
  207. for(unsigned int seg = 0; seg < cnt_segments; ++seg) {
  208. for(size_t i = 0; i < size; ++i) {
  209. const size_t next = (i+1)%size;
  210. result.mVertcnt.push_back(4);
  211. const IfcVector3 base_0 = out[base+i*4+3],base_1 = out[base+next*4+3];
  212. out.push_back(base_0);
  213. out.push_back(base_1);
  214. out.push_back(rot*base_1);
  215. out.push_back(rot*base_0);
  216. }
  217. base += size*4;
  218. }
  219. out.erase(out.begin(),out.begin()+size*4);
  220. if(has_area) {
  221. // leave the triangulation of the profile area to the ear cutting
  222. // implementation in aiProcess_Triangulate - for now we just
  223. // feed in two huge polygons.
  224. base -= size*8;
  225. for(size_t i = size; i--; ) {
  226. out.push_back(out[base+i*4+3]);
  227. }
  228. for(size_t i = 0; i < size; ++i ) {
  229. out.push_back(out[i*4]);
  230. }
  231. result.mVertcnt.push_back(static_cast<unsigned int>(size));
  232. result.mVertcnt.push_back(static_cast<unsigned int>(size));
  233. }
  234. IfcMatrix4 trafo;
  235. ConvertAxisPlacement(trafo, solid.Position);
  236. result.Transform(trafo);
  237. IFCImporter::LogVerboseDebug("generate mesh procedurally by radial extrusion (IfcRevolvedAreaSolid)");
  238. }
  239. // ------------------------------------------------------------------------------------------------
  240. void ProcessSweptDiskSolid(const Schema_2x3::IfcSweptDiskSolid &solid,
  241. TempMesh& result,
  242. ConversionData& conv) {
  243. const Curve* const curve = Curve::Convert(*solid.Directrix, conv);
  244. if(!curve) {
  245. IFCImporter::LogError("failed to convert Directrix curve (IfcSweptDiskSolid)");
  246. return;
  247. }
  248. const unsigned int cnt_segments = conv.settings.cylindricalTessellation;
  249. const IfcFloat deltaAngle = AI_MATH_TWO_PI/cnt_segments;
  250. TempMesh temp;
  251. curve->SampleDiscrete(temp, solid.StartParam, solid.EndParam);
  252. const std::vector<IfcVector3>& curve_points = temp.mVerts;
  253. const size_t samples = curve_points.size();
  254. result.mVerts.reserve(cnt_segments * samples * 4);
  255. result.mVertcnt.reserve((cnt_segments - 1) * samples);
  256. std::vector<IfcVector3> points;
  257. points.reserve(cnt_segments * samples);
  258. if(curve_points.empty()) {
  259. IFCImporter::LogWarn("curve evaluation yielded no points (IfcSweptDiskSolid)");
  260. return;
  261. }
  262. IfcVector3 current = curve_points[0];
  263. IfcVector3 previous = current;
  264. IfcVector3 next;
  265. IfcVector3 startvec;
  266. startvec.x = 1.0f;
  267. startvec.y = 1.0f;
  268. startvec.z = 1.0f;
  269. unsigned int last_dir = 0;
  270. // generate circles at the sweep positions
  271. for(size_t i = 0; i < samples; ++i) {
  272. if(i != samples - 1) {
  273. next = curve_points[i + 1];
  274. }
  275. // get a direction vector reflecting the approximate curvature (i.e. tangent)
  276. IfcVector3 d = (current-previous) + (next-previous);
  277. d.Normalize();
  278. // figure out an arbitrary point q so that (p-q) * d = 0,
  279. // try to maximize ||(p-q)|| * ||(p_last-q_last)||
  280. IfcVector3 q;
  281. bool take_any = false;
  282. for (unsigned int j = 0; j < 2; ++j, take_any = true) {
  283. if ((last_dir == 0 || take_any) && std::abs(d.x) > ai_epsilon) {
  284. q.y = startvec.y;
  285. q.z = startvec.z;
  286. q.x = -(d.y * q.y + d.z * q.z) / d.x;
  287. last_dir = 0;
  288. break;
  289. } else if ((last_dir == 1 || take_any) && std::abs(d.y) > ai_epsilon) {
  290. q.x = startvec.x;
  291. q.z = startvec.z;
  292. q.y = -(d.x * q.x + d.z * q.z) / d.y;
  293. last_dir = 1;
  294. break;
  295. } else if ((last_dir == 2 && std::abs(d.z) > ai_epsilon) || take_any) {
  296. q.y = startvec.y;
  297. q.x = startvec.x;
  298. q.z = -(d.y * q.y + d.x * q.x) / d.z;
  299. last_dir = 2;
  300. break;
  301. }
  302. }
  303. q *= solid.Radius / q.Length();
  304. startvec = q;
  305. // generate a rotation matrix to rotate q around d
  306. IfcMatrix4 rot;
  307. IfcMatrix4::Rotation(deltaAngle,d,rot);
  308. for (unsigned int seg = 0; seg < cnt_segments; ++seg, q *= rot ) {
  309. points.push_back(q + current);
  310. }
  311. previous = current;
  312. current = next;
  313. }
  314. // make quads
  315. for(size_t i = 0; i < samples - 1; ++i) {
  316. const aiVector3D& this_start = points[ i * cnt_segments ];
  317. // locate corresponding point on next sample ring
  318. unsigned int best_pair_offset = 0;
  319. float best_distance_squared = 1e10f;
  320. for (unsigned int seg = 0; seg < cnt_segments; ++seg) {
  321. const aiVector3D& p = points[ (i+1) * cnt_segments + seg];
  322. const float l = (p-this_start).SquareLength();
  323. if(l < best_distance_squared) {
  324. best_pair_offset = seg;
  325. best_distance_squared = l;
  326. }
  327. }
  328. for (unsigned int seg = 0; seg < cnt_segments; ++seg) {
  329. result.mVerts.push_back(points[ i * cnt_segments + (seg % cnt_segments)]);
  330. result.mVerts.push_back(points[ i * cnt_segments + (seg + 1) % cnt_segments]);
  331. result.mVerts.push_back(points[ (i+1) * cnt_segments + ((seg + 1 + best_pair_offset) % cnt_segments)]);
  332. result.mVerts.push_back(points[ (i+1) * cnt_segments + ((seg + best_pair_offset) % cnt_segments)]);
  333. IfcVector3& v1 = *(result.mVerts.end()-1);
  334. IfcVector3& v2 = *(result.mVerts.end()-2);
  335. IfcVector3& v3 = *(result.mVerts.end()-3);
  336. IfcVector3& v4 = *(result.mVerts.end()-4);
  337. if (((v4-v3) ^ (v4-v1)) * (v4 - curve_points[i]) < 0.0f) {
  338. std::swap(v4, v1);
  339. std::swap(v3, v2);
  340. }
  341. result.mVertcnt.push_back(4);
  342. }
  343. }
  344. IFCImporter::LogVerboseDebug("generate mesh procedurally by sweeping a disk along a curve (IfcSweptDiskSolid)");
  345. }
  346. // ------------------------------------------------------------------------------------------------
  347. IfcMatrix3 DerivePlaneCoordinateSpace(const TempMesh& curmesh, bool& ok, IfcVector3& norOut) {
  348. const std::vector<IfcVector3>& out = curmesh.mVerts;
  349. IfcMatrix3 m;
  350. ok = true;
  351. // The input "mesh" must be a single polygon
  352. const size_t s = out.size();
  353. ai_assert( curmesh.mVertcnt.size() == 1 );
  354. ai_assert( curmesh.mVertcnt.back() == s);
  355. const IfcVector3 any_point = out[s-1];
  356. IfcVector3 nor;
  357. // The input polygon is arbitrarily shaped, therefore we might need some tries
  358. // until we find a suitable normal. Note that Newell's algorithm would give
  359. // a more robust result, but this variant also gives us a suitable first
  360. // axis for the 2D coordinate space on the polygon plane, exploiting the
  361. // fact that the input polygon is nearly always a quad.
  362. bool done = false;
  363. size_t idx( 0 );
  364. for (size_t i = 0; !done && i < s-2; done || ++i) {
  365. idx = i;
  366. for (size_t j = i+1; j < s-1; ++j) {
  367. nor = -((out[i]-any_point)^(out[j]-any_point));
  368. if(std::fabs(nor.Length()) > 1e-8f) {
  369. done = true;
  370. break;
  371. }
  372. }
  373. }
  374. if(!done) {
  375. ok = false;
  376. return m;
  377. }
  378. nor.Normalize();
  379. norOut = nor;
  380. IfcVector3 r = (out[idx]-any_point);
  381. r.Normalize();
  382. // Reconstruct orthonormal basis
  383. // XXX use Gram Schmidt for increased robustness
  384. IfcVector3 u = r ^ nor;
  385. u.Normalize();
  386. m.a1 = r.x;
  387. m.a2 = r.y;
  388. m.a3 = r.z;
  389. m.b1 = u.x;
  390. m.b2 = u.y;
  391. m.b3 = u.z;
  392. m.c1 = -nor.x;
  393. m.c2 = -nor.y;
  394. m.c3 = -nor.z;
  395. return m;
  396. }
  397. const auto closeDistance = ai_epsilon;
  398. bool areClose(Schema_2x3::IfcCartesianPoint pt1,Schema_2x3::IfcCartesianPoint pt2) {
  399. if(pt1.Coordinates.size() != pt2.Coordinates.size()) {
  400. IFCImporter::LogWarn("unable to compare differently-dimensioned points");
  401. return false;
  402. }
  403. auto coord1 = pt1.Coordinates.begin();
  404. auto coord2 = pt2.Coordinates.begin();
  405. // we're just testing each dimension separately rather than doing euclidean distance, as we're
  406. // looking for very close coordinates
  407. for(; coord1 != pt1.Coordinates.end(); coord1++,coord2++) {
  408. if(std::fabs(*coord1 - *coord2) > closeDistance) {
  409. return false;
  410. }
  411. }
  412. return true;
  413. }
  414. bool areClose(IfcVector3 pt1,IfcVector3 pt2) {
  415. return (std::fabs(pt1.x - pt2.x) < closeDistance &&
  416. std::fabs(pt1.y - pt2.y) < closeDistance &&
  417. std::fabs(pt1.z - pt2.z) < closeDistance);
  418. }
  419. // Extrudes the given polygon along the direction, converts it into an opening or applies all openings as necessary.
  420. void ProcessExtrudedArea(const Schema_2x3::IfcExtrudedAreaSolid& solid, const TempMesh& curve,
  421. const IfcVector3& extrusionDir, TempMesh& result, ConversionData &conv, bool collect_openings)
  422. {
  423. // Outline: 'curve' is now a list of vertex points forming the underlying profile, extrude along the given axis,
  424. // forming new triangles.
  425. const bool has_area = solid.SweptArea->ProfileType == "AREA" && curve.mVerts.size() > 2;
  426. if (solid.Depth < ai_epsilon) {
  427. if( has_area ) {
  428. result.Append(curve);
  429. }
  430. return;
  431. }
  432. result.mVerts.reserve(curve.mVerts.size()*(has_area ? 4 : 2));
  433. result.mVertcnt.reserve(curve.mVerts.size() + 2);
  434. std::vector<IfcVector3> in = curve.mVerts;
  435. // First step: transform all vertices into the target coordinate space
  436. IfcMatrix4 trafo;
  437. ConvertAxisPlacement(trafo, solid.Position);
  438. IfcVector3 vmin, vmax;
  439. MinMaxChooser<IfcVector3>()(vmin, vmax);
  440. for(IfcVector3& v : in) {
  441. v *= trafo;
  442. vmin = std::min(vmin, v);
  443. vmax = std::max(vmax, v);
  444. }
  445. vmax -= vmin;
  446. const IfcFloat diag = vmax.Length();
  447. IfcVector3 dir = IfcMatrix3(trafo) * extrusionDir;
  448. // reverse profile polygon if it's winded in the wrong direction in relation to the extrusion direction
  449. IfcVector3 profileNormal = TempMesh::ComputePolygonNormal(in.data(), in.size());
  450. if( profileNormal * dir < 0.0 ) {
  451. std::reverse(in.begin(), in.end());
  452. }
  453. std::vector<IfcVector3> nors;
  454. const bool openings = !!conv.apply_openings && conv.apply_openings->size();
  455. // Compute the normal vectors for all opening polygons as a prerequisite
  456. // to TryAddOpenings_Poly2Tri()
  457. // XXX this belongs into the aforementioned function
  458. if( openings ) {
  459. if( !conv.settings.useCustomTriangulation ) {
  460. // it is essential to apply the openings in the correct spatial order. The direction
  461. // doesn't matter, but we would screw up if we started with e.g. a door in between
  462. // two windows.
  463. std::sort(conv.apply_openings->begin(), conv.apply_openings->end(), TempOpening::DistanceSorter(in[0]));
  464. }
  465. nors.reserve(conv.apply_openings->size());
  466. for(TempOpening& t : *conv.apply_openings) {
  467. TempMesh &bounds = *t.profileMesh;
  468. if( bounds.mVerts.size() <= 2 ) {
  469. nors.emplace_back();
  470. continue;
  471. }
  472. auto nor = ((bounds.mVerts[2] - bounds.mVerts[0]) ^ (bounds.mVerts[1] - bounds.mVerts[0])).Normalize();
  473. auto vI0 = bounds.mVertcnt[0];
  474. for(size_t faceI = 0; faceI < bounds.mVertcnt.size(); faceI++)
  475. {
  476. if(bounds.mVertcnt[faceI] >= 3) {
  477. // do a check that this is at least parallel to the base plane
  478. auto nor2 = ((bounds.mVerts[vI0 + 2] - bounds.mVerts[vI0]) ^ (bounds.mVerts[vI0 + 1] - bounds.mVerts[vI0])).Normalize();
  479. if(!areClose(nor,nor2)) {
  480. std::stringstream msg;
  481. msg << "Face " << faceI << " is not parallel with face 0 - opening on entity " << solid.GetID();
  482. IFCImporter::LogWarn(msg.str().c_str());
  483. }
  484. }
  485. }
  486. nors.push_back(nor);
  487. }
  488. }
  489. TempMesh temp;
  490. TempMesh& curmesh = openings ? temp : result;
  491. std::vector<IfcVector3>& out = curmesh.mVerts;
  492. size_t sides_with_openings = 0;
  493. for( size_t i = 0; i < in.size(); ++i ) {
  494. const size_t next = (i + 1) % in.size();
  495. curmesh.mVertcnt.push_back(4);
  496. out.push_back(in[i]);
  497. out.push_back(in[next]);
  498. out.push_back(in[next] + dir);
  499. out.push_back(in[i] + dir);
  500. if( openings ) {
  501. if( (in[i] - in[next]).Length() > diag * 0.1 && GenerateOpenings(*conv.apply_openings, temp, true, true, dir) ) {
  502. ++sides_with_openings;
  503. }
  504. result.Append(temp);
  505. temp.Clear();
  506. }
  507. }
  508. if(openings) {
  509. for(TempOpening& opening : *conv.apply_openings) {
  510. if(!opening.wallPoints.empty()) {
  511. std::stringstream msg;
  512. msg << "failed to generate all window caps on ID " << (int)solid.GetID();
  513. IFCImporter::LogError(msg.str().c_str());
  514. }
  515. opening.wallPoints.clear();
  516. }
  517. }
  518. size_t sides_with_v_openings = 0;
  519. if(has_area) {
  520. for(size_t n = 0; n < 2; ++n) {
  521. if(n > 0) {
  522. for(size_t i = 0; i < in.size(); ++i)
  523. out.push_back(in[i] + dir);
  524. } else {
  525. for(size_t i = in.size(); i--; )
  526. out.push_back(in[i]);
  527. }
  528. curmesh.mVertcnt.push_back(static_cast<unsigned int>(in.size()));
  529. if(openings && in.size() > 2) {
  530. if(GenerateOpenings(*conv.apply_openings,temp,true,true,dir)) {
  531. ++sides_with_v_openings;
  532. }
  533. result.Append(temp);
  534. temp.Clear();
  535. }
  536. }
  537. }
  538. if (openings && (sides_with_openings == 1 || sides_with_v_openings == 2)) {
  539. std::stringstream msg;
  540. msg << "failed to resolve all openings, presumably their topology is not supported by Assimp - ID " << solid.GetID() << " sides_with_openings " << sides_with_openings << " sides_with_v_openings " << sides_with_v_openings;
  541. IFCImporter::LogWarn(msg.str().c_str());
  542. }
  543. IFCImporter::LogVerboseDebug("generate mesh procedurally by extrusion (IfcExtrudedAreaSolid)");
  544. // If this is an opening element, store both the extruded mesh and the 2D profile mesh
  545. // it was created from. Return an empty mesh to the caller.
  546. if( collect_openings && !result.IsEmpty() ) {
  547. ai_assert(conv.collect_openings);
  548. std::shared_ptr<TempMesh> profile = std::shared_ptr<TempMesh>(new TempMesh());
  549. profile->Swap(result);
  550. std::shared_ptr<TempMesh> profile2D = std::shared_ptr<TempMesh>(new TempMesh());
  551. profile2D->mVerts.insert(profile2D->mVerts.end(), in.begin(), in.end());
  552. profile2D->mVertcnt.push_back(static_cast<unsigned int>(in.size()));
  553. conv.collect_openings->push_back(TempOpening(&solid, dir, std::move(profile), std::move(profile2D)));
  554. ai_assert(result.IsEmpty());
  555. }
  556. }
  557. // ------------------------------------------------------------------------------------------------
  558. void ProcessExtrudedAreaSolid(const Schema_2x3::IfcExtrudedAreaSolid& solid,
  559. TempMesh& result,
  560. ConversionData& conv,
  561. bool collect_openings) {
  562. TempMesh meshout;
  563. // First read the profile description.
  564. if(!ProcessProfile(*solid.SweptArea,meshout,conv) || meshout.mVerts.size()<=1) {
  565. return;
  566. }
  567. IfcVector3 dir;
  568. ConvertDirection(dir,solid.ExtrudedDirection);
  569. dir *= solid.Depth;
  570. // Some profiles bring their own holes, for which we need to provide a container. This all is somewhat backwards,
  571. // and there's still so many corner cases uncovered - we really need a generic solution to all of this hole carving.
  572. std::vector<TempOpening> fisherPriceMyFirstOpenings;
  573. std::vector<TempOpening>* oldApplyOpenings = conv.apply_openings;
  574. if( const Schema_2x3::IfcArbitraryProfileDefWithVoids* const cprofile = solid.SweptArea->ToPtr<Schema_2x3::IfcArbitraryProfileDefWithVoids>() ) {
  575. if( !cprofile->InnerCurves.empty() ) {
  576. // read all inner curves and extrude them to form proper openings.
  577. std::vector<TempOpening>* oldCollectOpenings = conv.collect_openings;
  578. conv.collect_openings = &fisherPriceMyFirstOpenings;
  579. for (const Schema_2x3::IfcCurve* curve : cprofile->InnerCurves) {
  580. TempMesh curveMesh, tempMesh;
  581. ProcessCurve(*curve, curveMesh, conv);
  582. ProcessExtrudedArea(solid, curveMesh, dir, tempMesh, conv, true);
  583. }
  584. // and then apply those to the geometry we're about to generate
  585. conv.apply_openings = conv.collect_openings;
  586. conv.collect_openings = oldCollectOpenings;
  587. }
  588. }
  589. ProcessExtrudedArea(solid, meshout, dir, result, conv, collect_openings);
  590. conv.apply_openings = oldApplyOpenings;
  591. }
  592. // ------------------------------------------------------------------------------------------------
  593. void ProcessSweptAreaSolid(const Schema_2x3::IfcSweptAreaSolid& swept,
  594. TempMesh& meshout,
  595. ConversionData& conv) {
  596. if(const Schema_2x3::IfcExtrudedAreaSolid* const solid = swept.ToPtr<Schema_2x3::IfcExtrudedAreaSolid>()) {
  597. ProcessExtrudedAreaSolid(*solid,meshout,conv, !!conv.collect_openings);
  598. } else if(const Schema_2x3::IfcRevolvedAreaSolid* const rev = swept.ToPtr<Schema_2x3::IfcRevolvedAreaSolid>()) {
  599. ProcessRevolvedAreaSolid(*rev,meshout,conv);
  600. } else {
  601. IFCImporter::LogWarn("skipping unknown IfcSweptAreaSolid entity, type is ", swept.GetClassName());
  602. }
  603. }
  604. // ------------------------------------------------------------------------------------------------
  605. bool ProcessGeometricItem(const Schema_2x3::IfcRepresentationItem& geo,
  606. unsigned int matid,
  607. std::set<unsigned int>& mesh_indices,
  608. ConversionData& conv) {
  609. bool fix_orientation = false;
  610. std::shared_ptr< TempMesh > meshtmp = std::make_shared<TempMesh>();
  611. if(const Schema_2x3::IfcShellBasedSurfaceModel* shellmod = geo.ToPtr<Schema_2x3::IfcShellBasedSurfaceModel>()) {
  612. for (const std::shared_ptr<const Schema_2x3::IfcShell> &shell : shellmod->SbsmBoundary) {
  613. try {
  614. const ::Assimp::STEP::EXPRESS::ENTITY& e = shell->To<::Assimp::STEP::EXPRESS::ENTITY>();
  615. const Schema_2x3::IfcConnectedFaceSet& fs = conv.db.MustGetObject(e).To<Schema_2x3::IfcConnectedFaceSet>();
  616. ProcessConnectedFaceSet(fs, *meshtmp, conv);
  617. } catch(std::bad_cast&) {
  618. IFCImporter::LogWarn("unexpected type error, IfcShell ought to inherit from IfcConnectedFaceSet");
  619. }
  620. }
  621. fix_orientation = true;
  622. } else if(const Schema_2x3::IfcConnectedFaceSet* fset = geo.ToPtr<Schema_2x3::IfcConnectedFaceSet>()) {
  623. ProcessConnectedFaceSet(*fset, *meshtmp, conv);
  624. fix_orientation = true;
  625. } else if(const Schema_2x3::IfcSweptAreaSolid* swept = geo.ToPtr<Schema_2x3::IfcSweptAreaSolid>()) {
  626. ProcessSweptAreaSolid(*swept, *meshtmp, conv);
  627. } else if(const Schema_2x3::IfcSweptDiskSolid* disk = geo.ToPtr<Schema_2x3::IfcSweptDiskSolid>()) {
  628. ProcessSweptDiskSolid(*disk, *meshtmp, conv);
  629. } else if(const Schema_2x3::IfcManifoldSolidBrep* brep = geo.ToPtr<Schema_2x3::IfcManifoldSolidBrep>()) {
  630. ProcessConnectedFaceSet(brep->Outer, *meshtmp, conv);
  631. fix_orientation = true;
  632. } else if(const Schema_2x3::IfcFaceBasedSurfaceModel* surf = geo.ToPtr<Schema_2x3::IfcFaceBasedSurfaceModel>()) {
  633. for(const Schema_2x3::IfcConnectedFaceSet& fc : surf->FbsmFaces) {
  634. ProcessConnectedFaceSet(fc, *meshtmp, conv);
  635. }
  636. fix_orientation = true;
  637. } else if(const Schema_2x3::IfcBooleanResult* boolean = geo.ToPtr<Schema_2x3::IfcBooleanResult>()) {
  638. ProcessBoolean(*boolean, *meshtmp, conv);
  639. } else if(geo.ToPtr<Schema_2x3::IfcBoundingBox>()) {
  640. // silently skip over bounding boxes
  641. return false;
  642. } else {
  643. std::stringstream toLog;
  644. toLog << "skipping unknown IfcGeometricRepresentationItem entity, type is " << geo.GetClassName() << " id is " << geo.GetID();
  645. IFCImporter::LogWarn(toLog.str().c_str());
  646. return false;
  647. }
  648. // Do we just collect openings for a parent element (i.e. a wall)?
  649. // In such a case, we generate the polygonal mesh as usual,
  650. // but attach it to a TempOpening instance which will later be applied
  651. // to the wall it pertains to.
  652. // Note: swep area solids are added in ProcessExtrudedAreaSolid(),
  653. // which returns an empty mesh.
  654. if(conv.collect_openings) {
  655. if (!meshtmp->IsEmpty()) {
  656. conv.collect_openings->push_back(TempOpening(geo.ToPtr<Schema_2x3::IfcSolidModel>(),
  657. IfcVector3(0,0,0),
  658. std::move(meshtmp),
  659. std::shared_ptr<TempMesh>()));
  660. }
  661. return true;
  662. }
  663. if (meshtmp->IsEmpty()) {
  664. return false;
  665. }
  666. meshtmp->RemoveAdjacentDuplicates();
  667. meshtmp->RemoveDegenerates();
  668. if(fix_orientation) {
  669. // meshtmp->FixupFaceOrientation();
  670. }
  671. aiMesh* const mesh = meshtmp->ToMesh();
  672. if(mesh) {
  673. mesh->mMaterialIndex = matid;
  674. mesh_indices.insert(static_cast<unsigned int>(conv.meshes.size()));
  675. conv.meshes.push_back(mesh);
  676. return true;
  677. }
  678. return false;
  679. }
  680. // ------------------------------------------------------------------------------------------------
  681. void AssignAddedMeshes(std::set<unsigned int>& mesh_indices,aiNode* nd, ConversionData& /*conv*/) {
  682. if (!mesh_indices.empty()) {
  683. std::set<unsigned int>::const_iterator it = mesh_indices.cbegin();
  684. std::set<unsigned int>::const_iterator end = mesh_indices.cend();
  685. nd->mNumMeshes = static_cast<unsigned int>(mesh_indices.size());
  686. nd->mMeshes = new unsigned int[nd->mNumMeshes];
  687. for(unsigned int i = 0; it != end && i < nd->mNumMeshes; ++i, ++it) {
  688. nd->mMeshes[i] = *it;
  689. }
  690. }
  691. }
  692. // ------------------------------------------------------------------------------------------------
  693. bool TryQueryMeshCache(const Schema_2x3::IfcRepresentationItem& item,
  694. std::set<unsigned int>& mesh_indices,
  695. unsigned int mat_index,
  696. ConversionData& conv) {
  697. ConversionData::MeshCacheIndex idx(&item, mat_index);
  698. ConversionData::MeshCache::const_iterator it = conv.cached_meshes.find(idx);
  699. if (it != conv.cached_meshes.end()) {
  700. std::copy((*it).second.begin(),(*it).second.end(),std::inserter(mesh_indices, mesh_indices.end()));
  701. return true;
  702. }
  703. return false;
  704. }
  705. // ------------------------------------------------------------------------------------------------
  706. void PopulateMeshCache(const Schema_2x3::IfcRepresentationItem& item,
  707. const std::set<unsigned int>& mesh_indices,
  708. unsigned int mat_index,
  709. ConversionData& conv) {
  710. ConversionData::MeshCacheIndex idx(&item, mat_index);
  711. conv.cached_meshes[idx] = mesh_indices;
  712. }
  713. // ------------------------------------------------------------------------------------------------
  714. bool ProcessRepresentationItem(const Schema_2x3::IfcRepresentationItem& item,
  715. unsigned int matid,
  716. std::set<unsigned int>& mesh_indices,
  717. ConversionData& conv) {
  718. // determine material
  719. unsigned int localmatid = ProcessMaterials(item.GetID(), matid, conv, true);
  720. if (!TryQueryMeshCache(item,mesh_indices,localmatid,conv)) {
  721. if(ProcessGeometricItem(item,localmatid,mesh_indices,conv)) {
  722. if(mesh_indices.size()) {
  723. PopulateMeshCache(item,mesh_indices,localmatid,conv);
  724. }
  725. } else {
  726. return false;
  727. }
  728. }
  729. return true;
  730. }
  731. } // ! IFC
  732. } // ! Assimp
  733. #endif // ASSIMP_BUILD_NO_IFC_IMPORTER