diff options
author | Paul Lemire <paul.lemire@kdab.com> | 2014-05-26 10:35:32 +0200 |
---|---|---|
committer | The Qt Project <gerrit-noreply@qt-project.org> | 2014-06-04 10:09:11 +0200 |
commit | 1cb807d440cc0d434bfd02fd0c699447b788b8ba (patch) | |
tree | f28f64fba6ebb30449c3301a75bba2b233b1f34e /src/3rdparty/assimp/code/IFCGeometry.cpp | |
parent | a45b8308ada361872502a678a12f08cff1760c64 (diff) |
Upgrade to Assimp 3.1
https://github.com/assimp/assimp/releases/tag/v3.1
This commit imports assimp 3.1, including CHANGES, CREDITS, LICENSE, README,
Readme.md, revision.h and code, contrib, include directories. contrib/zlib
was excluded.
assimp.pri was also updated.
Uses zlib from system or qt instead of contrib/zlib.
Task-number: QTBUG-39251
Change-Id: Ia0b446dcd9bc867d65897b9e2b157f6544ccaeac
Reviewed-by: Liang Qi <liang.qi@digia.com>
Reviewed-by: Sean Harmer <sean.harmer@kdab.com>
Reviewed-by: Lars Knoll <lars.knoll@digia.com>
Diffstat (limited to 'src/3rdparty/assimp/code/IFCGeometry.cpp')
-rw-r--r-- | src/3rdparty/assimp/code/IFCGeometry.cpp | 1591 |
1 files changed, 312 insertions, 1279 deletions
diff --git a/src/3rdparty/assimp/code/IFCGeometry.cpp b/src/3rdparty/assimp/code/IFCGeometry.cpp index bbf03203b..a3c6711d8 100644 --- a/src/3rdparty/assimp/code/IFCGeometry.cpp +++ b/src/3rdparty/assimp/code/IFCGeometry.cpp @@ -57,14 +57,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. namespace Assimp { namespace IFC { - using ClipperLib::ulong64; - // XXX use full -+ range ... - const ClipperLib::long64 max_ulong64 = 1518500249; // clipper.cpp / hiRange var - - //#define to_int64(p) (static_cast<ulong64>( std::max( 0., std::min( static_cast<IfcFloat>((p)), 1.) ) * max_ulong64 )) -#define to_int64(p) (static_cast<ulong64>(static_cast<IfcFloat>((p) ) * max_ulong64 )) -#define from_int64(p) (static_cast<IfcFloat>((p)) / max_ulong64) - // ------------------------------------------------------------------------------------------------ bool ProcessPolyloop(const IfcPolyLoop& loop, TempMesh& meshout, ConversionData& /*conv*/) { @@ -92,338 +84,123 @@ bool ProcessPolyloop(const IfcPolyLoop& loop, TempMesh& meshout, ConversionData& } // ------------------------------------------------------------------------------------------------ -void ComputePolygonNormals(const TempMesh& meshout, std::vector<IfcVector3>& normals, bool normalize = true, size_t ofs = 0) -{ - size_t max_vcount = 0; - std::vector<unsigned int>::const_iterator begin=meshout.vertcnt.begin()+ofs, end=meshout.vertcnt.end(), iit; - for(iit = begin; iit != end; ++iit) { - max_vcount = std::max(max_vcount,static_cast<size_t>(*iit)); - } - - std::vector<IfcFloat> temp((max_vcount+2)*4); - normals.reserve( normals.size() + meshout.vertcnt.size()-ofs ); - - // `NewellNormal()` currently has a relatively strange interface and need to - // re-structure things a bit to meet them. - size_t vidx = std::accumulate(meshout.vertcnt.begin(),begin,0); - for(iit = begin; iit != end; vidx += *iit++) { - if (!*iit) { - normals.push_back(IfcVector3()); - continue; - } - for(size_t vofs = 0, cnt = 0; vofs < *iit; ++vofs) { - const IfcVector3& v = meshout.verts[vidx+vofs]; - temp[cnt++] = v.x; - temp[cnt++] = v.y; - temp[cnt++] = v.z; -#ifdef _DEBUG - temp[cnt] = std::numeric_limits<IfcFloat>::quiet_NaN(); -#endif - ++cnt; - } - - normals.push_back(IfcVector3()); - NewellNormal<4,4,4>(normals.back(),*iit,&temp[0],&temp[1],&temp[2]); - } - - if(normalize) { - BOOST_FOREACH(IfcVector3& n, normals) { - n.Normalize(); - } - } -} - -// ------------------------------------------------------------------------------------------------ -// Compute the normal of the last polygon in the given mesh -IfcVector3 ComputePolygonNormal(const TempMesh& inmesh, bool normalize = true) -{ - size_t total = inmesh.vertcnt.back(), vidx = inmesh.verts.size() - total; - std::vector<IfcFloat> temp((total+2)*3); - for(size_t vofs = 0, cnt = 0; vofs < total; ++vofs) { - const IfcVector3& v = inmesh.verts[vidx+vofs]; - temp[cnt++] = v.x; - temp[cnt++] = v.y; - temp[cnt++] = v.z; - } - IfcVector3 nor; - NewellNormal<3,3,3>(nor,total,&temp[0],&temp[1],&temp[2]); - return normalize ? nor.Normalize() : nor; -} - -// ------------------------------------------------------------------------------------------------ -void FixupFaceOrientation(TempMesh& result) +void ProcessPolygonBoundaries(TempMesh& result, const TempMesh& inmesh, size_t master_bounds = (size_t)-1) { - const IfcVector3 vavg = result.Center(); - - std::vector<IfcVector3> normals; - ComputePolygonNormals(result,normals); - - size_t c = 0, ofs = 0; - BOOST_FOREACH(unsigned int cnt, result.vertcnt) { - if (cnt>2){ - const IfcVector3& thisvert = result.verts[c]; - if (normals[ofs]*(thisvert-vavg) < 0) { - std::reverse(result.verts.begin()+c,result.verts.begin()+cnt+c); - } - } - c += cnt; - ++ofs; - } -} - -// ------------------------------------------------------------------------------------------------ -void RecursiveMergeBoundaries(TempMesh& final_result, const TempMesh& in, const TempMesh& boundary, std::vector<IfcVector3>& normals, const IfcVector3& nor_boundary) -{ - ai_assert(in.vertcnt.size() >= 1); - ai_assert(boundary.vertcnt.size() == 1); - std::vector<unsigned int>::const_iterator end = in.vertcnt.end(), begin=in.vertcnt.begin(), iit, best_iit; - - TempMesh out; - - // iterate through all other bounds and find the one for which the shortest connection - // to the outer boundary is actually the shortest possible. - size_t vidx = 0, best_vidx_start = 0; - size_t best_ofs, best_outer = boundary.verts.size(); - IfcFloat best_dist = 1e10; - for(std::vector<unsigned int>::const_iterator iit = begin; iit != end; vidx += *iit++) { - - for(size_t vofs = 0; vofs < *iit; ++vofs) { - const IfcVector3& v = in.verts[vidx+vofs]; - - for(size_t outer = 0; outer < boundary.verts.size(); ++outer) { - const IfcVector3& o = boundary.verts[outer]; - const IfcFloat d = (o-v).SquareLength(); - - if (d < best_dist) { - best_dist = d; - best_ofs = vofs; - best_outer = outer; - best_iit = iit; - best_vidx_start = vidx; - } - } - } - } - - ai_assert(best_outer != boundary.verts.size()); - - - // now that we collected all vertex connections to be added, build the output polygon - const size_t cnt = boundary.verts.size() + *best_iit+2; - out.verts.reserve(cnt); - - for(size_t outer = 0; outer < boundary.verts.size(); ++outer) { - const IfcVector3& o = boundary.verts[outer]; - out.verts.push_back(o); - - if (outer == best_outer) { - for(size_t i = best_ofs; i < *best_iit; ++i) { - out.verts.push_back(in.verts[best_vidx_start + i]); - } - - // we need the first vertex of the inner polygon twice as we return to the - // outer loop through the very same connection through which we got there. - for(size_t i = 0; i <= best_ofs; ++i) { - out.verts.push_back(in.verts[best_vidx_start + i]); - } - - // reverse face winding if the normal of the sub-polygon points in the - // same direction as the normal of the outer polygonal boundary - if (normals[std::distance(begin,best_iit)] * nor_boundary > 0) { - std::reverse(out.verts.rbegin(),out.verts.rbegin()+*best_iit+1); - } - - // also append a copy of the initial insertion point to be able to continue the outer polygon - out.verts.push_back(o); - } - } - out.vertcnt.push_back(cnt); - ai_assert(out.verts.size() == cnt); - - if (in.vertcnt.size()-std::count(begin,end,0) > 1) { - // Recursively apply the same algorithm if there are more boundaries to merge. The - // current implementation is relatively inefficient, though. - - TempMesh temp; - - // drop the boundary that we just processed - const size_t dist = std::distance(begin, best_iit); - TempMesh remaining = in; - remaining.vertcnt.erase(remaining.vertcnt.begin() + dist); - remaining.verts.erase(remaining.verts.begin()+best_vidx_start,remaining.verts.begin()+best_vidx_start+*best_iit); - - normals.erase(normals.begin() + dist); - RecursiveMergeBoundaries(temp,remaining,out,normals,nor_boundary); - - final_result.Append(temp); + // handle all trivial cases + if(inmesh.vertcnt.empty()) { + return; } - else final_result.Append(out); -} - -// ------------------------------------------------------------------------------------------------ -void MergePolygonBoundaries(TempMesh& result, const TempMesh& inmesh, size_t master_bounds = -1) -{ - // standard case - only one boundary, just copy it to the result vector - if (inmesh.vertcnt.size() <= 1) { + if(inmesh.vertcnt.size() == 1) { result.Append(inmesh); return; } - result.vertcnt.reserve(inmesh.vertcnt.size()+result.vertcnt.size()); + ai_assert(std::count(inmesh.vertcnt.begin(), inmesh.vertcnt.end(), 0) == 0); - // XXX get rid of the extra copy if possible - TempMesh meshout = inmesh; + typedef std::vector<unsigned int>::const_iterator face_iter; - // handle polygons with holes. Our built in triangulation won't handle them as is, but - // the ear cutting algorithm is solid enough to deal with them if we join the inner - // holes with the outer boundaries by dummy connections. - IFCImporter::LogDebug("fixing polygon with holes for triangulation via ear-cutting"); - std::vector<unsigned int>::iterator outer_polygon = meshout.vertcnt.end(), begin=meshout.vertcnt.begin(), end=outer_polygon, iit; + face_iter begin = inmesh.vertcnt.begin(), end = inmesh.vertcnt.end(), iit; + std::vector<unsigned int>::const_iterator outer_polygon_it = end; - // each hole results in two extra vertices - result.verts.reserve(meshout.verts.size()+meshout.vertcnt.size()*2+result.verts.size()); - size_t outer_polygon_start = 0; + // major task here: given a list of nested polygon boundaries (one of which + // is the outer contour), reduce the triangulation task arising here to + // one that can be solved using the "quadrulation" algorithm which we use + // for pouring windows out of walls. The algorithm does not handle all + // cases but at least it is numerically stable and gives "nice" triangles. + // first compute normals for all polygons using Newell's algorithm // do not normalize 'normals', we need the original length for computing the polygon area std::vector<IfcVector3> normals; - ComputePolygonNormals(meshout,normals,false); + inmesh.ComputePolygonNormals(normals,false); - // see if one of the polygons is a IfcFaceOuterBound (in which case `master_bounds` is its index). - // sadly we can't rely on it, the docs say 'At most one of the bounds shall be of the type IfcFaceOuterBound' + // One of the polygons might be a IfcFaceOuterBound (in which case `master_bounds` + // is its index). Sadly we can't rely on it, the docs say 'At most one of the bounds + // shall be of the type IfcFaceOuterBound' IfcFloat area_outer_polygon = 1e-10f; if (master_bounds != (size_t)-1) { - outer_polygon = begin + master_bounds; - outer_polygon_start = std::accumulate(begin,outer_polygon,0); - area_outer_polygon = normals[master_bounds].SquareLength(); + ai_assert(master_bounds < inmesh.vertcnt.size()); + outer_polygon_it = begin + master_bounds; } else { - size_t vidx = 0; - for(iit = begin; iit != meshout.vertcnt.end(); vidx += *iit++) { - // find the polygon with the largest area, it must be the outer bound. + for(iit = begin; iit != end; iit++) { + // find the polygon with the largest area and take it as the outer bound. IfcVector3& n = normals[std::distance(begin,iit)]; const IfcFloat area = n.SquareLength(); if (area > area_outer_polygon) { area_outer_polygon = area; - outer_polygon = iit; - outer_polygon_start = vidx; + outer_polygon_it = iit; } } } - ai_assert(outer_polygon != meshout.vertcnt.end()); - std::vector<IfcVector3>& in = meshout.verts; + ai_assert(outer_polygon_it != end); - // skip over extremely small boundaries - this is a workaround to fix cases - // in which the number of holes is so extremely large that the - // triangulation code fails. -#define IFC_VERTICAL_HOLE_SIZE_THRESHOLD 0.000001f - size_t vidx = 0, removed = 0, index = 0; - const IfcFloat threshold = area_outer_polygon * IFC_VERTICAL_HOLE_SIZE_THRESHOLD; - for(iit = begin; iit != end ;++index) { - const IfcFloat sqlen = normals[index].SquareLength(); - if (sqlen < threshold) { - std::vector<IfcVector3>::iterator inbase = in.begin()+vidx; - in.erase(inbase,inbase+*iit); - - outer_polygon_start -= outer_polygon_start>vidx ? *iit : 0; - *iit++ = 0; - ++removed; + const size_t outer_polygon_size = *outer_polygon_it; + const IfcVector3& master_normal = normals[std::distance(begin, outer_polygon_it)]; - IFCImporter::LogDebug("skip small hole below threshold"); - } - else { - normals[index] /= sqrt(sqlen); - vidx += *iit++; - } - } + // Generate fake openings to meet the interface for the quadrulate + // algorithm. It boils down to generating small boxes given the + // inner polygon and the surface normal of the outer contour. + // It is important that we use the outer contour's normal because + // this is the plane onto which the quadrulate algorithm will + // project the entire mesh. + std::vector<TempOpening> fake_openings; + fake_openings.reserve(inmesh.vertcnt.size()-1); - // see if one or more of the hole has a face that lies directly on an outer bound. - // this happens for doors, for example. - vidx = 0; - for(iit = begin; ; vidx += *iit++) { -next_loop: - if (iit == end) { - break; - } - if (iit == outer_polygon) { + std::vector<IfcVector3>::const_iterator vit = inmesh.verts.begin(), outer_vit; + + for(iit = begin; iit != end; vit += *iit++) { + if (iit == outer_polygon_it) { + outer_vit = vit; continue; } - for(size_t vofs = 0; vofs < *iit; ++vofs) { - if (!*iit) { - continue; - } - const size_t next = (vofs+1)%*iit; - const IfcVector3& v = in[vidx+vofs], &vnext = in[vidx+next],&vd = (vnext-v).Normalize(); - - for(size_t outer = 0; outer < *outer_polygon; ++outer) { - const IfcVector3& o = in[outer_polygon_start+outer], &onext = in[outer_polygon_start+(outer+1)%*outer_polygon], &od = (onext-o).Normalize(); - - if (fabs(vd * od) > 1.f-1e-6f && (onext-v).Normalize() * vd > 1.f-1e-6f && (onext-v)*(o-v) < 0) { - IFCImporter::LogDebug("got an inner hole that lies partly on the outer polygonal boundary, merging them to a single contour"); - - // in between outer and outer+1 insert all vertices of this loop, then drop the original altogether. - std::vector<IfcVector3> tmp(*iit); - - const size_t start = (v-o).SquareLength() > (vnext-o).SquareLength() ? vofs : next; - std::vector<IfcVector3>::iterator inbase = in.begin()+vidx, it = std::copy(inbase+start, inbase+*iit,tmp.begin()); - std::copy(inbase, inbase+start,it); - std::reverse(tmp.begin(),tmp.end()); + // Filter degenerate polygons to keep them from causing trouble later on + IfcVector3& n = normals[std::distance(begin,iit)]; + const IfcFloat area = n.SquareLength(); + if (area < 1e-5f) { + IFCImporter::LogWarn("skipping degenerate polygon (ProcessPolygonBoundaries)"); + continue; + } - in.insert(in.begin()+outer_polygon_start+(outer+1)%*outer_polygon,tmp.begin(),tmp.end()); - vidx += outer_polygon_start<vidx ? *iit : 0; + fake_openings.push_back(TempOpening()); + TempOpening& opening = fake_openings.back(); - inbase = in.begin()+vidx; - in.erase(inbase,inbase+*iit); + opening.extrusionDir = master_normal; + opening.solid = NULL; - outer_polygon_start -= outer_polygon_start>vidx ? *iit : 0; - - *outer_polygon += tmp.size(); - *iit++ = 0; - ++removed; - goto next_loop; - } - } - } - } + opening.profileMesh = boost::make_shared<TempMesh>(); + opening.profileMesh->verts.reserve(*iit); + opening.profileMesh->vertcnt.push_back(*iit); - if ( meshout.vertcnt.size() - removed <= 1) { - result.Append(meshout); - return; + std::copy(vit, vit + *iit, std::back_inserter(opening.profileMesh->verts)); } - // extract the outer boundary and move it to a separate mesh - TempMesh boundary; - boundary.vertcnt.resize(1,*outer_polygon); - boundary.verts.resize(*outer_polygon); - - std::vector<IfcVector3>::iterator b = in.begin()+outer_polygon_start; - std::copy(b,b+*outer_polygon,boundary.verts.begin()); - in.erase(b,b+*outer_polygon); - - std::vector<IfcVector3>::iterator norit = normals.begin()+std::distance(meshout.vertcnt.begin(),outer_polygon); - const IfcVector3 nor_boundary = *norit; - normals.erase(norit); - meshout.vertcnt.erase(outer_polygon); + // fill a mesh with ONLY the main polygon + TempMesh temp; + temp.verts.reserve(outer_polygon_size); + temp.vertcnt.push_back(outer_polygon_size); + std::copy(outer_vit, outer_vit+outer_polygon_size, + std::back_inserter(temp.verts)); - // keep merging the closest inner boundary with the outer boundary until no more boundaries are left - RecursiveMergeBoundaries(result,meshout,boundary,normals,nor_boundary); + GenerateOpenings(fake_openings, normals, temp, false, false); + result.Append(temp); } - // ------------------------------------------------------------------------------------------------ void ProcessConnectedFaceSet(const IfcConnectedFaceSet& fset, TempMesh& result, ConversionData& conv) { BOOST_FOREACH(const IfcFace& face, fset.CfsFaces) { - // size_t ob = -1, cnt = 0; TempMesh meshout; BOOST_FOREACH(const IfcFaceBound& bound, face.Bounds) { - // XXX implement proper merging for polygonal loops if(const IfcPolyLoop* const polyloop = bound.Bound->ToPtr<IfcPolyLoop>()) { if(ProcessPolyloop(*polyloop, meshout,conv)) { + // The outer boundary is better determined by checking which + // polygon covers the largest area. + //if(bound.ToPtr<IfcFaceOuterBound>()) { // ob = cnt; //} @@ -436,6 +213,9 @@ void ProcessConnectedFaceSet(const IfcConnectedFaceSet& fset, TempMesh& result, continue; } + // And this, even though it is sometimes TRUE and sometimes FALSE, + // does not really improve results. + /*if(!IsTrue(bound.Orientation)) { size_t c = 0; BOOST_FOREACH(unsigned int& c, meshout.vertcnt) { @@ -443,15 +223,11 @@ void ProcessConnectedFaceSet(const IfcConnectedFaceSet& fset, TempMesh& result, cnt += c; } }*/ - } - MergePolygonBoundaries(result,meshout); + ProcessPolygonBoundaries(result, meshout); } } - - - // ------------------------------------------------------------------------------------------------ void ProcessRevolvedAreaSolid(const IfcRevolvedAreaSolid& solid, TempMesh& result, ConversionData& conv) { @@ -539,865 +315,217 @@ void ProcessRevolvedAreaSolid(const IfcRevolvedAreaSolid& solid, TempMesh& resul IFCImporter::LogDebug("generate mesh procedurally by radial extrusion (IfcRevolvedAreaSolid)"); } -// ------------------------------------------------------------------------------------------------ -IfcMatrix3 DerivePlaneCoordinateSpace(const TempMesh& curmesh) { - - const std::vector<IfcVector3>& out = curmesh.verts; - IfcMatrix3 m; - - const size_t s = out.size(); - assert(curmesh.vertcnt.size() == 1 && curmesh.vertcnt.back() == s); - - const IfcVector3 any_point = out[s-1]; - IfcVector3 nor; - - // The input polygon is arbitrarily shaped, so we might need some tries - // until we find a suitable normal (and it does not even need to be - // right in all cases, Newell's algorithm would be the correct one ... ). - size_t base = s-curmesh.vertcnt.back(), i, j; - for (i = base; i < s-1; ++i) { - for (j = i+1; j < s; ++j) { - nor = -((out[i]-any_point)^(out[j]-any_point)); - if(fabs(nor.Length()) > 1e-8f) { - goto out; - } - } - } - - assert(0); - -out: - - nor.Normalize(); - - IfcVector3 r = (out[i]-any_point); - r.Normalize(); - - // reconstruct orthonormal basis - IfcVector3 u = r ^ nor; - u.Normalize(); - - m.a1 = r.x; - m.a2 = r.y; - m.a3 = r.z; - - m.b1 = u.x; - m.b2 = u.y; - m.b3 = u.z; - - m.c1 = nor.x; - m.c2 = nor.y; - m.c3 = nor.z; - return m; -} // ------------------------------------------------------------------------------------------------ -bool TryAddOpenings_Poly2Tri(const std::vector<TempOpening>& openings,const std::vector<IfcVector3>& nors, TempMesh& curmesh) +void ProcessSweptDiskSolid(const IfcSweptDiskSolid solid, TempMesh& result, ConversionData& conv) { - std::vector<IfcVector3>& out = curmesh.verts; - - bool result = false; - - // Try to derive a solid base plane within the current surface for use as - // working coordinate system. - const IfcMatrix3& m = DerivePlaneCoordinateSpace(curmesh); - const IfcMatrix3 minv = IfcMatrix3(m).Inverse(); - const IfcVector3& nor = IfcVector3(m.c1, m.c2, m.c3); - - IfcFloat coord = -1; - - std::vector<IfcVector2> contour_flat; - contour_flat.reserve(out.size()); - - IfcVector2 vmin, vmax; - MinMaxChooser<IfcVector2>()(vmin, vmax); + const Curve* const curve = Curve::Convert(*solid.Directrix, conv); + if(!curve) { + IFCImporter::LogError("failed to convert Directrix curve (IfcSweptDiskSolid)"); + return; + } - // Move all points into the new coordinate system, collecting min/max verts on the way - BOOST_FOREACH(IfcVector3& x, out) { - const IfcVector3 vv = m * x; - - // keep Z offset in the plane coordinate system. Ignoring precision issues - // (which are present, of course), this should be the same value for - // all polygon vertices (assuming the polygon is planar). + const unsigned int cnt_segments = 16; + const IfcFloat deltaAngle = AI_MATH_TWO_PI/cnt_segments; + const size_t samples = curve->EstimateSampleCount(solid.StartParam,solid.EndParam); - // XXX this should be guarded, but we somehow need to pick a suitable - // epsilon - // if(coord != -1.0f) { - // assert(fabs(coord - vv.z) < 1e-3f); - // } + result.verts.reserve(cnt_segments * samples * 4); + result.vertcnt.reserve((cnt_segments - 1) * samples); - coord = vv.z; + std::vector<IfcVector3> points; + points.reserve(cnt_segments * samples); - vmin = std::min(IfcVector2(vv.x, vv.y), vmin); - vmax = std::max(IfcVector2(vv.x, vv.y), vmax); + TempMesh temp; + curve->SampleDiscrete(temp,solid.StartParam,solid.EndParam); + const std::vector<IfcVector3>& curve_points = temp.verts; - contour_flat.push_back(IfcVector2(vv.x,vv.y)); + if(curve_points.empty()) { + IFCImporter::LogWarn("curve evaluation yielded no points (IfcSweptDiskSolid)"); + return; } - - // With the current code in DerivePlaneCoordinateSpace, - // vmin,vmax should always be the 0...1 rectangle (+- numeric inaccuracies) - // but here we won't rely on this. - - vmax -= vmin; - - // If this happens then the projection must have been wrong. - assert(vmax.Length()); - - ClipperLib::ExPolygons clipped; - ClipperLib::Polygons holes_union; - - - IfcVector3 wall_extrusion; - bool do_connections = false, first = true; - - try { - - ClipperLib::Clipper clipper_holes; - size_t c = 0; - - BOOST_FOREACH(const TempOpening& t,openings) { - const IfcVector3& outernor = nors[c++]; - const IfcFloat dot = nor * outernor; - if (fabs(dot)<1.f-1e-6f) { - continue; - } - - const std::vector<IfcVector3>& va = t.profileMesh->verts; - if(va.size() <= 2) { - continue; - } - - std::vector<IfcVector2> contour; - - BOOST_FOREACH(const IfcVector3& xx, t.profileMesh->verts) { - IfcVector3 vv = m * xx, vv_extr = m * (xx + t.extrusionDir); - - const bool is_extruded_side = fabs(vv.z - coord) > fabs(vv_extr.z - coord); - if (first) { - first = false; - if (dot > 0.f) { - do_connections = true; - wall_extrusion = t.extrusionDir; - if (is_extruded_side) { - wall_extrusion = - wall_extrusion; - } - } - } - - // XXX should not be necessary - but it is. Why? For precision reasons? - vv = is_extruded_side ? vv_extr : vv; - contour.push_back(IfcVector2(vv.x,vv.y)); - } - - ClipperLib::Polygon hole; - BOOST_FOREACH(IfcVector2& pip, contour) { - pip.x = (pip.x - vmin.x) / vmax.x; - pip.y = (pip.y - vmin.y) / vmax.y; - - hole.push_back(ClipperLib::IntPoint( to_int64(pip.x), to_int64(pip.y) )); - } - - if (!ClipperLib::Orientation(hole)) { - std::reverse(hole.begin(), hole.end()); - // assert(ClipperLib::Orientation(hole)); - } - - /*ClipperLib::Polygons pol_temp(1), pol_temp2(1); - pol_temp[0] = hole; - - ClipperLib::OffsetPolygons(pol_temp,pol_temp2,5.0); - hole = pol_temp2[0];*/ - - clipper_holes.AddPolygon(hole,ClipperLib::ptSubject); - } - - clipper_holes.Execute(ClipperLib::ctUnion,holes_union, - ClipperLib::pftNonZero, - ClipperLib::pftNonZero); - if (holes_union.empty()) { - return false; - } + IfcVector3 current = curve_points[0]; + IfcVector3 previous = current; + IfcVector3 next; - // Now that we have the big union of all holes, subtract it from the outer contour - // to obtain the final polygon to feed into the triangulator. - { - ClipperLib::Polygon poly; - BOOST_FOREACH(IfcVector2& pip, contour_flat) { - pip.x = (pip.x - vmin.x) / vmax.x; - pip.y = (pip.y - vmin.y) / vmax.y; + IfcVector3 startvec; + startvec.x = 1.0f; + startvec.y = 1.0f; + startvec.z = 1.0f; - poly.push_back(ClipperLib::IntPoint( to_int64(pip.x), to_int64(pip.y) )); - } + unsigned int last_dir = 0; - if (ClipperLib::Orientation(poly)) { - std::reverse(poly.begin(), poly.end()); - } - clipper_holes.Clear(); - clipper_holes.AddPolygon(poly,ClipperLib::ptSubject); + // generate circles at the sweep positions + for(size_t i = 0; i < samples; ++i) { - clipper_holes.AddPolygons(holes_union,ClipperLib::ptClip); - clipper_holes.Execute(ClipperLib::ctDifference,clipped, - ClipperLib::pftNonZero, - ClipperLib::pftNonZero); + if(i != samples - 1) { + next = curve_points[i + 1]; } - } - catch (const char* sx) { - IFCImporter::LogError("Ifc: error during polygon clipping, skipping openings for this face: (Clipper: " - + std::string(sx) + ")"); - - return false; - } - - std::vector<IfcVector3> old_verts; - std::vector<unsigned int> old_vertcnt; - - old_verts.swap(curmesh.verts); - old_vertcnt.swap(curmesh.vertcnt); - - - // add connection geometry to close the adjacent 'holes' for the openings - // this should only be done from one side of the wall or the polygons - // would be emitted twice. - if (false && do_connections) { - - std::vector<IfcVector3> tmpvec; - BOOST_FOREACH(ClipperLib::Polygon& opening, holes_union) { - - assert(ClipperLib::Orientation(opening)); - - tmpvec.clear(); - - BOOST_FOREACH(ClipperLib::IntPoint& point, opening) { - - tmpvec.push_back( minv * IfcVector3( - vmin.x + from_int64(point.X) * vmax.x, - vmin.y + from_int64(point.Y) * vmax.y, - coord)); - } - - for(size_t i = 0, size = tmpvec.size(); i < size; ++i) { - const size_t next = (i+1)%size; - - curmesh.vertcnt.push_back(4); - - const IfcVector3& in_world = tmpvec[i]; - const IfcVector3& next_world = tmpvec[next]; - - // Assumptions: no 'partial' openings, wall thickness roughly the same across the wall - curmesh.verts.push_back(in_world); - curmesh.verts.push_back(in_world+wall_extrusion); - curmesh.verts.push_back(next_world+wall_extrusion); - curmesh.verts.push_back(next_world); - } - } - } + // get a direction vector reflecting the approximate curvature (i.e. tangent) + IfcVector3 d = (current-previous) + (next-previous); - std::vector< std::vector<p2t::Point*> > contours; - BOOST_FOREACH(ClipperLib::ExPolygon& clip, clipped) { - - contours.clear(); - - // Build the outer polygon contour line for feeding into poly2tri - std::vector<p2t::Point*> contour_points; - BOOST_FOREACH(ClipperLib::IntPoint& point, clip.outer) { - contour_points.push_back( new p2t::Point(from_int64(point.X), from_int64(point.Y)) ); - } - - p2t::CDT* cdt ; - try { - // Note: this relies on custom modifications in poly2tri to raise runtime_error's - // instead if assertions. These failures are not debug only, they can actually - // happen in production use if the input data is broken. An assertion would be - // inappropriate. - cdt = new p2t::CDT(contour_points); - } - catch(const std::exception& e) { - IFCImporter::LogError("Ifc: error during polygon triangulation, skipping some openings: (poly2tri: " - + std::string(e.what()) + ")"); - continue; - } - - - // Build the poly2tri inner contours for all holes we got from ClipperLib - BOOST_FOREACH(ClipperLib::Polygon& opening, clip.holes) { - - contours.push_back(std::vector<p2t::Point*>()); - std::vector<p2t::Point*>& contour = contours.back(); - - BOOST_FOREACH(ClipperLib::IntPoint& point, opening) { - contour.push_back( new p2t::Point(from_int64(point.X), from_int64(point.Y)) ); + d.Normalize(); + + // figure out an arbitrary point q so that (p-q) * d = 0, + // try to maximize ||(p-q)|| * ||(p_last-q_last)|| + IfcVector3 q; + bool take_any = false; + + for (unsigned int i = 0; i < 2; ++i, take_any = true) { + if ((last_dir == 0 || take_any) && abs(d.x) > 1e-6) { + q.y = startvec.y; + q.z = startvec.z; + q.x = -(d.y * q.y + d.z * q.z) / d.x; + last_dir = 0; + break; } - - cdt->AddHole(contour); - } - - try { - // Note: See above - cdt->Triangulate(); - } - catch(const std::exception& e) { - IFCImporter::LogError("Ifc: error during polygon triangulation, skipping some openings: (poly2tri: " - + std::string(e.what()) + ")"); - continue; - } - - const std::vector<p2t::Triangle*>& tris = cdt->GetTriangles(); - - // Collect the triangles we just produced - BOOST_FOREACH(p2t::Triangle* tri, tris) { - for(int i = 0; i < 3; ++i) { - - const IfcVector2& v = IfcVector2( - static_cast<IfcFloat>( tri->GetPoint(i)->x ), - static_cast<IfcFloat>( tri->GetPoint(i)->y ) - ); - - assert(v.x <= 1.0 && v.x >= 0.0 && v.y <= 1.0 && v.y >= 0.0); - const IfcVector3 v3 = minv * IfcVector3(vmin.x + v.x * vmax.x, vmin.y + v.y * vmax.y,coord) ; - - curmesh.verts.push_back(v3); + else if ((last_dir == 1 || take_any) && abs(d.y) > 1e-6) { + q.x = startvec.x; + q.z = startvec.z; + q.y = -(d.x * q.x + d.z * q.z) / d.y; + last_dir = 1; + break; + } + else if ((last_dir == 2 && abs(d.z) > 1e-6) || take_any) { + q.y = startvec.y; + q.x = startvec.x; + q.z = -(d.y * q.y + d.x * q.x) / d.z; + last_dir = 2; + break; } - curmesh.vertcnt.push_back(3); - } - - result = true; - } - - if (!result) { - // revert -- it's a shame, but better than nothing - curmesh.verts.insert(curmesh.verts.end(),old_verts.begin(), old_verts.end()); - curmesh.vertcnt.insert(curmesh.vertcnt.end(),old_vertcnt.begin(), old_vertcnt.end()); - - IFCImporter::LogError("Ifc: revert, could not generate openings for this wall"); - } - - return result; -} - -// ------------------------------------------------------------------------------------------------ -struct DistanceSorter { - - DistanceSorter(const IfcVector3& base) : base(base) {} - - bool operator () (const TempOpening& a, const TempOpening& b) const { - return (a.profileMesh->Center()-base).SquareLength() < (b.profileMesh->Center()-base).SquareLength(); - } - - IfcVector3 base; -}; - -// ------------------------------------------------------------------------------------------------ -struct XYSorter { - - // sort first by X coordinates, then by Y coordinates - bool operator () (const IfcVector2&a, const IfcVector2& b) const { - if (a.x == b.x) { - return a.y < b.y; } - return a.x < b.x; - } -}; - -typedef std::pair< IfcVector2, IfcVector2 > BoundingBox; -typedef std::map<IfcVector2,size_t,XYSorter> XYSortedField; + q *= solid.Radius / q.Length(); + startvec = q; -// ------------------------------------------------------------------------------------------------ -void QuadrifyPart(const IfcVector2& pmin, const IfcVector2& pmax, XYSortedField& field, const std::vector< BoundingBox >& bbs, - std::vector<IfcVector2>& out) -{ - if (!(pmin.x-pmax.x) || !(pmin.y-pmax.y)) { - return; - } + // generate a rotation matrix to rotate q around d + IfcMatrix4 rot; + IfcMatrix4::Rotation(deltaAngle,d,rot); - IfcFloat xs = 1e10, xe = 1e10; - bool found = false; - - // Search along the x-axis until we find an opening - XYSortedField::iterator start = field.begin(); - for(; start != field.end(); ++start) { - const BoundingBox& bb = bbs[(*start).second]; - if(bb.first.x >= pmax.x) { - break; - } - - if (bb.second.x > pmin.x && bb.second.y > pmin.y && bb.first.y < pmax.y) { - xs = bb.first.x; - xe = bb.second.x; - found = true; - break; + for (unsigned int seg = 0; seg < cnt_segments; ++seg, q *= rot ) { + points.push_back(q + current); } - } - if (!found) { - // the rectangle [pmin,pend] is opaque, fill it - out.push_back(pmin); - out.push_back(IfcVector2(pmin.x,pmax.y)); - out.push_back(pmax); - out.push_back(IfcVector2(pmax.x,pmin.y)); - return; + previous = current; + current = next; } - xs = std::max(pmin.x,xs); - xe = std::min(pmax.x,xe); - - // see if there's an offset to fill at the top of our quad - if (xs - pmin.x) { - out.push_back(pmin); - out.push_back(IfcVector2(pmin.x,pmax.y)); - out.push_back(IfcVector2(xs,pmax.y)); - out.push_back(IfcVector2(xs,pmin.y)); - } + // make quads + for(size_t i = 0; i < samples - 1; ++i) { - // search along the y-axis for all openings that overlap xs and our quad - IfcFloat ylast = pmin.y; - found = false; - for(; start != field.end(); ++start) { - const BoundingBox& bb = bbs[(*start).second]; - if (bb.first.x > xs || bb.first.y >= pmax.y) { - break; - } + const aiVector3D& this_start = points[ i * cnt_segments ]; - if (bb.second.y > ylast) { + // locate corresponding point on next sample ring + unsigned int best_pair_offset = 0; + float best_distance_squared = 1e10f; + for (unsigned int seg = 0; seg < cnt_segments; ++seg) { + const aiVector3D& p = points[ (i+1) * cnt_segments + seg]; + const float l = (p-this_start).SquareLength(); - found = true; - const IfcFloat ys = std::max(bb.first.y,pmin.y), ye = std::min(bb.second.y,pmax.y); - if (ys - ylast) { - QuadrifyPart( IfcVector2(xs,ylast), IfcVector2(xe,ys) ,field,bbs,out); - } - - // the following are the window vertices - - /*wnd.push_back(IfcVector2(xs,ys)); - wnd.push_back(IfcVector2(xs,ye)); - wnd.push_back(IfcVector2(xe,ye)); - wnd.push_back(IfcVector2(xe,ys));*/ - ylast = ye; - } - } - if (!found) { - // the rectangle [pmin,pend] is opaque, fill it - out.push_back(IfcVector2(xs,pmin.y)); - out.push_back(IfcVector2(xs,pmax.y)); - out.push_back(IfcVector2(xe,pmax.y)); - out.push_back(IfcVector2(xe,pmin.y)); - return; - } - if (ylast < pmax.y) { - QuadrifyPart( IfcVector2(xs,ylast), IfcVector2(xe,pmax.y) ,field,bbs,out); - } - - // now for the whole rest - if (pmax.x-xe) { - QuadrifyPart(IfcVector2(xe,pmin.y), pmax ,field,bbs,out); - } -} - -// ------------------------------------------------------------------------------------------------ -void InsertWindowContours(const std::vector< BoundingBox >& bbs, - const std::vector< std::vector<IfcVector2> >& contours, - const std::vector<TempOpening>& /*openings*/, - const std::vector<IfcVector3>& /*nors*/, - const IfcMatrix3& minv, - const IfcVector2& scale, - const IfcVector2& offset, - IfcFloat coord, - TempMesh& curmesh) -{ - ai_assert(contours.size() == bbs.size()); - - // fix windows - we need to insert the real, polygonal shapes into the quadratic holes that we have now - for(size_t i = 0; i < contours.size();++i) { - const BoundingBox& bb = bbs[i]; - const std::vector<IfcVector2>& contour = contours[i]; - - // check if we need to do it at all - many windows just fit perfectly into their quadratic holes, - // i.e. their contours *are* already their bounding boxes. - if (contour.size() == 4) { - std::set<IfcVector2,XYSorter> verts; - for(size_t n = 0; n < 4; ++n) { - verts.insert(contour[n]); - } - const std::set<IfcVector2,XYSorter>::const_iterator end = verts.end(); - if (verts.find(bb.first)!=end && verts.find(bb.second)!=end - && verts.find(IfcVector2(bb.first.x,bb.second.y))!=end - && verts.find(IfcVector2(bb.second.x,bb.first.y))!=end - ) { - continue; + if(l < best_distance_squared) { + best_pair_offset = seg; + best_distance_squared = l; } } - const IfcFloat diag = (bb.first-bb.second).Length(); - const IfcFloat epsilon = diag/1000.f; + for (unsigned int seg = 0; seg < cnt_segments; ++seg) { - // walk through all contour points and find those that lie on the BB corner - size_t last_hit = -1, very_first_hit = -1; - IfcVector2 edge; - for(size_t n = 0, e=0, size = contour.size();; n=(n+1)%size, ++e) { + result.verts.push_back(points[ i * cnt_segments + (seg % cnt_segments)]); + result.verts.push_back(points[ i * cnt_segments + (seg + 1) % cnt_segments]); + result.verts.push_back(points[ (i+1) * cnt_segments + ((seg + 1 + best_pair_offset) % cnt_segments)]); + result.verts.push_back(points[ (i+1) * cnt_segments + ((seg + best_pair_offset) % cnt_segments)]); - // sanity checking - if (e == size*2) { - IFCImporter::LogError("encountered unexpected topology while generating window contour"); - break; - } + IfcVector3& v1 = *(result.verts.end()-1); + IfcVector3& v2 = *(result.verts.end()-2); + IfcVector3& v3 = *(result.verts.end()-3); + IfcVector3& v4 = *(result.verts.end()-4); - const IfcVector2& v = contour[n]; + if (((v4-v3) ^ (v4-v1)) * (v4 - curve_points[i]) < 0.0f) { + std::swap(v4, v1); + std::swap(v3, v2); + } - bool hit = false; - if (fabs(v.x-bb.first.x)<epsilon) { - edge.x = bb.first.x; - hit = true; - } - else if (fabs(v.x-bb.second.x)<epsilon) { - edge.x = bb.second.x; - hit = true; - } - - if (fabs(v.y-bb.first.y)<epsilon) { - edge.y = bb.first.y; - hit = true; - } - else if (fabs(v.y-bb.second.y)<epsilon) { - edge.y = bb.second.y; - hit = true; - } - - if (hit) { - if (last_hit != (size_t)-1) { - - const size_t old = curmesh.verts.size(); - size_t cnt = last_hit > n ? size-(last_hit-n) : n-last_hit; - for(size_t a = last_hit, e = 0; e <= cnt; a=(a+1)%size, ++e) { - // hack: this is to fix cases where opening contours are self-intersecting. - // Clipper doesn't produce such polygons, but as soon as we're back in - // our brave new floating-point world, very small distances are consumed - // by the maximum available precision, leading to self-intersecting - // polygons. This fix makes concave windows fail even worse, but - // anyway, fail is fail. - if ((contour[a] - edge).SquareLength() > diag*diag*0.7) { - continue; - } - const IfcVector3 v3 = minv * IfcVector3(offset.x + contour[a].x * scale.x, offset.y + contour[a].y * scale.y,coord); - curmesh.verts.push_back(v3); - } - - if (edge != contour[last_hit]) { - - IfcVector2 corner = edge; - - if (fabs(contour[last_hit].x-bb.first.x)<epsilon) { - corner.x = bb.first.x; - } - else if (fabs(contour[last_hit].x-bb.second.x)<epsilon) { - corner.x = bb.second.x; - } - - if (fabs(contour[last_hit].y-bb.first.y)<epsilon) { - corner.y = bb.first.y; - } - else if (fabs(contour[last_hit].y-bb.second.y)<epsilon) { - corner.y = bb.second.y; - } - - const IfcVector3 v3 = minv * IfcVector3(offset.x + corner.x * scale.x, offset.y + corner.y * scale.y,coord); - curmesh.verts.push_back(v3); - } - else if (cnt == 1) { - // avoid degenerate polygons (also known as lines or points) - curmesh.verts.erase(curmesh.verts.begin()+old,curmesh.verts.end()); - } - - if (const size_t d = curmesh.verts.size()-old) { - curmesh.vertcnt.push_back(d); - std::reverse(curmesh.verts.rbegin(),curmesh.verts.rbegin()+d); - } - if (n == very_first_hit) { - break; - } - } - else { - very_first_hit = n; - } - - last_hit = n; - } + result.vertcnt.push_back(4); } } -} - -// ------------------------------------------------------------------------------------------------ -void MergeContours (const std::vector<IfcVector2>& a, const std::vector<IfcVector2>& b, ClipperLib::ExPolygons& out) -{ - ClipperLib::Clipper clipper; - ClipperLib::Polygon clip; - - BOOST_FOREACH(const IfcVector2& pip, a) { - clip.push_back(ClipperLib::IntPoint( to_int64(pip.x), to_int64(pip.y) )); - } - - if (ClipperLib::Orientation(clip)) { - std::reverse(clip.begin(), clip.end()); - } - - clipper.AddPolygon(clip, ClipperLib::ptSubject); - clip.clear(); - - BOOST_FOREACH(const IfcVector2& pip, b) { - clip.push_back(ClipperLib::IntPoint( to_int64(pip.x), to_int64(pip.y) )); - } - if (ClipperLib::Orientation(clip)) { - std::reverse(clip.begin(), clip.end()); - } - - clipper.AddPolygon(clip, ClipperLib::ptSubject); - clipper.Execute(ClipperLib::ctUnion, out,ClipperLib::pftNonZero,ClipperLib::pftNonZero); + IFCImporter::LogDebug("generate mesh procedurally by sweeping a disk along a curve (IfcSweptDiskSolid)"); } // ------------------------------------------------------------------------------------------------ -bool TryAddOpenings_Quadrulate(const std::vector<TempOpening>& openings,const std::vector<IfcVector3>& nors, TempMesh& curmesh) +IfcMatrix3 DerivePlaneCoordinateSpace(const TempMesh& curmesh, bool& ok, IfcVector3& norOut) { - std::vector<IfcVector3>& out = curmesh.verts; - - // Try to derive a solid base plane within the current surface for use as - // working coordinate system. - const IfcMatrix3& m = DerivePlaneCoordinateSpace(curmesh); - const IfcMatrix3 minv = IfcMatrix3(m).Inverse(); - const IfcVector3& nor = IfcVector3(m.c1, m.c2, m.c3); - - IfcFloat coord = -1; - - std::vector<IfcVector2> contour_flat; - contour_flat.reserve(out.size()); - - IfcVector2 vmin, vmax; - MinMaxChooser<IfcVector2>()(vmin, vmax); - - // Move all points into the new coordinate system, collecting min/max verts on the way - BOOST_FOREACH(IfcVector3& x, out) { - const IfcVector3 vv = m * x; - - // keep Z offset in the plane coordinate system. Ignoring precision issues - // (which are present, of course), this should be the same value for - // all polygon vertices (assuming the polygon is planar). - - - // XXX this should be guarded, but we somehow need to pick a suitable - // epsilon - // if(coord != -1.0f) { - // assert(fabs(coord - vv.z) < 1e-3f); - // } - - coord = vv.z; - vmin = std::min(IfcVector2(vv.x, vv.y), vmin); - vmax = std::max(IfcVector2(vv.x, vv.y), vmax); - - contour_flat.push_back(IfcVector2(vv.x,vv.y)); - } - - // With the current code in DerivePlaneCoordinateSpace, - // vmin,vmax should always be the 0...1 rectangle (+- numeric inaccuracies) - // but here we won't rely on this. - - vmax -= vmin; - BOOST_FOREACH(IfcVector2& vv, contour_flat) { - vv.x = (vv.x - vmin.x) / vmax.x; - vv.y = (vv.y - vmin.y) / vmax.y; - } - - // project all points into the coordinate system defined by the p+sv*tu plane - // and compute bounding boxes for them - std::vector< BoundingBox > bbs; - std::vector< std::vector<IfcVector2> > contours; - - size_t c = 0; - BOOST_FOREACH(const TempOpening& t,openings) { - const IfcVector3& outernor = nors[c++]; - const IfcFloat dot = nor * outernor; - if (fabs(dot)<1.f-1e-6f) { - continue; - } - - const std::vector<IfcVector3>& va = t.profileMesh->verts; - if(va.size() <= 2) { - continue; - } - - IfcVector2 vpmin,vpmax; - MinMaxChooser<IfcVector2>()(vpmin,vpmax); - - std::vector<IfcVector2> contour; - - BOOST_FOREACH(const IfcVector3& x, t.profileMesh->verts) { - const IfcVector3 v = m * x; - - IfcVector2 vv(v.x, v.y); - - // rescale - vv.x = (vv.x - vmin.x) / vmax.x; - vv.y = (vv.y - vmin.y) / vmax.y; - - vpmin = std::min(vpmin,vv); - vpmax = std::max(vpmax,vv); - - contour.push_back(vv); - } - - BoundingBox bb = BoundingBox(vpmin,vpmax); - - // see if this BB intersects any other, in which case we could not use the Quadrify() - // algorithm and would revert to Poly2Tri only. - for (std::vector<BoundingBox>::iterator it = bbs.begin(); it != bbs.end();) { - const BoundingBox& ibb = *it; - - if (ibb.first.x < bb.second.x && ibb.second.x > bb.first.x && - ibb.first.y < bb.second.y && ibb.second.y > bb.second.x) { - - // take these two contours and try to merge them. If they overlap (which - // should not happen, but in fact happens-in-the-real-world [tm] ), - // resume using a single contour and a single bounding box. - const std::vector<IfcVector2>& other = contours[std::distance(bbs.begin(),it)]; + const std::vector<IfcVector3>& out = curmesh.verts; + IfcMatrix3 m; - ClipperLib::ExPolygons poly; - MergeContours(contour, other, poly); + ok = true; - if (poly.size() > 1) { - IFCImporter::LogWarn("cannot use quadrify algorithm to generate wall openings due to " - "bounding box overlaps, using poly2tri fallback"); - return TryAddOpenings_Poly2Tri(openings, nors, curmesh); - } - else if (poly.size() == 0) { - IFCImporter::LogWarn("ignoring duplicate opening"); - contour.clear(); - break; - } - else { - IFCImporter::LogDebug("merging oberlapping openings, this should not happen"); - - contour.clear(); - BOOST_FOREACH(const ClipperLib::IntPoint& point, poly[0].outer) { - contour.push_back( IfcVector2( from_int64(point.X), from_int64(point.Y))); - } + // The input "mesh" must be a single polygon + const size_t s = out.size(); + assert(curmesh.vertcnt.size() == 1 && curmesh.vertcnt.back() == s); - bb.first = std::min(bb.first, ibb.first); - bb.second = std::max(bb.second, ibb.second); + const IfcVector3 any_point = out[s-1]; + IfcVector3 nor; - contours.erase(contours.begin() + std::distance(bbs.begin(),it)); - it = bbs.erase(it); - continue; - } + // The input polygon is arbitrarily shaped, therefore we might need some tries + // until we find a suitable normal. Note that Newell's algorithm would give + // a more robust result, but this variant also gives us a suitable first + // axis for the 2D coordinate space on the polygon plane, exploiting the + // fact that the input polygon is nearly always a quad. + bool done = false; + size_t i, j; + for (i = 0; !done && i < s-2; done || ++i) { + for (j = i+1; j < s-1; ++j) { + nor = -((out[i]-any_point)^(out[j]-any_point)); + if(fabs(nor.Length()) > 1e-8f) { + done = true; + break; } - ++it; - } - - if(contour.size()) { - contours.push_back(contour); - bbs.push_back(bb); } } - if (bbs.empty()) { - return false; - } - - XYSortedField field; - for (std::vector<BoundingBox>::iterator it = bbs.begin(); it != bbs.end(); ++it) { - if (field.find((*it).first) != field.end()) { - IFCImporter::LogWarn("constraint failure during generation of wall openings, results may be faulty"); - } - field[(*it).first] = std::distance(bbs.begin(),it); + if(!done) { + ok = false; + return m; } - std::vector<IfcVector2> outflat; - outflat.reserve(openings.size()*4); - QuadrifyPart(IfcVector2(0.f,0.f),IfcVector2(1.f,1.f),field,bbs,outflat); - ai_assert(!(outflat.size() % 4)); - - std::vector<IfcVector3> vold; - std::vector<unsigned int> iold; - - vold.reserve(outflat.size()); - iold.reserve(outflat.size() / 4); - - // Fix the outer contour using polyclipper - try { - - ClipperLib::Polygon subject; - ClipperLib::Clipper clipper; - ClipperLib::ExPolygons clipped; - - ClipperLib::Polygon clip; - clip.reserve(contour_flat.size()); - BOOST_FOREACH(const IfcVector2& pip, contour_flat) { - clip.push_back(ClipperLib::IntPoint( to_int64(pip.x), to_int64(pip.y) )); - } - - if (!ClipperLib::Orientation(clip)) { - std::reverse(clip.begin(), clip.end()); - } + nor.Normalize(); + norOut = nor; - // We need to run polyclipper on every single quad -- we can't run it one all - // of them at once or it would merge them all together which would undo all - // previous steps - subject.reserve(4); - size_t cnt = 0; - BOOST_FOREACH(const IfcVector2& pip, outflat) { - subject.push_back(ClipperLib::IntPoint( to_int64(pip.x), to_int64(pip.y) )); - if (!(++cnt % 4)) { - if (!ClipperLib::Orientation(subject)) { - std::reverse(subject.begin(), subject.end()); - } - - clipper.AddPolygon(subject,ClipperLib::ptSubject); - clipper.AddPolygon(clip,ClipperLib::ptClip); - - clipper.Execute(ClipperLib::ctIntersection,clipped,ClipperLib::pftNonZero,ClipperLib::pftNonZero); - - BOOST_FOREACH(const ClipperLib::ExPolygon& ex, clipped) { - iold.push_back(ex.outer.size()); - BOOST_FOREACH(const ClipperLib::IntPoint& point, ex.outer) { - vold.push_back( minv * IfcVector3( - vmin.x + from_int64(point.X) * vmax.x, - vmin.y + from_int64(point.Y) * vmax.y, - coord)); - } - } + IfcVector3 r = (out[i]-any_point); + r.Normalize(); - subject.clear(); - clipped.clear(); - clipper.Clear(); - } - } + //if(d) { + // *d = -any_point * nor; + //} - assert(!(cnt % 4)); - } - catch (const char* sx) { - IFCImporter::LogError("Ifc: error during polygon clipping, contour line may be wrong: (Clipper: " - + std::string(sx) + ")"); + // Reconstruct orthonormal basis + // XXX use Gram Schmidt for increased robustness + IfcVector3 u = r ^ nor; + u.Normalize(); - iold.resize(outflat.size()/4,4); + m.a1 = r.x; + m.a2 = r.y; + m.a3 = r.z; - BOOST_FOREACH(const IfcVector2& vproj, outflat) { - const IfcVector3 v3 = minv * IfcVector3(vmin.x + vproj.x * vmax.x, vmin.y + vproj.y * vmax.y,coord); - vold.push_back(v3); - } - } + m.b1 = u.x; + m.b2 = u.y; + m.b3 = u.z; - // undo the projection, generate output quads - std::swap(vold,curmesh.verts); - std::swap(iold,curmesh.vertcnt); + m.c1 = -nor.x; + m.c2 = -nor.y; + m.c3 = -nor.z; - InsertWindowContours(bbs,contours,openings, nors,minv,vmax, vmin, coord, curmesh); - return true; + return m; } // ------------------------------------------------------------------------------------------------ -void ProcessExtrudedAreaSolid(const IfcExtrudedAreaSolid& solid, TempMesh& result, ConversionData& conv) +void ProcessExtrudedAreaSolid(const IfcExtrudedAreaSolid& solid, TempMesh& result, + ConversionData& conv, bool collect_openings) { TempMesh meshout; @@ -1409,7 +537,10 @@ void ProcessExtrudedAreaSolid(const IfcExtrudedAreaSolid& solid, TempMesh& resul IfcVector3 dir; ConvertDirection(dir,solid.ExtrudedDirection); - dir *= solid.Depth; + dir *= solid.Depth; /* + if(conv.collect_openings && !conv.apply_openings) { + dir *= 1000.0; + } */ // Outline: assuming that `meshout.verts` is now a list of vertex points forming // the underlying profile, extrude along the given axis, forming new @@ -1419,9 +550,9 @@ void ProcessExtrudedAreaSolid(const IfcExtrudedAreaSolid& solid, TempMesh& resul const size_t size=in.size(); const bool has_area = solid.SweptArea->ProfileType == "AREA" && size>2; - if(solid.Depth < 1e-3) { + if(solid.Depth < 1e-6) { if(has_area) { - meshout = result; + result = meshout; } return; } @@ -1432,9 +563,18 @@ void ProcessExtrudedAreaSolid(const IfcExtrudedAreaSolid& solid, TempMesh& resul // First step: transform all vertices into the target coordinate space IfcMatrix4 trafo; ConvertAxisPlacement(trafo, solid.Position); + + IfcVector3 vmin, vmax; + MinMaxChooser<IfcVector3>()(vmin, vmax); BOOST_FOREACH(IfcVector3& v,in) { v *= trafo; + + vmin = std::min(vmin, v); + vmax = std::max(vmax, v); } + + vmax -= vmin; + const IfcFloat diag = vmax.Length(); IfcVector3 min = in[0]; dir *= IfcMatrix3(trafo); @@ -1444,6 +584,7 @@ void ProcessExtrudedAreaSolid(const IfcExtrudedAreaSolid& solid, TempMesh& resul // Compute the normal vectors for all opening polygons as a prerequisite // to TryAddOpenings_Poly2Tri() + // XXX this belongs into the aforementioned function if (openings) { if (!conv.settings.useCustomTriangulation) { @@ -1451,7 +592,7 @@ void ProcessExtrudedAreaSolid(const IfcExtrudedAreaSolid& solid, TempMesh& resul // doesn't matter, but we would screw up if we started with e.g. a door in between // two windows. std::sort(conv.apply_openings->begin(),conv.apply_openings->end(), - DistanceSorter(min)); + TempOpening::DistanceSorter(min)); } nors.reserve(conv.apply_openings->size()); @@ -1483,7 +624,7 @@ void ProcessExtrudedAreaSolid(const IfcExtrudedAreaSolid& solid, TempMesh& resul out.push_back(in[next]); if(openings) { - if(TryAddOpenings_Quadrulate(*conv.apply_openings,nors,temp)) { + if((in[i]-in[next]).Length() > diag * 0.1 && GenerateOpenings(*conv.apply_openings,nors,temp,true, true, dir)) { ++sides_with_openings; } @@ -1491,6 +632,15 @@ void ProcessExtrudedAreaSolid(const IfcExtrudedAreaSolid& solid, TempMesh& resul temp.Clear(); } } + + if(openings) { + BOOST_FOREACH(TempOpening& opening, *conv.apply_openings) { + if (!opening.wallPoints.empty()) { + IFCImporter::LogError("failed to generate all window caps"); + } + opening.wallPoints.clear(); + } + } size_t sides_with_v_openings = 0; if(has_area) { @@ -1502,7 +652,7 @@ void ProcessExtrudedAreaSolid(const IfcExtrudedAreaSolid& solid, TempMesh& resul curmesh.vertcnt.push_back(size); if(openings && size > 2) { - if(TryAddOpenings_Quadrulate(*conv.apply_openings,nors,temp)) { + if(GenerateOpenings(*conv.apply_openings,nors,temp,true, true, dir)) { ++sides_with_v_openings; } @@ -1512,37 +662,33 @@ void ProcessExtrudedAreaSolid(const IfcExtrudedAreaSolid& solid, TempMesh& resul } } - - if(openings && ((sides_with_openings != 2 && sides_with_openings) || (sides_with_v_openings != 2 && sides_with_v_openings))) { + if(openings && ((sides_with_openings == 1 && sides_with_openings) || (sides_with_v_openings == 2 && sides_with_v_openings))) { IFCImporter::LogWarn("failed to resolve all openings, presumably their topology is not supported by Assimp"); } IFCImporter::LogDebug("generate mesh procedurally by extrusion (IfcExtrudedAreaSolid)"); -} + // If this is an opening element, store both the extruded mesh and the 2D profile mesh + // it was created from. Return an empty mesh to the caller. + if(collect_openings && !result.IsEmpty()) { + ai_assert(conv.collect_openings); + boost::shared_ptr<TempMesh> profile = boost::shared_ptr<TempMesh>(new TempMesh()); + profile->Swap(result); + boost::shared_ptr<TempMesh> profile2D = boost::shared_ptr<TempMesh>(new TempMesh()); + profile2D->Swap(meshout); + conv.collect_openings->push_back(TempOpening(&solid,dir,profile, profile2D)); + + ai_assert(result.IsEmpty()); + } +} // ------------------------------------------------------------------------------------------------ -void ProcessSweptAreaSolid(const IfcSweptAreaSolid& swept, TempMesh& meshout, ConversionData& conv) +void ProcessSweptAreaSolid(const IfcSweptAreaSolid& swept, TempMesh& meshout, + ConversionData& conv) { if(const IfcExtrudedAreaSolid* const solid = swept.ToPtr<IfcExtrudedAreaSolid>()) { - // Do we just collect openings for a parent element (i.e. a wall)? - // In this case we don't extrude the surface yet, just keep the profile and transform it correctly - if(conv.collect_openings) { - boost::shared_ptr<TempMesh> meshtmp(new TempMesh()); - ProcessProfile(swept.SweptArea,*meshtmp,conv); - - IfcMatrix4 m; - ConvertAxisPlacement(m,solid->Position); - meshtmp->Transform(m); - - IfcVector3 dir; - ConvertDirection(dir,solid->ExtrudedDirection); - conv.collect_openings->push_back(TempOpening(solid, IfcMatrix3(m) * (dir*static_cast<IfcFloat>(solid->Depth)),meshtmp)); - return; - } - - ProcessExtrudedAreaSolid(*solid,meshout,conv); + ProcessExtrudedAreaSolid(*solid,meshout,conv, !!conv.collect_openings); } else if(const IfcRevolvedAreaSolid* const rev = swept.ToPtr<IfcRevolvedAreaSolid>()) { ProcessRevolvedAreaSolid(*rev,meshout,conv); @@ -1552,165 +698,19 @@ void ProcessSweptAreaSolid(const IfcSweptAreaSolid& swept, TempMesh& meshout, Co } } - -// ------------------------------------------------------------------------------------------------ -enum Intersect { - Intersect_No, - Intersect_LiesOnPlane, - Intersect_Yes -}; - // ------------------------------------------------------------------------------------------------ -Intersect IntersectSegmentPlane(const IfcVector3& p,const IfcVector3& n, const IfcVector3& e0, const IfcVector3& e1, IfcVector3& out) +bool ProcessGeometricItem(const IfcRepresentationItem& geo, std::vector<unsigned int>& mesh_indices, + ConversionData& conv) { - const IfcVector3 pdelta = e0 - p, seg = e1-e0; - const IfcFloat dotOne = n*seg, dotTwo = -(n*pdelta); - - if (fabs(dotOne) < 1e-6) { - return fabs(dotTwo) < 1e-6f ? Intersect_LiesOnPlane : Intersect_No; - } - - const IfcFloat t = dotTwo/dotOne; - // t must be in [0..1] if the intersection point is within the given segment - if (t > 1.f || t < 0.f) { - return Intersect_No; - } - out = e0+t*seg; - return Intersect_Yes; -} - -// ------------------------------------------------------------------------------------------------ -void ProcessBoolean(const IfcBooleanResult& boolean, TempMesh& result, ConversionData& conv) -{ - if(const IfcBooleanResult* const clip = boolean.ToPtr<IfcBooleanResult>()) { - if(clip->Operator != "DIFFERENCE") { - IFCImporter::LogWarn("encountered unsupported boolean operator: " + (std::string)clip->Operator); - return; - } - - TempMesh meshout; - const IfcHalfSpaceSolid* const hs = clip->SecondOperand->ResolveSelectPtr<IfcHalfSpaceSolid>(conv.db); - if(!hs) { - IFCImporter::LogError("expected IfcHalfSpaceSolid as second clipping operand"); - return; - } - - const IfcPlane* const plane = hs->BaseSurface->ToPtr<IfcPlane>(); - if(!plane) { - IFCImporter::LogError("expected IfcPlane as base surface for the IfcHalfSpaceSolid"); - return; - } - - if(const IfcBooleanResult* const op0 = clip->FirstOperand->ResolveSelectPtr<IfcBooleanResult>(conv.db)) { - ProcessBoolean(*op0,meshout,conv); - } - else if (const IfcSweptAreaSolid* const swept = clip->FirstOperand->ResolveSelectPtr<IfcSweptAreaSolid>(conv.db)) { - ProcessSweptAreaSolid(*swept,meshout,conv); - } - else { - IFCImporter::LogError("expected IfcSweptAreaSolid or IfcBooleanResult as first clipping operand"); - return; - } - - // extract plane base position vector and normal vector - IfcVector3 p,n(0.f,0.f,1.f); - if (plane->Position->Axis) { - ConvertDirection(n,plane->Position->Axis.Get()); - } - ConvertCartesianPoint(p,plane->Position->Location); - - if(!IsTrue(hs->AgreementFlag)) { - n *= -1.f; - } - - // clip the current contents of `meshout` against the plane we obtained from the second operand - const std::vector<IfcVector3>& in = meshout.verts; - std::vector<IfcVector3>& outvert = result.verts; - std::vector<unsigned int>::const_iterator begin=meshout.vertcnt.begin(), end=meshout.vertcnt.end(), iit; - - outvert.reserve(in.size()); - result.vertcnt.reserve(meshout.vertcnt.size()); - - unsigned int vidx = 0; - for(iit = begin; iit != end; vidx += *iit++) { - - unsigned int newcount = 0; - for(unsigned int i = 0; i < *iit; ++i) { - const IfcVector3& e0 = in[vidx+i], e1 = in[vidx+(i+1)%*iit]; - - // does the next segment intersect the plane? - IfcVector3 isectpos; - const Intersect isect = IntersectSegmentPlane(p,n,e0,e1,isectpos); - if (isect == Intersect_No || isect == Intersect_LiesOnPlane) { - if ( (e0-p).Normalize()*n > 0 ) { - outvert.push_back(e0); - ++newcount; - } - } - else if (isect == Intersect_Yes) { - if ( (e0-p).Normalize()*n > 0 ) { - // e0 is on the right side, so keep it - outvert.push_back(e0); - outvert.push_back(isectpos); - newcount += 2; - } - else { - // e0 is on the wrong side, so drop it and keep e1 instead - outvert.push_back(isectpos); - ++newcount; - } - } - } - - if (!newcount) { - continue; - } - - IfcVector3 vmin,vmax; - ArrayBounds(&*(outvert.end()-newcount),newcount,vmin,vmax); - - // filter our IfcFloat points - those may happen if a point lies - // directly on the intersection line. However, due to IfcFloat - // precision a bitwise comparison is not feasible to detect - // this case. - const IfcFloat epsilon = (vmax-vmin).SquareLength() / 1e6f; - FuzzyVectorCompare fz(epsilon); - - std::vector<IfcVector3>::iterator e = std::unique( outvert.end()-newcount, outvert.end(), fz ); - if (e != outvert.end()) { - newcount -= static_cast<unsigned int>(std::distance(e,outvert.end())); - outvert.erase(e,outvert.end()); - } - if (fz(*( outvert.end()-newcount),outvert.back())) { - outvert.pop_back(); - --newcount; - } - if(newcount > 2) { - result.vertcnt.push_back(newcount); - } - else while(newcount-->0)result.verts.pop_back(); - - } - IFCImporter::LogDebug("generating CSG geometry by plane clipping (IfcBooleanClippingResult)"); - } - else { - IFCImporter::LogWarn("skipping unknown IfcBooleanResult entity, type is " + boolean.GetClassName()); - } -} - - - -// ------------------------------------------------------------------------------------------------ -bool ProcessGeometricItem(const IfcRepresentationItem& geo, std::vector<unsigned int>& mesh_indices, ConversionData& conv) -{ - TempMesh meshtmp; + bool fix_orientation = true; + boost::shared_ptr< TempMesh > meshtmp = boost::make_shared<TempMesh>(); if(const IfcShellBasedSurfaceModel* shellmod = geo.ToPtr<IfcShellBasedSurfaceModel>()) { BOOST_FOREACH(boost::shared_ptr<const IfcShell> shell,shellmod->SbsmBoundary) { try { const EXPRESS::ENTITY& e = shell->To<ENTITY>(); const IfcConnectedFaceSet& fs = conv.db.MustGetObject(e).To<IfcConnectedFaceSet>(); - ProcessConnectedFaceSet(fs,meshtmp,conv); + ProcessConnectedFaceSet(fs,*meshtmp.get(),conv); } catch(std::bad_cast&) { IFCImporter::LogWarn("unexpected type error, IfcShell ought to inherit from IfcConnectedFaceSet"); @@ -1718,21 +718,25 @@ bool ProcessGeometricItem(const IfcRepresentationItem& geo, std::vector<unsigned } } else if(const IfcConnectedFaceSet* fset = geo.ToPtr<IfcConnectedFaceSet>()) { - ProcessConnectedFaceSet(*fset,meshtmp,conv); + ProcessConnectedFaceSet(*fset,*meshtmp.get(),conv); } else if(const IfcSweptAreaSolid* swept = geo.ToPtr<IfcSweptAreaSolid>()) { - ProcessSweptAreaSolid(*swept,meshtmp,conv); + ProcessSweptAreaSolid(*swept,*meshtmp.get(),conv); + } + else if(const IfcSweptDiskSolid* disk = geo.ToPtr<IfcSweptDiskSolid>()) { + ProcessSweptDiskSolid(*disk,*meshtmp.get(),conv); + fix_orientation = false; } else if(const IfcManifoldSolidBrep* brep = geo.ToPtr<IfcManifoldSolidBrep>()) { - ProcessConnectedFaceSet(brep->Outer,meshtmp,conv); + ProcessConnectedFaceSet(brep->Outer,*meshtmp.get(),conv); } else if(const IfcFaceBasedSurfaceModel* surf = geo.ToPtr<IfcFaceBasedSurfaceModel>()) { BOOST_FOREACH(const IfcConnectedFaceSet& fc, surf->FbsmFaces) { - ProcessConnectedFaceSet(fc,meshtmp,conv); + ProcessConnectedFaceSet(fc,*meshtmp.get(),conv); } } else if(const IfcBooleanResult* boolean = geo.ToPtr<IfcBooleanResult>()) { - ProcessBoolean(*boolean,meshtmp,conv); + ProcessBoolean(*boolean,*meshtmp.get(),conv); } else if(geo.ToPtr<IfcBoundingBox>()) { // silently skip over bounding boxes @@ -1743,10 +747,35 @@ bool ProcessGeometricItem(const IfcRepresentationItem& geo, std::vector<unsigned return false; } - meshtmp.RemoveAdjacentDuplicates(); - FixupFaceOrientation(meshtmp); + // Do we just collect openings for a parent element (i.e. a wall)? + // In such a case, we generate the polygonal mesh as usual, + // but attach it to a TempOpening instance which will later be applied + // to the wall it pertains to. + + // Note: swep area solids are added in ProcessExtrudedAreaSolid(), + // which returns an empty mesh. + if(conv.collect_openings) { + if (!meshtmp->IsEmpty()) { + conv.collect_openings->push_back(TempOpening(geo.ToPtr<IfcSolidModel>(), + IfcVector3(0,0,0), + meshtmp, + boost::shared_ptr<TempMesh>())); + } + return true; + } + + if (meshtmp->IsEmpty()) { + return false; + } + + meshtmp->RemoveAdjacentDuplicates(); + meshtmp->RemoveDegenerates(); + + if(fix_orientation) { + meshtmp->FixupFaceOrientation(); + } - aiMesh* const mesh = meshtmp.ToMesh(); + aiMesh* const mesh = meshtmp->ToMesh(); if(mesh) { mesh->mMaterialIndex = ProcessMaterials(geo,conv); mesh_indices.push_back(conv.meshes.size()); @@ -1757,7 +786,8 @@ bool ProcessGeometricItem(const IfcRepresentationItem& geo, std::vector<unsigned } // ------------------------------------------------------------------------------------------------ -void AssignAddedMeshes(std::vector<unsigned int>& mesh_indices,aiNode* nd,ConversionData& /*conv*/) +void AssignAddedMeshes(std::vector<unsigned int>& mesh_indices,aiNode* nd, + ConversionData& /*conv*/) { if (!mesh_indices.empty()) { @@ -1776,7 +806,9 @@ void AssignAddedMeshes(std::vector<unsigned int>& mesh_indices,aiNode* nd,Conver } // ------------------------------------------------------------------------------------------------ -bool TryQueryMeshCache(const IfcRepresentationItem& item, std::vector<unsigned int>& mesh_indices, ConversionData& conv) +bool TryQueryMeshCache(const IfcRepresentationItem& item, + std::vector<unsigned int>& mesh_indices, + ConversionData& conv) { ConversionData::MeshCache::const_iterator it = conv.cached_meshes.find(&item); if (it != conv.cached_meshes.end()) { @@ -1787,13 +819,17 @@ bool TryQueryMeshCache(const IfcRepresentationItem& item, std::vector<unsigned i } // ------------------------------------------------------------------------------------------------ -void PopulateMeshCache(const IfcRepresentationItem& item, const std::vector<unsigned int>& mesh_indices, ConversionData& conv) +void PopulateMeshCache(const IfcRepresentationItem& item, + const std::vector<unsigned int>& mesh_indices, + ConversionData& conv) { conv.cached_meshes[&item] = mesh_indices; } // ------------------------------------------------------------------------------------------------ -bool ProcessRepresentationItem(const IfcRepresentationItem& item, std::vector<unsigned int>& mesh_indices, ConversionData& conv) +bool ProcessRepresentationItem(const IfcRepresentationItem& item, + std::vector<unsigned int>& mesh_indices, + ConversionData& conv) { if (!TryQueryMeshCache(item,mesh_indices,conv)) { if(ProcessGeometricItem(item,mesh_indices,conv)) { @@ -1806,9 +842,6 @@ bool ProcessRepresentationItem(const IfcRepresentationItem& item, std::vector<un return true; } -#undef to_int64 -#undef from_int64 -#undef from_int64_f } // ! IFC } // ! Assimp |