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