IFCGeometry.cpp 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369
  1. /*
  2. Open Asset Import Library (ASSIMP)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2010, ASSIMP Development Team
  5. All rights reserved.
  6. Redistribution and use of this software in source and binary forms,
  7. with or without modification, are permitted provided that the
  8. following conditions are met:
  9. * Redistributions of source code must retain the above
  10. copyright notice, this list of conditions and the
  11. following disclaimer.
  12. * Redistributions in binary form must reproduce the above
  13. copyright notice, this list of conditions and the
  14. following disclaimer in the documentation and/or other
  15. materials provided with the distribution.
  16. * Neither the name of the ASSIMP team, nor the names of its
  17. contributors may be used to endorse or promote products
  18. derived from this software without specific prior
  19. written permission of the ASSIMP Development Team.
  20. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. ----------------------------------------------------------------------
  32. */
  33. /** @file IFCGeometry.cpp
  34. * @brief Geometry conversion and synthesis for IFC
  35. */
  36. #include "AssimpPCH.h"
  37. #ifndef ASSIMP_BUILD_NO_IFC_IMPORTER
  38. #include "IFCUtil.h"
  39. #include "PolyTools.h"
  40. #include "ProcessHelper.h"
  41. namespace Assimp {
  42. namespace IFC {
  43. // ------------------------------------------------------------------------------------------------
  44. bool ProcessPolyloop(const IfcPolyLoop& loop, TempMesh& meshout, ConversionData& /*conv*/)
  45. {
  46. size_t cnt = 0;
  47. BOOST_FOREACH(const IfcCartesianPoint& c, loop.Polygon) {
  48. aiVector3D tmp;
  49. ConvertCartesianPoint(tmp,c);
  50. meshout.verts.push_back(tmp);
  51. ++cnt;
  52. }
  53. meshout.vertcnt.push_back(cnt);
  54. // zero- or one- vertex polyloops simply ignored
  55. if (meshout.vertcnt.back() > 1) {
  56. return true;
  57. }
  58. if (meshout.vertcnt.back()==1) {
  59. meshout.vertcnt.pop_back();
  60. meshout.verts.pop_back();
  61. }
  62. return false;
  63. }
  64. // ------------------------------------------------------------------------------------------------
  65. void ComputePolygonNormals(const TempMesh& meshout, std::vector<aiVector3D>& normals, bool normalize = true, size_t ofs = 0)
  66. {
  67. size_t max_vcount = 0;
  68. std::vector<unsigned int>::const_iterator begin=meshout.vertcnt.begin()+ofs, end=meshout.vertcnt.end(), iit;
  69. for(iit = begin; iit != end; ++iit) {
  70. max_vcount = std::max(max_vcount,static_cast<size_t>(*iit));
  71. }
  72. std::vector<float> temp((max_vcount+2)*4);
  73. normals.reserve( normals.size() + meshout.vertcnt.size()-ofs );
  74. // `NewellNormal()` currently has a relatively strange interface and need to
  75. // re-structure things a bit to meet them.
  76. size_t vidx = std::accumulate(meshout.vertcnt.begin(),begin,0);
  77. for(iit = begin; iit != end; vidx += *iit++) {
  78. if (!*iit) {
  79. normals.push_back(aiVector3D());
  80. continue;
  81. }
  82. for(size_t vofs = 0, cnt = 0; vofs < *iit; ++vofs) {
  83. const aiVector3D& v = meshout.verts[vidx+vofs];
  84. temp[cnt++] = v.x;
  85. temp[cnt++] = v.y;
  86. temp[cnt++] = v.z;
  87. #ifdef _DEBUG
  88. temp[cnt] = std::numeric_limits<float>::quiet_NaN();
  89. #endif
  90. ++cnt;
  91. }
  92. normals.push_back(aiVector3D());
  93. NewellNormal<4,4,4>(normals.back(),*iit,&temp[0],&temp[1],&temp[2]);
  94. }
  95. if(normalize) {
  96. BOOST_FOREACH(aiVector3D& n, normals) {
  97. n.Normalize();
  98. }
  99. }
  100. }
  101. // ------------------------------------------------------------------------------------------------
  102. // Compute the normal of the last polygon in the given mesh
  103. aiVector3D ComputePolygonNormal(const TempMesh& inmesh, bool normalize = true)
  104. {
  105. size_t total = inmesh.vertcnt.back(), vidx = inmesh.verts.size() - total;
  106. std::vector<float> temp((total+2)*3);
  107. for(size_t vofs = 0, cnt = 0; vofs < total; ++vofs) {
  108. const aiVector3D& v = inmesh.verts[vidx+vofs];
  109. temp[cnt++] = v.x;
  110. temp[cnt++] = v.y;
  111. temp[cnt++] = v.z;
  112. }
  113. aiVector3D nor;
  114. NewellNormal<3,3,3>(nor,total,&temp[0],&temp[1],&temp[2]);
  115. return normalize ? nor.Normalize() : nor;
  116. }
  117. // ------------------------------------------------------------------------------------------------
  118. void FixupFaceOrientation(TempMesh& result)
  119. {
  120. const aiVector3D vavg = result.Center();
  121. std::vector<aiVector3D> normals;
  122. ComputePolygonNormals(result,normals);
  123. size_t c = 0, ofs = 0;
  124. BOOST_FOREACH(unsigned int cnt, result.vertcnt) {
  125. if (cnt>2){
  126. const aiVector3D& thisvert = result.verts[c];
  127. if (normals[ofs]*(thisvert-vavg) < 0) {
  128. std::reverse(result.verts.begin()+c,result.verts.begin()+cnt+c);
  129. }
  130. }
  131. c += cnt;
  132. ++ofs;
  133. }
  134. }
  135. // ------------------------------------------------------------------------------------------------
  136. void RecursiveMergeBoundaries(TempMesh& final_result, const TempMesh& in, const TempMesh& boundary, std::vector<aiVector3D>& normals, const aiVector3D& nor_boundary)
  137. {
  138. ai_assert(in.vertcnt.size() >= 1);
  139. ai_assert(boundary.vertcnt.size() == 1);
  140. std::vector<unsigned int>::const_iterator end = in.vertcnt.end(), begin=in.vertcnt.begin(), iit, best_iit;
  141. TempMesh out;
  142. // iterate through all other bounds and find the one for which the shortest connection
  143. // to the outer boundary is actually the shortest possible.
  144. size_t vidx = 0, best_vidx_start = 0;
  145. size_t best_ofs, best_outer = boundary.verts.size();
  146. float best_dist = 1e10;
  147. for(std::vector<unsigned int>::const_iterator iit = begin; iit != end; vidx += *iit++) {
  148. for(size_t vofs = 0; vofs < *iit; ++vofs) {
  149. const aiVector3D& v = in.verts[vidx+vofs];
  150. for(size_t outer = 0; outer < boundary.verts.size(); ++outer) {
  151. const aiVector3D& o = boundary.verts[outer];
  152. const float d = (o-v).SquareLength();
  153. if (d < best_dist) {
  154. best_dist = d;
  155. best_ofs = vofs;
  156. best_outer = outer;
  157. best_iit = iit;
  158. best_vidx_start = vidx;
  159. }
  160. }
  161. }
  162. }
  163. ai_assert(best_outer != boundary.verts.size());
  164. // now that we collected all vertex connections to be added, build the output polygon
  165. const size_t cnt = boundary.verts.size() + *best_iit+2;
  166. out.verts.reserve(cnt);
  167. for(size_t outer = 0; outer < boundary.verts.size(); ++outer) {
  168. const aiVector3D& o = boundary.verts[outer];
  169. out.verts.push_back(o);
  170. if (outer == best_outer) {
  171. for(size_t i = best_ofs; i < *best_iit; ++i) {
  172. out.verts.push_back(in.verts[best_vidx_start + i]);
  173. }
  174. // we need the first vertex of the inner polygon twice as we return to the
  175. // outer loop through the very same connection through which we got there.
  176. for(size_t i = 0; i <= best_ofs; ++i) {
  177. out.verts.push_back(in.verts[best_vidx_start + i]);
  178. }
  179. // reverse face winding if the normal of the sub-polygon points in the
  180. // same direction as the normal of the outer polygonal boundary
  181. if (normals[std::distance(begin,best_iit)] * nor_boundary > 0) {
  182. std::reverse(out.verts.rbegin(),out.verts.rbegin()+*best_iit+1);
  183. }
  184. // also append a copy of the initial insertion point to be able to continue the outer polygon
  185. out.verts.push_back(o);
  186. }
  187. }
  188. out.vertcnt.push_back(cnt);
  189. ai_assert(out.verts.size() == cnt);
  190. if (in.vertcnt.size()-std::count(begin,end,0) > 1) {
  191. // Recursively apply the same algorithm if there are more boundaries to merge. The
  192. // current implementation is relatively inefficient, though.
  193. TempMesh temp;
  194. // drop the boundary that we just processed
  195. const size_t dist = std::distance(begin, best_iit);
  196. TempMesh remaining = in;
  197. remaining.vertcnt.erase(remaining.vertcnt.begin() + dist);
  198. remaining.verts.erase(remaining.verts.begin()+best_vidx_start,remaining.verts.begin()+best_vidx_start+*best_iit);
  199. normals.erase(normals.begin() + dist);
  200. RecursiveMergeBoundaries(temp,remaining,out,normals,nor_boundary);
  201. final_result.Append(temp);
  202. }
  203. else final_result.Append(out);
  204. }
  205. // ------------------------------------------------------------------------------------------------
  206. void MergePolygonBoundaries(TempMesh& result, const TempMesh& inmesh, size_t master_bounds = -1)
  207. {
  208. // standard case - only one boundary, just copy it to the result vector
  209. if (inmesh.vertcnt.size() <= 1) {
  210. result.Append(inmesh);
  211. return;
  212. }
  213. result.vertcnt.reserve(inmesh.vertcnt.size()+result.vertcnt.size());
  214. // XXX get rid of the extra copy if possible
  215. TempMesh meshout = inmesh;
  216. // handle polygons with holes. Our built in triangulation won't handle them as is, but
  217. // the ear cutting algorithm is solid enough to deal with them if we join the inner
  218. // holes with the outer boundaries by dummy connections.
  219. IFCImporter::LogDebug("fixing polygon with holes for triangulation via ear-cutting");
  220. std::vector<unsigned int>::iterator outer_polygon = meshout.vertcnt.end(), begin=meshout.vertcnt.begin(), end=outer_polygon, iit;
  221. // each hole results in two extra vertices
  222. result.verts.reserve(meshout.verts.size()+meshout.vertcnt.size()*2+result.verts.size());
  223. size_t outer_polygon_start = 0;
  224. // do not normalize 'normals', we need the original length for computing the polygon area
  225. std::vector<aiVector3D> normals;
  226. ComputePolygonNormals(meshout,normals,false);
  227. // see if one of the polygons is a IfcFaceOuterBound (in which case `master_bounds` is its index).
  228. // sadly we can't rely on it, the docs say 'At most one of the bounds shall be of the type IfcFaceOuterBound'
  229. float area_outer_polygon = 1e-10f;
  230. if (master_bounds != (size_t)-1) {
  231. outer_polygon = begin + master_bounds;
  232. outer_polygon_start = std::accumulate(begin,outer_polygon,0);
  233. area_outer_polygon = normals[master_bounds].SquareLength();
  234. }
  235. else {
  236. size_t vidx = 0;
  237. for(iit = begin; iit != meshout.vertcnt.end(); vidx += *iit++) {
  238. // find the polygon with the largest area, it must be the outer bound.
  239. aiVector3D& n = normals[std::distance(begin,iit)];
  240. const float area = n.SquareLength();
  241. if (area > area_outer_polygon) {
  242. area_outer_polygon = area;
  243. outer_polygon = iit;
  244. outer_polygon_start = vidx;
  245. }
  246. }
  247. }
  248. ai_assert(outer_polygon != meshout.vertcnt.end());
  249. std::vector<aiVector3D>& in = meshout.verts;
  250. // skip over extremely small boundaries - this is a workaround to fix cases
  251. // in which the number of holes is so extremely large that the
  252. // triangulation code fails.
  253. #define IFC_VERTICAL_HOLE_SIZE_TRESHOLD 0.000001f
  254. size_t vidx = 0, removed = 0, index = 0;
  255. const float treshold = area_outer_polygon * IFC_VERTICAL_HOLE_SIZE_TRESHOLD;
  256. for(iit = begin; iit != end ;++index) {
  257. const float sqlen = normals[index].SquareLength();
  258. if (sqlen < treshold) {
  259. std::vector<aiVector3D>::iterator inbase = in.begin()+vidx;
  260. in.erase(inbase,inbase+*iit);
  261. outer_polygon_start -= outer_polygon_start>vidx ? *iit : 0;
  262. *iit++ = 0;
  263. ++removed;
  264. IFCImporter::LogDebug("skip small hole below treshold");
  265. }
  266. else {
  267. normals[index] /= sqrt(sqlen);
  268. vidx += *iit++;
  269. }
  270. }
  271. // see if one or more of the hole has a face that lies directly on an outer bound.
  272. // this happens for doors, for example.
  273. vidx = 0;
  274. for(iit = begin; ; vidx += *iit++) {
  275. next_loop:
  276. if (iit == end) {
  277. break;
  278. }
  279. if (iit == outer_polygon) {
  280. continue;
  281. }
  282. for(size_t vofs = 0; vofs < *iit; ++vofs) {
  283. if (!*iit) {
  284. continue;
  285. }
  286. const size_t next = (vofs+1)%*iit;
  287. const aiVector3D& v = in[vidx+vofs], &vnext = in[vidx+next],&vd = (vnext-v).Normalize();
  288. for(size_t outer = 0; outer < *outer_polygon; ++outer) {
  289. const aiVector3D& o = in[outer_polygon_start+outer], &onext = in[outer_polygon_start+(outer+1)%*outer_polygon], &od = (onext-o).Normalize();
  290. if (fabs(vd * od) > 1.f-1e-6f && (onext-v).Normalize() * vd > 1.f-1e-6f && (onext-v)*(o-v) < 0) {
  291. IFCImporter::LogDebug("got an inner hole that lies partly on the outer polygonal boundary, merging them to a single contour");
  292. // in between outer and outer+1 insert all vertices of this loop, then drop the original altogether.
  293. std::vector<aiVector3D> tmp(*iit);
  294. const size_t start = (v-o).SquareLength() > (vnext-o).SquareLength() ? vofs : next;
  295. std::vector<aiVector3D>::iterator inbase = in.begin()+vidx, it = std::copy(inbase+start, inbase+*iit,tmp.begin());
  296. std::copy(inbase, inbase+start,it);
  297. std::reverse(tmp.begin(),tmp.end());
  298. in.insert(in.begin()+outer_polygon_start+(outer+1)%*outer_polygon,tmp.begin(),tmp.end());
  299. vidx += outer_polygon_start<vidx ? *iit : 0;
  300. inbase = in.begin()+vidx;
  301. in.erase(inbase,inbase+*iit);
  302. outer_polygon_start -= outer_polygon_start>vidx ? *iit : 0;
  303. *outer_polygon += tmp.size();
  304. *iit++ = 0;
  305. ++removed;
  306. goto next_loop;
  307. }
  308. }
  309. }
  310. }
  311. if ( meshout.vertcnt.size() - removed <= 1) {
  312. result.Append(meshout);
  313. return;
  314. }
  315. // extract the outer boundary and move it to a separate mesh
  316. TempMesh boundary;
  317. boundary.vertcnt.resize(1,*outer_polygon);
  318. boundary.verts.resize(*outer_polygon);
  319. std::vector<aiVector3D>::iterator b = in.begin()+outer_polygon_start;
  320. std::copy(b,b+*outer_polygon,boundary.verts.begin());
  321. in.erase(b,b+*outer_polygon);
  322. std::vector<aiVector3D>::iterator norit = normals.begin()+std::distance(meshout.vertcnt.begin(),outer_polygon);
  323. const aiVector3D nor_boundary = *norit;
  324. normals.erase(norit);
  325. meshout.vertcnt.erase(outer_polygon);
  326. // keep merging the closest inner boundary with the outer boundary until no more boundaries are left
  327. RecursiveMergeBoundaries(result,meshout,boundary,normals,nor_boundary);
  328. }
  329. // ------------------------------------------------------------------------------------------------
  330. void ProcessConnectedFaceSet(const IfcConnectedFaceSet& fset, TempMesh& result, ConversionData& conv)
  331. {
  332. BOOST_FOREACH(const IfcFace& face, fset.CfsFaces) {
  333. // size_t ob = -1, cnt = 0;
  334. TempMesh meshout;
  335. BOOST_FOREACH(const IfcFaceBound& bound, face.Bounds) {
  336. // XXX implement proper merging for polygonal loops
  337. if(const IfcPolyLoop* const polyloop = bound.Bound->ToPtr<IfcPolyLoop>()) {
  338. if(ProcessPolyloop(*polyloop, meshout,conv)) {
  339. //if(bound.ToPtr<IfcFaceOuterBound>()) {
  340. // ob = cnt;
  341. //}
  342. //++cnt;
  343. }
  344. }
  345. else {
  346. IFCImporter::LogWarn("skipping unknown IfcFaceBound entity, type is " + bound.Bound->GetClassName());
  347. continue;
  348. }
  349. /*if(!IsTrue(bound.Orientation)) {
  350. size_t c = 0;
  351. BOOST_FOREACH(unsigned int& c, meshout.vertcnt) {
  352. std::reverse(result.verts.begin() + cnt,result.verts.begin() + cnt + c);
  353. cnt += c;
  354. }
  355. }*/
  356. }
  357. MergePolygonBoundaries(result,meshout);
  358. }
  359. }
  360. // ------------------------------------------------------------------------------------------------
  361. void ProcessRevolvedAreaSolid(const IfcRevolvedAreaSolid& solid, TempMesh& result, ConversionData& conv)
  362. {
  363. TempMesh meshout;
  364. // first read the profile description
  365. if(!ProcessProfile(*solid.SweptArea,meshout,conv) || meshout.verts.size()<=1) {
  366. return;
  367. }
  368. aiVector3D axis, pos;
  369. ConvertAxisPlacement(axis,pos,solid.Axis);
  370. aiMatrix4x4 tb0,tb1;
  371. aiMatrix4x4::Translation(pos,tb0);
  372. aiMatrix4x4::Translation(-pos,tb1);
  373. const std::vector<aiVector3D>& in = meshout.verts;
  374. const size_t size=in.size();
  375. bool has_area = solid.SweptArea->ProfileType == "AREA" && size>2;
  376. const float max_angle = solid.Angle*conv.angle_scale;
  377. if(fabs(max_angle) < 1e-3) {
  378. if(has_area) {
  379. result = meshout;
  380. }
  381. return;
  382. }
  383. const unsigned int cnt_segments = std::max(2u,static_cast<unsigned int>(16 * fabs(max_angle)/AI_MATH_HALF_PI_F));
  384. const float delta = max_angle/cnt_segments;
  385. has_area = has_area && fabs(max_angle) < AI_MATH_TWO_PI_F*0.99;
  386. result.verts.reserve(size*((cnt_segments+1)*4+(has_area?2:0)));
  387. result.vertcnt.reserve(size*cnt_segments+2);
  388. aiMatrix4x4 rot;
  389. rot = tb0 * aiMatrix4x4::Rotation(delta,axis,rot) * tb1;
  390. size_t base = 0;
  391. std::vector<aiVector3D>& out = result.verts;
  392. // dummy data to simplify later processing
  393. for(size_t i = 0; i < size; ++i) {
  394. out.insert(out.end(),4,in[i]);
  395. }
  396. for(unsigned int seg = 0; seg < cnt_segments; ++seg) {
  397. for(size_t i = 0; i < size; ++i) {
  398. const size_t next = (i+1)%size;
  399. result.vertcnt.push_back(4);
  400. const aiVector3D& base_0 = out[base+i*4+3],base_1 = out[base+next*4+3];
  401. out.push_back(base_0);
  402. out.push_back(base_1);
  403. out.push_back(rot*base_1);
  404. out.push_back(rot*base_0);
  405. }
  406. base += size*4;
  407. }
  408. out.erase(out.begin(),out.begin()+size*4);
  409. if(has_area) {
  410. // leave the triangulation of the profile area to the ear cutting
  411. // implementation in aiProcess_Triangulate - for now we just
  412. // feed in two huge polygons.
  413. base -= size*8;
  414. for(size_t i = size; i--; ) {
  415. out.push_back(out[base+i*4+3]);
  416. }
  417. for(size_t i = 0; i < size; ++i ) {
  418. out.push_back(out[i*4]);
  419. }
  420. result.vertcnt.push_back(size);
  421. result.vertcnt.push_back(size);
  422. }
  423. aiMatrix4x4 trafo;
  424. ConvertAxisPlacement(trafo, solid.Position);
  425. result.Transform(trafo);
  426. IFCImporter::LogDebug("generate mesh procedurally by radial extrusion (IfcRevolvedAreaSolid)");
  427. }
  428. // ------------------------------------------------------------------------------------------------
  429. bool TryAddOpenings(const std::vector<TempOpening>& openings,const std::vector<aiVector3D>& nors, TempMesh& curmesh)
  430. {
  431. std::vector<aiVector3D>& out = curmesh.verts;
  432. const size_t s = out.size();
  433. const aiVector3D any_point = out[s-1];
  434. const aiVector3D nor = ComputePolygonNormal(curmesh); ;
  435. bool got_openings = false;
  436. TempMesh res;
  437. size_t c = 0;
  438. BOOST_FOREACH(const TempOpening& t,openings) {
  439. const aiVector3D& outernor = nors[c++];
  440. const float dot = nor * outernor;
  441. if (fabs(dot)<1.f-1e-6f) {
  442. continue;
  443. }
  444. // const aiVector3D diff = t.extrusionDir;
  445. const std::vector<aiVector3D>& va = t.profileMesh->verts;
  446. if(va.size() <= 2) {
  447. continue;
  448. }
  449. // const float dd = t.extrusionDir*nor;
  450. IFCImporter::LogDebug("apply an IfcOpeningElement linked via IfcRelVoidsElement to this polygon");
  451. got_openings = true;
  452. // project va[i] onto the plane formed by the current polygon [given by (any_point,nor)]
  453. for(size_t i = 0; i < va.size(); ++i) {
  454. const aiVector3D& v = va[i];
  455. out.push_back(v-(nor*(v-any_point))*nor);
  456. }
  457. curmesh.vertcnt.push_back(va.size());
  458. res.Clear();
  459. MergePolygonBoundaries(res,curmesh,0);
  460. curmesh = res;
  461. }
  462. return got_openings;
  463. }
  464. // ------------------------------------------------------------------------------------------------
  465. struct DistanceSorter {
  466. DistanceSorter(const aiVector3D& base) : base(base) {}
  467. bool operator () (const TempOpening& a, const TempOpening& b) const {
  468. return (a.profileMesh->Center()-base).SquareLength() < (b.profileMesh->Center()-base).SquareLength();
  469. }
  470. aiVector3D base;
  471. };
  472. // ------------------------------------------------------------------------------------------------
  473. struct XYSorter {
  474. // sort first by X coordinates, then by Y coordinates
  475. bool operator () (const aiVector2D&a, const aiVector2D& b) const {
  476. if (a.x == b.x) {
  477. return a.y < b.y;
  478. }
  479. return a.x < b.x;
  480. }
  481. };
  482. // ------------------------------------------------------------------------------------------------
  483. struct ProjectionInfo {
  484. unsigned int ac, bc;
  485. aiVector3D p,u,v;
  486. };
  487. typedef std::pair< aiVector2D, aiVector2D > BoundingBox;
  488. typedef std::map<aiVector2D,size_t,XYSorter> XYSortedField;
  489. // ------------------------------------------------------------------------------------------------
  490. aiVector2D ProjectPositionVectorOntoPlane(const aiVector3D& x, const ProjectionInfo& proj)
  491. {
  492. const aiVector3D xx = x-proj.p;
  493. return aiVector2D(xx[proj.ac]/proj.u[proj.ac],xx[proj.bc]/proj.v[proj.bc]);
  494. }
  495. // ------------------------------------------------------------------------------------------------
  496. void QuadrifyPart(const aiVector2D& pmin, const aiVector2D& pmax, XYSortedField& field, const std::vector< BoundingBox >& bbs,
  497. std::vector<aiVector2D>& out)
  498. {
  499. if (!(pmin.x-pmax.x) || !(pmin.y-pmax.y)) {
  500. return;
  501. }
  502. float xs = 1e10, xe = 1e10;
  503. bool found = false;
  504. // Search along the x-axis until we find an opening
  505. XYSortedField::iterator start = field.begin();
  506. for(; start != field.end(); ++start) {
  507. const BoundingBox& bb = bbs[(*start).second];
  508. if(bb.first.x >= pmax.x) {
  509. break;
  510. }
  511. if (bb.second.x > pmin.x && bb.second.y > pmin.y && bb.first.y < pmax.y) {
  512. xs = bb.first.x;
  513. xe = bb.second.x;
  514. found = true;
  515. break;
  516. }
  517. }
  518. if (!found) {
  519. // the rectangle [pmin,pend] is opaque, fill it
  520. out.push_back(pmin);
  521. out.push_back(aiVector2D(pmin.x,pmax.y));
  522. out.push_back(pmax);
  523. out.push_back(aiVector2D(pmax.x,pmin.y));
  524. return;
  525. }
  526. xs = std::max(pmin.x,xs);
  527. xe = std::min(pmax.x,xe);
  528. // see if there's an offset to fill at the top of our quad
  529. if (xs - pmin.x) {
  530. out.push_back(pmin);
  531. out.push_back(aiVector2D(pmin.x,pmax.y));
  532. out.push_back(aiVector2D(xs,pmax.y));
  533. out.push_back(aiVector2D(xs,pmin.y));
  534. }
  535. // search along the y-axis for all openings that overlap xs and our quad
  536. float ylast = pmin.y;
  537. found = false;
  538. for(; start != field.end(); ++start) {
  539. const BoundingBox& bb = bbs[(*start).second];
  540. if (bb.first.x > xs || bb.first.y >= pmax.y) {
  541. break;
  542. }
  543. if (bb.second.y > ylast) {
  544. found = true;
  545. const float ys = std::max(bb.first.y,pmin.y), ye = std::min(bb.second.y,pmax.y);
  546. if (ys - ylast) {
  547. QuadrifyPart( aiVector2D(xs,ylast), aiVector2D(xe,ys) ,field,bbs,out);
  548. }
  549. // the following are the window vertices
  550. /*wnd.push_back(aiVector2D(xs,ys));
  551. wnd.push_back(aiVector2D(xs,ye));
  552. wnd.push_back(aiVector2D(xe,ye));
  553. wnd.push_back(aiVector2D(xe,ys));*/
  554. ylast = ye;
  555. }
  556. }
  557. if (!found) {
  558. // the rectangle [pmin,pend] is opaque, fill it
  559. out.push_back(aiVector2D(xs,pmin.y));
  560. out.push_back(aiVector2D(xs,pmax.y));
  561. out.push_back(aiVector2D(xe,pmax.y));
  562. out.push_back(aiVector2D(xe,pmin.y));
  563. return;
  564. }
  565. if (ylast < pmax.y) {
  566. QuadrifyPart( aiVector2D(xs,ylast), aiVector2D(xe,pmax.y) ,field,bbs,out);
  567. }
  568. // now for the whole rest
  569. if (pmax.x-xe) {
  570. QuadrifyPart(aiVector2D(xe,pmin.y), pmax ,field,bbs,out);
  571. }
  572. }
  573. // ------------------------------------------------------------------------------------------------
  574. enum Intersect {
  575. Intersect_No,
  576. Intersect_LiesOnPlane,
  577. Intersect_Yes
  578. };
  579. // ------------------------------------------------------------------------------------------------
  580. Intersect IntersectSegmentPlane(const aiVector3D& p,const aiVector3D& n, const aiVector3D& e0, const aiVector3D& e1, aiVector3D& out)
  581. {
  582. const aiVector3D pdelta = e0 - p, seg = e1-e0;
  583. const float dotOne = n*seg, dotTwo = -(n*pdelta);
  584. if (fabs(dotOne) < 1e-6) {
  585. return fabs(dotTwo) < 1e-6f ? Intersect_LiesOnPlane : Intersect_No;
  586. }
  587. const float t = dotTwo/dotOne;
  588. // t must be in [0..1] if the intersection point is within the given segment
  589. if (t > 1.f || t < 0.f) {
  590. return Intersect_No;
  591. }
  592. out = e0+t*seg;
  593. return Intersect_Yes;
  594. }
  595. // ------------------------------------------------------------------------------------------------
  596. aiVector3D Unproject(const aiVector2D& vproj, const ProjectionInfo& proj)
  597. {
  598. return vproj.x*proj.u + vproj.y*proj.v + proj.p;
  599. }
  600. // ------------------------------------------------------------------------------------------------
  601. void InsertWindowContours(const std::vector< BoundingBox >& bbs,const std::vector< std::vector<aiVector2D> >& contours,const ProjectionInfo& proj, TempMesh& curmesh)
  602. {
  603. ai_assert(contours.size() == bbs.size());
  604. // fix windows - we need to insert the real, polygonal shapes into the quadratic holes that we have now
  605. for(size_t i = 0; i < contours.size();++i) {
  606. const BoundingBox& bb = bbs[i];
  607. const std::vector<aiVector2D>& contour = contours[i];
  608. // check if we need to do it at all - many windows just fit perfectly into their quadratic holes,
  609. // i.e. their contours *are* already their bounding boxes.
  610. if (contour.size() == 4) {
  611. std::set<aiVector2D,XYSorter> verts;
  612. for(size_t n = 0; n < 4; ++n) {
  613. verts.insert(contour[n]);
  614. }
  615. const std::set<aiVector2D,XYSorter>::const_iterator end = verts.end();
  616. if (verts.find(bb.first)!=end && verts.find(bb.second)!=end
  617. && verts.find(aiVector2D(bb.first.x,bb.second.y))!=end
  618. && verts.find(aiVector2D(bb.second.x,bb.first.y))!=end
  619. ) {
  620. continue;
  621. }
  622. }
  623. const float epsilon = (bb.first-bb.second).Length()/1000.f;
  624. // walk through all contour points and find those that lie on the BB corner
  625. size_t last_hit = -1, very_first_hit = -1;
  626. aiVector2D edge;
  627. for(size_t n = 0, e=0, size = contour.size();; n=(n+1)%size, ++e) {
  628. // sanity checking
  629. if (e == size*2) {
  630. IFCImporter::LogError("encountered unexpected topology while generating window contour");
  631. break;
  632. }
  633. const aiVector2D& v = contour[n];
  634. bool hit = false;
  635. if (fabs(v.x-bb.first.x)<epsilon) {
  636. edge.x = bb.first.x;
  637. hit = true;
  638. }
  639. else if (fabs(v.x-bb.second.x)<epsilon) {
  640. edge.x = bb.second.x;
  641. hit = true;
  642. }
  643. if (fabs(v.y-bb.first.y)<epsilon) {
  644. edge.y = bb.first.y;
  645. hit = true;
  646. }
  647. else if (fabs(v.y-bb.second.y)<epsilon) {
  648. edge.y = bb.second.y;
  649. hit = true;
  650. }
  651. if (hit) {
  652. if (last_hit != (size_t)-1) {
  653. const size_t old = curmesh.verts.size();
  654. size_t cnt = last_hit > n ? size-(last_hit-n) : n-last_hit;
  655. for(size_t a = last_hit, e = 0; e <= cnt; a=(a+1)%size, ++e) {
  656. curmesh.verts.push_back(Unproject(contour[a],proj));
  657. }
  658. if (edge != contour[last_hit] && edge != contour[n]) {
  659. curmesh.verts.push_back(Unproject(edge,proj));
  660. }
  661. else if (cnt == 1) {
  662. // avoid degenerate polygons (also known as lines or points)
  663. curmesh.verts.erase(curmesh.verts.begin()+old,curmesh.verts.end());
  664. }
  665. if (const size_t d = curmesh.verts.size()-old) {
  666. curmesh.vertcnt.push_back(d);
  667. std::reverse(curmesh.verts.rbegin(),curmesh.verts.rbegin()+d);
  668. }
  669. if (n == very_first_hit) {
  670. break;
  671. }
  672. }
  673. else {
  674. very_first_hit = n;
  675. }
  676. last_hit = n;
  677. }
  678. }
  679. }
  680. }
  681. // ------------------------------------------------------------------------------------------------
  682. bool TryAddOpenings_Quadrulate(const std::vector<TempOpening>& openings,const std::vector<aiVector3D>& nors, TempMesh& curmesh)
  683. {
  684. std::vector<aiVector3D>& out = curmesh.verts;
  685. // Try to derive a solid base plane within the current surface for use as
  686. // working coordinate system.
  687. aiVector3D vmin,vmax;
  688. ArrayBounds(&out[0],out.size(),vmin,vmax);
  689. const size_t s = out.size();
  690. const aiVector3D any_point = out[s-4];
  691. const aiVector3D nor = ((out[s-3]-any_point)^(out[s-2]-any_point)).Normalize();
  692. const aiVector3D diag = vmax-vmin;
  693. const float ax = fabs(nor.x);
  694. const float ay = fabs(nor.y);
  695. const float az = fabs(nor.z);
  696. unsigned int ac = 0, bc = 1; /* no z coord. -> projection to xy */
  697. if (ax > ay) {
  698. if (ax > az) { /* no x coord. -> projection to yz */
  699. ac = 1; bc = 2;
  700. }
  701. }
  702. else if (ay > az) { /* no y coord. -> projection to zy */
  703. ac = 2; bc = 0;
  704. }
  705. ProjectionInfo proj;
  706. proj.u = proj.v = diag;
  707. proj.u[bc]=0;
  708. proj.v[ac]=0;
  709. proj.ac = ac;
  710. proj.bc = bc;
  711. proj.p = vmin;
  712. // project all points into the coordinate system defined by the p+sv*tu plane
  713. // and compute bounding boxes for them
  714. std::vector< BoundingBox > bbs;
  715. XYSortedField field;
  716. std::vector<aiVector2D> contour_flat;
  717. contour_flat.reserve(out.size());
  718. BOOST_FOREACH(const aiVector3D& x, out) {
  719. contour_flat.push_back(ProjectPositionVectorOntoPlane(x,proj));
  720. }
  721. std::vector< std::vector<aiVector2D> > contours;
  722. size_t c = 0;
  723. BOOST_FOREACH(const TempOpening& t,openings) {
  724. const aiVector3D& outernor = nors[c++];
  725. const float dot = nor * outernor;
  726. if (fabs(dot)<1.f-1e-6f) {
  727. continue;
  728. }
  729. // const aiVector3D diff = t.extrusionDir;
  730. const std::vector<aiVector3D>& va = t.profileMesh->verts;
  731. if(va.size() <= 2) {
  732. continue;
  733. }
  734. aiVector2D vpmin,vpmax;
  735. MinMaxChooser<aiVector2D>()(vpmin,vpmax);
  736. contours.push_back(std::vector<aiVector2D>());
  737. std::vector<aiVector2D>& contour = contours.back();
  738. BOOST_FOREACH(const aiVector3D& x, t.profileMesh->verts) {
  739. const aiVector2D& vproj = ProjectPositionVectorOntoPlane(x,proj);
  740. vpmin = std::min(vpmin,vproj);
  741. vpmax = std::max(vpmax,vproj);
  742. contour.push_back(vproj);
  743. }
  744. if (field.find(vpmin) != field.end()) {
  745. IFCImporter::LogWarn("constraint failure during generation of wall openings, results may be faulty");
  746. }
  747. field[vpmin] = bbs.size();
  748. bbs.push_back(BoundingBox(vpmin,vpmax));
  749. }
  750. if (bbs.empty()) {
  751. return false;
  752. }
  753. std::vector<aiVector2D> outflat;
  754. outflat.reserve(openings.size()*4);
  755. QuadrifyPart(aiVector2D(0.f,0.f),aiVector2D(1.f,1.f),field,bbs,outflat);
  756. ai_assert(!(outflat.size() % 4));
  757. //FixOuterBoundaries(outflat,contour_flat);
  758. // undo the projection, generate output quads
  759. std::vector<aiVector3D> vold;
  760. vold.reserve(outflat.size());
  761. std::swap(vold,curmesh.verts);
  762. std::vector<unsigned int> iold;
  763. iold.resize(outflat.size()/4,4);
  764. std::swap(iold,curmesh.vertcnt);
  765. BOOST_FOREACH(const aiVector2D& vproj, outflat) {
  766. out.push_back(Unproject(vproj,proj));
  767. }
  768. InsertWindowContours(bbs,contours,proj,curmesh);
  769. return true;
  770. }
  771. // ------------------------------------------------------------------------------------------------
  772. void ProcessExtrudedAreaSolid(const IfcExtrudedAreaSolid& solid, TempMesh& result, ConversionData& conv)
  773. {
  774. TempMesh meshout;
  775. // first read the profile description
  776. if(!ProcessProfile(*solid.SweptArea,meshout,conv) || meshout.verts.size()<=1) {
  777. return;
  778. }
  779. aiVector3D dir;
  780. ConvertDirection(dir,solid.ExtrudedDirection);
  781. dir *= solid.Depth;
  782. // assuming that `meshout.verts` is now a list of vertex points forming
  783. // the underlying profile, extrude along the given axis, forming new
  784. // triangles.
  785. std::vector<aiVector3D>& in = meshout.verts;
  786. const size_t size=in.size();
  787. const bool has_area = solid.SweptArea->ProfileType == "AREA" && size>2;
  788. if(solid.Depth < 1e-3) {
  789. if(has_area) {
  790. meshout = result;
  791. }
  792. return;
  793. }
  794. result.verts.reserve(size*(has_area?4:2));
  795. result.vertcnt.reserve(meshout.vertcnt.size()+2);
  796. // transform to target space
  797. aiMatrix4x4 trafo;
  798. ConvertAxisPlacement(trafo, solid.Position);
  799. BOOST_FOREACH(aiVector3D& v,in) {
  800. v *= trafo;
  801. }
  802. aiVector3D min = in[0];
  803. dir *= aiMatrix3x3(trafo);
  804. std::vector<aiVector3D> nors;
  805. // compute the normal vectors for all opening polygons
  806. if (conv.apply_openings) {
  807. if (!conv.settings.useCustomTriangulation) {
  808. // it is essential to apply the openings in the correct spatial order. The direction
  809. // doesn't matter, but we would screw up if we started with e.g. a door in between
  810. // two windows.
  811. std::sort(conv.apply_openings->begin(),conv.apply_openings->end(),DistanceSorter(min));
  812. }
  813. nors.reserve(conv.apply_openings->size());
  814. BOOST_FOREACH(TempOpening& t,*conv.apply_openings) {
  815. TempMesh& bounds = *t.profileMesh.get();
  816. if (bounds.verts.size() <= 2) {
  817. nors.push_back(aiVector3D());
  818. continue;
  819. }
  820. nors.push_back(((bounds.verts[2]-bounds.verts[0])^(bounds.verts[1]-bounds.verts[0]) ).Normalize());
  821. }
  822. }
  823. TempMesh temp;
  824. TempMesh& curmesh = conv.apply_openings ? temp : result;
  825. std::vector<aiVector3D>& out = curmesh.verts;
  826. bool (* const gen_openings)(const std::vector<TempOpening>&,const std::vector<aiVector3D>&, TempMesh&) = conv.settings.useCustomTriangulation
  827. ? &TryAddOpenings_Quadrulate
  828. : &TryAddOpenings;
  829. size_t sides_with_openings = 0;
  830. for(size_t i = 0; i < size; ++i) {
  831. const size_t next = (i+1)%size;
  832. curmesh.vertcnt.push_back(4);
  833. out.push_back(in[i]);
  834. out.push_back(in[i]+dir);
  835. out.push_back(in[next]+dir);
  836. out.push_back(in[next]);
  837. if(conv.apply_openings) {
  838. if(gen_openings(*conv.apply_openings,nors,temp)) {
  839. ++sides_with_openings;
  840. }
  841. result.Append(temp);
  842. temp.Clear();
  843. }
  844. }
  845. size_t sides_with_v_openings = 0;
  846. if(has_area) {
  847. for(size_t n = 0; n < 2; ++n) {
  848. for(size_t i = size; i--; ) {
  849. out.push_back(in[i]+(n?dir:aiVector3D()));
  850. }
  851. curmesh.vertcnt.push_back(size);
  852. if(conv.apply_openings && size > 2) {
  853. // XXX here we are forced to use the un-triangulated version of TryAddOpening, with
  854. // all the problems it causes. The reason is that vertical walls (ehm, floors)
  855. // can have an arbitrary outer shape, so the usual approach of projecting
  856. // the surface and all openings onto a flat quad and triangulating the quad
  857. // fails.
  858. if(TryAddOpenings(*conv.apply_openings,nors,temp)) {
  859. ++sides_with_v_openings;
  860. }
  861. result.Append(temp);
  862. temp.Clear();
  863. }
  864. }
  865. }
  866. // add connection geometry to close the 'holes' for the openings
  867. if(conv.apply_openings) {
  868. //result.infacing.resize(result.verts.size()+);
  869. BOOST_FOREACH(const TempOpening& t,*conv.apply_openings) {
  870. const std::vector<aiVector3D>& in = t.profileMesh->verts;
  871. std::vector<aiVector3D>& out = result.verts;
  872. const aiVector3D dir = t.extrusionDir;
  873. for(size_t i = 0, size = in.size(); i < size; ++i) {
  874. const size_t next = (i+1)%size;
  875. result.vertcnt.push_back(4);
  876. out.push_back(in[i]);
  877. out.push_back(in[i]+dir);
  878. out.push_back(in[next]+dir);
  879. out.push_back(in[next]);
  880. }
  881. }
  882. }
  883. if(conv.apply_openings && ((sides_with_openings != 2 && sides_with_openings) || (sides_with_v_openings != 2 && sides_with_v_openings))) {
  884. IFCImporter::LogWarn("failed to resolve all openings, presumably their topology is not supported by Assimp");
  885. }
  886. IFCImporter::LogDebug("generate mesh procedurally by extrusion (IfcExtrudedAreaSolid)");
  887. }
  888. // ------------------------------------------------------------------------------------------------
  889. void ProcessSweptAreaSolid(const IfcSweptAreaSolid& swept, TempMesh& meshout, ConversionData& conv)
  890. {
  891. if(const IfcExtrudedAreaSolid* const solid = swept.ToPtr<IfcExtrudedAreaSolid>()) {
  892. // Do we just collect openings for a parent element (i.e. a wall)?
  893. // In this case we don't extrude the surface yet, just keep the profile and transform it correctly
  894. if(conv.collect_openings) {
  895. boost::shared_ptr<TempMesh> meshtmp(new TempMesh());
  896. ProcessProfile(swept.SweptArea,*meshtmp,conv);
  897. aiMatrix4x4 m;
  898. ConvertAxisPlacement(m,solid->Position);
  899. meshtmp->Transform(m);
  900. aiVector3D dir;
  901. ConvertDirection(dir,solid->ExtrudedDirection);
  902. conv.collect_openings->push_back(TempOpening(solid, aiMatrix3x3(m) * (dir*solid->Depth),meshtmp));
  903. return;
  904. }
  905. ProcessExtrudedAreaSolid(*solid,meshout,conv);
  906. }
  907. else if(const IfcRevolvedAreaSolid* const rev = swept.ToPtr<IfcRevolvedAreaSolid>()) {
  908. ProcessRevolvedAreaSolid(*rev,meshout,conv);
  909. }
  910. else {
  911. IFCImporter::LogWarn("skipping unknown IfcSweptAreaSolid entity, type is " + swept.GetClassName());
  912. }
  913. }
  914. // ------------------------------------------------------------------------------------------------
  915. void ProcessBoolean(const IfcBooleanResult& boolean, TempMesh& result, ConversionData& conv)
  916. {
  917. if(const IfcBooleanClippingResult* const clip = boolean.ToPtr<IfcBooleanClippingResult>()) {
  918. if(clip->Operator != "DIFFERENCE") {
  919. IFCImporter::LogWarn("encountered unsupported boolean operator: " + (std::string)clip->Operator);
  920. return;
  921. }
  922. TempMesh meshout;
  923. const IfcHalfSpaceSolid* const hs = clip->SecondOperand->ResolveSelectPtr<IfcHalfSpaceSolid>(conv.db);
  924. if(!hs) {
  925. IFCImporter::LogError("expected IfcHalfSpaceSolid as second clipping operand");
  926. return;
  927. }
  928. const IfcPlane* const plane = hs->BaseSurface->ToPtr<IfcPlane>();
  929. if(!plane) {
  930. IFCImporter::LogError("expected IfcPlane as base surface for the IfcHalfSpaceSolid");
  931. return;
  932. }
  933. if(const IfcBooleanResult* const op0 = clip->FirstOperand->ResolveSelectPtr<IfcBooleanResult>(conv.db)) {
  934. ProcessBoolean(*op0,meshout,conv);
  935. }
  936. else if (const IfcSweptAreaSolid* const swept = clip->FirstOperand->ResolveSelectPtr<IfcSweptAreaSolid>(conv.db)) {
  937. ProcessSweptAreaSolid(*swept,meshout,conv);
  938. }
  939. else {
  940. IFCImporter::LogError("expected IfcSweptAreaSolid or IfcBooleanResult as first clipping operand");
  941. return;
  942. }
  943. // extract plane base position vector and normal vector
  944. aiVector3D p,n(0.f,0.f,1.f);
  945. if (plane->Position->Axis) {
  946. ConvertDirection(n,plane->Position->Axis.Get());
  947. }
  948. ConvertCartesianPoint(p,plane->Position->Location);
  949. if(!IsTrue(hs->AgreementFlag)) {
  950. n *= -1.f;
  951. }
  952. // clip the current contents of `meshout` against the plane we obtained from the second operand
  953. const std::vector<aiVector3D>& in = meshout.verts;
  954. std::vector<aiVector3D>& outvert = result.verts;
  955. std::vector<unsigned int>::const_iterator begin=meshout.vertcnt.begin(), end=meshout.vertcnt.end(), iit;
  956. outvert.reserve(in.size());
  957. result.vertcnt.reserve(meshout.vertcnt.size());
  958. unsigned int vidx = 0;
  959. for(iit = begin; iit != end; vidx += *iit++) {
  960. unsigned int newcount = 0;
  961. for(unsigned int i = 0; i < *iit; ++i) {
  962. const aiVector3D& e0 = in[vidx+i], e1 = in[vidx+(i+1)%*iit];
  963. // does the next segment intersect the plane?
  964. aiVector3D isectpos;
  965. const Intersect isect = IntersectSegmentPlane(p,n,e0,e1,isectpos);
  966. if (isect == Intersect_No || isect == Intersect_LiesOnPlane) {
  967. if ( (e0-p).Normalize()*n > 0 ) {
  968. outvert.push_back(e0);
  969. ++newcount;
  970. }
  971. }
  972. else if (isect == Intersect_Yes) {
  973. if ( (e0-p).Normalize()*n > 0 ) {
  974. // e0 is on the right side, so keep it
  975. outvert.push_back(e0);
  976. outvert.push_back(isectpos);
  977. newcount += 2;
  978. }
  979. else {
  980. // e0 is on the wrong side, so drop it and keep e1 instead
  981. outvert.push_back(isectpos);
  982. ++newcount;
  983. }
  984. }
  985. }
  986. if (!newcount) {
  987. continue;
  988. }
  989. aiVector3D vmin,vmax;
  990. ArrayBounds(&*(outvert.end()-newcount),newcount,vmin,vmax);
  991. // filter our double points - those may happen if a point lies
  992. // directly on the intersection line. However, due to float
  993. // precision a bitwise comparison is not feasible to detect
  994. // this case.
  995. const float epsilon = (vmax-vmin).SquareLength() / 1e6f;
  996. FuzzyVectorCompare fz(epsilon);
  997. std::vector<aiVector3D>::iterator e = std::unique( outvert.end()-newcount, outvert.end(), fz );
  998. if (e != outvert.end()) {
  999. newcount -= static_cast<unsigned int>(std::distance(e,outvert.end()));
  1000. outvert.erase(e,outvert.end());
  1001. }
  1002. if (fz(*( outvert.end()-newcount),outvert.back())) {
  1003. outvert.pop_back();
  1004. --newcount;
  1005. }
  1006. if(newcount > 2) {
  1007. result.vertcnt.push_back(newcount);
  1008. }
  1009. else while(newcount-->0)result.verts.pop_back();
  1010. }
  1011. IFCImporter::LogDebug("generating CSG geometry by plane clipping (IfcBooleanClippingResult)");
  1012. }
  1013. else {
  1014. IFCImporter::LogWarn("skipping unknown IfcBooleanResult entity, type is " + boolean.GetClassName());
  1015. }
  1016. }
  1017. // ------------------------------------------------------------------------------------------------
  1018. bool ProcessGeometricItem(const IfcRepresentationItem& geo, std::vector<unsigned int>& mesh_indices, ConversionData& conv)
  1019. {
  1020. TempMesh meshtmp;
  1021. if(const IfcShellBasedSurfaceModel* shellmod = geo.ToPtr<IfcShellBasedSurfaceModel>()) {
  1022. BOOST_FOREACH(boost::shared_ptr<const IfcShell> shell,shellmod->SbsmBoundary) {
  1023. try {
  1024. const EXPRESS::ENTITY& e = shell->To<ENTITY>();
  1025. const IfcConnectedFaceSet& fs = conv.db.MustGetObject(e).To<IfcConnectedFaceSet>();
  1026. ProcessConnectedFaceSet(fs,meshtmp,conv);
  1027. }
  1028. catch(std::bad_cast&) {
  1029. IFCImporter::LogWarn("unexpected type error, IfcShell ought to inherit from IfcConnectedFaceSet");
  1030. }
  1031. }
  1032. }
  1033. else if(const IfcConnectedFaceSet* fset = geo.ToPtr<IfcConnectedFaceSet>()) {
  1034. ProcessConnectedFaceSet(*fset,meshtmp,conv);
  1035. }
  1036. else if(const IfcSweptAreaSolid* swept = geo.ToPtr<IfcSweptAreaSolid>()) {
  1037. ProcessSweptAreaSolid(*swept,meshtmp,conv);
  1038. }
  1039. else if(const IfcManifoldSolidBrep* brep = geo.ToPtr<IfcManifoldSolidBrep>()) {
  1040. ProcessConnectedFaceSet(brep->Outer,meshtmp,conv);
  1041. }
  1042. else if(const IfcFaceBasedSurfaceModel* surf = geo.ToPtr<IfcFaceBasedSurfaceModel>()) {
  1043. BOOST_FOREACH(const IfcConnectedFaceSet& fc, surf->FbsmFaces) {
  1044. ProcessConnectedFaceSet(fc,meshtmp,conv);
  1045. }
  1046. }
  1047. else if(const IfcBooleanResult* boolean = geo.ToPtr<IfcBooleanResult>()) {
  1048. ProcessBoolean(*boolean,meshtmp,conv);
  1049. }
  1050. else if(geo.ToPtr<IfcBoundingBox>()) {
  1051. // silently skip over bounding boxes
  1052. return false;
  1053. }
  1054. else {
  1055. IFCImporter::LogWarn("skipping unknown IfcGeometricRepresentationItem entity, type is " + geo.GetClassName());
  1056. return false;
  1057. }
  1058. meshtmp.RemoveAdjacentDuplicates();
  1059. FixupFaceOrientation(meshtmp);
  1060. aiMesh* const mesh = meshtmp.ToMesh();
  1061. if(mesh) {
  1062. mesh->mMaterialIndex = ProcessMaterials(geo,conv);
  1063. mesh_indices.push_back(conv.meshes.size());
  1064. conv.meshes.push_back(mesh);
  1065. return true;
  1066. }
  1067. return false;
  1068. }
  1069. // ------------------------------------------------------------------------------------------------
  1070. void AssignAddedMeshes(std::vector<unsigned int>& mesh_indices,aiNode* nd,ConversionData& /*conv*/)
  1071. {
  1072. if (!mesh_indices.empty()) {
  1073. // make unique
  1074. std::sort(mesh_indices.begin(),mesh_indices.end());
  1075. std::vector<unsigned int>::iterator it_end = std::unique(mesh_indices.begin(),mesh_indices.end());
  1076. const size_t size = std::distance(mesh_indices.begin(),it_end);
  1077. nd->mNumMeshes = size;
  1078. nd->mMeshes = new unsigned int[nd->mNumMeshes];
  1079. for(unsigned int i = 0; i < nd->mNumMeshes; ++i) {
  1080. nd->mMeshes[i] = mesh_indices[i];
  1081. }
  1082. }
  1083. }
  1084. // ------------------------------------------------------------------------------------------------
  1085. bool TryQueryMeshCache(const IfcRepresentationItem& item, std::vector<unsigned int>& mesh_indices, ConversionData& conv)
  1086. {
  1087. ConversionData::MeshCache::const_iterator it = conv.cached_meshes.find(&item);
  1088. if (it != conv.cached_meshes.end()) {
  1089. std::copy((*it).second.begin(),(*it).second.end(),std::back_inserter(mesh_indices));
  1090. return true;
  1091. }
  1092. return false;
  1093. }
  1094. // ------------------------------------------------------------------------------------------------
  1095. void PopulateMeshCache(const IfcRepresentationItem& item, const std::vector<unsigned int>& mesh_indices, ConversionData& conv)
  1096. {
  1097. conv.cached_meshes[&item] = mesh_indices;
  1098. }
  1099. // ------------------------------------------------------------------------------------------------
  1100. bool ProcessRepresentationItem(const IfcRepresentationItem& item, std::vector<unsigned int>& mesh_indices, ConversionData& conv)
  1101. {
  1102. if (!TryQueryMeshCache(item,mesh_indices,conv)) {
  1103. if(ProcessGeometricItem(item,mesh_indices,conv)) {
  1104. if(mesh_indices.size()) {
  1105. PopulateMeshCache(item,mesh_indices,conv);
  1106. }
  1107. }
  1108. else return false;
  1109. }
  1110. return true;
  1111. }
  1112. } // ! IFC
  1113. } // ! Assimp
  1114. #endif