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