IFCBoolean.cpp 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2010, 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 IFCBoolean.cpp
  34. * @brief Implements a subset of Ifc boolean operations
  35. */
  36. #ifndef ASSIMP_BUILD_NO_IFC_IMPORTER
  37. #include "IFCUtil.h"
  38. #include "PolyTools.h"
  39. #include "ProcessHelper.h"
  40. #include "Defines.h"
  41. #include <iterator>
  42. #include <tuple>
  43. namespace Assimp {
  44. namespace IFC {
  45. // ------------------------------------------------------------------------------------------------
  46. // Calculates intersection between line segment and plane. To catch corner cases, specify which side you prefer.
  47. // The function then generates a hit only if the end is beyond a certain margin in that direction, filtering out
  48. // "very close to plane" ghost hits as long as start and end stay directly on or within the given plane side.
  49. bool IntersectSegmentPlane(const IfcVector3& p,const IfcVector3& n, const IfcVector3& e0,
  50. const IfcVector3& e1, bool assumeStartOnWhiteSide, IfcVector3& out)
  51. {
  52. const IfcVector3 pdelta = e0 - p, seg = e1 - e0;
  53. const IfcFloat dotOne = n*seg, dotTwo = -(n*pdelta);
  54. // if segment ends on plane, do not report a hit. We stay on that side until a following segment starting at this
  55. // point leaves the plane through the other side
  56. if( std::abs(dotOne + dotTwo) < 1e-6 )
  57. return false;
  58. // if segment starts on the plane, report a hit only if the end lies on the *other* side
  59. if( std::abs(dotTwo) < 1e-6 )
  60. {
  61. if( (assumeStartOnWhiteSide && dotOne + dotTwo < 1e-6) || (!assumeStartOnWhiteSide && dotOne + dotTwo > -1e-6) )
  62. {
  63. out = e0;
  64. return true;
  65. }
  66. else
  67. {
  68. return false;
  69. }
  70. }
  71. // ignore if segment is parallel to plane and far away from it on either side
  72. // Warning: if there's a few thousand of such segments which slowly accumulate beyond the epsilon, no hit would be registered
  73. if( std::abs(dotOne) < 1e-6 )
  74. return false;
  75. // t must be in [0..1] if the intersection point is within the given segment
  76. const IfcFloat t = dotTwo / dotOne;
  77. if( t > 1.0 || t < 0.0 )
  78. return false;
  79. out = e0 + t*seg;
  80. return true;
  81. }
  82. // ------------------------------------------------------------------------------------------------
  83. void FilterPolygon(std::vector<IfcVector3>& resultpoly)
  84. {
  85. if( resultpoly.size() < 3 )
  86. {
  87. resultpoly.clear();
  88. return;
  89. }
  90. IfcVector3 vmin, vmax;
  91. ArrayBounds(resultpoly.data(), static_cast<unsigned int>(resultpoly.size()), vmin, vmax);
  92. // filter our IfcFloat points - those may happen if a point lies
  93. // directly on the intersection line or directly on the clipping plane
  94. const IfcFloat epsilon = (vmax - vmin).SquareLength() / 1e6f;
  95. FuzzyVectorCompare fz(epsilon);
  96. std::vector<IfcVector3>::iterator e = std::unique(resultpoly.begin(), resultpoly.end(), fz);
  97. if( e != resultpoly.end() )
  98. resultpoly.erase(e, resultpoly.end());
  99. if( !resultpoly.empty() && fz(resultpoly.front(), resultpoly.back()) )
  100. resultpoly.pop_back();
  101. }
  102. // ------------------------------------------------------------------------------------------------
  103. void WritePolygon(std::vector<IfcVector3>& resultpoly, TempMesh& result)
  104. {
  105. FilterPolygon(resultpoly);
  106. if( resultpoly.size() > 2 )
  107. {
  108. result.verts.insert(result.verts.end(), resultpoly.begin(), resultpoly.end());
  109. result.vertcnt.push_back(static_cast<unsigned int>(resultpoly.size()));
  110. }
  111. }
  112. // ------------------------------------------------------------------------------------------------
  113. void ProcessBooleanHalfSpaceDifference(const IfcHalfSpaceSolid* hs, TempMesh& result,
  114. const TempMesh& first_operand,
  115. ConversionData& /*conv*/)
  116. {
  117. ai_assert(hs != NULL);
  118. const IfcPlane* const plane = hs->BaseSurface->ToPtr<IfcPlane>();
  119. if(!plane) {
  120. IFCImporter::LogError("expected IfcPlane as base surface for the IfcHalfSpaceSolid");
  121. return;
  122. }
  123. // extract plane base position vector and normal vector
  124. IfcVector3 p,n(0.f,0.f,1.f);
  125. if (plane->Position->Axis) {
  126. ConvertDirection(n,plane->Position->Axis.Get());
  127. }
  128. ConvertCartesianPoint(p,plane->Position->Location);
  129. if(!IsTrue(hs->AgreementFlag)) {
  130. n *= -1.f;
  131. }
  132. // clip the current contents of `meshout` against the plane we obtained from the second operand
  133. const std::vector<IfcVector3>& in = first_operand.verts;
  134. std::vector<IfcVector3>& outvert = result.verts;
  135. std::vector<unsigned int>::const_iterator begin = first_operand.vertcnt.begin(),
  136. end = first_operand.vertcnt.end(), iit;
  137. outvert.reserve(in.size());
  138. result.vertcnt.reserve(first_operand.vertcnt.size());
  139. unsigned int vidx = 0;
  140. for(iit = begin; iit != end; vidx += *iit++) {
  141. unsigned int newcount = 0;
  142. bool isAtWhiteSide = (in[vidx] - p) * n > -1e-6;
  143. for( unsigned int i = 0; i < *iit; ++i ) {
  144. const IfcVector3& e0 = in[vidx + i], e1 = in[vidx + (i + 1) % *iit];
  145. // does the next segment intersect the plane?
  146. IfcVector3 isectpos;
  147. if( IntersectSegmentPlane(p, n, e0, e1, isAtWhiteSide, isectpos) ) {
  148. if( isAtWhiteSide ) {
  149. // e0 is on the right side, so keep it
  150. outvert.push_back(e0);
  151. outvert.push_back(isectpos);
  152. newcount += 2;
  153. }
  154. else {
  155. // e0 is on the wrong side, so drop it and keep e1 instead
  156. outvert.push_back(isectpos);
  157. ++newcount;
  158. }
  159. isAtWhiteSide = !isAtWhiteSide;
  160. }
  161. else
  162. {
  163. if( isAtWhiteSide ) {
  164. outvert.push_back(e0);
  165. ++newcount;
  166. }
  167. }
  168. }
  169. if (!newcount) {
  170. continue;
  171. }
  172. IfcVector3 vmin,vmax;
  173. ArrayBounds(&*(outvert.end()-newcount),newcount,vmin,vmax);
  174. // filter our IfcFloat points - those may happen if a point lies
  175. // directly on the intersection line. However, due to IfcFloat
  176. // precision a bitwise comparison is not feasible to detect
  177. // this case.
  178. const IfcFloat epsilon = (vmax-vmin).SquareLength() / 1e6f;
  179. FuzzyVectorCompare fz(epsilon);
  180. std::vector<IfcVector3>::iterator e = std::unique( outvert.end()-newcount, outvert.end(), fz );
  181. if (e != outvert.end()) {
  182. newcount -= static_cast<unsigned int>(std::distance(e,outvert.end()));
  183. outvert.erase(e,outvert.end());
  184. }
  185. if (fz(*( outvert.end()-newcount),outvert.back())) {
  186. outvert.pop_back();
  187. --newcount;
  188. }
  189. if(newcount > 2) {
  190. result.vertcnt.push_back(newcount);
  191. }
  192. else while(newcount-->0) {
  193. result.verts.pop_back();
  194. }
  195. }
  196. IFCImporter::LogDebug("generating CSG geometry by plane clipping (IfcBooleanClippingResult)");
  197. }
  198. // ------------------------------------------------------------------------------------------------
  199. // Check if e0-e1 intersects a sub-segment of the given boundary line.
  200. // note: this functions works on 3D vectors, but performs its intersection checks solely in xy.
  201. // New version takes the supposed inside/outside state as a parameter and treats corner cases as if
  202. // the line stays on that side. This should make corner cases more stable.
  203. // Two million assumptions! Boundary should have all z at 0.0, will be treated as closed, should not have
  204. // segments with length <1e-6, self-intersecting might break the corner case handling... just don't go there, ok?
  205. bool IntersectsBoundaryProfile(const IfcVector3& e0, const IfcVector3& e1, const std::vector<IfcVector3>& boundary,
  206. const bool isStartAssumedInside, std::vector<std::pair<size_t, IfcVector3> >& intersect_results,
  207. const bool halfOpen = false)
  208. {
  209. ai_assert(intersect_results.empty());
  210. // determine winding order - necessary to detect segments going "inwards" or "outwards" from a point directly on the border
  211. // positive sum of angles means clockwise order when looking down the -Z axis
  212. IfcFloat windingOrder = 0.0;
  213. for( size_t i = 0, bcount = boundary.size(); i < bcount; ++i ) {
  214. IfcVector3 b01 = boundary[(i + 1) % bcount] - boundary[i];
  215. IfcVector3 b12 = boundary[(i + 2) % bcount] - boundary[(i + 1) % bcount];
  216. IfcVector3 b1_side = IfcVector3(b01.y, -b01.x, 0.0); // rotated 90° clockwise in Z plane
  217. // Warning: rough estimate only. A concave poly with lots of small segments each featuring a small counter rotation
  218. // could fool the accumulation. Correct implementation would be sum( acos( b01 * b2) * sign( b12 * b1_side))
  219. windingOrder += (b1_side.x*b12.x + b1_side.y*b12.y);
  220. }
  221. windingOrder = windingOrder > 0.0 ? 1.0 : -1.0;
  222. const IfcVector3 e = e1 - e0;
  223. for( size_t i = 0, bcount = boundary.size(); i < bcount; ++i ) {
  224. // boundary segment i: b0-b1
  225. const IfcVector3& b0 = boundary[i];
  226. const IfcVector3& b1 = boundary[(i + 1) % bcount];
  227. IfcVector3 b = b1 - b0;
  228. IfcFloat b_sqlen_inv = 1.0 / b.SquareLength();
  229. // segment-segment intersection
  230. // solve b0 + b*s = e0 + e*t for (s,t)
  231. const IfcFloat det = (-b.x * e.y + e.x * b.y);
  232. if( std::abs(det) < 1e-6 ) {
  233. // no solutions (parallel lines)
  234. continue;
  235. }
  236. const IfcFloat x = b0.x - e0.x;
  237. const IfcFloat y = b0.y - e0.y;
  238. const IfcFloat s = (x*e.y - e.x*y) / det; // scale along boundary edge
  239. const IfcFloat t = (x*b.y - b.x*y) / det; // scale along given segment
  240. const IfcVector3 p = e0 + e*t;
  241. #ifdef ASSIMP_BUILD_DEBUG
  242. const IfcVector3 check = b0 + b*s - p;
  243. ai_assert((IfcVector2(check.x, check.y)).SquareLength() < 1e-5);
  244. #endif
  245. // also calculate the distance of e0 and e1 to the segment. We need to detect the "starts directly on segment"
  246. // and "ends directly at segment" cases
  247. bool startsAtSegment, endsAtSegment;
  248. {
  249. // calculate closest point to each end on the segment, clamp that point to the segment's length, then check
  250. // distance to that point. This approach is like testing if e0 is inside a capped cylinder.
  251. IfcFloat et0 = (b.x*(e0.x - b0.x) + b.y*(e0.y - b0.y)) * b_sqlen_inv;
  252. IfcVector3 closestPosToE0OnBoundary = b0 + std::max(IfcFloat(0.0), std::min(IfcFloat(1.0), et0)) * b;
  253. startsAtSegment = (closestPosToE0OnBoundary - IfcVector3(e0.x, e0.y, 0.0)).SquareLength() < 1e-12;
  254. IfcFloat et1 = (b.x*(e1.x - b0.x) + b.y*(e1.y - b0.y)) * b_sqlen_inv;
  255. IfcVector3 closestPosToE1OnBoundary = b0 + std::max(IfcFloat(0.0), std::min(IfcFloat(1.0), et1)) * b;
  256. endsAtSegment = (closestPosToE1OnBoundary - IfcVector3(e1.x, e1.y, 0.0)).SquareLength() < 1e-12;
  257. }
  258. // Line segment ends at boundary -> ignore any hit, it will be handled by possibly following segments
  259. if( endsAtSegment && !halfOpen )
  260. continue;
  261. // Line segment starts at boundary -> generate a hit only if following that line would change the INSIDE/OUTSIDE
  262. // state. This should catch the case where a connected set of segments has a point directly on the boundary,
  263. // one segment not hitting it because it ends there and the next segment not hitting it because it starts there
  264. // Should NOT generate a hit if the segment only touches the boundary but turns around and stays inside.
  265. if( startsAtSegment )
  266. {
  267. IfcVector3 inside_dir = IfcVector3(b.y, -b.x, 0.0) * windingOrder;
  268. bool isGoingInside = (inside_dir * e) > 0.0;
  269. if( isGoingInside == isStartAssumedInside )
  270. continue;
  271. // only insert the point into the list if it is sufficiently far away from the previous intersection point.
  272. // This way, we avoid duplicate detection if the intersection is directly on the vertex between two segments.
  273. if( !intersect_results.empty() && intersect_results.back().first == i - 1 )
  274. {
  275. const IfcVector3 diff = intersect_results.back().second - e0;
  276. if( IfcVector2(diff.x, diff.y).SquareLength() < 1e-10 )
  277. continue;
  278. }
  279. intersect_results.push_back(std::make_pair(i, e0));
  280. continue;
  281. }
  282. // for a valid intersection, s and t should be in range [0,1]. Including a bit of epsilon on s, potential double
  283. // hits on two consecutive boundary segments are filtered
  284. if( s >= -1e-6 * b_sqlen_inv && s <= 1.0 + 1e-6*b_sqlen_inv && t >= 0.0 && (t <= 1.0 || halfOpen) )
  285. {
  286. // only insert the point into the list if it is sufficiently far away from the previous intersection point.
  287. // This way, we avoid duplicate detection if the intersection is directly on the vertex between two segments.
  288. if( !intersect_results.empty() && intersect_results.back().first == i - 1 )
  289. {
  290. const IfcVector3 diff = intersect_results.back().second - p;
  291. if( IfcVector2(diff.x, diff.y).SquareLength() < 1e-10 )
  292. continue;
  293. }
  294. intersect_results.push_back(std::make_pair(i, p));
  295. }
  296. }
  297. return !intersect_results.empty();
  298. }
  299. // ------------------------------------------------------------------------------------------------
  300. // note: this functions works on 3D vectors, but performs its intersection checks solely in xy.
  301. bool PointInPoly(const IfcVector3& p, const std::vector<IfcVector3>& boundary)
  302. {
  303. // even-odd algorithm: take a random vector that extends from p to infinite
  304. // and counts how many times it intersects edges of the boundary.
  305. // because checking for segment intersections is prone to numeric inaccuracies
  306. // or double detections (i.e. when hitting multiple adjacent segments at their
  307. // shared vertices) we do it thrice with different rays and vote on it.
  308. // the even-odd algorithm doesn't work for points which lie directly on
  309. // the border of the polygon. If any of our attempts produces this result,
  310. // we return false immediately.
  311. std::vector<std::pair<size_t, IfcVector3> > intersected_boundary;
  312. size_t votes = 0;
  313. IntersectsBoundaryProfile(p, p + IfcVector3(1.0, 0, 0), boundary, true, intersected_boundary, true);
  314. votes += intersected_boundary.size() % 2;
  315. intersected_boundary.clear();
  316. IntersectsBoundaryProfile(p, p + IfcVector3(0, 1.0, 0), boundary, true, intersected_boundary, true);
  317. votes += intersected_boundary.size() % 2;
  318. intersected_boundary.clear();
  319. IntersectsBoundaryProfile(p, p + IfcVector3(0.6, -0.6, 0.0), boundary, true, intersected_boundary, true);
  320. votes += intersected_boundary.size() % 2;
  321. // ai_assert(votes == 3 || votes == 0);
  322. return votes > 1;
  323. }
  324. // ------------------------------------------------------------------------------------------------
  325. void ProcessPolygonalBoundedBooleanHalfSpaceDifference(const IfcPolygonalBoundedHalfSpace* hs, TempMesh& result,
  326. const TempMesh& first_operand,
  327. ConversionData& conv)
  328. {
  329. ai_assert(hs != NULL);
  330. const IfcPlane* const plane = hs->BaseSurface->ToPtr<IfcPlane>();
  331. if(!plane) {
  332. IFCImporter::LogError("expected IfcPlane as base surface for the IfcHalfSpaceSolid");
  333. return;
  334. }
  335. // extract plane base position vector and normal vector
  336. IfcVector3 p,n(0.f,0.f,1.f);
  337. if (plane->Position->Axis) {
  338. ConvertDirection(n,plane->Position->Axis.Get());
  339. }
  340. ConvertCartesianPoint(p,plane->Position->Location);
  341. if(!IsTrue(hs->AgreementFlag)) {
  342. n *= -1.f;
  343. }
  344. n.Normalize();
  345. // obtain the polygonal bounding volume
  346. std::shared_ptr<TempMesh> profile = std::shared_ptr<TempMesh>(new TempMesh());
  347. if(!ProcessCurve(hs->PolygonalBoundary, *profile.get(), conv)) {
  348. IFCImporter::LogError("expected valid polyline for boundary of boolean halfspace");
  349. return;
  350. }
  351. // determine winding order by calculating the normal.
  352. IfcVector3 profileNormal = TempMesh::ComputePolygonNormal(profile->verts.data(), profile->verts.size());
  353. IfcMatrix4 proj_inv;
  354. ConvertAxisPlacement(proj_inv,hs->Position);
  355. // and map everything into a plane coordinate space so all intersection
  356. // tests can be done in 2D space.
  357. IfcMatrix4 proj = proj_inv;
  358. proj.Inverse();
  359. // clip the current contents of `meshout` against the plane we obtained from the second operand
  360. const std::vector<IfcVector3>& in = first_operand.verts;
  361. std::vector<IfcVector3>& outvert = result.verts;
  362. std::vector<unsigned int>& outvertcnt = result.vertcnt;
  363. outvert.reserve(in.size());
  364. outvertcnt.reserve(first_operand.vertcnt.size());
  365. unsigned int vidx = 0;
  366. std::vector<unsigned int>::const_iterator begin = first_operand.vertcnt.begin();
  367. std::vector<unsigned int>::const_iterator end = first_operand.vertcnt.end();
  368. std::vector<unsigned int>::const_iterator iit;
  369. for( iit = begin; iit != end; vidx += *iit++ )
  370. {
  371. // Our new approach: we cut the poly along the plane, then we intersect the part on the black side of the plane
  372. // against the bounding polygon. All the white parts, and the black part outside the boundary polygon, are kept.
  373. std::vector<IfcVector3> whiteside, blackside;
  374. {
  375. const IfcVector3* srcVertices = &in[vidx];
  376. const size_t srcVtxCount = *iit;
  377. if( srcVtxCount == 0 )
  378. continue;
  379. IfcVector3 polyNormal = TempMesh::ComputePolygonNormal(srcVertices, srcVtxCount, true);
  380. // if the poly is parallel to the plane, put it completely on the black or white side
  381. if( std::abs(polyNormal * n) > 0.9999 )
  382. {
  383. bool isOnWhiteSide = (srcVertices[0] - p) * n > -1e-6;
  384. std::vector<IfcVector3>& targetSide = isOnWhiteSide ? whiteside : blackside;
  385. targetSide.insert(targetSide.end(), srcVertices, srcVertices + srcVtxCount);
  386. }
  387. else
  388. {
  389. // otherwise start building one polygon for each side. Whenever the current line segment intersects the plane
  390. // we put a point there as an end of the current segment. Then we switch to the other side, put a point there, too,
  391. // as a beginning of the current segment, and simply continue accumulating vertices.
  392. bool isCurrentlyOnWhiteSide = ((srcVertices[0]) - p) * n > -1e-6;
  393. for( size_t a = 0; a < srcVtxCount; ++a )
  394. {
  395. IfcVector3 e0 = srcVertices[a];
  396. IfcVector3 e1 = srcVertices[(a + 1) % srcVtxCount];
  397. IfcVector3 ei;
  398. // put starting point to the current mesh
  399. std::vector<IfcVector3>& trgt = isCurrentlyOnWhiteSide ? whiteside : blackside;
  400. trgt.push_back(srcVertices[a]);
  401. // if there's an intersection, put an end vertex there, switch to the other side's mesh,
  402. // and add a starting vertex there, too
  403. bool isPlaneHit = IntersectSegmentPlane(p, n, e0, e1, isCurrentlyOnWhiteSide, ei);
  404. if( isPlaneHit )
  405. {
  406. if( trgt.empty() || (trgt.back() - ei).SquareLength() > 1e-12 )
  407. trgt.push_back(ei);
  408. isCurrentlyOnWhiteSide = !isCurrentlyOnWhiteSide;
  409. std::vector<IfcVector3>& newtrgt = isCurrentlyOnWhiteSide ? whiteside : blackside;
  410. newtrgt.push_back(ei);
  411. }
  412. }
  413. }
  414. }
  415. // the part on the white side can be written into the target mesh right away
  416. WritePolygon(whiteside, result);
  417. // The black part is the piece we need to get rid of, but only the part of it within the boundary polygon.
  418. // So we now need to construct all the polygons that result from BlackSidePoly minus BoundaryPoly.
  419. FilterPolygon(blackside);
  420. // Complicated, II. We run along the polygon. a) When we're inside the boundary, we run on until we hit an
  421. // intersection, which means we're leaving it. We then start a new out poly there. b) When we're outside the
  422. // boundary, we start collecting vertices until we hit an intersection, then we run along the boundary until we hit
  423. // an intersection, then we switch back to the poly and run on on this one again, and so on until we got a closed
  424. // loop. Then we continue with the path we left to catch potential additional polys on the other side of the
  425. // boundary as described in a)
  426. if( !blackside.empty() )
  427. {
  428. // poly edge index, intersection point, edge index in boundary poly
  429. std::vector<std::tuple<size_t, IfcVector3, size_t> > intersections;
  430. bool startedInside = PointInPoly(proj * blackside.front(), profile->verts);
  431. bool isCurrentlyInside = startedInside;
  432. std::vector<std::pair<size_t, IfcVector3> > intersected_boundary;
  433. for( size_t a = 0; a < blackside.size(); ++a )
  434. {
  435. const IfcVector3 e0 = proj * blackside[a];
  436. const IfcVector3 e1 = proj * blackside[(a + 1) % blackside.size()];
  437. intersected_boundary.clear();
  438. IntersectsBoundaryProfile(e0, e1, profile->verts, isCurrentlyInside, intersected_boundary);
  439. // sort the hits by distance from e0 to get the correct in/out/in sequence. Manually :-( I miss you, C++11.
  440. if( intersected_boundary.size() > 1 )
  441. {
  442. bool keepSorting = true;
  443. while( keepSorting )
  444. {
  445. keepSorting = false;
  446. for( size_t b = 0; b < intersected_boundary.size() - 1; ++b )
  447. {
  448. if( (intersected_boundary[b + 1].second - e0).SquareLength() < (intersected_boundary[b].second - e0).SquareLength() )
  449. {
  450. keepSorting = true;
  451. std::swap(intersected_boundary[b + 1], intersected_boundary[b]);
  452. }
  453. }
  454. }
  455. }
  456. // now add them to the list of intersections
  457. for( size_t b = 0; b < intersected_boundary.size(); ++b )
  458. intersections.push_back(std::make_tuple(a, proj_inv * intersected_boundary[b].second, intersected_boundary[b].first));
  459. // and calculate our new inside/outside state
  460. if( intersected_boundary.size() & 1 )
  461. isCurrentlyInside = !isCurrentlyInside;
  462. }
  463. // we got a list of in-out-combinations of intersections. That should be an even number of intersections, or
  464. // we're fucked.
  465. if( (intersections.size() & 1) != 0 )
  466. {
  467. IFCImporter::LogWarn("Odd number of intersections, can't work with that. Omitting half space boundary check.");
  468. continue;
  469. }
  470. if( intersections.size() > 1 )
  471. {
  472. // If we started outside, the first intersection is a out->in intersection. Cycle them so that it
  473. // starts with an intersection leaving the boundary
  474. if( !startedInside )
  475. for( size_t b = 0; b < intersections.size() - 1; ++b )
  476. std::swap(intersections[b], intersections[(b + intersections.size() - 1) % intersections.size()]);
  477. // Filter pairs of out->in->out that lie too close to each other.
  478. for( size_t a = 0; intersections.size() > 0 && a < intersections.size() - 1; /**/ )
  479. {
  480. if( (std::get<1>(intersections[a]) - std::get<1>(intersections[(a + 1) % intersections.size()])).SquareLength() < 1e-10 )
  481. intersections.erase(intersections.begin() + a, intersections.begin() + a + 2);
  482. else
  483. a++;
  484. }
  485. if( intersections.size() > 1 && (std::get<1>(intersections.back()) - std::get<1>(intersections.front())).SquareLength() < 1e-10 )
  486. {
  487. intersections.pop_back(); intersections.erase(intersections.begin());
  488. }
  489. }
  490. // no intersections at all: either completely inside the boundary, so everything gets discarded, or completely outside.
  491. // in the latter case we're implementional lost. I'm simply going to ignore this, so a large poly will not get any
  492. // holes if the boundary is smaller and does not touch it anywhere.
  493. if( intersections.empty() )
  494. {
  495. // starting point was outside -> everything is outside the boundary -> nothing is clipped -> add black side
  496. // to result mesh unchanged
  497. if( !startedInside )
  498. {
  499. outvertcnt.push_back(static_cast<unsigned int>(blackside.size()));
  500. outvert.insert(outvert.end(), blackside.begin(), blackside.end());
  501. continue;
  502. }
  503. else
  504. {
  505. // starting point was inside the boundary -> everything is inside the boundary -> nothing is spared from the
  506. // clipping -> nothing left to add to the result mesh
  507. continue;
  508. }
  509. }
  510. // determine the direction in which we're marching along the boundary polygon. If the src poly is faced upwards
  511. // and the boundary is also winded this way, we need to march *backwards* on the boundary.
  512. const IfcVector3 polyNormal = IfcMatrix3(proj) * TempMesh::ComputePolygonNormal(blackside.data(), blackside.size());
  513. bool marchBackwardsOnBoundary = (profileNormal * polyNormal) >= 0.0;
  514. // Build closed loops from these intersections. Starting from an intersection leaving the boundary we
  515. // walk along the polygon to the next intersection (which should be an IS entering the boundary poly).
  516. // From there we walk along the boundary until we hit another intersection leaving the boundary,
  517. // walk along the poly to the next IS and so on until we're back at the starting point.
  518. // We remove every intersection we "used up", so any remaining intersection is the start of a new loop.
  519. while( !intersections.empty() )
  520. {
  521. std::vector<IfcVector3> resultpoly;
  522. size_t currentIntersecIdx = 0;
  523. while( true )
  524. {
  525. ai_assert(intersections.size() > currentIntersecIdx + 1);
  526. std::tuple<size_t, IfcVector3, size_t> currintsec = intersections[currentIntersecIdx + 0];
  527. std::tuple<size_t, IfcVector3, size_t> nextintsec = intersections[currentIntersecIdx + 1];
  528. intersections.erase(intersections.begin() + currentIntersecIdx, intersections.begin() + currentIntersecIdx + 2);
  529. // we start with an in->out intersection
  530. resultpoly.push_back(std::get<1>(currintsec));
  531. // climb along the polygon to the next intersection, which should be an out->in
  532. size_t numPolyPoints = (std::get<0>(currintsec) > std::get<0>(nextintsec) ? blackside.size() : 0)
  533. + std::get<0>(nextintsec) - std::get<0>(currintsec);
  534. for( size_t a = 1; a <= numPolyPoints; ++a )
  535. resultpoly.push_back(blackside[(std::get<0>(currintsec) + a) % blackside.size()]);
  536. // put the out->in intersection
  537. resultpoly.push_back(std::get<1>(nextintsec));
  538. // generate segments along the boundary polygon that lie in the poly's plane until we hit another intersection
  539. IfcVector3 startingPoint = proj * std::get<1>(nextintsec);
  540. size_t currentBoundaryEdgeIdx = (std::get<2>(nextintsec) + (marchBackwardsOnBoundary ? 1 : 0)) % profile->verts.size();
  541. size_t nextIntsecIdx = SIZE_MAX;
  542. while( nextIntsecIdx == SIZE_MAX )
  543. {
  544. IfcFloat t = 1e10;
  545. size_t nextBoundaryEdgeIdx = marchBackwardsOnBoundary ? (currentBoundaryEdgeIdx + profile->verts.size() - 1) : currentBoundaryEdgeIdx + 1;
  546. nextBoundaryEdgeIdx %= profile->verts.size();
  547. // vertices of the current boundary segments
  548. IfcVector3 currBoundaryPoint = profile->verts[currentBoundaryEdgeIdx];
  549. IfcVector3 nextBoundaryPoint = profile->verts[nextBoundaryEdgeIdx];
  550. // project the two onto the polygon
  551. if( std::abs(polyNormal.z) > 1e-5 )
  552. {
  553. currBoundaryPoint.z = startingPoint.z + (currBoundaryPoint.x - startingPoint.x) * polyNormal.x/polyNormal.z + (currBoundaryPoint.y - startingPoint.y) * polyNormal.y/polyNormal.z;
  554. nextBoundaryPoint.z = startingPoint.z + (nextBoundaryPoint.x - startingPoint.x) * polyNormal.x/polyNormal.z + (nextBoundaryPoint.y - startingPoint.y) * polyNormal.y/polyNormal.z;
  555. }
  556. // build a direction that goes along the boundary border but lies in the poly plane
  557. IfcVector3 boundaryPlaneNormal = ((nextBoundaryPoint - currBoundaryPoint) ^ profileNormal).Normalize();
  558. IfcVector3 dirAtPolyPlane = (boundaryPlaneNormal ^ polyNormal).Normalize() * (marchBackwardsOnBoundary ? -1.0 : 1.0);
  559. // if we can project the direction to the plane, we can calculate a maximum marching distance along that dir
  560. // until we finish that boundary segment and continue on the next
  561. if( std::abs(polyNormal.z) > 1e-5 )
  562. {
  563. t = std::min(t, (nextBoundaryPoint - startingPoint).Length());
  564. }
  565. // check if the direction hits the loop start - if yes, we got a poly to output
  566. IfcVector3 dirToThatPoint = proj * resultpoly.front() - startingPoint;
  567. IfcFloat tpt = dirToThatPoint * dirAtPolyPlane;
  568. if( tpt > -1e-6 && tpt <= t && (dirToThatPoint - tpt * dirAtPolyPlane).SquareLength() < 1e-10 )
  569. {
  570. nextIntsecIdx = intersections.size(); // dirty hack to end marching along the boundary and signal the end of the loop
  571. t = tpt;
  572. }
  573. // also check if the direction hits any in->out intersections earlier. If we hit one, we can switch back
  574. // to marching along the poly border from that intersection point
  575. for( size_t a = 0; a < intersections.size(); a += 2 )
  576. {
  577. dirToThatPoint = proj * std::get<1>(intersections[a]) - startingPoint;
  578. tpt = dirToThatPoint * dirAtPolyPlane;
  579. if( tpt > -1e-6 && tpt <= t && (dirToThatPoint - tpt * dirAtPolyPlane).SquareLength() < 1e-10 )
  580. {
  581. nextIntsecIdx = a; // switch back to poly and march on from this in->out intersection
  582. t = tpt;
  583. }
  584. }
  585. // if we keep marching on the boundary, put the segment end point to the result poly and well... keep marching
  586. if( nextIntsecIdx == SIZE_MAX )
  587. {
  588. resultpoly.push_back(proj_inv * nextBoundaryPoint);
  589. currentBoundaryEdgeIdx = nextBoundaryEdgeIdx;
  590. startingPoint = nextBoundaryPoint;
  591. }
  592. // quick endless loop check
  593. if( resultpoly.size() > blackside.size() + profile->verts.size() )
  594. {
  595. IFCImporter::LogError("Encountered endless loop while clipping polygon against poly-bounded half space.");
  596. break;
  597. }
  598. }
  599. // we're back on the poly - if this is the intersection we started from, we got a closed loop.
  600. if( nextIntsecIdx >= intersections.size() )
  601. {
  602. break;
  603. }
  604. // otherwise it's another intersection. Continue marching from there.
  605. currentIntersecIdx = nextIntsecIdx;
  606. }
  607. WritePolygon(resultpoly, result);
  608. }
  609. }
  610. }
  611. IFCImporter::LogDebug("generating CSG geometry by plane clipping with polygonal bounding (IfcBooleanClippingResult)");
  612. }
  613. // ------------------------------------------------------------------------------------------------
  614. void ProcessBooleanExtrudedAreaSolidDifference(const IfcExtrudedAreaSolid* as, TempMesh& result,
  615. const TempMesh& first_operand,
  616. ConversionData& conv)
  617. {
  618. ai_assert(as != NULL);
  619. // This case is handled by reduction to an instance of the quadrify() algorithm.
  620. // Obviously, this won't work for arbitrarily complex cases. In fact, the first
  621. // operand should be near-planar. Luckily, this is usually the case in Ifc
  622. // buildings.
  623. std::shared_ptr<TempMesh> meshtmp = std::shared_ptr<TempMesh>(new TempMesh());
  624. ProcessExtrudedAreaSolid(*as,*meshtmp,conv,false);
  625. std::vector<TempOpening> openings(1, TempOpening(as,IfcVector3(0,0,0),meshtmp,std::shared_ptr<TempMesh>()));
  626. result = first_operand;
  627. TempMesh temp;
  628. std::vector<IfcVector3>::const_iterator vit = first_operand.verts.begin();
  629. for(unsigned int pcount : first_operand.vertcnt) {
  630. temp.Clear();
  631. temp.verts.insert(temp.verts.end(), vit, vit + pcount);
  632. temp.vertcnt.push_back(pcount);
  633. // The algorithms used to generate mesh geometry sometimes
  634. // spit out lines or other degenerates which must be
  635. // filtered to avoid running into assertions later on.
  636. // ComputePolygonNormal returns the Newell normal, so the
  637. // length of the normal is the area of the polygon.
  638. const IfcVector3& normal = temp.ComputeLastPolygonNormal(false);
  639. if (normal.SquareLength() < static_cast<IfcFloat>(1e-5)) {
  640. IFCImporter::LogWarn("skipping degenerate polygon (ProcessBooleanExtrudedAreaSolidDifference)");
  641. continue;
  642. }
  643. GenerateOpenings(openings, std::vector<IfcVector3>(1,IfcVector3(1,0,0)), temp, false, true);
  644. result.Append(temp);
  645. vit += pcount;
  646. }
  647. IFCImporter::LogDebug("generating CSG geometry by geometric difference to a solid (IfcExtrudedAreaSolid)");
  648. }
  649. // ------------------------------------------------------------------------------------------------
  650. void ProcessBoolean(const IfcBooleanResult& boolean, TempMesh& result, ConversionData& conv)
  651. {
  652. // supported CSG operations:
  653. // DIFFERENCE
  654. if(const IfcBooleanResult* const clip = boolean.ToPtr<IfcBooleanResult>()) {
  655. if(clip->Operator != "DIFFERENCE") {
  656. IFCImporter::LogWarn("encountered unsupported boolean operator: " + (std::string)clip->Operator);
  657. return;
  658. }
  659. // supported cases (1st operand):
  660. // IfcBooleanResult -- call ProcessBoolean recursively
  661. // IfcSweptAreaSolid -- obtain polygonal geometry first
  662. // supported cases (2nd operand):
  663. // IfcHalfSpaceSolid -- easy, clip against plane
  664. // IfcExtrudedAreaSolid -- reduce to an instance of the quadrify() algorithm
  665. const IfcHalfSpaceSolid* const hs = clip->SecondOperand->ResolveSelectPtr<IfcHalfSpaceSolid>(conv.db);
  666. const IfcExtrudedAreaSolid* const as = clip->SecondOperand->ResolveSelectPtr<IfcExtrudedAreaSolid>(conv.db);
  667. if(!hs && !as) {
  668. IFCImporter::LogError("expected IfcHalfSpaceSolid or IfcExtrudedAreaSolid as second clipping operand");
  669. return;
  670. }
  671. TempMesh first_operand;
  672. if(const IfcBooleanResult* const op0 = clip->FirstOperand->ResolveSelectPtr<IfcBooleanResult>(conv.db)) {
  673. ProcessBoolean(*op0,first_operand,conv);
  674. }
  675. else if (const IfcSweptAreaSolid* const swept = clip->FirstOperand->ResolveSelectPtr<IfcSweptAreaSolid>(conv.db)) {
  676. ProcessSweptAreaSolid(*swept,first_operand,conv);
  677. }
  678. else {
  679. IFCImporter::LogError("expected IfcSweptAreaSolid or IfcBooleanResult as first clipping operand");
  680. return;
  681. }
  682. if(hs) {
  683. const IfcPolygonalBoundedHalfSpace* const hs_bounded = clip->SecondOperand->ResolveSelectPtr<IfcPolygonalBoundedHalfSpace>(conv.db);
  684. if (hs_bounded) {
  685. ProcessPolygonalBoundedBooleanHalfSpaceDifference(hs_bounded, result, first_operand, conv);
  686. }
  687. else {
  688. ProcessBooleanHalfSpaceDifference(hs, result, first_operand, conv);
  689. }
  690. }
  691. else {
  692. ProcessBooleanExtrudedAreaSolidDifference(as, result, first_operand, conv);
  693. }
  694. }
  695. else {
  696. IFCImporter::LogWarn("skipping unknown IfcBooleanResult entity, type is " + boolean.GetClassName());
  697. }
  698. }
  699. } // ! IFC
  700. } // ! Assimp
  701. #endif