0028681: UnifySameDomain distorts face boundary when merges a chain of small linear...
[occt.git] / src / ShapeUpgrade / ShapeUpgrade_UnifySameDomain.cxx
CommitLineData
973c2be1 1// Created on: 2012-06-09
2// Created by: jgv@ROLEX
3// Copyright (c) 2012-2014 OPEN CASCADE SAS
4//
5// This file is part of Open CASCADE Technology software library.
6//
d5f74e42 7// This library is free software; you can redistribute it and/or modify it under
8// the terms of the GNU Lesser General Public License version 2.1 as published
973c2be1 9// by the Free Software Foundation, with special exception defined in the file
10// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
11// distribution for complete text of the license and disclaimer of any warranty.
12//
13// Alternatively, this file may be used under the terms of Open CASCADE
14// commercial license or contractual agreement.
2277323d 15
42cf5bc1 16
2277323d 17#include <BRep_Builder.hxx>
42cf5bc1 18#include <BRep_Tool.hxx>
19#include <BRepLib.hxx>
20#include <BRepLib_MakeEdge.hxx>
21#include <BRepTopAdaptor_TopolTool.hxx>
22#include <GC_MakeCircle.hxx>
23#include <Geom2d_Line.hxx>
2277323d 24#include <Geom2d_TrimmedCurve.hxx>
2277323d 25#include <Geom2dConvert.hxx>
2277323d 26#include <Geom2dConvert_CompCurveToBSplineCurve.hxx>
2277323d 27#include <Geom_BezierCurve.hxx>
42cf5bc1 28#include <Geom_BSplineCurve.hxx>
29#include <Geom_Circle.hxx>
30#include <Geom_CylindricalSurface.hxx>
31#include <Geom_ElementarySurface.hxx>
32#include <Geom_Line.hxx>
33#include <Geom_OffsetSurface.hxx>
f16a6cc5 34#include <Geom_Plane.hxx>
42cf5bc1 35#include <Geom_RectangularTrimmedSurface.hxx>
36#include <Geom_Surface.hxx>
37#include <Geom_SurfaceOfLinearExtrusion.hxx>
38#include <Geom_SurfaceOfRevolution.hxx>
39#include <Geom_SweptSurface.hxx>
40#include <Geom_TrimmedCurve.hxx>
41#include <GeomAdaptor_HSurface.hxx>
42#include <GeomConvert.hxx>
43#include <GeomConvert_CompCurveToBSplineCurve.hxx>
44#include <GeomLib_IsPlanarSurface.hxx>
45#include <gp_Cylinder.hxx>
46#include <gp_Dir.hxx>
47#include <gp_Lin.hxx>
48#include <IntPatch_ImpImpIntersection.hxx>
49#include <ShapeAnalysis_Edge.hxx>
2277323d 50#include <ShapeAnalysis_WireOrder.hxx>
51#include <ShapeBuild_Edge.hxx>
42cf5bc1 52#include <ShapeBuild_ReShape.hxx>
2277323d 53#include <ShapeFix_Edge.hxx>
42cf5bc1 54#include <ShapeFix_Face.hxx>
2277323d 55#include <ShapeFix_Shell.hxx>
42cf5bc1 56#include <ShapeFix_Wire.hxx>
42cf5bc1 57#include <ShapeUpgrade_UnifySameDomain.hxx>
58#include <Standard_Type.hxx>
59#include <TColGeom2d_Array1OfBSplineCurve.hxx>
60#include <TColGeom2d_HArray1OfBSplineCurve.hxx>
61#include <TColGeom2d_SequenceOfBoundedCurve.hxx>
62#include <TColGeom_Array1OfBSplineCurve.hxx>
63#include <TColGeom_HArray1OfBSplineCurve.hxx>
42cf5bc1 64#include <TColGeom_SequenceOfSurface.hxx>
65#include <TColStd_Array1OfReal.hxx>
66#include <TColStd_MapOfInteger.hxx>
67#include <TopExp.hxx>
68#include <TopExp_Explorer.hxx>
69#include <TopoDS.hxx>
70#include <TopoDS_Edge.hxx>
71#include <TopoDS_Face.hxx>
72#include <TopoDS_Shape.hxx>
73#include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
74#include <TopTools_IndexedMapOfShape.hxx>
75#include <TopTools_ListIteratorOfListOfShape.hxx>
b4d4dbe8 76#include <TopTools_MapOfShape.hxx>
42cf5bc1 77#include <TopTools_SequenceOfShape.hxx>
f7d70540 78#include <gp_Circ.hxx>
79#include <BRepAdaptor_Curve.hxx>
f0144633 80#include <BRepAdaptor_Curve2d.hxx>
81#include <gp_Vec2d.hxx>
f7d70540 82
25e59720 83IMPLEMENT_STANDARD_RTTIEXT(ShapeUpgrade_UnifySameDomain,Standard_Transient)
92efcf78 84
f7d70540 85struct SubSequenceOfEdges
86{
87 TopTools_SequenceOfShape SeqsEdges;
88 TopoDS_Edge UnionEdges;
89};
90
f0144633 91static Standard_Boolean IsLikeSeam(const TopoDS_Edge& anEdge,
92 const TopoDS_Face& aFace,
93 const Handle(Geom_Surface)& aBaseSurface)
94{
95 if (!aBaseSurface->IsUPeriodic() && !aBaseSurface->IsVPeriodic())
96 return Standard_False;
97
98 BRepAdaptor_Curve2d BAcurve2d(anEdge, aFace);
99 gp_Pnt2d FirstPoint, LastPoint;
100 gp_Vec2d FirstDir, LastDir;
101 BAcurve2d.D1(BAcurve2d.FirstParameter(), FirstPoint, FirstDir);
102 BAcurve2d.D1(BAcurve2d.LastParameter(), LastPoint, LastDir);
103 Standard_Real Length = FirstDir.Magnitude();
104 if (Length <= gp::Resolution())
105 return Standard_False;
106 else
107 FirstDir /= Length;
108 Length = LastDir.Magnitude();
109 if (Length <= gp::Resolution())
110 return Standard_False;
111 else
112 LastDir /= Length;
113
114 Standard_Real Tol = 1.e-7;
115 if (aBaseSurface->IsUPeriodic() &&
116 (Abs(FirstDir.X()) < Tol) &&
117 (Abs(LastDir.X()) < Tol))
118 return Standard_True;
119
120 if (aBaseSurface->IsVPeriodic() &&
121 (Abs(FirstDir.Y()) < Tol) &&
122 (Abs(LastDir.Y()) < Tol))
123 return Standard_True;
124
125 return Standard_False;
126}
2277323d 127
128//=======================================================================
129//function : AddOrdinaryEdges
130//purpose : auxilary
131//=======================================================================
132// adds edges from the shape to the sequence
133// seams and equal edges are dropped
134// Returns true if one of original edges dropped
135static Standard_Boolean AddOrdinaryEdges(TopTools_SequenceOfShape& edges,
136 const TopoDS_Shape aShape,
137 Standard_Integer& anIndex)
138{
139 //map of edges
140 TopTools_IndexedMapOfShape aNewEdges;
141 //add edges without seams
142 for(TopExp_Explorer exp(aShape,TopAbs_EDGE); exp.More(); exp.Next()) {
143 TopoDS_Shape edge = exp.Current();
144 if(aNewEdges.Contains(edge))
3f5aa017 145 aNewEdges.RemoveKey(edge);
2277323d 146 else
147 aNewEdges.Add(edge);
148 }
149
150 Standard_Boolean isDropped = Standard_False;
151 //merge edges and drop seams
152 Standard_Integer i;
153 for (i = 1; i <= edges.Length(); i++) {
154 TopoDS_Shape current = edges(i);
155 if(aNewEdges.Contains(current)) {
156
3f5aa017 157 aNewEdges.RemoveKey(current);
2277323d 158 edges.Remove(i);
159 i--;
160
161 if(!isDropped) {
162 isDropped = Standard_True;
163 anIndex = i;
164 }
165 }
166 }
167
9ed6494b 168 //add edges to the sequence
2277323d 169 for (i = 1; i <= aNewEdges.Extent(); i++)
170 edges.Append(aNewEdges(i));
171
172 return isDropped;
173}
174
175//=======================================================================
176//function : getCylinder
177//purpose : auxilary
178//=======================================================================
179static Standard_Boolean getCylinder(Handle(Geom_Surface)& theInSurface,
180 gp_Cylinder& theOutCylinder)
181{
182 Standard_Boolean isCylinder = Standard_False;
183
184 if (theInSurface->IsKind(STANDARD_TYPE(Geom_CylindricalSurface))) {
185 Handle(Geom_CylindricalSurface) aGC = Handle(Geom_CylindricalSurface)::DownCast(theInSurface);
186
187 theOutCylinder = aGC->Cylinder();
188 isCylinder = Standard_True;
189 }
190 else if (theInSurface->IsKind(STANDARD_TYPE(Geom_SurfaceOfRevolution))) {
191 Handle(Geom_SurfaceOfRevolution) aRS =
192 Handle(Geom_SurfaceOfRevolution)::DownCast(theInSurface);
193 Handle(Geom_Curve) aBasis = aRS->BasisCurve();
194 if (aBasis->IsKind(STANDARD_TYPE(Geom_Line))) {
195 Handle(Geom_Line) aBasisLine = Handle(Geom_Line)::DownCast(aBasis);
196 gp_Dir aDir = aRS->Direction();
197 gp_Dir aBasisDir = aBasisLine->Position().Direction();
198 if (aBasisDir.IsParallel(aDir, Precision::Angular())) {
199 // basis line is parallel to the revolution axis: it is a cylinder
200 gp_Pnt aLoc = aRS->Location();
201 Standard_Real aR = aBasisLine->Lin().Distance(aLoc);
202 gp_Ax3 aCylAx (aLoc, aDir);
203
204 theOutCylinder = gp_Cylinder(aCylAx, aR);
205 isCylinder = Standard_True;
206 }
207 }
208 }
209 else if (theInSurface->IsKind(STANDARD_TYPE(Geom_SurfaceOfLinearExtrusion))) {
210 Handle(Geom_SurfaceOfLinearExtrusion) aLES =
211 Handle(Geom_SurfaceOfLinearExtrusion)::DownCast(theInSurface);
212 Handle(Geom_Curve) aBasis = aLES->BasisCurve();
213 if (aBasis->IsKind(STANDARD_TYPE(Geom_Circle))) {
214 Handle(Geom_Circle) aBasisCircle = Handle(Geom_Circle)::DownCast(aBasis);
215 gp_Dir aDir = aLES->Direction();
216 gp_Dir aBasisDir = aBasisCircle->Position().Direction();
217 if (aBasisDir.IsParallel(aDir, Precision::Angular())) {
218 // basis circle is normal to the extrusion axis: it is a cylinder
219 gp_Pnt aLoc = aBasisCircle->Location();
220 Standard_Real aR = aBasisCircle->Radius();
221 gp_Ax3 aCylAx (aLoc, aDir);
222
223 theOutCylinder = gp_Cylinder(aCylAx, aR);
224 isCylinder = Standard_True;
225 }
226 }
227 }
228 else {
229 }
230
231 return isCylinder;
232}
233
234//=======================================================================
235//function : ClearRts
236//purpose : auxilary
237//=======================================================================
238static Handle(Geom_Surface) ClearRts(const Handle(Geom_Surface)& aSurface)
239{
240 if(aSurface->IsKind(STANDARD_TYPE(Geom_RectangularTrimmedSurface))) {
241 Handle(Geom_RectangularTrimmedSurface) rts =
242 Handle(Geom_RectangularTrimmedSurface)::DownCast(aSurface);
243 return rts->BasisSurface();
244 }
245 return aSurface;
246}
247
248//=======================================================================
10ce3246 249//function : GetNormalToSurface
250//purpose : Gets the normal to surface by the given parameter on edge.
251// Returns True if normal was computed.
252//=======================================================================
253static Standard_Boolean GetNormalToSurface(const TopoDS_Face& theFace,
254 const TopoDS_Edge& theEdge,
255 const Standard_Real theP,
256 gp_Dir& theNormal)
257{
258 Standard_Real f, l;
259 // get 2d curve to get point in 2d
260 const Handle(Geom2d_Curve)& aC2d = BRep_Tool::CurveOnSurface(theEdge, theFace, f, l);
261 if (aC2d.IsNull()) {
262 return Standard_False;
263 }
264 //
265 // 2d point
266 gp_Pnt2d aP2d;
267 aC2d->D0(theP, aP2d);
268 //
269 // get D1
270 gp_Vec aDU, aDV;
271 gp_Pnt aP3d;
272 TopLoc_Location aLoc;
273 const Handle(Geom_Surface)& aS = BRep_Tool::Surface(theFace, aLoc);
274 aS->D1(aP2d.X(), aP2d.Y(), aP3d, aDU, aDV);
275 //
276 // compute normal
277 gp_Vec aVNormal = aDU.Crossed(aDV);
278 if (aVNormal.Magnitude() < Precision::Confusion()) {
279 return Standard_False;
280 }
281 //
282 if (theFace.Orientation() == TopAbs_REVERSED) {
283 aVNormal.Reverse();
284 }
285 //
286 aVNormal.Transform(aLoc.Transformation());
287 theNormal = gp_Dir(aVNormal);
288 return Standard_True;
289}
290
291//=======================================================================
2277323d 292//function : IsSameDomain
293//purpose :
294//=======================================================================
295static Standard_Boolean IsSameDomain(const TopoDS_Face& aFace,
2ba9eb30 296 const TopoDS_Face& aCheckedFace,
297 const Standard_Real theLinTol,
298 const Standard_Real theAngTol)
2277323d 299{
300 //checking the same handles
301 TopLoc_Location L1, L2;
302 Handle(Geom_Surface) S1, S2;
303
304 S1 = BRep_Tool::Surface(aFace,L1);
305 S2 = BRep_Tool::Surface(aCheckedFace,L2);
306
307 if (S1 == S2 && L1 == L2)
308 return Standard_True;
309
2277323d 310 S1 = BRep_Tool::Surface(aFace);
311 S2 = BRep_Tool::Surface(aCheckedFace);
312
313 S1 = ClearRts(S1);
314 S2 = ClearRts(S2);
315
316 //Handle(Geom_OffsetSurface) aGOFS1, aGOFS2;
317 //aGOFS1 = Handle(Geom_OffsetSurface)::DownCast(S1);
318 //aGOFS2 = Handle(Geom_OffsetSurface)::DownCast(S2);
319 //if (!aGOFS1.IsNull()) S1 = aGOFS1->BasisSurface();
320 //if (!aGOFS2.IsNull()) S2 = aGOFS2->BasisSurface();
321
2ba9eb30 322 // case of two planar surfaces:
323 // all kinds of surfaces checked, including b-spline and bezier
324 GeomLib_IsPlanarSurface aPlanarityChecker1(S1, theLinTol);
325 if (aPlanarityChecker1.IsPlanar()) {
326 GeomLib_IsPlanarSurface aPlanarityChecker2(S2, theLinTol);
327 if (aPlanarityChecker2.IsPlanar()) {
328 gp_Pln aPln1 = aPlanarityChecker1.Plan();
329 gp_Pln aPln2 = aPlanarityChecker2.Plan();
330
331 if (aPln1.Position().Direction().IsParallel(aPln2.Position().Direction(), theAngTol) &&
332 aPln1.Distance(aPln2) < theLinTol) {
333 return Standard_True;
334 }
335 }
336 }
337
2277323d 338 // case of two elementary surfaces: use OCCT tool
339 // elementary surfaces: ConicalSurface, CylindricalSurface,
340 // Plane, SphericalSurface and ToroidalSurface
341 if (S1->IsKind(STANDARD_TYPE(Geom_ElementarySurface)) &&
342 S2->IsKind(STANDARD_TYPE(Geom_ElementarySurface)))
343 {
344 Handle(GeomAdaptor_HSurface) aGA1 = new GeomAdaptor_HSurface(S1);
345 Handle(GeomAdaptor_HSurface) aGA2 = new GeomAdaptor_HSurface(S2);
346
347 Handle(BRepTopAdaptor_TopolTool) aTT1 = new BRepTopAdaptor_TopolTool();
348 Handle(BRepTopAdaptor_TopolTool) aTT2 = new BRepTopAdaptor_TopolTool();
349
350 try {
2ba9eb30 351 IntPatch_ImpImpIntersection anIIInt(aGA1, aTT1, aGA2, aTT2, theLinTol, theLinTol);
2277323d 352 if (!anIIInt.IsDone() || anIIInt.IsEmpty())
353 return Standard_False;
354
355 return anIIInt.TangentFaces();
356 }
357 catch (Standard_Failure) {
358 return Standard_False;
359 }
360 }
361
2277323d 362 // case of two cylindrical surfaces, at least one of which is a swept surface
363 // swept surfaces: SurfaceOfLinearExtrusion, SurfaceOfRevolution
364 if ((S1->IsKind(STANDARD_TYPE(Geom_CylindricalSurface)) ||
365 S1->IsKind(STANDARD_TYPE(Geom_SweptSurface))) &&
366 (S2->IsKind(STANDARD_TYPE(Geom_CylindricalSurface)) ||
367 S2->IsKind(STANDARD_TYPE(Geom_SweptSurface))))
368 {
369 gp_Cylinder aCyl1, aCyl2;
370 if (getCylinder(S1, aCyl1) && getCylinder(S2, aCyl2)) {
2ba9eb30 371 if (fabs(aCyl1.Radius() - aCyl2.Radius()) < theLinTol) {
2277323d 372 gp_Dir aDir1 = aCyl1.Position().Direction();
373 gp_Dir aDir2 = aCyl2.Position().Direction();
374 if (aDir1.IsParallel(aDir2, Precision::Angular())) {
375 gp_Pnt aLoc1 = aCyl1.Location();
376 gp_Pnt aLoc2 = aCyl2.Location();
377 gp_Vec aVec12 (aLoc1, aLoc2);
2ba9eb30 378 if (aVec12.SquareMagnitude() < theLinTol*theLinTol ||
2277323d 379 aVec12.IsParallel(aDir1, Precision::Angular())) {
380 return Standard_True;
381 }
382 }
383 }
384 }
385 }
386
387 return Standard_False;
388}
389
390//=======================================================================
632175c3 391//function : UpdateMapOfShapes
392//purpose :
393//=======================================================================
394static void UpdateMapOfShapes(TopTools_MapOfShape& theMapOfShapes,
395 Handle(ShapeBuild_ReShape)& theContext)
396{
397 for (TopTools_MapIteratorOfMapOfShape it(theMapOfShapes); it.More(); it.Next()) {
398 const TopoDS_Shape& aShape = it.Value();
399 TopoDS_Shape aContextShape = theContext->Apply(aShape);
400 if (!aContextShape.IsSame(aShape))
401 theMapOfShapes.Add(aContextShape);
402 }
403}
404
405//=======================================================================
2277323d 406//function : GlueEdgesWithPCurves
407//purpose : Glues the pcurves of the sequence of edges
408// and glues their 3d curves
409//=======================================================================
410static TopoDS_Edge GlueEdgesWithPCurves(const TopTools_SequenceOfShape& aChain,
411 const TopoDS_Vertex& FirstVertex,
412 const TopoDS_Vertex& LastVertex)
413{
414 Standard_Integer i, j;
415
416 TopoDS_Edge FirstEdge = TopoDS::Edge(aChain(1));
2277323d 417 TColGeom_SequenceOfSurface SurfSeq;
fbfdf61a 418 NCollection_Sequence<TopLoc_Location> LocSeq;
2277323d 419
fbfdf61a 420 for (int aCurveIndex = 0;; aCurveIndex++)
2277323d 421 {
fbfdf61a 422 Handle(Geom2d_Curve) aCurve;
423 Handle(Geom_Surface) aSurface;
424 TopLoc_Location aLocation;
425 Standard_Real aFirst, aLast;
426 BRep_Tool::CurveOnSurface (FirstEdge, aCurve, aSurface, aLocation, aFirst, aLast, aCurveIndex);
427 if (aCurve.IsNull())
428 break;
429
430 SurfSeq.Append(aSurface);
431 LocSeq.Append(aLocation);
2277323d 432 }
433
434 Standard_Real fpar, lpar;
435 BRep_Tool::Range(FirstEdge, fpar, lpar);
436 TopoDS_Edge PrevEdge = FirstEdge;
437 TopoDS_Vertex CV;
438 Standard_Real MaxTol = 0.;
439
440 TopoDS_Edge ResEdge;
441 BRep_Builder BB;
442
443 Standard_Integer nb_curve = aChain.Length(); //number of curves
444 TColGeom_Array1OfBSplineCurve tab_c3d(0,nb_curve-1); //array of the curves
445 TColStd_Array1OfReal tabtolvertex(0,nb_curve-1); //(0,nb_curve-2); //array of the tolerances
446
447 TopoDS_Vertex PrevVertex = FirstVertex;
448 for (i = 1; i <= nb_curve; i++)
449 {
450 TopoDS_Edge anEdge = TopoDS::Edge(aChain(i));
451 TopoDS_Vertex VF, VL;
452 TopExp::Vertices(anEdge, VF, VL);
453 Standard_Boolean ToReverse = (!VF.IsSame(PrevVertex));
454
455 Standard_Real Tol1 = BRep_Tool::Tolerance(VF);
456 Standard_Real Tol2 = BRep_Tool::Tolerance(VL);
457 if (Tol1 > MaxTol)
458 MaxTol = Tol1;
459 if (Tol2 > MaxTol)
460 MaxTol = Tol2;
461
462 if (i > 1)
463 {
464 TopExp::CommonVertex(PrevEdge, anEdge, CV);
465 Standard_Real Tol = BRep_Tool::Tolerance(CV);
466 tabtolvertex(i-2) = Tol;
467 }
468
469 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, fpar, lpar);
470 Handle(Geom_TrimmedCurve) aTrCurve = new Geom_TrimmedCurve(aCurve, fpar, lpar);
471 tab_c3d(i-1) = GeomConvert::CurveToBSplineCurve(aTrCurve);
472 GeomConvert::C0BSplineToC1BSplineCurve(tab_c3d(i-1), Precision::Confusion());
473 if (ToReverse)
474 tab_c3d(i-1)->Reverse();
475 PrevVertex = (ToReverse)? VF : VL;
476 PrevEdge = anEdge;
477 }
478 Handle(TColGeom_HArray1OfBSplineCurve) concatcurve; //array of the concatenated curves
479 Handle(TColStd_HArray1OfInteger) ArrayOfIndices; //array of the remining Vertex
480 GeomConvert::ConcatC1(tab_c3d,
481 tabtolvertex,
482 ArrayOfIndices,
483 concatcurve,
484 Standard_False,
485 Precision::Confusion()); //C1 concatenation
486
487 if (concatcurve->Length() > 1)
488 {
489 GeomConvert_CompCurveToBSplineCurve Concat(concatcurve->Value(concatcurve->Lower()));
490
491 for (i = concatcurve->Lower()+1; i <= concatcurve->Upper(); i++)
492 Concat.Add( concatcurve->Value(i), MaxTol, Standard_True );
493
494 concatcurve->SetValue(concatcurve->Lower(), Concat.BSplineCurve());
495 }
496 Handle(Geom_BSplineCurve) ResCurve = concatcurve->Value(concatcurve->Lower());
497
498 TColGeom2d_SequenceOfBoundedCurve ResPCurves;
2277323d 499 for (j = 1; j <= SurfSeq.Length(); j++)
500 {
501 TColGeom2d_Array1OfBSplineCurve tab_c2d(0,nb_curve-1); //array of the pcurves
502
503 PrevVertex = FirstVertex;
504 PrevEdge = FirstEdge;
2277323d 505 for (i = 1; i <= nb_curve; i++)
506 {
507 TopoDS_Edge anEdge = TopoDS::Edge(aChain(i));
508 TopoDS_Vertex VF, VL;
509 TopExp::Vertices(anEdge, VF, VL);
510 Standard_Boolean ToReverse = (!VF.IsSame(PrevVertex));
511
2277323d 512 Handle(Geom2d_Curve) aPCurve =
fbfdf61a 513 BRep_Tool::CurveOnSurface(anEdge, SurfSeq(j), LocSeq(j), fpar, lpar);
514 if (aPCurve.IsNull())
515 continue;
2277323d 516 Handle(Geom2d_TrimmedCurve) aTrPCurve = new Geom2d_TrimmedCurve(aPCurve, fpar, lpar);
517 tab_c2d(i-1) = Geom2dConvert::CurveToBSplineCurve(aTrPCurve);
518 Geom2dConvert::C0BSplineToC1BSplineCurve(tab_c2d(i-1), Precision::Confusion());
519 if (ToReverse)
520 tab_c2d(i-1)->Reverse();
521 PrevVertex = (ToReverse)? VF : VL;
522 PrevEdge = anEdge;
523 }
524 Handle(TColGeom2d_HArray1OfBSplineCurve) concatc2d; //array of the concatenated curves
525 Handle(TColStd_HArray1OfInteger) ArrayOfInd2d; //array of the remining Vertex
526 Geom2dConvert::ConcatC1(tab_c2d,
527 tabtolvertex,
528 ArrayOfInd2d,
529 concatc2d,
530 Standard_False,
531 Precision::Confusion()); //C1 concatenation
532
533 if (concatc2d->Length() > 1)
534 {
535 Geom2dConvert_CompCurveToBSplineCurve Concat2d(concatc2d->Value(concatc2d->Lower()));
536
537 for (i = concatc2d->Lower()+1; i <= concatc2d->Upper(); i++)
538 Concat2d.Add( concatc2d->Value(i), MaxTol, Standard_True );
539
540 concatc2d->SetValue(concatc2d->Lower(), Concat2d.BSplineCurve());
541 }
542 Handle(Geom2d_BSplineCurve) aResPCurve = concatc2d->Value(concatc2d->Lower());
543 ResPCurves.Append(aResPCurve);
544 }
545
546 ResEdge = BRepLib_MakeEdge(ResCurve,
547 FirstVertex, LastVertex,
548 ResCurve->FirstParameter(), ResCurve->LastParameter());
549 BB.SameRange(ResEdge, Standard_False);
550 BB.SameParameter(ResEdge, Standard_False);
551 for (j = 1; j <= ResPCurves.Length(); j++)
552 {
fbfdf61a 553 BB.UpdateEdge(ResEdge, ResPCurves(j), SurfSeq(j), LocSeq(j), MaxTol);
554 BB.Range(ResEdge, SurfSeq(j), LocSeq(j), ResPCurves(j)->FirstParameter(), ResPCurves(j)->LastParameter());
2277323d 555 }
556
557 BRepLib::SameParameter(ResEdge, MaxTol, Standard_True);
558
559 return ResEdge;
560}
561
cef6867c 562//=======================================================================
563//function : MergeSubSeq
564//purpose : Merges a sequence of edges into one edge if possible
565//=======================================================================
566
632175c3 567static Standard_Boolean MergeSubSeq(const TopTools_SequenceOfShape& aChain,
568 TopoDS_Edge& OutEdge,
569 double theAngTol,
570 Standard_Boolean ConcatBSplines,
571 Standard_Boolean isSafeInputMode,
572 Handle(ShapeBuild_ReShape)& theContext)
2277323d 573{
2277323d 574 ShapeAnalysis_Edge sae;
f7d70540 575 BRep_Builder B;
2277323d 576 // union edges in chain
f7d70540 577 int j;
2277323d 578 Standard_Real fp1,lp1,fp2,lp2;
f7d70540 579 Standard_Boolean IsUnionOfLinesPossible = Standard_True;
580 Standard_Boolean IsUnionOfCirclesPossible = Standard_True;
581 Handle(Geom_Curve) c3d1, c3d2;
582 for(j=1; j<aChain.Length(); j++)
583 {
2277323d 584 TopoDS_Edge edge1 = TopoDS::Edge(aChain.Value(j));
f7d70540 585 c3d1 = BRep_Tool::Curve(edge1,fp1,lp1);
586
587 TopoDS_Edge edge2 = TopoDS::Edge(aChain.Value(j+1));
588 c3d2 = BRep_Tool::Curve(edge2,fp2,lp2);
589
590 if(c3d1.IsNull() || c3d2.IsNull())
591 return Standard_False;
b4d4dbe8 592
2277323d 593 while(c3d1->IsKind(STANDARD_TYPE(Geom_TrimmedCurve))) {
594 Handle(Geom_TrimmedCurve) tc =
595 Handle(Geom_TrimmedCurve)::DownCast(c3d1);
596 c3d1 = tc->BasisCurve();
597 }
2277323d 598 while(c3d2->IsKind(STANDARD_TYPE(Geom_TrimmedCurve))) {
599 Handle(Geom_TrimmedCurve) tc =
600 Handle(Geom_TrimmedCurve)::DownCast(c3d2);
601 c3d2 = tc->BasisCurve();
602 }
603 if( c3d1->IsKind(STANDARD_TYPE(Geom_Line)) && c3d2->IsKind(STANDARD_TYPE(Geom_Line)) ) {
2277323d 604 Handle(Geom_Line) L1 = Handle(Geom_Line)::DownCast(c3d1);
605 Handle(Geom_Line) L2 = Handle(Geom_Line)::DownCast(c3d2);
606 gp_Dir Dir1 = L1->Position().Direction();
607 gp_Dir Dir2 = L2->Position().Direction();
632175c3 608 if(!Dir1.IsParallel(Dir2,theAngTol))
f7d70540 609 IsUnionOfLinesPossible = Standard_False;
2277323d 610 }
f7d70540 611 else
612 IsUnionOfLinesPossible = Standard_False;
2277323d 613 if( c3d1->IsKind(STANDARD_TYPE(Geom_Circle)) && c3d2->IsKind(STANDARD_TYPE(Geom_Circle)) ) {
2277323d 614 Handle(Geom_Circle) C1 = Handle(Geom_Circle)::DownCast(c3d1);
615 Handle(Geom_Circle) C2 = Handle(Geom_Circle)::DownCast(c3d2);
616 gp_Pnt P01 = C1->Location();
617 gp_Pnt P02 = C2->Location();
b4d4dbe8 618 if (P01.Distance(P02) > Precision::Confusion())
f7d70540 619 IsUnionOfCirclesPossible = Standard_False;
620 }
621 else
622 IsUnionOfCirclesPossible = Standard_False;
623 }
624 if (IsUnionOfLinesPossible && IsUnionOfCirclesPossible)
625 return Standard_False;
626
627 //union of lines is possible
628 if (IsUnionOfLinesPossible)
629 {
632175c3 630 TopoDS_Vertex V[2];
631 V[0] = sae.FirstVertex(TopoDS::Edge(aChain.First()));
632 gp_Pnt PV1 = BRep_Tool::Pnt(V[0]);
633 V[1] = sae.LastVertex(TopoDS::Edge(aChain.Last()));
634 gp_Pnt PV2 = BRep_Tool::Pnt(V[1]);
f7d70540 635 gp_Vec Vec(PV1, PV2);
632175c3 636 if (isSafeInputMode) {
637 for (int k = 0; k < 2; k++) {
638 if (!theContext->IsRecorded(V[k])) {
639 TopoDS_Vertex Vcopy = TopoDS::Vertex(V[k].EmptyCopied());
640 theContext->Replace(V[k], Vcopy);
641 V[k] = Vcopy;
642 }
643 else
644 V[k] = TopoDS::Vertex(theContext->Apply(V[k]));
645 }
646 }
f7d70540 647 Handle(Geom_Line) L = new Geom_Line(gp_Ax1(PV1,Vec));
648 Standard_Real dist = PV1.Distance(PV2);
649 Handle(Geom_TrimmedCurve) tc = new Geom_TrimmedCurve(L,0.0,dist);
650 TopoDS_Edge E;
651 B.MakeEdge (E, tc ,Precision::Confusion());
632175c3 652 B.Add (E,V[0]); B.Add (E,V[1]);
653 B.UpdateVertex(V[0], 0., E, 0.);
654 B.UpdateVertex(V[1], dist, E, 0.);
f7d70540 655 OutEdge = E;
656 return Standard_True;
657 }
658
659 if (IsUnionOfCirclesPossible)
660 {
661 double f,l;
662 TopoDS_Edge FE = TopoDS::Edge(aChain.First());
663 Handle(Geom_Curve) c3d = BRep_Tool::Curve(FE,f,l);
664
665 while(c3d->IsKind(STANDARD_TYPE(Geom_TrimmedCurve))) {
666 Handle(Geom_TrimmedCurve) tc =
667 Handle(Geom_TrimmedCurve)::DownCast(c3d);
668 c3d = tc->BasisCurve();
669 }
670 Handle(Geom_Circle) Cir = Handle(Geom_Circle)::DownCast(c3d);
671
632175c3 672 TopoDS_Vertex V[2];
673 V[0] = sae.FirstVertex(FE);
674 V[1] = sae.LastVertex(TopoDS::Edge(aChain.Last()));
f7d70540 675 TopoDS_Edge E;
632175c3 676 if (V[0].IsSame(V[1])) {
f7d70540 677 // closed chain
dd2f1b75 678 BRepAdaptor_Curve adef(FE);
679 Handle(Geom_Circle) Cir1;
680 double FP, LP;
681 if ( FE.Orientation() == TopAbs_FORWARD)
682 {
683 FP = adef.FirstParameter();
684 LP = adef.LastParameter();
685 }
686 else
687 {
688 FP = adef.LastParameter();
689 LP = adef.FirstParameter();
690 }
691 if (Abs(FP) < Precision::PConfusion())
692 {
f0144633 693 B.MakeEdge (E,Cir, Precision::Confusion());
632175c3 694 B.Add(E,V[0]);
695 B.Add(E,V[1]);
f0144633 696 E.Orientation(FE.Orientation());
697 }
dd2f1b75 698 else
699 {
700 GC_MakeCircle MC1 (adef.Value(FP), adef.Value((FP + LP) * 0.5), adef.Value(LP));
701 if (MC1.IsDone())
702 Cir1 = MC1.Value();
703 else
704 return Standard_False;
705 B.MakeEdge (E, Cir1, Precision::Confusion());
632175c3 706 B.Add(E,V[0]);
707 B.Add(E,V[1]);
dd2f1b75 708 }
f7d70540 709 }
710 else {
632175c3 711 if (isSafeInputMode) {
712 for (int k = 0; k < 2; k++) {
713 if (!theContext->IsRecorded(V[k])) {
714 TopoDS_Vertex Vcopy = TopoDS::Vertex(V[k].EmptyCopied());
715 theContext->Replace(V[k], Vcopy);
716 V[k] = Vcopy;
717 }
718 else
719 V[k] = TopoDS::Vertex(theContext->Apply(V[k]));
720 }
721 }
722 gp_Pnt PV1 = BRep_Tool::Pnt(V[0]);
723 gp_Pnt PV2 = BRep_Tool::Pnt(V[1]);
dd2f1b75 724 TopoDS_Vertex VM = sae.LastVertex(FE);
725 gp_Pnt PVM = BRep_Tool::Pnt(VM);
726 GC_MakeCircle MC (PV1,PVM,PV2);
f7d70540 727 Handle(Geom_Circle) C = MC.Value();
728 gp_Pnt P0 = C->Location();
729 gp_Dir D1(gp_Vec(P0,PV1));
730 gp_Dir D2(gp_Vec(P0,PV2));
731 Standard_Real fpar = C->XAxis().Direction().Angle(D1);
732 if(fabs(fpar)>Precision::Confusion()) {
733 // check orientation
734 gp_Dir ND = C->XAxis().Direction().Crossed(D1);
735 if(ND.IsOpposite(C->Axis().Direction(),Precision::Confusion())) {
736 fpar = -fpar;
2277323d 737 }
f7d70540 738 }
739 Standard_Real lpar = C->XAxis().Direction().Angle(D2);
740 if(fabs(lpar)>Precision::Confusion()) {
741 // check orientation
742 gp_Dir ND = C->XAxis().Direction().Crossed(D2);
743 if(ND.IsOpposite(C->Axis().Direction(),Precision::Confusion())) {
744 lpar = -lpar;
2277323d 745 }
2277323d 746 }
f7d70540 747 if (lpar < fpar) lpar += 2*M_PI;
748 Handle(Geom_TrimmedCurve) tc = new Geom_TrimmedCurve(C,fpar,lpar);
749 B.MakeEdge (E,tc,Precision::Confusion());
632175c3 750 B.Add(E,V[0]);
751 B.Add(E,V[1]);
752 B.UpdateVertex(V[0], fpar, E, 0.);
753 B.UpdateVertex(V[1], lpar, E, 0.);
2277323d 754 }
f7d70540 755 OutEdge = E;
756 return Standard_True;
2277323d 757 }
758 if (aChain.Length() > 1 && ConcatBSplines) {
759 // second step: union edges with various curves
760 // skl for bug 0020052 from Mantis: perform such unions
761 // only if curves are bspline or bezier
f7d70540 762
763 TopoDS_Vertex VF = sae.FirstVertex(TopoDS::Edge(aChain.First()));
764 TopoDS_Vertex VL = sae.LastVertex(TopoDS::Edge(aChain.Last()));
765 Standard_Boolean NeedUnion = Standard_True;
2277323d 766 for(j=1; j<=aChain.Length(); j++) {
767 TopoDS_Edge edge = TopoDS::Edge(aChain.Value(j));
b4d4dbe8 768 TopLoc_Location Loc;
2277323d 769 Handle(Geom_Curve) c3d = BRep_Tool::Curve(edge,Loc,fp1,lp1);
770 if(c3d.IsNull()) continue;
771 while(c3d->IsKind(STANDARD_TYPE(Geom_TrimmedCurve))) {
772 Handle(Geom_TrimmedCurve) tc =
773 Handle(Geom_TrimmedCurve)::DownCast(c3d);
774 c3d = tc->BasisCurve();
775 }
776 if( ( c3d->IsKind(STANDARD_TYPE(Geom_BSplineCurve)) ||
777 c3d->IsKind(STANDARD_TYPE(Geom_BezierCurve)) ) ) continue;
f7d70540 778 NeedUnion = Standard_False;
2277323d 779 break;
780 }
781 if(NeedUnion) {
0797d9d3 782#ifdef OCCT_DEBUG
2277323d 783 cout<<"can not make analitical union => make approximation"<<endl;
784#endif
785 TopoDS_Edge E = GlueEdgesWithPCurves(aChain, VF, VL);
f7d70540 786 OutEdge = E;
787 return Standard_True;
2277323d 788 }
789 else {
0797d9d3 790#ifdef OCCT_DEBUG
2277323d 791 cout<<"can not make approximation for such types of curves"<<endl;
792#endif
793 return Standard_False;
794 }
795 }
f7d70540 796 return Standard_False;
797}
798
cef6867c 799//=======================================================================
800//function : IsMergingPossible
801//purpose : Checks if merging of two edges is possible
802//=======================================================================
803
f7d70540 804static Standard_Boolean IsMergingPossible(const TopoDS_Edge& edge1, const TopoDS_Edge& edge2,
1f59dfa9 805 double theAngTol, double theLinTol,
806 const TopTools_MapOfShape& AvoidEdgeVrt, const bool theLineDirectionOk,
807 const gp_Pnt& theFirstPoint, const gp_Vec& theDirectionVec)
f7d70540 808{
809 TopoDS_Vertex CV = TopExp::LastVertex(edge1, Standard_True);
9ed6494b 810 if (CV.IsNull() || AvoidEdgeVrt.Contains(CV))
f7d70540 811 return Standard_False;
812
813 BRepAdaptor_Curve ade1(edge1);
814 BRepAdaptor_Curve ade2(edge2);
815
816 GeomAbs_CurveType t1 = ade1.GetType();
817 GeomAbs_CurveType t2 = ade2.GetType();
818
819 if( t1 == GeomAbs_Circle && t2 == GeomAbs_Circle)
820 {
821 if (ade1.Circle().Location().Distance(ade2.Circle().Location()) > Precision::Confusion())
822 return Standard_False;
823 }
824
825 if( ( (t1 != GeomAbs_BezierCurve && t1 != GeomAbs_BSplineCurve) ||
826 (t2 != GeomAbs_BezierCurve && t2 != GeomAbs_BSplineCurve)) && t1 != t2)
827 return Standard_False;
828
829 gp_Vec Diff1, Diff2;
830 gp_Pnt P1, P2;
831 if (edge1.Orientation() == TopAbs_FORWARD)
832 ade1.D1(ade1.LastParameter(), P1, Diff1);
833 else
834 {
835 ade1.D1(ade1.FirstParameter(), P1, Diff1);
836 Diff1 = -Diff1;
837 }
838
839 if (edge2.Orientation() == TopAbs_FORWARD)
840 ade2.D1(ade2.FirstParameter(), P2, Diff2);
841 else
842 {
843 ade2.D1(ade2.LastParameter(), P2, Diff2);
844 Diff2 = -Diff2;
845 }
846
632175c3 847 if (Diff1.Angle(Diff2) > theAngTol)
f7d70540 848 return Standard_False;
849
1f59dfa9 850 if (theLineDirectionOk && t2 == GeomAbs_Line)
851 {
852 gp_Vec aCurV(theFirstPoint, BRep_Tool::Pnt(TopExp::LastVertex(edge2, Standard_True)));
853 Standard_Real aDD = theDirectionVec.CrossSquareMagnitude(aCurV);
854 if (aDD > theLinTol*theLinTol)
855 return Standard_False;
856 }
857
858 return Standard_True;
859}
860
861//=======================================================================
862//function : GetLineEdgePoints
863//purpose :
864//=======================================================================
865static Standard_Boolean GetLineEdgePoints(const TopoDS_Edge& theInpEdge, gp_Pnt& theFirstPoint, gp_Vec& theDirectionVec)
866{
867 double f, l;
868 Handle(Geom_Curve) aCur = BRep_Tool::Curve(theInpEdge, f, l);
869 if(aCur.IsNull())
870 return Standard_False;
871
872 Handle(Geom_TrimmedCurve) aTC = Handle(Geom_TrimmedCurve)::DownCast(aCur);
873 if (!aTC.IsNull())
874 aCur = aTC->BasisCurve();
875
876 if (aCur->DynamicType() != STANDARD_TYPE(Geom_Line))
877 return Standard_False;
878
879 theFirstPoint = BRep_Tool::Pnt(TopExp::FirstVertex(theInpEdge, Standard_True));
880 gp_Pnt aLP = BRep_Tool::Pnt(TopExp::LastVertex(theInpEdge, Standard_True));
881 theDirectionVec = aLP.XYZ().Subtracted(theFirstPoint.XYZ());
882 theDirectionVec.Normalize();
f7d70540 883 return Standard_True;
884}
885
cef6867c 886//=======================================================================
887//function : GenerateSubSeq
888//purpose : Generates sub-sequences of edges from sequence of edges
889//Edges from each subsequences can be merged into the one edge
890//=======================================================================
891
f7d70540 892static void GenerateSubSeq (const TopTools_SequenceOfShape& anInpEdgeSeq,
893 NCollection_Sequence<SubSequenceOfEdges>& SeqOfSubSeqOfEdges,
1f59dfa9 894 Standard_Boolean IsClosed, double theAngTol, double theLinTol,
895 const TopTools_MapOfShape& AvoidEdgeVrt)
f7d70540 896{
897 Standard_Boolean isOk = Standard_False;
898 TopoDS_Edge edge1, edge2;
899
900 SubSequenceOfEdges SubSeq;
1f59dfa9 901 TopoDS_Edge RefEdge = TopoDS::Edge(anInpEdgeSeq(1));
902 SubSeq.SeqsEdges.Append(RefEdge);
f7d70540 903 SeqOfSubSeqOfEdges.Append(SubSeq);
904
1f59dfa9 905 gp_Pnt aFirstPoint;
906 gp_Vec aDirectionVec;
907 Standard_Boolean isLineDirectionOk = GetLineEdgePoints(RefEdge, aFirstPoint, aDirectionVec);
908
f7d70540 909 for (int i = 1; i < anInpEdgeSeq.Length(); i++)
910 {
911 edge1 = TopoDS::Edge(anInpEdgeSeq(i));
912 edge2 = TopoDS::Edge(anInpEdgeSeq(i+1));
1f59dfa9 913 isOk = IsMergingPossible(edge1, edge2, theAngTol, theLinTol, AvoidEdgeVrt, isLineDirectionOk, aFirstPoint, aDirectionVec);
f7d70540 914 if (!isOk)
915 {
51740958 916 SubSequenceOfEdges aSubSeq;
917 aSubSeq.SeqsEdges.Append(edge2);
918 SeqOfSubSeqOfEdges.Append(aSubSeq);
1f59dfa9 919 isLineDirectionOk = GetLineEdgePoints(edge2, aFirstPoint, aDirectionVec);
f7d70540 920 }
921 else
922 SeqOfSubSeqOfEdges.ChangeLast().SeqsEdges.Append(edge2);
923 }
924 /// check first and last chain segments
925 if (IsClosed && SeqOfSubSeqOfEdges.Length() > 1)
926 {
927 edge1 = TopoDS::Edge(anInpEdgeSeq.Last());
928 edge2 = TopoDS::Edge(anInpEdgeSeq.First());
1f59dfa9 929 if (IsMergingPossible(edge1, edge2, theAngTol, theLinTol, AvoidEdgeVrt, Standard_False, aFirstPoint, aDirectionVec))
f7d70540 930 {
931 SeqOfSubSeqOfEdges.ChangeLast().SeqsEdges.Append(SeqOfSubSeqOfEdges.ChangeFirst().SeqsEdges);
932 SeqOfSubSeqOfEdges.Remove(1);
933 }
934 }
935}
936
f7d70540 937//=======================================================================
938//function : MergeEdges
939//purpose : auxilary
940//=======================================================================
f98965d2 941static Standard_Boolean MergeEdges(TopTools_SequenceOfShape& SeqEdges,
632175c3 942 const Standard_Real theAngTol,
1f59dfa9 943 const Standard_Real theLinTol,
f7d70540 944 const Standard_Boolean ConcatBSplines,
632175c3 945 const Standard_Boolean isSafeInputMode,
946 Handle(ShapeBuild_ReShape)& theContext,
f7d70540 947 NCollection_Sequence<SubSequenceOfEdges>& SeqOfSubSeqOfEdges,
9ed6494b 948 const TopTools_MapOfShape& NonMergVrt)
f7d70540 949{
f98965d2 950 // skip degenerated edges, and forbid merging through them
951 TopTools_IndexedDataMapOfShapeListOfShape aMapVE;
f7d70540 952 Standard_Integer j;
953 TopTools_MapOfShape VerticesToAvoid;
f7d70540 954 for (j = 1; j <= SeqEdges.Length(); j++)
955 {
956 TopoDS_Edge anEdge = TopoDS::Edge(SeqEdges(j));
957 if (BRep_Tool::Degenerated(anEdge))
958 {
959 TopoDS_Vertex V1, V2;
960 TopExp::Vertices(anEdge, V1, V2);
961 VerticesToAvoid.Add(V1);
962 VerticesToAvoid.Add(V2);
f98965d2 963 SeqEdges.Remove(j--);
964 }
965 else
966 {
967 // fill in the map V-E
968 for (TopoDS_Iterator it(anEdge.Oriented(TopAbs_FORWARD)); it.More(); it.Next())
969 {
970 TopoDS_Shape aV = it.Value();
971 if (aV.Orientation() == TopAbs_FORWARD || aV.Orientation() == TopAbs_REVERSED)
972 {
973 if (!aMapVE.Contains(aV))
974 aMapVE.Add(aV, TopTools_ListOfShape());
975 aMapVE.ChangeFromKey(aV).Append(anEdge);
38c2acd4 976 }
f98965d2 977 }
f7d70540 978 }
f7d70540 979 }
f98965d2 980 VerticesToAvoid.Unite(NonMergVrt);
f7d70540 981
f98965d2 982 // do loop while there are unused edges
983 TopTools_MapOfShape aUsedEdges;
984 for (;;)
985 {
986 TopoDS_Edge edge;
987 for(j=1; j <= SeqEdges.Length(); j++)
988 {
989 edge = TopoDS::Edge(SeqEdges.Value(j));
990 if (!aUsedEdges.Contains(edge))
991 break;
992 }
993 if (j > SeqEdges.Length())
994 break; // all edges have been used
995
996 // make chain for unite
997 TopTools_SequenceOfShape aChain;
38c2acd4 998 aChain.Append(edge);
f98965d2 999 aUsedEdges.Add(edge);
1000 TopoDS_Vertex V[2];
1001 TopExp::Vertices(edge, V[0], V[1], Standard_True);
1002
1003 // connect more edges to the chain in both directions
1004 for (j = 0; j < 2; j++)
1005 {
1006 Standard_Boolean isAdded = Standard_True;
1007 while (isAdded)
1008 {
1009 isAdded = Standard_False;
1010 if (V[j].IsNull())
1011 break;
1012 const TopTools_ListOfShape& aLE = aMapVE.FindFromKey(V[j]);
1013 for (TopTools_ListIteratorOfListOfShape itL(aLE); itL.More(); itL.Next())
1014 {
1015 edge = TopoDS::Edge(itL.Value());
1016 if (!aUsedEdges.Contains(edge))
1017 {
38c2acd4 1018 TopoDS_Vertex V2[2];
1019 TopExp::Vertices(edge, V2[0], V2[1], Standard_True);
1020 // the neighboring edge must have V[j] reversed and located on the opposite end
1021 if (V2[1 - j].IsEqual(V[j].Reversed()))
1022 {
1023 if (j == 0)
1024 aChain.Prepend(edge);
1025 else
1026 aChain.Append(edge);
1027 aUsedEdges.Add(edge);
1028 V[j] = V2[j];
1029 isAdded = Standard_True;
1030 break;
1031 }
1032 }
1033 }
f7d70540 1034 }
1035 }
f7d70540 1036
f98965d2 1037 if (aChain.Length() < 2)
1038 continue;
2277323d 1039
38c2acd4 1040 Standard_Boolean IsClosed = Standard_False;
f98965d2 1041 if (V[0].IsSame ( V[1] ))
38c2acd4 1042 IsClosed = Standard_True;
f98965d2 1043
1044 // split chain by vertices at which merging is not possible
1045 NCollection_Sequence<SubSequenceOfEdges> aOneSeq;
1f59dfa9 1046 GenerateSubSeq(aChain, aOneSeq, IsClosed, theAngTol, theLinTol, VerticesToAvoid);
f98965d2 1047
1048 // put sub-chains in the result
1049 SeqOfSubSeqOfEdges.Append(aOneSeq);
1050 }
f7d70540 1051
1052 for (int i = 1; i <= SeqOfSubSeqOfEdges.Length(); i++)
1053 {
1054 TopoDS_Edge UE;
1055 if (SeqOfSubSeqOfEdges(i).SeqsEdges.Length() < 2)
1056 continue;
632175c3 1057 if (MergeSubSeq(SeqOfSubSeqOfEdges(i).SeqsEdges, UE, theAngTol,
1058 ConcatBSplines, isSafeInputMode, theContext))
f7d70540 1059 SeqOfSubSeqOfEdges(i).UnionEdges = UE;
1060 }
2277323d 1061 return Standard_True;
1062}
1063
cef6867c 1064//=======================================================================
1065//function : MergeSeq
f523acf0 1066//purpose : Tries to unify the sequence of edges with the set of
1067// another edges which lies on the same geometry
cef6867c 1068//=======================================================================
f98965d2 1069static Standard_Boolean MergeSeq (TopTools_SequenceOfShape& SeqEdges,
632175c3 1070 const Standard_Real theAngTol,
1f59dfa9 1071 const Standard_Real theLinTol,
f7d70540 1072 const Standard_Boolean ConcatBSplines,
632175c3 1073 const Standard_Boolean isSafeInputMode,
f7d70540 1074 Handle(ShapeBuild_ReShape)& theContext,
f523acf0 1075 const TopTools_MapOfShape& nonMergVert)
1076{
f7d70540 1077 NCollection_Sequence<SubSequenceOfEdges> SeqOfSubsSeqOfEdges;
1f59dfa9 1078 if (MergeEdges(SeqEdges, theAngTol, theLinTol, ConcatBSplines, isSafeInputMode,
632175c3 1079 theContext, SeqOfSubsSeqOfEdges, nonMergVert))
f7d70540 1080 {
1081 for (Standard_Integer i = 1; i <= SeqOfSubsSeqOfEdges.Length(); i++ )
1082 {
1083 if (SeqOfSubsSeqOfEdges(i).UnionEdges.IsNull())
1084 continue;
654c48b2 1085
1086 theContext->Merge(SeqOfSubsSeqOfEdges(i).SeqsEdges,
1087 SeqOfSubsSeqOfEdges(i).UnionEdges);
f7d70540 1088 }
1089 return Standard_True;
1090 }
f523acf0 1091 return Standard_False;
f7d70540 1092}
1093
cef6867c 1094//=======================================================================
1095//function : CheckSharedVertices
1096//purpose : Checks the sequence of edges on the presence of shared vertex
1097//=======================================================================
1098
f7d70540 1099static void CheckSharedVertices(const TopTools_SequenceOfShape& theSeqEdges,
1100 const TopTools_IndexedDataMapOfShapeListOfShape& theMapEdgesVertex,
9ed6494b 1101 const TopTools_MapOfShape& theMapKeepShape,
f7d70540 1102 TopTools_MapOfShape& theShareVertMap)
1103{
1104 ShapeAnalysis_Edge sae;
1105 TopTools_SequenceOfShape SeqVertexes;
1106 TopTools_MapOfShape MapVertexes;
1107 for (Standard_Integer k = 1; k <= theSeqEdges.Length(); k++ )
1108 {
1109 TopoDS_Vertex aV1 = sae.FirstVertex(TopoDS::Edge(theSeqEdges(k)));
1110 TopoDS_Vertex aV2 = sae.LastVertex(TopoDS::Edge(theSeqEdges(k)));
1111 if (!MapVertexes.Add(aV1))
1112 SeqVertexes.Append(aV1);
1113 if (!MapVertexes.Add(aV2))
1114 SeqVertexes.Append(aV2);
1115 }
1116
1117 for (Standard_Integer k = 1; k <= SeqVertexes.Length()/* && !IsSharedVertexPresent*/; k++ )
1118 {
1119 const TopTools_ListOfShape& ListEdgesV1 = theMapEdgesVertex.FindFromKey(SeqVertexes(k));
f1191d30 1120 if (ListEdgesV1.Extent() > 2 || theMapKeepShape.Contains(SeqVertexes(k)))
f7d70540 1121 theShareVertMap.Add(SeqVertexes(k));
1122 }
1123 //return theShareVertMap.IsEmpty() ? false : true;
1124}
1125
2277323d 1126//=======================================================================
1127//function : ShapeUpgrade_UnifySameDomain
1128//purpose : Constructor
1129//=======================================================================
1130
1131ShapeUpgrade_UnifySameDomain::ShapeUpgrade_UnifySameDomain()
2ba9eb30 1132 : myLinTol(Precision::Confusion()),
1133 myAngTol(Precision::Angular()),
1134 myUnifyFaces(Standard_True),
fe1a6e4e 1135 myUnifyEdges (Standard_True),
1136 myConcatBSplines (Standard_False),
632175c3 1137 myAllowInternal (Standard_False),
654c48b2 1138 mySafeInputMode(Standard_True),
1139 myHistory(new BRepTools_History)
2277323d 1140{
2277323d 1141 myContext = new ShapeBuild_ReShape;
1142}
1143
1144//=======================================================================
1145//function : ShapeUpgrade_UnifySameDomain
1146//purpose : Constructor
1147//=======================================================================
1148
1149ShapeUpgrade_UnifySameDomain::ShapeUpgrade_UnifySameDomain(const TopoDS_Shape& aShape,
1150 const Standard_Boolean UnifyEdges,
1151 const Standard_Boolean UnifyFaces,
1152 const Standard_Boolean ConcatBSplines)
fe1a6e4e 1153 : myInitShape (aShape),
2ba9eb30 1154 myLinTol(Precision::Confusion()),
1155 myAngTol(Precision::Angular()),
1156 myUnifyFaces(UnifyFaces),
fe1a6e4e 1157 myUnifyEdges (UnifyEdges),
1158 myConcatBSplines (ConcatBSplines),
1159 myAllowInternal (Standard_False),
632175c3 1160 mySafeInputMode (Standard_True),
654c48b2 1161 myShape (aShape),
1162 myHistory(new BRepTools_History)
2277323d 1163{
2277323d 1164 myContext = new ShapeBuild_ReShape;
1165}
1166
1167//=======================================================================
1168//function : Initialize
1169//purpose :
1170//=======================================================================
1171
1172void ShapeUpgrade_UnifySameDomain::Initialize(const TopoDS_Shape& aShape,
1173 const Standard_Boolean UnifyEdges,
1174 const Standard_Boolean UnifyFaces,
1175 const Standard_Boolean ConcatBSplines)
1176{
1177 myInitShape = aShape;
1178 myShape = aShape;
1179 myUnifyEdges = UnifyEdges;
1180 myUnifyFaces = UnifyFaces;
1181 myConcatBSplines = ConcatBSplines;
1182
1183 myContext->Clear();
9ed6494b 1184 myKeepShapes.Clear();
f523acf0 1185 myHistory->Clear();
fe1a6e4e 1186}
1187
1188//=======================================================================
1189//function : AllowInternalEdges
1190//purpose :
1191//=======================================================================
1192
1193void ShapeUpgrade_UnifySameDomain::AllowInternalEdges (const Standard_Boolean theValue)
1194{
1195 myAllowInternal = theValue;
2277323d 1196}
1197
1198//=======================================================================
632175c3 1199//function : SetSafeInputMode
1200//purpose :
1201//=======================================================================
1202
1203void ShapeUpgrade_UnifySameDomain::SetSafeInputMode(Standard_Boolean theValue)
1204{
1205 mySafeInputMode = theValue;
1206}
1207
1208//=======================================================================
9ed6494b 1209//function : KeepShape
1210//purpose :
1211//=======================================================================
1212
1213void ShapeUpgrade_UnifySameDomain::KeepShape(const TopoDS_Shape& theShape)
1214{
1215 if (theShape.ShapeType() == TopAbs_EDGE || theShape.ShapeType() == TopAbs_VERTEX)
1216 myKeepShapes.Add(theShape);
1217}
1218
1219//=======================================================================
1220//function : KeepShapes
1221//purpose :
1222//=======================================================================
1223
1224void ShapeUpgrade_UnifySameDomain::KeepShapes(const TopTools_MapOfShape& theShapes)
1225{
1226 for (TopTools_MapIteratorOfMapOfShape it(theShapes); it.More(); it.Next()) {
1227 if (it.Value().ShapeType() == TopAbs_EDGE || it.Value().ShapeType() == TopAbs_VERTEX)
1228 myKeepShapes.Add(it.Value());
1229 }
1230}
1231
1232//=======================================================================
2277323d 1233//function : UnifyFaces
1234//purpose :
1235//=======================================================================
1236
1237void ShapeUpgrade_UnifySameDomain::UnifyFaces()
1238{
fe1a6e4e 1239 // creating map of edge faces for the whole shape
1240 TopTools_IndexedDataMapOfShapeListOfShape aGMapEdgeFaces;
1241 TopExp::MapShapesAndAncestors(myShape, TopAbs_EDGE, TopAbs_FACE, aGMapEdgeFaces);
56091b56 1242
1243 // unify faces in each shell separately
2277323d 1244 TopExp_Explorer exps;
56091b56 1245 for (exps.Init(myShape, TopAbs_SHELL); exps.More(); exps.Next())
977ad983 1246 IntUnifyFaces(exps.Current(), aGMapEdgeFaces);
56091b56 1247
1248 // gather all faces out of shells in one compound and unify them at once
1249 BRep_Builder aBB;
1250 TopoDS_Compound aCmp;
1251 aBB.MakeCompound(aCmp);
1252 Standard_Integer nbf = 0;
1253 for (exps.Init(myShape, TopAbs_FACE, TopAbs_SHELL); exps.More(); exps.Next(), nbf++)
1254 aBB.Add(aCmp, exps.Current());
1255
1256 if (nbf > 0)
977ad983 1257 IntUnifyFaces(aCmp, aGMapEdgeFaces);
56091b56 1258
1259 myShape = myContext->Apply(myShape);
1260}
2277323d 1261
632175c3 1262//=======================================================================
f16a6cc5 1263//function : SetFixWireModes
1264//purpose :
1265//=======================================================================
1266
1267static void SetFixWireModes(ShapeFix_Face& theSff)
1268{
1269 Handle(ShapeFix_Wire) aFixWire = theSff.FixWireTool();
1270 aFixWire->FixSelfIntersectionMode() = 0;
1271 aFixWire->FixNonAdjacentIntersectingEdgesMode() = 0;
1272 aFixWire->FixLackingMode() = 0;
1273 aFixWire->FixNotchedEdgesMode() = 0;
1274 aFixWire->ModifyTopologyMode() = Standard_False;
1275 aFixWire->ModifyRemoveLoopMode() = 0;
1276 aFixWire->FixGapsByRangesMode() = Standard_False;
1277 aFixWire->FixSmallMode() = 0;
1278}
1279
1280//=======================================================================
632175c3 1281//function : IntUnifyFaces
1282//purpose :
1283//=======================================================================
2277323d 1284
56091b56 1285void ShapeUpgrade_UnifySameDomain::IntUnifyFaces(const TopoDS_Shape& theInpShape,
977ad983 1286 TopTools_IndexedDataMapOfShapeListOfShape& theGMapEdgeFaces)
56091b56 1287{
1288 // creating map of edge faces for the shape
1289 TopTools_IndexedDataMapOfShapeListOfShape aMapEdgeFaces;
1290 TopExp::MapShapesAndAncestors(theInpShape, TopAbs_EDGE, TopAbs_FACE, aMapEdgeFaces);
1291
1292 // map of processed shapes
1293 TopTools_MapOfShape aProcessed;
1294
56091b56 1295 // processing each face
f523acf0 1296 TopExp_Explorer exp;
56091b56 1297 for (exp.Init(theInpShape, TopAbs_FACE); exp.More(); exp.Next()) {
10ce3246 1298 const TopoDS_Face& aFaceOriginal = TopoDS::Face(exp.Current());
1299 TopoDS_Face aFace = TopoDS::Face(aFaceOriginal.Oriented(TopAbs_FORWARD));
2277323d 1300
56091b56 1301 if (aProcessed.Contains(aFace))
1302 continue;
2277323d 1303
f523acf0 1304 // Boundary edges for the new face
56091b56 1305 TopTools_SequenceOfShape edges;
2277323d 1306
f523acf0 1307 Standard_Integer dummy;
1308 AddOrdinaryEdges(edges, aFace, dummy);
1309
1310 // Faces to get unified with the current faces
56091b56 1311 TopTools_SequenceOfShape faces;
f523acf0 1312
1313 // Add the current face for unification
56091b56 1314 faces.Append(aFace);
1315
f523acf0 1316 // surface and location to construct result
56091b56 1317 TopLoc_Location aBaseLocation;
1318 Handle(Geom_Surface) aBaseSurface = BRep_Tool::Surface(aFace,aBaseLocation);
1319 aBaseSurface = ClearRts(aBaseSurface);
1320
1321 // find adjacent faces to union
1322 Standard_Integer i;
1323 for (i = 1; i <= edges.Length(); i++) {
1324 TopoDS_Edge edge = TopoDS::Edge(edges(i));
1325 if (BRep_Tool::Degenerated(edge))
1326 continue;
2277323d 1327
56091b56 1328 // get connectivity of the edge in the global shape
1329 const TopTools_ListOfShape& aGList = theGMapEdgeFaces.FindFromKey(edge);
9ed6494b 1330 if (!myAllowInternal && (aGList.Extent() != 2 || myKeepShapes.Contains(edge))) {
f523acf0 1331 // non manifold case is not processed unless myAllowInternal
56091b56 1332 continue;
1333 }
10ce3246 1334 //
f523acf0 1335 // Get the faces connected through the edge in the current shape
1336 const TopTools_ListOfShape& aList = aMapEdgeFaces.FindFromKey(edge);
1337 if (aList.Extent() < 2) {
1338 continue;
1339 }
1340
f16a6cc5 1341 // for a planar face create and store pcurve of edge on face
1342 // to speed up all operations
1343 if (!mySafeInputMode && aBaseSurface->IsKind(STANDARD_TYPE(Geom_Plane)))
1344 BRepLib::BuildPCurveForEdgeOnPlane(edge, aFace);
1345
10ce3246 1346 // get normal of the face to compare it with normals of other faces
1347 gp_Dir aDN1;
1348 //
1349 // take intermediate point on edge to compute the normal
1350 Standard_Real f, l;
1351 BRep_Tool::Range(edge, f, l);
1352 Standard_Real aTMid = (f + l) * .5;
1353 //
1354 Standard_Boolean bCheckNormals = GetNormalToSurface(aFaceOriginal, edge, aTMid, aDN1);
1355 //
f523acf0 1356 // Process the faces
56091b56 1357 TopTools_ListIteratorOfListOfShape anIter(aList);
1358 for (; anIter.More(); anIter.Next()) {
10ce3246 1359 const TopoDS_Face& aCheckedFaceOriginal = TopoDS::Face(anIter.Value());
1360 TopoDS_Face anCheckedFace = TopoDS::Face(aCheckedFaceOriginal.Oriented(TopAbs_FORWARD));
56091b56 1361 if (anCheckedFace.IsSame(aFace))
fe1a6e4e 1362 continue;
2277323d 1363
56091b56 1364 if (aProcessed.Contains(anCheckedFace))
1365 continue;
2277323d 1366
10ce3246 1367 if (bCheckNormals) {
1368 // get normal of checked face using the same parameter on edge
1369 gp_Dir aDN2;
1370 if (GetNormalToSurface(aCheckedFaceOriginal, edge, aTMid, aDN2)) {
1371 // and check if the adjacent faces are having approximately same normals
1372 Standard_Real anAngle = aDN1.Angle(aDN2);
1373 if (anAngle > myAngTol) {
1374 continue;
1375 }
1376 }
1377 }
1378 //
2ba9eb30 1379 if (IsSameDomain(aFace,anCheckedFace, myLinTol, myAngTol)) {
f0144633 1380
56091b56 1381 // hotfix for 27271: prevent merging along periodic direction.
d3dadd23 1382 if (IsLikeSeam(edge, anCheckedFace, aBaseSurface))
56091b56 1383 continue;
2277323d 1384
f523acf0 1385 if (AddOrdinaryEdges(edges,anCheckedFace,dummy)) {
56091b56 1386 // sequence edges is modified
1387 i = dummy;
2277323d 1388 }
56091b56 1389
1390 faces.Append(anCheckedFace);
1391 aProcessed.Add(anCheckedFace);
1392 break;
2277323d 1393 }
1394 }
56091b56 1395 }
2277323d 1396
56091b56 1397 if (faces.Length() > 1) {
1398 // fill in the connectivity map for selected faces
1399 TopTools_IndexedDataMapOfShapeListOfShape aMapEF;
1400 for (i = 1; i <= faces.Length(); i++) {
1401 TopExp::MapShapesAndAncestors(faces(i), TopAbs_EDGE, TopAbs_FACE, aMapEF);
1402 }
f523acf0 1403 // Collect keep edges and multi-connected edges, i.e. edges that are internal to
56091b56 1404 // the set of selected faces and have connections to other faces.
9ed6494b 1405 TopTools_ListOfShape aKeepEdges;
56091b56 1406 for (i = 1; i <= aMapEF.Extent(); i++) {
1407 const TopTools_ListOfShape& aLF = aMapEF(i);
1408 if (aLF.Extent() == 2) {
1409 const TopoDS_Shape& aE = aMapEF.FindKey(i);
1410 const TopTools_ListOfShape& aGLF = theGMapEdgeFaces.FindFromKey(aE);
9ed6494b 1411 if (aGLF.Extent() > 2 || myKeepShapes.Contains(aE)) {
1412 aKeepEdges.Append(aE);
fe1a6e4e 1413 }
1414 }
9ed6494b 1415 }
1416 if (!aKeepEdges.IsEmpty()) {
1417 if (!myAllowInternal) {
1418 // Remove from the selection the faces which have no other connect edges
f523acf0 1419 // and contain multi-connected edges and/or keep edges.
56091b56 1420 TopTools_MapOfShape anAvoidFaces;
9ed6494b 1421 TopTools_ListIteratorOfListOfShape it(aKeepEdges);
56091b56 1422 for (; it.More(); it.Next()) {
1423 const TopoDS_Shape& aE = it.Value();
1424 const TopTools_ListOfShape& aLF = aMapEF.FindFromKey(aE);
1425 anAvoidFaces.Add(aLF.First());
1426 anAvoidFaces.Add(aLF.Last());
1427 }
9ed6494b 1428 for (i = 1; i <= faces.Length(); i++) {
56091b56 1429 if (anAvoidFaces.Contains(faces(i))) {
1430 // update the boundaries of merged area, for that
1431 // remove from 'edges' the edges of this face and add to 'edges'
1432 // the edges of this face that were not present in 'edges' before
9ed6494b 1433 Standard_Boolean hasConnectAnotherFaces = Standard_False;
56091b56 1434 TopExp_Explorer ex(faces(i), TopAbs_EDGE);
9ed6494b 1435 for (; ex.More() && !hasConnectAnotherFaces; ex.Next()) {
56091b56 1436 TopoDS_Shape aE = ex.Current();
9ed6494b 1437 const TopTools_ListOfShape& aLF = aMapEF.FindFromKey(aE);
1438 if (aLF.Extent() > 1) {
1439 for (it.Init(aLF); it.More() && !hasConnectAnotherFaces; it.Next()) {
1440 if (!anAvoidFaces.Contains(it.Value()))
1441 hasConnectAnotherFaces = Standard_True;
1442 }
1443 }
1444 }
1445 if (!hasConnectAnotherFaces) {
1446 AddOrdinaryEdges(edges, faces(i), dummy);
1447 faces.Remove(i);
1448 i--;
1449 }
1450 }
1451 }
1452 // check if the faces with keep edges contained in
1453 // already updated the boundaries of merged area
1454 if (!faces.IsEmpty()) {
1455 TopTools_MapOfShape aMapFaces;
1456 for (i = 1; i <= faces.Length(); i++) {
1457 aMapFaces.Add(faces(i));
1458 }
1459 for (it.Init(aKeepEdges); it.More(); it.Next()) {
1460 const TopoDS_Shape& aE = it.Value();
1461 const TopTools_ListOfShape& aLF = aMapEF.FindFromKey(aE);
1462 if (aLF.Extent() < 2)
1463 continue;
1464 if (aMapFaces.Contains(aLF.First()) &&
1465 aMapFaces.Contains(aLF.Last())) {
1466 for (i = 1; i <= faces.Length(); i++) {
1467 if (faces(i).IsEqual(aLF.First()) ||
1468 faces(i).IsEqual(aLF.Last())) {
1469 AddOrdinaryEdges(edges, faces(i), dummy);
1470 faces.Remove(i);
1471 i--;
1472 }
cb120537 1473 }
cb120537 1474 }
fe1a6e4e 1475 }
1476 }
56091b56 1477 }
1478 else {
f523acf0 1479 // add multi-connected and keep edges as internal in new face
9ed6494b 1480 TopTools_ListIteratorOfListOfShape it(aKeepEdges);
56091b56 1481 for (; it.More(); it.Next()) {
1482 const TopoDS_Shape& aE = it.Value();
1483 edges.Append(aE.Oriented(TopAbs_INTERNAL));
fe1a6e4e 1484 }
1485 }
1486 }
56091b56 1487 }
fe1a6e4e 1488
56091b56 1489 // all faces collected in the sequence. Perform union of faces
1490 if (faces.Length() > 1) {
56091b56 1491 TopoDS_Face aResult;
1492 BRep_Builder B;
1493 B.MakeFace(aResult,aBaseSurface,aBaseLocation,0);
1494 Standard_Integer nbWires = 0;
1495
f16a6cc5 1496 TopoDS_Face tmpF = TopoDS::Face(faces(1).Oriented(TopAbs_FORWARD));
20aa0d3f 1497
56091b56 1498 // connecting wires
1499 while (edges.Length()>0) {
1500
1501 Standard_Boolean isEdge3d = Standard_False;
1502 nbWires++;
1503 TopTools_MapOfShape aVertices;
1504 TopoDS_Wire aWire;
1505 B.MakeWire(aWire);
1506
1507 TopoDS_Edge anEdge = TopoDS::Edge(edges(1));
1508 edges.Remove(1);
1509 // collect internal edges in separate wires
1510 Standard_Boolean isInternal = (anEdge.Orientation() == TopAbs_INTERNAL);
1511
1512 isEdge3d |= !BRep_Tool::Degenerated(anEdge);
1513 B.Add(aWire,anEdge);
1514 TopoDS_Vertex V1,V2;
1515 TopExp::Vertices(anEdge,V1,V2);
1516 aVertices.Add(V1);
1517 aVertices.Add(V2);
1518
1519 Standard_Boolean isNewFound = Standard_False;
1520 do {
1521 isNewFound = Standard_False;
1522 for(Standard_Integer j = 1; j <= edges.Length(); j++) {
1523 anEdge = TopoDS::Edge(edges(j));
1524 // check if the current edge orientation corresponds to the first one
1525 Standard_Boolean isCurrInternal = (anEdge.Orientation() == TopAbs_INTERNAL);
1526 if (isCurrInternal != isInternal)
1527 continue;
1528 TopExp::Vertices(anEdge,V1,V2);
1529 if(aVertices.Contains(V1) || aVertices.Contains(V2)) {
1530 isEdge3d |= !BRep_Tool::Degenerated(anEdge);
1531 aVertices.Add(V1);
1532 aVertices.Add(V2);
1533 B.Add(aWire,anEdge);
1534 edges.Remove(j);
1535 j--;
1536 isNewFound = Standard_True;
2277323d 1537 }
2277323d 1538 }
56091b56 1539 } while (isNewFound);
1540
1541 // sorting any type of edges
1542 aWire.Closed (BRep_Tool::IsClosed (aWire));
56091b56 1543
1544 Handle(ShapeFix_Wire) sfw = new ShapeFix_Wire(aWire,tmpF,Precision::Confusion());
632175c3 1545 if (mySafeInputMode)
1546 sfw->SetContext(myContext);
56091b56 1547 sfw->FixReorder();
1548 Standard_Boolean isDegRemoved = Standard_False;
1549 if(!sfw->StatusReorder ( ShapeExtend_FAIL )) {
1550 // clear degenerated edges if at least one with 3d curve exist
2277323d 1551 if(isEdge3d) {
56091b56 1552 Handle(ShapeExtend_WireData) sewd = sfw->WireData();
1553 for(Standard_Integer j = 1; j<=sewd->NbEdges();j++) {
1554 TopoDS_Edge E = sewd->Edge(j);
1555 if(BRep_Tool::Degenerated(E)) {
1556 sewd->Remove(j);
1557 isDegRemoved = Standard_True;
1558 j--;
2277323d 1559 }
2277323d 1560 }
2277323d 1561 }
56091b56 1562 sfw->FixShifted();
1563 if(isDegRemoved)
1564 sfw->FixDegenerated();
2277323d 1565 }
f16a6cc5 1566 aWire = sfw->Wire();
2277323d 1567
56091b56 1568 // add resulting wire
1569 if(isEdge3d) {
f16a6cc5 1570 B.Add(aResult,aWire);
56091b56 1571 }
1572 else {
1573 // sorting edges
1574 Handle(ShapeExtend_WireData) sbwd = sfw->WireData();
1575 Standard_Integer nbEdges = sbwd->NbEdges();
1576 // sort degenerated edges and create one edge instead of several ones
1577 ShapeAnalysis_WireOrder sawo(Standard_False, 0);
1578 ShapeAnalysis_Edge sae;
1579 Standard_Integer aLastEdge = nbEdges;
1580 for(Standard_Integer j = 1; j <= nbEdges; j++) {
1581 Standard_Real f,l;
1582 //smh protection on NULL pcurve
1583 Handle(Geom2d_Curve) c2d;
1584 if(!sae.PCurve(sbwd->Edge(j),tmpF,c2d,f,l)) {
1585 aLastEdge--;
1586 continue;
38c2acd4 1587 }
56091b56 1588 sawo.Add(c2d->Value(f).XY(),c2d->Value(l).XY());
2277323d 1589 }
d3dadd23 1590 if (sawo.NbEdges() == 0)
1591 continue;
56091b56 1592 sawo.Perform();
1593
1594 // constructind one degenerative edge
1595 gp_XY aStart, anEnd, tmp;
1596 Standard_Integer nbFirst = sawo.Ordered(1);
1597 TopoDS_Edge anOrigE = TopoDS::Edge(sbwd->Edge(nbFirst).Oriented(TopAbs_FORWARD));
1598 ShapeBuild_Edge sbe;
1599 TopoDS_Vertex aDummyV;
1600 TopoDS_Edge E = sbe.CopyReplaceVertices(anOrigE,aDummyV,aDummyV);
1601 sawo.XY(nbFirst,aStart,tmp);
1602 sawo.XY(sawo.Ordered(aLastEdge),tmp,anEnd);
1603
1604 gp_XY aVec = anEnd-aStart;
1605 Handle(Geom2d_Line) aLine = new Geom2d_Line(aStart,gp_Dir2d(anEnd-aStart));
1606
1607 B.UpdateEdge(E,aLine,tmpF,0.);
1608 B.Range(E,tmpF,0.,aVec.Modulus());
1609 Handle(Geom_Curve) C3d;
1610 B.UpdateEdge(E,C3d,0.);
1611 B.Degenerated(E,Standard_True);
1612 TopoDS_Wire aW;
1613 B.MakeWire(aW);
1614 B.Add(aW,E);
1615 aW.Closed (Standard_True);
1616 B.Add(aResult,aW);
1617 }
1618 }
2277323d 1619
56091b56 1620 ShapeFix_Face sff (aResult);
f523acf0 1621 //Initializing by tolerances
56091b56 1622 sff.SetPrecision(Precision::Confusion());
f523acf0 1623 sff.SetMinTolerance(Precision::Confusion());
56091b56 1624 sff.SetMaxTolerance(1.);
1625 //Setting modes
f16a6cc5 1626 SetFixWireModes(sff);
1627 if (mySafeInputMode)
1628 sff.SetContext(myContext);
56091b56 1629 // Applying the fixes
1630 sff.Perform();
f16a6cc5 1631 if(!sff.Status(ShapeExtend_FAIL))
1632 {
1633 // perform substitution of faces
1634 aResult = sff.Face();
1635 myContext->Merge(faces, aResult);
2277323d 1636 }
56091b56 1637 }
1638 } // end processing each face
2277323d 1639}
1640
1641//=======================================================================
1642//function : UnifyEdges
1643//purpose :
1644//=======================================================================
2277323d 1645void ShapeUpgrade_UnifySameDomain::UnifyEdges()
1646{
632175c3 1647 TopoDS_Shape aRes = myContext->Apply(myShape);
2277323d 1648
ce41efde 1649 TopTools_IndexedMapOfShape ChangedFaces;
2277323d 1650
ce41efde 1651 // creating map of edge faces
1652 TopTools_IndexedDataMapOfShapeListOfShape aMapEdgeFaces;
632175c3 1653 TopExp::MapShapesAndAncestors(aRes, TopAbs_EDGE, TopAbs_FACE, aMapEdgeFaces);
ce41efde 1654
1655 // creating map of vertex edges
1656 TopTools_IndexedDataMapOfShapeListOfShape aMapEdgesVertex;
632175c3 1657 TopExp::MapShapesAndUniqueAncestors(aRes, TopAbs_VERTEX, TopAbs_EDGE, aMapEdgesVertex);
f7d70540 1658
1659 TopTools_MapOfShape SharedVert;
1660
f7d70540 1661 TopTools_IndexedMapOfShape anOldEdges;
1662 TopExp::MapShapes(myInitShape, TopAbs_EDGE, anOldEdges);
1663
1664 TopTools_DataMapOfShapeShape NewEdges2OldEdges;
1665 for (int i = 1; i <= anOldEdges.Extent(); i++)
1666 {
632175c3 1667 const TopoDS_Shape& anOldEdge = anOldEdges(i);
1668 TopoDS_Shape aNewEdge = myContext->Apply(anOldEdge);
1669 if (!aNewEdge.IsNull() && !aNewEdge.IsSame(anOldEdge))
1670 NewEdges2OldEdges.Bind(aNewEdge, anOldEdge);
f7d70540 1671 }
ce41efde 1672
632175c3 1673 if (mySafeInputMode)
1674 UpdateMapOfShapes(myKeepShapes, myContext);
1675
ce41efde 1676 TopExp_Explorer exp;
f7d70540 1677 // processing separate wires
1678 for (exp.Init(aRes, TopAbs_WIRE, TopAbs_FACE); exp.More(); exp.Next())
1679 {
1680 TopTools_SequenceOfShape SeqEdges;
1681 TopExp_Explorer expE(exp.Current(), TopAbs_EDGE);
1682 for (; expE.More(); expE.Next())
1683 SeqEdges.Append(expE.Current());
1684 SharedVert.Clear();
9ed6494b 1685 CheckSharedVertices(SeqEdges, aMapEdgesVertex, myKeepShapes, SharedVert);
1f59dfa9 1686 MergeSeq(SeqEdges, myAngTol, myLinTol, myConcatBSplines, mySafeInputMode, myContext,
f523acf0 1687 SharedVert);
f7d70540 1688 }
1689
1690 // processing each face
ce41efde 1691 for (exp.Init(aRes, TopAbs_FACE); exp.More(); exp.Next()) {
632175c3 1692 TopoDS_Shape aFace = exp.Current().Oriented(TopAbs_FORWARD);
ce41efde 1693 TopTools_IndexedDataMapOfShapeListOfShape aMapFacesEdges;
f7d70540 1694 TopTools_SequenceOfShape aNonSharedEdges;
ce41efde 1695 for (TopExp_Explorer expe(aFace,TopAbs_EDGE); expe.More(); expe.Next()) {
1696 TopoDS_Edge edge = TopoDS::Edge(expe.Current());
ce41efde 1697 const TopTools_ListOfShape& aList = aMapEdgeFaces.FindFromKey(edge);
1698 TopTools_ListIteratorOfListOfShape anIter(aList);
f7d70540 1699 Standard_Integer NbFacesPerEdge = aList.Extent();
ce41efde 1700 for ( ; anIter.More(); anIter.Next()) {
632175c3 1701 const TopoDS_Shape& aFace1 = anIter.Value();
1702 if (aFace1.IsSame(aFace) && NbFacesPerEdge != 1)
f7d70540 1703 continue;
1704 if (NbFacesPerEdge == 1)
1705 //store non-shared edges separately
1706 aNonSharedEdges.Append(edge);
1707 else
1708 {
632175c3 1709 if (aMapFacesEdges.Contains(aFace1))
1710 aMapFacesEdges.ChangeFromKey(aFace1).Append(edge);
f7d70540 1711 else
1712 {
1713 TopTools_ListOfShape ListEdges;
1714 ListEdges.Append(edge);
632175c3 1715 aMapFacesEdges.Add(aFace1, ListEdges);
f7d70540 1716 }
2277323d 1717 }
1718 }
ce41efde 1719 }
f7d70540 1720
1721 for (Standard_Integer i=1; i<=aMapFacesEdges.Extent(); i++)
1722 {
ce41efde 1723 const TopTools_ListOfShape& ListEdges = aMapFacesEdges.FindFromIndex(i);
1724 TopTools_SequenceOfShape SeqEdges;
ce41efde 1725 TopTools_ListIteratorOfListOfShape anIter(ListEdges);
ce41efde 1726 for ( ; anIter.More(); anIter.Next())
1727 SeqEdges.Append(anIter.Value());
1728 if (SeqEdges.Length()==1)
1729 continue;
2277323d 1730
f7d70540 1731 SharedVert.Clear();
9ed6494b 1732 CheckSharedVertices(SeqEdges, aMapEdgesVertex, myKeepShapes, SharedVert);
1f59dfa9 1733 if (MergeSeq(SeqEdges, myAngTol, myLinTol, myConcatBSplines, mySafeInputMode,
f523acf0 1734 myContext, SharedVert))
2277323d 1735 {
ce41efde 1736 TopoDS_Face tmpF = TopoDS::Face(exp.Current());
1737 if ( !ChangedFaces.Contains(tmpF) )
1738 ChangedFaces.Add(tmpF);
1739 tmpF = TopoDS::Face(aMapFacesEdges.FindKey(i));
1740 if ( !ChangedFaces.Contains(tmpF) )
1741 ChangedFaces.Add(tmpF);
2277323d 1742 }
ce41efde 1743 }
f7d70540 1744
1745 if ( aNonSharedEdges.Length() > 1 )
1746 {
1747 SharedVert.Clear();
9ed6494b 1748 CheckSharedVertices(aNonSharedEdges, aMapEdgesVertex, myKeepShapes, SharedVert);
1f59dfa9 1749 if (MergeSeq(aNonSharedEdges, myAngTol, myLinTol, myConcatBSplines, mySafeInputMode,
f523acf0 1750 myContext, SharedVert))
f7d70540 1751 {
1752 TopoDS_Face tmpF = TopoDS::Face(exp.Current());
1753 if ( !ChangedFaces.Contains(tmpF) )
1754 ChangedFaces.Add(tmpF);
1755 }
1756 }
ce41efde 1757
1758 } // end processing each face
1759
1760 // fix changed faces and replace them in the local context
632175c3 1761 Standard_Real aPrec = Precision::Confusion();
1762 for (Standard_Integer i = 1; i <= ChangedFaces.Extent(); i++) {
ce41efde 1763 TopoDS_Face aFace = TopoDS::Face(myContext->Apply(ChangedFaces.FindKey(i)));
f7d70540 1764 if (aFace.IsNull())
1765 continue;
f16a6cc5 1766
1767 // for a planar face create and store pcurve of edge on face
1768 // to speed up all operations; but this is allowed only when non-safe mode in force
1769 if (!mySafeInputMode)
1770 {
1771 TopLoc_Location aLoc;
1772 Handle(Geom_Surface) aSurface = BRep_Tool::Surface(aFace, aLoc);
1773 aSurface = ClearRts(aSurface);
1774 if (aSurface->IsKind(STANDARD_TYPE(Geom_Plane)))
1775 {
1776 TopTools_ListOfShape aLE;
1777 for (TopExp_Explorer anEx(aFace, TopAbs_EDGE); anEx.More(); anEx.Next())
1778 aLE.Append(anEx.Current());
1779 BRepLib::BuildPCurveForEdgesOnPlane(aLE, aFace);
1780 }
1781 }
1782
1783 ShapeFix_Face sff(aFace);
1784 if (mySafeInputMode)
1785 sff.SetContext(myContext);
1786 sff.SetPrecision(aPrec);
1787 sff.SetMinTolerance(aPrec);
1788 sff.SetMaxTolerance(Max(1., aPrec*1000.));
1789 sff.FixOrientationMode() = 0;
1790 sff.FixAddNaturalBoundMode() = 0;
1791 sff.FixIntersectingWiresMode() = 0;
1792 sff.FixLoopWiresMode() = 0;
1793 sff.FixSplitFaceMode() = 0;
1794 sff.FixPeriodicDegeneratedMode() = 0;
1795 SetFixWireModes(sff);
1796 sff.Perform();
1797 TopoDS_Shape aNewFace = sff.Face();
ce41efde 1798 myContext->Replace(aFace,aNewFace);
ce41efde 1799 }
1800
1801 if (ChangedFaces.Extent() > 0) {
1802 // fix changed shell and replace it in the local context
ce41efde 1803 TopoDS_Shape aRes1 = myContext->Apply(aRes);
632175c3 1804 Standard_Boolean isChanged = Standard_False;
ce41efde 1805 TopExp_Explorer expsh;
1806 for (expsh.Init(aRes1, TopAbs_SHELL); expsh.More(); expsh.Next()) {
1807 TopoDS_Shell aShell = TopoDS::Shell(expsh.Current());
1808 Handle(ShapeFix_Shell) sfsh = new ShapeFix_Shell;
1809 sfsh->FixFaceOrientation(aShell);
1810 TopoDS_Shape aNewShell = sfsh->Shell();
632175c3 1811 if (!aNewShell.IsSame(aShell)) {
1812 myContext->Replace(aShell, aNewShell);
1813 isChanged = Standard_True;
2277323d 1814 }
ce41efde 1815 }
632175c3 1816 if (isChanged)
1817 aRes1 = myContext->Apply(aRes1);
1818 myContext->Replace(myShape, aRes1);
ce41efde 1819 }
2277323d 1820
1821 myShape = myContext->Apply(myShape);
1822}
1823
1824//=======================================================================
2277323d 1825//function : Build
1826//purpose : builds the resulting shape
f523acf0 1827//=======================================================================
2277323d 1828void ShapeUpgrade_UnifySameDomain::Build()
1829{
f16a6cc5 1830 if (myUnifyFaces)
2277323d 1831 UnifyFaces();
f16a6cc5 1832 if (myUnifyEdges)
1833 UnifyEdges();
2277323d 1834
f523acf0 1835 // Fill the history of modifications during the operation
1836 FillHistory();
1837}
1838
1839//=======================================================================
1840//function : FillHistory
1841//purpose : Fill the history of modifications during the operation
1842//=======================================================================
1843void ShapeUpgrade_UnifySameDomain::FillHistory()
1844{
1845 if (myHistory.IsNull())
1846 // History is not requested
1847 return;
1848
1849 // Only Vertices, Edges and Faces can be modified during unification.
1850 // Thus, only these kind of shapes should be checked.
1851
1852 // Get history from the context.
1853 // It contains all modifications of the operation. Some of these
1854 // modifications become not relevant and should be filtered.
1855 Handle(BRepTools_History) aCtxHistory = myContext->History();
1856
1857 // Explore the history of the context and fill
1858 // the history of UnifySameDomain algorithm
1859 Handle(BRepTools_History) aUSDHistory = new BRepTools_History();
1860
1861 // Map all Vertices, Edges and Faces in the input shape
1862 TopTools_IndexedMapOfShape aMapInputShape;
1863 TopExp::MapShapes(myInitShape, TopAbs_VERTEX, aMapInputShape);
1864 TopExp::MapShapes(myInitShape, TopAbs_EDGE , aMapInputShape);
1865 TopExp::MapShapes(myInitShape, TopAbs_FACE , aMapInputShape);
1866
1867 // Map all Vertices, Edges and Faces in the result shape
1868 TopTools_IndexedMapOfShape aMapResultShapes;
1869 TopExp::MapShapes(myShape, TopAbs_VERTEX, aMapResultShapes);
1870 TopExp::MapShapes(myShape, TopAbs_EDGE , aMapResultShapes);
1871 TopExp::MapShapes(myShape, TopAbs_FACE , aMapResultShapes);
1872
1873 // Iterate on all input shapes and get their modifications
1874 Standard_Integer i, aNb = aMapInputShape.Extent();
1875 for (i = 1; i <= aNb; ++i)
654c48b2 1876 {
f523acf0 1877 const TopoDS_Shape& aS = aMapInputShape(i);
1878
1879 // Check the shape itself to be present in the result
1880 if (aMapResultShapes.Contains(aS))
1881 {
1882 // The shape is present in the result as is, thus has not been modified
1883 continue;
1884 }
1885
1886 // Check if the shape has been modified during the operation
1887 const TopTools_ListOfShape& aLSImages = aCtxHistory->Modified(aS);
1888 if (aLSImages.IsEmpty())
1889 {
1890 // The shape has not been modified and not present in the result,
1891 // thus it has been removed
1892 aUSDHistory->Remove(aS);
1893 continue;
1894 }
1895
1896 // Check the images of the shape to be present in the result
1897 Standard_Boolean bRemoved = Standard_True;
1898 TopTools_ListIteratorOfListOfShape aItLSIm(aLSImages);
1899 for (; aItLSIm.More(); aItLSIm.Next())
1900 {
1901 if (aMapResultShapes.Contains(aItLSIm.Value()))
1902 {
1903 // Image is found in the result, thus the shape has been modified
1904 aUSDHistory->AddModified(aS, aItLSIm.Value());
1905 bRemoved = Standard_False;
1906 }
1907 }
1908
1909 if (bRemoved)
654c48b2 1910 {
f523acf0 1911 // No images are found in the result, thus the shape has been removed
1912 aUSDHistory->Remove(aS);
654c48b2 1913 }
20aa0d3f 1914 }
f7d70540 1915
f523acf0 1916 // Merge the history of the operation into global history
1917 myHistory->Merge(aUSDHistory);
2277323d 1918}