Salome HOME
0023451: EDF - Remove Extra edges
[modules/geom.git] / src / BlockFix / BlockFix_UnionFaces.cxx
1 // Copyright (C) 2007-2016  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_UnionFaces.cxx
24 //  Created: Tue Dec  7 17:15:42 2004
25 //  Author:  Pavel DURANDIN
26
27 #include <BlockFix_UnionFaces.hxx>
28
29 #include <Basics_OCCTVersion.hxx>
30
31 #include <ShapeAnalysis_WireOrder.hxx>
32 #include <ShapeAnalysis_Edge.hxx>
33
34 #include <ShapeBuild_Edge.hxx>
35 #include <ShapeBuild_ReShape.hxx>
36
37 #include <ShapeExtend_WireData.hxx>
38 #include <ShapeExtend_CompositeSurface.hxx>
39
40 #include <ShapeFix_Face.hxx>
41 #include <ShapeFix_ComposeShell.hxx>
42 #include <ShapeFix_SequenceOfWireSegment.hxx>
43 #include <ShapeFix_WireSegment.hxx>
44 #include <ShapeFix_Wire.hxx>
45 #include <ShapeFix_Edge.hxx>
46
47 #include <IntPatch_ImpImpIntersection.hxx>
48
49 #include <BRep_Tool.hxx>
50 #include <BRep_Builder.hxx>
51 #include <BRepTools.hxx>
52 #include <BRepTopAdaptor_TopolTool.hxx>
53
54 #include <TopExp.hxx>
55 #include <TopExp_Explorer.hxx>
56
57 #include <TopTools_SequenceOfShape.hxx>
58 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
59 #include <TopTools_ListOfShape.hxx>
60 #include <TopTools_ListIteratorOfListOfShape.hxx>
61 #include <TopTools_MapOfShape.hxx>
62 #include <TopTools_MapIteratorOfMapOfShape.hxx>
63
64 #include <TopoDS.hxx>
65 #include <TopoDS_Edge.hxx>
66 #include <TopoDS_Wire.hxx>
67 #include <TopoDS_Face.hxx>
68 #include <TopoDS_Solid.hxx>
69 #include <TopoDS_Vertex.hxx>
70 #include <TopoDS_Shell.hxx>
71 #include <TopoDS_Iterator.hxx>
72 #include <TopoDS_Shape.hxx>
73
74 #include <TColGeom_HArray2OfSurface.hxx>
75
76 #include <GeomAdaptor_HSurface.hxx>
77 #include <GeomLib_IsPlanarSurface.hxx>
78
79 #include <Geom_Surface.hxx>
80 #include <Geom_Plane.hxx>
81 #include <Geom_OffsetSurface.hxx>
82 #include <Geom_SphericalSurface.hxx>
83 #include <Geom_CylindricalSurface.hxx>
84 #include <Geom_SurfaceOfRevolution.hxx>
85 #include <Geom_SurfaceOfLinearExtrusion.hxx>
86 #include <Geom_RectangularTrimmedSurface.hxx>
87 #include <BRepAdaptor_Surface.hxx>
88 #include <BRepAdaptor_HSurface.hxx>
89 #include <LocalAnalysis_SurfaceContinuity.hxx>
90 #include <GeomConvert_ApproxSurface.hxx>
91
92 #include <Geom_Curve.hxx>
93 #include <Geom_Line.hxx>
94 #include <Geom_Circle.hxx>
95
96 #include <Geom2d_Line.hxx>
97
98 #include <gp_XY.hxx>
99 #include <gp_Pnt2d.hxx>
100
101 #include <Standard_Failure.hxx>
102 #include <Standard_ErrorHandler.hxx> // CAREFUL ! position of this file is critic : see Lucien PIGNOLONI / OCC
103
104 //=======================================================================
105 //function : BlockFix_UnionFaces
106 //purpose  :
107 //=======================================================================
108 BlockFix_UnionFaces::BlockFix_UnionFaces()
109   : myTolerance(Precision::Confusion()),
110     myOptimumNbFaces(6)
111 {
112 }
113
114 //=======================================================================
115 //function : GetTolerance
116 //purpose  :
117 //=======================================================================
118 Standard_Real& BlockFix_UnionFaces::GetTolerance()
119 {
120   return myTolerance;
121 }
122
123 //=======================================================================
124 //function : GetOptimumNbFaces
125 //purpose  :
126 //=======================================================================
127 Standard_Integer& BlockFix_UnionFaces::GetOptimumNbFaces()
128 {
129   return myOptimumNbFaces;
130 }
131
132 //=======================================================================
133 //function : AddOrdinaryEdges
134 //purpose  : auxiliary
135 //           adds edges from the shape to the sequence
136 //           seams and equal edges are dropped
137 //           Returns true if one of original edges dropped
138 //=======================================================================
139 static Standard_Boolean AddOrdinaryEdges(TopTools_SequenceOfShape& edges,
140                                          const TopoDS_Shape aShape,
141                                          Standard_Integer& anIndex)
142 {
143   //map of edges
144   TopTools_MapOfShape aNewEdges;
145   TopExp_Explorer exp(aShape,TopAbs_EDGE);
146   //add edges without seams
147   for(; exp.More(); exp.Next()) {
148     TopoDS_Shape edge = exp.Current();
149     if(aNewEdges.Contains(edge))
150       aNewEdges.Remove(edge);
151     else
152       aNewEdges.Add(edge);
153   }
154
155   Standard_Boolean isDropped = Standard_False;
156   //merge edges and drop seams
157   for(Standard_Integer i = 1; i <= edges.Length(); i++) {
158     TopoDS_Shape current = edges(i);
159     if(aNewEdges.Contains(current)) {
160
161       aNewEdges.Remove(current);
162       edges.Remove(i);
163       i--;
164
165       if(!isDropped) {
166         isDropped = Standard_True;
167         anIndex = i;
168       }
169     }
170   }
171
172   //add edges to the sequence
173   for(exp.ReInit(); exp.More(); exp.Next()) {
174     const TopoDS_Shape &anEdge = exp.Current();
175
176     if (aNewEdges.Contains(anEdge)) {
177       edges.Append(anEdge);
178     }
179   }
180
181   return isDropped;
182 }
183
184 //=======================================================================
185 //function : ClearRts
186 //purpose  : auxiliary
187 //=======================================================================
188 static Handle(Geom_Surface) ClearRts(const Handle(Geom_Surface)& aSurface)
189 {
190   if(aSurface->IsKind(STANDARD_TYPE(Geom_RectangularTrimmedSurface))) {
191     Handle(Geom_RectangularTrimmedSurface) rts =
192       Handle(Geom_RectangularTrimmedSurface)::DownCast(aSurface);
193     return rts->BasisSurface();
194   }
195   return aSurface;
196 }
197
198 //=======================================================================
199 //function : IsFacesOfSameSolids
200 //purpose  : auxiliary
201 //=======================================================================
202 static Standard_Boolean IsFacesOfSameSolids
203        (const TopoDS_Face                               &theFace1,
204         const TopoDS_Face                               &theFace2,
205         const TopTools_IndexedDataMapOfShapeListOfShape &theMapFaceSolids)
206 {
207   Standard_Boolean isSame = Standard_False;
208
209   if (theMapFaceSolids.Contains(theFace1) &&
210       theMapFaceSolids.Contains(theFace2)) {
211     const TopTools_ListOfShape& aList1 = theMapFaceSolids.FindFromKey(theFace1);
212     const TopTools_ListOfShape& aList2 = theMapFaceSolids.FindFromKey(theFace2);
213
214     if (aList1.Extent() == aList2.Extent()) {
215       TopTools_ListIteratorOfListOfShape anIter1(aList1);
216
217       isSame = Standard_True;
218
219       for (; anIter1.More(); anIter1.Next()) {
220         const TopoDS_Shape                 &aSolid1 = anIter1.Value();
221         TopTools_ListIteratorOfListOfShape  anIter2(aList2);
222
223         for (; anIter2.More(); anIter2.Next()) {
224           if (aSolid1.IsSame(anIter2.Value())) {
225             // Same solid is detected. Break the loop
226             break;
227           }
228         }
229
230         if (!anIter2.More()) {
231           // No same solid is detected. Break the loop.
232           isSame = Standard_False;
233           break;
234         }
235       }
236     }
237   }
238
239   return isSame;
240 }
241
242 #if OCC_VERSION_LARGE > 0x07020001
243 // for Mantis issue 0023451 by JGV
244 //=======================================================================
245 //function : IsTangentFaces
246 //purpose  : decides: is edge on closed surface tangent or not
247 //=======================================================================
248 static Standard_Boolean IsTangentFaces(const TopoDS_Edge& theEdge,
249                                        const TopoDS_Face& theFace)
250 {
251   Standard_Real TolC0 = Max(0.001, 1.5*BRep_Tool::Tolerance(theEdge));
252
253   Standard_Real aFirst;
254   Standard_Real aLast;
255     
256 // Obtaining of pcurves of edge on two faces.
257   const Handle(Geom2d_Curve) aC2d1 = BRep_Tool::CurveOnSurface
258                                                 (theEdge, theFace, aFirst, aLast);
259   TopoDS_Edge ReversedEdge = theEdge;
260   ReversedEdge.Reverse();
261   const Handle(Geom2d_Curve) aC2d2 = BRep_Tool::CurveOnSurface
262                                                 (ReversedEdge, theFace, aFirst, aLast);
263   if (aC2d1.IsNull() || aC2d2.IsNull())
264     return Standard_False;
265
266 // Obtaining of two surfaces from adjacent faces.
267   Handle(Geom_Surface) aSurf = BRep_Tool::Surface(theFace);
268
269   if (aSurf.IsNull())
270     return Standard_False;
271
272 // Computation of the number of samples on the edge.
273   BRepAdaptor_Surface              aBAS(theFace);
274   Handle(BRepAdaptor_HSurface)     aBAHS      = new BRepAdaptor_HSurface(aBAS);
275   Handle(BRepTopAdaptor_TopolTool) aTool      = new BRepTopAdaptor_TopolTool(aBAHS);
276   Standard_Integer                 aNbSamples =     aTool->NbSamples();
277   const Standard_Integer           aNbSamplesMax =   23;
278   aNbSamples = Min(aNbSamplesMax, aNbSamples);
279   const Standard_Real              aTolAngle   =     M_PI/18;
280
281
282 // Computation of the continuity.
283   Standard_Real    aPar;
284   Standard_Real    aDelta = (aLast - aFirst)/(aNbSamples - 1);
285   Standard_Integer i, nbNotDone = 0;
286
287   for (i = 1, aPar = aFirst; i <= aNbSamples; i++, aPar += aDelta) {
288     if (i == aNbSamples) aPar = aLast;
289
290     LocalAnalysis_SurfaceContinuity aCont(aC2d1,  aC2d2,  aPar,
291                                           aSurf, aSurf, GeomAbs_G1,
292                                           0.001, TolC0, aTolAngle, 0.1, 0.1);
293     if (!aCont.IsDone()) 
294     {
295       nbNotDone++;
296       continue;
297     }
298
299     if (!aCont.IsG1())
300       return Standard_False;
301   }
302   
303   if (nbNotDone == aNbSamples)
304     return Standard_False;
305
306   return Standard_True;
307 }
308
309 //=======================================================================
310 //function : HasSeamEdge
311 //purpose  : Detects if a face contains a seam edge
312 //=======================================================================
313 static Standard_Boolean HasSeamEdge(const TopoDS_Face& theFace)
314 {
315   TopExp_Explorer Explo(theFace, TopAbs_EDGE);
316   for (; Explo.More(); Explo.Next())
317   {
318     const TopoDS_Edge& anEdge = TopoDS::Edge(Explo.Current());
319     if (BRepTools::IsReallyClosed(anEdge, theFace))
320       return Standard_True;
321   }
322
323   return Standard_False;
324 }
325 #endif
326
327 //=======================================================================
328 //function : IsEdgeValidToMerge
329 //purpose  : Edge is valid if it is not seam or if it is a seam and the face
330 //           has another seam edge.
331 //=======================================================================
332 #if OCC_VERSION_LARGE > 0x07020001
333 // for Mantis issue 0023451 by JGV
334 static Standard_Boolean IsEdgeValidToMerge(const TopoDS_Edge& theEdge,
335                                            const TopoDS_Face& theFace,
336                                            const Handle(Geom_Surface)& theSurface,
337                                            Standard_Boolean& theIsEdgeOnSeam,
338                                            Standard_Boolean& theToMakeUPeriodic,
339                                            Standard_Boolean& theToMakeVPeriodic)
340 {
341   Standard_Boolean isValid = Standard_True;
342
343   theIsEdgeOnSeam |= BRep_Tool::IsClosed(theEdge, theFace);
344   
345   if (BRepTools::IsReallyClosed(theEdge, theFace)) {
346     // Mantis issue 0023451, now code corresponds to the comment to this method
347     isValid = Standard_False;
348
349     // This is a seam edge. Check if there are another seam edges on the face.
350     TopExp_Explorer anExp(theFace, TopAbs_EDGE);
351
352     for (; anExp.More(); anExp.Next()) {
353       const TopoDS_Shape &aShEdge = anExp.Current();
354
355       // Skip same edge.
356       if (theEdge.IsSame(aShEdge)) {
357         continue;
358       }
359
360       // Check if this edge is a seam.
361       TopoDS_Edge anEdge = TopoDS::Edge(aShEdge);
362
363       if (BRep_Tool::IsClosed(anEdge, theFace)) {
364         // Mantis issue 0023451, now code corresponds to the comment to this method
365         //isValid = Standard_False;
366         isValid = Standard_True;
367         break;
368       }
369     }
370   }
371   else if (theIsEdgeOnSeam)
372   {
373     Standard_Real fpar, lpar;
374     Handle(Geom2d_Curve) aPCurve = BRep_Tool::CurveOnSurface(theEdge, theFace, fpar, lpar);
375     gp_Pnt2d P2d1 = aPCurve->Value(fpar);
376     gp_Pnt2d P2d2 = aPCurve->Value(lpar);
377     if (!theSurface->IsUPeriodic() &&
378         theSurface->IsUClosed() &&
379         Abs(P2d1.X() - P2d2.X()) < Abs(P2d1.Y() - P2d2.Y()))
380     {
381       if (IsTangentFaces(theEdge, theFace))
382         theToMakeUPeriodic = Standard_True;
383       else
384         isValid = Standard_False;
385     }
386     if (!theSurface->IsVPeriodic() &&
387         theSurface->IsVClosed() &&
388         Abs(P2d1.Y() - P2d2.Y()) < Abs(P2d1.X() - P2d2.X()))
389     {
390       if (IsTangentFaces(theEdge, theFace))
391         theToMakeVPeriodic = Standard_True;
392       else
393         isValid = Standard_False;
394     }
395   }
396
397   return isValid;
398 }
399 #else
400 static Standard_Boolean IsEdgeValidToMerge(const TopoDS_Edge &theEdge,
401                                            const TopoDS_Face &theFace)
402 {
403   Standard_Boolean isValid = Standard_True;
404
405   if (BRep_Tool::IsClosed(theEdge, theFace)) {
406     // This is a seam edge. Check if there are another seam edges on the face.
407     TopExp_Explorer anExp(theFace, TopAbs_EDGE);
408
409     for (; anExp.More(); anExp.Next()) {
410       const TopoDS_Shape &aShEdge = anExp.Current();
411
412       // Skip same edge.
413       if (theEdge.IsSame(aShEdge)) {
414         continue;
415       }
416
417       // Check if this edge is a seam.
418       TopoDS_Edge anEdge = TopoDS::Edge(aShEdge);
419
420       if (BRep_Tool::IsClosed(anEdge, theFace)) {
421         isValid = Standard_False;
422         break;
423       }
424     }
425   }
426
427   return isValid;
428 }
429 #endif
430
431 //=======================================================================
432 //function : Perform
433 //purpose  :
434 //=======================================================================
435 TopoDS_Shape BlockFix_UnionFaces::Perform(const TopoDS_Shape& Shape)
436 {
437   // Fill Map of faces as keys and list of solids or shells as items.
438   TopTools_IndexedDataMapOfShapeListOfShape aMapFaceSoOrSh;
439
440   TopAbs_ShapeEnum aType = Shape.ShapeType();
441
442   if (aType != TopAbs_SHELL) {
443     aType = TopAbs_SOLID;
444   }
445
446   TopExp::MapShapesAndAncestors
447     (Shape, TopAbs_FACE, aType, aMapFaceSoOrSh);
448
449   // processing each solid
450   Handle(ShapeBuild_ReShape) aContext = new ShapeBuild_ReShape;
451   TopTools_MapOfShape aProcessed;
452   TopExp_Explorer exps;
453   for (exps.Init(Shape, aType); exps.More(); exps.Next()) {
454     TopoDS_Shape aSoOrSh = exps.Current();
455
456     // creating map of edge faces
457     TopTools_IndexedDataMapOfShapeListOfShape aMapEdgeFaces;
458     TopExp::MapShapesAndAncestors(aSoOrSh, TopAbs_EDGE, TopAbs_FACE, aMapEdgeFaces);
459
460     Standard_Integer NbModif = 0;
461     Standard_Boolean hasFailed = Standard_False;
462     Standard_Real tol = Min(Max(Precision::Confusion(), myTolerance/10.), 0.1);
463
464     // count faces
465     int nbf = 0;
466     TopExp_Explorer exp;
467     TopTools_MapOfShape mapF;
468     for (exp.Init(aSoOrSh, TopAbs_FACE); exp.More(); exp.Next()) {
469       if (mapF.Add(exp.Current()))
470         nbf++;
471     }
472
473     bool doUnion = ((myOptimumNbFaces == 0) ||
474                     ((myOptimumNbFaces > 0) && (nbf > myOptimumNbFaces)));
475
476     // processing each face
477     mapF.Clear();
478     for (exp.Init(aSoOrSh, TopAbs_FACE); exp.More() && doUnion; exp.Next()) {
479       TopoDS_Face aFace = TopoDS::Face(exp.Current().Oriented(TopAbs_FORWARD));
480
481       if (aProcessed.Contains(aFace)) {
482         continue;
483       }
484
485       Standard_Integer dummy;
486       TopTools_SequenceOfShape edges;
487       AddOrdinaryEdges(edges,aFace,dummy);
488
489       TopTools_SequenceOfShape faces;
490       faces.Append(aFace);
491
492       //surface and location to construct result
493       TopLoc_Location aBaseLocation;
494       Handle(Geom_Surface) aBaseSurface = BRep_Tool::Surface(aFace,aBaseLocation);
495       aBaseSurface = ClearRts(aBaseSurface);
496       aBaseSurface = Handle(Geom_Surface)::DownCast(aBaseSurface->Copy());
497 #if OCC_VERSION_LARGE > 0x07020001
498 // for Mantis issue 0023451 by JGV
499       Standard_Boolean ToMakeUPeriodic = Standard_False, ToMakeVPeriodic = Standard_False;
500 #endif
501
502       // find adjacent faces to union
503       Standard_Integer i;
504       for (i = 1; i <= edges.Length(); i++) {
505         TopoDS_Edge edge = TopoDS::Edge(edges(i));
506 #if OCC_VERSION_LARGE > 0x07020001
507 // for Mantis issue 0023451 by JGV
508         Standard_Boolean IsEdgeOnSeam = Standard_False;
509 #endif
510         if (BRep_Tool::Degenerated(edge) ||
511 #if OCC_VERSION_LARGE > 0x07020001
512 // for Mantis issue 0023451 by JGV
513             !IsEdgeValidToMerge(edge, aFace, aBaseSurface, IsEdgeOnSeam, ToMakeUPeriodic, ToMakeVPeriodic))
514 #else
515             !IsEdgeValidToMerge(edge, aFace))
516 #endif
517           continue;
518
519         const TopTools_ListOfShape& aList = aMapEdgeFaces.FindFromKey(edge);
520         TopTools_ListIteratorOfListOfShape anIter(aList);
521         for (; anIter.More(); anIter.Next()) {
522           TopoDS_Face anCheckedFace = TopoDS::Face(anIter.Value().Oriented(TopAbs_FORWARD));
523           if (anCheckedFace.IsSame(aFace))
524             continue;
525
526           if (aProcessed.Contains(anCheckedFace))
527             continue;
528
529 #if OCC_VERSION_LARGE > 0x07020001
530 // for Mantis issue 0023451 by JGV
531           if (!IsEdgeValidToMerge(edge, anCheckedFace, aBaseSurface,
532                                   IsEdgeOnSeam, ToMakeUPeriodic, ToMakeVPeriodic)) {
533 #else
534           if (!IsEdgeValidToMerge(edge, anCheckedFace)) {
535 #endif
536             // Skip seam edge.
537             continue;
538           }
539
540           // Check if faces belong to same solids.
541           if (!IsFacesOfSameSolids(aFace, anCheckedFace, aMapFaceSoOrSh)) {
542             continue;
543           }
544
545           if (IsSameDomain(aFace,anCheckedFace)) {
546
547             if (aList.Extent() != 2) {
548               // non mainfold case is not processed
549               continue;
550             }
551
552 #if OCC_VERSION_LARGE > 0x07020001
553 // for Mantis issue 0023451 by JGV
554             //Prevent creating a face with parametric range more than period
555             if (IsEdgeOnSeam &&
556                 (HasSeamEdge(aFace) || HasSeamEdge(anCheckedFace)))
557               continue;
558 #endif
559
560             // replacing pcurves
561             TopoDS_Face aMockUpFace;
562             BRep_Builder B;
563             B.MakeFace(aMockUpFace,aBaseSurface,aBaseLocation,0.);
564             MovePCurves(aMockUpFace,anCheckedFace);
565
566             if (AddOrdinaryEdges(edges,aMockUpFace,dummy)) {
567               // sequence edges is modified
568               i = dummy;
569             }
570
571             faces.Append(anCheckedFace);
572             aProcessed.Add(anCheckedFace);
573             break;
574           }
575         }
576       }
577
578       // all faces collected in the sequence. Perform union of faces
579       if (faces.Length() > 1) {
580         NbModif++;
581         TopoDS_Face aResult;
582         BRep_Builder B;
583 #if OCC_VERSION_LARGE > 0x07020001
584 // for Mantis issue 0023451 by JGV
585         if (ToMakeUPeriodic || ToMakeVPeriodic)
586         {
587           Handle(Geom_BSplineSurface) aBSplineSurface = Handle(Geom_BSplineSurface)::DownCast(aBaseSurface);
588           if (aBSplineSurface.IsNull())
589           {
590             Standard_Real aTol = 1.e-4;
591             GeomAbs_Shape aUCont = GeomAbs_C1, aVCont = GeomAbs_C1;
592             Standard_Integer degU = 14, degV = 14;
593             Standard_Integer nmax = 16;
594             Standard_Integer aPrec = 1;  
595             GeomConvert_ApproxSurface Approximator(aBaseSurface,aTol,aUCont,aVCont,degU,degV,nmax,aPrec);
596             aBSplineSurface = Approximator.Surface();
597           }
598           
599           if (ToMakeUPeriodic)
600             aBSplineSurface->SetUPeriodic();
601           if (ToMakeVPeriodic)
602             aBSplineSurface->SetVPeriodic();
603           
604           aBaseSurface = aBSplineSurface;
605         }
606 #endif
607         B.MakeFace(aResult,aBaseSurface,aBaseLocation,0);
608         Standard_Integer nbWires = 0;
609
610         // connecting wires
611         while (edges.Length()>0) {
612
613           Standard_Boolean isEdge3d = Standard_False;
614           nbWires++;
615           TopTools_MapOfShape aVertices;
616           TopoDS_Wire aWire;
617           B.MakeWire(aWire);
618
619           TopoDS_Edge anEdge = TopoDS::Edge(edges(1));
620           edges.Remove(1);
621
622           isEdge3d |= !BRep_Tool::Degenerated(anEdge);
623           B.Add(aWire,anEdge);
624           TopoDS_Vertex V1,V2;
625           TopExp::Vertices(anEdge,V1,V2);
626           aVertices.Add(V1);
627           aVertices.Add(V2);
628
629           Standard_Boolean isNewFound = Standard_False;
630           do {
631             isNewFound = Standard_False;
632             for(Standard_Integer j = 1; j <= edges.Length(); j++) {
633               anEdge = TopoDS::Edge(edges(j));
634               TopExp::Vertices(anEdge,V1,V2);
635               if(aVertices.Contains(V1) || aVertices.Contains(V2)) {
636                 isEdge3d |= !BRep_Tool::Degenerated(anEdge);
637                 aVertices.Add(V1);
638                 aVertices.Add(V2);
639                 B.Add(aWire,anEdge);
640                 edges.Remove(j);
641                 j--;
642                 isNewFound = Standard_True;
643               }
644             }
645           } while (isNewFound);
646
647           // sorting any type of edges
648           aWire = TopoDS::Wire(aContext->Apply(aWire));
649
650           Handle(ShapeFix_Wire) sfw = new ShapeFix_Wire(aWire,aResult,Precision::Confusion());
651           sfw->FixReorder();
652           Standard_Boolean isDegRemoved = Standard_False;
653           if(!sfw->StatusReorder ( ShapeExtend_FAIL )) {
654             // clear degenerated edges if at least one with 3d curve exist
655             if(isEdge3d) {
656               Handle(ShapeExtend_WireData) sewd = sfw->WireData();
657               for(Standard_Integer j = 1; j<=sewd->NbEdges();j++) {
658                 TopoDS_Edge E = sewd->Edge(j);
659                 if(BRep_Tool::Degenerated(E)) {
660                   sewd->Remove(j);
661                   isDegRemoved = Standard_True;
662                   j--;
663                 }
664               }
665             }
666             sfw->FixShifted();
667             if(isDegRemoved)
668               sfw->FixDegenerated();
669           }
670           TopoDS_Wire aWireFixed = sfw->Wire();
671           aContext->Replace(aWire,aWireFixed);
672           // add resulting wire
673           if(isEdge3d) {
674             B.Add(aResult,aWireFixed);
675           }
676           else  {
677             // sorting edges
678             Handle(ShapeExtend_WireData) sbwd = sfw->WireData();
679             Standard_Integer nbEdges = sbwd->NbEdges();
680             // sort degenerated edges and create one edge instead of several ones
681             ShapeAnalysis_WireOrder sawo(Standard_False, 0);
682             ShapeAnalysis_Edge sae;
683             Standard_Integer aLastEdge = nbEdges;
684             for(Standard_Integer j = 1; j <= nbEdges; j++) {
685               Standard_Real f,l;
686               //smh protection on NULL pcurve
687               Handle(Geom2d_Curve) c2d;
688               if(!sae.PCurve(sbwd->Edge(j),aResult,c2d,f,l)) {
689                 aLastEdge--;
690                 continue;
691               }
692               sawo.Add(c2d->Value(f).XY(),c2d->Value(l).XY());
693             }
694             sawo.Perform();
695
696             // constructind one degenerative edge
697             gp_XY aStart, anEnd, tmp;
698             Standard_Integer nbFirst = sawo.Ordered(1);
699             TopoDS_Edge anOrigE = TopoDS::Edge(sbwd->Edge(nbFirst).Oriented(TopAbs_FORWARD));
700             ShapeBuild_Edge sbe;
701             TopoDS_Vertex aDummyV;
702             TopoDS_Edge E = sbe.CopyReplaceVertices(anOrigE,aDummyV,aDummyV);
703             sawo.XY(nbFirst,aStart,tmp);
704             sawo.XY(sawo.Ordered(aLastEdge),tmp,anEnd);
705
706             gp_XY aVec = anEnd-aStart;
707             Handle(Geom2d_Line) aLine = new Geom2d_Line(aStart,gp_Dir2d(anEnd-aStart));
708
709             B.UpdateEdge(E,aLine,aResult,0.);
710             B.Range(E,aResult,0.,aVec.Modulus());
711             Handle(Geom_Curve) C3d;
712             B.UpdateEdge(E,C3d,0.);
713             B.Degenerated(E,Standard_True);
714             TopoDS_Wire aW;
715             B.MakeWire(aW);
716             B.Add(aW,E);
717             B.Add(aResult,aW);
718           }
719         }
720
721         // perform substitution of face
722         aContext->Replace(aContext->Apply(aFace),aResult);
723
724         ShapeFix_Face sff (aResult);
725         //Intializing by tolerances
726         sff.SetPrecision(myTolerance);
727         sff.SetMinTolerance(tol);
728         sff.SetMaxTolerance(Max(1.,myTolerance*1000.));
729         //Setting modes
730         sff.FixOrientationMode() = 0;
731 #if OCC_VERSION_LARGE > 0x07020001
732         sff.FixWireTool()->CheckMissingEdgesMode() = Standard_False;
733 #endif
734         //sff.FixWireMode() = 0;
735         sff.SetContext(aContext);
736         // Applying the fixes
737         sff.Perform();
738         if(sff.Status(ShapeExtend_FAIL))
739         hasFailed = Standard_True;
740
741         // breaking down to several faces
742         TopoDS_Shape theResult = aContext->Apply(aResult);
743         for (TopExp_Explorer aFaceExp (theResult,TopAbs_FACE); aFaceExp.More(); aFaceExp.Next()) {
744           TopoDS_Face aCurrent = TopoDS::Face(aFaceExp.Current().Oriented(TopAbs_FORWARD));
745           Handle(TColGeom_HArray2OfSurface) grid = new TColGeom_HArray2OfSurface ( 1, 1, 1, 1 );
746           grid->SetValue ( 1, 1, aBaseSurface );
747           Handle(ShapeExtend_CompositeSurface) G = new ShapeExtend_CompositeSurface ( grid );
748           ShapeFix_ComposeShell CompShell;
749           CompShell.Init ( G, aBaseLocation, aCurrent, ::Precision::Confusion() );//myPrecision
750           CompShell.SetContext( aContext );
751
752           TopTools_SequenceOfShape parts;
753           ShapeFix_SequenceOfWireSegment wires;
754           for(TopExp_Explorer W_Exp(aCurrent,TopAbs_WIRE);W_Exp.More();W_Exp.Next()) {
755             Handle(ShapeExtend_WireData) sbwd =
756               new ShapeExtend_WireData ( TopoDS::Wire(W_Exp.Current() ));
757             ShapeFix_WireSegment seg ( sbwd, TopAbs_REVERSED );
758             wires.Append(seg);
759           }
760
761           CompShell.DispatchWires ( parts,wires );
762           for (Standard_Integer j=1; j <= parts.Length(); j++ ) {
763             ShapeFix_Face aFixOrient(TopoDS::Face(parts(j)));
764             aFixOrient.SetContext(aContext);
765             aFixOrient.FixOrientation();
766           }
767
768           TopoDS_Shape CompRes;
769           if ( faces.Length() !=1 ) {
770             TopoDS_Shell S;
771             B.MakeShell ( S );
772             for ( i=1; i <= parts.Length(); i++ )
773               B.Add ( S, parts(i) );
774             CompRes = S;
775           }
776           else CompRes = parts(1);
777
778           aContext->Replace(aCurrent,CompRes);
779         }
780
781         // remove the remaining faces
782         for(i = 2; i <= faces.Length(); i++)
783           aContext->Remove(faces(i));
784       }
785     } // end processing each face
786
787     //TopoDS_Shape aResult = Shape;
788     if (NbModif > 0 && !hasFailed) {
789       TopoDS_Shape aResult = aContext->Apply(aSoOrSh);
790
791       ShapeFix_Edge sfe;
792       for (exp.Init(aResult,TopAbs_EDGE); exp.More(); exp.Next()) {
793         TopoDS_Edge E = TopoDS::Edge(exp.Current());
794         sfe.FixVertexTolerance (E);
795         // ptv add fix same parameter
796         sfe.FixSameParameter(E, myTolerance);
797       }
798     }
799
800     for (exp.Init(aSoOrSh, TopAbs_FACE); exp.More(); exp.Next()) {
801       TopoDS_Face aFace = TopoDS::Face(exp.Current().Oriented(TopAbs_FORWARD));
802       Handle(ShapeFix_Wire) sfw = new ShapeFix_Wire;
803       sfw->SetContext(aContext);
804       sfw->SetPrecision(myTolerance);
805       sfw->SetMinTolerance(myTolerance);
806       sfw->SetMaxTolerance(Max(1.,myTolerance*1000.));
807       sfw->SetFace(aFace);
808       for (TopoDS_Iterator iter (aFace,Standard_False); iter.More(); iter.Next()) {
809         TopoDS_Shape aFaceCont = iter.Value();
810         if (!aFaceCont.IsNull() && aFaceCont.ShapeType() == TopAbs_WIRE) {
811           TopoDS_Wire wire = TopoDS::Wire(iter.Value());
812           sfw->Load(wire);
813           sfw->FixReorder();
814           sfw->FixShifted();
815         }
816       }
817     }
818   } // end processing each solid
819
820   const TopoDS_Shape aResShape = aContext->Apply(Shape);
821
822   return aResShape;
823 }
824
825 //=======================================================================
826 //function : IsSameDomain
827 //purpose  :
828 //=======================================================================
829 bool getCylinder (Handle(Geom_Surface)& theInSurface, gp_Cylinder& theOutCylinder)
830 {
831   bool isCylinder = false;
832
833   if (theInSurface->IsKind(STANDARD_TYPE(Geom_CylindricalSurface))) {
834     Handle(Geom_CylindricalSurface) aGC = Handle(Geom_CylindricalSurface)::DownCast(theInSurface);
835
836     theOutCylinder = aGC->Cylinder();
837     isCylinder = true;
838   }
839   else if (theInSurface->IsKind(STANDARD_TYPE(Geom_SurfaceOfRevolution))) {
840     Handle(Geom_SurfaceOfRevolution) aRS =
841       Handle(Geom_SurfaceOfRevolution)::DownCast(theInSurface);
842     Handle(Geom_Curve) aBasis = aRS->BasisCurve();
843     if (aBasis->IsKind(STANDARD_TYPE(Geom_Line))) {
844       Handle(Geom_Line) aBasisLine = Handle(Geom_Line)::DownCast(aBasis);
845       gp_Dir aDir = aRS->Direction();
846       gp_Dir aBasisDir = aBasisLine->Position().Direction();
847       if (aBasisDir.IsParallel(aDir, Precision::Confusion())) {
848         // basis line is parallel to the revolution axis: it is a cylinder
849         gp_Pnt aLoc = aRS->Location();
850         Standard_Real aR = aBasisLine->Lin().Distance(aLoc);
851         gp_Ax3 aCylAx (aLoc, aDir);
852
853         theOutCylinder = gp_Cylinder(aCylAx, aR);
854         isCylinder = true;
855       }
856     }
857   }
858   else if (theInSurface->IsKind(STANDARD_TYPE(Geom_SurfaceOfLinearExtrusion))) {
859     Handle(Geom_SurfaceOfLinearExtrusion) aLES =
860       Handle(Geom_SurfaceOfLinearExtrusion)::DownCast(theInSurface);
861     Handle(Geom_Curve) aBasis = aLES->BasisCurve();
862     if (aBasis->IsKind(STANDARD_TYPE(Geom_Circle))) {
863       Handle(Geom_Circle) aBasisCircle = Handle(Geom_Circle)::DownCast(aBasis);
864       gp_Dir aDir = aLES->Direction();
865       gp_Dir aBasisDir = aBasisCircle->Position().Direction();
866       if (aBasisDir.IsParallel(aDir, Precision::Confusion())) {
867         // basis circle is normal to the extrusion axis: it is a cylinder
868         gp_Pnt aLoc = aBasisCircle->Location();
869         Standard_Real aR = aBasisCircle->Radius();
870         gp_Ax3 aCylAx (aLoc, aDir);
871
872         theOutCylinder = gp_Cylinder(aCylAx, aR);
873         isCylinder = true;
874       }
875     }
876   }
877   else {
878   }
879
880   return isCylinder;
881 }
882
883 Standard_Boolean BlockFix_UnionFaces::IsSameDomain(const TopoDS_Face& aFace,
884                                                    const TopoDS_Face& aCheckedFace) const
885 {
886   //checking the same handles
887   TopLoc_Location L1, L2;
888   Handle(Geom_Surface) S1, S2;
889
890   S1 = BRep_Tool::Surface(aFace,L1);
891   S2 = BRep_Tool::Surface(aCheckedFace,L2);
892
893   if (S1 == S2 && L1 == L2)
894     return true;
895
896   // planar and cylindrical cases (IMP 20052)
897   Standard_Real aPrec = Precision::Confusion();
898
899   S1 = BRep_Tool::Surface(aFace);
900   S2 = BRep_Tool::Surface(aCheckedFace);
901
902   S1 = ClearRts(S1);
903   S2 = ClearRts(S2);
904
905   //Handle(Geom_OffsetSurface) aGOFS1, aGOFS2;
906   //aGOFS1 = Handle(Geom_OffsetSurface)::DownCast(S1);
907   //aGOFS2 = Handle(Geom_OffsetSurface)::DownCast(S2);
908   //if (!aGOFS1.IsNull()) S1 = aGOFS1->BasisSurface();
909   //if (!aGOFS2.IsNull()) S2 = aGOFS2->BasisSurface();
910
911   // case of two elementary surfaces: use OCCT tool
912   // elementary surfaces: ConicalSurface, CylindricalSurface,
913   //                      Plane, SphericalSurface and ToroidalSurface
914   if (S1->IsKind(STANDARD_TYPE(Geom_ElementarySurface)) &&
915       S2->IsKind(STANDARD_TYPE(Geom_ElementarySurface)))
916   {
917     Handle(GeomAdaptor_HSurface) aGA1 = new GeomAdaptor_HSurface(S1);
918     Handle(GeomAdaptor_HSurface) aGA2 = new GeomAdaptor_HSurface(S2);
919
920     Handle(BRepTopAdaptor_TopolTool) aTT1 = new BRepTopAdaptor_TopolTool();
921     Handle(BRepTopAdaptor_TopolTool) aTT2 = new BRepTopAdaptor_TopolTool();
922
923     try {
924       OCC_CATCH_SIGNALS;
925
926       IntPatch_ImpImpIntersection anIIInt (aGA1, aTT1, aGA2, aTT2, aPrec, aPrec);
927
928       if (!anIIInt.IsDone() || anIIInt.IsEmpty())
929         return false;
930
931       return anIIInt.TangentFaces();
932     }
933     catch (Standard_Failure) {
934       return false;
935     }
936   }
937
938   // case of two planar surfaces:
939   // all kinds of surfaces checked, including b-spline and bezier
940   GeomLib_IsPlanarSurface aPlanarityChecker1 (S1, aPrec);
941   if (aPlanarityChecker1.IsPlanar()) {
942     GeomLib_IsPlanarSurface aPlanarityChecker2 (S2, aPrec);
943     if (aPlanarityChecker2.IsPlanar()) {
944       gp_Pln aPln1 = aPlanarityChecker1.Plan();
945       gp_Pln aPln2 = aPlanarityChecker2.Plan();
946
947       if (aPln1.Position().Direction().IsParallel(aPln2.Position().Direction(), aPrec) &&
948           aPln1.Distance(aPln2) < aPrec) {
949         return true;
950       }
951     }
952   }
953
954   // case of two cylindrical surfaces, at least one of which is a swept surface
955   // swept surfaces: SurfaceOfLinearExtrusion, SurfaceOfRevolution
956   if ((S1->IsKind(STANDARD_TYPE(Geom_CylindricalSurface)) ||
957        S1->IsKind(STANDARD_TYPE(Geom_SweptSurface))) &&
958       (S2->IsKind(STANDARD_TYPE(Geom_CylindricalSurface)) ||
959        S2->IsKind(STANDARD_TYPE(Geom_SweptSurface))))
960   {
961     gp_Cylinder aCyl1, aCyl2;
962     if (getCylinder(S1, aCyl1) && getCylinder(S2, aCyl2)) {
963       if (fabs(aCyl1.Radius() - aCyl2.Radius()) < aPrec) {
964         gp_Dir aDir1 = aCyl1.Position().Direction();
965         gp_Dir aDir2 = aCyl2.Position().Direction();
966         if (aDir1.IsParallel(aDir2, aPrec)) {
967           gp_Pnt aLoc1 = aCyl1.Location();
968           gp_Pnt aLoc2 = aCyl2.Location();
969           gp_Vec aVec12 (aLoc1, aLoc2);
970           if (aVec12.SquareMagnitude() < aPrec*aPrec ||
971               aVec12.IsParallel(aDir1, aPrec)) {
972             return true;
973           }
974         }
975       }
976     }
977   }
978
979   return false;
980 }
981
982 //=======================================================================
983 //function : MovePCurves
984 //purpose  :
985 //=======================================================================
986 void BlockFix_UnionFaces::MovePCurves(TopoDS_Face& aTarget,
987                                       const TopoDS_Face& aSource) const
988 {
989   BRep_Builder B;
990   for(TopExp_Explorer wexp(aSource,TopAbs_WIRE);wexp.More();wexp.Next()) {
991     Handle(ShapeFix_Wire) sfw = new ShapeFix_Wire(TopoDS::Wire(wexp.Current()),
992                                                   aTarget, Precision::Confusion());
993     sfw->FixReorder();
994     Standard_Boolean isReoredFailed = sfw->StatusReorder ( ShapeExtend_FAIL );
995     sfw->FixEdgeCurves();
996     if(isReoredFailed)
997       continue;
998
999     sfw->FixShifted();
1000     sfw->FixDegenerated();
1001
1002     // remove degenerated edges from not degenerated points
1003     ShapeAnalysis_Edge sae;
1004     Handle(ShapeExtend_WireData) sewd = sfw->WireData();
1005     for(Standard_Integer i = 1; i<=sewd->NbEdges();i++) {
1006       TopoDS_Edge E = sewd->Edge(i);
1007       if(BRep_Tool::Degenerated(E)&&!sae.HasPCurve(E,aTarget)) {
1008         sewd->Remove(i);
1009         i--;
1010       }
1011     }
1012
1013     TopoDS_Wire ResWire = sfw->Wire();
1014     B.Add(aTarget,ResWire);
1015   }
1016 }