Salome HOME
PR: distributed geom and smesh scripts: first step
[modules/geom.git] / src / GEOMAlgo / BlockFix_UnionFaces.cxx
1 // Copyright (C) 2007-2012  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.
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.ixx>
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 #if OCC_VERSION_LARGE > 0x06040000 // Porting to OCCT6.5.1
48 #include <IntPatch_ImpImpIntersection.hxx>
49 #else
50 #include <IntPatch_TheIIIntOfIntersection.hxx>
51 #endif
52
53 #include <BRep_Tool.hxx>
54 #include <BRep_Builder.hxx>
55 #include <BRepTools.hxx>
56 #include <BRepTopAdaptor_TopolTool.hxx>
57
58 #include <TopExp.hxx>
59 #include <TopExp_Explorer.hxx>
60
61 #include <TopTools_SequenceOfShape.hxx>
62 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
63 #include <TopTools_ListOfShape.hxx>
64 #include <TopTools_ListIteratorOfListOfShape.hxx>
65 #include <TopTools_MapOfShape.hxx>
66 #include <TopTools_MapIteratorOfMapOfShape.hxx>
67
68 #include <TopoDS.hxx>
69 #include <TopoDS_Edge.hxx>
70 #include <TopoDS_Wire.hxx>
71 #include <TopoDS_Face.hxx>
72 #include <TopoDS_Solid.hxx>
73 #include <TopoDS_Vertex.hxx>
74 #include <TopoDS_Shell.hxx>
75 #include <TopoDS_Iterator.hxx>
76
77 #include <TColGeom_HArray2OfSurface.hxx>
78
79 #include <GeomAdaptor_HSurface.hxx>
80 #include <GeomLib_IsPlanarSurface.hxx>
81
82 #include <Geom_Surface.hxx>
83 #include <Geom_Plane.hxx>
84 #include <Geom_OffsetSurface.hxx>
85 #include <Geom_SphericalSurface.hxx>
86 #include <Geom_CylindricalSurface.hxx>
87 #include <Geom_SurfaceOfRevolution.hxx>
88 #include <Geom_SurfaceOfLinearExtrusion.hxx>
89 #include <Geom_RectangularTrimmedSurface.hxx>
90
91 #include <Geom_Curve.hxx>
92 #include <Geom_Line.hxx>
93 #include <Geom_Circle.hxx>
94
95 #include <Geom2d_Line.hxx>
96
97 #include <gp_XY.hxx>
98 #include <gp_Pnt2d.hxx>
99
100 #include <Standard_Failure.hxx>
101 #include <Standard_ErrorHandler.hxx> // CAREFUL ! position of this file is critic : see Lucien PIGNOLONI / OCC
102
103 //=======================================================================
104 //function : BlockFix_UnionFaces
105 //purpose  :
106 //=======================================================================
107
108 BlockFix_UnionFaces::BlockFix_UnionFaces()
109   : myTolerance(Precision::Confusion()),
110     myOptimumNbFaces(6)
111 {
112 }
113
114
115 //=======================================================================
116 //function : GetTolerance
117 //purpose  :
118 //=======================================================================
119
120 Standard_Real& BlockFix_UnionFaces::GetTolerance()
121 {
122   return myTolerance;
123 }
124
125
126 //=======================================================================
127 //function : GetOptimumNbFaces
128 //purpose  :
129 //=======================================================================
130
131 Standard_Integer& BlockFix_UnionFaces::GetOptimumNbFaces()
132 {
133   return myOptimumNbFaces;
134 }
135
136
137 //=======================================================================
138 //function : AddOrdinaryEdges
139 //purpose  : auxilary
140 //=======================================================================
141 // adds edges from the shape to the sequence
142 // seams and equal edges are dropped
143 // Returns true if one of original edges dropped
144 static Standard_Boolean AddOrdinaryEdges(TopTools_SequenceOfShape& edges,
145                                          const TopoDS_Shape aShape,
146                                          Standard_Integer& anIndex)
147 {
148   //map of edges
149   TopTools_MapOfShape aNewEdges;
150   //add edges without seams
151   for(TopExp_Explorer exp(aShape,TopAbs_EDGE); exp.More(); exp.Next()) {
152     TopoDS_Shape edge = exp.Current();
153     if(aNewEdges.Contains(edge))
154       aNewEdges.Remove(edge);
155     else
156       aNewEdges.Add(edge);
157   }
158
159   Standard_Boolean isDropped = Standard_False;
160   //merge edges and drop seams
161   for(Standard_Integer i = 1; i <= edges.Length(); i++) {
162     TopoDS_Shape current = edges(i);
163     if(aNewEdges.Contains(current)) {
164
165       aNewEdges.Remove(current);
166       edges.Remove(i);
167       i--;
168
169       if(!isDropped) {
170         isDropped = Standard_True;
171         anIndex = i;
172       }
173     }
174   }
175
176   //add edges to the sequemce
177   for(TopTools_MapIteratorOfMapOfShape anIter(aNewEdges); anIter.More(); anIter.Next())
178     edges.Append(anIter.Key());
179
180   return isDropped;
181 }
182
183
184 //=======================================================================
185 //function : ClearRts
186 //purpose  : auxilary
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 //=======================================================================
200 //function : Perform
201 //purpose  :
202 //=======================================================================
203
204 TopoDS_Shape BlockFix_UnionFaces::Perform(const TopoDS_Shape& Shape)
205 {
206   Handle(ShapeBuild_ReShape) myContext = new ShapeBuild_ReShape;
207   TopoDS_Shape aResShape = myContext->Apply(Shape);
208
209   // processing each solid
210   TopExp_Explorer exps;
211   for (exps.Init(Shape, TopAbs_SOLID); exps.More(); exps.Next()) {
212     TopoDS_Solid aSolid = TopoDS::Solid(exps.Current());
213
214     // creating map of edge faces
215     TopTools_IndexedDataMapOfShapeListOfShape aMapEdgeFaces;
216     TopExp::MapShapesAndAncestors(aSolid, TopAbs_EDGE, TopAbs_FACE, aMapEdgeFaces);
217
218     // map of processed shapes
219     TopTools_MapOfShape aProcessed;
220
221     Handle(ShapeBuild_ReShape) aContext = new ShapeBuild_ReShape;
222
223     Standard_Integer NbModif = 0;
224     Standard_Boolean hasFailed = Standard_False;
225     Standard_Real tol = Min(Max(Precision::Confusion(), myTolerance/10.), 0.1);
226
227     // count faces
228     int nbf = 0;
229     TopExp_Explorer exp;
230     TopTools_MapOfShape mapF;
231     for (exp.Init(aSolid, TopAbs_FACE); exp.More(); exp.Next()) {
232       if (mapF.Add(exp.Current()))
233         nbf++;
234     }
235
236     bool doUnion = ((myOptimumNbFaces == 0) ||
237                     ((myOptimumNbFaces > 0) && (nbf > myOptimumNbFaces)));
238
239     // processing each face
240     mapF.Clear();
241     for (exp.Init(aSolid, TopAbs_FACE); exp.More() && doUnion; exp.Next()) {
242       TopoDS_Face aFace = TopoDS::Face(exp.Current().Oriented(TopAbs_FORWARD));
243
244       if (aProcessed.Contains(aFace))
245         continue;
246
247       Standard_Integer dummy;
248       TopTools_SequenceOfShape edges;
249       AddOrdinaryEdges(edges,aFace,dummy);
250
251       TopTools_SequenceOfShape faces;
252       faces.Append(aFace);
253
254       //surface and location to construct result
255       TopLoc_Location aBaseLocation;
256       Handle(Geom_Surface) aBaseSurface = BRep_Tool::Surface(aFace,aBaseLocation);
257       aBaseSurface = ClearRts(aBaseSurface);
258
259       // find adjacent faces to union
260       Standard_Integer i;
261       for (i = 1; i <= edges.Length(); i++) {
262         TopoDS_Edge edge = TopoDS::Edge(edges(i));
263         if (BRep_Tool::Degenerated(edge))
264           continue;
265
266         const TopTools_ListOfShape& aList = aMapEdgeFaces.FindFromKey(edge);
267         TopTools_ListIteratorOfListOfShape anIter(aList);
268         for (; anIter.More(); anIter.Next()) {
269           TopoDS_Face anCheckedFace = TopoDS::Face(anIter.Value().Oriented(TopAbs_FORWARD));
270           if (anCheckedFace.IsSame(aFace))
271             continue;
272
273           if (aProcessed.Contains(anCheckedFace))
274             continue;
275
276           if (IsSameDomain(aFace,anCheckedFace)) {
277
278             if (aList.Extent() != 2) {
279               // non mainfold case is not processed
280               continue;
281             }
282
283             // replacing pcurves
284             TopoDS_Face aMockUpFace;
285             BRep_Builder B;
286             B.MakeFace(aMockUpFace,aBaseSurface,aBaseLocation,0.);
287             MovePCurves(aMockUpFace,anCheckedFace);
288
289             if (AddOrdinaryEdges(edges,aMockUpFace,dummy)) {
290               // sequence edges is modified
291               i = dummy;
292             }
293
294             faces.Append(anCheckedFace);
295             aProcessed.Add(anCheckedFace);
296             break;
297           }
298         }
299       }
300
301       // all faces collected in the sequence. Perform union of faces
302       if (faces.Length() > 1) {
303         NbModif++;
304         TopoDS_Face aResult;
305         BRep_Builder B;
306         B.MakeFace(aResult,aBaseSurface,aBaseLocation,0);
307         Standard_Integer nbWires = 0;
308
309         // connecting wires
310         while (edges.Length()>0) {
311
312           Standard_Boolean isEdge3d = Standard_False;
313           nbWires++;
314           TopTools_MapOfShape aVertices;
315           TopoDS_Wire aWire;
316           B.MakeWire(aWire);
317
318           TopoDS_Edge anEdge = TopoDS::Edge(edges(1));
319           edges.Remove(1);
320
321           isEdge3d |= !BRep_Tool::Degenerated(anEdge);
322           B.Add(aWire,anEdge);
323           TopoDS_Vertex V1,V2;
324           TopExp::Vertices(anEdge,V1,V2);
325           aVertices.Add(V1);
326           aVertices.Add(V2);
327
328           Standard_Boolean isNewFound = Standard_False;
329           do {
330             isNewFound = Standard_False;
331             for(Standard_Integer j = 1; j <= edges.Length(); j++) {
332               anEdge = TopoDS::Edge(edges(j));
333               TopExp::Vertices(anEdge,V1,V2);
334               if(aVertices.Contains(V1) || aVertices.Contains(V2)) {
335                 isEdge3d |= !BRep_Tool::Degenerated(anEdge);
336                 aVertices.Add(V1);
337                 aVertices.Add(V2);
338                 B.Add(aWire,anEdge);
339                 edges.Remove(j);
340                 j--;
341                 isNewFound = Standard_True;
342               }
343             }
344           } while (isNewFound);
345
346           // sorting any type of edges
347           aWire = TopoDS::Wire(aContext->Apply(aWire));
348
349           TopoDS_Face tmpF = TopoDS::Face(aContext->Apply(faces(1).Oriented(TopAbs_FORWARD)));
350           Handle(ShapeFix_Wire) sfw = new ShapeFix_Wire(aWire,tmpF,Precision::Confusion());
351           sfw->FixReorder();
352           Standard_Boolean isDegRemoved = Standard_False;
353           if(!sfw->StatusReorder ( ShapeExtend_FAIL )) {
354             // clear degenerated edges if at least one with 3d curve exist
355             if(isEdge3d) {
356               Handle(ShapeExtend_WireData) sewd = sfw->WireData();
357               for(Standard_Integer j = 1; j<=sewd->NbEdges();j++) {
358                 TopoDS_Edge E = sewd->Edge(j);
359                 if(BRep_Tool::Degenerated(E)) {
360                   sewd->Remove(j);
361                   isDegRemoved = Standard_True;
362                   j--;
363                 }
364               }
365             }
366             sfw->FixShifted();
367             if(isDegRemoved)
368               sfw->FixDegenerated();
369           }
370           TopoDS_Wire aWireFixed = sfw->Wire();
371           aContext->Replace(aWire,aWireFixed);
372           // add resulting wire
373           if(isEdge3d) {
374             B.Add(aResult,aWireFixed);
375           }
376           else  {
377             // sorting edges
378             Handle(ShapeExtend_WireData) sbwd = sfw->WireData();
379             Standard_Integer nbEdges = sbwd->NbEdges();
380             // sort degenerated edges and create one edge instead of several ones
381             ShapeAnalysis_WireOrder sawo(Standard_False, 0);
382             ShapeAnalysis_Edge sae;
383             Standard_Integer aLastEdge = nbEdges;
384             for(Standard_Integer j = 1; j <= nbEdges; j++) {
385               Standard_Real f,l;
386               //smh protection on NULL pcurve
387               Handle(Geom2d_Curve) c2d;
388               if(!sae.PCurve(sbwd->Edge(j),tmpF,c2d,f,l)) {
389                 aLastEdge--;
390                 continue;
391               }
392               sawo.Add(c2d->Value(f).XY(),c2d->Value(l).XY());
393             }
394             sawo.Perform();
395
396             // constructind one degenerative edge
397             gp_XY aStart, anEnd, tmp;
398             Standard_Integer nbFirst = sawo.Ordered(1);
399             TopoDS_Edge anOrigE = TopoDS::Edge(sbwd->Edge(nbFirst).Oriented(TopAbs_FORWARD));
400             ShapeBuild_Edge sbe;
401             TopoDS_Vertex aDummyV;
402             TopoDS_Edge E = sbe.CopyReplaceVertices(anOrigE,aDummyV,aDummyV);
403             sawo.XY(nbFirst,aStart,tmp);
404             sawo.XY(sawo.Ordered(aLastEdge),tmp,anEnd);
405
406             gp_XY aVec = anEnd-aStart;
407             Handle(Geom2d_Line) aLine = new Geom2d_Line(aStart,gp_Dir2d(anEnd-aStart));
408
409             B.UpdateEdge(E,aLine,tmpF,0.);
410             B.Range(E,tmpF,0.,aVec.Modulus());
411             Handle(Geom_Curve) C3d;
412             B.UpdateEdge(E,C3d,0.);
413             B.Degenerated(E,Standard_True);
414             TopoDS_Wire aW;
415             B.MakeWire(aW);
416             B.Add(aW,E);
417             B.Add(aResult,aW);
418           }
419         }
420
421         // perform substitution of face
422         aContext->Replace(aContext->Apply(aFace),aResult);
423
424         ShapeFix_Face sff (aResult);
425         //Intializing by tolerances
426         sff.SetPrecision(myTolerance);
427         sff.SetMinTolerance(tol);
428         sff.SetMaxTolerance(Max(1.,myTolerance*1000.));
429         //Setting modes
430         sff.FixOrientationMode() = 0;
431         //sff.FixWireMode() = 0;
432         sff.SetContext(aContext);
433         // Applying the fixes
434         sff.Perform();
435         if(sff.Status(ShapeExtend_FAIL))
436         hasFailed = Standard_True;
437
438         // breaking down to several faces
439         TopoDS_Shape theResult = aContext->Apply(aResult);
440         for (TopExp_Explorer aFaceExp (theResult,TopAbs_FACE); aFaceExp.More(); aFaceExp.Next()) {
441           TopoDS_Face aCurrent = TopoDS::Face(aFaceExp.Current().Oriented(TopAbs_FORWARD));
442           Handle(TColGeom_HArray2OfSurface) grid = new TColGeom_HArray2OfSurface ( 1, 1, 1, 1 );
443           grid->SetValue ( 1, 1, aBaseSurface );
444           Handle(ShapeExtend_CompositeSurface) G = new ShapeExtend_CompositeSurface ( grid );
445           ShapeFix_ComposeShell CompShell;
446           CompShell.Init ( G, aBaseLocation, aCurrent, ::Precision::Confusion() );//myPrecision
447           CompShell.SetContext( aContext );
448
449           TopTools_SequenceOfShape parts;
450           ShapeFix_SequenceOfWireSegment wires;
451           for(TopExp_Explorer W_Exp(aCurrent,TopAbs_WIRE);W_Exp.More();W_Exp.Next()) {
452             Handle(ShapeExtend_WireData) sbwd =
453               new ShapeExtend_WireData ( TopoDS::Wire(W_Exp.Current() ));
454             ShapeFix_WireSegment seg ( sbwd, TopAbs_REVERSED );
455             wires.Append(seg);
456           }
457
458           CompShell.DispatchWires ( parts,wires );
459           for (Standard_Integer j=1; j <= parts.Length(); j++ ) {
460             ShapeFix_Face aFixOrient(TopoDS::Face(parts(j)));
461             aFixOrient.SetContext(aContext);
462             aFixOrient.FixOrientation();
463           }
464
465           TopoDS_Shape CompRes;
466           if ( faces.Length() !=1 ) {
467             TopoDS_Shell S;
468             B.MakeShell ( S );
469             for ( i=1; i <= parts.Length(); i++ )
470               B.Add ( S, parts(i) );
471             CompRes = S;
472           }
473           else CompRes = parts(1);
474
475           aContext->Replace(aCurrent,CompRes);
476         }
477
478         // remove the remaining faces
479         for(i = 2; i <= faces.Length(); i++)
480           aContext->Remove(faces(i));
481       }
482     } // end processing each face
483
484     //TopoDS_Shape aResult = Shape;
485     if (NbModif > 0 && !hasFailed) {
486       TopoDS_Shape aResult = aContext->Apply(aSolid);
487
488       ShapeFix_Edge sfe;
489       for (exp.Init(aResult,TopAbs_EDGE); exp.More(); exp.Next()) {
490         TopoDS_Edge E = TopoDS::Edge(exp.Current());
491         sfe.FixVertexTolerance (E);
492         // ptv add fix same parameter
493         sfe.FixSameParameter(E, myTolerance);
494       }
495
496       myContext->Replace(aSolid, aResult);
497     }
498     //else
499     {
500       for (exp.Init(aSolid, TopAbs_FACE); exp.More(); exp.Next()) {
501         TopoDS_Face aFace = TopoDS::Face(exp.Current().Oriented(TopAbs_FORWARD));
502         Handle(ShapeFix_Wire) sfw = new ShapeFix_Wire;
503         sfw->SetContext(myContext);
504         sfw->SetPrecision(myTolerance);
505         sfw->SetMinTolerance(myTolerance);
506         sfw->SetMaxTolerance(Max(1.,myTolerance*1000.));
507         sfw->SetFace(aFace);
508         for (TopoDS_Iterator iter (aFace,Standard_False); iter.More(); iter.Next()) {
509           TopoDS_Wire wire = TopoDS::Wire(iter.Value());
510           sfw->Load(wire);
511           sfw->FixReorder();
512           sfw->FixShifted();
513         }
514       }
515     }
516   } // end processing each solid
517
518   aResShape = myContext->Apply(Shape);
519   return aResShape;
520 }
521
522
523 //=======================================================================
524 //function : IsSameDomain
525 //purpose  :
526 //=======================================================================
527
528 bool getCylinder (Handle(Geom_Surface)& theInSurface, gp_Cylinder& theOutCylinder)
529 {
530   bool isCylinder = false;
531
532   if (theInSurface->IsKind(STANDARD_TYPE(Geom_CylindricalSurface))) {
533     Handle(Geom_CylindricalSurface) aGC = Handle(Geom_CylindricalSurface)::DownCast(theInSurface);
534
535     theOutCylinder = aGC->Cylinder();
536     isCylinder = true;
537   }
538   else if (theInSurface->IsKind(STANDARD_TYPE(Geom_SurfaceOfRevolution))) {
539     Handle(Geom_SurfaceOfRevolution) aRS =
540       Handle(Geom_SurfaceOfRevolution)::DownCast(theInSurface);
541     Handle(Geom_Curve) aBasis = aRS->BasisCurve();
542     if (aBasis->IsKind(STANDARD_TYPE(Geom_Line))) {
543       Handle(Geom_Line) aBasisLine = Handle(Geom_Line)::DownCast(aBasis);
544       gp_Dir aDir = aRS->Direction();
545       gp_Dir aBasisDir = aBasisLine->Position().Direction();
546       if (aBasisDir.IsParallel(aDir, Precision::Confusion())) {
547         // basis line is parallel to the revolution axis: it is a cylinder
548         gp_Pnt aLoc = aRS->Location();
549         Standard_Real aR = aBasisLine->Lin().Distance(aLoc);
550         gp_Ax3 aCylAx (aLoc, aDir);
551
552         theOutCylinder = gp_Cylinder(aCylAx, aR);
553         isCylinder = true;
554       }
555     }
556   }
557   else if (theInSurface->IsKind(STANDARD_TYPE(Geom_SurfaceOfLinearExtrusion))) {
558     Handle(Geom_SurfaceOfLinearExtrusion) aLES =
559       Handle(Geom_SurfaceOfLinearExtrusion)::DownCast(theInSurface);
560     Handle(Geom_Curve) aBasis = aLES->BasisCurve();
561     if (aBasis->IsKind(STANDARD_TYPE(Geom_Circle))) {
562       Handle(Geom_Circle) aBasisCircle = Handle(Geom_Circle)::DownCast(aBasis);
563       gp_Dir aDir = aLES->Direction();
564       gp_Dir aBasisDir = aBasisCircle->Position().Direction();
565       if (aBasisDir.IsParallel(aDir, Precision::Confusion())) {
566         // basis circle is normal to the extrusion axis: it is a cylinder
567         gp_Pnt aLoc = aBasisCircle->Location();
568         Standard_Real aR = aBasisCircle->Radius();
569         gp_Ax3 aCylAx (aLoc, aDir);
570
571         theOutCylinder = gp_Cylinder(aCylAx, aR);
572         isCylinder = true;
573       }
574     }
575   }
576   else {
577   }
578
579   return isCylinder;
580 }
581
582 Standard_Boolean BlockFix_UnionFaces::IsSameDomain(const TopoDS_Face& aFace,
583                                                    const TopoDS_Face& aCheckedFace) const
584 {
585   //checking the same handles
586   TopLoc_Location L1, L2;
587   Handle(Geom_Surface) S1, S2;
588
589   S1 = BRep_Tool::Surface(aFace,L1);
590   S2 = BRep_Tool::Surface(aCheckedFace,L2);
591
592   if (S1 == S2 && L1 == L2)
593     return true;
594
595   // planar and cylindrical cases (IMP 20052)
596   Standard_Real aPrec = Precision::Confusion();
597
598   S1 = BRep_Tool::Surface(aFace);
599   S2 = BRep_Tool::Surface(aCheckedFace);
600
601   S1 = ClearRts(S1);
602   S2 = ClearRts(S2);
603
604   //Handle(Geom_OffsetSurface) aGOFS1, aGOFS2;
605   //aGOFS1 = Handle(Geom_OffsetSurface)::DownCast(S1);
606   //aGOFS2 = Handle(Geom_OffsetSurface)::DownCast(S2);
607   //if (!aGOFS1.IsNull()) S1 = aGOFS1->BasisSurface();
608   //if (!aGOFS2.IsNull()) S2 = aGOFS2->BasisSurface();
609
610   // case of two elementary surfaces: use OCCT tool
611   // elementary surfaces: ConicalSurface, CylindricalSurface,
612   //                      Plane, SphericalSurface and ToroidalSurface
613   if (S1->IsKind(STANDARD_TYPE(Geom_ElementarySurface)) &&
614       S2->IsKind(STANDARD_TYPE(Geom_ElementarySurface)))
615   {
616     Handle(GeomAdaptor_HSurface) aGA1 = new GeomAdaptor_HSurface(S1);
617     Handle(GeomAdaptor_HSurface) aGA2 = new GeomAdaptor_HSurface(S2);
618
619     Handle(BRepTopAdaptor_TopolTool) aTT1 = new BRepTopAdaptor_TopolTool();
620     Handle(BRepTopAdaptor_TopolTool) aTT2 = new BRepTopAdaptor_TopolTool();
621
622     try {
623 #if OCC_VERSION_LARGE > 0x06010000
624       OCC_CATCH_SIGNALS;
625 #endif
626
627 #if OCC_VERSION_LARGE > 0x06040000 // Porting to OCCT6.5.1
628       IntPatch_ImpImpIntersection anIIInt (aGA1, aTT1, aGA2, aTT2, aPrec, aPrec);
629 #else
630       IntPatch_TheIIIntOfIntersection anIIInt (aGA1, aTT1, aGA2, aTT2, aPrec, aPrec);
631 #endif
632       if (!anIIInt.IsDone() || anIIInt.IsEmpty())
633         return false;
634
635       return anIIInt.TangentFaces();
636     }
637     catch (Standard_Failure) {
638       return false;
639     }
640   }
641
642   // case of two planar surfaces:
643   // all kinds of surfaces checked, including b-spline and bezier
644   GeomLib_IsPlanarSurface aPlanarityChecker1 (S1, aPrec);
645   if (aPlanarityChecker1.IsPlanar()) {
646     GeomLib_IsPlanarSurface aPlanarityChecker2 (S2, aPrec);
647     if (aPlanarityChecker2.IsPlanar()) {
648       gp_Pln aPln1 = aPlanarityChecker1.Plan();
649       gp_Pln aPln2 = aPlanarityChecker2.Plan();
650
651       if (aPln1.Position().Direction().IsParallel(aPln2.Position().Direction(), aPrec) &&
652           aPln1.Distance(aPln2) < aPrec) {
653         return true;
654       }
655     }
656   }
657
658   // case of two cylindrical surfaces, at least one of which is a swept surface
659   // swept surfaces: SurfaceOfLinearExtrusion, SurfaceOfRevolution
660   if ((S1->IsKind(STANDARD_TYPE(Geom_CylindricalSurface)) ||
661        S1->IsKind(STANDARD_TYPE(Geom_SweptSurface))) &&
662       (S2->IsKind(STANDARD_TYPE(Geom_CylindricalSurface)) ||
663        S2->IsKind(STANDARD_TYPE(Geom_SweptSurface))))
664   {
665     gp_Cylinder aCyl1, aCyl2;
666     if (getCylinder(S1, aCyl1) && getCylinder(S2, aCyl2)) {
667       if (fabs(aCyl1.Radius() - aCyl2.Radius()) < aPrec) {
668         gp_Dir aDir1 = aCyl1.Position().Direction();
669         gp_Dir aDir2 = aCyl2.Position().Direction();
670         if (aDir1.IsParallel(aDir2, aPrec)) {
671           gp_Pnt aLoc1 = aCyl1.Location();
672           gp_Pnt aLoc2 = aCyl2.Location();
673           gp_Vec aVec12 (aLoc1, aLoc2);
674           if (aVec12.SquareMagnitude() < aPrec*aPrec ||
675               aVec12.IsParallel(aDir1, aPrec)) {
676             return true;
677           }
678         }
679       }
680     }
681   }
682
683   return false;
684 }
685
686
687 //=======================================================================
688 //function : MovePCurves
689 //purpose  :
690 //=======================================================================
691
692 void BlockFix_UnionFaces::MovePCurves(TopoDS_Face& aTarget,
693                                       const TopoDS_Face& aSource) const
694 {
695   BRep_Builder B;
696   for(TopExp_Explorer wexp(aSource,TopAbs_WIRE);wexp.More();wexp.Next()) {
697     Handle(ShapeFix_Wire) sfw = new ShapeFix_Wire(TopoDS::Wire(wexp.Current()),
698                                                   aTarget, Precision::Confusion());
699     sfw->FixReorder();
700     Standard_Boolean isReoredFailed = sfw->StatusReorder ( ShapeExtend_FAIL );
701     sfw->FixEdgeCurves();
702     if(isReoredFailed)
703       continue;
704
705     sfw->FixShifted();
706     sfw->FixDegenerated();
707
708     // remove degenerated edges from not degenerated points
709     ShapeAnalysis_Edge sae;
710     Handle(ShapeExtend_WireData) sewd = sfw->WireData();
711     for(Standard_Integer i = 1; i<=sewd->NbEdges();i++) {
712       TopoDS_Edge E = sewd->Edge(i);
713       if(BRep_Tool::Degenerated(E)&&!sae.HasPCurve(E,aTarget)) {
714         sewd->Remove(i);
715         i--;
716       }
717     }
718
719     TopoDS_Wire ResWire = sfw->Wire();
720     B.Add(aTarget,ResWire);
721   }
722 }