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