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