0026635: UnifySameDomain loses internal edges
[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
90 struct SubSequenceOfEdges
91 {
92   TopTools_SequenceOfShape SeqsEdges;
93   TopoDS_Edge UnionEdges;
94 };
95
96
97 //=======================================================================
98 //function : AddOrdinaryEdges
99 //purpose  : auxilary
100 //=======================================================================
101 // adds edges from the shape to the sequence
102 // seams and equal edges are dropped
103 // Returns true if one of original edges dropped
104 static Standard_Boolean AddOrdinaryEdges(TopTools_SequenceOfShape& edges,
105                                          const TopoDS_Shape aShape,
106                                          Standard_Integer& anIndex)
107 {
108   //map of edges
109   TopTools_IndexedMapOfShape aNewEdges;
110   //add edges without seams
111   for(TopExp_Explorer exp(aShape,TopAbs_EDGE); exp.More(); exp.Next()) {
112     TopoDS_Shape edge = exp.Current();
113     if(aNewEdges.Contains(edge))
114     {
115       //aNewEdges.Remove(edge);
116       TopoDS_Shape LastEdge = aNewEdges(aNewEdges.Extent());
117       aNewEdges.RemoveLast();
118       if (aNewEdges.FindIndex(edge) != 0)
119         aNewEdges.Substitute(aNewEdges.FindIndex(edge), LastEdge);
120       /////////////////////////
121     }
122     else
123       aNewEdges.Add(edge);
124   }
125
126   Standard_Boolean isDropped = Standard_False;
127   //merge edges and drop seams
128   Standard_Integer i;
129   for (i = 1; i <= edges.Length(); i++) {
130     TopoDS_Shape current = edges(i);
131     if(aNewEdges.Contains(current)) {
132
133       //aNewEdges.Remove(current);
134       TopoDS_Shape LastEdge = aNewEdges(aNewEdges.Extent());
135       aNewEdges.RemoveLast();
136       if (aNewEdges.FindIndex(current) != 0)
137         aNewEdges.Substitute(aNewEdges.FindIndex(current), LastEdge);
138       /////////////////////////
139       edges.Remove(i);
140       i--;
141
142       if(!isDropped) {
143         isDropped = Standard_True;
144         anIndex = i;
145       }
146     }
147   }
148
149   //add edges to the sequemce
150   for (i = 1; i <= aNewEdges.Extent(); i++)
151     edges.Append(aNewEdges(i));
152
153   return isDropped;
154 }
155
156 //=======================================================================
157 //function : getCylinder
158 //purpose  : auxilary
159 //=======================================================================
160 static Standard_Boolean getCylinder(Handle(Geom_Surface)& theInSurface,
161                                     gp_Cylinder& theOutCylinder)
162 {
163   Standard_Boolean isCylinder = Standard_False;
164
165   if (theInSurface->IsKind(STANDARD_TYPE(Geom_CylindricalSurface))) {
166     Handle(Geom_CylindricalSurface) aGC = Handle(Geom_CylindricalSurface)::DownCast(theInSurface);
167
168     theOutCylinder = aGC->Cylinder();
169     isCylinder = Standard_True;
170   }
171   else if (theInSurface->IsKind(STANDARD_TYPE(Geom_SurfaceOfRevolution))) {
172     Handle(Geom_SurfaceOfRevolution) aRS =
173       Handle(Geom_SurfaceOfRevolution)::DownCast(theInSurface);
174     Handle(Geom_Curve) aBasis = aRS->BasisCurve();
175     if (aBasis->IsKind(STANDARD_TYPE(Geom_Line))) {
176       Handle(Geom_Line) aBasisLine = Handle(Geom_Line)::DownCast(aBasis);
177       gp_Dir aDir = aRS->Direction();
178       gp_Dir aBasisDir = aBasisLine->Position().Direction();
179       if (aBasisDir.IsParallel(aDir, Precision::Angular())) {
180         // basis line is parallel to the revolution axis: it is a cylinder
181         gp_Pnt aLoc = aRS->Location();
182         Standard_Real aR = aBasisLine->Lin().Distance(aLoc);
183         gp_Ax3 aCylAx (aLoc, aDir);
184
185         theOutCylinder = gp_Cylinder(aCylAx, aR);
186         isCylinder = Standard_True;
187       }
188     }
189   }
190   else if (theInSurface->IsKind(STANDARD_TYPE(Geom_SurfaceOfLinearExtrusion))) {
191     Handle(Geom_SurfaceOfLinearExtrusion) aLES =
192       Handle(Geom_SurfaceOfLinearExtrusion)::DownCast(theInSurface);
193     Handle(Geom_Curve) aBasis = aLES->BasisCurve();
194     if (aBasis->IsKind(STANDARD_TYPE(Geom_Circle))) {
195       Handle(Geom_Circle) aBasisCircle = Handle(Geom_Circle)::DownCast(aBasis);
196       gp_Dir aDir = aLES->Direction();
197       gp_Dir aBasisDir = aBasisCircle->Position().Direction();
198       if (aBasisDir.IsParallel(aDir, Precision::Angular())) {
199         // basis circle is normal to the extrusion axis: it is a cylinder
200         gp_Pnt aLoc = aBasisCircle->Location();
201         Standard_Real aR = aBasisCircle->Radius();
202         gp_Ax3 aCylAx (aLoc, aDir);
203
204         theOutCylinder = gp_Cylinder(aCylAx, aR);
205         isCylinder = Standard_True;
206       }
207     }
208   }
209   else {
210   }
211
212   return isCylinder;
213 }
214
215 //=======================================================================
216 //function : ClearRts
217 //purpose  : auxilary
218 //=======================================================================
219 static Handle(Geom_Surface) ClearRts(const Handle(Geom_Surface)& aSurface)
220 {
221   if(aSurface->IsKind(STANDARD_TYPE(Geom_RectangularTrimmedSurface))) {
222     Handle(Geom_RectangularTrimmedSurface) rts =
223       Handle(Geom_RectangularTrimmedSurface)::DownCast(aSurface);
224     return rts->BasisSurface();
225   }
226   return aSurface;
227 }
228
229 //=======================================================================
230 //function : IsSameDomain
231 //purpose  : 
232 //=======================================================================
233 static Standard_Boolean IsSameDomain(const TopoDS_Face& aFace,
234                                      const TopoDS_Face& aCheckedFace)
235 {
236   //checking the same handles
237   TopLoc_Location L1, L2;
238   Handle(Geom_Surface) S1, S2;
239
240   S1 = BRep_Tool::Surface(aFace,L1);
241   S2 = BRep_Tool::Surface(aCheckedFace,L2);
242
243   if (S1 == S2 && L1 == L2)
244     return Standard_True;
245
246   // planar and cylindrical cases (IMP 20052)
247   Standard_Real aPrec = Precision::Confusion();
248
249   S1 = BRep_Tool::Surface(aFace);
250   S2 = BRep_Tool::Surface(aCheckedFace);
251
252   S1 = ClearRts(S1);
253   S2 = ClearRts(S2);
254
255   //Handle(Geom_OffsetSurface) aGOFS1, aGOFS2;
256   //aGOFS1 = Handle(Geom_OffsetSurface)::DownCast(S1);
257   //aGOFS2 = Handle(Geom_OffsetSurface)::DownCast(S2);
258   //if (!aGOFS1.IsNull()) S1 = aGOFS1->BasisSurface();
259   //if (!aGOFS2.IsNull()) S2 = aGOFS2->BasisSurface();
260
261   // case of two elementary surfaces: use OCCT tool
262   // elementary surfaces: ConicalSurface, CylindricalSurface,
263   //                      Plane, SphericalSurface and ToroidalSurface
264   if (S1->IsKind(STANDARD_TYPE(Geom_ElementarySurface)) &&
265       S2->IsKind(STANDARD_TYPE(Geom_ElementarySurface)))
266   {
267     Handle(GeomAdaptor_HSurface) aGA1 = new GeomAdaptor_HSurface(S1);
268     Handle(GeomAdaptor_HSurface) aGA2 = new GeomAdaptor_HSurface(S2);
269
270     Handle(BRepTopAdaptor_TopolTool) aTT1 = new BRepTopAdaptor_TopolTool();
271     Handle(BRepTopAdaptor_TopolTool) aTT2 = new BRepTopAdaptor_TopolTool();
272
273     try {
274       IntPatch_ImpImpIntersection anIIInt (aGA1, aTT1, aGA2, aTT2, aPrec, aPrec);
275       if (!anIIInt.IsDone() || anIIInt.IsEmpty())
276         return Standard_False;
277
278       return anIIInt.TangentFaces();
279     }
280     catch (Standard_Failure) {
281       return Standard_False;
282     }
283   }
284
285   // case of two planar surfaces:
286   // all kinds of surfaces checked, including b-spline and bezier
287   GeomLib_IsPlanarSurface aPlanarityChecker1 (S1, aPrec);
288   if (aPlanarityChecker1.IsPlanar()) {
289     GeomLib_IsPlanarSurface aPlanarityChecker2 (S2, aPrec);
290     if (aPlanarityChecker2.IsPlanar()) {
291       gp_Pln aPln1 = aPlanarityChecker1.Plan();
292       gp_Pln aPln2 = aPlanarityChecker2.Plan();
293
294       if (aPln1.Position().Direction().IsParallel(aPln2.Position().Direction(),Precision::Angular()) &&
295           aPln1.Distance(aPln2) < aPrec) {
296         return Standard_True;
297       }
298     }
299   }
300
301   // case of two cylindrical surfaces, at least one of which is a swept surface
302   // swept surfaces: SurfaceOfLinearExtrusion, SurfaceOfRevolution
303   if ((S1->IsKind(STANDARD_TYPE(Geom_CylindricalSurface)) ||
304        S1->IsKind(STANDARD_TYPE(Geom_SweptSurface))) &&
305       (S2->IsKind(STANDARD_TYPE(Geom_CylindricalSurface)) ||
306        S2->IsKind(STANDARD_TYPE(Geom_SweptSurface))))
307   {
308     gp_Cylinder aCyl1, aCyl2;
309     if (getCylinder(S1, aCyl1) && getCylinder(S2, aCyl2)) {
310       if (fabs(aCyl1.Radius() - aCyl2.Radius()) < aPrec) {
311         gp_Dir aDir1 = aCyl1.Position().Direction();
312         gp_Dir aDir2 = aCyl2.Position().Direction();
313         if (aDir1.IsParallel(aDir2, Precision::Angular())) {
314           gp_Pnt aLoc1 = aCyl1.Location();
315           gp_Pnt aLoc2 = aCyl2.Location();
316           gp_Vec aVec12 (aLoc1, aLoc2);
317           if (aVec12.SquareMagnitude() < aPrec*aPrec ||
318               aVec12.IsParallel(aDir1, Precision::Angular())) {
319             return Standard_True;
320           }
321         }
322       }
323     }
324   }
325
326   return Standard_False;
327 }
328
329 //=======================================================================
330 //function : MovePCurves
331 //purpose  :
332 //=======================================================================
333 static void MovePCurves(TopoDS_Face& aTarget,
334                         const TopoDS_Face& aSource)
335 {
336   BRep_Builder B;
337   for(TopExp_Explorer wexp(aSource,TopAbs_WIRE);wexp.More();wexp.Next()) {
338     Handle(ShapeFix_Wire) sfw = new ShapeFix_Wire(TopoDS::Wire(wexp.Current()),
339                                                   aTarget, Precision::Confusion());
340     sfw->FixReorder();
341     Standard_Boolean isReoredFailed = sfw->StatusReorder ( ShapeExtend_FAIL );
342     sfw->FixEdgeCurves();
343     if(isReoredFailed)
344       continue;
345
346     sfw->FixShifted();
347     sfw->FixDegenerated();
348
349     // remove degenerated edges from not degenerated points
350     ShapeAnalysis_Edge sae;
351     Handle(ShapeExtend_WireData) sewd = sfw->WireData();
352     for(Standard_Integer i = 1; i<=sewd->NbEdges();i++) {
353       TopoDS_Edge E = sewd->Edge(i);
354       if(BRep_Tool::Degenerated(E)&&!sae.HasPCurve(E,aTarget)) {
355         sewd->Remove(i);
356         i--;
357       }
358     }
359
360     TopoDS_Wire ResWire = sfw->Wire();
361     B.Add(aTarget,ResWire);
362   }
363 }
364
365 //=======================================================================
366 //function : GlueEdgesWithPCurves
367 //purpose  : Glues the pcurves of the sequence of edges
368 //           and glues their 3d curves
369 //=======================================================================
370 static TopoDS_Edge GlueEdgesWithPCurves(const TopTools_SequenceOfShape& aChain,
371                                         const TopoDS_Vertex& FirstVertex,
372                                         const TopoDS_Vertex& LastVertex)
373 {
374   Standard_Integer i, j;
375
376   TopoDS_Edge FirstEdge = TopoDS::Edge(aChain(1));
377   //TColGeom2d_SequenceOfCurve PCurveSeq;
378   TColGeom_SequenceOfSurface SurfSeq;
379   //TopTools_SequenceOfShape LocSeq;
380   
381   BRep_ListIteratorOfListOfCurveRepresentation itr( (Handle(BRep_TEdge)::DownCast(FirstEdge.TShape()))->Curves() );
382   for (; itr.More(); itr.Next())
383   {
384     Handle(BRep_CurveRepresentation) CurveRep = itr.Value();
385     if (CurveRep->IsCurveOnSurface())
386     {
387       //PCurveSeq.Append(CurveRep->PCurve());
388       SurfSeq.Append(CurveRep->Surface());
389       /*
390       TopoDS_Shape aLocShape;
391       aLocShape.Location(CurveRep->Location());
392       LocSeq.Append(aLocShape);
393       */
394     }
395   }
396
397   Standard_Real fpar, lpar;
398   BRep_Tool::Range(FirstEdge, fpar, lpar);
399   TopoDS_Edge PrevEdge = FirstEdge;
400   TopoDS_Vertex CV;
401   Standard_Real MaxTol = 0.;
402   
403   TopoDS_Edge ResEdge;
404   BRep_Builder BB;
405
406   Standard_Integer nb_curve = aChain.Length();   //number of curves
407   TColGeom_Array1OfBSplineCurve tab_c3d(0,nb_curve-1);                    //array of the curves
408   TColStd_Array1OfReal tabtolvertex(0,nb_curve-1); //(0,nb_curve-2);  //array of the tolerances
409     
410   TopoDS_Vertex PrevVertex = FirstVertex;
411   for (i = 1; i <= nb_curve; i++)
412   {
413     TopoDS_Edge anEdge = TopoDS::Edge(aChain(i));
414     TopoDS_Vertex VF, VL;
415     TopExp::Vertices(anEdge, VF, VL);
416     Standard_Boolean ToReverse = (!VF.IsSame(PrevVertex));
417     
418     Standard_Real Tol1 = BRep_Tool::Tolerance(VF);
419     Standard_Real Tol2 = BRep_Tool::Tolerance(VL);
420     if (Tol1 > MaxTol)
421       MaxTol = Tol1;
422     if (Tol2 > MaxTol)
423       MaxTol = Tol2;
424     
425     if (i > 1)
426     {
427       TopExp::CommonVertex(PrevEdge, anEdge, CV);
428       Standard_Real Tol = BRep_Tool::Tolerance(CV);
429       tabtolvertex(i-2) = Tol;
430     }
431     
432     Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, fpar, lpar);
433     Handle(Geom_TrimmedCurve) aTrCurve = new Geom_TrimmedCurve(aCurve, fpar, lpar);
434     tab_c3d(i-1) = GeomConvert::CurveToBSplineCurve(aTrCurve);
435     GeomConvert::C0BSplineToC1BSplineCurve(tab_c3d(i-1), Precision::Confusion());
436     if (ToReverse)
437       tab_c3d(i-1)->Reverse();
438     PrevVertex = (ToReverse)? VF : VL;
439     PrevEdge = anEdge;
440   }
441   Handle(TColGeom_HArray1OfBSplineCurve)  concatcurve;     //array of the concatenated curves
442   Handle(TColStd_HArray1OfInteger)        ArrayOfIndices;  //array of the remining Vertex
443   GeomConvert::ConcatC1(tab_c3d,
444                         tabtolvertex,
445                         ArrayOfIndices,
446                         concatcurve,
447                         Standard_False,
448                         Precision::Confusion());   //C1 concatenation
449   
450   if (concatcurve->Length() > 1)
451   {
452     GeomConvert_CompCurveToBSplineCurve Concat(concatcurve->Value(concatcurve->Lower()));
453     
454     for (i = concatcurve->Lower()+1; i <= concatcurve->Upper(); i++)
455       Concat.Add( concatcurve->Value(i), MaxTol, Standard_True );
456     
457     concatcurve->SetValue(concatcurve->Lower(), Concat.BSplineCurve());
458   }
459   Handle(Geom_BSplineCurve) ResCurve = concatcurve->Value(concatcurve->Lower());
460   
461   TColGeom2d_SequenceOfBoundedCurve ResPCurves;
462   TopLoc_Location aLoc;
463   for (j = 1; j <= SurfSeq.Length(); j++)
464   {
465     TColGeom2d_Array1OfBSplineCurve tab_c2d(0,nb_curve-1); //array of the pcurves
466     
467     PrevVertex = FirstVertex;
468     PrevEdge = FirstEdge;
469     //TopLoc_Location theLoc = LocSeq(j).Location();
470     for (i = 1; i <= nb_curve; i++)
471     {
472       TopoDS_Edge anEdge = TopoDS::Edge(aChain(i));
473       TopoDS_Vertex VF, VL;
474       TopExp::Vertices(anEdge, VF, VL);
475       Standard_Boolean ToReverse = (!VF.IsSame(PrevVertex));
476
477       /*
478       Handle(Geom2d_Curve) aPCurve =
479         BRep_Tool::CurveOnSurface(anEdge, SurfSeq(j), anEdge.Location()*theLoc, fpar, lpar);
480       */
481       Handle(Geom2d_Curve) aPCurve =
482         BRep_Tool::CurveOnSurface(anEdge, SurfSeq(j), aLoc, fpar, lpar);
483       Handle(Geom2d_TrimmedCurve) aTrPCurve = new Geom2d_TrimmedCurve(aPCurve, fpar, lpar);
484       tab_c2d(i-1) = Geom2dConvert::CurveToBSplineCurve(aTrPCurve);
485       Geom2dConvert::C0BSplineToC1BSplineCurve(tab_c2d(i-1), Precision::Confusion());
486       if (ToReverse)
487         tab_c2d(i-1)->Reverse();
488       PrevVertex = (ToReverse)? VF : VL;
489       PrevEdge = anEdge;
490     }
491     Handle(TColGeom2d_HArray1OfBSplineCurve)  concatc2d;     //array of the concatenated curves
492     Handle(TColStd_HArray1OfInteger)        ArrayOfInd2d;  //array of the remining Vertex
493     Geom2dConvert::ConcatC1(tab_c2d,
494                             tabtolvertex,
495                             ArrayOfInd2d,
496                             concatc2d,
497                             Standard_False,
498                             Precision::Confusion());   //C1 concatenation
499     
500     if (concatc2d->Length() > 1)
501     {
502       Geom2dConvert_CompCurveToBSplineCurve Concat2d(concatc2d->Value(concatc2d->Lower()));
503       
504       for (i = concatc2d->Lower()+1; i <= concatc2d->Upper(); i++)
505         Concat2d.Add( concatc2d->Value(i), MaxTol, Standard_True );
506       
507       concatc2d->SetValue(concatc2d->Lower(), Concat2d.BSplineCurve());
508     }
509     Handle(Geom2d_BSplineCurve) aResPCurve = concatc2d->Value(concatc2d->Lower());
510     ResPCurves.Append(aResPCurve);
511   }
512   
513   ResEdge = BRepLib_MakeEdge(ResCurve,
514                              FirstVertex, LastVertex,
515                              ResCurve->FirstParameter(), ResCurve->LastParameter());
516   BB.SameRange(ResEdge, Standard_False);
517   BB.SameParameter(ResEdge, Standard_False);
518   for (j = 1; j <= ResPCurves.Length(); j++)
519   {
520     BB.UpdateEdge(ResEdge, ResPCurves(j), SurfSeq(j), aLoc, MaxTol);
521     BB.Range(ResEdge, SurfSeq(j), aLoc, ResPCurves(j)->FirstParameter(), ResPCurves(j)->LastParameter());
522   }
523
524   BRepLib::SameParameter(ResEdge, MaxTol, Standard_True);
525   
526   return ResEdge;
527 }
528
529 static Standard_Boolean MergeSubSeq(const TopTools_SequenceOfShape& aChain, TopoDS_Edge& OutEdge, double Tol, Standard_Boolean ConcatBSplines) 
530 {
531   ShapeAnalysis_Edge sae;
532   BRep_Builder B;
533   // union edges in chain
534   int j;
535   Standard_Real fp1,lp1,fp2,lp2;
536   Standard_Boolean IsUnionOfLinesPossible = Standard_True;
537   Standard_Boolean IsUnionOfCirclesPossible = Standard_True;
538   Handle(Geom_Curve) c3d1, c3d2;
539   for(j=1; j<aChain.Length(); j++) 
540   {
541     TopoDS_Edge edge1 = TopoDS::Edge(aChain.Value(j));
542     c3d1 = BRep_Tool::Curve(edge1,fp1,lp1);
543
544     TopoDS_Edge edge2 = TopoDS::Edge(aChain.Value(j+1));
545     c3d2 = BRep_Tool::Curve(edge2,fp2,lp2);
546
547     if(c3d1.IsNull() || c3d2.IsNull()) 
548       return Standard_False;
549
550     while(c3d1->IsKind(STANDARD_TYPE(Geom_TrimmedCurve))) {
551       Handle(Geom_TrimmedCurve) tc =
552         Handle(Geom_TrimmedCurve)::DownCast(c3d1);
553       c3d1 = tc->BasisCurve();
554     }
555     while(c3d2->IsKind(STANDARD_TYPE(Geom_TrimmedCurve))) {
556       Handle(Geom_TrimmedCurve) tc =
557         Handle(Geom_TrimmedCurve)::DownCast(c3d2);
558       c3d2 = tc->BasisCurve();
559     }
560     if( c3d1->IsKind(STANDARD_TYPE(Geom_Line)) && c3d2->IsKind(STANDARD_TYPE(Geom_Line)) ) {
561       Handle(Geom_Line) L1 = Handle(Geom_Line)::DownCast(c3d1);
562       Handle(Geom_Line) L2 = Handle(Geom_Line)::DownCast(c3d2);
563       gp_Dir Dir1 = L1->Position().Direction();
564       gp_Dir Dir2 = L2->Position().Direction();
565       if(!Dir1.IsParallel(Dir2,Tol))  
566         IsUnionOfLinesPossible = Standard_False;
567     }
568     else
569       IsUnionOfLinesPossible = Standard_False;
570     if( c3d1->IsKind(STANDARD_TYPE(Geom_Circle)) && c3d2->IsKind(STANDARD_TYPE(Geom_Circle)) ) {
571       Handle(Geom_Circle) C1 = Handle(Geom_Circle)::DownCast(c3d1);
572       Handle(Geom_Circle) C2 = Handle(Geom_Circle)::DownCast(c3d2);
573       gp_Pnt P01 = C1->Location();
574       gp_Pnt P02 = C2->Location();
575       if (P01.Distance(P02) > Precision::Confusion())
576         IsUnionOfCirclesPossible = Standard_False;
577     }
578     else
579       IsUnionOfCirclesPossible = Standard_False;
580   }
581   if (IsUnionOfLinesPossible && IsUnionOfCirclesPossible)
582     return Standard_False;
583
584   //union of lines is possible
585   if (IsUnionOfLinesPossible)
586   {
587     TopoDS_Vertex V1 = sae.FirstVertex(TopoDS::Edge(aChain.First()));
588     gp_Pnt PV1 = BRep_Tool::Pnt(V1);
589     TopoDS_Vertex V2 = sae.LastVertex(TopoDS::Edge(aChain.Last()));
590     gp_Pnt PV2 = BRep_Tool::Pnt(V2);
591     gp_Vec Vec(PV1, PV2);
592     Handle(Geom_Line) L = new Geom_Line(gp_Ax1(PV1,Vec));
593     Standard_Real dist = PV1.Distance(PV2);
594     Handle(Geom_TrimmedCurve) tc = new Geom_TrimmedCurve(L,0.0,dist);
595     TopoDS_Edge E;
596     B.MakeEdge (E, tc ,Precision::Confusion());
597     B.Add (E,V1);  B.Add (E,V2);
598     B.UpdateVertex(V1, 0., E, 0.);
599     B.UpdateVertex(V2, dist, E, 0.);
600     OutEdge = E;
601     return Standard_True;
602   }
603
604   if (IsUnionOfCirclesPossible)
605   {
606     double f,l;
607     TopoDS_Edge FE = TopoDS::Edge(aChain.First());
608     Handle(Geom_Curve) c3d = BRep_Tool::Curve(FE,f,l);
609
610     while(c3d->IsKind(STANDARD_TYPE(Geom_TrimmedCurve))) {
611       Handle(Geom_TrimmedCurve) tc =
612         Handle(Geom_TrimmedCurve)::DownCast(c3d);
613       c3d = tc->BasisCurve();
614     }
615     Handle(Geom_Circle) Cir = Handle(Geom_Circle)::DownCast(c3d);
616
617     TopoDS_Vertex V1 = sae.FirstVertex(FE);
618     TopoDS_Vertex V2 = sae.LastVertex(TopoDS::Edge(aChain.Last()));
619     TopoDS_Edge E;
620     if (V1.IsSame(V2)) {
621       // closed chain
622       BRepAdaptor_Curve adef(FE);
623       Handle(Geom_Circle) Cir1;
624       double FP, LP;
625       if ( FE.Orientation() == TopAbs_FORWARD)
626       {
627         FP = adef.FirstParameter();
628         LP = adef.LastParameter();
629       }
630       else
631       {
632         FP = adef.LastParameter();
633         LP = adef.FirstParameter();
634       }
635       if (Abs(FP) < Precision::PConfusion())
636       {
637         B.MakeEdge (E,Cir, Precision::Confusion());
638         B.Add(E,V1);
639         B.Add(E,V2);
640         E.Orientation(FE.Orientation());
641       }
642       else
643       {
644         GC_MakeCircle MC1 (adef.Value(FP), adef.Value((FP + LP) * 0.5), adef.Value(LP));
645         if (MC1.IsDone())
646           Cir1 = MC1.Value();
647         else
648           return Standard_False;
649         B.MakeEdge (E, Cir1, Precision::Confusion());
650         B.Add(E,V1);
651         B.Add(E,V2);
652       }
653     }
654     else {
655       gp_Pnt PV1 = BRep_Tool::Pnt(V1);
656       gp_Pnt PV2 = BRep_Tool::Pnt(V2);
657       TopoDS_Vertex VM = sae.LastVertex(FE);
658       gp_Pnt PVM = BRep_Tool::Pnt(VM);
659       GC_MakeCircle MC (PV1,PVM,PV2);
660       Handle(Geom_Circle) C = MC.Value();
661       gp_Pnt P0 = C->Location();
662       gp_Dir D1(gp_Vec(P0,PV1));
663       gp_Dir D2(gp_Vec(P0,PV2));
664       Standard_Real fpar = C->XAxis().Direction().Angle(D1);
665       if(fabs(fpar)>Precision::Confusion()) {
666         // check orientation
667         gp_Dir ND =  C->XAxis().Direction().Crossed(D1);
668         if(ND.IsOpposite(C->Axis().Direction(),Precision::Confusion())) {
669           fpar = -fpar;
670         }
671       }
672       Standard_Real lpar = C->XAxis().Direction().Angle(D2);
673       if(fabs(lpar)>Precision::Confusion()) {
674         // check orientation
675         gp_Dir ND =  C->XAxis().Direction().Crossed(D2);
676         if(ND.IsOpposite(C->Axis().Direction(),Precision::Confusion())) {
677           lpar = -lpar;
678         }
679       }
680       if (lpar < fpar) lpar += 2*M_PI;
681       Handle(Geom_TrimmedCurve) tc = new Geom_TrimmedCurve(C,fpar,lpar);
682       B.MakeEdge (E,tc,Precision::Confusion());
683       B.Add(E,V1);
684       B.Add(E,V2);
685       B.UpdateVertex(V1, fpar, E, 0.);
686       B.UpdateVertex(V2, lpar, E, 0.);
687     }
688     OutEdge = E;
689     return Standard_True;
690   }
691   if (aChain.Length() > 1 && ConcatBSplines) {
692     // second step: union edges with various curves
693     // skl for bug 0020052 from Mantis: perform such unions
694     // only if curves are bspline or bezier
695
696     TopoDS_Vertex VF = sae.FirstVertex(TopoDS::Edge(aChain.First()));
697     TopoDS_Vertex VL = sae.LastVertex(TopoDS::Edge(aChain.Last()));
698     Standard_Boolean NeedUnion = Standard_True;
699     for(j=1; j<=aChain.Length(); j++) {
700       TopoDS_Edge edge = TopoDS::Edge(aChain.Value(j));
701       TopLoc_Location Loc;
702       Handle(Geom_Curve) c3d = BRep_Tool::Curve(edge,Loc,fp1,lp1);
703       if(c3d.IsNull()) continue;
704       while(c3d->IsKind(STANDARD_TYPE(Geom_TrimmedCurve))) {
705         Handle(Geom_TrimmedCurve) tc =
706           Handle(Geom_TrimmedCurve)::DownCast(c3d);
707         c3d = tc->BasisCurve();
708       }
709       if( ( c3d->IsKind(STANDARD_TYPE(Geom_BSplineCurve)) ||
710             c3d->IsKind(STANDARD_TYPE(Geom_BezierCurve)) ) ) continue;
711       NeedUnion = Standard_False;
712       break;
713     }
714     if(NeedUnion) {
715 #ifdef OCCT_DEBUG
716       cout<<"can not make analitical union => make approximation"<<endl;
717 #endif
718       TopoDS_Edge E = GlueEdgesWithPCurves(aChain, VF, VL);
719       OutEdge = E;
720       return Standard_True;
721     }
722     else {
723 #ifdef OCCT_DEBUG
724       cout<<"can not make approximation for such types of curves"<<endl;
725 #endif
726       return Standard_False;
727     }
728   }
729   return Standard_False;
730 }
731
732 static Standard_Boolean IsMergingPossible(const TopoDS_Edge& edge1, const TopoDS_Edge& edge2, 
733                                           double Tol, const TopTools_MapOfShape& DegEdgeVrt)
734 {
735   TopoDS_Vertex CV = TopExp::LastVertex(edge1, Standard_True);
736   if (CV.IsNull() || DegEdgeVrt.Contains(CV))
737     return Standard_False;
738
739   BRepAdaptor_Curve ade1(edge1);
740   BRepAdaptor_Curve ade2(edge2);
741
742   GeomAbs_CurveType t1 = ade1.GetType();
743   GeomAbs_CurveType t2 = ade2.GetType();
744
745   if( t1 == GeomAbs_Circle && t2 == GeomAbs_Circle)
746   {
747     if (ade1.Circle().Location().Distance(ade2.Circle().Location()) > Precision::Confusion())
748       return Standard_False;
749   }
750
751   if( ( (t1 != GeomAbs_BezierCurve && t1 != GeomAbs_BSplineCurve) ||
752       (t2 != GeomAbs_BezierCurve && t2 != GeomAbs_BSplineCurve)) && t1 != t2)
753     return Standard_False;
754
755   gp_Vec Diff1, Diff2;
756   gp_Pnt P1, P2;
757   if (edge1.Orientation() == TopAbs_FORWARD)
758     ade1.D1(ade1.LastParameter(), P1, Diff1);
759   else
760   {
761     ade1.D1(ade1.FirstParameter(), P1, Diff1);
762     Diff1 = -Diff1;
763   }
764
765   if (edge2.Orientation() == TopAbs_FORWARD)
766     ade2.D1(ade2.FirstParameter(), P2, Diff2);
767   else
768   {
769     ade2.D1(ade2.LastParameter(), P2, Diff2);
770     Diff2 = -Diff2;
771   }
772
773   if (Diff1.Angle(Diff2) > Tol)
774     return Standard_False;
775
776   return Standard_True;
777 }
778
779 static void GenerateSubSeq (const TopTools_SequenceOfShape& anInpEdgeSeq,
780                             NCollection_Sequence<SubSequenceOfEdges>& SeqOfSubSeqOfEdges,
781                             Standard_Boolean IsClosed, double Tol, const TopTools_MapOfShape& DegEdgeVrt )
782 {
783   Standard_Boolean isOk = Standard_False;
784   TopoDS_Edge edge1, edge2;
785
786   SubSequenceOfEdges SubSeq;
787   SubSeq.SeqsEdges.Append(TopoDS::Edge(anInpEdgeSeq(1)));
788   SeqOfSubSeqOfEdges.Append(SubSeq);
789
790   for (int i = 1; i < anInpEdgeSeq.Length(); i++)
791   {
792     edge1 = TopoDS::Edge(anInpEdgeSeq(i));
793     edge2 = TopoDS::Edge(anInpEdgeSeq(i+1));
794     isOk = IsMergingPossible(edge1, edge2, Tol, DegEdgeVrt);
795     if (!isOk)
796     {
797       SubSequenceOfEdges SubSeq;
798       SubSeq.SeqsEdges.Append(edge2);
799       SeqOfSubSeqOfEdges.Append(SubSeq);
800     }
801     else
802       SeqOfSubSeqOfEdges.ChangeLast().SeqsEdges.Append(edge2);
803   }
804   /// check first and last chain segments
805   if (IsClosed && SeqOfSubSeqOfEdges.Length() > 1)
806   {
807     edge1 = TopoDS::Edge(anInpEdgeSeq.Last());
808     edge2 = TopoDS::Edge(anInpEdgeSeq.First());
809     if (IsMergingPossible(edge1, edge2, Tol, DegEdgeVrt))
810     {
811       SeqOfSubSeqOfEdges.ChangeLast().SeqsEdges.Append(SeqOfSubSeqOfEdges.ChangeFirst().SeqsEdges);
812       SeqOfSubSeqOfEdges.Remove(1);
813     }
814   }
815 }
816
817
818 //=======================================================================
819 //function : MergeEdges
820 //purpose  : auxilary
821 //=======================================================================
822 static Standard_Boolean MergeEdges(const TopTools_SequenceOfShape& SeqEdges,
823                                    const Standard_Real Tol,
824                                    const Standard_Boolean ConcatBSplines,
825                                    NCollection_Sequence<SubSequenceOfEdges>& SeqOfSubSeqOfEdges,
826                                    const TopTools_MapOfShape& NonMergVrt )
827 {
828   // make chain for union
829   //BRep_Builder B;
830   ShapeAnalysis_Edge sae;
831   TopoDS_Edge FirstE = TopoDS::Edge(SeqEdges.Value(1));
832   TopoDS_Edge LastE = FirstE;
833   TopoDS_Vertex VF = sae.FirstVertex(FirstE);
834   TopoDS_Vertex VL = sae.LastVertex(LastE);
835   TopTools_SequenceOfShape aChain;
836   aChain.Append(FirstE);
837   TColStd_MapOfInteger IndUsedEdges;
838   IndUsedEdges.Add(1);
839   Standard_Integer j;
840   TopTools_MapOfShape VerticesToAvoid;
841   TopTools_SequenceOfShape SeqEdges1;
842   for (j = 1; j <= SeqEdges.Length(); j++)
843   {
844     TopoDS_Edge anEdge = TopoDS::Edge(SeqEdges(j));
845     if (BRep_Tool::Degenerated(anEdge))
846     {
847       TopoDS_Vertex V1, V2;
848       TopExp::Vertices(anEdge, V1, V2);
849       VerticesToAvoid.Add(V1);
850       VerticesToAvoid.Add(V2);
851       continue;
852     }
853     SeqEdges1.Append(anEdge);
854   }
855
856   for(j=2; j<=SeqEdges1.Length(); j++) {
857     for(Standard_Integer k=2; k<=SeqEdges1.Length(); k++) {
858       if(IndUsedEdges.Contains(k)) continue;
859       TopoDS_Edge edge = TopoDS::Edge(SeqEdges1.Value(k));
860       TopoDS_Vertex VF2 = sae.FirstVertex(edge);
861       TopoDS_Vertex VL2 = sae.LastVertex(edge);
862       if(VF2.IsSame(VL)) {
863         aChain.Append(edge);
864         LastE = edge;
865         VL = sae.LastVertex(LastE);
866         IndUsedEdges.Add(k);
867       }
868       else if(VL2.IsSame(VF)) {
869         aChain.Prepend(edge);
870         FirstE = edge;
871         VF = sae.FirstVertex(FirstE);
872         IndUsedEdges.Add(k);
873       }
874     }
875   }
876
877   Standard_Boolean IsClosed = Standard_False;
878   if (VF.IsSame ( VL ))
879     IsClosed = Standard_True;
880
881   VerticesToAvoid.Unite(NonMergVrt);
882   GenerateSubSeq(aChain, SeqOfSubSeqOfEdges, IsClosed, Tol, VerticesToAvoid);
883
884   for (int i = 1; i <= SeqOfSubSeqOfEdges.Length(); i++)
885   {
886     TopoDS_Edge UE;
887     if (SeqOfSubSeqOfEdges(i).SeqsEdges.Length() < 2)
888       continue;
889     if (MergeSubSeq(SeqOfSubSeqOfEdges(i).SeqsEdges, UE, Tol, ConcatBSplines))
890       SeqOfSubSeqOfEdges(i).UnionEdges = UE;
891   }
892   return Standard_True;
893 }
894
895 static Standard_Boolean MergeSeq (const TopTools_SequenceOfShape& SeqEdges,
896                                   const Standard_Real Tol,
897                                   const Standard_Boolean ConcatBSplines,
898                                   Handle(ShapeBuild_ReShape)& theContext,
899                                   TopTools_DataMapOfShapeShape& theOldShapes,
900                                   const TopTools_MapOfShape& nonMergVert,
901                                   const TopTools_DataMapOfShapeShape& NewEdges2OldEdges)
902
903   NCollection_Sequence<SubSequenceOfEdges> SeqOfSubsSeqOfEdges;
904   int k = 1;
905   if ( MergeEdges(SeqEdges, Tol, ConcatBSplines, SeqOfSubsSeqOfEdges, nonMergVert) )
906   {
907     for (Standard_Integer i = 1; i <= SeqOfSubsSeqOfEdges.Length(); i++ )
908     {
909       if (SeqOfSubsSeqOfEdges(i).UnionEdges.IsNull())
910         continue;
911       theContext->Replace(SeqOfSubsSeqOfEdges(i).SeqsEdges(1), SeqOfSubsSeqOfEdges(i).UnionEdges);
912       k++;
913       for (Standard_Integer j = 2; j <= SeqOfSubsSeqOfEdges(i).SeqsEdges.Length(); j++)
914       {
915         TopoDS_Shape OldEdge = NewEdges2OldEdges(SeqOfSubsSeqOfEdges(i).SeqsEdges(j));
916         theOldShapes.Bind(OldEdge, SeqOfSubsSeqOfEdges(i).UnionEdges);
917         theContext->Remove(SeqOfSubsSeqOfEdges(i).SeqsEdges(j));
918       }
919     }
920     return Standard_True;
921   }
922   else
923     return Standard_False;
924 }
925
926 static void CheckSharedVertices(const TopTools_SequenceOfShape& theSeqEdges, 
927                                 const TopTools_IndexedDataMapOfShapeListOfShape& theMapEdgesVertex,
928                                 TopTools_MapOfShape& theShareVertMap)
929 {
930   ShapeAnalysis_Edge sae;
931   TopTools_SequenceOfShape SeqVertexes;
932   TopTools_MapOfShape MapVertexes;
933   for (Standard_Integer k = 1; k <= theSeqEdges.Length(); k++ )
934   {
935     TopoDS_Vertex aV1 = sae.FirstVertex(TopoDS::Edge(theSeqEdges(k)));
936     TopoDS_Vertex aV2 = sae.LastVertex(TopoDS::Edge(theSeqEdges(k)));
937     if (!MapVertexes.Add(aV1))
938       SeqVertexes.Append(aV1);
939     if (!MapVertexes.Add(aV2))
940       SeqVertexes.Append(aV2);
941   }
942
943   for (Standard_Integer k = 1; k <= SeqVertexes.Length()/* && !IsSharedVertexPresent*/; k++ )
944   {
945     const TopTools_ListOfShape& ListEdgesV1 = theMapEdgesVertex.FindFromKey(SeqVertexes(k));
946     TopTools_MapOfShape aMapOfEdges;
947     TopTools_ListIteratorOfListOfShape iter(ListEdgesV1);
948     for (; iter.More(); iter.Next())
949       aMapOfEdges.Add(iter.Value());
950     if (aMapOfEdges.Extent() > 2)
951       theShareVertMap.Add(SeqVertexes(k));
952   }
953   //return theShareVertMap.IsEmpty() ? false : true;
954 }
955
956 //=======================================================================
957 //function : ShapeUpgrade_UnifySameDomain
958 //purpose  : Constructor
959 //=======================================================================
960
961 ShapeUpgrade_UnifySameDomain::ShapeUpgrade_UnifySameDomain()
962 {
963   myUnifyEdges = Standard_True;
964   myUnifyFaces = Standard_True;
965   myConcatBSplines = Standard_False;
966
967   myContext = new ShapeBuild_ReShape;
968 }
969
970 //=======================================================================
971 //function : ShapeUpgrade_UnifySameDomain
972 //purpose  : Constructor
973 //=======================================================================
974
975 ShapeUpgrade_UnifySameDomain::ShapeUpgrade_UnifySameDomain(const TopoDS_Shape& aShape,
976                                                            const Standard_Boolean UnifyEdges,
977                                                            const Standard_Boolean UnifyFaces,
978                                                            const Standard_Boolean ConcatBSplines)
979 {
980   myInitShape = aShape;
981   myShape = aShape;
982   myUnifyEdges = UnifyEdges;
983   myUnifyFaces = UnifyFaces;
984   myConcatBSplines = ConcatBSplines;
985
986   myContext = new ShapeBuild_ReShape;
987 }
988
989 //=======================================================================
990 //function : Initialize
991 //purpose  : 
992 //=======================================================================
993
994 void ShapeUpgrade_UnifySameDomain::Initialize(const TopoDS_Shape& aShape,
995                                               const Standard_Boolean UnifyEdges,
996                                               const Standard_Boolean UnifyFaces,
997                                               const Standard_Boolean ConcatBSplines)
998 {
999   myInitShape = aShape;
1000   myShape = aShape;
1001   myUnifyEdges = UnifyEdges;
1002   myUnifyFaces = UnifyFaces;
1003   myConcatBSplines = ConcatBSplines;
1004
1005   myContext->Clear();
1006   myOldShapes.Clear();
1007   //myGenerated.Clear();
1008 }
1009
1010 //=======================================================================
1011 //function : putIntWires
1012 //purpose  : Add internal wires that are classified inside the face as a subshape,
1013 //           and remove them from the sequence
1014 //=======================================================================
1015 static void putIntWires(TopoDS_Shape& theFace, TopTools_SequenceOfShape& theWires)
1016 {
1017   TopoDS_Face& aFace = TopoDS::Face(theFace);
1018   for (Standard_Integer i=1; i <= theWires.Length(); i++)
1019   {
1020     TopoDS_Shape aWire = theWires(i);
1021     gp_Pnt2d aP2d;
1022     Standard_Boolean isP2d = Standard_False;
1023     for (TopoDS_Iterator it(aWire); it.More() && !isP2d; it.Next())
1024     {
1025       const TopoDS_Edge& anEdge = TopoDS::Edge(it.Value());
1026       Standard_Real aFirst, aLast;
1027       Handle(Geom2d_Curve) aC2d = BRep_Tool::CurveOnSurface(anEdge, aFace, aFirst, aLast);
1028       aC2d->D0((aFirst + aLast) * 0.5, aP2d);
1029       isP2d = Standard_True;
1030     }
1031     BRepClass_FaceClassifier aClass(aFace, aP2d, Precision::PConfusion());
1032     if (aClass.State() == TopAbs_IN)
1033     {
1034       BRep_Builder().Add(aFace, aWire);
1035       theWires.Remove(i);
1036       i--;
1037     }
1038   }
1039 }
1040
1041 //=======================================================================
1042 //function : UnifyFaces
1043 //purpose  : 
1044 //=======================================================================
1045
1046 void ShapeUpgrade_UnifySameDomain::UnifyFaces()
1047 {
1048   //Handle(ShapeBuild_ReShape) myContext = new ShapeBuild_ReShape;
1049   TopoDS_Shape aResShape = myContext->Apply(myShape);
1050
1051   // processing each shell
1052   TopExp_Explorer exps;
1053   for (exps.Init(myShape, TopAbs_SHELL); exps.More(); exps.Next()) {
1054     TopoDS_Shell aShell = TopoDS::Shell(exps.Current());
1055
1056     // creating map of edge faces
1057     TopTools_IndexedDataMapOfShapeListOfShape aMapEdgeFaces;
1058     TopExp::MapShapesAndAncestors(aShell, TopAbs_EDGE, TopAbs_FACE, aMapEdgeFaces);
1059
1060     // map of processed shapes
1061     TopTools_MapOfShape aProcessed;
1062
1063     //Handle(ShapeBuild_ReShape) aContext = new ShapeBuild_ReShape;
1064
1065     Standard_Integer NbModif = 0;
1066     Standard_Boolean hasFailed = Standard_False;
1067     Standard_Real tol = Precision::Confusion();
1068
1069     // count faces
1070     Standard_Integer nbf = 0;
1071     TopExp_Explorer exp;
1072     TopTools_MapOfShape mapF;
1073     for (exp.Init(aShell, TopAbs_FACE); exp.More(); exp.Next()) {
1074       if (mapF.Add(exp.Current()))
1075         nbf++;
1076     }
1077
1078     // processing each face
1079     mapF.Clear();
1080     for (exp.Init(aShell, TopAbs_FACE); exp.More(); exp.Next()) {
1081       TopoDS_Face aFace = TopoDS::Face(exp.Current().Oriented(TopAbs_FORWARD));
1082
1083       if (aProcessed.Contains(aFace))
1084         continue;
1085
1086       Standard_Integer dummy;
1087       TopTools_SequenceOfShape edges;
1088       AddOrdinaryEdges(edges,aFace,dummy);
1089
1090       TopTools_SequenceOfShape faces;
1091       faces.Append(aFace);
1092
1093       //surface and location to construct result
1094       TopLoc_Location aBaseLocation;
1095       Handle(Geom_Surface) aBaseSurface = BRep_Tool::Surface(aFace,aBaseLocation);
1096       aBaseSurface = ClearRts(aBaseSurface);
1097
1098       // find adjacent faces to union
1099       Standard_Integer i;
1100       for (i = 1; i <= edges.Length(); i++) {
1101         TopoDS_Edge edge = TopoDS::Edge(edges(i));
1102         if (BRep_Tool::Degenerated(edge))
1103           continue;
1104
1105         const TopTools_ListOfShape& aList = aMapEdgeFaces.FindFromKey(edge);
1106         TopTools_ListIteratorOfListOfShape anIter(aList);
1107         for (; anIter.More(); anIter.Next()) {
1108           TopoDS_Face anCheckedFace = TopoDS::Face(anIter.Value().Oriented(TopAbs_FORWARD));
1109           if (anCheckedFace.IsSame(aFace))
1110             continue;
1111
1112           if (aProcessed.Contains(anCheckedFace))
1113             continue;
1114
1115           if (IsSameDomain(aFace,anCheckedFace)) {
1116
1117             if (aList.Extent() != 2) {
1118               // non mainfold case is not processed
1119               continue;
1120             }
1121
1122             // replacing pcurves
1123             TopoDS_Face aMockUpFace;
1124             BRep_Builder B;
1125             B.MakeFace(aMockUpFace,aBaseSurface,aBaseLocation,0.);
1126             MovePCurves(aMockUpFace,anCheckedFace);
1127
1128             if (AddOrdinaryEdges(edges,aMockUpFace,dummy)) {
1129               // sequence edges is modified
1130               i = dummy;
1131             }
1132
1133             faces.Append(anCheckedFace);
1134             aProcessed.Add(anCheckedFace);
1135             break;
1136           }
1137         }
1138       }
1139
1140       // all faces collected in the sequence. Perform union of faces
1141       if (faces.Length() > 1) {
1142         NbModif++;
1143         TopoDS_Face aResult;
1144         BRep_Builder B;
1145         B.MakeFace(aResult,aBaseSurface,aBaseLocation,0);
1146         Standard_Integer nbWires = 0;
1147
1148         // connecting wires
1149         while (edges.Length()>0) {
1150
1151           Standard_Boolean isEdge3d = Standard_False;
1152           nbWires++;
1153           TopTools_MapOfShape aVertices;
1154           TopoDS_Wire aWire;
1155           B.MakeWire(aWire);
1156
1157           TopoDS_Edge anEdge = TopoDS::Edge(edges(1));
1158           edges.Remove(1);
1159           // collect internal edges in separate wires
1160           Standard_Boolean isInternal = (anEdge.Orientation() == TopAbs_INTERNAL);
1161
1162           isEdge3d |= !BRep_Tool::Degenerated(anEdge);
1163           B.Add(aWire,anEdge);
1164           TopoDS_Vertex V1,V2;
1165           TopExp::Vertices(anEdge,V1,V2);
1166           aVertices.Add(V1);
1167           aVertices.Add(V2);
1168
1169           Standard_Boolean isNewFound = Standard_False;
1170           do {
1171             isNewFound = Standard_False;
1172             for(Standard_Integer j = 1; j <= edges.Length(); j++) {
1173               anEdge = TopoDS::Edge(edges(j));
1174               // check if the current edge orientation corresponds to the first one
1175               Standard_Boolean isCurrInternal = (anEdge.Orientation() == TopAbs_INTERNAL);
1176               if (isCurrInternal != isInternal)
1177                 continue;
1178               TopExp::Vertices(anEdge,V1,V2);
1179               if(aVertices.Contains(V1) || aVertices.Contains(V2)) {
1180                 isEdge3d |= !BRep_Tool::Degenerated(anEdge);
1181                 aVertices.Add(V1);
1182                 aVertices.Add(V2);
1183                 B.Add(aWire,anEdge);
1184                 edges.Remove(j);
1185                 j--;
1186                 isNewFound = Standard_True;
1187               }
1188             }
1189           } while (isNewFound);
1190
1191           // sorting any type of edges
1192           aWire.Closed (BRep_Tool::IsClosed (aWire));
1193           aWire = TopoDS::Wire(myContext->Apply(aWire));
1194
1195           TopoDS_Face tmpF = TopoDS::Face(myContext->Apply(faces(1).Oriented(TopAbs_FORWARD)));
1196           Handle(ShapeFix_Wire) sfw = new ShapeFix_Wire(aWire,tmpF,Precision::Confusion());
1197           sfw->FixReorder();
1198           Standard_Boolean isDegRemoved = Standard_False;
1199           if(!sfw->StatusReorder ( ShapeExtend_FAIL )) {
1200             // clear degenerated edges if at least one with 3d curve exist
1201             if(isEdge3d) {
1202               Handle(ShapeExtend_WireData) sewd = sfw->WireData();
1203               for(Standard_Integer j = 1; j<=sewd->NbEdges();j++) {
1204                 TopoDS_Edge E = sewd->Edge(j);
1205                 if(BRep_Tool::Degenerated(E)) {
1206                   sewd->Remove(j);
1207                   isDegRemoved = Standard_True;
1208                   j--;
1209                 }
1210               }
1211             }
1212             sfw->FixShifted();
1213             if(isDegRemoved)
1214               sfw->FixDegenerated();
1215           }
1216           TopoDS_Wire aWireFixed = sfw->Wire();
1217           //aContext->Replace(aWire,aWireFixed);
1218           myContext->Replace(aWire,aWireFixed);
1219           //for history
1220           /*
1221           if (!myOldNewMap.IsBound(aWire))
1222           {
1223             TopTools_ListOfShape EmptyList;
1224             myOldNewMap.Bind(aWire, EmptyList);
1225           }
1226           myOldNewMap(aWire).Clear();
1227           myOldNewMap(aWire).Append(aWireFixed);
1228           */
1229           /////////////
1230           
1231           // add resulting wire
1232           if(isEdge3d) {
1233             B.Add(aResult,aWireFixed);
1234           }
1235           else  {
1236             // sorting edges
1237             Handle(ShapeExtend_WireData) sbwd = sfw->WireData();
1238             Standard_Integer nbEdges = sbwd->NbEdges();
1239             // sort degenerated edges and create one edge instead of several ones
1240             ShapeAnalysis_WireOrder sawo(Standard_False, 0);
1241             ShapeAnalysis_Edge sae;
1242             Standard_Integer aLastEdge = nbEdges;
1243             for(Standard_Integer j = 1; j <= nbEdges; j++) {
1244               Standard_Real f,l;
1245               //smh protection on NULL pcurve
1246               Handle(Geom2d_Curve) c2d;
1247               if(!sae.PCurve(sbwd->Edge(j),tmpF,c2d,f,l)) {
1248                 aLastEdge--;
1249                 continue;
1250               }
1251               sawo.Add(c2d->Value(f).XY(),c2d->Value(l).XY());
1252             }
1253             sawo.Perform();
1254
1255             // constructind one degenerative edge
1256             gp_XY aStart, anEnd, tmp;
1257             Standard_Integer nbFirst = sawo.Ordered(1);
1258             TopoDS_Edge anOrigE = TopoDS::Edge(sbwd->Edge(nbFirst).Oriented(TopAbs_FORWARD));
1259             ShapeBuild_Edge sbe;
1260             TopoDS_Vertex aDummyV;
1261             TopoDS_Edge E = sbe.CopyReplaceVertices(anOrigE,aDummyV,aDummyV);
1262             sawo.XY(nbFirst,aStart,tmp);
1263             sawo.XY(sawo.Ordered(aLastEdge),tmp,anEnd);
1264
1265             gp_XY aVec = anEnd-aStart;
1266             Handle(Geom2d_Line) aLine = new Geom2d_Line(aStart,gp_Dir2d(anEnd-aStart));
1267
1268             B.UpdateEdge(E,aLine,tmpF,0.);
1269             B.Range(E,tmpF,0.,aVec.Modulus());
1270             Handle(Geom_Curve) C3d;
1271             B.UpdateEdge(E,C3d,0.);
1272             B.Degenerated(E,Standard_True);
1273             TopoDS_Wire aW;
1274             B.MakeWire(aW);
1275             B.Add(aW,E);
1276             aW.Closed (Standard_True);
1277             B.Add(aResult,aW);
1278           }
1279         }
1280
1281         // perform substitution of face
1282         //aContext->Replace(aContext->Apply(aFace),aResult);
1283         myContext->Replace(myContext->Apply(aFace),aResult);
1284         //for history
1285         /*
1286         if (!myOldNewMap.IsBound(aFace))
1287         {
1288           TopTools_ListOfShape EmptyList;
1289           myOldNewMap.Bind(aFace, EmptyList);
1290         }
1291         myOldNewMap(aFace).Clear();
1292         myOldNewMap(aFace).Append(aResult);
1293         */
1294         /////////////
1295
1296         ShapeFix_Face sff (aResult);
1297         //Intializing by tolerances
1298         sff.SetPrecision(Precision::Confusion());
1299         sff.SetMinTolerance(tol);
1300         sff.SetMaxTolerance(1.);
1301         //Setting modes
1302         sff.FixOrientationMode() = 0;
1303         //sff.FixWireMode() = 0;
1304         //sff.SetContext(aContext);
1305         sff.SetContext(myContext);
1306         // Applying the fixes
1307         sff.Perform();
1308         if(sff.Status(ShapeExtend_FAIL))
1309         hasFailed = Standard_True;
1310
1311         // breaking down to several faces
1312         //TopoDS_Shape theResult = aContext->Apply(aResult);
1313         TopoDS_Shape theResult = myContext->Apply(aResult);
1314         for (TopExp_Explorer aFaceExp (theResult,TopAbs_FACE); aFaceExp.More(); aFaceExp.Next()) {
1315           TopoDS_Face aCurrent = TopoDS::Face(aFaceExp.Current().Oriented(TopAbs_FORWARD));
1316           Handle(TColGeom_HArray2OfSurface) grid = new TColGeom_HArray2OfSurface ( 1, 1, 1, 1 );
1317           grid->SetValue ( 1, 1, aBaseSurface );
1318           Handle(ShapeExtend_CompositeSurface) G = new ShapeExtend_CompositeSurface ( grid );
1319           ShapeFix_ComposeShell CompShell;
1320           CompShell.Init ( G, aBaseLocation, aCurrent, ::Precision::Confusion() );//myPrecision
1321           //CompShell.SetContext( aContext );
1322           CompShell.SetContext( myContext );
1323
1324           TopTools_SequenceOfShape parts, anIntWires;
1325           ShapeFix_SequenceOfWireSegment wires;
1326           for(TopExp_Explorer W_Exp(aCurrent,TopAbs_WIRE);W_Exp.More();W_Exp.Next()) {
1327             const TopoDS_Wire& aWire = TopoDS::Wire(W_Exp.Current());
1328             // check if the wire is ordinary (contains non-internal edges)
1329             Standard_Boolean isInternal = Standard_True;
1330             for (TopoDS_Iterator it(aWire); it.More() && isInternal; it.Next())
1331               isInternal = (it.Value().Orientation() == TopAbs_INTERNAL);
1332             if (isInternal)
1333             {
1334               // place internal wire separately
1335               anIntWires.Append(aWire);
1336             }
1337             else
1338             {
1339               Handle(ShapeExtend_WireData) sbwd =
1340                 new ShapeExtend_WireData (aWire);
1341               ShapeFix_WireSegment seg ( sbwd, TopAbs_REVERSED );
1342               wires.Append(seg);
1343             }
1344           }
1345
1346           CompShell.DispatchWires ( parts,wires );
1347           for (Standard_Integer j=1; j <= parts.Length(); j++ ) {
1348             ShapeFix_Face aFixOrient(TopoDS::Face(parts(j)));
1349             //aFixOrient.SetContext(aContext);
1350             aFixOrient.SetContext(myContext);
1351             aFixOrient.FixOrientation();
1352             // put internal wires to faces
1353             putIntWires(parts(j), anIntWires);
1354           }
1355
1356           TopoDS_Shape CompRes;
1357           if ( parts.Length() !=1 ) {
1358             TopoDS_Shell S;
1359             B.MakeShell ( S );
1360             for ( i=1; i <= parts.Length(); i++ )
1361               B.Add ( S, parts(i) );
1362             S.Closed (BRep_Tool::IsClosed (S));
1363             CompRes = S;
1364           }
1365           else CompRes = parts(1);
1366
1367           //aContext->Replace(aCurrent,CompRes);
1368           myContext->Replace(aCurrent,CompRes);
1369           //for history
1370           /*
1371           if (!myOldNewMap.IsBound(aCurrent))
1372           {
1373             TopTools_ListOfShape EmptyList;
1374             myOldNewMap.Bind(aCurrent, EmptyList);
1375           }
1376           myOldNewMap(aCurrent).Clear();
1377           myOldNewMap(aCurrent).Append(CompRes);
1378           */
1379           /////////////
1380         }
1381
1382         // remove the remaining faces
1383         for(i = 2; i <= faces.Length(); i++)
1384         { 
1385           myOldShapes.Bind(faces(i), theResult);
1386           myContext->Remove(faces(i));
1387         }
1388       }
1389     } // end processing each face
1390
1391     //TopoDS_Shape aResult = Shape;
1392     if (NbModif > 0 && !hasFailed) {
1393       //TopoDS_Shape aResult = aContext->Apply(aShell);
1394       TopoDS_Shape aResult = myContext->Apply(aShell);
1395
1396       ShapeFix_Edge sfe;
1397       for (exp.Init(aResult,TopAbs_EDGE); exp.More(); exp.Next()) {
1398         TopoDS_Edge E = TopoDS::Edge(exp.Current());
1399         sfe.FixVertexTolerance (E);
1400         // ptv add fix same parameter
1401         sfe.FixSameParameter(E, Precision::Confusion());
1402       }
1403
1404       myContext->Replace(aShell, aResult);
1405       //for history
1406       /*
1407       if (!myOldNewMap.IsBound(aShell))
1408       {
1409         TopTools_ListOfShape EmptyList;
1410         myOldNewMap.Bind(aShell, EmptyList);
1411       }
1412       myOldNewMap(aShell).Clear();
1413       myOldNewMap(aShell).Append(aResult);
1414       */
1415       /////////////
1416     }
1417     //else
1418     {
1419       for (exp.Init(aShell, TopAbs_FACE); exp.More(); exp.Next()) {
1420         TopoDS_Face aFace = TopoDS::Face(exp.Current().Oriented(TopAbs_FORWARD));
1421         Handle(ShapeFix_Wire) sfw = new ShapeFix_Wire;
1422         sfw->SetContext(myContext);
1423         sfw->SetPrecision(Precision::Confusion());
1424         sfw->SetMinTolerance(Precision::Confusion());
1425         sfw->SetMaxTolerance(1.);
1426         sfw->SetFace(aFace);
1427         for (TopoDS_Iterator iter (aFace,Standard_False); iter.More(); iter.Next()) {
1428           TopoDS_Wire wire = TopoDS::Wire(iter.Value());
1429           sfw->Load(wire);
1430           sfw->FixReorder();
1431           sfw->FixShifted();
1432         }
1433       }
1434     }
1435   } // end processing each shell
1436
1437   myShape = myContext->Apply(myShape);
1438 }
1439
1440 //=======================================================================
1441 //function : UnifyEdges
1442 //purpose  : 
1443 //=======================================================================
1444 void ShapeUpgrade_UnifySameDomain::UnifyEdges()
1445 {
1446   Standard_Real Tol = Precision::Confusion();
1447   
1448   //Handle(ShapeBuild_ReShape) myContext = new ShapeBuild_ReShape;
1449   Standard_Real myTolerance = Precision::Confusion();
1450   TopoDS_Shape aResult = myContext->Apply(myShape);
1451
1452   TopTools_IndexedMapOfShape ChangedFaces;
1453
1454   // creating map of edge faces
1455   TopTools_IndexedDataMapOfShapeListOfShape aMapEdgeFaces;
1456   TopExp::MapShapesAndAncestors(myShape, TopAbs_EDGE, TopAbs_FACE, aMapEdgeFaces);
1457   
1458   // creating map of vertex edges
1459   TopTools_IndexedDataMapOfShapeListOfShape aMapEdgesVertex;
1460   TopExp::MapShapesAndAncestors(myShape, TopAbs_VERTEX, TopAbs_EDGE, aMapEdgesVertex);
1461
1462   //Handle(ShapeBuild_ReShape) aContext = new ShapeBuild_ReShape;
1463   TopoDS_Shape aRes = myShape;
1464   //aRes = aContext->Apply(aSolid);
1465   aRes = myContext->Apply(myShape);
1466   
1467   TopTools_MapOfShape SharedVert;
1468
1469   
1470   TopTools_IndexedMapOfShape anOldEdges;
1471   TopExp::MapShapes(myInitShape, TopAbs_EDGE, anOldEdges);
1472
1473   TopTools_DataMapOfShapeShape NewEdges2OldEdges;
1474   for (int i = 1; i <= anOldEdges.Extent(); i++)
1475   {
1476     TopoDS_Shape NewEdge = myContext->Apply(anOldEdges(i));
1477     if (!NewEdge.IsNull())
1478       NewEdges2OldEdges.Bind(NewEdge, anOldEdges(i));
1479   }
1480
1481   TopExp_Explorer exp;
1482   // processing separate wires
1483   for (exp.Init(aRes, TopAbs_WIRE, TopAbs_FACE); exp.More(); exp.Next()) 
1484   {
1485     TopTools_SequenceOfShape SeqEdges;
1486     TopExp_Explorer expE(exp.Current(), TopAbs_EDGE);
1487     for (; expE.More(); expE.Next())
1488       SeqEdges.Append(expE.Current());
1489     SharedVert.Clear();
1490     CheckSharedVertices(SeqEdges, aMapEdgesVertex, SharedVert); 
1491     MergeSeq(SeqEdges, Tol, myConcatBSplines, myContext, myOldShapes, SharedVert, NewEdges2OldEdges);
1492   }
1493
1494   // processing each face
1495   for (exp.Init(aRes, TopAbs_FACE); exp.More(); exp.Next()) {
1496     //TopoDS_Face aFace = TopoDS::Face(aContext->Apply(exp.Current().Oriented(TopAbs_FORWARD)));
1497     TopoDS_Face aFace = TopoDS::Face(myContext->Apply(exp.Current().Oriented(TopAbs_FORWARD)));
1498     TopTools_IndexedDataMapOfShapeListOfShape aMapFacesEdges;
1499     TopTools_SequenceOfShape aNonSharedEdges;
1500     for (TopExp_Explorer expe(aFace,TopAbs_EDGE); expe.More(); expe.Next()) {
1501       TopoDS_Edge edge = TopoDS::Edge(expe.Current());
1502       if (!aMapEdgeFaces.Contains(edge)) continue;
1503       const TopTools_ListOfShape& aList = aMapEdgeFaces.FindFromKey(edge);
1504       TopTools_ListIteratorOfListOfShape anIter(aList);
1505       Standard_Integer NbFacesPerEdge = aList.Extent();
1506       for ( ; anIter.More(); anIter.Next()) {
1507         TopoDS_Face face = TopoDS::Face(anIter.Value());
1508         TopoDS_Face face1 = TopoDS::Face(myContext->Apply(anIter.Value()));
1509         if (face1.IsSame(aFace) && NbFacesPerEdge != 1)
1510           continue;
1511         if (NbFacesPerEdge == 1)
1512           //store non-shared edges separately 
1513           aNonSharedEdges.Append(edge);
1514         else 
1515         {
1516           if (aMapFacesEdges.Contains(face))
1517             aMapFacesEdges.ChangeFromKey(face).Append(edge);
1518           else 
1519           {
1520             TopTools_ListOfShape ListEdges;
1521             ListEdges.Append(edge);
1522             aMapFacesEdges.Add(face,ListEdges);
1523           }
1524         }
1525       }
1526     }
1527       
1528     for (Standard_Integer i=1; i<=aMapFacesEdges.Extent(); i++)
1529     {
1530       const TopTools_ListOfShape& ListEdges = aMapFacesEdges.FindFromIndex(i);
1531       TopTools_SequenceOfShape SeqEdges;
1532       TopTools_ListIteratorOfListOfShape anIter(ListEdges);
1533       for ( ; anIter.More(); anIter.Next())
1534         SeqEdges.Append(anIter.Value());
1535       if (SeqEdges.Length()==1) 
1536         continue;  
1537
1538       SharedVert.Clear();
1539       CheckSharedVertices(SeqEdges, aMapEdgesVertex, SharedVert);
1540       //if (!SharedVert.IsEmpty()) 
1541       //  continue;
1542       if ( MergeSeq(SeqEdges,Tol,myConcatBSplines, myContext, myOldShapes, SharedVert, NewEdges2OldEdges) )
1543       {
1544         //for history
1545         /*
1546         for (j = 1; j <= SeqEdges.Length(); j++)
1547         {
1548           if (!myOldNewMap.IsBound(SeqEdges(j)))
1549           {
1550             TopTools_ListOfShape EmptyList;
1551             myOldNewMap.Bind(SeqEdges(j), EmptyList);
1552           }
1553           myOldNewMap(SeqEdges(j)).Clear();
1554           myOldNewMap(SeqEdges(j)).Append(E);
1555         }
1556         */
1557         /////////////
1558         
1559         TopoDS_Face tmpF = TopoDS::Face(exp.Current());
1560         if ( !ChangedFaces.Contains(tmpF) )
1561           ChangedFaces.Add(tmpF);
1562         tmpF = TopoDS::Face(aMapFacesEdges.FindKey(i));
1563         if ( !ChangedFaces.Contains(tmpF) )
1564           ChangedFaces.Add(tmpF);
1565       }
1566     }
1567     
1568     if ( aNonSharedEdges.Length() > 1 )
1569     {
1570       SharedVert.Clear();
1571       CheckSharedVertices(aNonSharedEdges, aMapEdgesVertex, SharedVert); 
1572       if ( MergeSeq(aNonSharedEdges, Tol, myConcatBSplines, myContext, myOldShapes, SharedVert, NewEdges2OldEdges) )
1573       {
1574         TopoDS_Face tmpF = TopoDS::Face(exp.Current());
1575         if ( !ChangedFaces.Contains(tmpF) )
1576           ChangedFaces.Add(tmpF);
1577       }
1578     }
1579
1580   } // end processing each face
1581
1582   // fix changed faces and replace them in the local context
1583   for (Standard_Integer i=1; i<=ChangedFaces.Extent(); i++) {
1584     //TopoDS_Face aFace = TopoDS::Face(aContext->Apply(ChangedFaces.FindKey(i)));
1585     TopoDS_Face aFace = TopoDS::Face(myContext->Apply(ChangedFaces.FindKey(i)));
1586     if (aFace.IsNull())
1587       continue;
1588     Handle(ShapeFix_Face) sff = new ShapeFix_Face(aFace);
1589     sff->SetContext(myContext);
1590     sff->SetPrecision(myTolerance);
1591     sff->SetMinTolerance(myTolerance);
1592     sff->SetMaxTolerance(Max(1.,myTolerance*1000.));
1593     sff->Perform();
1594     TopoDS_Shape aNewFace = sff->Face();
1595     //aContext->Replace(aFace,aNewFace);
1596     myContext->Replace(aFace,aNewFace);
1597     //for history
1598     /*
1599     if (!myOldNewMap.IsBound(aFace))
1600     {
1601       TopTools_ListOfShape EmptyList;
1602       myOldNewMap.Bind(aFace, EmptyList);
1603     }
1604     myOldNewMap(aFace).Clear();
1605     myOldNewMap(aFace).Append(aNewFace);
1606     */
1607     /////////////
1608   }
1609
1610   if (ChangedFaces.Extent() > 0) {
1611     // fix changed shell and replace it in the local context
1612     //TopoDS_Shape aRes1 = aContext->Apply(aRes);
1613     TopoDS_Shape aRes1 = myContext->Apply(aRes);
1614     TopExp_Explorer expsh;
1615     for (expsh.Init(aRes1, TopAbs_SHELL); expsh.More(); expsh.Next()) {
1616       TopoDS_Shell aShell = TopoDS::Shell(expsh.Current());
1617       Handle(ShapeFix_Shell) sfsh = new ShapeFix_Shell;
1618       sfsh->FixFaceOrientation(aShell);
1619       TopoDS_Shape aNewShell = sfsh->Shell();
1620       //aContext->Replace(aShell,aNewShell);
1621       myContext->Replace(aShell,aNewShell);
1622       //for history
1623       /*
1624       if (!myOldNewMap.IsBound(aShell))
1625       {
1626         TopTools_ListOfShape EmptyList;
1627         myOldNewMap.Bind(aShell, EmptyList);
1628       }
1629       myOldNewMap(aShell).Clear();
1630       myOldNewMap(aShell).Append(aNewShell);
1631       */
1632       /////////////
1633     }
1634     //TopoDS_Shape aRes2 = aContext->Apply(aRes1);
1635     TopoDS_Shape aRes2 = myContext->Apply(aRes1);
1636     myContext->Replace(myShape,aRes2);
1637     //for history
1638     /*
1639     if (!myOldNewMap.IsBound(aSolid))
1640     {
1641       TopTools_ListOfShape EmptyList;
1642       myOldNewMap.Bind(aSolid, EmptyList);
1643     }
1644     myOldNewMap(aSolid).Clear();
1645     myOldNewMap(aSolid).Append(aRes2);
1646     */
1647     /////////////
1648   }
1649
1650   myShape = myContext->Apply(myShape);
1651 }
1652
1653 //=======================================================================
1654 //function : UnifyFacesAndEdges
1655 //purpose  : 
1656 //=======================================================================
1657
1658 void ShapeUpgrade_UnifySameDomain::UnifyFacesAndEdges()
1659 {
1660   UnifyFaces();
1661   
1662   /*
1663   ShapeUpgrade_RemoveLocations RemLoc;
1664   RemLoc.Remove(myShape);
1665   myShape = RemLoc.GetResult();
1666   */
1667
1668   UnifyEdges();
1669 }
1670
1671 //=======================================================================
1672 //function : Build
1673 //purpose  : builds the resulting shape
1674 //======================================================================
1675 void ShapeUpgrade_UnifySameDomain::Build() 
1676 {
1677   if (myUnifyFaces && myUnifyEdges)
1678     UnifyFacesAndEdges();
1679
1680   else if (myUnifyEdges)
1681     UnifyEdges();
1682   else if (myUnifyFaces)
1683     UnifyFaces();
1684
1685   //Done();
1686 }
1687
1688 //=======================================================================
1689 //function : Shape
1690 //purpose  : give the resulting shape
1691 //=======================================================================
1692 const TopoDS_Shape& ShapeUpgrade_UnifySameDomain::Shape() const
1693 {
1694   return myShape;
1695 }
1696
1697 //=======================================================================
1698 //function : Generated
1699 //purpose  : returns the new shape from the old one
1700 //=======================================================================
1701 TopoDS_Shape ShapeUpgrade_UnifySameDomain::Generated(const TopoDS_Shape& aShape) const
1702 {
1703   TopoDS_Shape aNewShape = myContext->Apply(aShape);
1704
1705   if (aNewShape.IsNull())
1706     aNewShape = myContext->Apply(myOldShapes(aShape));
1707   
1708   return aNewShape;
1709 }