60ef5a3f01b06b2f79d88d25ce5ca3bced6d9fb8
[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 //=======================================================================
530 //function : MergeSubSeq
531 //purpose  : Merges a sequence of edges into one edge if possible
532 //=======================================================================
533
534 static Standard_Boolean MergeSubSeq(const TopTools_SequenceOfShape& aChain, TopoDS_Edge& OutEdge, double Tol, Standard_Boolean ConcatBSplines) 
535 {
536   ShapeAnalysis_Edge sae;
537   BRep_Builder B;
538   // union edges in chain
539   int j;
540   Standard_Real fp1,lp1,fp2,lp2;
541   Standard_Boolean IsUnionOfLinesPossible = Standard_True;
542   Standard_Boolean IsUnionOfCirclesPossible = Standard_True;
543   Handle(Geom_Curve) c3d1, c3d2;
544   for(j=1; j<aChain.Length(); j++) 
545   {
546     TopoDS_Edge edge1 = TopoDS::Edge(aChain.Value(j));
547     c3d1 = BRep_Tool::Curve(edge1,fp1,lp1);
548
549     TopoDS_Edge edge2 = TopoDS::Edge(aChain.Value(j+1));
550     c3d2 = BRep_Tool::Curve(edge2,fp2,lp2);
551
552     if(c3d1.IsNull() || c3d2.IsNull()) 
553       return Standard_False;
554
555     while(c3d1->IsKind(STANDARD_TYPE(Geom_TrimmedCurve))) {
556       Handle(Geom_TrimmedCurve) tc =
557         Handle(Geom_TrimmedCurve)::DownCast(c3d1);
558       c3d1 = tc->BasisCurve();
559     }
560     while(c3d2->IsKind(STANDARD_TYPE(Geom_TrimmedCurve))) {
561       Handle(Geom_TrimmedCurve) tc =
562         Handle(Geom_TrimmedCurve)::DownCast(c3d2);
563       c3d2 = tc->BasisCurve();
564     }
565     if( c3d1->IsKind(STANDARD_TYPE(Geom_Line)) && c3d2->IsKind(STANDARD_TYPE(Geom_Line)) ) {
566       Handle(Geom_Line) L1 = Handle(Geom_Line)::DownCast(c3d1);
567       Handle(Geom_Line) L2 = Handle(Geom_Line)::DownCast(c3d2);
568       gp_Dir Dir1 = L1->Position().Direction();
569       gp_Dir Dir2 = L2->Position().Direction();
570       if(!Dir1.IsParallel(Dir2,Tol))  
571         IsUnionOfLinesPossible = Standard_False;
572     }
573     else
574       IsUnionOfLinesPossible = Standard_False;
575     if( c3d1->IsKind(STANDARD_TYPE(Geom_Circle)) && c3d2->IsKind(STANDARD_TYPE(Geom_Circle)) ) {
576       Handle(Geom_Circle) C1 = Handle(Geom_Circle)::DownCast(c3d1);
577       Handle(Geom_Circle) C2 = Handle(Geom_Circle)::DownCast(c3d2);
578       gp_Pnt P01 = C1->Location();
579       gp_Pnt P02 = C2->Location();
580       if (P01.Distance(P02) > Precision::Confusion())
581         IsUnionOfCirclesPossible = Standard_False;
582     }
583     else
584       IsUnionOfCirclesPossible = Standard_False;
585   }
586   if (IsUnionOfLinesPossible && IsUnionOfCirclesPossible)
587     return Standard_False;
588
589   //union of lines is possible
590   if (IsUnionOfLinesPossible)
591   {
592     TopoDS_Vertex V1 = sae.FirstVertex(TopoDS::Edge(aChain.First()));
593     gp_Pnt PV1 = BRep_Tool::Pnt(V1);
594     TopoDS_Vertex V2 = sae.LastVertex(TopoDS::Edge(aChain.Last()));
595     gp_Pnt PV2 = BRep_Tool::Pnt(V2);
596     gp_Vec Vec(PV1, PV2);
597     Handle(Geom_Line) L = new Geom_Line(gp_Ax1(PV1,Vec));
598     Standard_Real dist = PV1.Distance(PV2);
599     Handle(Geom_TrimmedCurve) tc = new Geom_TrimmedCurve(L,0.0,dist);
600     TopoDS_Edge E;
601     B.MakeEdge (E, tc ,Precision::Confusion());
602     B.Add (E,V1);  B.Add (E,V2);
603     B.UpdateVertex(V1, 0., E, 0.);
604     B.UpdateVertex(V2, dist, E, 0.);
605     OutEdge = E;
606     return Standard_True;
607   }
608
609   if (IsUnionOfCirclesPossible)
610   {
611     double f,l;
612     TopoDS_Edge FE = TopoDS::Edge(aChain.First());
613     Handle(Geom_Curve) c3d = BRep_Tool::Curve(FE,f,l);
614
615     while(c3d->IsKind(STANDARD_TYPE(Geom_TrimmedCurve))) {
616       Handle(Geom_TrimmedCurve) tc =
617         Handle(Geom_TrimmedCurve)::DownCast(c3d);
618       c3d = tc->BasisCurve();
619     }
620     Handle(Geom_Circle) Cir = Handle(Geom_Circle)::DownCast(c3d);
621
622     TopoDS_Vertex V1 = sae.FirstVertex(FE);
623     TopoDS_Vertex V2 = sae.LastVertex(TopoDS::Edge(aChain.Last()));
624     TopoDS_Edge E;
625     if (V1.IsSame(V2)) {
626       // closed chain
627       BRepAdaptor_Curve adef(FE);
628       Handle(Geom_Circle) Cir1;
629       double FP, LP;
630       if ( FE.Orientation() == TopAbs_FORWARD)
631       {
632         FP = adef.FirstParameter();
633         LP = adef.LastParameter();
634       }
635       else
636       {
637         FP = adef.LastParameter();
638         LP = adef.FirstParameter();
639       }
640       if (Abs(FP) < Precision::PConfusion())
641       {
642         B.MakeEdge (E,Cir, Precision::Confusion());
643         B.Add(E,V1);
644         B.Add(E,V2);
645         E.Orientation(FE.Orientation());
646       }
647       else
648       {
649         GC_MakeCircle MC1 (adef.Value(FP), adef.Value((FP + LP) * 0.5), adef.Value(LP));
650         if (MC1.IsDone())
651           Cir1 = MC1.Value();
652         else
653           return Standard_False;
654         B.MakeEdge (E, Cir1, Precision::Confusion());
655         B.Add(E,V1);
656         B.Add(E,V2);
657       }
658     }
659     else {
660       gp_Pnt PV1 = BRep_Tool::Pnt(V1);
661       gp_Pnt PV2 = BRep_Tool::Pnt(V2);
662       TopoDS_Vertex VM = sae.LastVertex(FE);
663       gp_Pnt PVM = BRep_Tool::Pnt(VM);
664       GC_MakeCircle MC (PV1,PVM,PV2);
665       Handle(Geom_Circle) C = MC.Value();
666       gp_Pnt P0 = C->Location();
667       gp_Dir D1(gp_Vec(P0,PV1));
668       gp_Dir D2(gp_Vec(P0,PV2));
669       Standard_Real fpar = C->XAxis().Direction().Angle(D1);
670       if(fabs(fpar)>Precision::Confusion()) {
671         // check orientation
672         gp_Dir ND =  C->XAxis().Direction().Crossed(D1);
673         if(ND.IsOpposite(C->Axis().Direction(),Precision::Confusion())) {
674           fpar = -fpar;
675         }
676       }
677       Standard_Real lpar = C->XAxis().Direction().Angle(D2);
678       if(fabs(lpar)>Precision::Confusion()) {
679         // check orientation
680         gp_Dir ND =  C->XAxis().Direction().Crossed(D2);
681         if(ND.IsOpposite(C->Axis().Direction(),Precision::Confusion())) {
682           lpar = -lpar;
683         }
684       }
685       if (lpar < fpar) lpar += 2*M_PI;
686       Handle(Geom_TrimmedCurve) tc = new Geom_TrimmedCurve(C,fpar,lpar);
687       B.MakeEdge (E,tc,Precision::Confusion());
688       B.Add(E,V1);
689       B.Add(E,V2);
690       B.UpdateVertex(V1, fpar, E, 0.);
691       B.UpdateVertex(V2, lpar, E, 0.);
692     }
693     OutEdge = E;
694     return Standard_True;
695   }
696   if (aChain.Length() > 1 && ConcatBSplines) {
697     // second step: union edges with various curves
698     // skl for bug 0020052 from Mantis: perform such unions
699     // only if curves are bspline or bezier
700
701     TopoDS_Vertex VF = sae.FirstVertex(TopoDS::Edge(aChain.First()));
702     TopoDS_Vertex VL = sae.LastVertex(TopoDS::Edge(aChain.Last()));
703     Standard_Boolean NeedUnion = Standard_True;
704     for(j=1; j<=aChain.Length(); j++) {
705       TopoDS_Edge edge = TopoDS::Edge(aChain.Value(j));
706       TopLoc_Location Loc;
707       Handle(Geom_Curve) c3d = BRep_Tool::Curve(edge,Loc,fp1,lp1);
708       if(c3d.IsNull()) continue;
709       while(c3d->IsKind(STANDARD_TYPE(Geom_TrimmedCurve))) {
710         Handle(Geom_TrimmedCurve) tc =
711           Handle(Geom_TrimmedCurve)::DownCast(c3d);
712         c3d = tc->BasisCurve();
713       }
714       if( ( c3d->IsKind(STANDARD_TYPE(Geom_BSplineCurve)) ||
715             c3d->IsKind(STANDARD_TYPE(Geom_BezierCurve)) ) ) continue;
716       NeedUnion = Standard_False;
717       break;
718     }
719     if(NeedUnion) {
720 #ifdef OCCT_DEBUG
721       cout<<"can not make analitical union => make approximation"<<endl;
722 #endif
723       TopoDS_Edge E = GlueEdgesWithPCurves(aChain, VF, VL);
724       OutEdge = E;
725       return Standard_True;
726     }
727     else {
728 #ifdef OCCT_DEBUG
729       cout<<"can not make approximation for such types of curves"<<endl;
730 #endif
731       return Standard_False;
732     }
733   }
734   return Standard_False;
735 }
736
737 //=======================================================================
738 //function : IsMergingPossible
739 //purpose  : Checks if merging of two edges is possible
740 //=======================================================================
741
742 static Standard_Boolean IsMergingPossible(const TopoDS_Edge& edge1, const TopoDS_Edge& edge2, 
743                                           double Tol, const TopTools_MapOfShape& DegEdgeVrt)
744 {
745   TopoDS_Vertex CV = TopExp::LastVertex(edge1, Standard_True);
746   if (CV.IsNull() || DegEdgeVrt.Contains(CV))
747     return Standard_False;
748
749   BRepAdaptor_Curve ade1(edge1);
750   BRepAdaptor_Curve ade2(edge2);
751
752   GeomAbs_CurveType t1 = ade1.GetType();
753   GeomAbs_CurveType t2 = ade2.GetType();
754
755   if( t1 == GeomAbs_Circle && t2 == GeomAbs_Circle)
756   {
757     if (ade1.Circle().Location().Distance(ade2.Circle().Location()) > Precision::Confusion())
758       return Standard_False;
759   }
760
761   if( ( (t1 != GeomAbs_BezierCurve && t1 != GeomAbs_BSplineCurve) ||
762       (t2 != GeomAbs_BezierCurve && t2 != GeomAbs_BSplineCurve)) && t1 != t2)
763     return Standard_False;
764
765   gp_Vec Diff1, Diff2;
766   gp_Pnt P1, P2;
767   if (edge1.Orientation() == TopAbs_FORWARD)
768     ade1.D1(ade1.LastParameter(), P1, Diff1);
769   else
770   {
771     ade1.D1(ade1.FirstParameter(), P1, Diff1);
772     Diff1 = -Diff1;
773   }
774
775   if (edge2.Orientation() == TopAbs_FORWARD)
776     ade2.D1(ade2.FirstParameter(), P2, Diff2);
777   else
778   {
779     ade2.D1(ade2.LastParameter(), P2, Diff2);
780     Diff2 = -Diff2;
781   }
782
783   if (Diff1.Angle(Diff2) > Tol)
784     return Standard_False;
785
786   return Standard_True;
787 }
788
789 //=======================================================================
790 //function : GenerateSubSeq
791 //purpose  : Generates sub-sequences of edges from sequence of edges
792 //Edges from each subsequences can be merged into the one edge  
793 //=======================================================================
794
795 static void GenerateSubSeq (const TopTools_SequenceOfShape& anInpEdgeSeq,
796                             NCollection_Sequence<SubSequenceOfEdges>& SeqOfSubSeqOfEdges,
797                             Standard_Boolean IsClosed, double Tol, const TopTools_MapOfShape& DegEdgeVrt )
798 {
799   Standard_Boolean isOk = Standard_False;
800   TopoDS_Edge edge1, edge2;
801
802   SubSequenceOfEdges SubSeq;
803   SubSeq.SeqsEdges.Append(TopoDS::Edge(anInpEdgeSeq(1)));
804   SeqOfSubSeqOfEdges.Append(SubSeq);
805
806   for (int i = 1; i < anInpEdgeSeq.Length(); i++)
807   {
808     edge1 = TopoDS::Edge(anInpEdgeSeq(i));
809     edge2 = TopoDS::Edge(anInpEdgeSeq(i+1));
810     isOk = IsMergingPossible(edge1, edge2, Tol, DegEdgeVrt);
811     if (!isOk)
812     {
813       SubSequenceOfEdges SubSeq;
814       SubSeq.SeqsEdges.Append(edge2);
815       SeqOfSubSeqOfEdges.Append(SubSeq);
816     }
817     else
818       SeqOfSubSeqOfEdges.ChangeLast().SeqsEdges.Append(edge2);
819   }
820   /// check first and last chain segments
821   if (IsClosed && SeqOfSubSeqOfEdges.Length() > 1)
822   {
823     edge1 = TopoDS::Edge(anInpEdgeSeq.Last());
824     edge2 = TopoDS::Edge(anInpEdgeSeq.First());
825     if (IsMergingPossible(edge1, edge2, Tol, DegEdgeVrt))
826     {
827       SeqOfSubSeqOfEdges.ChangeLast().SeqsEdges.Append(SeqOfSubSeqOfEdges.ChangeFirst().SeqsEdges);
828       SeqOfSubSeqOfEdges.Remove(1);
829     }
830   }
831 }
832
833
834 //=======================================================================
835 //function : MergeEdges
836 //purpose  : auxilary
837 //=======================================================================
838 static Standard_Boolean MergeEdges(const TopTools_SequenceOfShape& SeqEdges,
839                                    const Standard_Real Tol,
840                                    const Standard_Boolean ConcatBSplines,
841                                    NCollection_Sequence<SubSequenceOfEdges>& SeqOfSubSeqOfEdges,
842                                    const TopTools_MapOfShape& NonMergVrt )
843 {
844   // make chain for union
845   //BRep_Builder B;
846   ShapeAnalysis_Edge sae;
847   TopoDS_Edge FirstE = TopoDS::Edge(SeqEdges.Value(1));
848   TopoDS_Edge LastE = FirstE;
849   TopoDS_Vertex VF = sae.FirstVertex(FirstE);
850   TopoDS_Vertex VL = sae.LastVertex(LastE);
851   TopTools_SequenceOfShape aChain;
852   aChain.Append(FirstE);
853   TColStd_MapOfInteger IndUsedEdges;
854   IndUsedEdges.Add(1);
855   Standard_Integer j;
856   TopTools_MapOfShape VerticesToAvoid;
857   TopTools_SequenceOfShape SeqEdges1;
858   for (j = 1; j <= SeqEdges.Length(); j++)
859   {
860     TopoDS_Edge anEdge = TopoDS::Edge(SeqEdges(j));
861     if (BRep_Tool::Degenerated(anEdge))
862     {
863       TopoDS_Vertex V1, V2;
864       TopExp::Vertices(anEdge, V1, V2);
865       VerticesToAvoid.Add(V1);
866       VerticesToAvoid.Add(V2);
867       continue;
868     }
869     SeqEdges1.Append(anEdge);
870   }
871
872   for(j=2; j<=SeqEdges1.Length(); j++) {
873     for(Standard_Integer k=2; k<=SeqEdges1.Length(); k++) {
874       if(IndUsedEdges.Contains(k)) continue;
875       TopoDS_Edge edge = TopoDS::Edge(SeqEdges1.Value(k));
876       TopoDS_Vertex VF2 = sae.FirstVertex(edge);
877       TopoDS_Vertex VL2 = sae.LastVertex(edge);
878       if(VF2.IsSame(VL)) {
879         aChain.Append(edge);
880         LastE = edge;
881         VL = sae.LastVertex(LastE);
882         IndUsedEdges.Add(k);
883       }
884       else if(VL2.IsSame(VF)) {
885         aChain.Prepend(edge);
886         FirstE = edge;
887         VF = sae.FirstVertex(FirstE);
888         IndUsedEdges.Add(k);
889       }
890     }
891   }
892
893   Standard_Boolean IsClosed = Standard_False;
894   if (VF.IsSame ( VL ))
895     IsClosed = Standard_True;
896
897   VerticesToAvoid.Unite(NonMergVrt);
898   GenerateSubSeq(aChain, SeqOfSubSeqOfEdges, IsClosed, Tol, VerticesToAvoid);
899
900   for (int i = 1; i <= SeqOfSubSeqOfEdges.Length(); i++)
901   {
902     TopoDS_Edge UE;
903     if (SeqOfSubSeqOfEdges(i).SeqsEdges.Length() < 2)
904       continue;
905     if (MergeSubSeq(SeqOfSubSeqOfEdges(i).SeqsEdges, UE, Tol, ConcatBSplines))
906       SeqOfSubSeqOfEdges(i).UnionEdges = UE;
907   }
908   return Standard_True;
909 }
910
911 //=======================================================================
912 //function : MergeSeq
913 //purpose  : Tries to unify the sequence of edges with the set of another edges 
914 //which lies on the same geometry
915 //=======================================================================
916
917 static Standard_Boolean MergeSeq (const TopTools_SequenceOfShape& SeqEdges,
918                                   const Standard_Real Tol,
919                                   const Standard_Boolean ConcatBSplines,
920                                   Handle(ShapeBuild_ReShape)& theContext,
921                                   TopTools_DataMapOfShapeShape& theOldShapes,
922                                   const TopTools_MapOfShape& nonMergVert,
923                                   const TopTools_DataMapOfShapeShape& NewEdges2OldEdges)
924
925   NCollection_Sequence<SubSequenceOfEdges> SeqOfSubsSeqOfEdges;
926   int k = 1;
927   if ( MergeEdges(SeqEdges, Tol, ConcatBSplines, SeqOfSubsSeqOfEdges, nonMergVert) )
928   {
929     for (Standard_Integer i = 1; i <= SeqOfSubsSeqOfEdges.Length(); i++ )
930     {
931       if (SeqOfSubsSeqOfEdges(i).UnionEdges.IsNull())
932         continue;
933       theContext->Replace(SeqOfSubsSeqOfEdges(i).SeqsEdges(1), SeqOfSubsSeqOfEdges(i).UnionEdges);
934       k++;
935       for (Standard_Integer j = 2; j <= SeqOfSubsSeqOfEdges(i).SeqsEdges.Length(); j++)
936       {
937         TopoDS_Shape OldEdge = NewEdges2OldEdges(SeqOfSubsSeqOfEdges(i).SeqsEdges(j));
938         theOldShapes.Bind(OldEdge, SeqOfSubsSeqOfEdges(i).UnionEdges);
939         theContext->Remove(SeqOfSubsSeqOfEdges(i).SeqsEdges(j));
940       }
941     }
942     return Standard_True;
943   }
944   else
945     return Standard_False;
946 }
947
948 //=======================================================================
949 //function : CheckSharedVertices
950 //purpose  : Checks the sequence of edges on the presence of shared vertex 
951 //=======================================================================
952
953 static void CheckSharedVertices(const TopTools_SequenceOfShape& theSeqEdges, 
954                                 const TopTools_IndexedDataMapOfShapeListOfShape& theMapEdgesVertex,
955                                 TopTools_MapOfShape& theShareVertMap)
956 {
957   ShapeAnalysis_Edge sae;
958   TopTools_SequenceOfShape SeqVertexes;
959   TopTools_MapOfShape MapVertexes;
960   for (Standard_Integer k = 1; k <= theSeqEdges.Length(); k++ )
961   {
962     TopoDS_Vertex aV1 = sae.FirstVertex(TopoDS::Edge(theSeqEdges(k)));
963     TopoDS_Vertex aV2 = sae.LastVertex(TopoDS::Edge(theSeqEdges(k)));
964     if (!MapVertexes.Add(aV1))
965       SeqVertexes.Append(aV1);
966     if (!MapVertexes.Add(aV2))
967       SeqVertexes.Append(aV2);
968   }
969
970   for (Standard_Integer k = 1; k <= SeqVertexes.Length()/* && !IsSharedVertexPresent*/; k++ )
971   {
972     const TopTools_ListOfShape& ListEdgesV1 = theMapEdgesVertex.FindFromKey(SeqVertexes(k));
973     TopTools_MapOfShape aMapOfEdges;
974     TopTools_ListIteratorOfListOfShape iter(ListEdgesV1);
975     for (; iter.More(); iter.Next())
976       aMapOfEdges.Add(iter.Value());
977     if (aMapOfEdges.Extent() > 2)
978       theShareVertMap.Add(SeqVertexes(k));
979   }
980   //return theShareVertMap.IsEmpty() ? false : true;
981 }
982
983 //=======================================================================
984 //function : ShapeUpgrade_UnifySameDomain
985 //purpose  : Constructor
986 //=======================================================================
987
988 ShapeUpgrade_UnifySameDomain::ShapeUpgrade_UnifySameDomain()
989 {
990   myUnifyEdges = Standard_True;
991   myUnifyFaces = Standard_True;
992   myConcatBSplines = Standard_False;
993
994   myContext = new ShapeBuild_ReShape;
995 }
996
997 //=======================================================================
998 //function : ShapeUpgrade_UnifySameDomain
999 //purpose  : Constructor
1000 //=======================================================================
1001
1002 ShapeUpgrade_UnifySameDomain::ShapeUpgrade_UnifySameDomain(const TopoDS_Shape& aShape,
1003                                                            const Standard_Boolean UnifyEdges,
1004                                                            const Standard_Boolean UnifyFaces,
1005                                                            const Standard_Boolean ConcatBSplines)
1006 {
1007   myInitShape = aShape;
1008   myShape = aShape;
1009   myUnifyEdges = UnifyEdges;
1010   myUnifyFaces = UnifyFaces;
1011   myConcatBSplines = ConcatBSplines;
1012
1013   myContext = new ShapeBuild_ReShape;
1014 }
1015
1016 //=======================================================================
1017 //function : Initialize
1018 //purpose  : 
1019 //=======================================================================
1020
1021 void ShapeUpgrade_UnifySameDomain::Initialize(const TopoDS_Shape& aShape,
1022                                               const Standard_Boolean UnifyEdges,
1023                                               const Standard_Boolean UnifyFaces,
1024                                               const Standard_Boolean ConcatBSplines)
1025 {
1026   myInitShape = aShape;
1027   myShape = aShape;
1028   myUnifyEdges = UnifyEdges;
1029   myUnifyFaces = UnifyFaces;
1030   myConcatBSplines = ConcatBSplines;
1031
1032   myContext->Clear();
1033   myOldShapes.Clear();
1034   //myGenerated.Clear();
1035 }
1036
1037 //=======================================================================
1038 //function : putIntWires
1039 //purpose  : Add internal wires that are classified inside the face as a subshape,
1040 //           and remove them from the sequence
1041 //=======================================================================
1042 static void putIntWires(TopoDS_Shape& theFace, TopTools_SequenceOfShape& theWires)
1043 {
1044   TopoDS_Face& aFace = TopoDS::Face(theFace);
1045   for (Standard_Integer i=1; i <= theWires.Length(); i++)
1046   {
1047     TopoDS_Shape aWire = theWires(i);
1048     gp_Pnt2d aP2d;
1049     Standard_Boolean isP2d = Standard_False;
1050     for (TopoDS_Iterator it(aWire); it.More() && !isP2d; it.Next())
1051     {
1052       const TopoDS_Edge& anEdge = TopoDS::Edge(it.Value());
1053       Standard_Real aFirst, aLast;
1054       Handle(Geom2d_Curve) aC2d = BRep_Tool::CurveOnSurface(anEdge, aFace, aFirst, aLast);
1055       aC2d->D0((aFirst + aLast) * 0.5, aP2d);
1056       isP2d = Standard_True;
1057     }
1058     BRepClass_FaceClassifier aClass(aFace, aP2d, Precision::PConfusion());
1059     if (aClass.State() == TopAbs_IN)
1060     {
1061       BRep_Builder().Add(aFace, aWire);
1062       theWires.Remove(i);
1063       i--;
1064     }
1065   }
1066 }
1067
1068 //=======================================================================
1069 //function : UnifyFaces
1070 //purpose  : 
1071 //=======================================================================
1072
1073 void ShapeUpgrade_UnifySameDomain::UnifyFaces()
1074 {
1075   //Handle(ShapeBuild_ReShape) myContext = new ShapeBuild_ReShape;
1076   TopoDS_Shape aResShape = myContext->Apply(myShape);
1077
1078   // processing each shell
1079   TopExp_Explorer exps;
1080   for (exps.Init(myShape, TopAbs_SHELL); exps.More(); exps.Next()) {
1081     TopoDS_Shell aShell = TopoDS::Shell(exps.Current());
1082
1083     // creating map of edge faces
1084     TopTools_IndexedDataMapOfShapeListOfShape aMapEdgeFaces;
1085     TopExp::MapShapesAndAncestors(aShell, TopAbs_EDGE, TopAbs_FACE, aMapEdgeFaces);
1086
1087     // map of processed shapes
1088     TopTools_MapOfShape aProcessed;
1089
1090     //Handle(ShapeBuild_ReShape) aContext = new ShapeBuild_ReShape;
1091
1092     Standard_Integer NbModif = 0;
1093     Standard_Boolean hasFailed = Standard_False;
1094     Standard_Real tol = Precision::Confusion();
1095
1096     // count faces
1097     Standard_Integer nbf = 0;
1098     TopExp_Explorer exp;
1099     TopTools_MapOfShape mapF;
1100     for (exp.Init(aShell, TopAbs_FACE); exp.More(); exp.Next()) {
1101       if (mapF.Add(exp.Current()))
1102         nbf++;
1103     }
1104
1105     // processing each face
1106     mapF.Clear();
1107     for (exp.Init(aShell, TopAbs_FACE); exp.More(); exp.Next()) {
1108       TopoDS_Face aFace = TopoDS::Face(exp.Current().Oriented(TopAbs_FORWARD));
1109
1110       if (aProcessed.Contains(aFace))
1111         continue;
1112
1113       Standard_Integer dummy;
1114       TopTools_SequenceOfShape edges;
1115       AddOrdinaryEdges(edges,aFace,dummy);
1116
1117       TopTools_SequenceOfShape faces;
1118       faces.Append(aFace);
1119
1120       //surface and location to construct result
1121       TopLoc_Location aBaseLocation;
1122       Handle(Geom_Surface) aBaseSurface = BRep_Tool::Surface(aFace,aBaseLocation);
1123       aBaseSurface = ClearRts(aBaseSurface);
1124
1125       // find adjacent faces to union
1126       Standard_Integer i;
1127       for (i = 1; i <= edges.Length(); i++) {
1128         TopoDS_Edge edge = TopoDS::Edge(edges(i));
1129         if (BRep_Tool::Degenerated(edge))
1130           continue;
1131
1132         const TopTools_ListOfShape& aList = aMapEdgeFaces.FindFromKey(edge);
1133         TopTools_ListIteratorOfListOfShape anIter(aList);
1134         for (; anIter.More(); anIter.Next()) {
1135           TopoDS_Face anCheckedFace = TopoDS::Face(anIter.Value().Oriented(TopAbs_FORWARD));
1136           if (anCheckedFace.IsSame(aFace))
1137             continue;
1138
1139           if (aProcessed.Contains(anCheckedFace))
1140             continue;
1141
1142           if (IsSameDomain(aFace,anCheckedFace)) {
1143
1144             if (aList.Extent() != 2) {
1145               // non mainfold case is not processed
1146               continue;
1147             }
1148
1149             // replacing pcurves
1150             TopoDS_Face aMockUpFace;
1151             BRep_Builder B;
1152             B.MakeFace(aMockUpFace,aBaseSurface,aBaseLocation,0.);
1153             MovePCurves(aMockUpFace,anCheckedFace);
1154
1155             if (AddOrdinaryEdges(edges,aMockUpFace,dummy)) {
1156               // sequence edges is modified
1157               i = dummy;
1158             }
1159
1160             faces.Append(anCheckedFace);
1161             aProcessed.Add(anCheckedFace);
1162             break;
1163           }
1164         }
1165       }
1166
1167       // all faces collected in the sequence. Perform union of faces
1168       if (faces.Length() > 1) {
1169         NbModif++;
1170         TopoDS_Face aResult;
1171         BRep_Builder B;
1172         B.MakeFace(aResult,aBaseSurface,aBaseLocation,0);
1173         Standard_Integer nbWires = 0;
1174
1175         // connecting wires
1176         while (edges.Length()>0) {
1177
1178           Standard_Boolean isEdge3d = Standard_False;
1179           nbWires++;
1180           TopTools_MapOfShape aVertices;
1181           TopoDS_Wire aWire;
1182           B.MakeWire(aWire);
1183
1184           TopoDS_Edge anEdge = TopoDS::Edge(edges(1));
1185           edges.Remove(1);
1186           // collect internal edges in separate wires
1187           Standard_Boolean isInternal = (anEdge.Orientation() == TopAbs_INTERNAL);
1188
1189           isEdge3d |= !BRep_Tool::Degenerated(anEdge);
1190           B.Add(aWire,anEdge);
1191           TopoDS_Vertex V1,V2;
1192           TopExp::Vertices(anEdge,V1,V2);
1193           aVertices.Add(V1);
1194           aVertices.Add(V2);
1195
1196           Standard_Boolean isNewFound = Standard_False;
1197           do {
1198             isNewFound = Standard_False;
1199             for(Standard_Integer j = 1; j <= edges.Length(); j++) {
1200               anEdge = TopoDS::Edge(edges(j));
1201               // check if the current edge orientation corresponds to the first one
1202               Standard_Boolean isCurrInternal = (anEdge.Orientation() == TopAbs_INTERNAL);
1203               if (isCurrInternal != isInternal)
1204                 continue;
1205               TopExp::Vertices(anEdge,V1,V2);
1206               if(aVertices.Contains(V1) || aVertices.Contains(V2)) {
1207                 isEdge3d |= !BRep_Tool::Degenerated(anEdge);
1208                 aVertices.Add(V1);
1209                 aVertices.Add(V2);
1210                 B.Add(aWire,anEdge);
1211                 edges.Remove(j);
1212                 j--;
1213                 isNewFound = Standard_True;
1214               }
1215             }
1216           } while (isNewFound);
1217
1218           // sorting any type of edges
1219           aWire.Closed (BRep_Tool::IsClosed (aWire));
1220           aWire = TopoDS::Wire(myContext->Apply(aWire));
1221
1222           TopoDS_Face tmpF = TopoDS::Face(myContext->Apply(faces(1).Oriented(TopAbs_FORWARD)));
1223           Handle(ShapeFix_Wire) sfw = new ShapeFix_Wire(aWire,tmpF,Precision::Confusion());
1224           sfw->FixReorder();
1225           Standard_Boolean isDegRemoved = Standard_False;
1226           if(!sfw->StatusReorder ( ShapeExtend_FAIL )) {
1227             // clear degenerated edges if at least one with 3d curve exist
1228             if(isEdge3d) {
1229               Handle(ShapeExtend_WireData) sewd = sfw->WireData();
1230               for(Standard_Integer j = 1; j<=sewd->NbEdges();j++) {
1231                 TopoDS_Edge E = sewd->Edge(j);
1232                 if(BRep_Tool::Degenerated(E)) {
1233                   sewd->Remove(j);
1234                   isDegRemoved = Standard_True;
1235                   j--;
1236                 }
1237               }
1238             }
1239             sfw->FixShifted();
1240             if(isDegRemoved)
1241               sfw->FixDegenerated();
1242           }
1243           TopoDS_Wire aWireFixed = sfw->Wire();
1244           //aContext->Replace(aWire,aWireFixed);
1245           myContext->Replace(aWire,aWireFixed);
1246           //for history
1247           /*
1248           if (!myOldNewMap.IsBound(aWire))
1249           {
1250             TopTools_ListOfShape EmptyList;
1251             myOldNewMap.Bind(aWire, EmptyList);
1252           }
1253           myOldNewMap(aWire).Clear();
1254           myOldNewMap(aWire).Append(aWireFixed);
1255           */
1256           /////////////
1257           
1258           // add resulting wire
1259           if(isEdge3d) {
1260             B.Add(aResult,aWireFixed);
1261           }
1262           else  {
1263             // sorting edges
1264             Handle(ShapeExtend_WireData) sbwd = sfw->WireData();
1265             Standard_Integer nbEdges = sbwd->NbEdges();
1266             // sort degenerated edges and create one edge instead of several ones
1267             ShapeAnalysis_WireOrder sawo(Standard_False, 0);
1268             ShapeAnalysis_Edge sae;
1269             Standard_Integer aLastEdge = nbEdges;
1270             for(Standard_Integer j = 1; j <= nbEdges; j++) {
1271               Standard_Real f,l;
1272               //smh protection on NULL pcurve
1273               Handle(Geom2d_Curve) c2d;
1274               if(!sae.PCurve(sbwd->Edge(j),tmpF,c2d,f,l)) {
1275                 aLastEdge--;
1276                 continue;
1277               }
1278               sawo.Add(c2d->Value(f).XY(),c2d->Value(l).XY());
1279             }
1280             sawo.Perform();
1281
1282             // constructind one degenerative edge
1283             gp_XY aStart, anEnd, tmp;
1284             Standard_Integer nbFirst = sawo.Ordered(1);
1285             TopoDS_Edge anOrigE = TopoDS::Edge(sbwd->Edge(nbFirst).Oriented(TopAbs_FORWARD));
1286             ShapeBuild_Edge sbe;
1287             TopoDS_Vertex aDummyV;
1288             TopoDS_Edge E = sbe.CopyReplaceVertices(anOrigE,aDummyV,aDummyV);
1289             sawo.XY(nbFirst,aStart,tmp);
1290             sawo.XY(sawo.Ordered(aLastEdge),tmp,anEnd);
1291
1292             gp_XY aVec = anEnd-aStart;
1293             Handle(Geom2d_Line) aLine = new Geom2d_Line(aStart,gp_Dir2d(anEnd-aStart));
1294
1295             B.UpdateEdge(E,aLine,tmpF,0.);
1296             B.Range(E,tmpF,0.,aVec.Modulus());
1297             Handle(Geom_Curve) C3d;
1298             B.UpdateEdge(E,C3d,0.);
1299             B.Degenerated(E,Standard_True);
1300             TopoDS_Wire aW;
1301             B.MakeWire(aW);
1302             B.Add(aW,E);
1303             aW.Closed (Standard_True);
1304             B.Add(aResult,aW);
1305           }
1306         }
1307
1308         // perform substitution of face
1309         //aContext->Replace(aContext->Apply(aFace),aResult);
1310         myContext->Replace(myContext->Apply(aFace),aResult);
1311         //for history
1312         /*
1313         if (!myOldNewMap.IsBound(aFace))
1314         {
1315           TopTools_ListOfShape EmptyList;
1316           myOldNewMap.Bind(aFace, EmptyList);
1317         }
1318         myOldNewMap(aFace).Clear();
1319         myOldNewMap(aFace).Append(aResult);
1320         */
1321         /////////////
1322
1323         ShapeFix_Face sff (aResult);
1324         //Intializing by tolerances
1325         sff.SetPrecision(Precision::Confusion());
1326         sff.SetMinTolerance(tol);
1327         sff.SetMaxTolerance(1.);
1328         //Setting modes
1329         sff.FixOrientationMode() = 0;
1330         //sff.FixWireMode() = 0;
1331         //sff.SetContext(aContext);
1332         sff.SetContext(myContext);
1333         // Applying the fixes
1334         sff.Perform();
1335         if(sff.Status(ShapeExtend_FAIL))
1336         hasFailed = Standard_True;
1337
1338         // breaking down to several faces
1339         //TopoDS_Shape theResult = aContext->Apply(aResult);
1340         TopoDS_Shape theResult = myContext->Apply(aResult);
1341         for (TopExp_Explorer aFaceExp (theResult,TopAbs_FACE); aFaceExp.More(); aFaceExp.Next()) {
1342           TopoDS_Face aCurrent = TopoDS::Face(aFaceExp.Current().Oriented(TopAbs_FORWARD));
1343           Handle(TColGeom_HArray2OfSurface) grid = new TColGeom_HArray2OfSurface ( 1, 1, 1, 1 );
1344           grid->SetValue ( 1, 1, aBaseSurface );
1345           Handle(ShapeExtend_CompositeSurface) G = new ShapeExtend_CompositeSurface ( grid );
1346           ShapeFix_ComposeShell CompShell;
1347           CompShell.Init ( G, aBaseLocation, aCurrent, ::Precision::Confusion() );//myPrecision
1348           //CompShell.SetContext( aContext );
1349           CompShell.SetContext( myContext );
1350
1351           TopTools_SequenceOfShape parts, anIntWires;
1352           ShapeFix_SequenceOfWireSegment wires;
1353           for(TopExp_Explorer W_Exp(aCurrent,TopAbs_WIRE);W_Exp.More();W_Exp.Next()) {
1354             const TopoDS_Wire& aWire = TopoDS::Wire(W_Exp.Current());
1355             // check if the wire is ordinary (contains non-internal edges)
1356             Standard_Boolean isInternal = Standard_True;
1357             for (TopoDS_Iterator it(aWire); it.More() && isInternal; it.Next())
1358               isInternal = (it.Value().Orientation() == TopAbs_INTERNAL);
1359             if (isInternal)
1360             {
1361               // place internal wire separately
1362               anIntWires.Append(aWire);
1363             }
1364             else
1365             {
1366               Handle(ShapeExtend_WireData) sbwd =
1367                 new ShapeExtend_WireData (aWire);
1368               ShapeFix_WireSegment seg ( sbwd, TopAbs_REVERSED );
1369               wires.Append(seg);
1370             }
1371           }
1372
1373           CompShell.DispatchWires ( parts,wires );
1374           for (Standard_Integer j=1; j <= parts.Length(); j++ ) {
1375             ShapeFix_Face aFixOrient(TopoDS::Face(parts(j)));
1376             //aFixOrient.SetContext(aContext);
1377             aFixOrient.SetContext(myContext);
1378             aFixOrient.FixOrientation();
1379             // put internal wires to faces
1380             putIntWires(parts(j), anIntWires);
1381           }
1382
1383           TopoDS_Shape CompRes;
1384           if ( parts.Length() !=1 ) {
1385             TopoDS_Shell S;
1386             B.MakeShell ( S );
1387             for ( i=1; i <= parts.Length(); i++ )
1388               B.Add ( S, parts(i) );
1389             S.Closed (BRep_Tool::IsClosed (S));
1390             CompRes = S;
1391           }
1392           else CompRes = parts(1);
1393
1394           //aContext->Replace(aCurrent,CompRes);
1395           myContext->Replace(aCurrent,CompRes);
1396           //for history
1397           /*
1398           if (!myOldNewMap.IsBound(aCurrent))
1399           {
1400             TopTools_ListOfShape EmptyList;
1401             myOldNewMap.Bind(aCurrent, EmptyList);
1402           }
1403           myOldNewMap(aCurrent).Clear();
1404           myOldNewMap(aCurrent).Append(CompRes);
1405           */
1406           /////////////
1407         }
1408
1409         // remove the remaining faces
1410         for(i = 2; i <= faces.Length(); i++)
1411         { 
1412           myOldShapes.Bind(faces(i), theResult);
1413           myContext->Remove(faces(i));
1414         }
1415       }
1416     } // end processing each face
1417
1418     //TopoDS_Shape aResult = Shape;
1419     if (NbModif > 0 && !hasFailed) {
1420       //TopoDS_Shape aResult = aContext->Apply(aShell);
1421       TopoDS_Shape aResult = myContext->Apply(aShell);
1422
1423       ShapeFix_Edge sfe;
1424       for (exp.Init(aResult,TopAbs_EDGE); exp.More(); exp.Next()) {
1425         TopoDS_Edge E = TopoDS::Edge(exp.Current());
1426         sfe.FixVertexTolerance (E);
1427         // ptv add fix same parameter
1428         sfe.FixSameParameter(E, Precision::Confusion());
1429       }
1430
1431       myContext->Replace(aShell, aResult);
1432       //for history
1433       /*
1434       if (!myOldNewMap.IsBound(aShell))
1435       {
1436         TopTools_ListOfShape EmptyList;
1437         myOldNewMap.Bind(aShell, EmptyList);
1438       }
1439       myOldNewMap(aShell).Clear();
1440       myOldNewMap(aShell).Append(aResult);
1441       */
1442       /////////////
1443     }
1444     //else
1445     {
1446       for (exp.Init(aShell, TopAbs_FACE); exp.More(); exp.Next()) {
1447         TopoDS_Face aFace = TopoDS::Face(exp.Current().Oriented(TopAbs_FORWARD));
1448         Handle(ShapeFix_Wire) sfw = new ShapeFix_Wire;
1449         sfw->SetContext(myContext);
1450         sfw->SetPrecision(Precision::Confusion());
1451         sfw->SetMinTolerance(Precision::Confusion());
1452         sfw->SetMaxTolerance(1.);
1453         sfw->SetFace(aFace);
1454         for (TopoDS_Iterator iter (aFace,Standard_False); iter.More(); iter.Next()) {
1455           TopoDS_Wire wire = TopoDS::Wire(iter.Value());
1456           sfw->Load(wire);
1457           sfw->FixReorder();
1458           sfw->FixShifted();
1459         }
1460       }
1461     }
1462   } // end processing each shell
1463
1464   myShape = myContext->Apply(myShape);
1465 }
1466
1467 //=======================================================================
1468 //function : UnifyEdges
1469 //purpose  : 
1470 //=======================================================================
1471 void ShapeUpgrade_UnifySameDomain::UnifyEdges()
1472 {
1473   Standard_Real Tol = Precision::Confusion();
1474   
1475   //Handle(ShapeBuild_ReShape) myContext = new ShapeBuild_ReShape;
1476   Standard_Real myTolerance = Precision::Confusion();
1477   TopoDS_Shape aResult = myContext->Apply(myShape);
1478
1479   TopTools_IndexedMapOfShape ChangedFaces;
1480
1481   // creating map of edge faces
1482   TopTools_IndexedDataMapOfShapeListOfShape aMapEdgeFaces;
1483   TopExp::MapShapesAndAncestors(myShape, TopAbs_EDGE, TopAbs_FACE, aMapEdgeFaces);
1484   
1485   // creating map of vertex edges
1486   TopTools_IndexedDataMapOfShapeListOfShape aMapEdgesVertex;
1487   TopExp::MapShapesAndAncestors(myShape, TopAbs_VERTEX, TopAbs_EDGE, aMapEdgesVertex);
1488
1489   //Handle(ShapeBuild_ReShape) aContext = new ShapeBuild_ReShape;
1490   TopoDS_Shape aRes = myShape;
1491   //aRes = aContext->Apply(aSolid);
1492   aRes = myContext->Apply(myShape);
1493   
1494   TopTools_MapOfShape SharedVert;
1495
1496   
1497   TopTools_IndexedMapOfShape anOldEdges;
1498   TopExp::MapShapes(myInitShape, TopAbs_EDGE, anOldEdges);
1499
1500   TopTools_DataMapOfShapeShape NewEdges2OldEdges;
1501   for (int i = 1; i <= anOldEdges.Extent(); i++)
1502   {
1503     TopoDS_Shape NewEdge = myContext->Apply(anOldEdges(i));
1504     if (!NewEdge.IsNull())
1505       NewEdges2OldEdges.Bind(NewEdge, anOldEdges(i));
1506   }
1507
1508   TopExp_Explorer exp;
1509   // processing separate wires
1510   for (exp.Init(aRes, TopAbs_WIRE, TopAbs_FACE); exp.More(); exp.Next()) 
1511   {
1512     TopTools_SequenceOfShape SeqEdges;
1513     TopExp_Explorer expE(exp.Current(), TopAbs_EDGE);
1514     for (; expE.More(); expE.Next())
1515       SeqEdges.Append(expE.Current());
1516     SharedVert.Clear();
1517     CheckSharedVertices(SeqEdges, aMapEdgesVertex, SharedVert); 
1518     MergeSeq(SeqEdges, Tol, myConcatBSplines, myContext, myOldShapes, SharedVert, NewEdges2OldEdges);
1519   }
1520
1521   // processing each face
1522   for (exp.Init(aRes, TopAbs_FACE); exp.More(); exp.Next()) {
1523     //TopoDS_Face aFace = TopoDS::Face(aContext->Apply(exp.Current().Oriented(TopAbs_FORWARD)));
1524     TopoDS_Face aFace = TopoDS::Face(myContext->Apply(exp.Current().Oriented(TopAbs_FORWARD)));
1525     TopTools_IndexedDataMapOfShapeListOfShape aMapFacesEdges;
1526     TopTools_SequenceOfShape aNonSharedEdges;
1527     for (TopExp_Explorer expe(aFace,TopAbs_EDGE); expe.More(); expe.Next()) {
1528       TopoDS_Edge edge = TopoDS::Edge(expe.Current());
1529       if (!aMapEdgeFaces.Contains(edge)) continue;
1530       const TopTools_ListOfShape& aList = aMapEdgeFaces.FindFromKey(edge);
1531       TopTools_ListIteratorOfListOfShape anIter(aList);
1532       Standard_Integer NbFacesPerEdge = aList.Extent();
1533       for ( ; anIter.More(); anIter.Next()) {
1534         TopoDS_Face face = TopoDS::Face(anIter.Value());
1535         TopoDS_Face face1 = TopoDS::Face(myContext->Apply(anIter.Value()));
1536         if (face1.IsSame(aFace) && NbFacesPerEdge != 1)
1537           continue;
1538         if (NbFacesPerEdge == 1)
1539           //store non-shared edges separately 
1540           aNonSharedEdges.Append(edge);
1541         else 
1542         {
1543           if (aMapFacesEdges.Contains(face))
1544             aMapFacesEdges.ChangeFromKey(face).Append(edge);
1545           else 
1546           {
1547             TopTools_ListOfShape ListEdges;
1548             ListEdges.Append(edge);
1549             aMapFacesEdges.Add(face,ListEdges);
1550           }
1551         }
1552       }
1553     }
1554       
1555     for (Standard_Integer i=1; i<=aMapFacesEdges.Extent(); i++)
1556     {
1557       const TopTools_ListOfShape& ListEdges = aMapFacesEdges.FindFromIndex(i);
1558       TopTools_SequenceOfShape SeqEdges;
1559       TopTools_ListIteratorOfListOfShape anIter(ListEdges);
1560       for ( ; anIter.More(); anIter.Next())
1561         SeqEdges.Append(anIter.Value());
1562       if (SeqEdges.Length()==1) 
1563         continue;  
1564
1565       SharedVert.Clear();
1566       CheckSharedVertices(SeqEdges, aMapEdgesVertex, SharedVert);
1567       //if (!SharedVert.IsEmpty()) 
1568       //  continue;
1569       if ( MergeSeq(SeqEdges,Tol,myConcatBSplines, myContext, myOldShapes, SharedVert, NewEdges2OldEdges) )
1570       {
1571         //for history
1572         /*
1573         for (j = 1; j <= SeqEdges.Length(); j++)
1574         {
1575           if (!myOldNewMap.IsBound(SeqEdges(j)))
1576           {
1577             TopTools_ListOfShape EmptyList;
1578             myOldNewMap.Bind(SeqEdges(j), EmptyList);
1579           }
1580           myOldNewMap(SeqEdges(j)).Clear();
1581           myOldNewMap(SeqEdges(j)).Append(E);
1582         }
1583         */
1584         /////////////
1585         
1586         TopoDS_Face tmpF = TopoDS::Face(exp.Current());
1587         if ( !ChangedFaces.Contains(tmpF) )
1588           ChangedFaces.Add(tmpF);
1589         tmpF = TopoDS::Face(aMapFacesEdges.FindKey(i));
1590         if ( !ChangedFaces.Contains(tmpF) )
1591           ChangedFaces.Add(tmpF);
1592       }
1593     }
1594     
1595     if ( aNonSharedEdges.Length() > 1 )
1596     {
1597       SharedVert.Clear();
1598       CheckSharedVertices(aNonSharedEdges, aMapEdgesVertex, SharedVert); 
1599       if ( MergeSeq(aNonSharedEdges, Tol, myConcatBSplines, myContext, myOldShapes, SharedVert, NewEdges2OldEdges) )
1600       {
1601         TopoDS_Face tmpF = TopoDS::Face(exp.Current());
1602         if ( !ChangedFaces.Contains(tmpF) )
1603           ChangedFaces.Add(tmpF);
1604       }
1605     }
1606
1607   } // end processing each face
1608
1609   // fix changed faces and replace them in the local context
1610   for (Standard_Integer i=1; i<=ChangedFaces.Extent(); i++) {
1611     //TopoDS_Face aFace = TopoDS::Face(aContext->Apply(ChangedFaces.FindKey(i)));
1612     TopoDS_Face aFace = TopoDS::Face(myContext->Apply(ChangedFaces.FindKey(i)));
1613     if (aFace.IsNull())
1614       continue;
1615     Handle(ShapeFix_Face) sff = new ShapeFix_Face(aFace);
1616     sff->SetContext(myContext);
1617     sff->SetPrecision(myTolerance);
1618     sff->SetMinTolerance(myTolerance);
1619     sff->SetMaxTolerance(Max(1.,myTolerance*1000.));
1620     sff->Perform();
1621     TopoDS_Shape aNewFace = sff->Face();
1622     //aContext->Replace(aFace,aNewFace);
1623     myContext->Replace(aFace,aNewFace);
1624     //for history
1625     /*
1626     if (!myOldNewMap.IsBound(aFace))
1627     {
1628       TopTools_ListOfShape EmptyList;
1629       myOldNewMap.Bind(aFace, EmptyList);
1630     }
1631     myOldNewMap(aFace).Clear();
1632     myOldNewMap(aFace).Append(aNewFace);
1633     */
1634     /////////////
1635   }
1636
1637   if (ChangedFaces.Extent() > 0) {
1638     // fix changed shell and replace it in the local context
1639     //TopoDS_Shape aRes1 = aContext->Apply(aRes);
1640     TopoDS_Shape aRes1 = myContext->Apply(aRes);
1641     TopExp_Explorer expsh;
1642     for (expsh.Init(aRes1, TopAbs_SHELL); expsh.More(); expsh.Next()) {
1643       TopoDS_Shell aShell = TopoDS::Shell(expsh.Current());
1644       Handle(ShapeFix_Shell) sfsh = new ShapeFix_Shell;
1645       sfsh->FixFaceOrientation(aShell);
1646       TopoDS_Shape aNewShell = sfsh->Shell();
1647       //aContext->Replace(aShell,aNewShell);
1648       myContext->Replace(aShell,aNewShell);
1649       //for history
1650       /*
1651       if (!myOldNewMap.IsBound(aShell))
1652       {
1653         TopTools_ListOfShape EmptyList;
1654         myOldNewMap.Bind(aShell, EmptyList);
1655       }
1656       myOldNewMap(aShell).Clear();
1657       myOldNewMap(aShell).Append(aNewShell);
1658       */
1659       /////////////
1660     }
1661     //TopoDS_Shape aRes2 = aContext->Apply(aRes1);
1662     TopoDS_Shape aRes2 = myContext->Apply(aRes1);
1663     myContext->Replace(myShape,aRes2);
1664     //for history
1665     /*
1666     if (!myOldNewMap.IsBound(aSolid))
1667     {
1668       TopTools_ListOfShape EmptyList;
1669       myOldNewMap.Bind(aSolid, EmptyList);
1670     }
1671     myOldNewMap(aSolid).Clear();
1672     myOldNewMap(aSolid).Append(aRes2);
1673     */
1674     /////////////
1675   }
1676
1677   myShape = myContext->Apply(myShape);
1678 }
1679
1680 //=======================================================================
1681 //function : UnifyFacesAndEdges
1682 //purpose  : 
1683 //=======================================================================
1684
1685 void ShapeUpgrade_UnifySameDomain::UnifyFacesAndEdges()
1686 {
1687   UnifyFaces();
1688   
1689   /*
1690   ShapeUpgrade_RemoveLocations RemLoc;
1691   RemLoc.Remove(myShape);
1692   myShape = RemLoc.GetResult();
1693   */
1694
1695   UnifyEdges();
1696 }
1697
1698 //=======================================================================
1699 //function : Build
1700 //purpose  : builds the resulting shape
1701 //======================================================================
1702 void ShapeUpgrade_UnifySameDomain::Build() 
1703 {
1704   if (myUnifyFaces && myUnifyEdges)
1705     UnifyFacesAndEdges();
1706
1707   else if (myUnifyEdges)
1708     UnifyEdges();
1709   else if (myUnifyFaces)
1710     UnifyFaces();
1711
1712   //Done();
1713 }
1714
1715 //=======================================================================
1716 //function : Shape
1717 //purpose  : give the resulting shape
1718 //=======================================================================
1719 const TopoDS_Shape& ShapeUpgrade_UnifySameDomain::Shape() const
1720 {
1721   return myShape;
1722 }
1723
1724 //=======================================================================
1725 //function : Generated
1726 //purpose  : returns the new shape from the old one
1727 //=======================================================================
1728 TopoDS_Shape ShapeUpgrade_UnifySameDomain::Generated(const TopoDS_Shape& aShape) const
1729 {
1730   TopoDS_Shape aNewShape = myContext->Apply(aShape);
1731
1732   if (aNewShape.IsNull())
1733     aNewShape = myContext->Apply(myOldShapes(aShape));
1734   
1735   return aNewShape;
1736 }