IFCGeometry.cpp 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2010, assimp team
  5. All rights reserved.
  6. Redistribution and use of this software in source and binary forms,
  7. with or without modification, are permitted provided that the
  8. following conditions are met:
  9. * Redistributions of source code must retain the above
  10. copyright notice, this list of conditions and the
  11. following disclaimer.
  12. * Redistributions in binary form must reproduce the above
  13. copyright notice, this list of conditions and the
  14. following disclaimer in the documentation and/or other
  15. materials provided with the distribution.
  16. * Neither the name of the assimp team, nor the names of its
  17. contributors may be used to endorse or promote products
  18. derived from this software without specific prior
  19. written permission of the assimp team.
  20. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. ----------------------------------------------------------------------
  32. */
  33. /** @file 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. #include "../contrib/poly2tri/poly2tri/poly2tri.h"
  42. #include "../contrib/clipper/clipper.hpp"
  43. #include <iterator>
  44. namespace Assimp {
  45. namespace IFC {
  46. using ClipperLib::ulong64;
  47. // XXX use full -+ range ...
  48. const ClipperLib::long64 max_ulong64 = 1518500249; // clipper.cpp / hiRange var
  49. //#define to_int64(p) (static_cast<ulong64>( std::max( 0., std::min( static_cast<IfcFloat>((p)), 1.) ) * max_ulong64 ))
  50. #define to_int64(p) (static_cast<ulong64>(static_cast<IfcFloat>((p) ) * max_ulong64 ))
  51. #define from_int64(p) (static_cast<IfcFloat>((p)) / max_ulong64)
  52. // ------------------------------------------------------------------------------------------------
  53. bool ProcessPolyloop(const IfcPolyLoop& loop, TempMesh& meshout, ConversionData& /*conv*/)
  54. {
  55. size_t cnt = 0;
  56. BOOST_FOREACH(const IfcCartesianPoint& c, loop.Polygon) {
  57. IfcVector3 tmp;
  58. ConvertCartesianPoint(tmp,c);
  59. meshout.verts.push_back(tmp);
  60. ++cnt;
  61. }
  62. meshout.vertcnt.push_back(cnt);
  63. // zero- or one- vertex polyloops simply ignored
  64. if (meshout.vertcnt.back() > 1) {
  65. return true;
  66. }
  67. if (meshout.vertcnt.back()==1) {
  68. meshout.vertcnt.pop_back();
  69. meshout.verts.pop_back();
  70. }
  71. return false;
  72. }
  73. // ------------------------------------------------------------------------------------------------
  74. void ComputePolygonNormals(const TempMesh& meshout, std::vector<IfcVector3>& normals, bool normalize = true, size_t ofs = 0)
  75. {
  76. size_t max_vcount = 0;
  77. std::vector<unsigned int>::const_iterator begin=meshout.vertcnt.begin()+ofs, end=meshout.vertcnt.end(), iit;
  78. for(iit = begin; iit != end; ++iit) {
  79. max_vcount = std::max(max_vcount,static_cast<size_t>(*iit));
  80. }
  81. std::vector<IfcFloat> temp((max_vcount+2)*4);
  82. normals.reserve( normals.size() + meshout.vertcnt.size()-ofs );
  83. // `NewellNormal()` currently has a relatively strange interface and need to
  84. // re-structure things a bit to meet them.
  85. size_t vidx = std::accumulate(meshout.vertcnt.begin(),begin,0);
  86. for(iit = begin; iit != end; vidx += *iit++) {
  87. if (!*iit) {
  88. normals.push_back(IfcVector3());
  89. continue;
  90. }
  91. for(size_t vofs = 0, cnt = 0; vofs < *iit; ++vofs) {
  92. const IfcVector3& v = meshout.verts[vidx+vofs];
  93. temp[cnt++] = v.x;
  94. temp[cnt++] = v.y;
  95. temp[cnt++] = v.z;
  96. #ifdef _DEBUG
  97. temp[cnt] = std::numeric_limits<IfcFloat>::quiet_NaN();
  98. #endif
  99. ++cnt;
  100. }
  101. normals.push_back(IfcVector3());
  102. NewellNormal<4,4,4>(normals.back(),*iit,&temp[0],&temp[1],&temp[2]);
  103. }
  104. if(normalize) {
  105. BOOST_FOREACH(IfcVector3& n, normals) {
  106. n.Normalize();
  107. }
  108. }
  109. }
  110. // ------------------------------------------------------------------------------------------------
  111. // Compute the normal of the last polygon in the given mesh
  112. IfcVector3 ComputePolygonNormal(const TempMesh& inmesh, bool normalize = true)
  113. {
  114. size_t total = inmesh.vertcnt.back(), vidx = inmesh.verts.size() - total;
  115. std::vector<IfcFloat> temp((total+2)*3);
  116. for(size_t vofs = 0, cnt = 0; vofs < total; ++vofs) {
  117. const IfcVector3& v = inmesh.verts[vidx+vofs];
  118. temp[cnt++] = v.x;
  119. temp[cnt++] = v.y;
  120. temp[cnt++] = v.z;
  121. }
  122. IfcVector3 nor;
  123. NewellNormal<3,3,3>(nor,total,&temp[0],&temp[1],&temp[2]);
  124. return normalize ? nor.Normalize() : nor;
  125. }
  126. // ------------------------------------------------------------------------------------------------
  127. void FixupFaceOrientation(TempMesh& result)
  128. {
  129. const IfcVector3 vavg = result.Center();
  130. std::vector<IfcVector3> normals;
  131. ComputePolygonNormals(result,normals);
  132. size_t c = 0, ofs = 0;
  133. BOOST_FOREACH(unsigned int cnt, result.vertcnt) {
  134. if (cnt>2){
  135. const IfcVector3& thisvert = result.verts[c];
  136. if (normals[ofs]*(thisvert-vavg) < 0) {
  137. std::reverse(result.verts.begin()+c,result.verts.begin()+cnt+c);
  138. }
  139. }
  140. c += cnt;
  141. ++ofs;
  142. }
  143. }
  144. // ------------------------------------------------------------------------------------------------
  145. void RecursiveMergeBoundaries(TempMesh& final_result, const TempMesh& in, const TempMesh& boundary, std::vector<IfcVector3>& normals, const IfcVector3& nor_boundary)
  146. {
  147. ai_assert(in.vertcnt.size() >= 1);
  148. ai_assert(boundary.vertcnt.size() == 1);
  149. std::vector<unsigned int>::const_iterator end = in.vertcnt.end(), begin=in.vertcnt.begin(), iit, best_iit;
  150. TempMesh out;
  151. // iterate through all other bounds and find the one for which the shortest connection
  152. // to the outer boundary is actually the shortest possible.
  153. size_t vidx = 0, best_vidx_start = 0;
  154. size_t best_ofs, best_outer = boundary.verts.size();
  155. IfcFloat best_dist = 1e10;
  156. for(std::vector<unsigned int>::const_iterator iit = begin; iit != end; vidx += *iit++) {
  157. for(size_t vofs = 0; vofs < *iit; ++vofs) {
  158. const IfcVector3& v = in.verts[vidx+vofs];
  159. for(size_t outer = 0; outer < boundary.verts.size(); ++outer) {
  160. const IfcVector3& o = boundary.verts[outer];
  161. const IfcFloat d = (o-v).SquareLength();
  162. if (d < best_dist) {
  163. best_dist = d;
  164. best_ofs = vofs;
  165. best_outer = outer;
  166. best_iit = iit;
  167. best_vidx_start = vidx;
  168. }
  169. }
  170. }
  171. }
  172. ai_assert(best_outer != boundary.verts.size());
  173. // now that we collected all vertex connections to be added, build the output polygon
  174. const size_t cnt = boundary.verts.size() + *best_iit+2;
  175. out.verts.reserve(cnt);
  176. for(size_t outer = 0; outer < boundary.verts.size(); ++outer) {
  177. const IfcVector3& o = boundary.verts[outer];
  178. out.verts.push_back(o);
  179. if (outer == best_outer) {
  180. for(size_t i = best_ofs; i < *best_iit; ++i) {
  181. out.verts.push_back(in.verts[best_vidx_start + i]);
  182. }
  183. // we need the first vertex of the inner polygon twice as we return to the
  184. // outer loop through the very same connection through which we got there.
  185. for(size_t i = 0; i <= best_ofs; ++i) {
  186. out.verts.push_back(in.verts[best_vidx_start + i]);
  187. }
  188. // reverse face winding if the normal of the sub-polygon points in the
  189. // same direction as the normal of the outer polygonal boundary
  190. if (normals[std::distance(begin,best_iit)] * nor_boundary > 0) {
  191. std::reverse(out.verts.rbegin(),out.verts.rbegin()+*best_iit+1);
  192. }
  193. // also append a copy of the initial insertion point to be able to continue the outer polygon
  194. out.verts.push_back(o);
  195. }
  196. }
  197. out.vertcnt.push_back(cnt);
  198. ai_assert(out.verts.size() == cnt);
  199. if (in.vertcnt.size()-std::count(begin,end,0) > 1) {
  200. // Recursively apply the same algorithm if there are more boundaries to merge. The
  201. // current implementation is relatively inefficient, though.
  202. TempMesh temp;
  203. // drop the boundary that we just processed
  204. const size_t dist = std::distance(begin, best_iit);
  205. TempMesh remaining = in;
  206. remaining.vertcnt.erase(remaining.vertcnt.begin() + dist);
  207. remaining.verts.erase(remaining.verts.begin()+best_vidx_start,remaining.verts.begin()+best_vidx_start+*best_iit);
  208. normals.erase(normals.begin() + dist);
  209. RecursiveMergeBoundaries(temp,remaining,out,normals,nor_boundary);
  210. final_result.Append(temp);
  211. }
  212. else final_result.Append(out);
  213. }
  214. // ------------------------------------------------------------------------------------------------
  215. void MergePolygonBoundaries(TempMesh& result, const TempMesh& inmesh, size_t master_bounds = -1)
  216. {
  217. // standard case - only one boundary, just copy it to the result vector
  218. if (inmesh.vertcnt.size() <= 1) {
  219. result.Append(inmesh);
  220. return;
  221. }
  222. result.vertcnt.reserve(inmesh.vertcnt.size()+result.vertcnt.size());
  223. // XXX get rid of the extra copy if possible
  224. TempMesh meshout = inmesh;
  225. // handle polygons with holes. Our built in triangulation won't handle them as is, but
  226. // the ear cutting algorithm is solid enough to deal with them if we join the inner
  227. // holes with the outer boundaries by dummy connections.
  228. IFCImporter::LogDebug("fixing polygon with holes for triangulation via ear-cutting");
  229. std::vector<unsigned int>::iterator outer_polygon = meshout.vertcnt.end(), begin=meshout.vertcnt.begin(), end=outer_polygon, iit;
  230. // each hole results in two extra vertices
  231. result.verts.reserve(meshout.verts.size()+meshout.vertcnt.size()*2+result.verts.size());
  232. size_t outer_polygon_start = 0;
  233. // do not normalize 'normals', we need the original length for computing the polygon area
  234. std::vector<IfcVector3> normals;
  235. ComputePolygonNormals(meshout,normals,false);
  236. // see if one of the polygons is a IfcFaceOuterBound (in which case `master_bounds` is its index).
  237. // sadly we can't rely on it, the docs say 'At most one of the bounds shall be of the type IfcFaceOuterBound'
  238. IfcFloat area_outer_polygon = 1e-10f;
  239. if (master_bounds != (size_t)-1) {
  240. outer_polygon = begin + master_bounds;
  241. outer_polygon_start = std::accumulate(begin,outer_polygon,0);
  242. area_outer_polygon = normals[master_bounds].SquareLength();
  243. }
  244. else {
  245. size_t vidx = 0;
  246. for(iit = begin; iit != meshout.vertcnt.end(); vidx += *iit++) {
  247. // find the polygon with the largest area, it must be the outer bound.
  248. IfcVector3& n = normals[std::distance(begin,iit)];
  249. const IfcFloat area = n.SquareLength();
  250. if (area > area_outer_polygon) {
  251. area_outer_polygon = area;
  252. outer_polygon = iit;
  253. outer_polygon_start = vidx;
  254. }
  255. }
  256. }
  257. ai_assert(outer_polygon != meshout.vertcnt.end());
  258. std::vector<IfcVector3>& in = meshout.verts;
  259. // skip over extremely small boundaries - this is a workaround to fix cases
  260. // in which the number of holes is so extremely large that the
  261. // triangulation code fails.
  262. #define IFC_VERTICAL_HOLE_SIZE_THRESHOLD 0.000001f
  263. size_t vidx = 0, removed = 0, index = 0;
  264. const IfcFloat threshold = area_outer_polygon * IFC_VERTICAL_HOLE_SIZE_THRESHOLD;
  265. for(iit = begin; iit != end ;++index) {
  266. const IfcFloat sqlen = normals[index].SquareLength();
  267. if (sqlen < threshold) {
  268. std::vector<IfcVector3>::iterator inbase = in.begin()+vidx;
  269. in.erase(inbase,inbase+*iit);
  270. outer_polygon_start -= outer_polygon_start>vidx ? *iit : 0;
  271. *iit++ = 0;
  272. ++removed;
  273. IFCImporter::LogDebug("skip small hole below threshold");
  274. }
  275. else {
  276. normals[index] /= sqrt(sqlen);
  277. vidx += *iit++;
  278. }
  279. }
  280. // see if one or more of the hole has a face that lies directly on an outer bound.
  281. // this happens for doors, for example.
  282. vidx = 0;
  283. for(iit = begin; ; vidx += *iit++) {
  284. next_loop:
  285. if (iit == end) {
  286. break;
  287. }
  288. if (iit == outer_polygon) {
  289. continue;
  290. }
  291. for(size_t vofs = 0; vofs < *iit; ++vofs) {
  292. if (!*iit) {
  293. continue;
  294. }
  295. const size_t next = (vofs+1)%*iit;
  296. const IfcVector3& v = in[vidx+vofs], &vnext = in[vidx+next],&vd = (vnext-v).Normalize();
  297. for(size_t outer = 0; outer < *outer_polygon; ++outer) {
  298. const IfcVector3& o = in[outer_polygon_start+outer], &onext = in[outer_polygon_start+(outer+1)%*outer_polygon], &od = (onext-o).Normalize();
  299. if (fabs(vd * od) > 1.f-1e-6f && (onext-v).Normalize() * vd > 1.f-1e-6f && (onext-v)*(o-v) < 0) {
  300. IFCImporter::LogDebug("got an inner hole that lies partly on the outer polygonal boundary, merging them to a single contour");
  301. // in between outer and outer+1 insert all vertices of this loop, then drop the original altogether.
  302. std::vector<IfcVector3> tmp(*iit);
  303. const size_t start = (v-o).SquareLength() > (vnext-o).SquareLength() ? vofs : next;
  304. std::vector<IfcVector3>::iterator inbase = in.begin()+vidx, it = std::copy(inbase+start, inbase+*iit,tmp.begin());
  305. std::copy(inbase, inbase+start,it);
  306. std::reverse(tmp.begin(),tmp.end());
  307. in.insert(in.begin()+outer_polygon_start+(outer+1)%*outer_polygon,tmp.begin(),tmp.end());
  308. vidx += outer_polygon_start<vidx ? *iit : 0;
  309. inbase = in.begin()+vidx;
  310. in.erase(inbase,inbase+*iit);
  311. outer_polygon_start -= outer_polygon_start>vidx ? *iit : 0;
  312. *outer_polygon += tmp.size();
  313. *iit++ = 0;
  314. ++removed;
  315. goto next_loop;
  316. }
  317. }
  318. }
  319. }
  320. if ( meshout.vertcnt.size() - removed <= 1) {
  321. result.Append(meshout);
  322. return;
  323. }
  324. // extract the outer boundary and move it to a separate mesh
  325. TempMesh boundary;
  326. boundary.vertcnt.resize(1,*outer_polygon);
  327. boundary.verts.resize(*outer_polygon);
  328. std::vector<IfcVector3>::iterator b = in.begin()+outer_polygon_start;
  329. std::copy(b,b+*outer_polygon,boundary.verts.begin());
  330. in.erase(b,b+*outer_polygon);
  331. std::vector<IfcVector3>::iterator norit = normals.begin()+std::distance(meshout.vertcnt.begin(),outer_polygon);
  332. const IfcVector3 nor_boundary = *norit;
  333. normals.erase(norit);
  334. meshout.vertcnt.erase(outer_polygon);
  335. // keep merging the closest inner boundary with the outer boundary until no more boundaries are left
  336. RecursiveMergeBoundaries(result,meshout,boundary,normals,nor_boundary);
  337. }
  338. // ------------------------------------------------------------------------------------------------
  339. void ProcessConnectedFaceSet(const IfcConnectedFaceSet& fset, TempMesh& result, ConversionData& conv)
  340. {
  341. BOOST_FOREACH(const IfcFace& face, fset.CfsFaces) {
  342. // size_t ob = -1, cnt = 0;
  343. TempMesh meshout;
  344. BOOST_FOREACH(const IfcFaceBound& bound, face.Bounds) {
  345. // XXX implement proper merging for polygonal loops
  346. if(const IfcPolyLoop* const polyloop = bound.Bound->ToPtr<IfcPolyLoop>()) {
  347. if(ProcessPolyloop(*polyloop, meshout,conv)) {
  348. //if(bound.ToPtr<IfcFaceOuterBound>()) {
  349. // ob = cnt;
  350. //}
  351. //++cnt;
  352. }
  353. }
  354. else {
  355. IFCImporter::LogWarn("skipping unknown IfcFaceBound entity, type is " + bound.Bound->GetClassName());
  356. continue;
  357. }
  358. /*if(!IsTrue(bound.Orientation)) {
  359. size_t c = 0;
  360. BOOST_FOREACH(unsigned int& c, meshout.vertcnt) {
  361. std::reverse(result.verts.begin() + cnt,result.verts.begin() + cnt + c);
  362. cnt += c;
  363. }
  364. }*/
  365. }
  366. MergePolygonBoundaries(result,meshout);
  367. }
  368. }
  369. // ------------------------------------------------------------------------------------------------
  370. void ProcessRevolvedAreaSolid(const IfcRevolvedAreaSolid& solid, TempMesh& result, ConversionData& conv)
  371. {
  372. TempMesh meshout;
  373. // first read the profile description
  374. if(!ProcessProfile(*solid.SweptArea,meshout,conv) || meshout.verts.size()<=1) {
  375. return;
  376. }
  377. IfcVector3 axis, pos;
  378. ConvertAxisPlacement(axis,pos,solid.Axis);
  379. IfcMatrix4 tb0,tb1;
  380. IfcMatrix4::Translation(pos,tb0);
  381. IfcMatrix4::Translation(-pos,tb1);
  382. const std::vector<IfcVector3>& in = meshout.verts;
  383. const size_t size=in.size();
  384. bool has_area = solid.SweptArea->ProfileType == "AREA" && size>2;
  385. const IfcFloat max_angle = solid.Angle*conv.angle_scale;
  386. if(fabs(max_angle) < 1e-3) {
  387. if(has_area) {
  388. result = meshout;
  389. }
  390. return;
  391. }
  392. const unsigned int cnt_segments = std::max(2u,static_cast<unsigned int>(16 * fabs(max_angle)/AI_MATH_HALF_PI_F));
  393. const IfcFloat delta = max_angle/cnt_segments;
  394. has_area = has_area && fabs(max_angle) < AI_MATH_TWO_PI_F*0.99;
  395. result.verts.reserve(size*((cnt_segments+1)*4+(has_area?2:0)));
  396. result.vertcnt.reserve(size*cnt_segments+2);
  397. IfcMatrix4 rot;
  398. rot = tb0 * IfcMatrix4::Rotation(delta,axis,rot) * tb1;
  399. size_t base = 0;
  400. std::vector<IfcVector3>& out = result.verts;
  401. // dummy data to simplify later processing
  402. for(size_t i = 0; i < size; ++i) {
  403. out.insert(out.end(),4,in[i]);
  404. }
  405. for(unsigned int seg = 0; seg < cnt_segments; ++seg) {
  406. for(size_t i = 0; i < size; ++i) {
  407. const size_t next = (i+1)%size;
  408. result.vertcnt.push_back(4);
  409. const IfcVector3& base_0 = out[base+i*4+3],base_1 = out[base+next*4+3];
  410. out.push_back(base_0);
  411. out.push_back(base_1);
  412. out.push_back(rot*base_1);
  413. out.push_back(rot*base_0);
  414. }
  415. base += size*4;
  416. }
  417. out.erase(out.begin(),out.begin()+size*4);
  418. if(has_area) {
  419. // leave the triangulation of the profile area to the ear cutting
  420. // implementation in aiProcess_Triangulate - for now we just
  421. // feed in two huge polygons.
  422. base -= size*8;
  423. for(size_t i = size; i--; ) {
  424. out.push_back(out[base+i*4+3]);
  425. }
  426. for(size_t i = 0; i < size; ++i ) {
  427. out.push_back(out[i*4]);
  428. }
  429. result.vertcnt.push_back(size);
  430. result.vertcnt.push_back(size);
  431. }
  432. IfcMatrix4 trafo;
  433. ConvertAxisPlacement(trafo, solid.Position);
  434. result.Transform(trafo);
  435. IFCImporter::LogDebug("generate mesh procedurally by radial extrusion (IfcRevolvedAreaSolid)");
  436. }
  437. // ------------------------------------------------------------------------------------------------
  438. void ProcessSweptDiskSolid(const IfcSweptDiskSolid solid, TempMesh& result, ConversionData& conv)
  439. {
  440. const Curve* const curve = Curve::Convert(*solid.Directrix, conv);
  441. if(!curve) {
  442. IFCImporter::LogError("failed to convert Directrix curve (IfcSweptDiskSolid)");
  443. return;
  444. }
  445. const std::vector<IfcVector3>& in = result.verts;
  446. const size_t size=in.size();
  447. const unsigned int cnt_segments = 16;
  448. const IfcFloat deltaAngle = AI_MATH_TWO_PI/cnt_segments;
  449. const size_t samples = curve->EstimateSampleCount(solid.StartParam,solid.EndParam);
  450. result.verts.reserve(cnt_segments * samples * 4);
  451. result.vertcnt.reserve((cnt_segments - 1) * samples);
  452. std::vector<IfcVector3> points;
  453. points.reserve(cnt_segments * samples);
  454. TempMesh temp;
  455. curve->SampleDiscrete(temp,solid.StartParam,solid.EndParam);
  456. const std::vector<IfcVector3>& curve_points = temp.verts;
  457. if(curve_points.empty()) {
  458. IFCImporter::LogWarn("curve evaluation yielded no points (IfcSweptDiskSolid)");
  459. return;
  460. }
  461. IfcVector3 current = curve_points[0];
  462. IfcVector3 previous = current;
  463. IfcVector3 next;
  464. IfcVector3 startvec;
  465. startvec.x = 1.0f;
  466. startvec.y = 1.0f;
  467. startvec.z = 1.0f;
  468. unsigned int last_dir = 0;
  469. // generate circles at the sweep positions
  470. for(size_t i = 0; i < samples; ++i) {
  471. if(i != samples - 1) {
  472. next = curve_points[i + 1];
  473. }
  474. // get a direction vector reflecting the approximate curvature (i.e. tangent)
  475. IfcVector3 d = (current-previous) + (next-previous);
  476. d.Normalize();
  477. // figure out an arbitrary point q so that (p-q) * d = 0,
  478. // try to maximize ||(p-q)|| * ||(p_last-q_last)||
  479. IfcVector3 q;
  480. bool take_any = false;
  481. for (unsigned int i = 0; i < 2; ++i, take_any = true) {
  482. if ((last_dir == 0 || take_any) && abs(d.x) > 1e-6) {
  483. q.y = startvec.y;
  484. q.z = startvec.z;
  485. q.x = -(d.y * q.y + d.z * q.z) / d.x;
  486. last_dir = 0;
  487. break;
  488. }
  489. else if ((last_dir == 1 || take_any) && abs(d.y) > 1e-6) {
  490. q.x = startvec.x;
  491. q.z = startvec.z;
  492. q.y = -(d.x * q.x + d.z * q.z) / d.y;
  493. last_dir = 1;
  494. break;
  495. }
  496. else if ((last_dir == 2 && abs(d.z) > 1e-6) || take_any) {
  497. q.y = startvec.y;
  498. q.x = startvec.x;
  499. q.z = -(d.y * q.y + d.x * q.x) / d.z;
  500. last_dir = 2;
  501. break;
  502. }
  503. }
  504. q *= solid.Radius / q.Length();
  505. startvec = q;
  506. // generate a rotation matrix to rotate q around d
  507. IfcMatrix4 rot;
  508. IfcMatrix4::Rotation(deltaAngle,d,rot);
  509. for (unsigned int seg = 0; seg < cnt_segments; ++seg, q *= rot ) {
  510. points.push_back(q + current);
  511. }
  512. previous = current;
  513. current = next;
  514. }
  515. // make quads
  516. for(size_t i = 0; i < samples - 1; ++i) {
  517. const aiVector3D& this_start = points[ i * cnt_segments ];
  518. // locate corresponding point on next sample ring
  519. unsigned int best_pair_offset = 0;
  520. float best_distance_squared = 1e10f;
  521. for (unsigned int seg = 0; seg < cnt_segments; ++seg) {
  522. const aiVector3D& p = points[ (i+1) * cnt_segments + seg];
  523. const float l = (p-this_start).SquareLength();
  524. if(l < best_distance_squared) {
  525. best_pair_offset = seg;
  526. best_distance_squared = l;
  527. }
  528. }
  529. for (unsigned int seg = 0; seg < cnt_segments; ++seg) {
  530. result.verts.push_back(points[ i * cnt_segments + (seg % cnt_segments)]);
  531. result.verts.push_back(points[ i * cnt_segments + (seg + 1) % cnt_segments]);
  532. result.verts.push_back(points[ (i+1) * cnt_segments + ((seg + 1 + best_pair_offset) % cnt_segments)]);
  533. result.verts.push_back(points[ (i+1) * cnt_segments + ((seg + best_pair_offset) % cnt_segments)]);
  534. IfcVector3& v1 = *(result.verts.end()-1);
  535. IfcVector3& v2 = *(result.verts.end()-2);
  536. IfcVector3& v3 = *(result.verts.end()-3);
  537. IfcVector3& v4 = *(result.verts.end()-4);
  538. if (((v4-v3) ^ (v4-v1)) * (v4 - curve_points[i]) < 0.0f) {
  539. std::swap(v4, v1);
  540. std::swap(v3, v2);
  541. }
  542. result.vertcnt.push_back(4);
  543. }
  544. }
  545. IFCImporter::LogDebug("generate mesh procedurally by sweeping a disk along a curve (IfcSweptDiskSolid)");
  546. }
  547. // ------------------------------------------------------------------------------------------------
  548. IfcMatrix3 DerivePlaneCoordinateSpace(const TempMesh& curmesh) {
  549. const std::vector<IfcVector3>& out = curmesh.verts;
  550. IfcMatrix3 m;
  551. const size_t s = out.size();
  552. assert(curmesh.vertcnt.size() == 1 && curmesh.vertcnt.back() == s);
  553. const IfcVector3 any_point = out[s-1];
  554. IfcVector3 nor;
  555. // The input polygon is arbitrarily shaped, so we might need some tries
  556. // until we find a suitable normal (and it does not even need to be
  557. // right in all cases, Newell's algorithm would be the correct one ... ).
  558. size_t base = s-curmesh.vertcnt.back(), i, j;
  559. for (i = base; i < s-1; ++i) {
  560. for (j = i+1; j < s; ++j) {
  561. nor = -((out[i]-any_point)^(out[j]-any_point));
  562. if(fabs(nor.Length()) > 1e-8f) {
  563. goto out;
  564. }
  565. }
  566. }
  567. assert(0);
  568. out:
  569. nor.Normalize();
  570. IfcVector3 r = (out[i]-any_point);
  571. r.Normalize();
  572. // reconstruct orthonormal basis
  573. IfcVector3 u = r ^ nor;
  574. u.Normalize();
  575. m.a1 = r.x;
  576. m.a2 = r.y;
  577. m.a3 = r.z;
  578. m.b1 = u.x;
  579. m.b2 = u.y;
  580. m.b3 = u.z;
  581. m.c1 = nor.x;
  582. m.c2 = nor.y;
  583. m.c3 = nor.z;
  584. return m;
  585. }
  586. // ------------------------------------------------------------------------------------------------
  587. bool TryAddOpenings_Poly2Tri(const std::vector<TempOpening>& openings,const std::vector<IfcVector3>& nors, TempMesh& curmesh)
  588. {
  589. std::vector<IfcVector3>& out = curmesh.verts;
  590. bool result = false;
  591. // Try to derive a solid base plane within the current surface for use as
  592. // working coordinate system.
  593. const IfcMatrix3& m = DerivePlaneCoordinateSpace(curmesh);
  594. const IfcMatrix3 minv = IfcMatrix3(m).Inverse();
  595. const IfcVector3& nor = IfcVector3(m.c1, m.c2, m.c3);
  596. IfcFloat coord = -1;
  597. std::vector<IfcVector2> contour_flat;
  598. contour_flat.reserve(out.size());
  599. IfcVector2 vmin, vmax;
  600. MinMaxChooser<IfcVector2>()(vmin, vmax);
  601. // Move all points into the new coordinate system, collecting min/max verts on the way
  602. BOOST_FOREACH(IfcVector3& x, out) {
  603. const IfcVector3 vv = m * x;
  604. // keep Z offset in the plane coordinate system. Ignoring precision issues
  605. // (which are present, of course), this should be the same value for
  606. // all polygon vertices (assuming the polygon is planar).
  607. // XXX this should be guarded, but we somehow need to pick a suitable
  608. // epsilon
  609. // if(coord != -1.0f) {
  610. // assert(fabs(coord - vv.z) < 1e-3f);
  611. // }
  612. coord = vv.z;
  613. vmin = std::min(IfcVector2(vv.x, vv.y), vmin);
  614. vmax = std::max(IfcVector2(vv.x, vv.y), vmax);
  615. contour_flat.push_back(IfcVector2(vv.x,vv.y));
  616. }
  617. // With the current code in DerivePlaneCoordinateSpace,
  618. // vmin,vmax should always be the 0...1 rectangle (+- numeric inaccuracies)
  619. // but here we won't rely on this.
  620. vmax -= vmin;
  621. // If this happens then the projection must have been wrong.
  622. assert(vmax.Length());
  623. ClipperLib::ExPolygons clipped;
  624. ClipperLib::Polygons holes_union;
  625. IfcVector3 wall_extrusion;
  626. bool do_connections = false, first = true;
  627. try {
  628. ClipperLib::Clipper clipper_holes;
  629. size_t c = 0;
  630. BOOST_FOREACH(const TempOpening& t,openings) {
  631. const IfcVector3& outernor = nors[c++];
  632. const IfcFloat dot = nor * outernor;
  633. if (fabs(dot)<1.f-1e-6f) {
  634. continue;
  635. }
  636. const std::vector<IfcVector3>& va = t.profileMesh->verts;
  637. if(va.size() <= 2) {
  638. continue;
  639. }
  640. std::vector<IfcVector2> contour;
  641. BOOST_FOREACH(const IfcVector3& xx, t.profileMesh->verts) {
  642. IfcVector3 vv = m * xx, vv_extr = m * (xx + t.extrusionDir);
  643. const bool is_extruded_side = fabs(vv.z - coord) > fabs(vv_extr.z - coord);
  644. if (first) {
  645. first = false;
  646. if (dot > 0.f) {
  647. do_connections = true;
  648. wall_extrusion = t.extrusionDir;
  649. if (is_extruded_side) {
  650. wall_extrusion = - wall_extrusion;
  651. }
  652. }
  653. }
  654. // XXX should not be necessary - but it is. Why? For precision reasons?
  655. vv = is_extruded_side ? vv_extr : vv;
  656. contour.push_back(IfcVector2(vv.x,vv.y));
  657. }
  658. ClipperLib::Polygon hole;
  659. BOOST_FOREACH(IfcVector2& pip, contour) {
  660. pip.x = (pip.x - vmin.x) / vmax.x;
  661. pip.y = (pip.y - vmin.y) / vmax.y;
  662. hole.push_back(ClipperLib::IntPoint( to_int64(pip.x), to_int64(pip.y) ));
  663. }
  664. if (!ClipperLib::Orientation(hole)) {
  665. std::reverse(hole.begin(), hole.end());
  666. // assert(ClipperLib::Orientation(hole));
  667. }
  668. /*ClipperLib::Polygons pol_temp(1), pol_temp2(1);
  669. pol_temp[0] = hole;
  670. ClipperLib::OffsetPolygons(pol_temp,pol_temp2,5.0);
  671. hole = pol_temp2[0];*/
  672. clipper_holes.AddPolygon(hole,ClipperLib::ptSubject);
  673. }
  674. clipper_holes.Execute(ClipperLib::ctUnion,holes_union,
  675. ClipperLib::pftNonZero,
  676. ClipperLib::pftNonZero);
  677. if (holes_union.empty()) {
  678. return false;
  679. }
  680. // Now that we have the big union of all holes, subtract it from the outer contour
  681. // to obtain the final polygon to feed into the triangulator.
  682. {
  683. ClipperLib::Polygon poly;
  684. BOOST_FOREACH(IfcVector2& pip, contour_flat) {
  685. pip.x = (pip.x - vmin.x) / vmax.x;
  686. pip.y = (pip.y - vmin.y) / vmax.y;
  687. poly.push_back(ClipperLib::IntPoint( to_int64(pip.x), to_int64(pip.y) ));
  688. }
  689. if (ClipperLib::Orientation(poly)) {
  690. std::reverse(poly.begin(), poly.end());
  691. }
  692. clipper_holes.Clear();
  693. clipper_holes.AddPolygon(poly,ClipperLib::ptSubject);
  694. clipper_holes.AddPolygons(holes_union,ClipperLib::ptClip);
  695. clipper_holes.Execute(ClipperLib::ctDifference,clipped,
  696. ClipperLib::pftNonZero,
  697. ClipperLib::pftNonZero);
  698. }
  699. }
  700. catch (const char* sx) {
  701. IFCImporter::LogError("Ifc: error during polygon clipping, skipping openings for this face: (Clipper: "
  702. + std::string(sx) + ")");
  703. return false;
  704. }
  705. std::vector<IfcVector3> old_verts;
  706. std::vector<unsigned int> old_vertcnt;
  707. old_verts.swap(curmesh.verts);
  708. old_vertcnt.swap(curmesh.vertcnt);
  709. // add connection geometry to close the adjacent 'holes' for the openings
  710. // this should only be done from one side of the wall or the polygons
  711. // would be emitted twice.
  712. if (false && do_connections) {
  713. std::vector<IfcVector3> tmpvec;
  714. BOOST_FOREACH(ClipperLib::Polygon& opening, holes_union) {
  715. assert(ClipperLib::Orientation(opening));
  716. tmpvec.clear();
  717. BOOST_FOREACH(ClipperLib::IntPoint& point, opening) {
  718. tmpvec.push_back( minv * IfcVector3(
  719. vmin.x + from_int64(point.X) * vmax.x,
  720. vmin.y + from_int64(point.Y) * vmax.y,
  721. coord));
  722. }
  723. for(size_t i = 0, size = tmpvec.size(); i < size; ++i) {
  724. const size_t next = (i+1)%size;
  725. curmesh.vertcnt.push_back(4);
  726. const IfcVector3& in_world = tmpvec[i];
  727. const IfcVector3& next_world = tmpvec[next];
  728. // Assumptions: no 'partial' openings, wall thickness roughly the same across the wall
  729. curmesh.verts.push_back(in_world);
  730. curmesh.verts.push_back(in_world+wall_extrusion);
  731. curmesh.verts.push_back(next_world+wall_extrusion);
  732. curmesh.verts.push_back(next_world);
  733. }
  734. }
  735. }
  736. std::vector< std::vector<p2t::Point*> > contours;
  737. BOOST_FOREACH(ClipperLib::ExPolygon& clip, clipped) {
  738. contours.clear();
  739. // Build the outer polygon contour line for feeding into poly2tri
  740. std::vector<p2t::Point*> contour_points;
  741. BOOST_FOREACH(ClipperLib::IntPoint& point, clip.outer) {
  742. contour_points.push_back( new p2t::Point(from_int64(point.X), from_int64(point.Y)) );
  743. }
  744. p2t::CDT* cdt ;
  745. try {
  746. // Note: this relies on custom modifications in poly2tri to raise runtime_error's
  747. // instead if assertions. These failures are not debug only, they can actually
  748. // happen in production use if the input data is broken. An assertion would be
  749. // inappropriate.
  750. cdt = new p2t::CDT(contour_points);
  751. }
  752. catch(const std::exception& e) {
  753. IFCImporter::LogError("Ifc: error during polygon triangulation, skipping some openings: (poly2tri: "
  754. + std::string(e.what()) + ")");
  755. continue;
  756. }
  757. // Build the poly2tri inner contours for all holes we got from ClipperLib
  758. BOOST_FOREACH(ClipperLib::Polygon& opening, clip.holes) {
  759. contours.push_back(std::vector<p2t::Point*>());
  760. std::vector<p2t::Point*>& contour = contours.back();
  761. BOOST_FOREACH(ClipperLib::IntPoint& point, opening) {
  762. contour.push_back( new p2t::Point(from_int64(point.X), from_int64(point.Y)) );
  763. }
  764. cdt->AddHole(contour);
  765. }
  766. try {
  767. // Note: See above
  768. cdt->Triangulate();
  769. }
  770. catch(const std::exception& e) {
  771. IFCImporter::LogError("Ifc: error during polygon triangulation, skipping some openings: (poly2tri: "
  772. + std::string(e.what()) + ")");
  773. continue;
  774. }
  775. const std::vector<p2t::Triangle*>& tris = cdt->GetTriangles();
  776. // Collect the triangles we just produced
  777. BOOST_FOREACH(p2t::Triangle* tri, tris) {
  778. for(int i = 0; i < 3; ++i) {
  779. const IfcVector2& v = IfcVector2(
  780. static_cast<IfcFloat>( tri->GetPoint(i)->x ),
  781. static_cast<IfcFloat>( tri->GetPoint(i)->y )
  782. );
  783. assert(v.x <= 1.0 && v.x >= 0.0 && v.y <= 1.0 && v.y >= 0.0);
  784. const IfcVector3 v3 = minv * IfcVector3(vmin.x + v.x * vmax.x, vmin.y + v.y * vmax.y,coord) ;
  785. curmesh.verts.push_back(v3);
  786. }
  787. curmesh.vertcnt.push_back(3);
  788. }
  789. result = true;
  790. }
  791. if (!result) {
  792. // revert -- it's a shame, but better than nothing
  793. curmesh.verts.insert(curmesh.verts.end(),old_verts.begin(), old_verts.end());
  794. curmesh.vertcnt.insert(curmesh.vertcnt.end(),old_vertcnt.begin(), old_vertcnt.end());
  795. IFCImporter::LogError("Ifc: revert, could not generate openings for this wall");
  796. }
  797. return result;
  798. }
  799. // ------------------------------------------------------------------------------------------------
  800. struct DistanceSorter {
  801. DistanceSorter(const IfcVector3& base) : base(base) {}
  802. bool operator () (const TempOpening& a, const TempOpening& b) const {
  803. return (a.profileMesh->Center()-base).SquareLength() < (b.profileMesh->Center()-base).SquareLength();
  804. }
  805. IfcVector3 base;
  806. };
  807. // ------------------------------------------------------------------------------------------------
  808. struct XYSorter {
  809. // sort first by X coordinates, then by Y coordinates
  810. bool operator () (const IfcVector2&a, const IfcVector2& b) const {
  811. if (a.x == b.x) {
  812. return a.y < b.y;
  813. }
  814. return a.x < b.x;
  815. }
  816. };
  817. typedef std::pair< IfcVector2, IfcVector2 > BoundingBox;
  818. typedef std::map<IfcVector2,size_t,XYSorter> XYSortedField;
  819. // ------------------------------------------------------------------------------------------------
  820. void QuadrifyPart(const IfcVector2& pmin, const IfcVector2& pmax, XYSortedField& field,
  821. const std::vector< BoundingBox >& bbs,
  822. std::vector<IfcVector2>& out)
  823. {
  824. if (!(pmin.x-pmax.x) || !(pmin.y-pmax.y)) {
  825. return;
  826. }
  827. IfcFloat xs = 1e10, xe = 1e10;
  828. bool found = false;
  829. // Search along the x-axis until we find an opening
  830. XYSortedField::iterator start = field.begin();
  831. for(; start != field.end(); ++start) {
  832. const BoundingBox& bb = bbs[(*start).second];
  833. if(bb.first.x >= pmax.x) {
  834. break;
  835. }
  836. if (bb.second.x > pmin.x && bb.second.y > pmin.y && bb.first.y < pmax.y) {
  837. xs = bb.first.x;
  838. xe = bb.second.x;
  839. found = true;
  840. break;
  841. }
  842. }
  843. if (!found) {
  844. // the rectangle [pmin,pend] is opaque, fill it
  845. out.push_back(pmin);
  846. out.push_back(IfcVector2(pmin.x,pmax.y));
  847. out.push_back(pmax);
  848. out.push_back(IfcVector2(pmax.x,pmin.y));
  849. return;
  850. }
  851. xs = std::max(pmin.x,xs);
  852. xe = std::min(pmax.x,xe);
  853. // see if there's an offset to fill at the top of our quad
  854. if (xs - pmin.x) {
  855. out.push_back(pmin);
  856. out.push_back(IfcVector2(pmin.x,pmax.y));
  857. out.push_back(IfcVector2(xs,pmax.y));
  858. out.push_back(IfcVector2(xs,pmin.y));
  859. }
  860. // search along the y-axis for all openings that overlap xs and our quad
  861. IfcFloat ylast = pmin.y;
  862. found = false;
  863. for(; start != field.end(); ++start) {
  864. const BoundingBox& bb = bbs[(*start).second];
  865. if (bb.first.x > xs || bb.first.y >= pmax.y) {
  866. break;
  867. }
  868. if (bb.second.y > ylast) {
  869. found = true;
  870. const IfcFloat ys = std::max(bb.first.y,pmin.y), ye = std::min(bb.second.y,pmax.y);
  871. if (ys - ylast > 0.0f) {
  872. QuadrifyPart( IfcVector2(xs,ylast), IfcVector2(xe,ys) ,field,bbs,out);
  873. }
  874. // the following are the window vertices
  875. /*wnd.push_back(IfcVector2(xs,ys));
  876. wnd.push_back(IfcVector2(xs,ye));
  877. wnd.push_back(IfcVector2(xe,ye));
  878. wnd.push_back(IfcVector2(xe,ys));*/
  879. ylast = ye;
  880. }
  881. }
  882. if (!found) {
  883. // the rectangle [pmin,pend] is opaque, fill it
  884. out.push_back(IfcVector2(xs,pmin.y));
  885. out.push_back(IfcVector2(xs,pmax.y));
  886. out.push_back(IfcVector2(xe,pmax.y));
  887. out.push_back(IfcVector2(xe,pmin.y));
  888. return;
  889. }
  890. if (ylast < pmax.y) {
  891. QuadrifyPart( IfcVector2(xs,ylast), IfcVector2(xe,pmax.y) ,field,bbs,out);
  892. }
  893. // now for the whole rest
  894. if (pmax.x-xe) {
  895. QuadrifyPart(IfcVector2(xe,pmin.y), pmax ,field,bbs,out);
  896. }
  897. }
  898. // ------------------------------------------------------------------------------------------------
  899. void InsertWindowContours(const std::vector< BoundingBox >& bbs,
  900. const std::vector< std::vector<IfcVector2> >& contours,
  901. const std::vector<TempOpening>& openings,
  902. const IfcMatrix3& minv,
  903. const IfcVector2& scale,
  904. const IfcVector2& offset,
  905. IfcFloat coord,
  906. TempMesh& curmesh)
  907. {
  908. ai_assert(contours.size() == bbs.size());
  909. // fix windows - we need to insert the real, polygonal shapes into the quadratic holes that we have now
  910. for(size_t i = 0; i < contours.size();++i) {
  911. const BoundingBox& bb = bbs[i];
  912. const std::vector<IfcVector2>& contour = contours[i];
  913. // check if we need to do it at all - many windows just fit perfectly into their quadratic holes,
  914. // i.e. their contours *are* already their bounding boxes.
  915. if (contour.size() == 4) {
  916. std::set<IfcVector2,XYSorter> verts;
  917. for(size_t n = 0; n < 4; ++n) {
  918. verts.insert(contour[n]);
  919. }
  920. const std::set<IfcVector2,XYSorter>::const_iterator end = verts.end();
  921. if (verts.find(bb.first)!=end && verts.find(bb.second)!=end
  922. && verts.find(IfcVector2(bb.first.x,bb.second.y))!=end
  923. && verts.find(IfcVector2(bb.second.x,bb.first.y))!=end
  924. ) {
  925. continue;
  926. }
  927. }
  928. const IfcFloat diag = (bb.first-bb.second).Length();
  929. const IfcFloat epsilon = diag/1000.f;
  930. // walk through all contour points and find those that lie on the BB corner
  931. size_t last_hit = -1, very_first_hit = -1;
  932. IfcVector2 edge;
  933. for(size_t n = 0, e=0, size = contour.size();; n=(n+1)%size, ++e) {
  934. // sanity checking
  935. if (e == size*2) {
  936. IFCImporter::LogError("encountered unexpected topology while generating window contour");
  937. break;
  938. }
  939. const IfcVector2& v = contour[n];
  940. bool hit = false;
  941. if (fabs(v.x-bb.first.x)<epsilon) {
  942. edge.x = bb.first.x;
  943. hit = true;
  944. }
  945. else if (fabs(v.x-bb.second.x)<epsilon) {
  946. edge.x = bb.second.x;
  947. hit = true;
  948. }
  949. if (fabs(v.y-bb.first.y)<epsilon) {
  950. edge.y = bb.first.y;
  951. hit = true;
  952. }
  953. else if (fabs(v.y-bb.second.y)<epsilon) {
  954. edge.y = bb.second.y;
  955. hit = true;
  956. }
  957. if (hit) {
  958. if (last_hit != (size_t)-1) {
  959. const size_t old = curmesh.verts.size();
  960. size_t cnt = last_hit > n ? size-(last_hit-n) : n-last_hit;
  961. for(size_t a = last_hit, e = 0; e <= cnt; a=(a+1)%size, ++e) {
  962. // hack: this is to fix cases where opening contours are self-intersecting.
  963. // Clipper doesn't produce such polygons, but as soon as we're back in
  964. // our brave new floating-point world, very small distances are consumed
  965. // by the maximum available precision, leading to self-intersecting
  966. // polygons. This fix makes concave windows fail even worse, but
  967. // anyway, fail is fail.
  968. if ((contour[a] - edge).SquareLength() > diag*diag*0.7) {
  969. continue;
  970. }
  971. const IfcVector3 v3 = minv * IfcVector3(offset.x + contour[a].x * scale.x, offset.y + contour[a].y * scale.y, coord);
  972. curmesh.verts.push_back(v3);
  973. }
  974. if (edge != contour[last_hit]) {
  975. IfcVector2 corner = edge;
  976. if (fabs(contour[last_hit].x-bb.first.x)<epsilon) {
  977. corner.x = bb.first.x;
  978. }
  979. else if (fabs(contour[last_hit].x-bb.second.x)<epsilon) {
  980. corner.x = bb.second.x;
  981. }
  982. if (fabs(contour[last_hit].y-bb.first.y)<epsilon) {
  983. corner.y = bb.first.y;
  984. }
  985. else if (fabs(contour[last_hit].y-bb.second.y)<epsilon) {
  986. corner.y = bb.second.y;
  987. }
  988. const IfcVector3 v3 = minv * IfcVector3(offset.x + corner.x * scale.x, offset.y + corner.y * scale.y,coord);
  989. curmesh.verts.push_back(v3);
  990. }
  991. else if (cnt == 1) {
  992. // avoid degenerate polygons (also known as lines or points)
  993. curmesh.verts.erase(curmesh.verts.begin()+old,curmesh.verts.end());
  994. }
  995. if (const size_t d = curmesh.verts.size()-old) {
  996. curmesh.vertcnt.push_back(d);
  997. std::reverse(curmesh.verts.rbegin(),curmesh.verts.rbegin()+d);
  998. }
  999. if (n == very_first_hit) {
  1000. break;
  1001. }
  1002. }
  1003. else {
  1004. very_first_hit = n;
  1005. }
  1006. last_hit = n;
  1007. }
  1008. }
  1009. }
  1010. }
  1011. // ------------------------------------------------------------------------------------------------
  1012. void MergeWindowContours (const std::vector<IfcVector2>& a,
  1013. const std::vector<IfcVector2>& b,
  1014. ClipperLib::ExPolygons& out)
  1015. {
  1016. ClipperLib::Clipper clipper;
  1017. ClipperLib::Polygon clip;
  1018. BOOST_FOREACH(const IfcVector2& pip, a) {
  1019. clip.push_back(ClipperLib::IntPoint( to_int64(pip.x), to_int64(pip.y) ));
  1020. }
  1021. if (ClipperLib::Orientation(clip)) {
  1022. std::reverse(clip.begin(), clip.end());
  1023. }
  1024. clipper.AddPolygon(clip, ClipperLib::ptSubject);
  1025. clip.clear();
  1026. BOOST_FOREACH(const IfcVector2& pip, b) {
  1027. clip.push_back(ClipperLib::IntPoint( to_int64(pip.x), to_int64(pip.y) ));
  1028. }
  1029. if (ClipperLib::Orientation(clip)) {
  1030. std::reverse(clip.begin(), clip.end());
  1031. }
  1032. clipper.AddPolygon(clip, ClipperLib::ptSubject);
  1033. clipper.Execute(ClipperLib::ctUnion, out,ClipperLib::pftNonZero,ClipperLib::pftNonZero);
  1034. }
  1035. // ------------------------------------------------------------------------------------------------
  1036. void CleanupWindowContours(std::vector< std::vector<IfcVector2> >& contours)
  1037. {
  1038. std::vector<IfcVector2> scratch;
  1039. // use polyclipper to clean up window contours as well
  1040. try {
  1041. BOOST_FOREACH(std::vector<IfcVector2>& contour, contours) {
  1042. ClipperLib::Polygon subject;
  1043. ClipperLib::Clipper clipper;
  1044. ClipperLib::ExPolygons clipped;
  1045. BOOST_FOREACH(const IfcVector2& pip, contour) {
  1046. subject.push_back(ClipperLib::IntPoint( to_int64(pip.x), to_int64(pip.y) ));
  1047. }
  1048. clipper.AddPolygon(subject,ClipperLib::ptSubject);
  1049. clipper.Execute(ClipperLib::ctUnion,clipped,ClipperLib::pftNonZero,ClipperLib::pftNonZero);
  1050. // this should yield only one polygon or something went wrong
  1051. if (clipped.size() != 1) {
  1052. // empty polygon? drop the contour altogether
  1053. if(clipped.empty()) {
  1054. contour.clear();
  1055. continue;
  1056. }
  1057. // else: take only the first ...
  1058. IFCImporter::LogError("error during polygon clipping, window contour is not convex");
  1059. }
  1060. scratch.clear();
  1061. BOOST_FOREACH(const ClipperLib::IntPoint& point, clipped[0].outer) {
  1062. scratch.push_back( IfcVector2(from_int64(point.X), from_int64(point.Y)));
  1063. }
  1064. contour.swap(scratch);
  1065. }
  1066. }
  1067. catch (const char* sx) {
  1068. IFCImporter::LogError("error during polygon clipping, window shape may be wrong: (Clipper: "
  1069. + std::string(sx) + ")");
  1070. }
  1071. }
  1072. // ------------------------------------------------------------------------------------------------
  1073. void CleanupOuterContour(const std::vector<IfcVector2>& contour_flat, TempMesh& curmesh,
  1074. const IfcMatrix3& minv,
  1075. const IfcVector2& scale,
  1076. const IfcVector2& offset,
  1077. IfcFloat coord,
  1078. const std::vector<IfcVector2>& outflat)
  1079. {
  1080. std::vector<IfcVector3> vold;
  1081. std::vector<unsigned int> iold;
  1082. vold.reserve(outflat.size());
  1083. iold.reserve(outflat.size() / 4);
  1084. // Fix the outer contour using polyclipper
  1085. try {
  1086. ClipperLib::Polygon subject;
  1087. ClipperLib::Clipper clipper;
  1088. ClipperLib::ExPolygons clipped;
  1089. ClipperLib::Polygon clip;
  1090. clip.reserve(contour_flat.size());
  1091. BOOST_FOREACH(const IfcVector2& pip, contour_flat) {
  1092. clip.push_back(ClipperLib::IntPoint( to_int64(pip.x), to_int64(pip.y) ));
  1093. }
  1094. if (!ClipperLib::Orientation(clip)) {
  1095. std::reverse(clip.begin(), clip.end());
  1096. }
  1097. // We need to run polyclipper on every single quad -- we can't run it one all
  1098. // of them at once or it would merge them all together which would undo all
  1099. // previous steps
  1100. subject.reserve(4);
  1101. size_t cnt = 0;
  1102. BOOST_FOREACH(const IfcVector2& pip, outflat) {
  1103. subject.push_back(ClipperLib::IntPoint( to_int64(pip.x), to_int64(pip.y) ));
  1104. if (!(++cnt % 4)) {
  1105. if (!ClipperLib::Orientation(subject)) {
  1106. std::reverse(subject.begin(), subject.end());
  1107. }
  1108. clipper.AddPolygon(subject,ClipperLib::ptSubject);
  1109. clipper.AddPolygon(clip,ClipperLib::ptClip);
  1110. clipper.Execute(ClipperLib::ctIntersection,clipped,ClipperLib::pftNonZero,ClipperLib::pftNonZero);
  1111. BOOST_FOREACH(const ClipperLib::ExPolygon& ex, clipped) {
  1112. iold.push_back(ex.outer.size());
  1113. BOOST_FOREACH(const ClipperLib::IntPoint& point, ex.outer) {
  1114. vold.push_back( minv * IfcVector3(
  1115. offset.x + from_int64(point.X) * scale.x,
  1116. offset.y + from_int64(point.Y) * scale.y,
  1117. coord));
  1118. }
  1119. }
  1120. subject.clear();
  1121. clipped.clear();
  1122. clipper.Clear();
  1123. }
  1124. }
  1125. assert(!(cnt % 4));
  1126. }
  1127. catch (const char* sx) {
  1128. IFCImporter::LogError("Ifc: error during polygon clipping, wall contour line may be wrong: (Clipper: "
  1129. + std::string(sx) + ")");
  1130. iold.resize(outflat.size()/4,4);
  1131. BOOST_FOREACH(const IfcVector2& vproj, outflat) {
  1132. const IfcVector3 v3 = minv * IfcVector3(offset.x + vproj.x * scale.x, offset.y + vproj.y * scale.y,coord);
  1133. vold.push_back(v3);
  1134. }
  1135. }
  1136. // undo the projection, generate output quads
  1137. std::swap(vold,curmesh.verts);
  1138. std::swap(iold,curmesh.vertcnt);
  1139. }
  1140. // ------------------------------------------------------------------------------------------------
  1141. bool TryAddOpenings_Quadrulate(const std::vector<TempOpening>& openings,
  1142. const std::vector<IfcVector3>& nors,
  1143. TempMesh& curmesh)
  1144. {
  1145. std::vector<IfcVector3>& out = curmesh.verts;
  1146. const IfcVector2 one_vec = IfcVector2(static_cast<IfcFloat>(1.0),static_cast<IfcFloat>(1.0));
  1147. // Try to derive a solid base plane within the current surface for use as
  1148. // working coordinate system.
  1149. const IfcMatrix3& m = DerivePlaneCoordinateSpace(curmesh);
  1150. const IfcMatrix3& minv = IfcMatrix3(m).Inverse();
  1151. const IfcVector3& nor = IfcVector3(m.c1, m.c2, m.c3);
  1152. IfcFloat coord = -1;
  1153. std::vector<IfcVector2> contour_flat;
  1154. contour_flat.reserve(out.size());
  1155. IfcVector2 vmin, vmax;
  1156. MinMaxChooser<IfcVector2>()(vmin, vmax);
  1157. // Move all points into the new coordinate system, collecting min/max verts on the way
  1158. BOOST_FOREACH(IfcVector3& x, out) {
  1159. const IfcVector3& vv = m * x;
  1160. // keep Z offset in the plane coordinate system. Ignoring precision issues
  1161. // (which are present, of course), this should be the same value for
  1162. // all polygon vertices (assuming the polygon is planar).
  1163. // XXX this should be guarded, but we somehow need to pick a suitable
  1164. // epsilon
  1165. // if(coord != -1.0f) {
  1166. // assert(fabs(coord - vv.z) < 1e-3f);
  1167. // }
  1168. coord = vv.z;
  1169. vmin = std::min(IfcVector2(vv.x, vv.y), vmin);
  1170. vmax = std::max(IfcVector2(vv.x, vv.y), vmax);
  1171. contour_flat.push_back(IfcVector2(vv.x,vv.y));
  1172. }
  1173. // With the current code in DerivePlaneCoordinateSpace,
  1174. // vmin,vmax should always be the 0...1 rectangle (+- numeric inaccuracies)
  1175. // but here we really need this to be accurate, so normalize again.
  1176. vmax -= vmin;
  1177. BOOST_FOREACH(IfcVector2& vv, contour_flat) {
  1178. vv.x = (vv.x - vmin.x) / vmax.x;
  1179. vv.y = (vv.y - vmin.y) / vmax.y;
  1180. // sanity rounding
  1181. vv = std::max(vv,IfcVector2());
  1182. vv = std::min(vv,one_vec);
  1183. }
  1184. // project all openings into the coordinate system defined by the p+sv*tu plane
  1185. // and compute bounding boxes for them
  1186. std::vector< BoundingBox > bbs;
  1187. std::vector< std::vector<IfcVector2> > contours;
  1188. size_t c = 0;
  1189. BOOST_FOREACH(const TempOpening& t,openings) {
  1190. std::vector<IfcVector3> profile_verts = t.profileMesh->verts;
  1191. std::vector<unsigned int> profile_vertcnts = t.profileMesh->vertcnt;
  1192. if(profile_verts.size() <= 2) {
  1193. continue;
  1194. }
  1195. IfcVector2 vpmin,vpmax;
  1196. MinMaxChooser<IfcVector2>()(vpmin,vpmax);
  1197. // the opening meshes are real 3D meshes so skip over all faces
  1198. // clearly facing into the wrong direction.
  1199. std::vector<IfcVector2> contour;
  1200. for (size_t f = 0, vi_total = 0, fend = profile_vertcnts.size(); f < fend; ++f) {
  1201. const IfcVector3& face_nor = ((profile_verts[vi_total+2] - profile_verts[vi_total]) ^
  1202. (profile_verts[vi_total+1] - profile_verts[vi_total])).Normalize();
  1203. const IfcFloat abs_dot_face_nor = abs(nor * face_nor);
  1204. if (abs_dot_face_nor < 0.5) {
  1205. vi_total += profile_vertcnts[f];
  1206. continue;
  1207. }
  1208. for (unsigned int vi = 0, vend = profile_vertcnts[f]; vi < vend; ++vi, ++vi_total) {
  1209. const IfcVector3& x = profile_verts[vi_total];
  1210. const IfcVector3& v = m * x;
  1211. IfcVector2 vv(v.x, v.y);
  1212. // rescale
  1213. vv.x = (vv.x - vmin.x) / vmax.x;
  1214. vv.y = (vv.y - vmin.y) / vmax.y;
  1215. vv = std::max(vv,IfcVector2());
  1216. vv = std::min(vv,one_vec);
  1217. vpmin = std::min(vpmin,vv);
  1218. vpmax = std::max(vpmax,vv);
  1219. contour.push_back(vv);
  1220. }
  1221. }
  1222. if(contour.size() <= 2) {
  1223. continue;
  1224. }
  1225. BoundingBox bb = BoundingBox(vpmin,vpmax);
  1226. // see if this BB intersects any other, in which case we could not use the Quadrify()
  1227. // algorithm and would revert to Poly2Tri only.
  1228. for (std::vector<BoundingBox>::iterator it = bbs.begin(); it != bbs.end();) {
  1229. const BoundingBox& ibb = *it;
  1230. if (ibb.first.x < bb.second.x && ibb.second.x > bb.first.x &&
  1231. ibb.first.y < bb.second.y && ibb.second.y > bb.second.x) {
  1232. // take these two contours and try to merge them. If they overlap (which
  1233. // should not happen, but in fact happens-in-the-real-world [tm] ),
  1234. // resume using a single contour and a single bounding box.
  1235. const std::vector<IfcVector2>& other = contours[std::distance(bbs.begin(),it)];
  1236. ClipperLib::ExPolygons poly;
  1237. MergeWindowContours(contour, other, poly);
  1238. if (poly.size() > 1) {
  1239. IFCImporter::LogWarn("cannot use quadrify algorithm to generate wall openings due to "
  1240. "bounding box overlaps, using poly2tri fallback method");
  1241. return TryAddOpenings_Poly2Tri(openings, nors, curmesh);
  1242. }
  1243. else if (poly.size() == 0) {
  1244. IFCImporter::LogWarn("ignoring duplicate opening");
  1245. contour.clear();
  1246. break;
  1247. }
  1248. else {
  1249. IFCImporter::LogDebug("merging overlapping openings, this should not happen");
  1250. contour.clear();
  1251. BOOST_FOREACH(const ClipperLib::IntPoint& point, poly[0].outer) {
  1252. IfcVector2 vv = IfcVector2( from_int64(point.X), from_int64(point.Y));
  1253. vv = std::max(vv,IfcVector2());
  1254. vv = std::min(vv,one_vec);
  1255. contour.push_back( vv );
  1256. }
  1257. bb.first = std::min(bb.first, ibb.first);
  1258. bb.second = std::max(bb.second, ibb.second);
  1259. contours.erase(contours.begin() + std::distance(bbs.begin(),it));
  1260. it = bbs.erase(it);
  1261. continue;
  1262. }
  1263. }
  1264. ++it;
  1265. }
  1266. if(!contour.empty()) {
  1267. contours.push_back(contour);
  1268. bbs.push_back(bb);
  1269. }
  1270. }
  1271. if (bbs.empty()) {
  1272. return false;
  1273. }
  1274. XYSortedField field;
  1275. for (std::vector<BoundingBox>::iterator it = bbs.begin(); it != bbs.end(); ++it) {
  1276. if (field.find((*it).first) != field.end()) {
  1277. IFCImporter::LogWarn("constraint failure during generation of wall openings, results may be faulty");
  1278. }
  1279. field[(*it).first] = std::distance(bbs.begin(),it);
  1280. }
  1281. std::vector<IfcVector2> outflat;
  1282. outflat.reserve(openings.size()*4);
  1283. QuadrifyPart(IfcVector2(0.f,0.f),IfcVector2(1.f,1.f),field,bbs,outflat);
  1284. ai_assert(!(outflat.size() % 4));
  1285. CleanupOuterContour(contour_flat, curmesh, minv, vmax, vmin, coord, outflat);
  1286. CleanupWindowContours(contours);
  1287. InsertWindowContours(bbs,contours,openings, minv,vmax, vmin, coord, curmesh);
  1288. return true;
  1289. }
  1290. // ------------------------------------------------------------------------------------------------
  1291. void ProcessExtrudedAreaSolid(const IfcExtrudedAreaSolid& solid, TempMesh& result,
  1292. ConversionData& conv)
  1293. {
  1294. TempMesh meshout;
  1295. // First read the profile description
  1296. if(!ProcessProfile(*solid.SweptArea,meshout,conv) || meshout.verts.size()<=1) {
  1297. return;
  1298. }
  1299. IfcVector3 dir;
  1300. ConvertDirection(dir,solid.ExtrudedDirection);
  1301. dir *= solid.Depth;
  1302. // Outline: assuming that `meshout.verts` is now a list of vertex points forming
  1303. // the underlying profile, extrude along the given axis, forming new
  1304. // triangles.
  1305. std::vector<IfcVector3>& in = meshout.verts;
  1306. const size_t size=in.size();
  1307. const bool has_area = solid.SweptArea->ProfileType == "AREA" && size>2;
  1308. if(solid.Depth < 1e-3) {
  1309. if(has_area) {
  1310. meshout = result;
  1311. }
  1312. return;
  1313. }
  1314. result.verts.reserve(size*(has_area?4:2));
  1315. result.vertcnt.reserve(meshout.vertcnt.size()+2);
  1316. // First step: transform all vertices into the target coordinate space
  1317. IfcMatrix4 trafo;
  1318. ConvertAxisPlacement(trafo, solid.Position);
  1319. BOOST_FOREACH(IfcVector3& v,in) {
  1320. v *= trafo;
  1321. }
  1322. IfcVector3 min = in[0];
  1323. dir *= IfcMatrix3(trafo);
  1324. std::vector<IfcVector3> nors;
  1325. const bool openings = !!conv.apply_openings && conv.apply_openings->size();
  1326. // Compute the normal vectors for all opening polygons as a prerequisite
  1327. // to TryAddOpenings_Poly2Tri()
  1328. // XXX this belongs into the aforementioned function
  1329. if (openings) {
  1330. if (!conv.settings.useCustomTriangulation) {
  1331. // it is essential to apply the openings in the correct spatial order. The direction
  1332. // doesn't matter, but we would screw up if we started with e.g. a door in between
  1333. // two windows.
  1334. std::sort(conv.apply_openings->begin(),conv.apply_openings->end(),
  1335. DistanceSorter(min));
  1336. }
  1337. nors.reserve(conv.apply_openings->size());
  1338. BOOST_FOREACH(TempOpening& t,*conv.apply_openings) {
  1339. TempMesh& bounds = *t.profileMesh.get();
  1340. if (bounds.verts.size() <= 2) {
  1341. nors.push_back(IfcVector3());
  1342. continue;
  1343. }
  1344. nors.push_back(((bounds.verts[2]-bounds.verts[0])^(bounds.verts[1]-bounds.verts[0]) ).Normalize());
  1345. }
  1346. }
  1347. TempMesh temp;
  1348. TempMesh& curmesh = openings ? temp : result;
  1349. std::vector<IfcVector3>& out = curmesh.verts;
  1350. size_t sides_with_openings = 0;
  1351. for(size_t i = 0; i < size; ++i) {
  1352. const size_t next = (i+1)%size;
  1353. curmesh.vertcnt.push_back(4);
  1354. out.push_back(in[i]);
  1355. out.push_back(in[i]+dir);
  1356. out.push_back(in[next]+dir);
  1357. out.push_back(in[next]);
  1358. if(openings) {
  1359. if(TryAddOpenings_Quadrulate(*conv.apply_openings,nors,temp)) {
  1360. ++sides_with_openings;
  1361. }
  1362. result.Append(temp);
  1363. temp.Clear();
  1364. }
  1365. }
  1366. size_t sides_with_v_openings = 0;
  1367. if(has_area) {
  1368. for(size_t n = 0; n < 2; ++n) {
  1369. for(size_t i = size; i--; ) {
  1370. out.push_back(in[i]+(n?dir:IfcVector3()));
  1371. }
  1372. curmesh.vertcnt.push_back(size);
  1373. if(openings && size > 2) {
  1374. if(TryAddOpenings_Quadrulate(*conv.apply_openings,nors,temp)) {
  1375. ++sides_with_v_openings;
  1376. }
  1377. result.Append(temp);
  1378. temp.Clear();
  1379. }
  1380. }
  1381. }
  1382. if(openings && ((sides_with_openings != 2 && sides_with_openings) || (sides_with_v_openings != 2 && sides_with_v_openings))) {
  1383. IFCImporter::LogWarn("failed to resolve all openings, presumably their topology is not supported by Assimp");
  1384. }
  1385. IFCImporter::LogDebug("generate mesh procedurally by extrusion (IfcExtrudedAreaSolid)");
  1386. }
  1387. // ------------------------------------------------------------------------------------------------
  1388. void ProcessSweptAreaSolid(const IfcSweptAreaSolid& swept, TempMesh& meshout,
  1389. ConversionData& conv)
  1390. {
  1391. if(const IfcExtrudedAreaSolid* const solid = swept.ToPtr<IfcExtrudedAreaSolid>()) {
  1392. // Do we just collect openings for a parent element (i.e. a wall)?
  1393. // In this case we don't extrude the surface yet, just keep the profile and transform it correctly
  1394. if(conv.collect_openings) {
  1395. boost::shared_ptr<TempMesh> meshtmp(new TempMesh());
  1396. ProcessExtrudedAreaSolid(*solid,*meshtmp,conv);
  1397. /*
  1398. ProcessProfile(swept.SweptArea,*meshtmp,conv);
  1399. IfcMatrix4 m;
  1400. ConvertAxisPlacement(m,solid->Position);
  1401. meshtmp->Transform(m);
  1402. IfcVector3 dir;
  1403. ConvertDirection(dir,solid->ExtrudedDirection); */
  1404. conv.collect_openings->push_back(TempOpening(solid,IfcVector3(0,0,0)
  1405. /* IfcMatrix3(m) * (dir*static_cast<IfcFloat>(solid->Depth)) */,meshtmp));
  1406. return;
  1407. }
  1408. ProcessExtrudedAreaSolid(*solid,meshout,conv);
  1409. }
  1410. else if(const IfcRevolvedAreaSolid* const rev = swept.ToPtr<IfcRevolvedAreaSolid>()) {
  1411. ProcessRevolvedAreaSolid(*rev,meshout,conv);
  1412. }
  1413. else {
  1414. IFCImporter::LogWarn("skipping unknown IfcSweptAreaSolid entity, type is " + swept.GetClassName());
  1415. }
  1416. }
  1417. // ------------------------------------------------------------------------------------------------
  1418. enum Intersect {
  1419. Intersect_No,
  1420. Intersect_LiesOnPlane,
  1421. Intersect_Yes
  1422. };
  1423. // ------------------------------------------------------------------------------------------------
  1424. Intersect IntersectSegmentPlane(const IfcVector3& p,const IfcVector3& n, const IfcVector3& e0,
  1425. const IfcVector3& e1,
  1426. IfcVector3& out)
  1427. {
  1428. const IfcVector3 pdelta = e0 - p, seg = e1-e0;
  1429. const IfcFloat dotOne = n*seg, dotTwo = -(n*pdelta);
  1430. if (fabs(dotOne) < 1e-6) {
  1431. return fabs(dotTwo) < 1e-6f ? Intersect_LiesOnPlane : Intersect_No;
  1432. }
  1433. const IfcFloat t = dotTwo/dotOne;
  1434. // t must be in [0..1] if the intersection point is within the given segment
  1435. if (t > 1.f || t < 0.f) {
  1436. return Intersect_No;
  1437. }
  1438. out = e0+t*seg;
  1439. return Intersect_Yes;
  1440. }
  1441. // ------------------------------------------------------------------------------------------------
  1442. void ProcessBoolean(const IfcBooleanResult& boolean, TempMesh& result, ConversionData& conv)
  1443. {
  1444. if(const IfcBooleanResult* const clip = boolean.ToPtr<IfcBooleanResult>()) {
  1445. if(clip->Operator != "DIFFERENCE") {
  1446. IFCImporter::LogWarn("encountered unsupported boolean operator: " + (std::string)clip->Operator);
  1447. return;
  1448. }
  1449. TempMesh meshout;
  1450. const IfcHalfSpaceSolid* const hs = clip->SecondOperand->ResolveSelectPtr<IfcHalfSpaceSolid>(conv.db);
  1451. if(!hs) {
  1452. IFCImporter::LogError("expected IfcHalfSpaceSolid as second clipping operand");
  1453. return;
  1454. }
  1455. const IfcPlane* const plane = hs->BaseSurface->ToPtr<IfcPlane>();
  1456. if(!plane) {
  1457. IFCImporter::LogError("expected IfcPlane as base surface for the IfcHalfSpaceSolid");
  1458. return;
  1459. }
  1460. if(const IfcBooleanResult* const op0 = clip->FirstOperand->ResolveSelectPtr<IfcBooleanResult>(conv.db)) {
  1461. ProcessBoolean(*op0,meshout,conv);
  1462. }
  1463. else if (const IfcSweptAreaSolid* const swept = clip->FirstOperand->ResolveSelectPtr<IfcSweptAreaSolid>(conv.db)) {
  1464. ProcessSweptAreaSolid(*swept,meshout,conv);
  1465. }
  1466. else {
  1467. IFCImporter::LogError("expected IfcSweptAreaSolid or IfcBooleanResult as first clipping operand");
  1468. return;
  1469. }
  1470. // extract plane base position vector and normal vector
  1471. IfcVector3 p,n(0.f,0.f,1.f);
  1472. if (plane->Position->Axis) {
  1473. ConvertDirection(n,plane->Position->Axis.Get());
  1474. }
  1475. ConvertCartesianPoint(p,plane->Position->Location);
  1476. if(!IsTrue(hs->AgreementFlag)) {
  1477. n *= -1.f;
  1478. }
  1479. // clip the current contents of `meshout` against the plane we obtained from the second operand
  1480. const std::vector<IfcVector3>& in = meshout.verts;
  1481. std::vector<IfcVector3>& outvert = result.verts;
  1482. std::vector<unsigned int>::const_iterator begin=meshout.vertcnt.begin(), end=meshout.vertcnt.end(), iit;
  1483. outvert.reserve(in.size());
  1484. result.vertcnt.reserve(meshout.vertcnt.size());
  1485. unsigned int vidx = 0;
  1486. for(iit = begin; iit != end; vidx += *iit++) {
  1487. unsigned int newcount = 0;
  1488. for(unsigned int i = 0; i < *iit; ++i) {
  1489. const IfcVector3& e0 = in[vidx+i], e1 = in[vidx+(i+1)%*iit];
  1490. // does the next segment intersect the plane?
  1491. IfcVector3 isectpos;
  1492. const Intersect isect = IntersectSegmentPlane(p,n,e0,e1,isectpos);
  1493. if (isect == Intersect_No || isect == Intersect_LiesOnPlane) {
  1494. if ( (e0-p).Normalize()*n > 0 ) {
  1495. outvert.push_back(e0);
  1496. ++newcount;
  1497. }
  1498. }
  1499. else if (isect == Intersect_Yes) {
  1500. if ( (e0-p).Normalize()*n > 0 ) {
  1501. // e0 is on the right side, so keep it
  1502. outvert.push_back(e0);
  1503. outvert.push_back(isectpos);
  1504. newcount += 2;
  1505. }
  1506. else {
  1507. // e0 is on the wrong side, so drop it and keep e1 instead
  1508. outvert.push_back(isectpos);
  1509. ++newcount;
  1510. }
  1511. }
  1512. }
  1513. if (!newcount) {
  1514. continue;
  1515. }
  1516. IfcVector3 vmin,vmax;
  1517. ArrayBounds(&*(outvert.end()-newcount),newcount,vmin,vmax);
  1518. // filter our IfcFloat points - those may happen if a point lies
  1519. // directly on the intersection line. However, due to IfcFloat
  1520. // precision a bitwise comparison is not feasible to detect
  1521. // this case.
  1522. const IfcFloat epsilon = (vmax-vmin).SquareLength() / 1e6f;
  1523. FuzzyVectorCompare fz(epsilon);
  1524. std::vector<IfcVector3>::iterator e = std::unique( outvert.end()-newcount, outvert.end(), fz );
  1525. if (e != outvert.end()) {
  1526. newcount -= static_cast<unsigned int>(std::distance(e,outvert.end()));
  1527. outvert.erase(e,outvert.end());
  1528. }
  1529. if (fz(*( outvert.end()-newcount),outvert.back())) {
  1530. outvert.pop_back();
  1531. --newcount;
  1532. }
  1533. if(newcount > 2) {
  1534. result.vertcnt.push_back(newcount);
  1535. }
  1536. else while(newcount-->0)result.verts.pop_back();
  1537. }
  1538. IFCImporter::LogDebug("generating CSG geometry by plane clipping (IfcBooleanClippingResult)");
  1539. }
  1540. else {
  1541. IFCImporter::LogWarn("skipping unknown IfcBooleanResult entity, type is " + boolean.GetClassName());
  1542. }
  1543. }
  1544. // ------------------------------------------------------------------------------------------------
  1545. bool ProcessGeometricItem(const IfcRepresentationItem& geo, std::vector<unsigned int>& mesh_indices,
  1546. ConversionData& conv)
  1547. {
  1548. bool fix_orientation = true;
  1549. TempMesh meshtmp;
  1550. if(const IfcShellBasedSurfaceModel* shellmod = geo.ToPtr<IfcShellBasedSurfaceModel>()) {
  1551. BOOST_FOREACH(boost::shared_ptr<const IfcShell> shell,shellmod->SbsmBoundary) {
  1552. try {
  1553. const EXPRESS::ENTITY& e = shell->To<ENTITY>();
  1554. const IfcConnectedFaceSet& fs = conv.db.MustGetObject(e).To<IfcConnectedFaceSet>();
  1555. ProcessConnectedFaceSet(fs,meshtmp,conv);
  1556. }
  1557. catch(std::bad_cast&) {
  1558. IFCImporter::LogWarn("unexpected type error, IfcShell ought to inherit from IfcConnectedFaceSet");
  1559. }
  1560. }
  1561. }
  1562. else if(const IfcConnectedFaceSet* fset = geo.ToPtr<IfcConnectedFaceSet>()) {
  1563. ProcessConnectedFaceSet(*fset,meshtmp,conv);
  1564. }
  1565. else if(const IfcSweptAreaSolid* swept = geo.ToPtr<IfcSweptAreaSolid>()) {
  1566. ProcessSweptAreaSolid(*swept,meshtmp,conv);
  1567. }
  1568. else if(const IfcSweptDiskSolid* disk = geo.ToPtr<IfcSweptDiskSolid>()) {
  1569. ProcessSweptDiskSolid(*disk,meshtmp,conv);
  1570. fix_orientation = false;
  1571. }
  1572. else if(const IfcManifoldSolidBrep* brep = geo.ToPtr<IfcManifoldSolidBrep>()) {
  1573. ProcessConnectedFaceSet(brep->Outer,meshtmp,conv);
  1574. }
  1575. else if(const IfcFaceBasedSurfaceModel* surf = geo.ToPtr<IfcFaceBasedSurfaceModel>()) {
  1576. BOOST_FOREACH(const IfcConnectedFaceSet& fc, surf->FbsmFaces) {
  1577. ProcessConnectedFaceSet(fc,meshtmp,conv);
  1578. }
  1579. }
  1580. else if(const IfcBooleanResult* boolean = geo.ToPtr<IfcBooleanResult>()) {
  1581. ProcessBoolean(*boolean,meshtmp,conv);
  1582. }
  1583. else if(geo.ToPtr<IfcBoundingBox>()) {
  1584. // silently skip over bounding boxes
  1585. return false;
  1586. }
  1587. else {
  1588. IFCImporter::LogWarn("skipping unknown IfcGeometricRepresentationItem entity, type is " + geo.GetClassName());
  1589. return false;
  1590. }
  1591. meshtmp.RemoveAdjacentDuplicates();
  1592. if(fix_orientation) {
  1593. FixupFaceOrientation(meshtmp);
  1594. }
  1595. aiMesh* const mesh = meshtmp.ToMesh();
  1596. if(mesh) {
  1597. mesh->mMaterialIndex = ProcessMaterials(geo,conv);
  1598. mesh_indices.push_back(conv.meshes.size());
  1599. conv.meshes.push_back(mesh);
  1600. return true;
  1601. }
  1602. return false;
  1603. }
  1604. // ------------------------------------------------------------------------------------------------
  1605. void AssignAddedMeshes(std::vector<unsigned int>& mesh_indices,aiNode* nd,
  1606. ConversionData& /*conv*/)
  1607. {
  1608. if (!mesh_indices.empty()) {
  1609. // make unique
  1610. std::sort(mesh_indices.begin(),mesh_indices.end());
  1611. std::vector<unsigned int>::iterator it_end = std::unique(mesh_indices.begin(),mesh_indices.end());
  1612. const size_t size = std::distance(mesh_indices.begin(),it_end);
  1613. nd->mNumMeshes = size;
  1614. nd->mMeshes = new unsigned int[nd->mNumMeshes];
  1615. for(unsigned int i = 0; i < nd->mNumMeshes; ++i) {
  1616. nd->mMeshes[i] = mesh_indices[i];
  1617. }
  1618. }
  1619. }
  1620. // ------------------------------------------------------------------------------------------------
  1621. bool TryQueryMeshCache(const IfcRepresentationItem& item,
  1622. std::vector<unsigned int>& mesh_indices,
  1623. ConversionData& conv)
  1624. {
  1625. ConversionData::MeshCache::const_iterator it = conv.cached_meshes.find(&item);
  1626. if (it != conv.cached_meshes.end()) {
  1627. std::copy((*it).second.begin(),(*it).second.end(),std::back_inserter(mesh_indices));
  1628. return true;
  1629. }
  1630. return false;
  1631. }
  1632. // ------------------------------------------------------------------------------------------------
  1633. void PopulateMeshCache(const IfcRepresentationItem& item,
  1634. const std::vector<unsigned int>& mesh_indices,
  1635. ConversionData& conv)
  1636. {
  1637. conv.cached_meshes[&item] = mesh_indices;
  1638. }
  1639. // ------------------------------------------------------------------------------------------------
  1640. bool ProcessRepresentationItem(const IfcRepresentationItem& item,
  1641. std::vector<unsigned int>& mesh_indices,
  1642. ConversionData& conv)
  1643. {
  1644. if (!TryQueryMeshCache(item,mesh_indices,conv)) {
  1645. if(ProcessGeometricItem(item,mesh_indices,conv)) {
  1646. if(mesh_indices.size()) {
  1647. PopulateMeshCache(item,mesh_indices,conv);
  1648. }
  1649. }
  1650. else return false;
  1651. }
  1652. return true;
  1653. }
  1654. #undef to_int64
  1655. #undef from_int64
  1656. #undef from_int64_f
  1657. } // ! IFC
  1658. } // ! Assimp
  1659. #endif