diff --git a/source/MRMesh/MR2DContoursTriangulation.cpp b/source/MRMesh/MR2DContoursTriangulation.cpp index ec582487446d..367938c60ade 100644 --- a/source/MRMesh/MR2DContoursTriangulation.cpp +++ b/source/MRMesh/MR2DContoursTriangulation.cpp @@ -1978,7 +1978,9 @@ static bool setLoopPredicates( SweepLinePredicates& p, LoopPoints& lp, const Mes // two vertices defined alike make the predicates fail only if the sweep compares them, unless the shifts of their edges tell them apart // (as the crossings of the edges of a multiple edge of the other mesh with their wedges), so every two of them are compared before // the sweep, and the loops are rejected if that fails: a vertex point by its id, a crossing by the ids of its segment and triangle - // in any order (of its two triangles for a crossing of two cuts), with the index of the point + // in any order (of its two triangles for a crossing of two cuts), with the index of the point; a crossing of two cuts by triangles + // with a common edge, defined alike with the crossings of that edge, is keyed by its triangles, so its comparisons with them come + // in the sweep, where less stays a strict weak order and the failure is still found Vector, int>> keys( verts.size() ); for ( int i = 0; i < verts.size(); ++i ) { diff --git a/source/MRMesh/MRCutTrianglePredicates.cpp b/source/MRMesh/MRCutTrianglePredicates.cpp index 7b1fc9649ed8..6fb8b14e765c 100644 --- a/source/MRMesh/MRCutTrianglePredicates.cpp +++ b/source/MRMesh/MRCutTrianglePredicates.cpp @@ -281,25 +281,32 @@ SosPolyOf sosCoord( const PointDegree & v, int i ) return SosPolyOf( std::move( terms ) ); } -/// the polynomial with the coefficients converted into 256 bits -SosPoly256 widen( const SosPolyOf & p ) +/// the default degree cap of the functions below: all terms, known at compile time, so that their default paths compare no degrees (see mulAs) +using AllDegrees = std::integral_constant; + +/// the polynomial with the coefficients converted into To, which hold them, without the terms of degrees above an integer maxDeg +template +SosPolyOf convertPoly( const SosPolyOf & p, MaxDeg maxDeg = {} ) { - std::vector terms; + static_assert( std::is_integral_v || std::is_same_v ); // no other cap at compile time + std::vector::Term> terms; terms.reserve( p.get().size() ); for ( const auto & [deg, c] : p.get() ) - terms.emplace_back( deg, FastInt256( c ) ); - return SosPoly256( std::move( terms ) ); + { + if constexpr ( std::is_integral_v ) + { + if ( deg > maxDeg ) + break; + } + terms.emplace_back( deg, To( c ) ); + } + return SosPolyOf( std::move( terms ) ); } /// the product of two polynomials whose coefficients fit in 256 bits, as the bounds of the caller prove SosPoly256 mul256( const SosPoly256 & a, const SosPoly256 & b ) { - const auto p = mulAs( a, b ); - std::vector terms; - terms.reserve( p.get().size() ); - for ( const auto & [deg, c] : p.get() ) - terms.emplace_back( deg, FastInt256( c ) ); - return SosPoly256( std::move( terms ) ); + return convertPoly( mulAs( a, b ) ); } // the perturbed vectors of the directions of segments and lines, which only the rare points with zero exact directions need; @@ -322,12 +329,12 @@ SosVec sub( const SosVec & a, const SosVec & b ) return { a[0] - b[0], a[1] - b[1], a[2] - b[2] }; } -/// the cross product, with the coefficients converted into T before multiplication -template -auto cross( const SosVec & a, const SosVec & b ) +/// the cross product, with the coefficients converted into T before multiplication, without the terms of degrees above an integer maxDeg +template +auto cross( const SosVec & a, const SosVec & b, MaxDeg maxDeg = {} ) { - return std::array{ mulAs( a[1], b[2] ) - mulAs( a[2], b[1] ), mulAs( a[2], b[0] ) - mulAs( a[0], b[2] ), - mulAs( a[0], b[1] ) - mulAs( a[1], b[0] ) }; + return std::array{ mulAs( a[1], b[2], maxDeg ) - mulAs( a[2], b[1], maxDeg ), mulAs( a[2], b[0], maxDeg ) - mulAs( a[0], b[2], maxDeg ), + mulAs( a[0], b[1], maxDeg ) - mulAs( a[1], b[0], maxDeg ) }; } /// the vertices of a predicate perturbed at stage s (see PerturbationStagesOf), or with only the vertex of stage s perturbed (alone): @@ -376,9 +383,9 @@ SosCrossing sosCrossing( const Stage & st, const SosPointVerts & v ) const auto nt = sosNormal( st, i[0], i[1], i[2] ); const auto nP = sosNormal( st, i[3], i[4], i[5] ); const auto nQ = sosNormal( st, i[6], i[7], i[8] ); - const auto at = widen( sosOffset( st, nt, i[0] ) ); - const auto aP = widen( sosOffset( st, nP, i[3] ) ); - const auto aQ = widen( sosOffset( st, nQ, i[6] ) ); + const auto at = convertPoly( sosOffset( st, nt, i[0] ) ); + const auto aP = convertPoly( sosOffset( st, nP, i[3] ) ); + const auto aQ = convertPoly( sosOffset( st, nQ, i[6] ) ); const auto cPQ = cross( nP, nQ ); const auto cQt = cross( nQ, nt ); const auto ctP = cross( nt, nP ); @@ -386,7 +393,7 @@ SosCrossing sosCrossing( const Stage & st, const SosPointVerts & v ) for ( int k = 0; k < 3; ++k ) { res.n[k] = mul256( at, cPQ[k] ) + mul256( aP, cQt[k] ) + mul256( aQ, ctP[k] ); - res.d += mul256( widen( nt[k] ), cPQ[k] ); + res.d += mul256( convertPoly( nt[k] ), cPQ[k] ); } return res; } @@ -445,7 +452,7 @@ std::optional sosPoint( const PreciseCutPoint & p, const Stage & st // and a coefficient of a product sums at most two products of them res.nx = mulAs( oa, sosCoord( b, kx ) ) - mulAs( ob, sosCoord( a, kx ) ); res.ny = mulAs( oa, sosCoord( b, ky ) ) - mulAs( ob, sosCoord( a, ky ) ); - res.d = widen( oa - ob ); + res.d = convertPoly( oa - ob ); if ( res.d.empty() ) return {}; } @@ -860,8 +867,35 @@ struct CutPoint ExactCoords exact; // found once in addPoint, since a sort compares the same points many times where their rounded coordinates cannot decide int sides = 0; // bit i is set if the point is on side i of the triangle, from vertex i to vertex i+1 int crossing = -1; // the index of the data of a crossing of two cuts, whose exact coordinates are not in exact + // a crossing of two cuts by triangles with a common edge, kept as the crossing of that edge (def) moved by its own shift, + // with the third vertices of the triangles of its two cuts + bool delta = false; + std::array thirds{}; }; +/// whether the vertices of t have valid distinct ids +bool distinctIds( const std::array & t ) +{ + return t[0].id.valid() && t[1].id.valid() && t[2].id.valid() && t[0].id != t[1].id && t[1].id != t[2].id && t[2].id != t[0].id; +} + +/// for a crossing of two cuts by distinct triangles with exactly two common vertices a, b, the crossing of segment ab with triangle t, +/// which the crossing of the cuts is before the shifts; nullopt otherwise +std::optional commonEdgeCrossing( const PreciseCutPoint & x, const std::array & t ) +{ + if ( !distinctIds( x.tri ) || !distinctIds( x.tri2 ) ) + return {}; + PreciseCutPoint res; + int num = 0; + for ( const auto & v : x.tri ) + if ( hasVert( x.tri2, v.id ) && num < 2 ) + res.seg[num++] = v; + if ( num != 2 || sameTriangle( x.tri, x.tri2 ) ) + return {}; + res.tri = t; + return res; +} + /// whether point x, not a vertex, is on the plane of triangle t by its definition: a crossing of a side with t, a crossing of an edge of t /// with the cut triangle, or a crossing of two cuts, one of them by t bool onPlane( const std::array & t, const CutPoint & x ) @@ -927,6 +961,18 @@ MR_FORCE_INLINE int compareExactCoord( const ExactCoords & a, const ExactCoords return l < r ? -1 : ( r < l ? 1 : 0 ); } +/// what the shift of a point defined alike with others is found from, exact and perturbed (see CutTrianglePredicates::shift_ and sosShift): +/// for the crossing of an edge, its wedge w[0], w[1] and whether it moves away from it; for a crossing of the cuts by P and Q at their common +/// edge, the wedges w[0], w[1] and w[2], w[3] of the crossings X_P and X_Q of the edges of P and Q, whether they move away from them, +/// and the third vertices of P and Q +struct ShiftDef +{ + std::array w; + std::array away{}; + std::array thirds; + bool delta = false; +}; + } // anonymous namespace struct CutTrianglePredicates::Impl @@ -968,13 +1014,293 @@ struct CutTrianglePredicates::Impl }; /// the shift of the edge of a point defined alike with others (see CutTrianglePredicates): x and y are the projected coordinates -/// of the direction in which the point moves, times scale > 0, which is the same for all points defined alike +/// of the direction in which the point moves, times scale = |n.d| (see shift_), which is the same for all points defined alike, +/// and 0 for a segment in the plane of the triangle, along which they move then struct CutTrianglePredicates::Shift { - FastInt256 x, y; + // the position ( x, y ) / den among the points defined alike, which share the scale; den is 1 for the crossing of an edge, + // and |det( d, p, q )| for a crossing of two cuts (see shift_), or 0 if only the perturbed shift tells + FastInt512 x, y; + FastInt256 den; FastInt128 scale; + ShiftDef def; // what the perturbed shift is found from +}; + +namespace +{ + +/// the difference of two shifts with the numerators over the product of their denominators +struct DiffTerm +{ + FastInt<768> x, y; }; +/// q - p for two shifts of points defined alike, over p.den * q.den > 0 +template +DiffTerm shiftDiff( const S & p, const S & q ) +{ + return { q.x * p.den - p.x * q.den, q.y * p.den - p.y * q.den }; +} + +/// whether edge crossing p moves away from its wedge: if the triangles of another point defined alike are in its angle +/// (see CutTrianglePredicates::shift_); found only here, since points defined alike are rare +template +bool awayOf( const Points & points, VertId p ) +{ + const auto & def = points[p].def; + for ( auto x = points.beginId(); x < points.endId(); ++x ) + if ( x != p && points[x].sides == 0 && hasWedge( points[x].def ) && definedAlike( def, points[x].def ) && nestedIn( def, points[x].def ) ) + return true; + return false; +} + +/// b - a for the segment ab of a point, or for a segment of zero length the leading term of its perturbed direction: +/// the z, y, x coordinates of the end with the smaller id come first (as in orient3d), with the sign of that end in b - a +Vector3i64 shiftSegment( const PreciseCutPoint & def ) +{ + const auto d = Vector3i64( def.seg[1].pt ) - Vector3i64( def.seg[0].pt ); + if ( d != Vector3i64() ) + return d; + return Vector3i64( 0, 0, def.seg[1].id < def.seg[0].id ? 1 : -1 ); +} + +/// the sign of the perturbed n.d for the normal n of triangle t and the segment ab of a point, which crosses its plane: that of n.( b - t0 ), +/// as orient3dVolume( t0, t1, t2, x ) = -n.( x - t0 ) +int ndSignOf( const std::array & t, const PreciseCutPoint & def ) +{ + return orient3d( { t[0], t[1], t[2], def.seg[1] } ) ? -1 : 1; +} + +/// finds the crossings X_P and X_Q of the edges ab of the cut triangles P and Q of crossing p of two cuts at their common edge ab +/// (see CutTrianglePredicates::shift_), as the edge crossings defined alike with the wedge that has the third vertex of the cut, which have +/// shifts of their own, since all crossings of edges with wedges off the sides have; false if they are not found, or not unique +template +bool deltaEdges( const Points & points, VertId p, std::array & xs ) +{ + const auto & pt = points[p]; + for ( int k = 0; k < 2; ++k ) + { + int num = 0; + for ( auto x = points.beginId(); x < points.endId(); ++x ) + { + const auto & y = points[x]; + if ( x == p || y.delta || y.sides != 0 || !hasWedge( y.def ) || !definedAlike( pt.def, y.def ) ) + continue; + if ( y.def.wedge[0].id == pt.thirds[k].id || y.def.wedge[1].id == pt.thirds[k].id ) + { + xs[k] = x; + ++num; + } + } + if ( num != 1 ) + return false; + } + return xs[0] != xs[1]; +} + +/// the definition of the shift of point p, or nullopt if it has none (see CutTrianglePredicates::shift_) +template +std::optional shiftDefOf( const Points & points, VertId p ) +{ + const auto & pt = points[p]; + ShiftDef res; + if ( pt.delta ) + { + std::array xs; + if ( !deltaEdges( points, p, xs ) ) + return {}; + res.thirds = pt.thirds; + for ( int k = 0; k < 2; ++k ) + { + res.w[2 * k] = points[xs[k]].def.wedge[0]; + res.w[2 * k + 1] = points[xs[k]].def.wedge[1]; + res.away[k] = awayOf( points, xs[k] ); + } + res.delta = true; + return res; + } + const auto & def = pt.def; + // the segment of a crossing of a side is that side, and a crossing of two cuts has no segment + if ( def.isVertex() || def.isCrossing() || pt.sides != 0 || !hasWedge( def ) ) + return {}; + res.w[0] = def.wedge[0]; + res.w[1] = def.wedge[1]; + res.away[0] = awayOf( points, p ); + return res; +} + +using SosPolyW = SosPolyOf; + +/// the indices among those of SosVerts of the vertices of the cut triangle and of the segment ab of the points defined alike +struct GroupVerts +{ + std::array t{}; + std::array ab{}; +}; + +/// the indices among those of SosVerts of the vertices of a shift +struct ShiftVerts +{ + std::array w{}; + std::array thirds{}; +}; + +/// adds the vertices of the numerator and the denominator of shift s (see sosShift) with the bounds of their weights in one product +/// with each of them: n x ( u x d ) takes one coordinate of each of u and d and two of the normal of the triangle (see sosNormal); the numerator +/// of a crossing of two cuts takes up to five coordinates of a, three of b and two of each third vertex, and its denominator three of a +/// and one of b and of each third vertex +ShiftVerts addShift( SosVerts & r, const std::array & tri, const std::array & ab, const ShiftDef & s, + GroupVerts & g ) +{ + g.t = { r.add( tri[0], 12 ), r.add( tri[1], 9 ), r.add( tri[2], 9 ) }; + g.ab = { r.add( ab[0], s.delta ? 72 : 18 ), r.add( ab[1], s.delta ? 36 : 18 ) }; + ShiftVerts res; + for ( int k = 0; k < ( s.delta ? 4 : 2 ); ++k ) + res.w[k] = r.add( s.w[k], 9 ); + if ( s.delta ) + for ( int k = 0; k < 2; ++k ) + res.thirds[k] = r.add( s.thirds[k], 27 ); + return res; +} + +/// the perturbed shift of a point defined alike with others: num / ( ( n.d ) * c ) with the projected numerator num; +/// c is 1 for the crossing of an edge +struct SosShift +{ + std::array num; + SosPolyW c; +}; + +/// the perturbed shift of a point at stage st without the terms of degrees above maxDeg, with the vertices v of its definition s +/// and g of the cut triangle and the segment ab: for the crossing of an edge, the numerator is n x ( u x d ) for d = b - a and the signed +/// wedge vector u (see CutTrianglePredicates::shift_); for a crossing of two cuts, ( n x ( uP x d ) ) * det( d, p, q ) + ( n x ( d x p ) ) * det( uQ - uP, d, q ), +/// with c = det( d, p, q ) (see CutTrianglePredicates::shift_); the coefficients of the numerators below 2^63 * 2 * 2^33 * 2^31 * 2 < 2^130 +/// for the crossing of an edge, and 2^130 * 3 * 2^63 * 2^31 + 2 * 2^63 * 2^63 * 3 * 2^63 * 2^34 < 2^228 for a crossing of two cuts (see SosVec) +SosShift sosShift( const Stage & st, const GroupVerts & g, const ShiftDef & s, const ShiftVerts & v, int kx, int ky, std::int64_t maxDeg ) +{ + const auto n = sosNormal( st, g.t[0], g.t[1], g.t[2] ); + const auto a = sosCoords( st.at( g.ab[0] ) ); + const auto d = sub( sosCoords( st.at( g.ab[1] ) ), a ); + const auto ab = std::array{ a[0] + a[0] + d[0], a[1] + a[1] + d[1], a[2] + a[2] + d[2] }; + auto wedge = [&] ( int k ) + { + const auto w0 = sosCoords( st.at( v.w[2 * k] ) ), w1 = sosCoords( st.at( v.w[2 * k + 1] ) ); + const auto u = sub( std::array{ w0[0] + w1[0], w0[1] + w1[1], w0[2] + w1[2] }, ab ); + return s.away[k] ? sub( SosVec{}, u ) : u; + }; + auto numOf = [&] ( const SosVec & u ) { return cross( n, cross( u, d, maxDeg ), maxDeg ); }; + SosShift res; + if ( !s.delta ) + { + const auto S = numOf( wedge( 0 ) ); + res.num = { convertPoly( S[kx] ), convertPoly( S[ky] ) }; + res.c = SosPolyW( std::vector{ { 0, FastInt512( 1 ) } } ); + return res; + } + const auto uP = wedge( 0 ), uQ = wedge( 1 ); + const auto p = sub( sosCoords( st.at( v.thirds[0] ) ), a ), q = sub( sosCoords( st.at( v.thirds[1] ) ), a ); + const auto nP = cross( d, p, maxDeg ), nQ = cross( d, q, maxDeg ); + auto dot = [&] ( const SosVec & x, const SosVec & y ) + { + return mulAs( x[0], y[0], maxDeg ) + mulAs( x[1], y[1], maxDeg ) + mulAs( x[2], y[2], maxDeg ); + }; + const auto c = dot( nP, q ), k = dot( nQ, sub( uQ, uP ) ); + const auto tP = cross( n, nP, maxDeg ); + const auto S = numOf( uP ); + res.num = { mulAs( S[kx], c, maxDeg ) + mulAs( tP[kx], k, maxDeg ), + mulAs( S[ky], c, maxDeg ) + mulAs( tP[ky], k, maxDeg ) }; + res.c = convertPoly( c ); + return res; +} + +/// the first value that f( shifts, x, maxDeg ) gives at the stages of the perturbation of the vertices of the cut triangle tri, +/// of the segment ab of the points defined alike, of the shifts defs, each taken uses[i] times in a product of the predicate, and of the points pts, +/// as SosFraction x (see sosPoint); at every stage, the shifts and the points are found without the terms of degrees above maxDeg, +/// which keeps their other terms, from 0 up to the largest degree of the stage, since the polynomials of all vertices are too big to multiply, +/// and f gives a value only from a term not above maxDeg; a stage where the denominator of a shift or of a point is zero is skipped, +/// since every polynomial keeps its leading term at the later stages; the empty value if none; cutShort, if given, tells whether the stages +/// end before the first one whose degrees do not fit in int64 (see SosStages), after which the empty value may hide a later term +template +auto sosAlike( const std::array & tri, const std::array & ab, int kx, int ky, + const std::array & defs, const std::array & uses, const std::array & pts, const F & f, + bool * cutShort = nullptr ) +{ + SosVerts r; + GroupVerts g; + std::array v; + for ( int i = 0; i < N; ++i ) + for ( int k = 0; k < uses[i]; ++k ) + v[i] = addShift( r, tri, ab, *defs[i], g ); + std::array pv; + for ( int i = 0; i < M; ++i ) + pv[i] = r.add( *pts[i], tri ); + const auto ps = r.stages(); + if ( cutShort ) + *cutShort = ps.numStages() < r.num; + using Res = decltype( f( std::array{}, std::array{}, std::int64_t{} ) ); + std::int64_t lowest = 0; // the polynomial of f has no terms below it: it was zero at the last stage with all shifts and points defined + return ps.firstStage( [&] ( int s ) -> Res + { + const Stage st{ ps, s }; + std::array full; + for ( int i = 0; i < M; ++i ) + { + auto o = sosPoint( *pts[i], st, pv[i], kx, ky ); + if ( !o ) + return {}; + full[i] = std::move( *o ); + } + // every term of the stage has a degree below the place of the next one (see PerturbationStagesOf) + const std::int64_t top = s < ps.numStages() ? ps.place( s + 1 ) : cMaxPolyDAll; + for ( std::int64_t maxDeg = lowest;; maxDeg = maxDeg == 0 ? 1 : ( maxDeg > top / 4 ? top : 4 * maxDeg ) ) + { + std::array sh; + bool defined = true; + for ( int i = 0; i < N; ++i ) + { + sh[i] = sosShift( st, g, *defs[i], v[i], kx, ky, maxDeg ); + defined = defined && !sh[i].c.empty(); + } + if ( defined ) + { + std::array x; + for ( int i = 0; i < M; ++i ) + x[i] = { convertPoly( full[i].nx, maxDeg ), convertPoly( full[i].ny, maxDeg ), + convertPoly( full[i].d, maxDeg ) }; + if ( auto res = f( sh, x, maxDeg ) ) + return res; + } + if ( maxDeg >= top ) + { + if ( defined ) + lowest = top; + return {}; + } + } + } ); +} + +/// the numerator of the difference of the perturbed shifts q - p, ( q.num * p.c - p.num * q.c ) / ( ( n.d ) * p.c * q.c ), +/// below 2 * 2^228 * 2^97, without the terms of degrees above maxDeg +std::array, 2> sosShiftDiff( const SosShift & p, const SosShift & q, std::int64_t maxDeg ) +{ + return { mulAs( q.num[0], p.c, maxDeg ) - mulAs( p.num[0], q.c, maxDeg ), + mulAs( q.num[1], p.c, maxDeg ) - mulAs( p.num[1], q.c, maxDeg ) }; +} + +/// the sign of the lowest term of cross( a, b ) for the projected vectors a and b, or 0 if it has a degree above maxDeg, +/// where the terms of a and b may be missing; the products of the terms are visited in the order of increasing degree till the first +/// not-zero sum, which counts only up to maxDeg +template +int sosCross( const std::array & a, const std::array & b, std::int64_t maxDeg ) +{ + const SignedProduct products[2] = { { &a[0], &b[1], false }, { &a[1], &b[0], true } }; + const auto [deg, sign] = lowestTermOfSumOfProducts( products, 2 ); + return deg <= maxDeg ? sign : 0; +} + +} + CutTrianglePredicates::CutTrianglePredicates() : impl_( std::make_unique() ) { } @@ -1050,11 +1376,16 @@ void CutTrianglePredicates::reset( const std::array & tri } } -void CutTrianglePredicates::addPoint( VertId v, const PreciseCutPoint & p ) +void CutTrianglePredicates::addPoint( VertId v, const PreciseCutPoint & in ) { - assert( inRange( p.seg[0] ) && ( p.isVertex() || ( inRange( p.seg[1] ) && std::all_of( p.tri.begin(), p.tri.end(), inRange ) ) ) ); - assert( !hasWedge( p ) || ( inRange( p.wedge[0] ) && inRange( p.wedge[1] ) ) ); - assert( !p.isCrossing() || std::all_of( p.tri2.begin(), p.tri2.end(), inRange ) ); + assert( inRange( in.seg[0] ) && ( in.isVertex() || ( inRange( in.seg[1] ) && std::all_of( in.tri.begin(), in.tri.end(), inRange ) ) ) ); + assert( !hasWedge( in ) || ( inRange( in.wedge[0] ) && inRange( in.wedge[1] ) ) ); + assert( !in.isCrossing() || std::all_of( in.tri2.begin(), in.tri2.end(), inRange ) ); + // a crossing of two cuts by triangles with a common edge ab is the crossing of ab with this triangle moved by its own shift, + // so it is defined alike with the crossings of the edges of the multiple edge ab (see shift_) + const auto base = in.isCrossing() ? commonEdgeCrossing( in, tri_ ) : std::nullopt; + const bool delta = base.has_value(); + const PreciseCutPoint & p = delta ? *base : in; auto & points = impl_->points; if ( points.size() <= v ) { @@ -1067,6 +1398,11 @@ void CutTrianglePredicates::addPoint( VertId v, const PreciseCutPoint & p ) if ( pt.def.seg[0].id.valid() || pt.def.isCrossing() || ( impl_->shifted.load( std::memory_order_relaxed ) && hasWedge( p ) ) ) impl_->clearCaches(); pt.def = p; + pt.delta = delta; + for ( int k = 0; k < 2 && delta; ++k ) + for ( const auto & x : k == 0 ? in.tri : in.tri2 ) + if ( x.id != p.seg[0].id && x.id != p.seg[1].id ) + pt.thirds[k] = x; if ( p.isCrossing() ) { addCrossing_( v, p ); @@ -1170,18 +1506,14 @@ void CutTrianglePredicates::addCrossing_( VertId v, const PreciseCutPoint & p ) } auto & c = impl_->crossings[pt.crossing]; c = {}; - auto distinct = [] ( const std::array & t ) - { - return t[0].id.valid() && t[1].id.valid() && t[2].id.valid() && t[0].id != t[1].id && t[1].id != t[2].id && t[2].id != t[0].id; - }; // a triangle with two corners of this triangle cuts it along a side, where a crossing is on the side, and this triangle does not cut itself auto alongSide = [&] ( const std::array & t ) { return int( hasVert( t, tri_[0].id ) ) + int( hasVert( t, tri_[1].id ) ) + int( hasVert( t, tri_[2].id ) ) >= 2; }; - // the crossing is another point also after the perturbation if both triangles have a corner of this triangle, which they cross at, - // or two common vertices, whose edge they cross where it crosses this triangle (and the same triangle if three, while distinct - // triangles in one plane give parallel cuts, which cross at the limit of their perturbed crossing, see below) + // the crossing is another point also after the perturbation if both triangles have a corner of this triangle, which they cross at; + // triangles with two common vertices come as the crossing of their edge (see addPoint), and three are the same triangle, while distinct + // triangles in one plane give parallel cuts, which cross at the limit of their perturbed crossing (see below) const int numCommon = int( hasVert( p.tri, p.tri2[0].id ) ) + int( hasVert( p.tri, p.tri2[1].id ) ) + int( hasVert( p.tri, p.tri2[2].id ) ); auto atCorner = [&] { @@ -1190,7 +1522,7 @@ void CutTrianglePredicates::addCrossing_( VertId v, const PreciseCutPoint & p ) return true; return false; }; - bool valid = distinct( p.tri ) && distinct( p.tri2 ) && numCommon < 2 && !alongSide( p.tri ) && !alongSide( p.tri2 ) && !atCorner(); + bool valid = distinctIds( p.tri ) && distinctIds( p.tri2 ) && numCommon < 2 && !alongSide( p.tri ) && !alongSide( p.tri2 ) && !atCorner(); if ( valid ) c.parts = crossingExact( tri_, p.tri, p.tri2 ); if ( valid && c.parts.d.sign() != 0 ) @@ -1266,8 +1598,8 @@ void CutTrianglePredicates::addCrossing_( VertId v, const PreciseCutPoint & p ) } if ( !valid ) { - // repeated ids, a triangle taken twice, along a side or this one, cuts crossing at a corner or at the crossing of a common edge, or cuts - // that do not cross also after the perturbation, or whose crossing goes to infinity + // repeated ids, a triangle taken twice, along a side or this one, cuts crossing at a corner, or cuts that do not cross also after + // the perturbation, or whose crossing goes to infinity fail_(); c.dSign = 1; c.exact = { FastInt256( tri_[0].pt[kx_] ), FastInt256( tri_[0].pt[ky_] ), FastInt256( 1 ) }; // any point, since the answers are arbitrary now @@ -1333,7 +1665,10 @@ bool CutTrianglePredicates::less( VertId p, VertId q ) const return c < 0; if ( const auto dir = coincidentDirection_( p, q ) ) return sweepForward( *dir ); - return p < q; // the failure: points defined alike, not told apart by their shifts, ordered by their ids + // the failure: points defined alike that their shifts do not tell apart, those with a shift first and then by their ids, + // so that the order by the shifts stays transitive with them (see failed) + const bool sp = shiftDefOf( impl_->points, p ).has_value(), sq = shiftDefOf( impl_->points, q ).has_value(); + return sp != sq ? sp : p < q; } /// the signs of the projected coordinates of perturbed q - p for points p and q that coincide before the perturbation, @@ -1471,17 +1806,39 @@ std::optional CutTrianglePredicates::directionByPerturbation( VertId p return sosDirection( impl_->points[p].def, impl_->points[q].def, tri_, kx_, ky_ ); } -/// the signs of the projected coordinates of q - p for points p and q defined alike: of the difference of their shifts, with the same scale; -/// nullopt if they have no shifts, or equal ones +/// the signs of the projected coordinates of q - p for points p and q defined alike: of the difference of their shifts, or of the perturbed +/// ones where that is zero or unknown (den 0), as the sweep sees them; nullopt if they have no shifts, or equal ones also after the perturbation std::optional CutTrianglePredicates::shiftDirection_( VertId p, VertId q ) const { const auto sp = shift_( p ), sq = shift_( q ); if ( !sp || !sq ) return {}; - const Vector2i dir( ( sq->x - sp->x ).sign(), ( sq->y - sp->y ).sign() ); - if ( dir == Vector2i() ) - return {}; - return dir; + // the exact shifts give the terms of degree 0 of the perturbed ones, which decide unless both coordinates of the difference are zero + // (see sweepSigns); otherwise the perturbed difference ( q.num * p.c - p.num * q.c ) / ( ( n.d ) * p.c * q.c ) decides (see sosShift) + const auto & points = impl_->points; + auto sos = [&] () -> std::optional + { + const auto & def = points[p].def; + const int ndSign = ndSignOf( tri_, def ); + return sosAlike<2, 0>( tri_, { def.seg[0], def.seg[1] }, kx_, ky_, { &sp->def, &sq->def }, { 1, 1 }, {}, + [&] ( const std::array & sh, const auto &, std::int64_t maxDeg ) -> std::optional + { + const auto diff = sosShiftDiff( sh[0], sh[1], maxDeg ); + const auto x = leadOf( diff[0] ), y = leadOf( diff[1] ); + if ( x.second == 0 && y.second == 0 ) + return {}; + const auto dir = sweepSigns( x, y ); + return ndSign * leadOf( sh[0].c ).second * leadOf( sh[1].c ).second > 0 ? dir : -dir; + } ); + }; + if ( sp->den != 0 && sq->den != 0 ) + { + const auto t = shiftDiff( *sp, *sq ); + const Vector2i dir( t.x.sign(), t.y.sign() ); + if ( dir != Vector2i() ) + return dir; + } + return sos(); } /// the shift of crossing p of an edge of another mesh with the triangle, by which the predicates tell apart the points defined alike: @@ -1489,38 +1846,106 @@ std::optional CutTrianglePredicates::shiftDirection_( VertId p, VertId /// of the vertices, and so its crossing with the plane of normal n by delta * ( u - ( n.u ) / ( n.d ) * d ), d = b - a, along the cut of the plane /// by the plane of ab and u, into the angle between the cuts by the triangles of the edge (the same for either direction of the segment and /// either orientation of the triangle); or by -delta * u if the triangles of another edge defined alike are in that angle, so that the sheets -/// of the edges that touch along the segment give contours that do not cross; nullopt without a wedge, or if the segment is parallel to the plane +/// of the edges that touch along the segment give contours that do not cross; nullopt without a wedge; +/// or the shift of a crossing of the cuts by triangles P and Q with the common edge ab, which coincides with the crossings X_P and X_Q +/// of the two edges ab of P and Q (a multiple edge) with this triangle before the shifts: the shifted edges move X_P and X_Q by delta * sP +/// and delta * sQ, and the cuts through them keep their directions tP and tQ up to delta, so the cuts cross at X + delta * y, +/// y = sP + a * tP = sQ + b * tQ, a = cross( sQ - sP, tQ ) / cross( tP, tQ ); nullopt if X_P or X_Q is not found (or not unique, as with +/// a triangle on the third vertex of P or Q on both edges); den 0 if P and Q are on one plane before the perturbation std::optional CutTrianglePredicates::shift_( VertId p ) const { - const auto & points = impl_->points; - const auto & pt = points[p]; - const auto & def = pt.def; - // the segment of a crossing of a side is that side, and a crossing of two cuts has no segment - if ( def.isVertex() || def.isCrossing() || pt.sides != 0 || !hasWedge( def ) ) + const auto s = shiftDefOf( impl_->points, p ); + if ( !s ) return {}; + const auto & def = impl_->points[p].def; const Vector3i64 a( def.seg[0].pt ), b( def.seg[1].pt ); - const auto d = b - a; - const auto u = Vector3i64( def.wedge[0].pt ) + Vector3i64( def.wedge[1].pt ) - a - b; + const auto d = shiftSegment( def ); + // the vector of edge k toward its wedge, or away from it; sP is found for X_P with the segment of p, which gives the same shift + auto wedge = [&] ( int k ) + { + const auto u = Vector3i64( s->w[2 * k].pt ) + Vector3i64( s->w[2 * k + 1].pt ) - a - b; + return s->away[k] ? -u : u; + }; + const auto u = wedge( 0 ); // with the components of the normal below 2^63 (see normalOf), those of d below 2^31 and those of u below 2^32, // n.d and n.u are below 3 * 2^95, and the projected coordinates below 6 * 2^126 - const FastInt128 nd = normalDot( normal_, d ), nu = normalDot( normal_, u ); - if ( nd == 0 ) - return {}; // the segment is in the plane before the perturbation, or the triangle has a zero normal + const auto n = shiftNormal_(); + const FastInt128 nd = normalDot( n, d ), nu = normalDot( n, u ); + // the numerator n x ( u x d ) = ( n.d ) * u - ( n.u ) * d of the shift, which is also the term of degree 0 of the perturbed one; + // for a segment in the plane (n.d == 0), which the perturbation tilts by an infinitesimal n.d, the shift moves the crossing along + // the segment infinitely farther than delta * u, and the scale is infinitesimal (0) auto coord = [&] ( int k ) { return Int128Mul256( nd ) * Int128Mul256( u[k] ) - Int128Mul256( nu ) * Int128Mul256( d[k] ); }; - Shift res{ coord( kx_ ), coord( ky_ ), nd < 0 ? -nd : nd }; - // away from the wedge if the triangles of another point defined alike are in its angle; found only here, since points defined alike are rare - bool away = false; - for ( auto x = points.beginId(); x < points.endId() && !away; ++x ) - away = x != p && points[x].sides == 0 && hasWedge( points[x].def ) && definedAlike( def, points[x].def ) && nestedIn( def, points[x].def ); - if ( ( nd < 0 ) != away ) + Shift res{ FastInt512( coord( kx_ ) ), FastInt512( coord( ky_ ) ), FastInt256( 1 ), nd < 0 ? -nd : nd, *s }; + // the sign of the perturbed n.d + const bool ndNegative = ndSignOf( tri_, def ) < 0; + if ( ndNegative ) { res.x = -res.x; res.y = -res.y; } impl_->shifted.store( true, std::memory_order_relaxed ); + if ( !s->delta ) + return res; + // the cuts cross where the cut of P through X_P + delta * sP meets the cut of Q through X_Q + delta * sQ, with directions + // tP = n x nP and tQ = n x nQ; for the normals nP = d x p and nQ = d x q of the planes through ab and the third vertices a + p, a + q, + // cross( tP, tQ ) is ( n.d ) * det( d, p, q ) * n, and cross( sQ - sP, tQ ) is det( dU, d, q ) * n for the difference dU + // of the signed wedge vectors, with n.d cancelled out, so y = sP + tP * det( dU, d, q ) / ( ( n.d ) * det( d, p, q ) ); + // in the units of the shifts, times |n.d|: ( sP * c + sgn( n.d ) * tP * k ) / c, with c = det( d, p, q ), k = dU.nQ, which stay finite + // also for a segment in the plane, where the cuts are parallel before the perturbation + const Vector3i64 nP = cross( d, Vector3i64( s->thirds[0].pt ) - a ), nQ = cross( d, Vector3i64( s->thirds[1].pt ) - a ); + // the components of nP and nQ below 2^63, of dU below 2^33, so c below 3 * 2^63 * 2^31 < 2^96 and k below 3 * 2^63 * 2^33 < 2^98; + // with sP below 6 * 2^126 and tP below 2 * 2^126 = 2^127, the numerators are below 6 * 2^126 * 3 * 2^94 + 2^127 * 3 * 2^96 + // = 21 * 2^221 < 2^226 + const FastInt128 c = normalDot( nP, Vector3i64( s->thirds[1].pt ) - a ); + const FastInt128 k = normalDot( nQ, wedge( 1 ) - u ); + if ( c == 0 ) + return Shift{ {}, {}, {}, res.scale, *s }; // P and Q are on one plane before the perturbation: only the perturbed shift tells (see sosShift) + const auto tP = cross( Vector3i64mul( n ), Vector3i64mul( nP ) ); + auto crossingCoord = [&] ( const FastInt512 & x, const FastInt128 & t ) + { + const auto tk = FastInt512( Int128Mul256( t ) * Int128Mul256( k ) ); + return FastInt512( FastInt256( x ) * FastInt256( c ) ) + ( ndNegative ? -tk : tk ); + }; + res.x = crossingCoord( res.x, tP[kx_] ); + res.y = crossingCoord( res.y, tP[ky_] ); + res.den = FastInt256( c ); + if ( c < 0 ) + { + res.x = -res.x; + res.y = -res.y; + res.den = -res.den; + } return res; } +/// the normal of the triangle for the shifts: the exact one, or for a zero one the terms of the lowest degree of the perturbed one, +/// whose direction it tends to, with the coefficients below 2^63 (see SosVec) and zero components at that degree +Vector3i64 CutTrianglePredicates::shiftNormal_() const +{ + if ( normal_ != Vector3i64() ) + return normal_; + SosVerts r; + const int i0 = r.add( tri_[0], 12 ), i1 = r.add( tri_[1], 12 ), i2 = r.add( tri_[2], 12 ); + const auto ps = r.stages(); + const auto n = ps.firstStage( [&] ( int s ) -> std::optional + { + const auto v = sosNormal( { ps, s }, i0, i1, i2 ); + std::optional deg; + for ( const auto & c : v ) + if ( !c.empty() && ( !deg || c.get().front().first < *deg ) ) + deg = c.get().front().first; + if ( !deg ) + return {}; + Vector3i64 lead; + for ( int k = 0; k < 3; ++k ) + if ( !v[k].empty() && v[k].get().front().first == *deg ) + lead[k] = std::int64_t( v[k].get().front().second ); + return lead; + } ); + assert( n ); // the perturbed points of distinct ids are not on one line (see reset) + return *n; +} + std::optional CutTrianglePredicates::commonLine_( VertId p, VertId q, bool withVertex ) const { const auto & a = impl_->points[p]; @@ -1805,13 +2230,17 @@ std::optional CutTrianglePredicates::ccwByPlanes_( VertId a, VertId b, Ver } /// the orientation of triangle abc with two points defined alike, by the shifts of their edges (see shift_), or nullopt if no two of them are; -/// line is the known line of all three points that ccwByPlanes_ found, or null; the failure if the shifts do not tell it either, or if -/// the first-order term of the third point is zero also after the perturbation, and a crossing of two cuts is on the line, among the points +/// line is the known line of all three points that ccwByPlanes_ found, or null; the failure if the shifts do not tell it either, if the expansion +/// of the first-order term ends zero before a stage whose degrees do not fit in int64 (see SosStages), or if the first-order term of the third +/// point is zero also after the perturbation, and a crossing of two cuts is on the line, among the points /// or not: then the points of the line bulge (see ccwByPlanes_), so the bulge decides before the second-order term for the triangles of the two /// points defined alike with that crossing, while neither the order along the line, as for the other points of the line, nor the second-order term, /// as for the triangles of a third point without a crossing, keeps the axioms of CC systems in every set; that needs the difference of the shifts -/// along the line also after the perturbation, which turns the line, so valid input hardly gives it; without a known line, the second-order term -/// decides then +/// along the line also after the perturbation, which turns the line; without a known line, the second-order term decides then; a crossing +/// of two cuts at their common edge has it with the crossing of the edge of either cut and the other such crossings of that cut, on the line +/// of the cut (see shift_), so the side of the third point of the plane of the cut decides the triangle of two of them, as for ccwByPlanes_, +/// and the bulge that of three; with a third point of the line not defined alike, the bulge decides if a crossing of two cuts not at a common edge +/// is on the line, and the second-order term otherwise std::optional CutTrianglePredicates::ccwByShifts_( VertId a, VertId b, VertId c, const Line * line ) const { const auto & points = impl_->points; @@ -1831,60 +2260,147 @@ std::optional CutTrianglePredicates::ccwByShifts_( VertId a, VertId b, Ver } // p and q at the common point P are shifted by delta * wp and delta * wq, and r by delta * wr, so the doubled area of the triangle is // delta * cross( wq - wp, r - P ) + delta^2 * cross( wq - wp, wr - wp ), where r - P is perturbed, and all its terms come before delta - const FastInt256 dx = sq->x - sp->x, dy = sq->y - sp->y; - if ( !definedAlike( points[p].def, points[r].def ) ) - { - // r - P = ( f.nx * e.d - e.nx * f.d, f.ny * e.d - e.ny * f.d ) / ( e.d * f.d ) with positive denominators, and the numerators - // below 2 * 1.3 * 2^126 * 1.3 * 2^96 < 2^224 (see exactCoords), or 2 * 2^224 * 2^97 for a crossing r of two cuts (see WideCoords), - // times the coordinates of the difference of the shifts below 2^130, in the wide integers, since points defined alike are rare - const auto e = wideOf( points[p], impl_->crossings ), f = wideOf( points[r], impl_->crossings ); - const auto ex = f.nx * e.d - e.nx * f.d, ey = f.ny * e.d - e.ny * f.d; - if ( const int s = ( dx * ey - dy * ex ).sign() ) - return s > 0; - // r - P is parallel to the difference of the shifts before the perturbation, so the expansion of the perturbation decides - auto constant = [] ( const FastInt256 & x ) { return x.sign() ? SosPoly256( std::vector{ { 0, x } } ) : SosPoly256(); }; - const SosPoly256 wx = constant( dx ), wy = constant( dy ); - const int sos = sosFirstStage<2>( { &points[p].def, &points[r].def }, tri_, kx_, ky_, - [&] ( const auto & pts, std::int64_t from, std::int64_t & deg ) -> std::optional + // wq - wp over sp->den * sq->den > 0, below 2 * 2^226 * 2^96 (see shift_); the exact shifts give the terms of degree 0 + // of the perturbed ones (see sosShift), and the perturbed ones decide where the exact ones give 0 + const bool exact = sp->den != 0 && sq->den != 0; + const auto dw = exact ? shiftDiff( *sp, *sq ) : DiffTerm{}; + const auto & dx = dw.x; + const auto & dy = dw.y; + const auto & def = points[p].def; + const std::array ab{ def.seg[0], def.seg[1] }; + const bool alikeR = definedAlike( def, points[r].def ); + // the shift of a crossing of two cuts at their common edge ab is that of the crossing of the edge of either cut plus a move along that cut + // (see sosShift), so it is on the line of each of its cuts at every stage of the perturbation, with the crossing of the edge of that cut + // and its other such crossings: with p and q on one such line, the first-order term is cross( t, r - P ) times a scalar for the direction t + // of the line, whose sign is the side of r of the plane of the cut, as for ccwByPlanes_, without the expansion of the perturbation, whose terms + // grow with the vertices of the cuts and of r; with r defined alike on the line too, all terms are zero, and the bulge decides, as for other + // points of one line; the vertices of the cut are ab and the third vertex of its triangle + std::optional cut; + bool rOnCut = false; + for ( const auto & [x, y] : { std::pair{ p, q }, std::pair{ q, p } } ) + { + std::array xs; + if ( cut || !points[x].delta || !deltaEdges( points, x, xs ) ) + continue; + for ( int k = 0; k < 2 && !cut; ++k ) { - const SosFraction & pp = *pts[0]; - const SosFraction & rr = *pts[1]; - const SosPoly512 nx = mulAs( rr.nx, pp.d ) - mulAs( pp.nx, rr.d ); - const SosPoly512 ny = mulAs( rr.ny, pp.d ) - mulAs( pp.ny, rr.d ); - const SignedProduct products[2] = { { &wx, &ny, false }, { &wy, &nx, true } }; - const auto [leadDeg, sign] = lowestTermOfSumOfProducts( products, 2, from ); - if ( sign == 0 ) - return {}; - deg = leadDeg; - return sign; - } ).value_or( 0 ); + const VertId t = points[x].thirds[k].id; + auto onCut = [&] ( VertId z ) { return z == xs[k] || ( points[z].delta && ( points[z].thirds[0].id == t || points[z].thirds[1].id == t ) ); }; + if ( onCut( y ) ) + { + cut = Line{ .plane = { ab[0], ab[1], points[x].thirds[k] } }; + rOnCut = alikeR && onCut( r ); + } + } + } + if ( rOnCut ) + return int( less( a, b ) ) + int( less( b, c ) ) + int( less( c, a ) ) == 1; // the bulge, along the sweep (see ccwByPlanes_) + // the first-order term with the perturbed r - P: cross( q.num * p.c - p.num * q.c, r - P ) / ( ( n.d ) * p.c * q.c ) + auto sosFirst = [&] () -> int + { + bool cutShort = false; + const int res = sosAlike<2, 2>( tri_, ab, kx_, ky_, { &sp->def, &sq->def }, { 1, 1 }, { &def, &points[r].def }, + [&] ( const std::array & sh, const std::array & x, std::int64_t maxDeg ) -> std::optional + { + const auto diff = sosShiftDiff( sh[0], sh[1], maxDeg ); + const std::array e{ mulAs( x[1].nx, x[0].d, maxDeg ) - mulAs( x[0].nx, x[1].d, maxDeg ), + mulAs( x[1].ny, x[0].d, maxDeg ) - mulAs( x[0].ny, x[1].d, maxDeg ) }; + if ( const int s = sosCross( diff, e, maxDeg ) ) + return ndSignOf( tri_, def ) * leadOf( sh[0].c ).second * leadOf( sh[1].c ).second * s; + return {}; + }, &cutShort ).value_or( 0 ); + if ( res != 0 || !cutShort ) + return res; + fail_(); // the term may not be zero at a stage whose degrees do not fit (see SosStages), so the second-order one cannot decide + return -1; + }; + if ( cut && !alikeR ) + { + if ( const int side = sideOfPlane_( cut->plane, r ) ) + return along_( lineDirection_( *cut ), p, q ) == ( side > 0 ); + line = &*cut; // r is on the line of the cut too, and the first-order term is zero + } + if ( !alikeR ) + { + if ( exact ) + { + // r - P = ( f.nx * e.d - e.nx * f.d, f.ny * e.d - e.ny * f.d ) / ( e.d * f.d ) with positive denominators, and the numerators + // below 2 * 1.3 * 2^126 * 1.3 * 2^96 < 2^224 (see exactCoords), or 2 * 2^224 * 2^97 for a crossing r of two cuts (see WideCoords), + // times the coordinates of the difference of the shifts, in the wide integers, since points defined alike are rare + const auto e = wideOf( points[p], impl_->crossings ), f = wideOf( points[r], impl_->crossings ); + const auto ex = f.nx * e.d - e.nx * f.d, ey = f.ny * e.d - e.ny * f.d; + if ( const int s = ( dx * ey - dy * ex ).sign() ) + return s > 0; + } + // r - P is parallel to the difference of the shifts before the perturbation, so the expansion of the perturbation decides, + // unless they are points of the line of a cut with r + const bool along = cut.has_value(); + const int sos = along ? 0 : sosFirst(); if ( sos ) return sos > 0; - // a crossing of two cuts is on the line iff the line is a cut of it, as sideOfPlane_ finds it, also for a made-up plane; - // the scan is rare, as this path is + // a crossing of two cuts is on the line iff the line is a cut of it, as sideOfPlane_ finds it, also for a made-up plane; one at a common edge + // (as p or q may be) does not count, so it does not make the line of its cut bulge: without another one there, the second-order term decides + // (as for the crossing of the edge of a cut, the crossing at that edge and the other end of the cut); the scan is rare, as this path is auto onLine = [&] ( const CutPoint & x ) { return x.crossing >= 0 && ( sameTriangle( line->plane, x.def.tri ) || sameTriangle( line->plane, x.def.tri2 ) ); }; if ( line && std::any_of( points.begin(), points.end(), onLine ) ) { + if ( along ) + return int( less( a, b ) ) + int( less( b, c ) ) + int( less( c, a ) ) == 1; // the bulge, along the sweep (see ccwByPlanes_) fail_(); // the bulge would decide before the second-order term for the triangles of p and q with that crossing return false; } } // the second-order term, with the shift of r of its own scale (zero for a point without a shift): - // wr - wp = ( Wr * scale - Wp * rScale ) / ( scale * rScale ), the products below 2^129 * 2^96 - FastInt256 rx, ry; - FastInt128 rScale = 1; - if ( const auto sr = shift_( r ) ) - { - rx = sr->x; - ry = sr->y; - rScale = sr->scale; + // wr - wp over a positive denominator: in the units of the points defined alike as p, with the same scale, + // or with the scales of both, ( Wr * den_p * scale - Wp * den_r * rScale ) / ( den_p * scale * den_r * rScale ), or -wp for a point without a shift + const auto sr = shift_( r ); + if ( sr && !alikeR ) + { + // the shift of another multiple edge: only the exact shifts + if ( exact && sr->den != 0 ) + { + auto scaled = [] ( const Shift & s ) { return Shift{ .x = s.x, .y = s.y, .den = FastInt256( s.den * s.scale ) }; }; + const auto fw = shiftDiff( scaled( *sp ), scaled( *sr ) ); // over den * scale below 2^96 * 2^97, so below 2 * 2^226 * 2^193 + if ( const int s = ( dx * fw.y - dy * fw.x ).sign() ) + return s > 0; + } + fail_(); + return false; } - const FastInt256 fx( rx * sp->scale - sp->x * rScale ), fy( ry * sp->scale - sp->y * rScale ); - if ( const int s = ( dx * fy - dy * fx ).sign() ) - return s > 0; + if ( exact && ( !sr || sr->den != 0 ) ) + { + const DiffTerm fw = sr ? shiftDiff( *sp, *sr ) : DiffTerm{ -FastInt<768>( sp->x ), -FastInt<768>( sp->y ) }; + if ( const int s = ( dx * fw.y - dy * fw.x ).sign() ) + return s > 0; + } + // the second-order term with the perturbed shifts: for r with a shift, defined alike here, cross( q - p, r - p ) of the differences of the shifts + // (see sosShiftDiff), over ( n.d )^2 * p.c^2 * q.c * r.c; for r without a shift, unshifted as in the exact term, -cross( q - p, p.num ) + // over ( n.d )^2 * p.c^2 * q.c + auto sosSecond = [&] () -> int + { + if ( sr ) + { + return sosAlike<3, 0>( tri_, ab, kx_, ky_, { &sp->def, &sq->def, &sr->def }, { 2, 1, 1 }, {}, + [&] ( const std::array & sh, const auto &, std::int64_t maxDeg ) -> std::optional + { + if ( const int s = sosCross( sosShiftDiff( sh[0], sh[1], maxDeg ), sosShiftDiff( sh[0], sh[2], maxDeg ), maxDeg ) ) + return leadOf( sh[1].c ).second * leadOf( sh[2].c ).second * s; + return {}; + } ).value_or( 0 ); + } + return sosAlike<2, 0>( tri_, ab, kx_, ky_, { &sp->def, &sq->def }, { 2, 1 }, {}, + [&] ( const std::array & sh, const auto &, std::int64_t maxDeg ) -> std::optional + { + if ( const int s = sosCross( sosShiftDiff( sh[0], sh[1], maxDeg ), sh[0].num, maxDeg ) ) + return -leadOf( sh[1].c ).second * s; + return {}; + } ).value_or( 0 ); + }; + if ( const int sos = sosSecond() ) + return sos > 0; fail_(); // the shifts are on one line too return false; } diff --git a/source/MRMesh/MRCutTrianglePredicates.h b/source/MRMesh/MRCutTrianglePredicates.h index cfd5786cae58..8ce460163a0d 100644 --- a/source/MRMesh/MRCutTrianglePredicates.h +++ b/source/MRMesh/MRCutTrianglePredicates.h @@ -49,7 +49,8 @@ struct MR_BIND_IGNORE PreciseCutPoint /// or away from them if the triangles of another edge defined alike are in the angle between its own ones, so that the contours of two edges /// whose sheets touch along the segment without crossing do not cross either, while those of crossing sheets do; /// a crossing of two cuts is the point where the perturbed planes of the triangle and of the two cuts meet, so it is on the side -/// of every other plane that the perturbation puts it on, as a vertex is; +/// of every other plane that the perturbation puts it on, as a vertex is, unless the cuts are by triangles with a common edge: +/// then it is the crossing of that edge moved by the shifts of the edges of the cuts along them, defined alike with the crossings of those edges; /// the sweep goes over the projection of the perturbed triangle on the plane of the two axes least aligned with its normal /// (dropping the axis of the largest component of the normal, the first one of equal components, or the axis of the leading /// term of the perturbed normal if the exact one is zero), meeting the points in the order of one linear functional, @@ -85,8 +86,9 @@ class MR_BIND_IGNORE CutTrianglePredicates /// cross the plane of its triangle, two cuts by the same triangle (with three common vertex ids, while distinct triangles in one plane /// give two parallel cuts, which cross as said above), a cut along a side or by this triangle (by a triangle with two or three corners /// of this triangle), two cuts whose crossing is another point also after the perturbation (by triangles with a common corner of this - /// triangle, or with two common vertices, whose edge they cross where it crosses this triangle), and two cuts that stay parallel - /// after the perturbation or whose crossing goes to infinity as it vanishes are failures (see failed) + /// triangle, which they cross at), and two cuts that stay parallel after the perturbation or whose crossing goes to infinity as it vanishes + /// are failures (see failed); two cuts by triangles with a common edge cross where that edge crosses this triangle, moved by the shifts + /// of the edges along the cuts (see CutTrianglePredicates) MRMESH_API void addPoint( VertId v, const PreciseCutPoint & p ); /// whether point p comes before point q along the sweep: a strict total order, unless reset or addPoint failed (see failed) @@ -101,7 +103,10 @@ class MR_BIND_IGNORE CutTrianglePredicates /// whether triangle abc of distinct points is counterclockwise in the projection, for any three points: the first rule that applies /// decides, of the rounded coordinates (if their errors cannot change the sign), a side through two of the points, and, with the answers /// kept till reset since the sweep asks about the same triangles often, a plane line through two of them (the lines of ccwByLines), - /// the exact positions, and the expansion of the perturbation; where several rules apply, they agree + /// the exact positions, and the expansion of the perturbation; where several rules apply, they agree; the shifts of the edges of two points + /// defined alike decide their triangles with a third point (see ccwByLines), and a crossing of two cuts by triangles with a common edge + /// is on the line of each cut at every stage, with the crossing of the edge of that cut and the other such crossings of it, so the side + /// of the third point of the plane of the cut decides the triangle of two of them, and the bulge that of three [[nodiscard]] MRMESH_API bool ccw( VertId a, VertId b, VertId c ) const; /// the same as ccw, decided by a line through two of the points known from their definitions, as the ends of every edge @@ -112,13 +117,17 @@ class MR_BIND_IGNORE CutTrianglePredicates /// a crossing of two cuts is on both of them; /// the points on one side stay on one line after the perturbation, and they are taken /// as bulging inward a little, so three of them make a counterclockwise triangle if they come in the order - /// from vertex i+1 to vertex i of side i, up to a cyclic shift; so are the points on a cut with a crossing of two cuts among them, - /// as the pieces of a cut split at its crossings are, bulging to the left of the cut in the direction that the sweep goes along it; + /// from vertex i+1 to vertex i of side i, up to a cyclic shift; so are the points on a cut with a crossing of two cuts among them + /// (not counting one by triangles with a common edge), as the pieces of a cut split at its crossings are, bulging to the left of the cut + /// in the direction that the sweep goes along it; /// where the line has the third point too otherwise, two of the points are defined alike in valid input, and the shifts of their edges decide; /// with a crossing of two cuts among the points, the first-order term of the shifts decides before the bulge, since only the shifts /// move those two apart (a failure if that term is zero, as with the difference of the shifts along the cut also after the perturbation, - /// and so for a third point that is not a crossing of two cuts too, if a crossing of two cuts is on the line); - /// nullopt if no two of the points are on a known line + /// and so for a third point that is not a crossing of two cuts too, if a crossing of two cuts is on the line, but not for two points + /// on a cut of a crossing at their common edge among them, where the bulge decides, or the second-order term without a crossing of two + /// cuts on the line); the rule of ccw for a crossing of two cuts by triangles with a common edge applies here only where a line goes + /// through two of the points; + /// nullopt if no two of the points are on a known line, as two crossings of one segment are not [[nodiscard]] MRMESH_API std::optional ccwByLines( VertId a, VertId b, VertId c ) const; /// the same as ccw found by expanding the perturbation alone, which is slow, while ccw decides most triangles by faster rules; @@ -132,16 +141,19 @@ class MR_BIND_IGNORE CutTrianglePredicates /// whether the input broke a precondition that reset or addPoint checks, or a predicate met points it cannot tell apart: two points /// defined alike that the shifts of their edges do not tell apart (a vertex twice, crossings of a side, crossings without wedges or - /// with the same one, or with the segment parallel to the triangle before the perturbation, as with a zero normal, or crossings of - /// the same two cuts), three points defined alike with their shifts on one line, two points defined alike on a known line (see ccwByLines) + /// with the same one, crossings of the same two cuts, or a crossing of two cuts by triangles with a common edge without exactly one + /// crossing of the edge of each of them, with the third vertex of that triangle in its wedge), three points defined alike with their shifts + /// on one line but not on the line of a cut (see ccwByLines), two points defined alike on a known line (see ccwByLines) /// with a crossing of two cuts, among the points of the triangle or not, with the difference of their shifts along the line also after - /// the perturbation, three points off the sides on one line also after the perturbation and without a crossing of two cuts among them - /// (as three crossings of one cut by edges, while valid input has two at most, apart from points defined alike), or points whose expansion - /// of the perturbation reaches a stage whose degrees do not fit in int64 (see ccwByPerturbation); it stays set till reset; the caller checks - /// it after the addPoint calls and calls no predicate on the point of a failed addPoint, since they take the points as valid (less may be - /// cyclic then, and Debug asserts may fire), while predicates on the other points stay callable; a failure that a predicate finds leaves - /// the predicates callable, with arbitrary answers that the caller discards, and less a strict total order (points defined alike compare - /// alike with every other point, and by their ids with one another if their shifts do not tell them apart) + /// the perturbation, unless it is a cut of a crossing at their common edge among them (see ccw), three points off the sides on one line + /// also after the perturbation and without a crossing of two cuts among them (as three crossings of one cut by edges, while valid input + /// has two at most, apart from points defined alike), or points whose expansion of the perturbation, also of the shifts of points + /// defined alike, reaches a stage whose degrees do not fit in int64 (see ccwByPerturbation); + /// it stays set till reset; the caller checks it after the addPoint calls and calls no predicate on the point of a failed addPoint, since + /// they take the points as valid (less may be cyclic then, and Debug asserts may fire), while predicates on the other points stay callable; + /// a failure that a predicate finds leaves the predicates callable, with arbitrary answers that the caller discards, and less a strict total + /// order (points defined alike compare alike with every other point, and with one another by their shifts, or where those do not tell them + /// apart, those with a shift first and then by their ids) [[nodiscard]] MRMESH_API bool failed() const; private: @@ -174,6 +186,7 @@ class MR_BIND_IGNORE CutTrianglePredicates std::optional perturbedDirection_( VertId p, VertId q, bool alike ) const; std::optional shiftDirection_( VertId p, VertId q ) const; std::optional shift_( VertId p ) const; + Vector3i64 shiftNormal_() const; std::optional commonLine_( VertId p, VertId q, bool withVertex ) const; Vector2i lineDirection_( const Line & l ) const; bool along_( const Vector2i & dir, VertId p, VertId q ) const; diff --git a/source/MRMesh/MRSparsePolynomial.h b/source/MRMesh/MRSparsePolynomial.h index b3e0f4b8fd7d..212eb2ff4bf4 100644 --- a/source/MRMesh/MRSparsePolynomial.h +++ b/source/MRMesh/MRSparsePolynomial.h @@ -17,9 +17,10 @@ template using SparsePolynomialProduct = SparsePolynomial() * std::declval() ), D, M>; /// computes the product of two polynomials, converting every coefficient into type T before multiplication; -/// e.g. T=Int128Mul256 multiplies FastInt128 coefficients without overflow into a polynomial with FastInt256 coefficients -template -SparsePolynomialProduct mulAs( const SparsePolynomial& a, const SparsePolynomial& b ); +/// e.g. T=Int128Mul256 multiplies FastInt128 coefficients without overflow into a polynomial with FastInt256 coefficients; +/// an integer maxDeg drops the terms of larger degrees too, while by default only M bounds the degrees, at compile time +template > +SparsePolynomialProduct mulAs( const SparsePolynomial& a, const SparsePolynomial& b, MaxDeg maxDeg = {} ); /// computes the product of two polynomials with the coefficients of the same type template @@ -113,8 +114,8 @@ class SparsePolynomial SparsePolynomial& operator -=( const SparsePolynomial& b ); [[nodiscard]] friend SparsePolynomial operator +( SparsePolynomial a, const SparsePolynomial& b ) { a += b; return a; } [[nodiscard]] friend SparsePolynomial operator -( SparsePolynomial a, const SparsePolynomial& b ) { a -= b; return a; } - template - friend SparsePolynomialProduct mulAs( const SparsePolynomial& a, const SparsePolynomial& b ); + template + friend SparsePolynomialProduct mulAs( const SparsePolynomial& a, const SparsePolynomial& b, MaxDeg maxDeg ); private: /// merges the terms of a degree-sorted sequence, dropping the vanished ones @@ -247,13 +248,17 @@ SparsePolynomial& SparsePolynomial::operator -=( const SparsePolyn return * this; } -template -[[nodiscard]] SparsePolynomialProduct mulAs( const SparsePolynomial& a, const SparsePolynomial& b ) +template +[[nodiscard]] SparsePolynomialProduct mulAs( const SparsePolynomial& a, const SparsePolynomial& b, MaxDeg maxDeg ) { using Res = SparsePolynomialProduct; using Term = typename Res::Term; + // a cap at run time may keep few of all the products, which are not reserved then + constexpr bool capped = std::is_integral_v; + static_assert( capped || std::is_same_v> ); // M is the only cap at compile time std::vector res; - res.reserve( a.terms_.size() * b.terms_.size() ); + if constexpr ( !capped ) + res.reserve( a.terms_.size() * b.terms_.size() ); for ( const auto & [degA, cfA] : a.terms_ ) { assert( cfA != 0 ); @@ -263,6 +268,11 @@ template const auto deg = degA + degB; if ( deg > M ) break; + if constexpr ( capped ) + { + if ( deg > maxDeg ) + break; + } // no conversion (and no copy of a big integer) if the coefficients have type T already if constexpr ( std::is_same_v ) res.emplace_back( deg, cfA * cfB ); diff --git a/source/MRTest/MRCutTrianglePredicatesTests.cpp b/source/MRTest/MRCutTrianglePredicatesTests.cpp index 05837a15f735..4f66dba47b3b 100644 --- a/source/MRTest/MRCutTrianglePredicatesTests.cpp +++ b/source/MRTest/MRCutTrianglePredicatesTests.cpp @@ -7,8 +7,10 @@ #include #include #include +#include #include #include +#include #include #include @@ -1133,30 +1135,58 @@ TEST( MRMesh, CutTrianglePredicatesFailed ) EXPECT_TRUE( preds.failed() ); } + // the number of the pairs and triples of points 0 to n-1 that break a strict total order by less: irreflexive, asymmetric, total + // and transitive, so a strict weak order too, whose incomparability (of a point with itself only) is transitive + auto numNotOrdered = [&] ( int n ) + { + std::vector lt( n * n ); + for ( int p = 0; p < n; ++p ) + for ( int q = 0; q < n; ++q ) + lt[p * n + q] = preds.less( VertId( p ), VertId( q ) ); + int num = 0; + for ( int p = 0; p < n; ++p ) + for ( int q = 0; q < n; ++q ) + { + num += p == q ? lt[p * n + q] : lt[p * n + q] == lt[q * n + p]; + for ( int r = 0; r < n; ++r ) + num += lt[p * n + q] && lt[q * n + r] && !lt[p * n + r]; + } + return num; + }; + // two points defined alike without wedges, the second one with the segment backward, which less cannot order: it orders them by their ids, // and alike with the other points, also with a third point at their position, so it stays a strict total order + const PreciseCutPoint other{ { vert( 12, 1, 0, -1 ), vert( 13, 3, 2, 1 ) }, f }; auto alike = [&] { start(); preds.addPoint( 3_v, x ); preds.addPoint( 4_v, { { x.seg[1], x.seg[0] }, x.tri } ); - preds.addPoint( 5_v, { { vert( 12, 1, 0, -1 ), vert( 13, 3, 2, 1 ) }, f } ); + preds.addPoint( 5_v, other ); EXPECT_FALSE( preds.failed() ); }; alike(); - for ( int p = 0; p < 6; ++p ) - for ( int q = 0; q < 6; ++q ) - { - if ( p != q ) - { - EXPECT_NE( preds.less( VertId( p ), VertId( q ) ), preds.less( VertId( q ), VertId( p ) ) ); - } - for ( int r = 0; r < 6; ++r ) - { - EXPECT_FALSE( preds.less( VertId( p ), VertId( q ) ) && preds.less( VertId( q ), VertId( r ) ) && !preds.less( VertId( p ), VertId( r ) ) ); - } - } + EXPECT_EQ( numNotOrdered( 6 ), 0 ); EXPECT_TRUE( preds.failed() ); + // the crossings of the edges of a multiple edge with twin faces abo, from x toward o, o2 and o, w, which their shifts order, and between + // them by id, the crossing of the cuts by abo and abw, which gets no shift, since both edges have the third vertex of abo: less puts it after + // them, also where the shifts order them against their ids, and alike with the other points, so it stays a strict total order + const auto o = vert( 14, 6, 1, 1 ), o2 = vert( 15, 2, 5, 1 ), w = vert( 16, 2, -3, 1 ); + const std::array edges = { PreciseCutPoint{ .seg = x.seg, .tri = f, .wedge = { o, o2 } }, + PreciseCutPoint{ .seg = { x.seg[1], x.seg[0] }, .tri = f, .wedge = { o, w } } }; + for ( int first = 0; first < 2; ++first ) + { + start(); + preds.addPoint( 3_v, edges[first] ); + preds.addPoint( 4_v, { .tri = { x.seg[0], x.seg[1], o }, .tri2 = { x.seg[0], x.seg[1], w } } ); + preds.addPoint( 5_v, edges[1 - first] ); + preds.addPoint( 6_v, other ); + EXPECT_FALSE( preds.failed() ); + EXPECT_EQ( preds.less( 3_v, 5_v ), first == 1 ); // by the shifts, the second edge first + EXPECT_FALSE( preds.failed() ); + EXPECT_EQ( numNotOrdered( 7 ), 0 ); + EXPECT_TRUE( preds.failed() ); + } // nor can ccw tell them apart: with a vertex of f, on the plane line through it and either of them, and with a third point defined // alike, on no known line with them, where the expansion of the perturbation finds the three on one line after all its stages // (with a third point of other vertices, about 50 times slower); nor can ccwFromBehind @@ -1475,6 +1505,401 @@ TEST( MRMesh, CutTrianglePredicatesDefinedAlike ) EXPECT_GE( ccwStats.exact, atLeast( 110000, 21000 ) ); } +// an expansion of the perturbation of orient3d of its own, for the models of the tests: coordinate i of a vertex gets eps^( w_i * D ), +// w = 9, 3, 1 for x, y, z, with D growing so fast with the id that a term is keyed by the weights (the sums of w over its coordinates) +// of its vertices by rank, compared from the largest id down (see getPointDegrees), without the degrees themselves; at most 16 vertices, +// and a weight of a vertex in a term below 256 +class SosModel +{ +public: + using Key = std::array; + struct KeyLess + { + bool operator()( const Key& a, const Key& b ) const + { + for ( size_t i = a.size(); i-- > 0; ) + if ( a[i] != b[i] ) + return a[i] < b[i]; + return false; + } + }; + using Poly = std::map; + using Vec = std::array; + + explicit SosModel( const std::vector& verts ) + { + for ( const auto& v : verts ) + ids_.push_back( v.id ); + std::sort( ids_.begin(), ids_.end() ); + ids_.erase( std::unique( ids_.begin(), ids_.end() ), ids_.end() ); + EXPECT_LE( ids_.size(), Key().size() ); + } + + Poly constant( std::int64_t c ) const + { + Poly res; + if ( c != 0 ) + res[Key{}] = c; + return res; + } + + // the perturbed coordinates of v + Vec coords( const PreciseVertCoords& v ) const + { + const auto rank = std::lower_bound( ids_.begin(), ids_.end(), v.id ) - ids_.begin(); + Vec res; + for ( int i = 0; i < 3; ++i ) + { + res[i] = constant( v.pt[i] ); + Key key{}; + key[rank] = std::uint8_t( i == 0 ? 9 : ( i == 1 ? 3 : 1 ) ); + res[i][key] = 1; + } + return res; + } + + static Poly add( Poly a, const Poly& b, std::int64_t s = 1 ) + { + for ( const auto& [k, c] : b ) + if ( ( a[k] += s * c ) == 0 ) + a.erase( k ); + return a; + } + static Poly mul( const Poly& a, const Poly& b ) + { + Poly res; + for ( const auto& [ka, ca] : a ) + for ( const auto& [kb, cb] : b ) + { + auto k = ka; + for ( size_t i = 0; i < k.size(); ++i ) + { + assert( k[i] + kb[i] < 256 ); + k[i] = std::uint8_t( k[i] + kb[i] ); + } + if ( ( res[k] += ca * cb ) == 0 ) + res.erase( k ); + } + return res; + } + static Vec add( const Vec& a, const Vec& b ) { return { add( a[0], b[0] ), add( a[1], b[1] ), add( a[2], b[2] ) }; } + static Vec sub( const Vec& a, const Vec& b ) { return { add( a[0], b[0], -1 ), add( a[1], b[1], -1 ), add( a[2], b[2], -1 ) }; } + static Vec scale( const Vec& a, const Poly& s ) { return { mul( a[0], s ), mul( a[1], s ), mul( a[2], s ) }; } + static Poly dot( const Vec& a, const Vec& b ) { return add( add( mul( a[0], b[0] ), mul( a[1], b[1] ) ), mul( a[2], b[2] ) ); } + static Vec cross( const Vec& a, const Vec& b ) + { + return { add( mul( a[1], b[2] ), mul( a[2], b[1] ), -1 ), add( mul( a[2], b[0] ), mul( a[0], b[2] ), -1 ), + add( mul( a[0], b[1] ), mul( a[1], b[0] ), -1 ) }; + } + // the sign for infinitesimal eps: of the lowest term + static int sign( const Poly& p ) { return p.empty() ? 0 : ( p.begin()->second < 0 ? -1 : 1 ); } + + // the sign of a * b - c * d, without the products: the products of their terms in the increasing order of the keys, which adding a key keeps, + // up to the first key whose sum is not zero + static int productsDiffSign( const Poly& a, const Poly& b, const Poly& c, const Poly& d ) + { + struct Cursor + { + Key key; + Poly::const_iterator x, y, yEnd; + std::int64_t s = 1; + }; + auto later = [] ( const Cursor& u, const Cursor& v ) { return KeyLess()( v.key, u.key ); }; + std::priority_queue, decltype( later )> heap( later ); + auto push = [&] ( Poly::const_iterator x, Poly::const_iterator y, Poly::const_iterator yEnd, std::int64_t s ) + { + if ( y == yEnd ) + return; + Key k = x->first; + for ( size_t i = 0; i < k.size(); ++i ) + { + assert( k[i] + y->first[i] < 256 ); + k[i] = std::uint8_t( k[i] + y->first[i] ); + } + heap.push( { k, x, y, yEnd, s } ); + }; + for ( auto x = a.begin(); x != a.end(); ++x ) + push( x, b.begin(), b.end(), 1 ); + for ( auto x = c.begin(); x != c.end(); ++x ) + push( x, d.begin(), d.end(), -1 ); + while ( !heap.empty() ) + { + const Key key = heap.top().key; + std::int64_t sum = 0; + while ( !heap.empty() && heap.top().key == key ) + { + const auto u = heap.top(); + heap.pop(); + sum += u.s * u.x->second * u.y->second; + push( u.x, std::next( u.y ), u.yEnd, u.s ); + } + if ( sum != 0 ) + return sum < 0 ? -1 : 1; + } + return 0; + } + +private: + std::vector ids_; +}; + +// two crossings of one segment ab with f defined alike, as of the two edges of a multiple edge, with ab along a side of f +// (or of zero length on it) but with other vertex ids, so that n.d is zero before the perturbation and the shifts go along ab +// (see CutTrianglePredicates::shift_); wedges with other n.u, with the same n.u (where the perturbation of the wedge vertices decides), +// and sharing a vertex; also a segment off the sides with wedges whose difference is parallel to it, where the exact shifts are equal; +// for every segment that crosses f after the perturbation, less must be a strict total order without a failure, the same with the segment +// backward, the triangle rotated or reversed, or the wedge swapped in either point, and with f rotated; and less and ccw must agree +// with a model of the perturbed shifts of its own (see SosModel) +TEST( MRMesh, CutTrianglePredicatesDefinedAlikeAlongSide ) +{ + const Tri f = { vert( 1, 0, 0, 0 ), vert( 3, 8, 0, 0 ), vert( 4, 0, 8, 0 ) }; + const auto [kx, ky] = projectionAxes( f ); + CutTrianglePredicates preds; + OrderStats orderStats; + CcwStats ccwStats; + int numModel = 0; + + // the points defined alike, crossings of ab with wedges w0 and w1, with the vertices of f and another crossing + auto check = [&] ( const PreciseVertCoords& a, const PreciseVertCoords& b, const std::array& w0, + const std::array& w1 ) + { + CutPoints pts; + for ( int i = 0; i < 3; ++i ) + pts.add( vertexPoint( f[i] ), ( 1 << i ) | ( 1 << ( ( i + 2 ) % 3 ) ) ); + pts.add( { { vert( 20, 2, 1, -1 ), vert( 21, 2, 1, 1 ) }, f }, 0 ); + const int i0 = int( pts.defs.size() ), i1 = i0 + 1; + pts.add( { .seg = { a, b }, .tri = f, .wedge = w0 }, 0 ); + pts.add( { .seg = { a, b }, .tri = f, .wedge = w1 }, 0 ); + const int num = int( pts.defs.size() ); + + // the table of less with the points i0 and i1 in variants v0 and v1: bit 0 swaps the segment, bit 1 rotates the triangle, + // bit 2 reverses it, bit 3 swaps the wedge; and with f rotated by r in reset + auto variant = [] ( PreciseCutPoint p, int v ) + { + if ( v & 1 ) + std::swap( p.seg[0], p.seg[1] ); + if ( v & 2 ) + std::rotate( p.tri.begin(), p.tri.begin() + 1, p.tri.end() ); + if ( v & 4 ) + std::swap( p.tri[1], p.tri[2] ); + if ( v & 8 ) + std::swap( p.wedge[0], p.wedge[1] ); + return p; + }; + auto lessTable = [&] ( int v0, int v1, int r ) + { + Tri g = f; + std::rotate( g.begin(), g.begin() + r, g.end() ); + preds.reset( g ); + for ( int i = 0; i < num; ++i ) + preds.addPoint( VertId( i ), i == i0 ? variant( pts.defs[i], v0 ) : ( i == i1 ? variant( pts.defs[i], v1 ) : pts.defs[i] ) ); + EXPECT_FALSE( preds.failed() ); + std::vector res( num * num ); + for ( int p = 0; p < num; ++p ) + for ( int q = 0; q < num; ++q ) + res[p * num + q] = preds.less( VertId( p ), VertId( q ) ); + EXPECT_FALSE( preds.failed() ) << "seg " << a.id << " " << b.id << " wedges " << w0[0].id << w0[1].id << " " << w1[0].id << w1[1].id + << " variants " << v0 << " " << v1 << " r " << r; + return res; + }; + const auto base = lessTable( 0, 0, 0 ); + for ( int v = 0; v < 16; ++v ) + { + EXPECT_EQ( lessTable( v, 0, 0 ), base ); + EXPECT_EQ( lessTable( 0, v, 0 ), base ); + EXPECT_EQ( lessTable( v, v, 0 ), base ); + } + for ( int r = 1; r < 3; ++r ) + EXPECT_EQ( lessTable( 0, 0, r ), base ); + + // the model of the shifts by an expansion of the perturbation of its own (see SosModel): X1 - X0 = delta * F / ( n.d ) for the perturbed + // normal n of f and d = b - a, with F = n x ( dU x d ), dU = u1 - u0 for the wedge vectors u = w0 + w1 - a - b, each reversed + // if the triangles of the other point are in the angle of the point's ones (see CutTrianglePredicates::shift_); the sweep sees + // the coordinate of the lower leading term, or both if they are equal (see sweepSigns); and the first-order term of the orientation + // of X0, X1, z is cross( F, z - P ) / ( n.d ) for the perturbed position P of the points defined alike and z + (void)lessTable( 0, 0, 0 ); + auto nestedIn = [&] ( const PreciseCutPoint& p, const PreciseCutPoint& q ) + { + auto o = [&] ( const PreciseVertCoords& x, const PreciseVertCoords& y ) { return orient3d( { p.seg[0], p.seg[1], x, y } ); }; + int numShared = 0; + for ( const auto& y : q.wedge ) + { + if ( y.id == p.wedge[0].id || y.id == p.wedge[1].id ) + ++numShared; + else if ( o( p.wedge[0], y ) != o( p.wedge[0], p.wedge[1] ) || o( p.wedge[1], y ) != o( p.wedge[1], p.wedge[0] ) ) + return false; + } + return numShared < 2; + }; + const PreciseVertCoords s0 = vert( 20, 2, 1, -1 ), s1 = vert( 21, 2, 1, 1 ); + const SosModel m( { f[0], f[1], f[2], a, b, w0[0], w0[1], w1[0], w1[1], s0, s1 } ); + using M = SosModel; + const auto f0 = m.coords( f[0] ); + const auto nf = M::cross( M::sub( m.coords( f[1] ), f0 ), M::sub( m.coords( f[2] ), f0 ) ); + const auto ca = m.coords( a ), cb = m.coords( b ); + const auto d = M::sub( cb, ca ); + auto wedgeVec = [&] ( int k ) + { + const auto& p = pts.defs[k == 0 ? i0 : i1]; + const auto u = M::sub( M::sub( M::add( m.coords( p.wedge[0] ), m.coords( p.wedge[1] ) ), ca ), cb ); + return nestedIn( p, pts.defs[k == 0 ? i1 : i0] ) ? M::sub( {}, u ) : u; + }; + const auto F = M::cross( nf, M::cross( M::sub( wedgeVec( 1 ), wedgeVec( 0 ) ), d ) ); + const int ndSign = M::sign( M::dot( nf, d ) ); + Vector2i dir( M::sign( F[kx] ), M::sign( F[ky] ) ); + if ( dir.x != 0 && dir.y != 0 ) + { + if ( M::KeyLess()( F[kx].begin()->first, F[ky].begin()->first ) ) + dir.y = 0; + else if ( M::KeyLess()( F[ky].begin()->first, F[kx].begin()->first ) ) + dir.x = 0; + } + if ( ndSign < 0 ) + dir = -dir; + // the positions num / den: of a vertex, and of the crossing of segment st with f, ( vs * t - vt * s ) / ( vs - vt ) for v( x ) = n.( x - f0 ) + struct Pos + { + M::Vec num; + M::Poly den; + }; + auto vertexPos = [&] ( const PreciseVertCoords& v ) { return Pos{ m.coords( v ), m.constant( 1 ) }; }; + auto crossingPos = [&] ( const PreciseVertCoords& s, const PreciseVertCoords& t ) + { + const auto cs = m.coords( s ), ct = m.coords( t ); + const auto vs = M::dot( nf, M::sub( cs, f0 ) ), vt = M::dot( nf, M::sub( ct, f0 ) ); + return Pos{ M::sub( M::scale( ct, vs ), M::scale( cs, vt ) ), M::add( vs, vt, -1 ) }; + }; + const auto P = crossingPos( a, b ); + const std::array known = { vertexPos( f[0] ), vertexPos( f[1] ), vertexPos( f[2] ), crossingPos( s0, s1 ) }; + // the sign of cross( X1 - X0, z - P ), with z - P = ( z.num * P.den - P.num * z.den ) / ( z.den * P.den ) + std::array crossSigns{}; + for ( int z = 0; z < 4; ++z ) + { + const auto& Z = known[z]; + const auto e = M::sub( M::scale( Z.num, P.den ), M::scale( P.num, Z.den ) ); + crossSigns[z] = ndSign * M::sign( Z.den ) * M::sign( P.den ) * M::productsDiffSign( F[kx], e[ky], F[ky], e[kx] ); + } + + std::vector>> pos; + for ( const auto& def : pts.defs ) + pos.push_back( fractionOf( def ) ); + auto compare = [&] ( int p, int q, int c ) -> std::optional + { + if ( p >= i0 && q >= i0 ) + return p == i0 ? -( c == kx ? dir.x : dir.y ) : ( c == kx ? dir.x : dir.y ); + if ( !pos[p] || !pos[q] ) + return {}; + return compareFractions( *pos[p], *pos[q], c ); + }; + auto orient = [&] ( int p, int q, int r ) + { + const int numAlike = ( p >= i0 ) + ( q >= i0 ) + ( r >= i0 ); + if ( numAlike == 0 ) + return orientFractions( *pos[p], *pos[q], *pos[r], kx, ky ); + if ( numAlike == 1 ) + return 0; + // rotate the triangle to z last, which keeps the orientation + while ( r >= i0 ) + std::tie( p, q, r ) = std::tuple( q, r, p ); + const int s = crossSigns[r]; + numModel += s != 0; + return p == i0 ? s : -s; + }; + checkOrder( preds, f, pts, kx, ky, false, compare, orderStats ); + checkCcw( preds, pts, orient, 0, ccwStats ); + // the expansion of the perturbation on the triangles with at most one of the points defined alike, which it does not move + for ( int p = 0; p < num; ++p ) + for ( int q = p + 1; q < num; ++q ) + for ( int r = q + 1; r < i1; ++r ) + EXPECT_EQ( preds.ccwByPerturbation( VertId( p ), VertId( q ), VertId( r ) ), preds.ccw( VertId( p ), VertId( q ), VertId( r ) ) ); + EXPECT_FALSE( preds.failed() ); + }; + + // segments along every side of f, f[s] + t / 4 * ( f[s+1] - f[s] ), which are integer since the coordinates of f are multiples of 8, + // with ids below, between and above those of f, that cross f after the perturbation + const PreciseVertCoords w[] = { vert( 10, 3, 5, 4 ), vert( 11, 5, -4, 3 ), vert( 12, 2, 3, -5 ), vert( 13, 6, -2, -2 ), + vert( 14, 4, 6, 3 ), vert( 15, 1, -3, 12 ), vert( 16, -2, 5, 3 ) }; + const int wedges[][2][2] = { { { 0, 1 }, { 2, 3 } }, { { 0, 1 }, { 4, 3 } }, { { 0, 1 }, { 2, 5 } }, { { 0, 1 }, { 0, 3 } }, { { 0, 1 }, { 0, 6 } } }; + const int segIds[] = { 0, 2, 5, 6 }; + int numSegs = 0, numZeroLength = 0; + for ( int s = 0; s < 3; ++s ) + { + auto onSide = [&] ( int id, int t ) + { + return PreciseVertCoords{ VertId( id ), ( f[s].pt * ( 4 - t ) + f[( s + 1 ) % 3].pt * t ) / 4 }; + }; + for ( int ia : segIds ) + for ( int ib : segIds ) + for ( int ta = -1; ta <= 5; ta += 2 ) + for ( int tb = -1; tb <= 5; tb += 2 ) + { + const auto a = onSide( ia, ta ), b = onSide( ib, tb ); + if ( ia == ib || !doTriangleSegmentIntersect( { f[0], f[1], f[2], a, b } ) ) + continue; + ++numSegs; + numZeroLength += ta == tb; + // Debug takes one of the five wedge sets with every segment, in turn + for ( int k = 0; k < 5; ++k ) + if ( ( numSegs + k ) % cTrialDivisor == 0 ) + check( a, b, { w[wedges[k][0][0]], w[wedges[k][0][1]] }, { w[wedges[k][1][0]], w[wedges[k][1][1]] } ); + } + } + EXPECT_GE( numSegs, 10 ); + EXPECT_GE( numZeroLength, 1 ); + + // a segment off the sides, crossing f at ( 2, 2 ), with u1 - u0 parallel to d = ( 0, 2, 2 ), so that the exact shifts are equal + // and only the perturbed ones differ; with the wedges in either order + const PreciseVertCoords v0 = vert( 10, 5, 2, 3 ), v1 = vert( 11, -1, 2, 2 ); + const PreciseVertCoords v2 = vert( 12, 5, 3, 4 ), v3 = vert( 13, -1, 3, 3 ); + check( vert( 5, 2, 1, -1 ), vert( 6, 2, 3, 1 ), { v0, v1 }, { v2, v3 } ); + check( vert( 5, 2, 1, -1 ), vert( 6, 2, 3, 1 ), { v2, v3 }, { v0, v1 } ); + + EXPECT_GT( numModel, 0 ); +} + +// Crossings of one segment ab with f defined alike, four with wedges and one without (as of a boundary edge), which has no shift: the second-order +// term of the triangle of two others with it takes it at their common position P, also by the perturbed shifts where the exact shifts of the two +// are parallel; with it last by index, as ccw takes the points of a triangle in that order and fails if one of the first two has no shift, all triangles +// of these points are decided, and ccw must agree with a model of the perturbed shifts of its own (see SosModel) and be consistent (see checkCcw) +TEST( MRMesh, CutTrianglePredicatesUnshiftedAlike ) +{ + const Tri f = { vert( 0, 0, 0, 0 ), vert( 1, 8, 0, 0 ), vert( 2, 0, 8, 0 ) }; + const auto [kx, ky] = projectionAxes( f ); + // ab crosses f at P = ( 2, 1 ), and the wedges go from P along ( 4, 0 ) and ( 0, 4 ), ( 3, 1 ) and ( -1, 1 ), ( -3, -1 ) and ( 1, -3 ), + // ( -3, 2 ) and ( -4, -2 ), none in the angle of another, so every point moves toward the sum of its two, the first two of them parallel + const auto a = vert( 3, 2, 1, -1 ), b = vert( 4, 2, 1, 1 ); + const PreciseVertCoords w[] = { vert( 5, 6, 1, 1 ), vert( 6, 2, 5, 1 ), vert( 7, 5, 2, 1 ), vert( 8, 1, 2, 1 ), + vert( 9, -1, 0, 1 ), vert( 10, 3, -2, 1 ), vert( 11, -1, 3, 1 ), vert( 12, -2, -1, 1 ) }; + CutPoints pts; + for ( int k = 0; k < 4; ++k ) + pts.add( { .seg = { a, b }, .tri = f, .wedge = { w[2 * k], w[2 * k + 1] } }, 0 ); + pts.add( { .seg = { a, b }, .tri = f }, 0 ); + EXPECT_EQ( cross2( shiftOf( f, pts.defs[0], kx, ky ), shiftOf( f, pts.defs[1], kx, ky ) ), 0 ); + CutTrianglePredicates preds; + preds.reset( f ); + for ( int i = 0; i < 5; ++i ) + preds.addPoint( VertId( i ), pts.defs[i] ); + EXPECT_FALSE( preds.failed() ); + + // the model: every point with a wedge at P + delta * F / ( n.d ) for F = n x ( u x d ), with the perturbed normal n of f, d = b - a + // and u = w0 + w1 - a - b (see shiftOf), and the last one at P, so the orientation is the sign of cross( Fq - Fp, Fr - Fp ) + const SosModel m( { f[0], f[1], f[2], a, b, w[0], w[1], w[2], w[3], w[4], w[5], w[6], w[7] } ); + using M = SosModel; + const auto f0 = m.coords( f[0] ); + const auto nf = M::cross( M::sub( m.coords( f[1] ), f0 ), M::sub( m.coords( f[2] ), f0 ) ); + const auto ca = m.coords( a ), cb = m.coords( b ); + std::array shifts; + for ( int k = 0; k < 4; ++k ) + shifts[k] = M::cross( nf, M::cross( M::sub( M::sub( M::add( m.coords( w[2 * k] ), m.coords( w[2 * k + 1] ) ), ca ), cb ), M::sub( cb, ca ) ) ); + CcwStats ccwStats; + checkCcw( preds, pts, [&] ( int p, int q, int r ) + { + const auto u = M::sub( shifts[q], shifts[p] ), v = M::sub( shifts[r], shifts[p] ); + return M::productsDiffSign( u[kx], v[ky], u[ky], v[kx] ); + }, 0, ccwStats ); + EXPECT_EQ( ccwStats.exact, 10 ); +} + // The crossings of the cuts of f by other triangles in general position, which cross f in long segments, so that many of them cross: // with coordinates in the whole range of 2^30, where the exact positions in 512-bit integers decide every pair and every triangle, and up // to 2^20, where the rounded coordinates decide most of them; the predicates must agree with the exact positions, which the test finds @@ -1709,9 +2134,11 @@ TEST( MRMesh, CutTrianglePredicatesCrossingRules ) EXPECT_FALSE( preds.failed() ); // the definitions that make addPoint fail: a triangle twice (also with its vertices in another order), a triangle with two vertices of f - // (whose cut is a side), f itself, repeated ids in a triangle, and two cuts whose crossing is another point also after the perturbation: - // by triangles through a vertex of f, which they cross at, as two folds from it, and by triangles with a common edge, which they cross - // where that edge crosses f + // (whose cut is a side), f itself, repeated ids in a triangle, and two cuts by triangles through a vertex of f, as two folds from it, + // whose crossing is that vertex also after the perturbation, also with a common edge from that vertex, at either end of the edge, whose + // crossing with f is that vertex too (while the crossing of two cuts by triangles with a common edge is otherwise that of the edge moved + // along them, see CutTrianglePredicatesDeltaCrossing) + const auto e = vert( 24, 2, -2, 2 ); const PreciseCutPoint broken[] = { crossing( p, p ), @@ -1720,7 +2147,8 @@ TEST( MRMesh, CutTrianglePredicatesCrossingRules ) crossing( f, p ), crossing( p, { q[0], q[1], q[0] } ), crossing( { f[0], vert( 20, -2, -4, 2 ), vert( 21, -4, -2, -2 ) }, { vert( 22, 2, -6, 1 ), f[0], vert( 23, -4, 2, -1 ) } ), - crossing( { vert( 24, 1, 2, -3 ), vert( 25, 1, 2, 3 ), vert( 26, 6, 0, 1 ) }, { vert( 25, 1, 2, 3 ), vert( 24, 1, 2, -3 ), vert( 27, -3, 5, 2 ) } ), + crossing( { f[0], e, vert( 25, 4, -6, -1 ) }, { e, f[0], vert( 26, -6, 4, -1 ) } ), + crossing( { e, f[1], vert( 25, 4, -6, -1 ) }, { f[1], vert( 26, -6, 4, -1 ), e } ), }; for ( const auto& x : broken ) { @@ -1818,6 +2246,434 @@ TEST( MRMesh, CutTrianglePredicatesDefinedAlikeOnCut ) namespace { +// whether the cuts from XP to R and from XQ to RQ cross as ccw sees them; if so, their crossing Y at the common edge of the cuts +// must be between XP and R and between XQ and RQ along the sweep, as the boolean's sweep needs it +bool crossesAtY( const CutTrianglePredicates& preds, int xp, int r, int xq, int rq, int y ) +{ + auto ccw = [&] ( int i, int j, int k ) { return preds.ccw( VertId( i ), VertId( j ), VertId( k ) ); }; + auto less = [&] ( int i, int j ) { return preds.less( VertId( i ), VertId( j ) ); }; + const bool res = ccw( xp, r, xq ) != ccw( xp, r, rq ) && ccw( xq, rq, xp ) != ccw( xq, rq, r ); + if ( res ) + { + EXPECT_EQ( less( xp, y ), less( y, r ) ); + EXPECT_EQ( less( xq, y ), less( y, rq ) ); + } + EXPECT_FALSE( preds.failed() ); + return res; +} + +} // anonymous namespace + +// The crossing Y of the cuts by triangles P = abo and Q = abw of a multiple edge ab with f, defined alike with the crossings XP and XQ +// of its edges with the wedges o, o2 and w, w2 (see CutTrianglePredicates::shift_), with the end R of the cut by P, its crossing X +// with the cut by u, the ends of that cut and the end RQ of the cut by Q: Y moves from XP along the cut by P, and from XQ along the cut by Q, +// so the side of a point off the line of that cut decides the triangle of the two with it, and with a point of the line, the bulge +// of the line with X on it; ccw must be consistent (see checkCcw), the same for Y with its cuts swapped or rotated, and with all coordinates +// scaled to near 2^30; less must order XP, XQ and Y as the model of the shifts (see shiftOf) where Y is the crossing of the lines of the cuts +// through the shifted XP and XQ: with interleaved wedges, whose shifted cuts from XP and XQ cross at Y, between XP and R and between XQ and RQ, +// and with the wedge of XQ in the angle of that of XP, which reverses the shift of XP; also with P and Q in one plane, where only +// the perturbation turns the cuts apart; and the multiple edge in the plane of f, also of zero length, and f with a zero normal, +// where only the perturbation gives the shifts and the cuts, with the ids that make ab cross f after it, with ccw consistent; +// without the model (P and Q in one plane, on both sides of ab or overlapping, and the degenerate edges), Y must be between the ends +// of the cuts where ccw finds them crossing, as with the model, which some of them, as the overlapping P and Q, must give +TEST( MRMesh, CutTrianglePredicatesDeltaCrossing ) +{ + struct Case + { + Vector3i o2, w, w2; + bool crossing = false; // whether the shifted cuts cross, from XP to R and from XQ to RQ + bool parallel = false; // whether P and Q are in one plane, where the model of the shifts has no crossing of the cuts + }; + const Case cases[] = + { + { { -11, 8, 2 }, { 1, 9, 1 }, { 7, -10, -2 }, true }, // interleaved + { { -11, 8, 2 }, { 1, 9, 1 }, { 6, 8, -2 } }, // nested + { { -11, 8, 2 }, { -7, 1, 1 }, { 7, -10, -2 }, false, true }, // in one plane + { { -11, 8, 2 }, { 7, 1, 1 }, { 2, 9, -2 }, false, true }, // in one plane, overlapping + }; + int numInOnePlane = 0; // tables with P and Q in one plane where the cuts cross + // the table of ccw for the points with the coordinates x and y times m and z times mz, and with Y by the cuts in the order of variant + auto table = [&] ( const Case& c, int m, int mz, int variant, CcwStats& ccwStats ) + { + auto v = [&] ( int id, const Vector3i& p ) { return vert( id, p.x * m, p.y * m, p.z * mz ); }; + const Tri f = { v( 0, { -16, -16, 0 } ), v( 1, { 32, -16, 0 } ), v( 2, { -16, 32, 0 } ) }; + // ab crosses f at ( 1, 1 ); P cuts f along y = 1 to R = ( 5, 1 ) through X = ( 3, 1 ), and Q along x = 1 to RQ = ( 1, 5 ), + // or in the plane of P along y = 1 to RQ = ( -3, 1 ), or to RQ = ( 4, 1 ) overlapping P + const auto a = v( 3, { 1, 1, -1 } ), b = v( 4, { 1, 1, 1 } ), o = v( 5, { 9, 1, 1 } ), o2 = v( 6, c.o2 ); + const auto w = v( 7, c.w ), w2 = v( 8, c.w2 ); + const Tri p = { a, b, o }, q = { a, b, w }; + const Tri u = { v( 9, { 3, -4, -1 } ), v( 10, { 3, 6, -1 } ), v( 11, { 3, 1, 1 } ) }; + auto pts = cutPoints( f, {} ); + // XP, XQ and Y, marked on no cut, since their shifts move them off the cuts + pts.add( { .seg = { a, b }, .tri = f, .wedge = { o, o2 } }, 0 ); + pts.add( { .seg = { b, a }, .tri = f, .wedge = { w, w2 } }, 0 ); + const PreciseCutPoint ys[] = { { .tri = p, .tri2 = q }, { .tri = q, .tri2 = p }, { .tri = { b, o, a }, .tri2 = { w, a, b } } }; + pts.add( ys[variant], 0 ); + pts.add( { .seg = { a, o }, .tri = f }, cutBit( 0 ) ); + pts.add( { .tri = p, .tri2 = u }, cutBit( 0 ) | cutBit( 2 ) ); + pts.add( { .seg = { u[0], u[2] }, .tri = f }, cutBit( 2 ) ); + pts.add( { .seg = { u[1], u[2] }, .tri = f }, cutBit( 2 ) ); + pts.add( { .seg = { a, w }, .tri = f }, cutBit( 1 ) ); + const int n = int( pts.defs.size() ); + std::vector>> pos; + for ( const auto& def : pts.defs ) + pos.push_back( fractionOf( def ) ); + pos[5] = pos[3]; // Y is at ( 1, 1 ) before the shifts + pos[7] = Fraction{ { FastInt256( 3 * m ), FastInt256( m ), FastInt256( 0 ) }, FastInt256( 1 ) }; + CutTrianglePredicates preds; + preds.reset( f ); + for ( int i = 0; i < n; ++i ) + preds.addPoint( VertId( i ), pts.defs[i] ); + EXPECT_FALSE( preds.failed() ); + // the exact orientations of the triangles with at most one of XP, XQ and Y, at ( 1, 1 ) + checkCcw( preds, pts, [&] ( int i, int j, int k ) + { + const int numAlike = ( i >= 3 && i <= 5 ) + ( j >= 3 && j <= 5 ) + ( k >= 3 && k <= 5 ); + return numAlike < 2 ? orientFractions( *pos[i], *pos[j], *pos[k], 0, 1 ) : 0; + }, 0, ccwStats ); + // the side of the line of the cut decides, the same for all points on one side of it: of y = 1 for P, and of x = 1 for Q + // (or y = 1 in the plane of P) + for ( int k = 0; k < 2; ++k ) + { + const int axis = k == 0 || c.parallel ? 1 : 0; + int numOff = 0, numAgree = 0; + for ( int z = 0; z < n; ++z ) + { + const int side = z < 3 || z > 5 ? compareFractions( *pos[z], *pos[3], axis ) : 0; + numOff += side != 0; + numAgree += side != 0 && preds.ccw( VertId( 3 + k ), 5_v, VertId( z ) ) == ( side > 0 ); + } + EXPECT_GE( numOff, 5 ); + EXPECT_TRUE( numAgree == 0 || numAgree == numOff ); + } + // on the line, the bulge + EXPECT_EQ( preds.ccw( 3_v, 5_v, 6_v ), preds.ccw( 3_v, 5_v, 7_v ) ); + // Y between the ends of the cuts where they cross, which the model below must give where it applies + const bool crosses = crossesAtY( preds, 3, 6, 4, 10, 5 ); + numInOnePlane += c.parallel && crosses; + if ( m == 1 && !c.parallel ) + { + // the model: the shifts sP and sQ of XP and XQ, the first one reversed if the triangles of XQ are in its angle, and the other way round, + // and Y = XP + alpha * tP = XQ + beta * tQ for the directions tP and tQ of the cuts by P and Q from ( 1, 1 ) toward o and w + const auto [kx, ky] = projectionAxes( f ); + auto ray = [&] ( const PreciseVertCoords& x ) { return shiftOf( f, { .seg = { a, b }, .wedge = { x, x } }, kx, ky ); }; + const Vector2i64 rays[] = { ray( o ), ray( o2 ), ray( w ), ray( w2 ) }; + auto shift = [&] ( int k ) + { + const bool nested = insideAngle2( rays[2 * k], rays[2 * k + 1], rays[2 - 2 * k] ) && insideAngle2( rays[2 * k], rays[2 * k + 1], rays[3 - 2 * k] ); + const auto s = shiftOf( f, pts.defs[3 + k], kx, ky ); + return nested ? -s : s; + }; + const auto tP = rays[0], tQ = rays[2], ds = shift( 1 ) - shift( 0 ); + const int alpha = sgn( cross2( ds, tQ ) ) * sgn( cross2( tP, tQ ) ), beta = sgn( cross2( ds, tP ) ) * sgn( cross2( tP, tQ ) ); + EXPECT_TRUE( alpha != 0 && beta != 0 ); + auto forward = [] ( const Vector2i64& d ) { return d.x != 0 ? d.x > 0 : d.y > 0; }; + EXPECT_EQ( preds.less( 3_v, 4_v ), forward( ds ) ); + EXPECT_EQ( preds.less( 3_v, 5_v ), forward( alpha > 0 ? tP : -tP ) ); + EXPECT_EQ( preds.less( 4_v, 5_v ), forward( beta > 0 ? tQ : -tQ ) ); + EXPECT_EQ( c.crossing, alpha > 0 && beta > 0 ); + EXPECT_EQ( crosses, c.crossing ); + } + std::vector res; + for ( int i = 0; i < n; ++i ) + for ( int j = 0; j < n; ++j ) + for ( int k = 0; k < n; ++k ) + res.push_back( i != j && j != k && k != i && preds.ccw( VertId( i ), VertId( j ), VertId( k ) ) ); + EXPECT_FALSE( preds.failed() ); + return res; + }; + CcwStats ccwStats; + for ( const auto& c : cases ) + { + const auto base = table( c, 1, 1, 0, ccwStats ); + if ( &c == &cases[3] && cTrialDivisor > 1 ) + continue; // Debug takes the overlapping P and Q only as they are, since their tables are slow there + for ( int variant = 1; variant < 3; ++variant ) + EXPECT_EQ( table( c, 1, 1, variant, ccwStats ), base ); + EXPECT_EQ( table( c, ( 1 << 25 ) - 1, ( 1 << 29 ) - 1, 0, ccwStats ), base ); + } + + // the wedges o, o2, w, w2 of DefinedAlikeAlongSide, and two sets that interleave around ab with other projections of their wedge vectors + // along ab, so that the shifted cuts cross, made for ab of zero length at ( 2, 0, 0 ) and for ab from ( 12, -1, -1 ) to ( 12, 1, 1 ) across + // the flat f; every segment takes all of them, and the cuts must cross with some + const std::array wedgeSets[] = { { Vector3i( 3, 5, 4 ), Vector3i( 5, -4, 3 ), Vector3i( 2, 3, -5 ), Vector3i( 6, -2, -2 ) }, + { Vector3i( 3, 5, 4 ), Vector3i( -2, -2, 3 ), Vector3i( -1, 4, -5 ), Vector3i( 6, -5, -2 ) }, + { Vector3i( 13, 3, 4 ), Vector3i( 10, -3, -5 ), Vector3i( 11, 3, 4 ), Vector3i( 14, -3, -5 ) } }; + // the multiple edge in the plane of f along a side, of zero length or not, and f with a zero normal, with the vertices of f, XP, XQ, Y + // and the other points of the cuts by P and Q, where only the perturbation gives the shifts and the cuts and no model the order: + // ccw must be consistent (see checkCcw), and Y between the ends of the cuts where they cross (see crossesAtY), counted in numCrossing + auto degenerate = [&] ( const Tri& f, const PreciseVertCoords& a, const PreciseVertCoords& b, const std::array& wedges, int& numCrossing ) + { + auto v = [&] ( int k ) { return PreciseVertCoords{ VertId( 10 + k ), wedges[k] }; }; + const auto o = v( 0 ), o2 = v( 1 ), w = v( 2 ), w2 = v( 3 ); + auto pts = cutPoints( f, { { a, b, o }, { a, b, w } } ); + // the crossing of ab with f, on both cuts, becomes XP, and the other end of each cut is its only other point + const auto it = std::find_if( pts.defs.begin(), pts.defs.end(), [&] ( const PreciseCutPoint& p ) { return p.seg[0].id == a.id && p.seg[1].id == b.id; } ); + ASSERT_TRUE( it != pts.defs.end() ); + const int xp = int( it - pts.defs.begin() ), xq = int( pts.defs.size() ), y = xq + 1; + pts.defs[xp].wedge = { o, o2 }; + pts.lines[xp] = 0; + std::array ends{}; + for ( int j = 0; j < 2; ++j ) + { + int num = 0; + for ( int i = 0; i < xq; ++i ) + if ( pts.lines[i] & cutBit( j ) ) + ends[j] = i, ++num; + ASSERT_EQ( num, 1 ); + } + pts.add( { .seg = { b, a }, .tri = f, .wedge = { w, w2 } }, 0 ); + pts.add( { .tri = { a, b, o }, .tri2 = { a, b, w } }, 0 ); + CutTrianglePredicates preds; + preds.reset( f ); + for ( int i = 0; i < int( pts.defs.size() ); ++i ) + preds.addPoint( VertId( i ), pts.defs[i] ); + EXPECT_FALSE( preds.failed() ); + // Debug checks the consistency with the first wedges only, since the flat f with the last ones takes seconds there + if ( wedges == wedgeSets[0] || cTrialDivisor == 1 ) + checkCcw( preds, pts, [] ( int, int, int ) { return 0; }, 0, ccwStats ); + numCrossing += crossesAtY( preds, xp, ends[0], xq, ends[1], y ); + }; + const Tri g = { vert( 1, 0, 0, 0 ), vert( 3, 8, 0, 0 ), vert( 4, 0, 8, 0 ) }, flat = { vert( 1, 0, 0, 0 ), vert( 3, 8, 0, 0 ), vert( 4, 16, 0, 0 ) }; + const int ids[] = { 0, 2, 5, 6 }; + int numInPlane = 0, numZeroLength = 0, numFlat = 0; + std::array numCrossing{}; // in the plane, of zero length, flat + for ( int ia : ids ) + for ( int ib : ids ) + { + if ( ia == ib ) + continue; + for ( int ta = -2; ta <= 10; ta += 4 ) + for ( int tb = -2; tb <= 10; tb += 4 ) + { + const auto a = vert( ia, ta, 0, 0 ), b = vert( ib, tb, 0, 0 ); + int& num = ta == tb ? numZeroLength : numInPlane; + if ( num == 0 && doTriangleSegmentIntersect( { g[0], g[1], g[2], a, b } ) ) + { + for ( const auto& ws : wedgeSets ) + degenerate( g, a, b, ws, numCrossing[ta == tb] ); + ++num; + } + } + for ( const Vector3i d : { Vector3i( 0, 1, 1 ), Vector3i( 0, 1, -1 ), Vector3i( 0, 1, 0 ), Vector3i( 0, 0, 1 ), Vector3i( 1, 1, 1 ) } ) + for ( int x : { 4, 12 } ) + { + const PreciseVertCoords a{ VertId( ia ), Vector3i( x, 0, 0 ) - d }, b{ VertId( ib ), Vector3i( x, 0, 0 ) + d }; + if ( numFlat == 0 && doTriangleSegmentIntersect( { flat[0], flat[1], flat[2], a, b } ) ) + { + for ( const auto& ws : wedgeSets ) + degenerate( flat, a, b, ws, numCrossing[2] ); + ++numFlat; + } + } + } + EXPECT_EQ( numInPlane, 1 ); + EXPECT_EQ( numZeroLength, 1 ); + EXPECT_EQ( numFlat, 1 ); + for ( int num : numCrossing ) + { + EXPECT_GE( num, 1 ); + } + EXPECT_GE( numInOnePlane, 1 ); +} + +// The crossings of the cuts by the triangles P = abo, Q = abw and S = abv of a triple edge ab with f, defined alike with the crossings XP, XQ +// and XS of its edges with distinct wedges (see CutTrianglePredicates::shift_): Y1 of P and Q and Y2 of P and S, which are on the line +// of the cut by P with XP at every stage, and Y3 of Q and S, with the ends R, RQ and RS of the cuts, and with the crossing X of the cut by P +// with the cut by u or without it: the side of a point off the line of a cut decides the triangles of two points of the line with it, +// the bulge (the order along the sweep) the triangles of three points of the line defined alike, and with X, of any three points of the line +// of P; ccw must be consistent (see checkCcw), the same with the cuts of every crossing swapped and with the points in another order +TEST( MRMesh, CutTrianglePredicatesTripleEdge ) +{ + const Tri f = { vert( 0, -16, -16, 0 ), vert( 1, 32, -16, 0 ), vert( 2, -16, 32, 0 ) }; + // ab crosses f at ( 1, 1 ), and P, Q and S cut f from there toward o, w and v to the crossings R = ( 5, 1 ), RQ = ( 1, 5 ) and RS = ( -3, -2 ) + // of ao, aw and av, and the cut by u crosses that by P at X = ( 3, 1 ); the wedges of XP, XQ and XS interleave, none in the angle of another + const auto a = vert( 3, 1, 1, -1 ), b = vert( 4, 1, 1, 1 ); + const auto o = vert( 5, 9, 1, 1 ), o2 = vert( 6, -11, 8, 2 ), w = vert( 7, 1, 9, 1 ), w2 = vert( 8, 7, -10, -2 ); + const auto v = vert( 9, -7, -5, 1 ), v2 = vert( 10, 10, 5, -2 ); + const Tri p = { a, b, o }, q = { a, b, w }, s = { a, b, v }; + const Tri u = { vert( 11, 3, -4, -1 ), vert( 12, 3, 6, -1 ), vert( 13, 3, 1, 1 ) }; + CcwStats ccwStats; + // the table of ccw for the points 0 to 11 (and 12 to 14 with X), with the cuts of the crossings swapped or not, set in reverse order + // after the vertices of f or not + auto table = [&] ( bool withX, bool swapped, bool reversed ) + { + auto pts = cutPoints( f, {} ); + // XP, XQ, XS, Y1, Y2 and Y3, marked on no cut, since their shifts move them off the cuts + pts.add( { .seg = { a, b }, .tri = f, .wedge = { o, o2 } }, 0 ); + pts.add( { .seg = { b, a }, .tri = f, .wedge = { w, w2 } }, 0 ); + pts.add( { .seg = { a, b }, .tri = f, .wedge = { v2, v } }, 0 ); + auto crossing = [&] ( const Tri& x, const Tri& y ) { return swapped ? PreciseCutPoint{ .tri = y, .tri2 = x } : PreciseCutPoint{ .tri = x, .tri2 = y }; }; + pts.add( crossing( p, q ), 0 ); + pts.add( crossing( p, s ), 0 ); + pts.add( crossing( q, s ), 0 ); + pts.add( { .seg = { a, o }, .tri = f }, cutBit( 0 ) ); + pts.add( { .seg = { a, w }, .tri = f }, cutBit( 1 ) ); + pts.add( { .seg = { a, v }, .tri = f }, cutBit( 2 ) ); + if ( withX ) + { + pts.add( { .tri = p, .tri2 = u }, cutBit( 0 ) | cutBit( 3 ) ); + pts.add( { .seg = { u[0], u[2] }, .tri = f }, cutBit( 3 ) ); + pts.add( { .seg = { u[1], u[2] }, .tri = f }, cutBit( 3 ) ); + } + const int n = int( pts.defs.size() ); + std::vector>> pos; + for ( const auto& def : pts.defs ) + pos.push_back( fractionOf( def ) ); + for ( int i = 6; i < 9; ++i ) + pos[i] = pos[3]; // Y1, Y2 and Y3 are at ( 1, 1 ) before the shifts + if ( withX ) + pos[12] = Fraction{ { 3, 1, 0 }, 1 }; + // point i is set as id[i] + std::vector id( n ); + auto set = pts; + for ( int i = 0; i < n; ++i ) + { + id[i] = reversed && i >= 3 ? n + 2 - i : i; + set.defs[id[i]] = pts.defs[i]; + set.lines[id[i]] = pts.lines[i]; + } + CutTrianglePredicates preds; + preds.reset( f ); + for ( int i = 0; i < n; ++i ) + preds.addPoint( VertId( i ), set.defs[i] ); + EXPECT_FALSE( preds.failed() ); + // the exact orientations of the triangles with at most one point defined alike, at ( 1, 1 ) + std::vector layout( n ); + for ( int i = 0; i < n; ++i ) + layout[id[i]] = i; + checkCcw( preds, set, [&] ( int i, int j, int k ) + { + auto alike = [&] ( int x ) { return layout[x] >= 3 && layout[x] <= 8; }; + return int( alike( i ) ) + int( alike( j ) ) + int( alike( k ) ) < 2 + ? orientFractions( *pos[layout[i]], *pos[layout[j]], *pos[layout[k]], 0, 1 ) : 0; + }, 0, ccwStats ); + auto ccw = [&] ( int i, int j, int k ) { return preds.ccw( VertId( id[i] ), VertId( id[j] ), VertId( id[k] ) ); }; + auto less = [&] ( int i, int j ) { return preds.less( VertId( id[i] ), VertId( id[j] ) ); }; + auto bulge = [&] ( int i, int j, int k ) { return int( less( i, j ) ) + int( less( j, k ) ) + int( less( k, i ) ) == 1; }; + // the lines of the cuts by P, Q and S with their points defined alike, and their ends + const int lines[3][4] = { { 3, 6, 7, 9 }, { 4, 6, 8, 10 }, { 5, 7, 8, 11 } }; + for ( const auto& l : lines ) + { + // the side of a point off the line decides, the same for all points on one side of it + for ( const auto& [x, y] : { std::pair{ l[0], l[1] }, std::pair{ l[0], l[2] }, std::pair{ l[1], l[2] } } ) + { + int numOff = 0, numAgree = 0; + for ( int z = 0; z < n; ++z ) + { + const int side = z < 3 || z > 8 ? orientFractions( *pos[3], *pos[l[3]], *pos[z], 0, 1 ) : 0; + numOff += side != 0; + numAgree += side != 0 && ccw( x, y, z ) == ( side > 0 ); + } + EXPECT_GE( numOff, 5 ); + EXPECT_TRUE( numAgree == 0 || numAgree == numOff ); + } + EXPECT_EQ( ccw( l[0], l[1], l[2] ), bulge( l[0], l[1], l[2] ) ); + } + // with X, the bulge of all points of the line of P + if ( withX ) + { + const int onP[] = { 3, 6, 7, 9, 12 }; + for ( int i : onP ) + for ( int j : onP ) + for ( int k : onP ) + if ( i < j && j < k ) + { + EXPECT_EQ( ccw( i, j, k ), bulge( i, j, k ) ); + } + } + std::vector res; + for ( int i = 0; i < n; ++i ) + for ( int j = 0; j < n; ++j ) + for ( int k = 0; k < n; ++k ) + res.push_back( i != j && j != k && k != i && ccw( i, j, k ) ); + EXPECT_FALSE( preds.failed() ); + return res; + }; + for ( bool withX : { false, true } ) + { + const auto base = table( withX, false, false ); + EXPECT_EQ( table( withX, true, false ), base ); + EXPECT_EQ( table( withX, false, true ), base ); + } +} + +// The crossings Y1 of the cuts by P = abo and Q = abw, which overlap in one plane, and Y2 of the cuts by S = abs and T = abt of a quadruple edge ab +// with f, defined alike with the crossings XP, XQ, XS and XT of its edges (see CutTrianglePredicates::shift_), on no common cut, where the cuts +// cross as ccw sees them, between their ends (see crossesAtY), and the crossing r of two other cuts: only the perturbation of a, b, o or w +// turns P and Q apart and gives Y1 its shift, which decides the triangle Y1, Y2, r by the first-order term; the expansion of that term takes +// 19 vertices, whose degrees do not fit in int64, so it ends before the stages of the largest ids: with a, b, o and w of the smallest ids, +// it decides, the same in every order of the points, and ccw must be consistent (see checkCcw), and with them of the largest +// ids, it ends before their stages, and ccw must fail instead of leaving the triangle to the second-order term +TEST( MRMesh, CutTrianglePredicatesQuadrupleEdge ) +{ + CcwStats ccwStats; + for ( bool last : { false, true } ) + { + // a, b, o and w take the ids from first, and the other vertices those from next + const int first = last ? 15 : 0; + int next = last ? 0 : 4; + auto v = [&] ( int x, int y, int z ) { return vert( next++, x, y, z ); }; + const Tri f = { v( -16, -16, 0 ), v( 32, -16, 0 ), v( -16, 32, 0 ) }; + // ab crosses f at ( 1, 1 ), P and Q cut it along y = 1 to ( 5, 1 ) and ( 4, 1 ), S along x = 1 to ( 1, 5 ) and T along y = x + // to ( -0.5, -0.5 ), and u and u2 along x = -5 and y = -7 + const auto a = vert( first, 1, 1, -1 ), b = vert( first + 1, 1, 1, 1 ), o = vert( first + 2, 9, 1, 1 ), w = vert( first + 3, 7, 1, 1 ); + const auto o2 = v( -11, 8, 2 ), w2 = v( 2, 9, -2 ), s = v( 1, 9, 1 ), s2 = v( -7, 0, -2 ), t = v( -2, -2, 1 ), t2 = v( -3, 13, -2 ); + const Tri u = { v( -5, -12, -1 ), v( -5, 6, -1 ), v( -5, -3, 2 ) }, u2 = { v( -12, -7, -1 ), v( 8, -7, -1 ), v( -2, -7, 2 ) }; + auto pts = cutPoints( f, {} ); + pts.add( { .seg = { a, b }, .tri = f, .wedge = { o, o2 } }, 0 ); + pts.add( { .seg = { b, a }, .tri = f, .wedge = { w, w2 } }, 0 ); + pts.add( { .seg = { a, b }, .tri = f, .wedge = { s, s2 } }, 0 ); + pts.add( { .seg = { b, a }, .tri = f, .wedge = { t2, t } }, 0 ); + pts.add( { .tri = { a, b, o }, .tri2 = { a, b, w } }, 0 ); + pts.add( { .tri = { b, a, s }, .tri2 = { a, b, t } }, 0 ); + pts.add( { .tri = u, .tri2 = u2 }, 0 ); + CutTrianglePredicates preds; + auto start = [&] ( const CutPoints& set ) + { + preds.reset( f ); + for ( int i = 0; i < int( set.defs.size() ); ++i ) + preds.addPoint( VertId( i ), set.defs[i] ); + EXPECT_FALSE( preds.failed() ); + }; + // with the other ends of the cuts by P, Q, S and T, the crossings of ao, aw, as and at (points 10 to 13) + auto withEnds = pts; + for ( const auto& e : { o, w, s, t } ) + withEnds.add( { .seg = { a, e }, .tri = f }, 0 ); + start( withEnds ); + EXPECT_TRUE( crossesAtY( preds, 3, 10, 4, 11, 7 ) ); + EXPECT_TRUE( crossesAtY( preds, 5, 12, 6, 13, 8 ) ); + // Y1, Y2 and r (points 7, 8, 9), and if it decides, in every other order, each from the start, so that no cached orientation decides it: + // the rotations of 7, 8, 9 keep the orientation, and the other orders flip it + start( pts ); + const bool c = preds.ccw( 7_v, 8_v, 9_v ); + EXPECT_EQ( preds.failed(), last ); + if ( last ) + continue; + std::array order = { 7, 8, 9 }; + while ( std::next_permutation( order.begin(), order.end() ) ) + { + start( pts ); + EXPECT_EQ( preds.ccw( VertId( order[0] ), VertId( order[1] ), VertId( order[2] ) ), c == ( ( order[1] - order[0] + 3 ) % 3 == 1 ) ); + EXPECT_FALSE( preds.failed() ); + } + std::vector>> pos; + for ( const auto& def : pts.defs ) + pos.push_back( fractionOf( def ) ); + pos[7] = pos[8] = pos[3]; // Y1 and Y2 are at ( 1, 1 ) before the shifts + pos[9] = Fraction{ { -5, -7, 0 }, 1 }; + start( pts ); + checkCcw( preds, pts, [&] ( int i, int j, int k ) + { + const int numAlike = ( i >= 3 && i <= 8 ) + ( j >= 3 && j <= 8 ) + ( k >= 3 && k <= 8 ); + return numAlike < 2 ? orientFractions( *pos[i], *pos[j], *pos[k], 0, 1 ) : 0; + }, 0, ccwStats ); + } +} + +namespace +{ + // the triangles of CutTrianglePredicatesCrossingsCollinear: f in the plane z = 0, and vertical triangles whose cuts cross at ( 0, 0 ) (the planes x = 0 // and x = y), at ( 4, 0 ) (x = 4 and x + y = 4) and, with three crossings, at ( 8, 0 ) (x = 8 and x - y = 8), or else a vertical edge crossing f // at ( 8, 0 ); the ids in a random order diff --git a/source/MRTest/MRPrecisePredicatesTests.cpp b/source/MRTest/MRPrecisePredicatesTests.cpp index 3e38b2b319bf..12c2879a3c1a 100644 --- a/source/MRTest/MRPrecisePredicatesTests.cpp +++ b/source/MRTest/MRPrecisePredicatesTests.cpp @@ -1213,6 +1213,23 @@ TEST( MRMesh, lowestTermOfSumOfProducts ) EXPECT_EQ( lowestTermOfProductsDiff( a64, one64, one64, d64, 2 ), ( std::pair( 2, -1 ) ) ); } +// mulAs with a degree cap at run time keeps the terms of the full product up to the cap: none for a cap below the lowest degree, +// and for a cap between two degrees the same as for the lower one +TEST( MRMesh, mulAsMaxDeg ) +{ + using P = SparsePolynomial; + const P a( 1, 2, 1, 4, 1 ); // 1 + x^2 + x^4 + const P b( 0, 3, 2, 5, 1 ); // 2x^3 + x^5 + const auto full = mulAs( a, b ); // 2x^3 + 3x^5 + 3x^7 + x^9, with the products of equal degrees summed + EXPECT_EQ( full.get().size(), 4 ); + for ( int maxDeg = 0; maxDeg <= 10; ++maxDeg ) + { + auto terms = full.get(); + std::erase_if( terms, [&] ( const P::Term& t ) { return t.first > maxDeg; } ); + EXPECT_EQ( mulAs( a, b, maxDeg ).get(), terms ); + } +} + TEST( MRMesh, PerturbationStages ) { // ids 7, 3, 7, 5: the stages of 3, 5, 7 with the degrees 1, r(3), r(3) * r(5)