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