]> SALOME platform Git repositories - modules/geom.git/blob - src/BlockFix/BlockFix_UnionFaces.cxx
Salome HOME
4c6d17e0850dfaaad1db66c02ece62580f6c3e4b
[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 #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 #include <TopoDS_Shape.hxx>
77
78 #include <TColGeom_HArray2OfSurface.hxx>
79
80 #include <GeomAdaptor_HSurface.hxx>
81 #include <GeomLib_IsPlanarSurface.hxx>
82
83 #include <Geom_Surface.hxx>
84 #include <Geom_Plane.hxx>
85 #include <Geom_OffsetSurface.hxx>
86 #include <Geom_SphericalSurface.hxx>
87 #include <Geom_CylindricalSurface.hxx>
88 #include <Geom_SurfaceOfRevolution.hxx>
89 #include <Geom_SurfaceOfLinearExtrusion.hxx>
90 #include <Geom_RectangularTrimmedSurface.hxx>
91
92 #include <Geom_Curve.hxx>
93 #include <Geom_Line.hxx>
94 #include <Geom_Circle.hxx>
95
96 #include <Geom2d_Line.hxx>
97
98 #include <gp_XY.hxx>
99 #include <gp_Pnt2d.hxx>
100
101 #include <Standard_Failure.hxx>
102 #include <Standard_ErrorHandler.hxx> // CAREFUL ! position of this file is critic : see Lucien PIGNOLONI / OCC
103
104 //=======================================================================
105 //function : BlockFix_UnionFaces
106 //purpose  :
107 //=======================================================================
108 BlockFix_UnionFaces::BlockFix_UnionFaces()
109   : myTolerance(Precision::Confusion()),
110     myOptimumNbFaces(6)
111 {
112 }
113
114 //=======================================================================
115 //function : GetTolerance
116 //purpose  :
117 //=======================================================================
118 Standard_Real& BlockFix_UnionFaces::GetTolerance()
119 {
120   return myTolerance;
121 }
122
123 //=======================================================================
124 //function : GetOptimumNbFaces
125 //purpose  :
126 //=======================================================================
127 Standard_Integer& BlockFix_UnionFaces::GetOptimumNbFaces()
128 {
129   return myOptimumNbFaces;
130 }
131
132 //=======================================================================
133 //function : AddOrdinaryEdges
134 //purpose  : auxilary
135 //           adds edges from the shape to the sequence
136 //           seams and equal edges are dropped
137 //           Returns true if one of original edges dropped
138 //=======================================================================
139 static Standard_Boolean AddOrdinaryEdges(TopTools_SequenceOfShape& edges,
140                                          const TopoDS_Shape aShape,
141                                          Standard_Integer& anIndex)
142 {
143   //map of edges
144   TopTools_MapOfShape aNewEdges;
145   //add edges without seams
146   for(TopExp_Explorer exp(aShape,TopAbs_EDGE); exp.More(); exp.Next()) {
147     TopoDS_Shape edge = exp.Current();
148     if(aNewEdges.Contains(edge))
149       aNewEdges.Remove(edge);
150     else
151       aNewEdges.Add(edge);
152   }
153
154   Standard_Boolean isDropped = Standard_False;
155   //merge edges and drop seams
156   for(Standard_Integer i = 1; i <= edges.Length(); i++) {
157     TopoDS_Shape current = edges(i);
158     if(aNewEdges.Contains(current)) {
159
160       aNewEdges.Remove(current);
161       edges.Remove(i);
162       i--;
163
164       if(!isDropped) {
165         isDropped = Standard_True;
166         anIndex = i;
167       }
168     }
169   }
170
171   //add edges to the sequemce
172   for(TopTools_MapIteratorOfMapOfShape anIter(aNewEdges); anIter.More(); anIter.Next())
173     edges.Append(anIter.Key());
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     // This is a seam edge. Check if there are another seam edges on the face.
248     TopExp_Explorer anExp(theFace, TopAbs_EDGE);
249
250     for (; anExp.More(); anExp.Next()) {
251       const TopoDS_Shape &aShEdge = anExp.Current();
252
253       // Skip same edge.
254       if (theEdge.IsSame(aShEdge)) {
255         continue;
256       }
257
258       // Check if this edge is a seam.
259       TopoDS_Edge anEdge = TopoDS::Edge(aShEdge);
260
261       if (BRep_Tool::IsClosed(anEdge, theFace)) {
262         isValid = Standard_False;
263         break;
264       }
265     }
266   }
267
268   return isValid;
269 }
270
271 //=======================================================================
272 //function : Perform
273 //purpose  :
274 //=======================================================================
275 TopoDS_Shape BlockFix_UnionFaces::Perform(const TopoDS_Shape& Shape)
276 {
277   Handle(ShapeBuild_ReShape) myContext = new ShapeBuild_ReShape;
278   TopoDS_Shape aResShape = myContext->Apply(Shape);
279
280   // Fill Map of faces as keys and list of solids or shells as items.
281   TopTools_IndexedDataMapOfShapeListOfShape aMapFaceSoOrSh;
282
283   TopAbs_ShapeEnum aType = Shape.ShapeType();
284
285   if (aType != TopAbs_SHELL) {
286     aType = TopAbs_SOLID;
287   }
288
289   TopExp::MapShapesAndAncestors
290     (Shape, TopAbs_FACE, aType, aMapFaceSoOrSh);
291
292   // processing each solid
293   TopExp_Explorer exps;
294   for (exps.Init(Shape, aType); exps.More(); exps.Next()) {
295     TopoDS_Shape aSoOrSh = exps.Current();
296
297     // creating map of edge faces
298     TopTools_IndexedDataMapOfShapeListOfShape aMapEdgeFaces;
299     TopExp::MapShapesAndAncestors(aSoOrSh, TopAbs_EDGE, TopAbs_FACE, aMapEdgeFaces);
300
301     // map of processed shapes
302     TopTools_MapOfShape aProcessed;
303
304     Handle(ShapeBuild_ReShape) aContext = new ShapeBuild_ReShape;
305
306     Standard_Integer NbModif = 0;
307     Standard_Boolean hasFailed = Standard_False;
308     Standard_Real tol = Min(Max(Precision::Confusion(), myTolerance/10.), 0.1);
309
310     // count faces
311     int nbf = 0;
312     TopExp_Explorer exp;
313     TopTools_MapOfShape mapF;
314     for (exp.Init(aSoOrSh, TopAbs_FACE); exp.More(); exp.Next()) {
315       if (mapF.Add(exp.Current()))
316         nbf++;
317     }
318
319     bool doUnion = ((myOptimumNbFaces == 0) ||
320                     ((myOptimumNbFaces > 0) && (nbf > myOptimumNbFaces)));
321
322     // processing each face
323     mapF.Clear();
324     for (exp.Init(aSoOrSh, TopAbs_FACE); exp.More() && doUnion; exp.Next()) {
325       TopoDS_Face aFace = TopoDS::Face(exp.Current().Oriented(TopAbs_FORWARD));
326
327       if (aProcessed.Contains(aFace))
328         continue;
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
342       // find adjacent faces to union
343       Standard_Integer i;
344       for (i = 1; i <= edges.Length(); i++) {
345         TopoDS_Edge edge = TopoDS::Edge(edges(i));
346         if (BRep_Tool::Degenerated(edge) || !IsEdgeValidToMerge(edge, aFace))
347           continue;
348
349         const TopTools_ListOfShape& aList = aMapEdgeFaces.FindFromKey(edge);
350         TopTools_ListIteratorOfListOfShape anIter(aList);
351         for (; anIter.More(); anIter.Next()) {
352           TopoDS_Face anCheckedFace = TopoDS::Face(anIter.Value().Oriented(TopAbs_FORWARD));
353           if (anCheckedFace.IsSame(aFace))
354             continue;
355
356           if (aProcessed.Contains(anCheckedFace))
357             continue;
358
359           if (!IsEdgeValidToMerge(edge, anCheckedFace)) {
360             // Skip seam edge.
361             continue;
362           }
363
364           // Check if faces belong to same solids.
365           if (!IsFacesOfSameSolids(aFace, anCheckedFace, aMapFaceSoOrSh)) {
366             continue;
367           }
368
369           if (IsSameDomain(aFace,anCheckedFace)) {
370
371             if (aList.Extent() != 2) {
372               // non mainfold case is not processed
373               continue;
374             }
375
376             // replacing pcurves
377             TopoDS_Face aMockUpFace;
378             BRep_Builder B;
379             B.MakeFace(aMockUpFace,aBaseSurface,aBaseLocation,0.);
380             MovePCurves(aMockUpFace,anCheckedFace);
381
382             if (AddOrdinaryEdges(edges,aMockUpFace,dummy)) {
383               // sequence edges is modified
384               i = dummy;
385             }
386
387             faces.Append(anCheckedFace);
388             aProcessed.Add(anCheckedFace);
389             break;
390           }
391         }
392       }
393
394       // all faces collected in the sequence. Perform union of faces
395       if (faces.Length() > 1) {
396         NbModif++;
397         TopoDS_Face aResult;
398         BRep_Builder B;
399         B.MakeFace(aResult,aBaseSurface,aBaseLocation,0);
400         Standard_Integer nbWires = 0;
401
402         // connecting wires
403         while (edges.Length()>0) {
404
405           Standard_Boolean isEdge3d = Standard_False;
406           nbWires++;
407           TopTools_MapOfShape aVertices;
408           TopoDS_Wire aWire;
409           B.MakeWire(aWire);
410
411           TopoDS_Edge anEdge = TopoDS::Edge(edges(1));
412           edges.Remove(1);
413
414           isEdge3d |= !BRep_Tool::Degenerated(anEdge);
415           B.Add(aWire,anEdge);
416           TopoDS_Vertex V1,V2;
417           TopExp::Vertices(anEdge,V1,V2);
418           aVertices.Add(V1);
419           aVertices.Add(V2);
420
421           Standard_Boolean isNewFound = Standard_False;
422           do {
423             isNewFound = Standard_False;
424             for(Standard_Integer j = 1; j <= edges.Length(); j++) {
425               anEdge = TopoDS::Edge(edges(j));
426               TopExp::Vertices(anEdge,V1,V2);
427               if(aVertices.Contains(V1) || aVertices.Contains(V2)) {
428                 isEdge3d |= !BRep_Tool::Degenerated(anEdge);
429                 aVertices.Add(V1);
430                 aVertices.Add(V2);
431                 B.Add(aWire,anEdge);
432                 edges.Remove(j);
433                 j--;
434                 isNewFound = Standard_True;
435               }
436             }
437           } while (isNewFound);
438
439           // sorting any type of edges
440           aWire = TopoDS::Wire(aContext->Apply(aWire));
441
442           TopoDS_Face tmpF = TopoDS::Face(aContext->Apply(faces(1).Oriented(TopAbs_FORWARD)));
443           Handle(ShapeFix_Wire) sfw = new ShapeFix_Wire(aWire,tmpF,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),tmpF,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,tmpF,0.);
503             B.Range(E,tmpF,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       myContext->Replace(aSoOrSh, aResult);
590     }
591     //else
592     {
593       for (exp.Init(aSoOrSh, TopAbs_FACE); exp.More(); exp.Next()) {
594         TopoDS_Face aFace = TopoDS::Face(exp.Current().Oriented(TopAbs_FORWARD));
595         Handle(ShapeFix_Wire) sfw = new ShapeFix_Wire;
596         sfw->SetContext(myContext);
597         sfw->SetPrecision(myTolerance);
598         sfw->SetMinTolerance(myTolerance);
599         sfw->SetMaxTolerance(Max(1.,myTolerance*1000.));
600         sfw->SetFace(aFace);
601         for (TopoDS_Iterator iter (aFace,Standard_False); iter.More(); iter.Next()) {
602           TopoDS_Wire wire = TopoDS::Wire(iter.Value());
603           sfw->Load(wire);
604           sfw->FixReorder();
605           sfw->FixShifted();
606         }
607       }
608     }
609   } // end processing each solid
610
611   aResShape = myContext->Apply(Shape);
612   return aResShape;
613 }
614
615 //=======================================================================
616 //function : IsSameDomain
617 //purpose  :
618 //=======================================================================
619 bool getCylinder (Handle(Geom_Surface)& theInSurface, gp_Cylinder& theOutCylinder)
620 {
621   bool isCylinder = false;
622
623   if (theInSurface->IsKind(STANDARD_TYPE(Geom_CylindricalSurface))) {
624     Handle(Geom_CylindricalSurface) aGC = Handle(Geom_CylindricalSurface)::DownCast(theInSurface);
625
626     theOutCylinder = aGC->Cylinder();
627     isCylinder = true;
628   }
629   else if (theInSurface->IsKind(STANDARD_TYPE(Geom_SurfaceOfRevolution))) {
630     Handle(Geom_SurfaceOfRevolution) aRS =
631       Handle(Geom_SurfaceOfRevolution)::DownCast(theInSurface);
632     Handle(Geom_Curve) aBasis = aRS->BasisCurve();
633     if (aBasis->IsKind(STANDARD_TYPE(Geom_Line))) {
634       Handle(Geom_Line) aBasisLine = Handle(Geom_Line)::DownCast(aBasis);
635       gp_Dir aDir = aRS->Direction();
636       gp_Dir aBasisDir = aBasisLine->Position().Direction();
637       if (aBasisDir.IsParallel(aDir, Precision::Confusion())) {
638         // basis line is parallel to the revolution axis: it is a cylinder
639         gp_Pnt aLoc = aRS->Location();
640         Standard_Real aR = aBasisLine->Lin().Distance(aLoc);
641         gp_Ax3 aCylAx (aLoc, aDir);
642
643         theOutCylinder = gp_Cylinder(aCylAx, aR);
644         isCylinder = true;
645       }
646     }
647   }
648   else if (theInSurface->IsKind(STANDARD_TYPE(Geom_SurfaceOfLinearExtrusion))) {
649     Handle(Geom_SurfaceOfLinearExtrusion) aLES =
650       Handle(Geom_SurfaceOfLinearExtrusion)::DownCast(theInSurface);
651     Handle(Geom_Curve) aBasis = aLES->BasisCurve();
652     if (aBasis->IsKind(STANDARD_TYPE(Geom_Circle))) {
653       Handle(Geom_Circle) aBasisCircle = Handle(Geom_Circle)::DownCast(aBasis);
654       gp_Dir aDir = aLES->Direction();
655       gp_Dir aBasisDir = aBasisCircle->Position().Direction();
656       if (aBasisDir.IsParallel(aDir, Precision::Confusion())) {
657         // basis circle is normal to the extrusion axis: it is a cylinder
658         gp_Pnt aLoc = aBasisCircle->Location();
659         Standard_Real aR = aBasisCircle->Radius();
660         gp_Ax3 aCylAx (aLoc, aDir);
661
662         theOutCylinder = gp_Cylinder(aCylAx, aR);
663         isCylinder = true;
664       }
665     }
666   }
667   else {
668   }
669
670   return isCylinder;
671 }
672
673 Standard_Boolean BlockFix_UnionFaces::IsSameDomain(const TopoDS_Face& aFace,
674                                                    const TopoDS_Face& aCheckedFace) const
675 {
676   //checking the same handles
677   TopLoc_Location L1, L2;
678   Handle(Geom_Surface) S1, S2;
679
680   S1 = BRep_Tool::Surface(aFace,L1);
681   S2 = BRep_Tool::Surface(aCheckedFace,L2);
682
683   if (S1 == S2 && L1 == L2)
684     return true;
685
686   // planar and cylindrical cases (IMP 20052)
687   Standard_Real aPrec = Precision::Confusion();
688
689   S1 = BRep_Tool::Surface(aFace);
690   S2 = BRep_Tool::Surface(aCheckedFace);
691
692   S1 = ClearRts(S1);
693   S2 = ClearRts(S2);
694
695   //Handle(Geom_OffsetSurface) aGOFS1, aGOFS2;
696   //aGOFS1 = Handle(Geom_OffsetSurface)::DownCast(S1);
697   //aGOFS2 = Handle(Geom_OffsetSurface)::DownCast(S2);
698   //if (!aGOFS1.IsNull()) S1 = aGOFS1->BasisSurface();
699   //if (!aGOFS2.IsNull()) S2 = aGOFS2->BasisSurface();
700
701   // case of two elementary surfaces: use OCCT tool
702   // elementary surfaces: ConicalSurface, CylindricalSurface,
703   //                      Plane, SphericalSurface and ToroidalSurface
704   if (S1->IsKind(STANDARD_TYPE(Geom_ElementarySurface)) &&
705       S2->IsKind(STANDARD_TYPE(Geom_ElementarySurface)))
706   {
707     Handle(GeomAdaptor_HSurface) aGA1 = new GeomAdaptor_HSurface(S1);
708     Handle(GeomAdaptor_HSurface) aGA2 = new GeomAdaptor_HSurface(S2);
709
710     Handle(BRepTopAdaptor_TopolTool) aTT1 = new BRepTopAdaptor_TopolTool();
711     Handle(BRepTopAdaptor_TopolTool) aTT2 = new BRepTopAdaptor_TopolTool();
712
713     try {
714 #if OCC_VERSION_LARGE > 0x06010000
715       OCC_CATCH_SIGNALS;
716 #endif
717
718 #if OCC_VERSION_LARGE > 0x06040000 // Porting to OCCT6.5.1
719       IntPatch_ImpImpIntersection anIIInt (aGA1, aTT1, aGA2, aTT2, aPrec, aPrec);
720 #else
721       IntPatch_TheIIIntOfIntersection anIIInt (aGA1, aTT1, aGA2, aTT2, aPrec, aPrec);
722 #endif
723       if (!anIIInt.IsDone() || anIIInt.IsEmpty())
724         return false;
725
726       return anIIInt.TangentFaces();
727     }
728     catch (Standard_Failure) {
729       return false;
730     }
731   }
732
733   // case of two planar surfaces:
734   // all kinds of surfaces checked, including b-spline and bezier
735   GeomLib_IsPlanarSurface aPlanarityChecker1 (S1, aPrec);
736   if (aPlanarityChecker1.IsPlanar()) {
737     GeomLib_IsPlanarSurface aPlanarityChecker2 (S2, aPrec);
738     if (aPlanarityChecker2.IsPlanar()) {
739       gp_Pln aPln1 = aPlanarityChecker1.Plan();
740       gp_Pln aPln2 = aPlanarityChecker2.Plan();
741
742       if (aPln1.Position().Direction().IsParallel(aPln2.Position().Direction(), aPrec) &&
743           aPln1.Distance(aPln2) < aPrec) {
744         return true;
745       }
746     }
747   }
748
749   // case of two cylindrical surfaces, at least one of which is a swept surface
750   // swept surfaces: SurfaceOfLinearExtrusion, SurfaceOfRevolution
751   if ((S1->IsKind(STANDARD_TYPE(Geom_CylindricalSurface)) ||
752        S1->IsKind(STANDARD_TYPE(Geom_SweptSurface))) &&
753       (S2->IsKind(STANDARD_TYPE(Geom_CylindricalSurface)) ||
754        S2->IsKind(STANDARD_TYPE(Geom_SweptSurface))))
755   {
756     gp_Cylinder aCyl1, aCyl2;
757     if (getCylinder(S1, aCyl1) && getCylinder(S2, aCyl2)) {
758       if (fabs(aCyl1.Radius() - aCyl2.Radius()) < aPrec) {
759         gp_Dir aDir1 = aCyl1.Position().Direction();
760         gp_Dir aDir2 = aCyl2.Position().Direction();
761         if (aDir1.IsParallel(aDir2, aPrec)) {
762           gp_Pnt aLoc1 = aCyl1.Location();
763           gp_Pnt aLoc2 = aCyl2.Location();
764           gp_Vec aVec12 (aLoc1, aLoc2);
765           if (aVec12.SquareMagnitude() < aPrec*aPrec ||
766               aVec12.IsParallel(aDir1, aPrec)) {
767             return true;
768           }
769         }
770       }
771     }
772   }
773
774   return false;
775 }
776
777 //=======================================================================
778 //function : MovePCurves
779 //purpose  :
780 //=======================================================================
781 void BlockFix_UnionFaces::MovePCurves(TopoDS_Face& aTarget,
782                                       const TopoDS_Face& aSource) const
783 {
784   BRep_Builder B;
785   for(TopExp_Explorer wexp(aSource,TopAbs_WIRE);wexp.More();wexp.Next()) {
786     Handle(ShapeFix_Wire) sfw = new ShapeFix_Wire(TopoDS::Wire(wexp.Current()),
787                                                   aTarget, Precision::Confusion());
788     sfw->FixReorder();
789     Standard_Boolean isReoredFailed = sfw->StatusReorder ( ShapeExtend_FAIL );
790     sfw->FixEdgeCurves();
791     if(isReoredFailed)
792       continue;
793
794     sfw->FixShifted();
795     sfw->FixDegenerated();
796
797     // remove degenerated edges from not degenerated points
798     ShapeAnalysis_Edge sae;
799     Handle(ShapeExtend_WireData) sewd = sfw->WireData();
800     for(Standard_Integer i = 1; i<=sewd->NbEdges();i++) {
801       TopoDS_Edge E = sewd->Edge(i);
802       if(BRep_Tool::Degenerated(E)&&!sae.HasPCurve(E,aTarget)) {
803         sewd->Remove(i);
804         i--;
805       }
806     }
807
808     TopoDS_Wire ResWire = sfw->Wire();
809     B.Add(aTarget,ResWire);
810   }
811 }