2
0

IFCBoolean.cpp 39 KB

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