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