2
0

IFCGeometry.cpp 32 KB

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