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