Salome HOME
Merge from V6_main_20120808 08Aug12
[modules/geom.git] / src / GEOMAlgo / BlockFix_UnionEdges.cxx
1 // Copyright (C) 2007-2012  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License.
10 //
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 // Lesser General Public License for more details.
15 //
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21
22 // File:      BlockFix_UnionEdges.cxx
23 // Created:   07.12.04 15:27:30
24 // Author:    Sergey KUUL
25
26 #include <BlockFix_UnionEdges.ixx>
27
28 #include <ShapeAnalysis_Edge.hxx>
29
30 #include <ShapeFix_Edge.hxx>
31 #include <ShapeFix_Face.hxx>
32 #include <ShapeFix_Shell.hxx>
33
34 #include <BRep_Builder.hxx>
35 #include <BRep_CurveRepresentation.hxx>
36 #include <BRep_ListIteratorOfListOfCurveRepresentation.hxx>
37 #include <BRep_TEdge.hxx>
38 #include <BRep_Tool.hxx>
39 #include <BRepAdaptor_HCompCurve.hxx>
40 #include <BRepLib.hxx>
41 #include <BRepLib_MakeEdge.hxx>
42
43 #include <TopExp.hxx>
44 #include <TopExp_Explorer.hxx>
45
46 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
47 #include <TopTools_IndexedMapOfShape.hxx>
48 #include <TopTools_ListOfShape.hxx>
49 #include <TopTools_MapOfShape.hxx>
50 #include <TopTools_ListIteratorOfListOfShape.hxx>
51 #include <TopTools_SequenceOfShape.hxx>
52
53 #include <TopoDS.hxx>
54 #include <TopoDS_Edge.hxx>
55 #include <TopoDS_Face.hxx>
56 #include <TopoDS_Shell.hxx>
57 #include <TopoDS_Solid.hxx>
58 #include <TopoDS_Vertex.hxx>
59 #include <TopoDS_Iterator.hxx>
60
61 #include <Approx_Curve3d.hxx>
62
63 #include <GC_MakeCircle.hxx>
64
65 #include <Geom_BSplineCurve.hxx>
66 #include <Geom_Circle.hxx>
67 #include <Geom_Curve.hxx>
68 #include <Geom_Line.hxx>
69 #include <Geom_TrimmedCurve.hxx>
70 #include <GeomConvert.hxx>
71 #include <GeomConvert_CompCurveToBSplineCurve.hxx>
72
73 #include <Geom2dConvert.hxx>
74 #include <Geom2dConvert_CompCurveToBSplineCurve.hxx>
75 #include <Geom2d_TrimmedCurve.hxx>
76 #include <Geom2d_BSplineCurve.hxx>
77
78 #include <TColGeom_SequenceOfSurface.hxx>
79 #include <TColGeom_Array1OfBSplineCurve.hxx>
80 #include <TColGeom_HArray1OfBSplineCurve.hxx>
81 #include <TColGeom2d_Array1OfBSplineCurve.hxx>
82 #include <TColGeom2d_HArray1OfBSplineCurve.hxx>
83 #include <TColGeom2d_SequenceOfBoundedCurve.hxx>
84 #include <TColgp_SequenceOfPnt.hxx>
85 #include <TColStd_Array1OfReal.hxx>
86 #include <TColStd_MapOfInteger.hxx>
87
88 #include "utilities.h"
89
90 //=======================================================================
91 //function : BlockFix_UnionEdges()
92 //purpose  : Constructor
93 //=======================================================================
94 BlockFix_UnionEdges::BlockFix_UnionEdges (  )
95 {
96 }
97
98 //=======================================================================
99 //function : GlueEdgesWithPCurves
100 //purpose  : Glues the pcurves of the sequence of edges
101 //           and glues their 3d curves
102 //=======================================================================
103 static TopoDS_Edge GlueEdgesWithPCurves(const TopTools_SequenceOfShape& aChain,
104                                         const TopoDS_Vertex& FirstVertex,
105                                         const TopoDS_Vertex& LastVertex)
106 {
107   Standard_Integer i, j;
108
109   TopoDS_Edge FirstEdge = TopoDS::Edge(aChain(1));
110   //TColGeom2d_SequenceOfCurve PCurveSeq;
111   TColGeom_SequenceOfSurface SurfSeq;
112   //TopTools_SequenceOfShape LocSeq;
113   
114   BRep_ListIteratorOfListOfCurveRepresentation itr( (Handle(BRep_TEdge)::DownCast(FirstEdge.TShape()))->Curves() );
115   for (; itr.More(); itr.Next())
116   {
117     Handle(BRep_CurveRepresentation) CurveRep = itr.Value();
118     if (CurveRep->IsCurveOnSurface())
119     {
120       //PCurveSeq.Append(CurveRep->PCurve());
121       SurfSeq.Append(CurveRep->Surface());
122       /*
123       TopoDS_Shape aLocShape;
124       aLocShape.Location(CurveRep->Location());
125       LocSeq.Append(aLocShape);
126       */
127     }
128   }
129
130   Standard_Real fpar, lpar;
131   BRep_Tool::Range(FirstEdge, fpar, lpar);
132   TopoDS_Edge PrevEdge = FirstEdge;
133   TopoDS_Vertex CV;
134   Standard_Real MaxTol = 0.;
135   
136   TopoDS_Edge ResEdge;
137   BRep_Builder BB;
138
139   Standard_Integer nb_curve = aChain.Length();   //number of curves
140   TColGeom_Array1OfBSplineCurve tab_c3d(0,nb_curve-1);                    //array of the curves
141   TColStd_Array1OfReal tabtolvertex(0,nb_curve-1); //(0,nb_curve-2);  //array of the tolerances
142     
143   TopoDS_Vertex PrevVertex = FirstVertex;
144   for (i = 1; i <= nb_curve; i++)
145   {
146     TopoDS_Edge anEdge = TopoDS::Edge(aChain(i));
147     TopoDS_Vertex VF, VL;
148     TopExp::Vertices(anEdge, VF, VL);
149     Standard_Boolean ToReverse = (!VF.IsSame(PrevVertex));
150     
151     Standard_Real Tol1 = BRep_Tool::Tolerance(VF);
152     Standard_Real Tol2 = BRep_Tool::Tolerance(VL);
153     if (Tol1 > MaxTol)
154       MaxTol = Tol1;
155     if (Tol2 > MaxTol)
156       MaxTol = Tol2;
157     
158     if (i > 1)
159     {
160       TopExp::CommonVertex(PrevEdge, anEdge, CV);
161       Standard_Real Tol = BRep_Tool::Tolerance(CV);
162       tabtolvertex(i-2) = Tol;
163     }
164     
165     Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, fpar, lpar);
166     Handle(Geom_TrimmedCurve) aTrCurve = new Geom_TrimmedCurve(aCurve, fpar, lpar);
167     tab_c3d(i-1) = GeomConvert::CurveToBSplineCurve(aTrCurve);
168     GeomConvert::C0BSplineToC1BSplineCurve(tab_c3d(i-1), Precision::Confusion());
169     if (ToReverse)
170       tab_c3d(i-1)->Reverse();
171     PrevVertex = (ToReverse)? VF : VL;
172     PrevEdge = anEdge;
173   }
174   Handle(TColGeom_HArray1OfBSplineCurve)  concatcurve;     //array of the concatenated curves
175   Handle(TColStd_HArray1OfInteger)        ArrayOfIndices;  //array of the remining Vertex
176   GeomConvert::ConcatC1(tab_c3d,
177                         tabtolvertex,
178                         ArrayOfIndices,
179                         concatcurve,
180                         Standard_False,
181                         Precision::Confusion());   //C1 concatenation
182   
183   if (concatcurve->Length() > 1)
184   {
185     GeomConvert_CompCurveToBSplineCurve Concat(concatcurve->Value(concatcurve->Lower()));
186     
187     for (i = concatcurve->Lower()+1; i <= concatcurve->Upper(); i++)
188       Concat.Add( concatcurve->Value(i), MaxTol, Standard_True );
189     
190     concatcurve->SetValue(concatcurve->Lower(), Concat.BSplineCurve());
191   }
192   Handle(Geom_BSplineCurve) ResCurve = concatcurve->Value(concatcurve->Lower());
193   
194   TColGeom2d_SequenceOfBoundedCurve ResPCurves;
195   TopLoc_Location aLoc;
196   for (j = 1; j <= SurfSeq.Length(); j++)
197   {
198     TColGeom2d_Array1OfBSplineCurve tab_c2d(0,nb_curve-1); //array of the pcurves
199     
200     PrevVertex = FirstVertex;
201     PrevEdge = FirstEdge;
202     //TopLoc_Location theLoc = LocSeq(j).Location();
203     for (i = 1; i <= nb_curve; i++)
204     {
205       TopoDS_Edge anEdge = TopoDS::Edge(aChain(i));
206       TopoDS_Vertex VF, VL;
207       TopExp::Vertices(anEdge, VF, VL);
208       Standard_Boolean ToReverse = (!VF.IsSame(PrevVertex));
209
210       /*
211       Handle(Geom2d_Curve) aPCurve =
212         BRep_Tool::CurveOnSurface(anEdge, SurfSeq(j), anEdge.Location()*theLoc, fpar, lpar);
213       */
214       Handle(Geom2d_Curve) aPCurve =
215         BRep_Tool::CurveOnSurface(anEdge, SurfSeq(j), aLoc, fpar, lpar);
216       Handle(Geom2d_TrimmedCurve) aTrPCurve = new Geom2d_TrimmedCurve(aPCurve, fpar, lpar);
217       tab_c2d(i-1) = Geom2dConvert::CurveToBSplineCurve(aTrPCurve);
218       Geom2dConvert::C0BSplineToC1BSplineCurve(tab_c2d(i-1), Precision::Confusion());
219       if (ToReverse)
220         tab_c2d(i-1)->Reverse();
221       PrevVertex = (ToReverse)? VF : VL;
222       PrevEdge = anEdge;
223     }
224     Handle(TColGeom2d_HArray1OfBSplineCurve)  concatc2d;     //array of the concatenated curves
225     Handle(TColStd_HArray1OfInteger)        ArrayOfInd2d;  //array of the remining Vertex
226     Geom2dConvert::ConcatC1(tab_c2d,
227                             tabtolvertex,
228                             ArrayOfInd2d,
229                             concatc2d,
230                             Standard_False,
231                             Precision::Confusion());   //C1 concatenation
232     
233     if (concatc2d->Length() > 1)
234     {
235       Geom2dConvert_CompCurveToBSplineCurve Concat2d(concatc2d->Value(concatc2d->Lower()));
236       
237       for (i = concatc2d->Lower()+1; i <= concatc2d->Upper(); i++)
238         Concat2d.Add( concatc2d->Value(i), MaxTol, Standard_True );
239       
240       concatc2d->SetValue(concatc2d->Lower(), Concat2d.BSplineCurve());
241     }
242     Handle(Geom2d_BSplineCurve) aResPCurve = concatc2d->Value(concatc2d->Lower());
243     ResPCurves.Append(aResPCurve);
244   }
245   
246   ResEdge = BRepLib_MakeEdge(ResCurve,
247                              FirstVertex, LastVertex,
248                              ResCurve->FirstParameter(), ResCurve->LastParameter());
249   BB.SameRange(ResEdge, Standard_False);
250   BB.SameParameter(ResEdge, Standard_False);
251   for (j = 1; j <= ResPCurves.Length(); j++)
252   {
253     BB.UpdateEdge(ResEdge, ResPCurves(j), SurfSeq(j), aLoc, MaxTol);
254     BB.Range(ResEdge, SurfSeq(j), aLoc, ResPCurves(j)->FirstParameter(), ResPCurves(j)->LastParameter());
255   }
256
257   BRepLib::SameParameter(ResEdge, MaxTol, Standard_True);
258   
259   return ResEdge;
260 }
261
262 //=======================================================================
263 //function : MergeEdges
264 //purpose  : auxilary
265 //=======================================================================
266 static Standard_Boolean MergeEdges(const TopTools_SequenceOfShape& SeqEdges,
267                                    const TopoDS_Face& aFace,
268                                    const Standard_Real Tol,
269                                    TopoDS_Edge& anEdge)
270 {
271   // make chain for union
272   BRep_Builder B;
273   ShapeAnalysis_Edge sae;
274   TopoDS_Edge FirstE = TopoDS::Edge(SeqEdges.Value(1));
275   TopoDS_Edge LastE = FirstE;
276   TopoDS_Vertex VF = sae.FirstVertex(FirstE);
277   TopoDS_Vertex VL = sae.LastVertex(LastE);
278   TopTools_SequenceOfShape aChain;
279   aChain.Append(FirstE);
280   TColStd_MapOfInteger IndUsedEdges;
281   IndUsedEdges.Add(1);
282   Standard_Integer j;
283   for(j=2; j<=SeqEdges.Length(); j++) {
284     for(Standard_Integer k=2; k<=SeqEdges.Length(); k++) {
285       if(IndUsedEdges.Contains(k)) continue;
286       TopoDS_Edge edge = TopoDS::Edge(SeqEdges.Value(k));
287       TopoDS_Vertex VF2 = sae.FirstVertex(edge);
288       TopoDS_Vertex VL2 = sae.LastVertex(edge);
289       if(sae.FirstVertex(edge).IsSame(VL)) {
290         aChain.Append(edge);
291         LastE = edge;
292         VL = sae.LastVertex(LastE);
293         IndUsedEdges.Add(k);
294       }
295       else if(sae.LastVertex(edge).IsSame(VF)) {
296         aChain.Prepend(edge);
297         FirstE = edge;
298         VF = sae.FirstVertex(FirstE);
299         IndUsedEdges.Add(k);
300       }
301     }
302   }
303   if(aChain.Length()<SeqEdges.Length()) {
304     MESSAGE ("can not create correct chain...");
305     return Standard_False;
306   }
307   // union edges in chain
308   // first step: union lines and circles
309   TopLoc_Location Loc;
310   Standard_Real fp1,lp1,fp2,lp2;
311   for(j=1; j<aChain.Length(); j++) {
312     TopoDS_Edge edge1 = TopoDS::Edge(aChain.Value(j));
313     Handle(Geom_Curve) c3d1 = BRep_Tool::Curve(edge1,Loc,fp1,lp1);
314     if(c3d1.IsNull()) break;
315     while(c3d1->IsKind(STANDARD_TYPE(Geom_TrimmedCurve))) {
316       Handle(Geom_TrimmedCurve) tc =
317         Handle(Geom_TrimmedCurve)::DownCast(c3d1);
318       c3d1 = tc->BasisCurve();
319     }
320     TopoDS_Edge edge2 = TopoDS::Edge(aChain.Value(j+1));
321     Handle(Geom_Curve) c3d2 = BRep_Tool::Curve(edge2,Loc,fp2,lp2);
322     if(c3d2.IsNull()) break;
323     while(c3d2->IsKind(STANDARD_TYPE(Geom_TrimmedCurve))) {
324       Handle(Geom_TrimmedCurve) tc =
325         Handle(Geom_TrimmedCurve)::DownCast(c3d2);
326       c3d2 = tc->BasisCurve();
327     }
328     if( c3d1->IsKind(STANDARD_TYPE(Geom_Line)) && c3d2->IsKind(STANDARD_TYPE(Geom_Line)) ) {
329       // union lines
330       Handle(Geom_Line) L1 = Handle(Geom_Line)::DownCast(c3d1);
331       Handle(Geom_Line) L2 = Handle(Geom_Line)::DownCast(c3d2);
332       gp_Dir Dir1 = L1->Position().Direction();
333       gp_Dir Dir2 = L2->Position().Direction();
334       //if(!Dir1.IsEqual(Dir2,Precision::Angular())) {
335       //if(!Dir1.IsParallel(Dir2,Precision::Angular())) {
336       if(!Dir1.IsParallel(Dir2,Tol)) {
337         continue;
338       }
339       // can union lines => create new edge
340       TopoDS_Vertex V1 = sae.FirstVertex(edge1);
341       gp_Pnt PV1 = BRep_Tool::Pnt(V1);
342       TopoDS_Vertex V2 = sae.LastVertex(edge2);
343       gp_Pnt PV2 = BRep_Tool::Pnt(V2);
344       gp_Vec Vec(PV1,PV2);
345       Handle(Geom_Line) L = new Geom_Line(gp_Ax1(PV1,Vec));
346       Standard_Real dist = PV1.Distance(PV2);
347       Handle(Geom_TrimmedCurve) tc = new Geom_TrimmedCurve(L,0.0,dist);
348       TopoDS_Edge E;
349       B.MakeEdge (E,tc,Precision::Confusion());
350       B.Add (E,V1);  B.Add (E,V2);
351       B.UpdateVertex(V1, 0., E, 0.);
352       B.UpdateVertex(V2, dist, E, 0.);
353       //ShapeFix_Edge sfe;
354       //sfe.FixAddPCurve(E,aFace,Standard_False);
355       //sfe.FixSameParameter(E);
356       aChain.Remove(j);
357       aChain.SetValue(j,E);
358       j--;
359     }
360     if( c3d1->IsKind(STANDARD_TYPE(Geom_Circle)) && c3d2->IsKind(STANDARD_TYPE(Geom_Circle)) ) {
361       // union circles
362       Handle(Geom_Circle) C1 = Handle(Geom_Circle)::DownCast(c3d1);
363       Handle(Geom_Circle) C2 = Handle(Geom_Circle)::DownCast(c3d2);
364       gp_Pnt P01 = C1->Location();
365       gp_Pnt P02 = C2->Location();
366       if (P01.Distance(P02) > Precision::Confusion()) continue;
367       // can union circles => create new edge
368       TopoDS_Vertex V1 = sae.FirstVertex(edge1);
369       gp_Pnt PV1 = BRep_Tool::Pnt(V1);
370       TopoDS_Vertex V2 = sae.LastVertex(edge2);
371       gp_Pnt PV2 = BRep_Tool::Pnt(V2);
372       TopoDS_Vertex VM = sae.LastVertex(edge1);
373       gp_Pnt PVM = BRep_Tool::Pnt(VM);
374       GC_MakeCircle MC (PV1,PVM,PV2);
375       Handle(Geom_Circle) C = MC.Value();
376       TopoDS_Edge E;
377       if (!MC.IsDone() || C.IsNull()) {
378         // jfa for Mantis issue 0020228
379         if (PV1.Distance(PV2) > Precision::Confusion()) continue;
380         // closed chain
381         C = C1;
382         B.MakeEdge (E,C,Precision::Confusion());
383         B.Add(E,V1);
384         B.Add(E,V2);
385       }
386       else {
387         gp_Pnt P0 = C->Location();
388         gp_Dir D1(gp_Vec(P0,PV1));
389         gp_Dir D2(gp_Vec(P0,PV2));
390         Standard_Real fpar = C->XAxis().Direction().Angle(D1);
391         if(fabs(fpar)>Precision::Confusion()) {
392           // check orientation
393           gp_Dir ND =  C->XAxis().Direction().Crossed(D1);
394           if(ND.IsOpposite(C->Axis().Direction(),Precision::Confusion())) {
395             fpar = -fpar;
396           }
397         }
398         Standard_Real lpar = C->XAxis().Direction().Angle(D2);
399         if(fabs(lpar)>Precision::Confusion()) {
400           // check orientation
401           gp_Dir ND =  C->XAxis().Direction().Crossed(D2);
402           if(ND.IsOpposite(C->Axis().Direction(),Precision::Confusion())) {
403             lpar = -lpar;
404           }
405         }
406         if (lpar < fpar) lpar += 2*M_PI;
407         Handle(Geom_TrimmedCurve) tc = new Geom_TrimmedCurve(C,fpar,lpar);
408         B.MakeEdge (E,tc,Precision::Confusion());
409         B.Add(E,V1);
410         B.Add(E,V2);
411         B.UpdateVertex(V1, fpar, E, 0.);
412         B.UpdateVertex(V2, lpar, E, 0.);
413       }
414       aChain.Remove(j);
415       aChain.SetValue(j,E);
416       j--;
417     }
418   }
419   if (j < aChain.Length()) {
420     MESSAGE ("null curve3d in edge...");
421     return Standard_False;
422   }
423   if (aChain.Length() > 1) {
424     // second step: union edges with various curves
425     // skl for bug 0020052 from Mantis: perform such unions
426     // only if curves are bspline or bezier
427     bool NeedUnion = true;
428     for(j=1; j<=aChain.Length(); j++) {
429       TopoDS_Edge edge = TopoDS::Edge(aChain.Value(j));
430       Handle(Geom_Curve) c3d = BRep_Tool::Curve(edge,Loc,fp1,lp1);
431       if(c3d.IsNull()) continue;
432       while(c3d->IsKind(STANDARD_TYPE(Geom_TrimmedCurve))) {
433         Handle(Geom_TrimmedCurve) tc =
434           Handle(Geom_TrimmedCurve)::DownCast(c3d);
435         c3d = tc->BasisCurve();
436       }
437       if( ( c3d->IsKind(STANDARD_TYPE(Geom_BSplineCurve)) ||
438             c3d->IsKind(STANDARD_TYPE(Geom_BezierCurve)) ) ) continue;
439       NeedUnion = false;
440       break;
441     }
442     if(NeedUnion) {
443       MESSAGE ("can not make analitical union => make approximation");
444       TopoDS_Edge E = GlueEdgesWithPCurves(aChain, VF, VL);
445       /*
446       TopoDS_Wire W;
447       B.MakeWire(W);
448       for(j=1; j<=aChain.Length(); j++) {
449         TopoDS_Edge edge = TopoDS::Edge(aChain.Value(j));
450         B.Add(W,edge);
451       }
452       Handle(BRepAdaptor_HCompCurve) Adapt = new BRepAdaptor_HCompCurve(W);
453       Approx_Curve3d Conv(Adapt,Tol,GeomAbs_C1,9,1000);
454       Handle(Geom_BSplineCurve) bc = Conv.Curve();
455       TopoDS_Edge E;
456       B.MakeEdge (E,bc,Precision::Confusion());
457       B.Add (E,VF);
458       B.Add (E,VL);
459       */
460       aChain.SetValue(1,E);
461     }
462     else {
463       MESSAGE ("can not make approximation for such types of curves");
464       return Standard_False;
465     }
466   }
467
468   anEdge = TopoDS::Edge(aChain.Value(1));
469   return Standard_True;
470 }
471
472 //=======================================================================
473 //function : Perform
474 //purpose  :
475 //=======================================================================
476 TopoDS_Shape BlockFix_UnionEdges::Perform(const TopoDS_Shape& Shape,
477                                           const Standard_Real Tol)
478 {
479   myContext = new ShapeBuild_ReShape;
480   myTolerance = Tol;
481   TopoDS_Shape aResult = myContext->Apply(Shape);
482
483   // processing each solid
484   TopAbs_ShapeEnum aType = TopAbs_SOLID;
485   TopExp_Explorer exps (Shape, aType);
486   if (!exps.More()) {
487     aType = TopAbs_SHELL;
488     exps.Init(Shape, aType);
489   }
490   for (; exps.More(); exps.Next()) {
491     //TopoDS_Solid aSolid = TopoDS::Solid(exps.Current());
492     TopoDS_Shape aSolid = exps.Current();
493
494     TopTools_IndexedMapOfShape ChangedFaces;
495
496     // creating map of edge faces
497     TopTools_IndexedDataMapOfShapeListOfShape aMapEdgeFaces;
498     TopExp::MapShapesAndAncestors(aSolid, TopAbs_EDGE, TopAbs_FACE, aMapEdgeFaces);
499
500     Handle(ShapeBuild_ReShape) aContext = new ShapeBuild_ReShape;
501     TopoDS_Shape aRes = aSolid;
502     aRes = aContext->Apply(aSolid);
503
504     // processing each face
505     TopExp_Explorer exp;
506     for (exp.Init(aRes, TopAbs_FACE); exp.More(); exp.Next()) {
507       TopoDS_Face aFace =
508         TopoDS::Face(aContext->Apply(exp.Current().Oriented(TopAbs_FORWARD)));
509       TopTools_IndexedDataMapOfShapeListOfShape aMapFacesEdges;
510
511       for (TopExp_Explorer expe(aFace,TopAbs_EDGE); expe.More(); expe.Next()) {
512         TopoDS_Edge edge = TopoDS::Edge(expe.Current());
513         if (!aMapEdgeFaces.Contains(edge)) continue;
514         const TopTools_ListOfShape& aList = aMapEdgeFaces.FindFromKey(edge);
515         TopTools_ListIteratorOfListOfShape anIter(aList);
516         for ( ; anIter.More(); anIter.Next()) {
517           TopoDS_Face face = TopoDS::Face(anIter.Value());
518           TopoDS_Face face1 = TopoDS::Face(aContext->Apply(anIter.Value()));
519           if (face1.IsSame(aFace)) continue;
520           if (aMapFacesEdges.Contains(face)) {
521             aMapFacesEdges.ChangeFromKey(face).Append(edge);
522           }
523           else {
524             TopTools_ListOfShape ListEdges;
525             ListEdges.Append(edge);
526             aMapFacesEdges.Add(face,ListEdges);
527           }
528         }
529       }
530
531       for (Standard_Integer i=1; i<=aMapFacesEdges.Extent(); i++) {
532         const TopTools_ListOfShape& ListEdges = aMapFacesEdges.FindFromIndex(i);
533         TopTools_SequenceOfShape SeqEdges;
534         TopTools_ListIteratorOfListOfShape anIter(ListEdges);
535         for ( ; anIter.More(); anIter.Next()) {
536           SeqEdges.Append(anIter.Value());
537         }
538         if (SeqEdges.Length()==1) continue;
539         TopoDS_Edge E;
540         if ( MergeEdges(SeqEdges,aFace,Tol,E) ) {
541           // now we have only one edge - aChain.Value(1)
542           // we have to replace old ListEdges with this new edge
543           aContext->Replace(SeqEdges(1),E);
544           for (Standard_Integer j=2; j<=SeqEdges.Length(); j++) {
545             aContext->Remove(SeqEdges(j));
546           }
547           TopoDS_Face tmpF = TopoDS::Face(exp.Current());
548           if ( !ChangedFaces.Contains(tmpF) )
549             ChangedFaces.Add(tmpF);
550           tmpF = TopoDS::Face(aMapFacesEdges.FindKey(i));
551           if ( !ChangedFaces.Contains(tmpF) )
552             ChangedFaces.Add(tmpF);
553         }
554       }
555
556     } // end processing each face
557
558     // fix changed faces and replace them in the local context
559     for (Standard_Integer i=1; i<=ChangedFaces.Extent(); i++) {
560       TopoDS_Face aFace = TopoDS::Face(aContext->Apply(ChangedFaces.FindKey(i)));
561       Handle(ShapeFix_Face) sff = new ShapeFix_Face(aFace);
562       sff->SetContext(myContext);
563       sff->SetPrecision(myTolerance);
564       sff->SetMinTolerance(myTolerance);
565       sff->SetMaxTolerance(Max(1.,myTolerance*1000.));
566       sff->Perform();
567       aContext->Replace(aFace,sff->Face());
568     }
569
570     if (ChangedFaces.Extent() > 0) {
571       // fix changed shell and replace it in the local context
572       TopoDS_Shape aRes1 = aContext->Apply(aRes);
573       TopExp_Explorer expsh;
574       for (expsh.Init(aRes1, TopAbs_SHELL); expsh.More(); expsh.Next()) {
575         TopoDS_Shell aShell = TopoDS::Shell(expsh.Current());
576         Handle(ShapeFix_Shell) sfsh = new ShapeFix_Shell;
577         sfsh->FixFaceOrientation(aShell);
578         aContext->Replace(aShell,sfsh->Shell());
579       }
580       TopoDS_Shape aRes2 = aContext->Apply(aRes1);
581       // put new solid into global context
582       myContext->Replace(aSolid,aRes2);
583     }
584
585   } // end processing each solid
586
587   aResult = myContext->Apply(Shape);
588   return aResult;
589 }