Salome HOME
09c2caf0d398e37180a1237b26299645f02b43a6
[modules/geom.git] / src / BlockFix / BlockFix_UnionEdges.cxx
1 // Copyright (C) 2007-2014  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, or (at your option) any later version.
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
23 // File:      BlockFix_UnionEdges.cxx
24 // Created:   07.12.04 15:27:30
25 // Author:    Sergey KUUL
26
27 #include <BlockFix_UnionEdges.hxx>
28
29 #include <ShapeAnalysis_Edge.hxx>
30
31 #include <ShapeBuild_ReShape.hxx>
32
33 #include <ShapeFix_Face.hxx>
34 #include <ShapeFix_Shell.hxx>
35
36 #include <BRep_Builder.hxx>
37 #include <BRep_CurveRepresentation.hxx>
38 #include <BRep_ListIteratorOfListOfCurveRepresentation.hxx>
39 #include <BRep_TEdge.hxx>
40 #include <BRep_Tool.hxx>
41 #include <BRepLib.hxx>
42 #include <BRepLib_MakeEdge.hxx>
43 #include <BRepTools_WireExplorer.hxx>
44
45 #include <TopExp.hxx>
46 #include <TopExp_Explorer.hxx>
47
48 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
49 #include <TopTools_ListOfShape.hxx>
50 #include <TopTools_MapIteratorOfMapOfShape.hxx>
51 #include <TopTools_MapOfShape.hxx>
52 #include <TopTools_ListIteratorOfListOfShape.hxx>
53 #include <TopTools_SequenceOfShape.hxx>
54
55 #include <TopoDS.hxx>
56 #include <TopoDS_Edge.hxx>
57 #include <TopoDS_Face.hxx>
58 #include <TopoDS_Shell.hxx>
59 #include <TopoDS_Vertex.hxx>
60 #include <TopoDS_Shape.hxx>
61
62 #include <GC_MakeCircle.hxx>
63
64 #include <Geom_BezierCurve.hxx>
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 <TColStd_Array1OfReal.hxx>
85 #include <TColStd_ListIteratorOfListOfInteger.hxx>
86 #include <TColStd_ListOfInteger.hxx>
87 #include <TColStd_MapOfInteger.hxx>
88
89 #include "utilities.h"
90
91
92 //=======================================================================
93 //function : IsToMerge
94 //purpose  : This method return Standard_True if two consequent edges can
95 //           be merged. The edges can be merged if:
96 //             1. They belong to same faces.
97 //             2. They either both seam or both not seam on each face.
98 //             3. They are based on coincident lines, or:
99 //             4. They are based on coincident circles, or:
100 //             5. They are based on either Bezier of BSplines.
101 //=======================================================================
102 static Standard_Boolean IsToMerge
103     (const TopoDS_Edge                               &theEdge1,
104      const TopoDS_Edge                               &theEdge2,
105      const TopTools_IndexedDataMapOfShapeListOfShape &theMapEdgeFaces,
106      const Standard_Real                              theTolerance)
107 {
108   Standard_Boolean aResult  = Standard_False;
109   Standard_Boolean isDegen1 = BRep_Tool::Degenerated(theEdge1);
110   Standard_Boolean isDegen2 = BRep_Tool::Degenerated(theEdge2);
111   Standard_Boolean isCompareGeom = Standard_False;
112
113   if (isDegen1 && isDegen2) {
114     // Both of edges are degenerated.
115     aResult = Standard_True;
116   } else if (!isDegen1 && !isDegen2) {
117     // Both of edges are not degenerated.
118     // Check if they belong to the same faces.
119     Standard_Boolean isSame = Standard_False;
120     Standard_Boolean has1   = theMapEdgeFaces.Contains(theEdge1);
121     Standard_Boolean has2   = theMapEdgeFaces.Contains(theEdge1);
122
123     if (has1 && has2) {
124       const TopTools_ListOfShape &aLst1 = theMapEdgeFaces.FindFromKey(theEdge1);
125       const TopTools_ListOfShape &aLst2 = theMapEdgeFaces.FindFromKey(theEdge2);
126
127       if (aLst1.Extent() == aLst2.Extent()) {
128         TopTools_ListIteratorOfListOfShape anIter1(aLst1);
129
130         isSame = Standard_True;
131
132         for (; anIter1.More(); anIter1.Next()) {
133           TopoDS_Face aFace1 = TopoDS::Face(anIter1.Value());
134           TopTools_ListIteratorOfListOfShape  anIter2(aLst2);
135
136           for (; anIter2.More(); anIter2.Next()) {
137             if (aFace1.IsSame(anIter2.Value())) {
138               // Same face is detected. Break the loop.
139               // Check if edges either both seam or both not seam on this face.
140               Standard_Boolean isSeam1 = BRep_Tool::IsClosed(theEdge1, aFace1);
141               Standard_Boolean isSeam2 = BRep_Tool::IsClosed(theEdge2, aFace1);
142
143               isSame = (isSeam1 && isSeam2) || (isSeam1 == isSeam2);
144               break;
145             }
146           }
147
148           if (isSame && !anIter2.More()) {
149             // No same face is detected. Break the loop.
150             isSame = Standard_False;
151             break;
152           }
153         }
154       }
155     } else {
156       isSame = (has1 == has2); // True if the both of has are negative.
157     }
158
159     if (isSame) {
160       // Check edges geometry.
161       Standard_Real aFP1;
162       Standard_Real aFP2;
163       Standard_Real aLP1;
164       Standard_Real aLP2;
165       Handle(Geom_Curve) aC3d1 = BRep_Tool::Curve(theEdge1, aFP1, aLP1);
166       Handle(Geom_Curve) aC3d2 = BRep_Tool::Curve(theEdge2, aFP2, aLP2);
167
168       if (aC3d1.IsNull() == Standard_False &&
169           aC3d2.IsNull() == Standard_False) {
170         // Get the basis curves.
171         while(aC3d1->IsKind(STANDARD_TYPE(Geom_TrimmedCurve))) {
172           Handle(Geom_TrimmedCurve) aTc =
173             Handle(Geom_TrimmedCurve)::DownCast(aC3d1);
174           aC3d1 = aTc->BasisCurve();
175         }
176
177         while(aC3d2->IsKind(STANDARD_TYPE(Geom_TrimmedCurve))) {
178           Handle(Geom_TrimmedCurve) aTc =
179             Handle(Geom_TrimmedCurve)::DownCast(aC3d2);
180           aC3d2 = aTc->BasisCurve();
181         }
182
183         if(aC3d1->IsKind(STANDARD_TYPE(Geom_Line)) &&
184            aC3d2->IsKind(STANDARD_TYPE(Geom_Line))) {
185           // Two curves are lines.
186           Handle(Geom_Line) aL1 = Handle(Geom_Line)::DownCast(aC3d1);
187           Handle(Geom_Line) aL2 = Handle(Geom_Line)::DownCast(aC3d2);
188           gp_Dir aDir1 = aL1->Position().Direction();
189           gp_Dir aDir2 = aL2->Position().Direction();
190     
191           if(aDir1.IsParallel(aDir2, theTolerance)) {
192             // Two coincident lines.
193             aResult = Standard_True;
194           }
195         } else if(aC3d1->IsKind(STANDARD_TYPE(Geom_Circle)) &&
196                   aC3d2->IsKind(STANDARD_TYPE(Geom_Circle))) {
197           // Two curves are circles.
198           Handle(Geom_Circle) aC1 = Handle(Geom_Circle)::DownCast(aC3d1);
199           Handle(Geom_Circle) aC2 = Handle(Geom_Circle)::DownCast(aC3d2);
200           gp_Pnt aP01 = aC1->Location();
201           gp_Pnt aP02 = aC2->Location();
202
203           if (aP01.Distance(aP02) <= Precision::Confusion()) {
204             // Two coincident circles.
205             aResult = Standard_True;
206           }
207         } else if (aC3d1->IsKind(STANDARD_TYPE(Geom_BSplineCurve)) ||
208                    aC3d1->IsKind(STANDARD_TYPE(Geom_BezierCurve))) {
209           if (aC3d2->IsKind(STANDARD_TYPE(Geom_BSplineCurve)) ||
210               aC3d2->IsKind(STANDARD_TYPE(Geom_BezierCurve))) {
211             // Both of the curves are either bezier or BSplines.
212             aResult = Standard_True;
213           }
214         }
215       }
216     }
217   }
218
219   return aResult;
220 }
221
222 //=======================================================================
223 //function : BlockFix_UnionEdges()
224 //purpose  : Constructor
225 //=======================================================================
226 BlockFix_UnionEdges::BlockFix_UnionEdges (  )
227 {
228 }
229
230 //=======================================================================
231 //function : GlueEdgesWithPCurves
232 //purpose  : Glues the pcurves of the sequence of edges
233 //           and glues their 3d curves
234 //=======================================================================
235 static TopoDS_Edge GlueEdgesWithPCurves(const TopTools_SequenceOfShape& aChain,
236                                         const TopoDS_Vertex& FirstVertex,
237                                         const TopoDS_Vertex& LastVertex)
238 {
239   Standard_Integer i, j;
240
241   TopoDS_Edge FirstEdge = TopoDS::Edge(aChain(1));
242   //TColGeom2d_SequenceOfCurve PCurveSeq;
243   TColGeom_SequenceOfSurface SurfSeq;
244   //TopTools_SequenceOfShape LocSeq;
245   
246   BRep_ListIteratorOfListOfCurveRepresentation itr( (Handle(BRep_TEdge)::DownCast(FirstEdge.TShape()))->Curves() );
247   for (; itr.More(); itr.Next())
248   {
249     Handle(BRep_CurveRepresentation) CurveRep = itr.Value();
250     if (CurveRep->IsCurveOnSurface())
251     {
252       //PCurveSeq.Append(CurveRep->PCurve());
253       SurfSeq.Append(CurveRep->Surface());
254       /*
255       TopoDS_Shape aLocShape;
256       aLocShape.Location(CurveRep->Location());
257       LocSeq.Append(aLocShape);
258       */
259     }
260   }
261
262   Standard_Real fpar, lpar;
263   BRep_Tool::Range(FirstEdge, fpar, lpar);
264   TopoDS_Edge PrevEdge = FirstEdge;
265   TopoDS_Vertex CV;
266   Standard_Real MaxTol = 0.;
267   
268   TopoDS_Edge ResEdge;
269   BRep_Builder BB;
270
271   Standard_Integer nb_curve = aChain.Length();   //number of curves
272   TColGeom_Array1OfBSplineCurve tab_c3d(0,nb_curve-1);                    //array of the curves
273   TColStd_Array1OfReal tabtolvertex(0,nb_curve-1); //(0,nb_curve-2);  //array of the tolerances
274     
275   TopoDS_Vertex PrevVertex = FirstVertex;
276   for (i = 1; i <= nb_curve; i++)
277   {
278     TopoDS_Edge anEdge = TopoDS::Edge(aChain(i));
279     TopoDS_Vertex VF, VL;
280     TopExp::Vertices(anEdge, VF, VL);
281     Standard_Boolean ToReverse = (!VF.IsSame(PrevVertex));
282     
283     Standard_Real Tol1 = BRep_Tool::Tolerance(VF);
284     Standard_Real Tol2 = BRep_Tool::Tolerance(VL);
285     if (Tol1 > MaxTol)
286       MaxTol = Tol1;
287     if (Tol2 > MaxTol)
288       MaxTol = Tol2;
289     
290     if (i > 1)
291     {
292       TopExp::CommonVertex(PrevEdge, anEdge, CV);
293       Standard_Real Tol = BRep_Tool::Tolerance(CV);
294       tabtolvertex(i-2) = Tol;
295     }
296     
297     Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, fpar, lpar);
298     Handle(Geom_TrimmedCurve) aTrCurve = new Geom_TrimmedCurve(aCurve, fpar, lpar);
299     tab_c3d(i-1) = GeomConvert::CurveToBSplineCurve(aTrCurve);
300     GeomConvert::C0BSplineToC1BSplineCurve(tab_c3d(i-1), Precision::Confusion());
301     if (ToReverse)
302       tab_c3d(i-1)->Reverse();
303     PrevVertex = (ToReverse)? VF : VL;
304     PrevEdge = anEdge;
305   }
306   Handle(TColGeom_HArray1OfBSplineCurve)  concatcurve;     //array of the concatenated curves
307   Handle(TColStd_HArray1OfInteger)        ArrayOfIndices;  //array of the remining Vertex
308   GeomConvert::ConcatC1(tab_c3d,
309                         tabtolvertex,
310                         ArrayOfIndices,
311                         concatcurve,
312                         Standard_False,
313                         Precision::Confusion());   //C1 concatenation
314   
315   if (concatcurve->Length() > 1)
316   {
317     GeomConvert_CompCurveToBSplineCurve Concat(concatcurve->Value(concatcurve->Lower()));
318     
319     for (i = concatcurve->Lower()+1; i <= concatcurve->Upper(); i++)
320       Concat.Add( concatcurve->Value(i), MaxTol, Standard_True );
321     
322     concatcurve->SetValue(concatcurve->Lower(), Concat.BSplineCurve());
323   }
324   Handle(Geom_BSplineCurve) ResCurve = concatcurve->Value(concatcurve->Lower());
325   
326   TColGeom2d_SequenceOfBoundedCurve ResPCurves;
327   TopLoc_Location aLoc;
328   for (j = 1; j <= SurfSeq.Length(); j++)
329   {
330     TColGeom2d_Array1OfBSplineCurve tab_c2d(0,nb_curve-1); //array of the pcurves
331     
332     PrevVertex = FirstVertex;
333     PrevEdge = FirstEdge;
334     //TopLoc_Location theLoc = LocSeq(j).Location();
335     for (i = 1; i <= nb_curve; i++)
336     {
337       TopoDS_Edge anEdge = TopoDS::Edge(aChain(i));
338       TopoDS_Vertex VF, VL;
339       TopExp::Vertices(anEdge, VF, VL);
340       Standard_Boolean ToReverse = (!VF.IsSame(PrevVertex));
341
342       /*
343       Handle(Geom2d_Curve) aPCurve =
344         BRep_Tool::CurveOnSurface(anEdge, SurfSeq(j), anEdge.Location()*theLoc, fpar, lpar);
345       */
346       Handle(Geom2d_Curve) aPCurve =
347         BRep_Tool::CurveOnSurface(anEdge, SurfSeq(j), aLoc, fpar, lpar);
348       Handle(Geom2d_TrimmedCurve) aTrPCurve = new Geom2d_TrimmedCurve(aPCurve, fpar, lpar);
349       tab_c2d(i-1) = Geom2dConvert::CurveToBSplineCurve(aTrPCurve);
350       Geom2dConvert::C0BSplineToC1BSplineCurve(tab_c2d(i-1), Precision::Confusion());
351       if (ToReverse)
352         tab_c2d(i-1)->Reverse();
353       PrevVertex = (ToReverse)? VF : VL;
354       PrevEdge = anEdge;
355     }
356     Handle(TColGeom2d_HArray1OfBSplineCurve)  concatc2d;     //array of the concatenated curves
357     Handle(TColStd_HArray1OfInteger)        ArrayOfInd2d;  //array of the remining Vertex
358     Geom2dConvert::ConcatC1(tab_c2d,
359                             tabtolvertex,
360                             ArrayOfInd2d,
361                             concatc2d,
362                             Standard_False,
363                             Precision::Confusion());   //C1 concatenation
364     
365     if (concatc2d->Length() > 1)
366     {
367       Geom2dConvert_CompCurveToBSplineCurve Concat2d(concatc2d->Value(concatc2d->Lower()));
368       
369       for (i = concatc2d->Lower()+1; i <= concatc2d->Upper(); i++)
370         Concat2d.Add( concatc2d->Value(i), MaxTol, Standard_True );
371       
372       concatc2d->SetValue(concatc2d->Lower(), Concat2d.BSplineCurve());
373     }
374     Handle(Geom2d_BSplineCurve) aResPCurve = concatc2d->Value(concatc2d->Lower());
375     ResPCurves.Append(aResPCurve);
376   }
377   
378   ResEdge = BRepLib_MakeEdge(ResCurve,
379                              FirstVertex, LastVertex,
380                              ResCurve->FirstParameter(), ResCurve->LastParameter());
381   BB.SameRange(ResEdge, Standard_False);
382   BB.SameParameter(ResEdge, Standard_False);
383   for (j = 1; j <= ResPCurves.Length(); j++)
384   {
385     BB.UpdateEdge(ResEdge, ResPCurves(j), SurfSeq(j), aLoc, MaxTol);
386     BB.Range(ResEdge, SurfSeq(j), aLoc, ResPCurves(j)->FirstParameter(), ResPCurves(j)->LastParameter());
387   }
388
389   BRepLib::SameParameter(ResEdge, MaxTol, Standard_True);
390   
391   return ResEdge;
392 }
393
394 //=======================================================================
395 //function : MergeEdges
396 //purpose  : auxilary
397 //=======================================================================
398 static Standard_Boolean MergeEdges(const TopTools_SequenceOfShape& SeqEdges,
399                                    const Standard_Real Tol,
400                                    TopoDS_Edge& anEdge)
401 {
402   // make chain for union
403   BRep_Builder B;
404   ShapeAnalysis_Edge sae;
405   TopoDS_Edge FirstE = TopoDS::Edge(SeqEdges.Value(1));
406   TopoDS_Edge LastE = FirstE;
407   TopoDS_Vertex VF = sae.FirstVertex(FirstE);
408   TopoDS_Vertex VL = sae.LastVertex(LastE);
409   TopTools_SequenceOfShape aChain;
410   aChain.Append(FirstE);
411   TColStd_MapOfInteger IndUsedEdges;
412   IndUsedEdges.Add(1);
413   Standard_Integer j;
414   for(j=2; j<=SeqEdges.Length(); j++) {
415     for(Standard_Integer k=2; k<=SeqEdges.Length(); k++) {
416       if(IndUsedEdges.Contains(k)) continue;
417       TopoDS_Edge edge = TopoDS::Edge(SeqEdges.Value(k));
418       TopoDS_Vertex VF2 = sae.FirstVertex(edge);
419       TopoDS_Vertex VL2 = sae.LastVertex(edge);
420       if(sae.FirstVertex(edge).IsSame(VL)) {
421         aChain.Append(edge);
422         LastE = edge;
423         VL = sae.LastVertex(LastE);
424         IndUsedEdges.Add(k);
425       }
426       else if(sae.LastVertex(edge).IsSame(VF)) {
427         aChain.Prepend(edge);
428         FirstE = edge;
429         VF = sae.FirstVertex(FirstE);
430         IndUsedEdges.Add(k);
431       }
432     }
433   }
434   if(aChain.Length()<SeqEdges.Length()) {
435     MESSAGE ("can not create correct chain...");
436     return Standard_False;
437   }
438
439   // union edges in chain
440   // first step: union lines and circles
441   TopLoc_Location Loc;
442   Standard_Real fp1,lp1,fp2,lp2;
443   for(j=1; j<aChain.Length(); j++) {
444     TopoDS_Edge edge1 = TopoDS::Edge(aChain.Value(j));
445     Handle(Geom_Curve) c3d1 = BRep_Tool::Curve(edge1,Loc,fp1,lp1);
446     if(c3d1.IsNull()) break;
447     while(c3d1->IsKind(STANDARD_TYPE(Geom_TrimmedCurve))) {
448       Handle(Geom_TrimmedCurve) tc =
449         Handle(Geom_TrimmedCurve)::DownCast(c3d1);
450       c3d1 = tc->BasisCurve();
451     }
452     TopoDS_Edge edge2 = TopoDS::Edge(aChain.Value(j+1));
453     Handle(Geom_Curve) c3d2 = BRep_Tool::Curve(edge2,Loc,fp2,lp2);
454     if(c3d2.IsNull()) break;
455     while(c3d2->IsKind(STANDARD_TYPE(Geom_TrimmedCurve))) {
456       Handle(Geom_TrimmedCurve) tc =
457         Handle(Geom_TrimmedCurve)::DownCast(c3d2);
458       c3d2 = tc->BasisCurve();
459     }
460     if( c3d1->IsKind(STANDARD_TYPE(Geom_Line)) && c3d2->IsKind(STANDARD_TYPE(Geom_Line)) ) {
461       // union lines
462       Handle(Geom_Line) L1 = Handle(Geom_Line)::DownCast(c3d1);
463       Handle(Geom_Line) L2 = Handle(Geom_Line)::DownCast(c3d2);
464       gp_Dir Dir1 = L1->Position().Direction();
465       gp_Dir Dir2 = L2->Position().Direction();
466       //if(!Dir1.IsEqual(Dir2,Precision::Angular())) {
467       //if(!Dir1.IsParallel(Dir2,Precision::Angular())) {
468       if(!Dir1.IsParallel(Dir2,Tol)) {
469         continue;
470       }
471       // can union lines => create new edge
472       TopoDS_Vertex V1 = sae.FirstVertex(edge1);
473       gp_Pnt PV1 = BRep_Tool::Pnt(V1);
474       TopoDS_Vertex V2 = sae.LastVertex(edge2);
475       gp_Pnt PV2 = BRep_Tool::Pnt(V2);
476       gp_Vec Vec(PV1,PV2);
477       Handle(Geom_Line) L = new Geom_Line(gp_Ax1(PV1,Vec));
478       Standard_Real dist = PV1.Distance(PV2);
479       Handle(Geom_TrimmedCurve) tc = new Geom_TrimmedCurve(L,0.0,dist);
480       TopoDS_Edge E;
481       B.MakeEdge (E,tc,Precision::Confusion());
482       B.Add (E,V1);  B.Add (E,V2);
483       B.UpdateVertex(V1, 0., E, 0.);
484       B.UpdateVertex(V2, dist, E, 0.);
485       aChain.Remove(j);
486       aChain.SetValue(j,E);
487       j--;
488     }
489     if( c3d1->IsKind(STANDARD_TYPE(Geom_Circle)) && c3d2->IsKind(STANDARD_TYPE(Geom_Circle)) ) {
490       // union circles
491       Handle(Geom_Circle) C1 = Handle(Geom_Circle)::DownCast(c3d1);
492       Handle(Geom_Circle) C2 = Handle(Geom_Circle)::DownCast(c3d2);
493       gp_Pnt P01 = C1->Location();
494       gp_Pnt P02 = C2->Location();
495       if (P01.Distance(P02) > Precision::Confusion()) continue;
496       // can union circles => create new edge
497       TopoDS_Vertex V1 = sae.FirstVertex(edge1);
498       gp_Pnt PV1 = BRep_Tool::Pnt(V1);
499       TopoDS_Vertex V2 = sae.LastVertex(edge2);
500       gp_Pnt PV2 = BRep_Tool::Pnt(V2);
501       TopoDS_Vertex VM = sae.LastVertex(edge1);
502       gp_Pnt PVM = BRep_Tool::Pnt(VM);
503       GC_MakeCircle MC (PV1,PVM,PV2);
504       Handle(Geom_Circle) C;
505       TopoDS_Edge E;
506
507       if (MC.IsDone()) {
508         C = MC.Value();
509       }
510
511       if (C.IsNull()) {
512         // jfa for Mantis issue 0020228
513         if (PV1.Distance(PV2) > Precision::Confusion()) continue;
514         // closed chain
515         if (edge1.Orientation() == TopAbs_FORWARD) {
516           C = C1;
517         } else {
518           C = Handle(Geom_Circle)::DownCast(C1->Reversed());
519         }
520
521         B.MakeEdge (E,C,Precision::Confusion());
522         B.Add(E,V1);
523         B.Add(E,V2);
524       }
525       else {
526         gp_Pnt P0 = C->Location();
527         gp_Dir D1(gp_Vec(P0,PV1));
528         gp_Dir D2(gp_Vec(P0,PV2));
529         Standard_Real fpar = C->XAxis().Direction().Angle(D1);
530         if(fabs(fpar)>Precision::Confusion()) {
531           // check orientation
532           gp_Dir ND =  C->XAxis().Direction().Crossed(D1);
533           if(ND.IsOpposite(C->Axis().Direction(),Precision::Confusion())) {
534             fpar = -fpar;
535           }
536         }
537         Standard_Real lpar = C->XAxis().Direction().Angle(D2);
538         if(fabs(lpar)>Precision::Confusion()) {
539           // check orientation
540           gp_Dir ND =  C->XAxis().Direction().Crossed(D2);
541           if(ND.IsOpposite(C->Axis().Direction(),Precision::Confusion())) {
542             lpar = -lpar;
543           }
544         }
545         if (lpar < fpar) lpar += 2*M_PI;
546         Handle(Geom_TrimmedCurve) tc = new Geom_TrimmedCurve(C,fpar,lpar);
547         B.MakeEdge (E,tc,Precision::Confusion());
548         B.Add(E,V1);
549         B.Add(E,V2);
550         B.UpdateVertex(V1, fpar, E, 0.);
551         B.UpdateVertex(V2, lpar, E, 0.);
552       }
553       aChain.Remove(j);
554       aChain.SetValue(j,E);
555       j--;
556     }
557   }
558   if (j < aChain.Length()) {
559     MESSAGE ("null curve3d in edge...");
560     return Standard_False;
561   }
562   if (aChain.Length() > 1) {
563     // second step: union edges with various curves
564     // skl for bug 0020052 from Mantis: perform such unions
565     // only if curves are bspline or bezier
566     bool NeedUnion = true;
567     for(j=1; j<=aChain.Length(); j++) {
568       TopoDS_Edge edge = TopoDS::Edge(aChain.Value(j));
569       Handle(Geom_Curve) c3d = BRep_Tool::Curve(edge,Loc,fp1,lp1);
570       if(c3d.IsNull()) continue;
571       while(c3d->IsKind(STANDARD_TYPE(Geom_TrimmedCurve))) {
572         Handle(Geom_TrimmedCurve) tc =
573           Handle(Geom_TrimmedCurve)::DownCast(c3d);
574         c3d = tc->BasisCurve();
575       }
576       if( ( c3d->IsKind(STANDARD_TYPE(Geom_BSplineCurve)) ||
577             c3d->IsKind(STANDARD_TYPE(Geom_BezierCurve)) ) ) continue;
578       NeedUnion = false;
579       break;
580     }
581     if(NeedUnion) {
582       MESSAGE ("can not make analitical union => make approximation");
583       TopoDS_Edge E = GlueEdgesWithPCurves(aChain, VF, VL);
584       aChain.SetValue(1,E);
585     }
586     else {
587       MESSAGE ("can not make approximation for such types of curves");
588       return Standard_False;
589     }
590   }
591
592   anEdge = TopoDS::Edge(aChain.Value(1));
593   return Standard_True;
594 }
595
596 //=======================================================================
597 //function : Perform
598 //purpose  :
599 //=======================================================================
600 TopoDS_Shape BlockFix_UnionEdges::Perform(const TopoDS_Shape& theShape,
601                                           const Standard_Real theTol)
602 {
603   // Fill Map of edges as keys and list of faces as items.
604   TopTools_IndexedDataMapOfShapeListOfShape aMapEdgeFaces;
605   Standard_Boolean isModified = Standard_False;
606
607   TopExp::MapShapesAndAncestors
608     (theShape, TopAbs_EDGE, TopAbs_FACE, aMapEdgeFaces);
609
610   // processing each face
611   Handle(ShapeBuild_ReShape) aContext = new ShapeBuild_ReShape;
612   TopTools_MapOfShape        aProcessed;
613   TopTools_MapOfShape        aModifiedFaces;
614   TopExp_Explorer            anExpF(theShape, TopAbs_FACE);
615
616   for (; anExpF.More(); anExpF.Next()) {
617     // Processing of each wire of the face
618     TopoDS_Face aFace = TopoDS::Face(anExpF.Current());
619
620     if (!aProcessed.Add(aFace)) {
621       continue;
622     }
623
624     TopExp_Explorer anExpW(aFace, TopAbs_WIRE);
625
626     for (; anExpW.More(); anExpW.Next()) {
627       // Get the ordered list of edges in the wire.
628       TopoDS_Wire            aWire = TopoDS::Wire(anExpW.Current());
629       BRepTools_WireExplorer aWExp(aWire, aFace);
630       TopTools_ListOfShape   aChainEdges;
631       Standard_Integer       aNbEdges = 0;
632
633       for (; aWExp.More(); aWExp.Next(), aNbEdges++) {
634         aChainEdges.Append(aWExp.Current());
635       }
636
637       if (aNbEdges < 2) {
638         // Nothing to merge.
639         continue;
640       }
641
642       // Fill the list of flags that neighbour edges can be merged.
643       TColStd_ListOfInteger aChainCanMerged;
644       TopoDS_Edge           anEdge1 = TopoDS::Edge(aChainEdges.Last());
645       TopoDS_Edge           anEdge2;
646       Standard_Boolean      isToMerge;
647       TopTools_ListIteratorOfListOfShape anIter(aChainEdges);
648       Standard_Boolean      isFirstMerge = Standard_False;
649       Standard_Boolean      isFirst = Standard_True;
650       Standard_Boolean      isReorder = Standard_False;
651
652       // The first element is the flag between last and first edges.
653       for (; anIter.More(); anIter.Next()) {
654         anEdge2 = TopoDS::Edge(anIter.Value());
655  
656         if (aProcessed.Contains(anEdge1) || aProcessed.Contains(anEdge2)) {
657           // No need to merge already processed edges.
658           isToMerge = Standard_False;
659         } else {
660           isToMerge = IsToMerge(anEdge1, anEdge2, aMapEdgeFaces, theTol);
661         }
662
663         aChainCanMerged.Append(isToMerge);
664         anEdge1 = anEdge2;
665
666         if (isFirst) {
667           isFirstMerge = isToMerge;
668           isFirst      = Standard_False;
669         } else if (isFirstMerge && !isToMerge) {
670           isReorder = Standard_True;
671         }
672       }
673
674       // Fill the map of processed shape by the edges.
675       for (anIter.Initialize(aChainEdges); anIter.More(); anIter.Next()) {
676         aProcessed.Add(anIter.Value());
677       }
678
679       // Reorder edges in the chain.
680       if (isReorder) {
681         // Find the first edge that can't be merged.
682         while (aChainCanMerged.First()) {
683           TopoDS_Shape aTmpShape = aChainEdges.First();
684
685           isToMerge = aChainCanMerged.First();
686           aChainCanMerged.RemoveFirst();
687           aChainCanMerged.Append(isToMerge);
688           aChainEdges.RemoveFirst();
689           aChainEdges.Append(aTmpShape);
690         }
691       }
692
693       // Merge parts of chain to be merged.
694       TColStd_ListIteratorOfListOfInteger aFlagIter(aChainCanMerged);
695       anIter.Initialize(aChainEdges);
696
697       while (anIter.More()) {
698         TopTools_SequenceOfShape aSeqEdges;
699
700         aSeqEdges.Append(anIter.Value());
701         aFlagIter.Next();
702         anIter.Next();
703
704         for (; anIter.More(); anIter.Next(), aFlagIter.Next()) {
705           if (aFlagIter.Value()) {
706             // Continue the chain.
707             aSeqEdges.Append(anIter.Value());
708           } else {
709             // Stop the chain.
710             break;
711           }
712         }
713
714         const Standard_Integer aNbEdges = aSeqEdges.Length();
715
716         if (aNbEdges > 1) {
717           // There are several edges to be merged.
718           TopoDS_Edge aMergedEdge;
719
720           if (MergeEdges(aSeqEdges, theTol, aMergedEdge)) {
721             isModified = Standard_True;
722             // now we have only one edge - aMergedEdge.
723             // we have to replace old ListEdges with this new edge
724             const TopoDS_Shape &anEdge = aSeqEdges.Value(1);
725
726             aContext->Replace(anEdge, aMergedEdge);
727
728             for (Standard_Integer j = 2; j <= aNbEdges; j++) {
729               aContext->Remove(aSeqEdges(j));
730             }
731
732             // Fix affected faces.
733             if (aMapEdgeFaces.Contains(anEdge)) {
734               const TopTools_ListOfShape &aList =
735                 aMapEdgeFaces.FindFromKey(anEdge);
736               TopTools_ListIteratorOfListOfShape anIter(aList);
737
738               for (; anIter.More(); anIter.Next()) {
739                 aModifiedFaces.Add(anIter.Value());
740               }
741             }
742           }
743         }
744       }
745     }
746   }
747
748   if (isModified) {
749     // Fix modified faces.
750     TopTools_MapIteratorOfMapOfShape aModifIt(aModifiedFaces);
751
752     for (; aModifIt.More(); aModifIt.Next()) {
753       TopoDS_Face aModifiedFace =
754         TopoDS::Face(aContext->Apply(aModifIt.Key()));
755       Handle(ShapeFix_Face) aSff = new ShapeFix_Face(aModifiedFace);
756
757       aSff->SetContext(aContext);
758       aSff->SetPrecision(theTol);
759       aSff->SetMinTolerance(theTol);
760       aSff->SetMaxTolerance(Max(1., theTol*1000.));
761       aSff->Perform();
762       aContext->Replace(aModifiedFace, aSff->Face());
763     }
764
765     // Check if the result shape contains shells.
766     // If yes, fix the faces orientation in the shell.
767     TopoDS_Shape    aModifShape = aContext->Apply(theShape);
768     TopExp_Explorer anExpSh(aModifShape, TopAbs_SHELL);
769
770     for (; anExpSh.More(); anExpSh.Next()) {
771       TopoDS_Shell           aShell = TopoDS::Shell(anExpSh.Current());
772       Handle(ShapeFix_Shell) aSfsh = new ShapeFix_Shell;
773
774       aSfsh->FixFaceOrientation(aShell);
775       aContext->Replace(aShell, aSfsh->Shell());
776     }
777   }
778
779   const TopoDS_Shape aResult = aContext->Apply(theShape);
780
781   return aResult;
782 }