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