]> SALOME platform Git repositories - modules/geom.git/blob - src/BlockFix/BlockFix_UnionEdges.cxx
Salome HOME
0023122: EDF 11178 GEOM: Fuse between a cylinder and a part with a hole fails
[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 //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(theEdge1);
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(); 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  : auxilary
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
585         if (edge1.Orientation() == TopAbs_FORWARD) {
586           C = C1;
587         } else {
588           C = Handle(Geom_Circle)::DownCast(C1->Reversed());
589         }
590
591         B.MakeEdge (E,C,Precision::Confusion());
592         B.Add(E,V1);
593         B.Add(E,V2);
594       }
595       else {
596         gp_Pnt P0 = C->Location();
597         gp_Dir D1(gp_Vec(P0,PV1));
598         gp_Dir D2(gp_Vec(P0,PV2));
599         Standard_Real fpar = C->XAxis().Direction().Angle(D1);
600         if(fabs(fpar)>Precision::Confusion()) {
601           // check orientation
602           gp_Dir ND =  C->XAxis().Direction().Crossed(D1);
603           if(ND.IsOpposite(C->Axis().Direction(),Precision::Confusion())) {
604             fpar = -fpar;
605           }
606         }
607         Standard_Real lpar = C->XAxis().Direction().Angle(D2);
608         if(fabs(lpar)>Precision::Confusion()) {
609           // check orientation
610           gp_Dir ND =  C->XAxis().Direction().Crossed(D2);
611           if(ND.IsOpposite(C->Axis().Direction(),Precision::Confusion())) {
612             lpar = -lpar;
613           }
614         }
615         if (lpar < fpar) lpar += 2*M_PI;
616         Handle(Geom_TrimmedCurve) tc = new Geom_TrimmedCurve(C,fpar,lpar);
617         B.MakeEdge (E,tc,Precision::Confusion());
618         B.Add(E,V1);
619         B.Add(E,V2);
620         B.UpdateVertex(V1, fpar, E, 0.);
621         B.UpdateVertex(V2, lpar, E, 0.);
622       }
623       aChain.Remove(j);
624       aChain.SetValue(j,E);
625       j--;
626     }
627   }
628   if (j < aChain.Length()) {
629     MESSAGE ("null curve3d in edge...");
630     return Standard_False;
631   }
632   if (aChain.Length() > 1) {
633     // second step: union edges with various curves
634     // skl for bug 0020052 from Mantis: perform such unions
635     // only if curves are bspline or bezier
636     bool NeedUnion = true;
637     for(j=1; j<=aChain.Length(); j++) {
638       TopoDS_Edge edge = TopoDS::Edge(aChain.Value(j));
639       Handle(Geom_Curve) c3d = BRep_Tool::Curve(edge,Loc,fp1,lp1);
640       if(c3d.IsNull()) continue;
641       while(c3d->IsKind(STANDARD_TYPE(Geom_TrimmedCurve))) {
642         Handle(Geom_TrimmedCurve) tc =
643           Handle(Geom_TrimmedCurve)::DownCast(c3d);
644         c3d = tc->BasisCurve();
645       }
646       if( ( c3d->IsKind(STANDARD_TYPE(Geom_BSplineCurve)) ||
647             c3d->IsKind(STANDARD_TYPE(Geom_BezierCurve)) ) ) continue;
648       NeedUnion = false;
649       break;
650     }
651     if(NeedUnion) {
652       MESSAGE ("can not make analitical union => make approximation");
653       TopoDS_Edge E = GlueEdgesWithPCurves(aChain, VF, VL);
654       aChain.SetValue(1,E);
655     }
656     else {
657       MESSAGE ("can not make approximation for such types of curves");
658       return Standard_False;
659     }
660   }
661
662   anEdge = TopoDS::Edge(aChain.Value(1));
663   return Standard_True;
664 }
665
666 //=======================================================================
667 //function : Perform
668 //purpose  :
669 //=======================================================================
670 TopoDS_Shape BlockFix_UnionEdges::Perform(const TopoDS_Shape& theShape,
671                                           const Standard_Real theTol)
672 {
673   // Fill Map of edges as keys and list of faces as items.
674   TopTools_IndexedDataMapOfShapeListOfShape aMapEdgeFaces;
675   Standard_Boolean isModified = Standard_False;
676
677   TopExp::MapShapesAndAncestors
678     (theShape, TopAbs_EDGE, TopAbs_FACE, aMapEdgeFaces);
679
680   // processing each face
681   Handle(ShapeBuild_ReShape) aContext = new ShapeBuild_ReShape;
682   TopTools_MapOfShape        aProcessed;
683   TopTools_MapOfShape        aModifiedFaces;
684   TopExp_Explorer            anExpF(theShape, TopAbs_FACE);
685
686   for (; anExpF.More(); anExpF.Next()) {
687     // Processing of each wire of the face
688     TopoDS_Face aFace = TopoDS::Face(anExpF.Current());
689
690     if (!aProcessed.Add(aFace)) {
691       continue;
692     }
693
694     TopExp_Explorer anExpW(aFace, TopAbs_WIRE);
695
696     for (; anExpW.More(); anExpW.Next()) {
697       // Get the ordered list of edges in the wire.
698       TopoDS_Wire            aWire = TopoDS::Wire(anExpW.Current());
699       BRepTools_WireExplorer aWExp(aWire, aFace);
700       TopTools_ListOfShape   aChainEdges;
701       Standard_Integer       aNbEdges = 0;
702
703       for (; aWExp.More(); aWExp.Next(), aNbEdges++) {
704         aChainEdges.Append(aWExp.Current());
705       }
706
707       if (aNbEdges < 2) {
708         // Nothing to merge.
709         continue;
710       }
711
712       // Fill the list of flags that neighbour edges can be merged.
713       TColStd_ListOfInteger aChainCanMerged;
714       TopoDS_Edge           anEdge1 = TopoDS::Edge(aChainEdges.Last());
715       TopoDS_Edge           anEdge2;
716       Standard_Boolean      isToMerge;
717       TopTools_ListIteratorOfListOfShape anIter(aChainEdges);
718       Standard_Boolean      isFirstMerge = Standard_False;
719       Standard_Boolean      isFirst = Standard_True;
720       Standard_Boolean      isReorder = Standard_False;
721
722       // The first element is the flag between last and first edges.
723       for (; anIter.More(); anIter.Next()) {
724         anEdge2 = TopoDS::Edge(anIter.Value());
725  
726         if (aProcessed.Contains(anEdge1) || aProcessed.Contains(anEdge2)) {
727           // No need to merge already processed edges.
728           isToMerge = Standard_False;
729         } else {
730           isToMerge = IsToMerge(anEdge1, anEdge2, aMapEdgeFaces, theTol);
731         }
732
733         aChainCanMerged.Append(isToMerge);
734         anEdge1 = anEdge2;
735
736         if (isFirst) {
737           isFirstMerge = isToMerge;
738           isFirst      = Standard_False;
739         } else if (isFirstMerge && !isToMerge) {
740           isReorder = Standard_True;
741         }
742       }
743
744       // Fill the map of processed shape by the edges.
745       for (anIter.Initialize(aChainEdges); anIter.More(); anIter.Next()) {
746         aProcessed.Add(anIter.Value());
747       }
748
749       // Reorder edges in the chain.
750       if (isReorder) {
751         // Find the first edge that can't be merged.
752         while (aChainCanMerged.First()) {
753           TopoDS_Shape aTmpShape = aChainEdges.First();
754
755           isToMerge = aChainCanMerged.First();
756           aChainCanMerged.RemoveFirst();
757           aChainCanMerged.Append(isToMerge);
758           aChainEdges.RemoveFirst();
759           aChainEdges.Append(aTmpShape);
760         }
761       }
762
763       // Merge parts of chain to be merged.
764       TColStd_ListIteratorOfListOfInteger aFlagIter(aChainCanMerged);
765       anIter.Initialize(aChainEdges);
766
767       while (anIter.More()) {
768         TopTools_SequenceOfShape aSeqEdges;
769
770         aSeqEdges.Append(anIter.Value());
771         aFlagIter.Next();
772         anIter.Next();
773
774         for (; anIter.More(); anIter.Next(), aFlagIter.Next()) {
775           if (aFlagIter.Value()) {
776             // Continue the chain.
777             aSeqEdges.Append(anIter.Value());
778           } else {
779             // Stop the chain.
780             break;
781           }
782         }
783
784         const Standard_Integer aNbEdges = aSeqEdges.Length();
785
786         if (aNbEdges > 1) {
787           // There are several edges to be merged.
788           TopoDS_Edge aMergedEdge;
789
790           if (MergeEdges(aSeqEdges, theTol, aMergedEdge)) {
791             isModified = Standard_True;
792             // now we have only one edge - aMergedEdge.
793             // we have to replace old ListEdges with this new edge
794             const TopoDS_Shape &anEdge = aSeqEdges.Value(1);
795
796             aContext->Replace(anEdge, aMergedEdge);
797
798             for (Standard_Integer j = 2; j <= aNbEdges; j++) {
799               aContext->Remove(aSeqEdges(j));
800             }
801
802             // Fix affected faces.
803             if (aMapEdgeFaces.Contains(anEdge)) {
804               const TopTools_ListOfShape &aList =
805                 aMapEdgeFaces.FindFromKey(anEdge);
806               TopTools_ListIteratorOfListOfShape anIter(aList);
807
808               for (; anIter.More(); anIter.Next()) {
809                 aModifiedFaces.Add(anIter.Value());
810               }
811             }
812           }
813         }
814       }
815     }
816   }
817
818   if (isModified) {
819     // Fix modified faces.
820     TopTools_MapIteratorOfMapOfShape aModifIt(aModifiedFaces);
821
822     for (; aModifIt.More(); aModifIt.Next()) {
823       TopoDS_Face aModifiedFace =
824         TopoDS::Face(aContext->Apply(aModifIt.Key()));
825       Handle(ShapeFix_Face) aSff = new ShapeFix_Face(aModifiedFace);
826
827       aSff->SetContext(aContext);
828       aSff->SetPrecision(theTol);
829       aSff->SetMinTolerance(theTol);
830       aSff->SetMaxTolerance(Max(1., theTol*1000.));
831       aSff->Perform();
832       aContext->Replace(aModifiedFace, aSff->Face());
833     }
834
835     // Check if the result shape contains shells.
836     // If yes, fix the faces orientation in the shell.
837     TopoDS_Shape    aModifShape = aContext->Apply(theShape);
838     TopExp_Explorer anExpSh(aModifShape, TopAbs_SHELL);
839
840     for (; anExpSh.More(); anExpSh.Next()) {
841       TopoDS_Shell           aShell = TopoDS::Shell(anExpSh.Current());
842       Handle(ShapeFix_Shell) aSfsh = new ShapeFix_Shell;
843
844       aSfsh->FixFaceOrientation(aShell);
845       aContext->Replace(aShell, aSfsh->Shell());
846     }
847   }
848
849   const TopoDS_Shape aResult = aContext->Apply(theShape);
850
851   return aResult;
852 }