]> SALOME platform Git repositories - modules/geom.git/blob - src/GEOMImpl/GEOMImpl_PipeDriver.cxx
Salome HOME
430cb0ef9b99047fdacd5930c5bcb8de2be3d4ac
[modules/geom.git] / src / GEOMImpl / GEOMImpl_PipeDriver.cxx
1 //  Copyright (C) 2007-2008  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 //  Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 //  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 //  This library is free software; you can redistribute it and/or
7 //  modify it under the terms of the GNU Lesser General Public
8 //  License as published by the Free Software Foundation; either
9 //  version 2.1 of the License.
10 //
11 //  This library is distributed in the hope that it will be useful,
12 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 //  Lesser General Public License for more details.
15 //
16 //  You should have received a copy of the GNU Lesser General Public
17 //  License along with this library; if not, write to the Free Software
18 //  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 //  See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22 #include <Standard_Stream.hxx>
23
24 #include <GEOMImpl_PipeDriver.hxx>
25
26 #include <GEOMImpl_IShapesOperations.hxx>
27 #include <GEOMImpl_IPipeDiffSect.hxx>
28 #include <GEOMImpl_IPipeShellSect.hxx>
29 #include <GEOMImpl_IPipeBiNormal.hxx>
30 #include <GEOMImpl_IPipe.hxx>
31 #include <GEOMImpl_Types.hxx>
32 #include <GEOM_Function.hxx>
33
34 #include <GEOMAlgo_GlueAnalyser.hxx>
35
36 #include <ShapeAnalysis_FreeBounds.hxx>
37 #include <ShapeAnalysis_Edge.hxx>
38 #include <ShapeFix_Face.hxx>
39 #include <ShapeFix_Shell.hxx>
40 #include <ShapeFix_Shape.hxx>
41 #include <ShapeFix_ShapeTolerance.hxx>
42
43 #include <BRep_Tool.hxx>
44 #include <BRep_Builder.hxx>
45 #include <BRepBuilderAPI_MakeWire.hxx>
46 #include <BRepBuilderAPI_Sewing.hxx>
47 #include <BRepCheck_Analyzer.hxx>
48 #include <BRepOffsetAPI_MakePipe.hxx>
49 #include <BRepOffsetAPI_MakePipeShell.hxx>
50 #include <GProp_GProps.hxx>
51 #include <BRepGProp.hxx>
52 #include <BRepBuilderAPI_MakeFace.hxx>
53
54 #include <TopAbs.hxx>
55 #include <TopExp.hxx>
56 #include <TopExp_Explorer.hxx>
57 #include <TopoDS.hxx>
58 #include <TopoDS_Wire.hxx>
59 #include <TopoDS_Edge.hxx>
60 #include <TopoDS_Shape.hxx>
61 #include <TopoDS_Solid.hxx>
62 #include <TopoDS_Shell.hxx>
63 #include <TopoDS_Face.hxx>
64 #include <TopoDS_Compound.hxx>
65 #include <TopTools_SequenceOfShape.hxx>
66 #include <TopTools_IndexedDataMapOfShapeShape.hxx>
67 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
68 #include <TopTools_ListIteratorOfListOfShape.hxx>
69
70 #include <GeomAPI_ProjectPointOnCurve.hxx>
71 #include <GeomAPI_Interpolate.hxx>
72 #include <Geom_TrimmedCurve.hxx>
73 #include <Geom_Plane.hxx>
74 #include <Geom_RectangularTrimmedSurface.hxx>
75 #include <Geom_BezierSurface.hxx>
76 #include <Geom_Line.hxx>
77 #include <Geom_Conic.hxx>
78 #include <Geom_BSplineCurve.hxx>
79 #include <Geom_BSplineSurface.hxx>
80 #include <GeomFill_BSplineCurves.hxx>
81 #include <GeomConvert_ApproxCurve.hxx>
82 #include <GeomConvert.hxx>
83
84 #include <TColgp_SequenceOfPnt.hxx>
85 #include <TColgp_HArray1OfPnt.hxx>
86 #include <TColgp_Array2OfPnt.hxx>
87 #include <TColStd_HSequenceOfTransient.hxx>
88
89 #include <Precision.hxx>
90 #include <Standard_NullObject.hxx>
91 #include <Standard_TypeMismatch.hxx>
92 #include <Standard_ConstructionError.hxx>
93
94 #include "utilities.h"
95
96
97 //=======================================================================
98 //function : GetID
99 //purpose  :
100 //=======================================================================
101 const Standard_GUID& GEOMImpl_PipeDriver::GetID()
102 {
103   static Standard_GUID aPipeDriver("FF1BBB19-5D14-4df2-980B-3A668264EA16");
104   return aPipeDriver;
105 }
106
107
108 //=======================================================================
109 //function : GEOMImpl_PipeDriver
110 //purpose  :
111 //=======================================================================
112 GEOMImpl_PipeDriver::GEOMImpl_PipeDriver()
113 {
114 }
115
116
117 //=======================================================================
118 //function : FillForOtherEdges
119 //purpose  : auxilary for CreatePipeForShellSections()
120 //=======================================================================
121 static bool FillForOtherEdges(const TopoDS_Shape& F1,
122                               const TopoDS_Shape& E1,
123                               const TopoDS_Shape& V1,
124                               TopTools_IndexedDataMapOfShapeShape& FF)
125 {
126   //cout<<"FillForOtherEdges"<<endl;
127   // find other pairs for vertexes and edges
128   // creating map of vertex edges for both faces
129   TopTools_IndexedDataMapOfShapeListOfShape aMapVertEdge1;
130   TopExp::MapShapesAndAncestors(F1, TopAbs_VERTEX, TopAbs_EDGE, aMapVertEdge1);
131   if (!FF.Contains(F1))
132     MESSAGE("    FillForOtherEdges: map FF not contains key F1");
133   if (!FF.Contains(E1))
134     MESSAGE("    FillForOtherEdges: map FF not contains key E1");
135   if (!FF.Contains(V1))
136     MESSAGE("    FillForOtherEdges: map FF not contains key V1");
137   const TopoDS_Shape& F2 = FF.FindFromKey(F1);
138   const TopoDS_Shape& E2 = FF.FindFromKey(E1);
139   const TopoDS_Shape& V2 = FF.FindFromKey(V1);
140   TopTools_IndexedDataMapOfShapeListOfShape aMapVertEdge2;
141   TopExp::MapShapesAndAncestors(F2, TopAbs_VERTEX, TopAbs_EDGE, aMapVertEdge2);
142
143   TopoDS_Edge ES1 = TopoDS::Edge(E1);
144   TopoDS_Edge ES2 = TopoDS::Edge(E2);
145   TopoDS_Shape VS1 = V1;
146   TopoDS_Shape VS2 = V2;
147
148   ShapeAnalysis_Edge sae;
149   while(1) {
150     if(!aMapVertEdge1.Contains(VS1))
151       MESSAGE ("    FillForOtherEdges: map aMapVertEdge1 not contains key VS1");
152     const TopTools_ListOfShape& aList1 = aMapVertEdge1.FindFromKey(VS1);
153     //TopoDS_Shape E1next;
154     TopTools_ListIteratorOfListOfShape anIter1(aList1);
155     if(anIter1.Value().IsSame(ES1)) {
156       anIter1.Next();
157     }
158     //E1next = anIter1.Value();
159     if(!aMapVertEdge2.Contains(VS2))
160       MESSAGE ("    FillForOtherEdges: map aMapVertEdge2 not contains key VS2");
161     const TopTools_ListOfShape& aList2 = aMapVertEdge2.FindFromKey(VS2);
162     //TopoDS_Shape E2next;
163     TopTools_ListIteratorOfListOfShape anIter2(aList2);
164     if(anIter2.Value().IsSame(ES2)) {
165       anIter2.Next();
166     }
167     //E2next = anIter2.Value();
168     //ES1 = TopoDS::Edge(E1next);
169     //ES2 = TopoDS::Edge(E2next);
170     ES1 = TopoDS::Edge(anIter1.Value());
171     ES2 = TopoDS::Edge(anIter2.Value());
172     if(!FF.Contains(ES1)) {
173       FF.Add(ES1,ES2);
174     }
175     if(VS1.IsSame(sae.FirstVertex(ES1)))
176       VS1 = sae.LastVertex(ES1);
177     else
178       VS1 = sae.FirstVertex(ES1);
179     if(VS2.IsSame(sae.FirstVertex(ES2)))
180       VS2 = sae.LastVertex(ES2);
181     else
182       VS2 = sae.FirstVertex(ES2);
183     if(VS1.IsSame(V1))
184       break;
185     if(!FF.Contains(VS1)) {
186       FF.Add(VS1,VS2);
187     }
188   }
189
190   return true;
191 }
192
193
194 //=======================================================================
195 //function : FillCorrespondingEdges
196 //purpose  : auxilary for CreatePipeForShellSections()
197 //=======================================================================
198 static bool FillCorrespondingEdges(const TopoDS_Shape& FS1,
199                                    const TopoDS_Shape& FS2,
200                                    const TopoDS_Vertex& aLoc1,
201                                    const TopoDS_Vertex& aLoc2,
202                                    const TopoDS_Wire& aWirePath,
203                                    TopTools_IndexedDataMapOfShapeShape& FF)
204 {
205   //cout<<"FillCorrespondingEdges"<<endl;
206   // find corresponding edges
207   TopExp_Explorer expw1(FS1,TopAbs_WIRE);
208   TopoDS_Wire aWire1 = TopoDS::Wire(expw1.Current());
209   //exp = TopExp_Explorer(FS2,TopAbs_WIRE);
210   TopExp_Explorer expw2(FS2,TopAbs_WIRE);
211   TopoDS_Wire aWire2 = TopoDS::Wire(expw2.Current());
212   BRepOffsetAPI_MakePipeShell aBuilder(aWirePath);
213   aBuilder.Add(aWire1, aLoc1);
214   aBuilder.Add(aWire2, aLoc2);
215   if(!aBuilder.IsReady()) {
216     return false;
217   }
218   aBuilder.Build();
219   TopoDS_Shape aShape = aBuilder.Shape();
220   /*
221   TopoDS_Compound C;
222   BRep_Builder B;
223   B.MakeCompound(C);
224   B.Add(C,aShape);
225   B.Add(C,FS1);
226   B.Add(C,FS2);
227   BRepTools::Write(C,"/dn02/users_Linux/skl/work/Bugs/14857/comp.brep");
228   */
229   ShapeAnalysis_Edge sae;
230   double tol = Max( BRep_Tool::Tolerance(TopoDS::Face(FS1)),
231                     BRep_Tool::Tolerance(TopoDS::Face(FS2)) );
232   TopTools_MapOfShape Vs1,Vs2;
233   TopExp_Explorer exp;
234   exp.Init( FS1, TopAbs_EDGE );
235   TopoDS_Edge E1 = TopoDS::Edge(exp.Current());
236   TopoDS_Vertex V11 = sae.FirstVertex(E1);
237   TopoDS_Vertex V21 = sae.LastVertex(E1);
238   gp_Pnt P11 = BRep_Tool::Pnt(V11);
239   gp_Pnt P21 = BRep_Tool::Pnt(V21);
240   //cout<<"P11("<<P11.X()<<","<<P11.Y()<<","<<P11.Z()<<")"<<endl;
241   //cout<<"P21("<<P21.X()<<","<<P21.Y()<<","<<P21.Z()<<")"<<endl;
242   // find corresponding vertexes from created shape
243   TopoDS_Vertex VN11,VN21;
244   for( exp.Init( aShape, TopAbs_VERTEX ); exp.More(); exp.Next() ) {
245     TopoDS_Vertex V = TopoDS::Vertex(exp.Current());
246     gp_Pnt P = BRep_Tool::Pnt(V);
247     if(P.Distance(P11)<tol) {
248       VN11 = V;
249     }
250     if(P.Distance(P21)<tol) {
251       VN21 = V;
252     }
253   }
254   // find edge contains VN11 and VN21 and corresponding vertexes
255   TopoDS_Vertex VN12,VN22;
256   for( exp.Init( aShape, TopAbs_FACE ); exp.More(); exp.Next() ) {
257     TopoDS_Shape F = exp.Current();
258     TopExp_Explorer expe;
259     bool IsFind = false;
260     for( expe.Init( F, TopAbs_EDGE ); expe.More(); expe.Next() ) {
261       TopoDS_Edge E = TopoDS::Edge(expe.Current());
262       TopoDS_Vertex VF = sae.FirstVertex(E);
263       TopoDS_Vertex VL = sae.LastVertex(E);
264       if( (VF.IsSame(VN11) && VL.IsSame(VN21)) || (VF.IsSame(VN21) && VL.IsSame(VN11)) ) {
265         IsFind = true;
266         break;
267       }
268     }
269     if(IsFind) {
270       for( expe.Init( F, TopAbs_EDGE ); expe.More(); expe.Next() ) {
271         TopoDS_Edge E = TopoDS::Edge(expe.Current());
272         TopoDS_Vertex VF = sae.FirstVertex(E);
273         TopoDS_Vertex VL = sae.LastVertex(E);
274         if( VF.IsSame(VN11) && !VL.IsSame(VN21) )
275           VN12 = VL;
276         if( VL.IsSame(VN11) && !VF.IsSame(VN21) )
277           VN12 = VF;
278         if( VF.IsSame(VN21) && !VL.IsSame(VN11) )
279           VN22 = VL;
280         if( VL.IsSame(VN21) && !VF.IsSame(VN11) )
281           VN22 = VF;
282       }
283       break;
284     }
285   }
286   // find vertexes from FS2 corresponded to VN12 and VN22
287   // and find edge from FS2 contains V12 and V22,
288   // this edge will be corresponded to edge E1
289   TopoDS_Vertex V12,V22;
290   gp_Pnt PN12 = BRep_Tool::Pnt(VN12);
291   gp_Pnt PN22 = BRep_Tool::Pnt(VN22);
292   //cout<<"PN12("<<PN12.X()<<","<<PN12.Y()<<","<<PN12.Z()<<")"<<endl;
293   //cout<<"PN22("<<PN22.X()<<","<<PN22.Y()<<","<<PN22.Z()<<")"<<endl;
294   TopoDS_Edge E2;
295   TopExp_Explorer expe;
296   for( expe.Init( FS2, TopAbs_EDGE ); expe.More(); expe.Next() ) {
297     TopoDS_Edge E = TopoDS::Edge(expe.Current());
298     TopoDS_Vertex VF = sae.FirstVertex(E);
299     TopoDS_Vertex VL = sae.LastVertex(E);
300     gp_Pnt PF = BRep_Tool::Pnt(VF);
301     gp_Pnt PL = BRep_Tool::Pnt(VL);
302     if( PF.Distance(PN12)<tol && PL.Distance(PN22)<tol ) {
303       V12 = VF;
304       V22 = VL;
305       E2 = E;
306       break;
307     }
308     if( PF.Distance(PN22)<tol && PL.Distance(PN12)<tol ) {
309       V12 = VL;
310       V22 = VF;
311       E2 = E;
312       break;
313     }
314   }
315   FF.Add(V11,V12);
316   FF.Add(V21,V22);
317   FF.Add(E1,E2);
318
319   // find other pairs for vertexes and edges
320   // creating map of vertex edges for both faces
321   return FillForOtherEdges(FS1,E1,V21,FF);
322
323   //return true;
324 }
325
326
327 //=======================================================================
328 //function : FillCorrespondingEdges
329 //purpose  : auxilary for CreatePipeShellsWithoutPath()
330 //=======================================================================
331 static bool FillCorrespondingEdges(const TopoDS_Shape& FS1,
332                                    const TopoDS_Shape& FS2,
333                                    const TopoDS_Vertex& aLoc1,
334                                    const TopoDS_Vertex& aLoc2,
335                                    TopTools_IndexedDataMapOfShapeShape& FF)
336 {
337   //cout<<"FillCorrespondingEdges"<<endl;
338
339   gp_Pnt P1 = BRep_Tool::Pnt(aLoc1);
340   gp_Pnt P2 = BRep_Tool::Pnt(aLoc2);
341   gp_Vec aDir(P1,P2);
342
343   ShapeAnalysis_Edge sae;
344   double tol = Max( BRep_Tool::Tolerance(TopoDS::Face(FS1)),
345                     BRep_Tool::Tolerance(TopoDS::Face(FS2)) );
346   TopTools_MapOfShape Vs1,Vs2;
347
348   TopoDS_Vertex V11=aLoc1, V12=aLoc2, V21, V22;
349   TopoDS_Edge E1,E2;
350
351   TopExp_Explorer exp1;
352   for( exp1.Init(FS1,TopAbs_EDGE); exp1.More(); exp1.Next() ) {
353     E1 = TopoDS::Edge(exp1.Current());
354     TopoDS_Vertex V1 = sae.FirstVertex(E1);
355     TopoDS_Vertex V2 = sae.LastVertex(E1);
356     gp_Pnt Ptmp1 = BRep_Tool::Pnt(V1);
357     gp_Pnt Ptmp2 = BRep_Tool::Pnt(V2);
358     //cout<<"P11("<<P11.X()<<","<<P11.Y()<<","<<P11.Z()<<")"<<endl;
359     //cout<<"P21("<<P21.X()<<","<<P21.Y()<<","<<P21.Z()<<")"<<endl;
360     if(P1.Distance(Ptmp1)<tol) {
361       V21 = V2;
362       break;
363     }
364     if(P1.Distance(Ptmp2)<tol) {
365       V21 = V1;
366       break;
367     }
368   }
369
370   TopoDS_Edge E21,E22;
371   TopoDS_Vertex VE21,VE22;
372   int nbe=0;
373   for( exp1.Init(FS2,TopAbs_EDGE); exp1.More() && nbe<2; exp1.Next() ) {
374     TopoDS_Edge E = TopoDS::Edge(exp1.Current());
375     TopoDS_Vertex V1 = sae.FirstVertex(E);
376     TopoDS_Vertex V2 = sae.LastVertex(E);
377     gp_Pnt Ptmp1 = BRep_Tool::Pnt(V1);
378     gp_Pnt Ptmp2 = BRep_Tool::Pnt(V2);
379     if(P2.Distance(Ptmp1)<tol) {
380       if(nbe==0) {
381         E21 = E;
382         VE21 = V2;
383         nbe++;
384       }
385       else if(nbe==1) {
386         E22 = E;
387         VE22 = V2;
388         nbe++;
389       }
390     }
391     if(P2.Distance(Ptmp2)<tol) {
392       if(nbe==0) {
393         E21 = E;
394         VE21 = V1;
395         nbe++;
396       }
397       else if(nbe==1) {
398         E22 = E;
399         VE22 = V1;
400         nbe++;
401       }
402     }
403   }
404
405   gp_Pnt PV21 = BRep_Tool::Pnt(V21);
406   gp_Pnt PE21 = BRep_Tool::Pnt(VE21);
407   gp_Pnt PE22 = BRep_Tool::Pnt(VE22);
408   gp_Vec aDir1(PV21,PE21);
409   gp_Vec aDir2(PV21,PE22);
410   double ang1 = aDir.Angle(aDir1);
411   double ang2 = aDir.Angle(aDir2);
412   if(fabs(ang1)<fabs(ang2)) {
413     E2 = E21;
414     V22 = VE21;
415   }
416   else {
417     E2 = E22;
418     V22 = VE22;
419   }
420
421   FF.Add(V11,V12);
422   FF.Add(V21,V22);
423   FF.Add(E1,E2);
424
425   // find other pairs for vertexes and edges
426   return FillForOtherEdges(FS1,E1,V21,FF);
427 }
428
429
430 //=======================================================================
431 //function : FindNextPairOfFaces
432 //purpose  : auxilary for CreatePipeForShellSections()
433 //=======================================================================
434 static void FindNextPairOfFaces(const TopoDS_Shape& aCurFace,
435                                 TopTools_IndexedDataMapOfShapeListOfShape& aMapEdgeFaces1,
436                                 TopTools_IndexedDataMapOfShapeListOfShape& aMapEdgeFaces2,
437                                 TopTools_IndexedDataMapOfShapeShape& FF,
438                                 GEOMImpl_IPipe* aCI)
439 {
440   //cout<<"FindNextPairOfFaces"<<endl;
441   TopExp_Explorer anExp;
442   for ( anExp.Init( aCurFace, TopAbs_EDGE ); anExp.More(); anExp.Next() ) {
443     TopoDS_Shape E1 = anExp.Current();
444     if(!FF.Contains(E1)) {
445       if(aCI) delete aCI;
446       Standard_ConstructionError::Raise("FindNextPairOfFaces: Can not find edge in map");
447     }
448     if(!FF.Contains(E1))
449       MESSAGE ("    FindNextPairOfFaces: map FF not contains key E1");
450     const TopoDS_Shape& E2 = FF.FindFromKey(E1);
451     TopExp_Explorer anExpV;
452     anExpV.Init( E1, TopAbs_VERTEX );
453     TopoDS_Shape V1 = anExpV.Current();
454     if(!FF.Contains(V1)) {
455       if(aCI) delete aCI;
456       Standard_ConstructionError::Raise("FindNextPairOfFaces: Can not find vertex in map");
457     }
458
459     if(!aMapEdgeFaces1.Contains(E1))
460       MESSAGE ("    FindNextPairOfFaces: map aMapEdgeFaces1 not contains key E1");
461     const TopTools_ListOfShape& aList1 = aMapEdgeFaces1.FindFromKey(E1);
462     if(aList1.Extent()<2)
463       continue;
464     TopTools_ListIteratorOfListOfShape anIter(aList1);
465     if(anIter.Value().IsEqual(aCurFace)) {
466       anIter.Next();
467     }
468     TopoDS_Shape F1other = anIter.Value();
469     if(FF.Contains(F1other))
470       continue;
471
472     if(!FF.Contains(aCurFace))
473       MESSAGE ("    FindNextPairOfFaces: map FF not contains key aCurFace");
474     const TopoDS_Shape& F2 = FF.FindFromKey(aCurFace);
475     if(!aMapEdgeFaces2.Contains(E2))
476       MESSAGE ("    FindNextPairOfFaces: map aMapEdgeFaces2 not contains key E2");
477     const TopTools_ListOfShape& aList2 = aMapEdgeFaces2.FindFromKey(E2);
478     if(aList2.Extent()<2) {
479       if(aCI) delete aCI;
480       Standard_ConstructionError::Raise("FindNextPairOfFaces: Can not find corresponding face");
481     }
482     TopTools_ListIteratorOfListOfShape anIter2(aList2);
483     if(anIter2.Value().IsEqual(F2)) {
484       anIter2.Next();
485     }
486     TopoDS_Shape F2other = anIter2.Value();
487     FF.Add(F1other,F2other);
488
489     // add pairs of edges to FF
490     bool stat =  FillForOtherEdges(F1other,E1,V1,FF);
491     if( !stat ) {
492       if(aCI) delete aCI;
493       Standard_ConstructionError::Raise("FindNextPairOfFaces: Can not mapping other egdes");
494     }
495
496     FindNextPairOfFaces(F1other, aMapEdgeFaces1, aMapEdgeFaces2, FF, aCI);
497   }
498 }
499
500
501 //=======================================================================
502 //function : FindFirstPairFaces
503 //purpose  : auxilary for Execute()
504 //=======================================================================
505 static void FindFirstPairFaces(const TopoDS_Shape& S1, const TopoDS_Shape& S2,
506                                TopoDS_Vertex& V1, TopoDS_Vertex& V2,
507                                TopoDS_Shape& FS1, TopoDS_Shape& FS2)
508 {
509   //cout<<"FindFirstPairFaces"<<endl;
510
511   // check if vertexes are subshapes of sections
512   gp_Pnt P1 = BRep_Tool::Pnt(V1);
513   gp_Pnt P2 = BRep_Tool::Pnt(V2);
514   TopoDS_Vertex V1new,V2new;
515   TopExp_Explorer exp;
516   double mindist = 1.e10;
517   for( exp.Init( S1, TopAbs_VERTEX ); exp.More(); exp.Next() ) {
518     TopoDS_Vertex V = TopoDS::Vertex(exp.Current());
519     gp_Pnt P = BRep_Tool::Pnt(V);
520     double dist = P1.Distance(P);
521     if(dist<mindist) {
522       mindist = dist;
523       V1new = V;
524     }
525   }
526   mindist = 1.e10;
527   for( exp.Init( S2, TopAbs_VERTEX ); exp.More(); exp.Next() ) {
528     TopoDS_Vertex V = TopoDS::Vertex(exp.Current());
529     gp_Pnt P = BRep_Tool::Pnt(V);
530     double dist = P2.Distance(P);
531     if(dist<mindist) {
532       mindist = dist;
533       V2new = V;
534     }
535   }
536
537   //gp_Pnt P1new = BRep_Tool::Pnt(V1new);
538   //gp_Pnt P2new = BRep_Tool::Pnt(V2new);
539   //cout<<"  P1("<<P1.X()<<","<<P1.Y()<<","<<P1.Z()<<")"<<endl;
540   //cout<<"  P2("<<P2.X()<<","<<P2.Y()<<","<<P2.Z()<<")"<<endl;
541   //cout<<"  P1new("<<P1new.X()<<","<<P1new.Y()<<","<<P1new.Z()<<")"<<endl;
542   //cout<<"  P2new("<<P2new.X()<<","<<P2new.Y()<<","<<P2new.Z()<<")"<<endl;
543
544   // replace vertexes if it is needed
545   if(!V1.IsSame(V1new)) {
546     V1 = V1new;
547     P1 = BRep_Tool::Pnt(V1);
548     MESSAGE ("  replace V1");
549   }
550   else
551     MESSAGE ("  not replace V1");
552   if(!V2.IsSame(V2new)) {
553     V2 = V2new;
554     P2 = BRep_Tool::Pnt(V2);
555     MESSAGE ("  replace V2");
556   }
557   else
558     MESSAGE ("  not replace V2");
559
560   TopTools_IndexedDataMapOfShapeListOfShape aMapVertFaces1;
561   TopExp::MapShapesAndAncestors(S1, TopAbs_VERTEX, TopAbs_FACE, aMapVertFaces1);
562   TopTools_IndexedDataMapOfShapeListOfShape aMapVertFaces2;
563   TopExp::MapShapesAndAncestors(S2, TopAbs_VERTEX, TopAbs_FACE, aMapVertFaces2);
564
565   if(!aMapVertFaces1.Contains(V1))
566     MESSAGE ("    FindFirstPairFaces: map aMapVertFaces1 not contains key V1");
567   const TopTools_ListOfShape& aList1 = aMapVertFaces1.FindFromKey(V1);
568   TopTools_ListIteratorOfListOfShape anIter1(aList1);
569   FS1 = anIter1.Value();
570   // find middle point
571   double x1=0., y1=0., z1=0.;
572   int nbv1=0;
573   for( exp.Init( FS1, TopAbs_VERTEX ); exp.More(); exp.Next() ) {
574     TopoDS_Vertex V = TopoDS::Vertex(exp.Current());
575     gp_Pnt P = BRep_Tool::Pnt(V);
576     x1 += P.X();
577     y1 += P.Y();
578     z1 += P.Z();
579     nbv1++;
580   }
581   gp_Pnt PM1(x1/nbv1, y1/nbv1, z1/nbv1);
582
583   TColgp_SequenceOfPnt Ps;
584   TopTools_SequenceOfShape Fs;
585   if(!aMapVertFaces2.Contains(V2))
586     MESSAGE ("    FindFirstPairFaces: map aMapVertFaces2 not contains key V2");
587   const TopTools_ListOfShape& aList2 = aMapVertFaces2.FindFromKey(V2);
588   TopTools_ListIteratorOfListOfShape anIter2(aList2);
589   for(; anIter2.More(); anIter2.Next()) {
590     TopoDS_Shape F = anIter2.Value();
591     double x2=0., y2=0., z2=0.;
592     int nbv2=0;
593     for( exp.Init( F, TopAbs_VERTEX ); exp.More(); exp.Next() ) {
594       TopoDS_Vertex V = TopoDS::Vertex(exp.Current());
595       gp_Pnt P = BRep_Tool::Pnt(V);
596       x2 += P.X();
597       y2 += P.Y();
598       z2 += P.Z();
599       nbv2++;
600     }
601     gp_Pnt PM(x2/nbv1, y2/nbv1, z2/nbv1);
602     Fs.Append(F);
603     Ps.Append(PM);
604   }
605
606   gp_Vec aDir(P1,P2);
607   int i=1;
608   double MinAng = PI;
609   int numface = 0;
610   for(; i<=Fs.Length(); i++) {
611     gp_Vec tmpDir(PM1,Ps(i));
612     double ang = fabs(aDir.Angle(tmpDir));
613     if(ang<MinAng) {
614       MinAng = ang;
615       numface = i;
616     }
617   }
618   FS2 = Fs(numface);
619 }
620
621
622 //=======================================================================
623 //function : CreatePipeForShellSections
624 //purpose  : auxilary for Execute()
625 //=======================================================================
626 static TopoDS_Shape CreatePipeForShellSections(const TopoDS_Wire& aWirePath,
627                                                GEOMImpl_IPipe* aCI)
628 {
629   //cout<<"CreatePipeForShellSections"<<endl;
630   //TopoDS_Shape res;
631   int i,j;
632   BRep_Builder B;
633
634   GEOMImpl_IPipeShellSect* aCIDS = (GEOMImpl_IPipeShellSect*)aCI;
635   Handle(TColStd_HSequenceOfTransient) aBasesObjs = aCIDS->GetBases();
636   Handle(TColStd_HSequenceOfTransient) aSubBasesObjs = aCIDS->GetSubBases();
637   Handle(TColStd_HSequenceOfTransient) aLocObjs = aCIDS->GetLocations();
638   Standard_Boolean aWithContact = (aCIDS->GetWithContactMode());
639   Standard_Boolean aWithCorrect = (aCIDS->GetWithCorrectionMode());
640
641   Standard_Integer nbBases = aBasesObjs->Length(),
642     nbSubBases = (aSubBasesObjs.IsNull() ? 0 :aSubBasesObjs->Length()),
643     nbLocs = (aLocObjs.IsNull() ? 0 :aLocObjs->Length());
644
645   if( nbLocs != nbBases) {
646     if(aCI) delete aCI;
647     Standard_ConstructionError::Raise("Number of sections is not equal to number of locations ");
648   }
649   if( nbSubBases && nbSubBases != nbBases) {
650     if(aCI) delete aCI;
651     Standard_ConstructionError::Raise("Number of sections is not equal to number of subsections ");
652   }
653
654   //BRepOffsetAPI_MakePipeShell aBuilder(aWirePath);
655
656   TopTools_SequenceOfShape VLocs;
657   for(i=1; i<=nbBases; i++) {
658     Handle(Standard_Transient) anItemLoc = aLocObjs->Value(i);
659     if(anItemLoc.IsNull())
660       continue;
661     Handle(GEOM_Function) aRefLoc = Handle(GEOM_Function)::DownCast(anItemLoc);
662     TopoDS_Shape aShapeLoc = aRefLoc->GetValue();
663     if(aShapeLoc.IsNull() || aShapeLoc.ShapeType() != TopAbs_VERTEX)
664       continue;
665     VLocs.Append(aShapeLoc);
666   }
667   nbLocs = VLocs.Length();
668   if( nbLocs != nbBases) {
669     if(aCI) delete aCI;
670     Standard_ConstructionError::Raise("One of location shapes is not a vertex");
671   }
672   // split wire path by location points
673   TColgp_SequenceOfPnt PLocs;
674   for(i=1; i<=nbLocs; i++) {
675     TopoDS_Vertex V = TopoDS::Vertex(VLocs.Value(i));
676     PLocs.Append(BRep_Tool::Pnt(V));
677   }
678
679   TopTools_SequenceOfShape Edges;
680   TopTools_SequenceOfShape Wires;
681   ShapeAnalysis_Edge sae;
682
683   if(nbLocs==2) {
684     TopExp_Explorer anExp;
685     for ( anExp.Init( aWirePath, TopAbs_EDGE ); anExp.More(); anExp.Next() ) {
686       Edges.Append(anExp.Current());
687     }
688     Standard_Integer Num1 = 0;
689     Standard_Integer Num2 = 0;
690     for(i=1; i<=Edges.Length(); i++) {
691       TopoDS_Edge E = TopoDS::Edge(Edges.Value(i));
692       double tol = BRep_Tool::Tolerance(E);
693       TopoDS_Vertex V1 = sae.FirstVertex(E);
694       TopoDS_Vertex V2 = sae.LastVertex(E);
695       gp_Pnt P1 = BRep_Tool::Pnt(V1);
696       gp_Pnt P2 = BRep_Tool::Pnt(V2);
697       if( P1.Distance(PLocs.First()) < tol ) {
698         Num1 = i;
699       }
700       if( P2.Distance(PLocs.Last()) < tol ) {
701         Num2 = i;
702       }
703     }
704     if( Num1>0 && Num2>0 ) {
705       TopoDS_Wire W;
706       B.MakeWire(W);
707       for(i=Num1; i<=Num2; i++) {
708         B.Add(W,Edges.Value(i));
709       }
710       Wires.Append(W);
711     }
712     else {
713       Wires.Append(aWirePath);
714     }
715   }
716   else {
717     TopExp_Explorer anExp;
718     for ( anExp.Init( aWirePath, TopAbs_EDGE ); anExp.More(); anExp.Next() ) {
719       Edges.Append(anExp.Current());
720     }
721     TopoDS_Edge edge = TopoDS::Edge(Edges.First());
722     double tol = BRep_Tool::Tolerance(edge);
723     TopoDS_Vertex VF = sae.FirstVertex(edge);
724     gp_Pnt PF = BRep_Tool::Pnt(VF);
725     //cout<<"PF("<<PF.X()<<","<<PF.Y()<<","<<PF.Z()<<")"<<endl;
726     if( PF.Distance(PLocs.First()) > tol ) {
727       if(aCI) delete aCI;
728       Standard_ConstructionError::Raise
729         ("First location shapes is not coincided with first vertex of aWirePath");
730     }
731     VLocs.ChangeValue(1) = VF;
732     edge = TopoDS::Edge(Edges.Last());
733     tol = BRep_Tool::Tolerance(edge);
734     TopoDS_Vertex VL = sae.LastVertex(edge);
735     gp_Pnt PL = BRep_Tool::Pnt(VL);
736     if( PL.Distance(PLocs.Last()) > tol ) {
737       if(aCI) delete aCI;
738       Standard_ConstructionError::Raise
739         ("Last location shapes is not coincided with last vertex of aWirePath");
740     }
741     VLocs.ChangeValue(nbLocs) = VL;
742     int jcurr = 2;
743     TopTools_SequenceOfShape tmpEdges;
744     for(i=1; i<=Edges.Length() && jcurr<nbLocs; i++) {
745       TopoDS_Edge E = TopoDS::Edge(Edges.Value(i));
746       tol = BRep_Tool::Tolerance(E);
747       TopoDS_Vertex V1 = sae.FirstVertex(E);
748       TopoDS_Vertex V2 = sae.LastVertex(E);
749       gp_Pnt P1 = BRep_Tool::Pnt(V1);
750       gp_Pnt P2 = BRep_Tool::Pnt(V2);
751       if( P2.Distance(PLocs.Value(jcurr)) < tol ) {
752         // make wire from current edge and add created
753         // wire to Wires
754         TopoDS_Wire W;
755         B.MakeWire(W);
756         for(j=1; j<=tmpEdges.Length(); j++)
757           B.Add(W,tmpEdges.Value(j));
758         B.Add(W,E);
759         Wires.Append(W);
760         VLocs.ChangeValue(jcurr) = V2;
761         jcurr++;
762         tmpEdges.Clear();
763       }
764       else {
765         // find distance between E and aLocs(jcurr)
766         double fp,lp;
767         Handle(Geom_Curve) C = BRep_Tool::Curve(E,fp,lp);
768         GeomAPI_ProjectPointOnCurve PPC (PLocs.Value(jcurr),C);
769         if( PPC.NbPoints()>0 &&
770             PLocs.Value(jcurr).Distance(PPC.Point(1)) < tol ) {
771           double param = PPC.Parameter(1);
772           gp_Pnt PC1;
773           C->D0(param,PC1);
774           // split current edge
775           Handle(Geom_TrimmedCurve) tc1 = new Geom_TrimmedCurve(C,fp,param);
776           Handle(Geom_TrimmedCurve) tc2 = new Geom_TrimmedCurve(C,param,lp);
777           TopoDS_Edge E1,E2;
778           gp_Pnt Pfp;
779           C->D0(fp,Pfp);
780           if(Pfp.Distance(P1)<tol) {
781             B.MakeEdge(E1,tc1,tol);
782             B.Add(E1,V1);
783             TopoDS_Shape tmpV = VLocs.Value(jcurr).Oriented(TopAbs_REVERSED);
784             B.Add(E1,TopoDS::Vertex(tmpV));
785             tmpEdges.Append(E1);
786             B.MakeEdge(E2,tc2,tol);
787             tmpV = VLocs.Value(jcurr).Oriented(TopAbs_FORWARD);
788             B.Add(E2,TopoDS::Vertex(tmpV));
789             B.Add(E2,V2);
790           }
791           else {
792             B.MakeEdge(E1,tc2,tol);
793             TopoDS_Shape tmpV = VLocs.Value(jcurr).Oriented(TopAbs_FORWARD);
794             B.Add(E1,TopoDS::Vertex(tmpV));
795             B.Add(E1,V1);
796             E1.Reverse();
797             tmpEdges.Append(E1);
798             B.MakeEdge(E2,tc1,tol);
799             B.Add(E2,V2);
800             tmpV = VLocs.Value(jcurr).Oriented(TopAbs_REVERSED);
801             B.Add(E2,TopoDS::Vertex(tmpV));
802             E2.Reverse();
803           }
804           // create wire from tmpEdges
805           TopoDS_Wire W;
806           B.MakeWire(W);
807           for(j=1; j<=tmpEdges.Length(); j++)
808             B.Add(W,tmpEdges.Value(j));
809           Wires.Append(W);
810           jcurr++;
811           tmpEdges.Clear();
812           Edges.Remove(i);
813           Edges.InsertAfter(i-1,E1);
814           Edges.InsertAfter(i,E2);
815         }
816         else {
817           tmpEdges.Append(E);
818         }
819       }
820     }
821     // create wire from other edges
822     TopoDS_Wire W;
823     B.MakeWire(W);
824     for(; i<=Edges.Length(); i++)
825       B.Add(W,Edges.Value(i));
826     Wires.Append(W);
827     //cout<<"Wires.Length()="<<Wires.Length()<<endl;
828   }
829
830   if( Wires.Length() != nbLocs-1 ) {
831     if(aCI) delete aCI;
832     Standard_ConstructionError::Raise
833       ("One of location shapes is not lied on the path");
834   }
835
836   //TopTools_SequenceOfShape aSeqBases;
837   //TopTools_SequenceOfShape aSeqSubBases;
838   //TopTools_SequenceOfShape aSeqFaces;
839   TopoDS_Compound aComp;
840   B.MakeCompound(aComp);
841   for(i=1 ; i<nbBases; i++) {
842     TopoDS_Wire WPath = TopoDS::Wire(Wires.Value(i));
843     // 1 section
844     Handle(Standard_Transient) anItem1 = aBasesObjs->Value(i);
845     if(anItem1.IsNull())
846       continue;
847     Handle(GEOM_Function) aRefBase1 = Handle(GEOM_Function)::DownCast(anItem1);
848     if(aRefBase1.IsNull())
849       continue;
850     TopoDS_Shape aShBase1 = aRefBase1->GetValue();
851     if(aShBase1.IsNull())
852       continue;
853     TopAbs_ShapeEnum aType1 = aShBase1.ShapeType();
854     // 2 section
855     Handle(Standard_Transient) anItem2 = aBasesObjs->Value(i+1);
856     if(anItem2.IsNull())
857       continue;
858     Handle(GEOM_Function) aRefBase2 = Handle(GEOM_Function)::DownCast(anItem2);
859     if(aRefBase2.IsNull())
860       continue;
861     TopoDS_Shape aShBase2 = aRefBase2->GetValue();
862     if(aShBase2.IsNull())
863       continue;
864     TopAbs_ShapeEnum aType2 = aShBase2.ShapeType();
865
866     //BRepTools::Write(aShBase1,"/dn02/users_Linux/skl/work/Bugs/14857/base1.brep");
867
868     bool OkSec = ( aType1==TopAbs_SHELL || aType1==TopAbs_FACE ) &&
869                  ( aType2==TopAbs_SHELL || aType2==TopAbs_FACE );
870     if( !OkSec ) {
871       if(aCI) delete aCI;
872       Standard_ConstructionError::Raise("One of section shapes has invalid type");
873     }
874
875     bool CreateFewSolids = false;
876     // compare sections
877     TopExp_Explorer anExp;
878     Standard_Integer nbf1 = 0;
879     for ( anExp.Init( aShBase1, TopAbs_FACE ); anExp.More(); anExp.Next() ) {
880       nbf1++;
881     }
882     Standard_Integer nbf2 = 0;
883     for ( anExp.Init( aShBase2, TopAbs_FACE ); anExp.More(); anExp.Next() ) {
884       nbf2++;
885     }
886     if(nbf1==nbf2) {
887       CreateFewSolids = true;
888     }
889
890     /*
891     // check orientation of sections
892     bool NeedReverse = false;
893     {
894       // first section
895       anExp.Init( aShBase1, TopAbs_FACE );
896       TopoDS_Shape aFace = anExp.Current();
897       TColgp_SequenceOfPnt aPnts;
898       double xc=0, yc=0, zc=0;
899       for ( anExp.Init( aFace, TopAbs_VERTEX ); anExp.More(); anExp.Next() ) {
900         TopoDS_Vertex V = TopoDS::Vertex(anExp.Current());
901         aPnts.Append(BRep_Tool::Pnt(V));
902         xc += aPnts.Last().X();
903         yc += aPnts.Last().Y();
904         zc += aPnts.Last().Z();
905       }
906       gp_Pnt PC( xc/aPnts.Length(), yc/aPnts.Length(), zc/aPnts.Length() );
907       gp_Vec V1(PC,aPnts.Value(1));
908       gp_Vec V2(PC,aPnts.Value(2));
909       gp_Vec VN = V1.Crossed(V2);
910       for(int ip=2; ip<aPnts.Length(); ip++) {
911         V1 = gp_Vec(PC,aPnts.Value(ip));
912         V2 = gp_Vec(PC,aPnts.Value(ip+1));
913         VN.Add(V1.Crossed(V2));
914       }
915       gp_Vec PathNorm;
916       gp_Pnt PLoc = BRep_Tool::Pnt(TopoDS::Vertex(VLocs(i)));
917       TopExp_Explorer WE;
918       for ( WE.Init( WPath, TopAbs_EDGE ); WE.More(); WE.Next() ) {
919         TopoDS_Edge edge = TopoDS::Edge(WE.Current());
920         double tol = BRep_Tool::Tolerance(edge);
921         TopoDS_Vertex VF = sae.FirstVertex(edge);
922         gp_Pnt PF = BRep_Tool::Pnt(VF);
923         if( PF.Distance(PLoc) < tol ) {
924           double fp,lp;
925           Handle(Geom_Curve) C = BRep_Tool::Curve(edge,fp,lp);
926           gp_Pnt P1,P2;
927           C->D0(fp,P1);
928           if( P1.Distance(PLoc) < tol ) {
929             C->D0(fp+(lp-fp)/100,P2);
930           }
931           else {
932             C->D0(lp,P1);
933             C->D0(lp+(fp-lp)/100,P2);
934           }
935           PathNorm = gp_Vec(P1,P2);
936           break;
937         }
938         else {
939           TopoDS_Vertex VL = sae.LastVertex(edge);
940           gp_Pnt PL = BRep_Tool::Pnt(VL);
941           if( PL.Distance(PLoc) < tol ) {
942             double fp,lp;
943             Handle(Geom_Curve) C = BRep_Tool::Curve(edge,fp,lp);
944             gp_Pnt P1,P2;
945             C->D0(fp,P1);
946             if( P1.Distance(PLoc) < tol ) {
947               C->D0(fp+(lp-fp)/100,P2);
948             }
949             else {
950               C->D0(lp,P1);
951               C->D0(lp+(fp-lp)/100,P2);
952             }
953             PathNorm = gp_Vec(P2,P1);
954             break;
955           }
956         }
957       }
958       cout<<"VN("<<VN.X()<<","<<VN.Y()<<","<<VN.Z()<<")"<<endl;
959       cout<<"PathNorm("<<PathNorm.X()<<","<<PathNorm.Y()<<","<<PathNorm.Z()<<")"<<endl;
960       if(fabs(VN.Angle(PathNorm))>PI/2.) {
961         NeedReverse = true;
962         aShBase1.Reverse();
963       }
964     }
965     {
966       // second section
967       anExp.Init( aShBase2, TopAbs_FACE );
968       TopoDS_Shape aFace = anExp.Current();
969       TColgp_SequenceOfPnt aPnts;
970       double xc=0, yc=0, zc=0;
971       for ( anExp.Init( aFace, TopAbs_VERTEX ); anExp.More(); anExp.Next() ) {
972         TopoDS_Vertex V = TopoDS::Vertex(anExp.Current());
973         aPnts.Append(BRep_Tool::Pnt(V));
974         xc += aPnts.Last().X();
975         yc += aPnts.Last().Y();
976         zc += aPnts.Last().Z();
977       }
978       gp_Pnt PC( xc/aPnts.Length(), yc/aPnts.Length(), zc/aPnts.Length() );
979       gp_Vec V1(PC,aPnts.Value(1));
980       gp_Vec V2(PC,aPnts.Value(2));
981       gp_Vec VN = V1.Crossed(V2);
982       for(int ip=2; ip<aPnts.Length(); ip++) {
983         V1 = gp_Vec(PC,aPnts.Value(ip));
984         V2 = gp_Vec(PC,aPnts.Value(ip+1));
985         VN.Add(V1.Crossed(V2));
986       }
987       gp_Vec PathNorm;
988       gp_Pnt PLoc = BRep_Tool::Pnt(TopoDS::Vertex(VLocs(i+1)));
989       TopExp_Explorer WE;
990       for ( WE.Init( WPath, TopAbs_EDGE ); WE.More(); WE.Next() ) {
991         TopoDS_Edge edge = TopoDS::Edge(WE.Current());
992         double tol = BRep_Tool::Tolerance(edge);
993         TopoDS_Vertex VF = sae.FirstVertex(edge);
994         gp_Pnt PF = BRep_Tool::Pnt(VF);
995         if( PF.Distance(PLoc) < tol ) {
996           double fp,lp;
997           Handle(Geom_Curve) C = BRep_Tool::Curve(edge,fp,lp);
998           gp_Pnt P1,P2;
999           C->D0(fp,P1);
1000           if( P1.Distance(PLoc) < tol ) {
1001             C->D0(fp+(lp-fp)/100,P2);
1002           }
1003           else {
1004             C->D0(lp,P1);
1005             C->D0(lp+(fp-lp)/100,P2);
1006           }
1007           PathNorm = gp_Vec(P2,P1);
1008           break;
1009         }
1010         else {
1011           TopoDS_Vertex VL = sae.LastVertex(edge);
1012           gp_Pnt PL = BRep_Tool::Pnt(VL);
1013           if( PL.Distance(PLoc) < tol ) {
1014             double fp,lp;
1015             Handle(Geom_Curve) C = BRep_Tool::Curve(edge,fp,lp);
1016             gp_Pnt P1,P2;
1017             C->D0(fp,P1);
1018             if( P1.Distance(PLoc) < tol ) {
1019               C->D0(fp+(lp-fp)/100,P2);
1020             }
1021             else {
1022               C->D0(lp,P1);
1023               C->D0(lp+(fp-lp)/100,P2);
1024             }
1025             PathNorm = gp_Vec(P2,P1);
1026             break;
1027           }
1028         }
1029       }
1030       //cout<<"VN("<<VN.X()<<","<<VN.Y()<<","<<VN.Z()<<")"<<endl;
1031       //cout<<"PathNorm("<<PathNorm.X()<<","<<PathNorm.Y()<<","<<PathNorm.Z()<<")"<<endl;
1032       if(fabs(VN.Angle(PathNorm))>PI/2.)
1033         aShBase2.Reverse();
1034     }
1035     */
1036
1037     if(!CreateFewSolids) {
1038       // we can create only one solid
1039       TopoDS_Shape aWire1, aWire2;
1040       // prepare aWire1
1041       if(aType1==TopAbs_SHELL) {
1042         // create wire as boundary contour if shell is no closed
1043         // get free boundary shapes
1044         ShapeAnalysis_FreeBounds anAnalizer( aShBase1 );
1045         TopoDS_Compound aClosed = anAnalizer.GetClosedWires();
1046         //TopExp_Explorer anExp;
1047         Standard_Integer NbWires = 0;
1048         for ( anExp.Init( aClosed, TopAbs_WIRE ); anExp.More(); anExp.Next() ) {
1049           NbWires++;
1050           aWire1 = anExp.Current();
1051         }
1052         if(NbWires!=1) {
1053           // bad case
1054           if(aCI) delete aCI;
1055           Standard_ConstructionError::Raise("Bad shell is used as section ");
1056         }
1057       }
1058       else { // aType1==TopAbs_FACE
1059         TopExp_Explorer aExpW(aShBase1,TopAbs_WIRE);
1060         aWire1 = aExpW.Current();
1061       }
1062       // prepare aWire2
1063       if(aType2==TopAbs_SHELL) {
1064         // create wire as boundary contour if shell is no closed
1065         // get free boundary shapes
1066         ShapeAnalysis_FreeBounds anAnalizer( aShBase2 );
1067         TopoDS_Compound aClosed = anAnalizer.GetClosedWires();
1068         //TopExp_Explorer anExp;
1069         Standard_Integer NbWires = 0;
1070         for ( anExp.Init( aClosed, TopAbs_WIRE ); anExp.More(); anExp.Next() ) {
1071           NbWires++;
1072           aWire2 = anExp.Current();
1073         }
1074         if(NbWires!=1) {
1075           // bad case
1076           if(aCI) delete aCI;
1077           Standard_ConstructionError::Raise("Bad shell is used as section ");
1078         }
1079       }
1080       else { // aType2==TopAbs_FACE
1081         TopExp_Explorer aExpW(aShBase2,TopAbs_WIRE);
1082         aWire2 = aExpW.Current();
1083       }
1084       // make pipe using aWire1 and aWire2
1085       if( !aWire1.IsNull() && !aWire2.IsNull() ) {
1086         //BRepOffsetAPI_MakePipeShell aBuilder(aWirePath);
1087         BRepOffsetAPI_MakePipeShell aBuilder(WPath);
1088         aBuilder.Add(aWire1, TopoDS::Vertex(VLocs(i)),
1089                      aWithContact, aWithCorrect);
1090         aBuilder.Add(aWire2, TopoDS::Vertex(VLocs(i+1)),
1091                      aWithContact, aWithCorrect);
1092         if(!aBuilder.IsReady()) {
1093           if(aCI) delete aCI;
1094           Standard_ConstructionError::Raise("Invalid input data for building PIPE: bases are invalid");
1095         }
1096         aBuilder.Build();
1097         TopoDS_Shape aShape = aBuilder.Shape();
1098         TopoDS_Shell aShell;
1099         B.MakeShell(aShell);
1100         for ( anExp.Init( aShape, TopAbs_FACE ); anExp.More(); anExp.Next() ) {
1101           B.Add(aShell,anExp.Current());
1102         }
1103         for ( anExp.Init( aShBase1, TopAbs_FACE ); anExp.More(); anExp.Next() ) {
1104           B.Add(aShell,anExp.Current());
1105         }
1106         for ( anExp.Init( aShBase2, TopAbs_FACE ); anExp.More(); anExp.Next() ) {
1107           B.Add(aShell,anExp.Current());
1108         }
1109         // make sewing for this shell
1110         Handle(BRepBuilderAPI_Sewing) aSewing = new BRepBuilderAPI_Sewing;
1111         aSewing->SetTolerance(Precision::Confusion());
1112         aSewing->SetFaceMode(Standard_True);
1113         aSewing->SetFloatingEdgesMode(Standard_False);
1114         aSewing->SetNonManifoldMode(Standard_False);
1115         for ( anExp.Init( aShell, TopAbs_FACE ); anExp.More(); anExp.Next() ) {
1116           aSewing->Add(anExp.Current());
1117         }
1118         aSewing->Perform();
1119         const TopoDS_Shape aSewShape = aSewing->SewedShape();
1120         if( aSewShape.ShapeType() == TopAbs_SHELL ) {
1121           aShell = TopoDS::Shell(aSewShape);
1122           GProp_GProps aSystem;
1123           BRepGProp::VolumeProperties(aShell, aSystem);
1124           if(aSystem.Mass()<0) {
1125             aShell.Reverse();
1126           }
1127           if(BRep_Tool::IsClosed(aShell)) {
1128             TopoDS_Solid aSolid;
1129             B.MakeSolid(aSolid);
1130             B.Add(aSolid,aShell);
1131             B.Add(aComp,aSolid);
1132           }
1133           else {
1134             B.Add(aComp,aShell);
1135           }
1136         }
1137         else {
1138           B.Add(aComp,aShell);
1139         }
1140       }
1141     }
1142     else {
1143       // main block - creation few solids (for each pair of faces)
1144       TopTools_MapOfShape aFaces1,aFaces2;
1145       for ( anExp.Init( aShBase1, TopAbs_FACE ); anExp.More(); anExp.Next() ) {
1146         aFaces1.Add(anExp.Current());
1147       }
1148       for ( anExp.Init( aShBase2, TopAbs_FACE ); anExp.More(); anExp.Next() ) {
1149         aFaces2.Add(anExp.Current());
1150       }
1151       // creating map of edge faces
1152       TopTools_IndexedDataMapOfShapeListOfShape aMapEdgeFaces1;
1153       TopExp::MapShapesAndAncestors(aShBase1, TopAbs_EDGE, TopAbs_FACE, aMapEdgeFaces1);
1154       TopTools_IndexedDataMapOfShapeListOfShape aMapEdgeFaces2;
1155       TopExp::MapShapesAndAncestors(aShBase2, TopAbs_EDGE, TopAbs_FACE, aMapEdgeFaces2);
1156
1157       // constuct map face->face
1158       TopTools_IndexedDataMapOfShapeShape FF;
1159       TopoDS_Shape FS1,FS2;
1160       if(nbSubBases==0) {
1161         // find edge the most distant from location point
1162         // (this edge is not shared by two faces)
1163         double maxdist = 0.;
1164         TopoDS_Shape E1;
1165         TopoDS_Vertex V11,V21;
1166         for(j=1; j<=aMapEdgeFaces1.Extent(); j++) {
1167           TopoDS_Shape tmp = aMapEdgeFaces1.FindKey(j);
1168           const TopTools_ListOfShape& aList = aMapEdgeFaces1.FindFromKey(tmp);
1169           if(aList.Extent()>1)
1170             continue;
1171           TopExp_Explorer expv;
1172           expv.Init( tmp, TopAbs_VERTEX );
1173           TopoDS_Vertex V1 = TopoDS::Vertex(expv.Current());
1174           expv.Next();
1175           TopoDS_Vertex V2 = TopoDS::Vertex(expv.Current());
1176           gp_Pnt P1 = BRep_Tool::Pnt(V1);
1177           gp_Pnt P2 = BRep_Tool::Pnt(V2);
1178           double dist = PLocs.Value(i).Distance(P1) + PLocs.Value(i).Distance(P2);
1179           if(dist>maxdist) {
1180             E1 = tmp;
1181             V11 = V1;
1182             V21 = V2;
1183             TopTools_ListIteratorOfListOfShape anIter(aList);
1184             FS1 = anIter.Value();
1185             maxdist = dist;
1186           }
1187         }
1188         // main direction for comparing
1189         gp_Vec VM(PLocs.Value(i),PLocs.Value(i+1));
1190         // find corresponding edge from next section
1191         double minang = PI;
1192         gp_Pnt P11 = BRep_Tool::Pnt(V11);
1193         gp_Pnt P21 = BRep_Tool::Pnt(V21);
1194         TopoDS_Shape E2;
1195         TopoDS_Vertex V12,V22;
1196         for(j=1; j<=aMapEdgeFaces2.Extent(); j++) {
1197           TopoDS_Shape tmp = aMapEdgeFaces2.FindKey(j);
1198           const TopTools_ListOfShape& aList = aMapEdgeFaces2.FindFromKey(tmp);
1199           if(aList.Extent()>1)
1200             continue;
1201           TopExp_Explorer expv;
1202           expv.Init( tmp, TopAbs_VERTEX );
1203           TopoDS_Vertex V1tmp = TopoDS::Vertex(expv.Current());
1204           expv.Next();
1205           TopoDS_Vertex V2tmp = TopoDS::Vertex(expv.Current());
1206           gp_Pnt P1tmp = BRep_Tool::Pnt(V1tmp);
1207           gp_Pnt P2tmp = BRep_Tool::Pnt(V2tmp);
1208           double d1 = P1tmp.Distance(P11) + P2tmp.Distance(P21);
1209           double d2 = P1tmp.Distance(P21) + P2tmp.Distance(P11);
1210           TopoDS_Vertex V1,V2;
1211           gp_Pnt P1,P2;
1212           if(d1>d2) {
1213             V1 = V2tmp; P1 = P2tmp;
1214             V2 = V1tmp; P2 = P1tmp;
1215           }
1216           else {
1217             V1 = V1tmp; P1 = P1tmp;
1218             V2 = V2tmp; P2 = P2tmp;
1219           }
1220           gp_Vec Vec1(P11,P1);
1221           gp_Vec Vec2(P21,P2);
1222           double ang = fabs(Vec1.Angle(VM)) + fabs(Vec2.Angle(VM));
1223           if(ang<minang) {
1224             E2 = tmp;
1225             V12 = V1;
1226             V22 = V2;
1227             TopTools_ListIteratorOfListOfShape anIter(aList);
1228             FS2 = anIter.Value();
1229             minang = ang;
1230           }
1231         }
1232         // put all pairs to map FF
1233         FF.Add(FS1,FS2);
1234         FF.Add(E1,E2);
1235         FF.Add(V11,V12);
1236         FF.Add(V21,V22);
1237
1238         // add pairs of edges to FF
1239         bool stat =  FillForOtherEdges(FS1,E1,V11,FF);
1240         if( !stat ) {
1241           if(aCI) delete aCI;
1242           Standard_ConstructionError::Raise("FindForOtherEdges: Can not mapping other egdes");
1243         }
1244
1245       }
1246       else {
1247         { // 1 section
1248           Handle(Standard_Transient) anItem = aSubBasesObjs->Value(i);
1249           if(anItem.IsNull()) {
1250             if(aCI) delete aCI;
1251             Standard_ConstructionError::Raise("Invalid subbase shape");
1252           }
1253           Handle(GEOM_Function) aRefBase = Handle(GEOM_Function)::DownCast(anItem);
1254           if(aRefBase.IsNull()) {
1255             if(aCI) delete aCI;
1256             Standard_ConstructionError::Raise("Invalid subbase shape");
1257           }
1258           TopoDS_Shape aSh = aRefBase->GetValue();
1259           if(aSh.IsNull()) {
1260             if(aCI) delete aCI;
1261             Standard_ConstructionError::Raise("Invalid subbase shape");
1262           }
1263           if(aSh.ShapeType()!=TopAbs_FACE) {
1264             if(aCI) delete aCI;
1265             Standard_ConstructionError::Raise("Invalid subbase shape");
1266           }
1267           FS1 = aSh;
1268         }
1269         { // 2 section
1270           Handle(Standard_Transient) anItem = aSubBasesObjs->Value(i+1);
1271           if(anItem.IsNull()) {
1272             if(aCI) delete aCI;
1273             Standard_ConstructionError::Raise("Invalid subbase shape");
1274           }
1275           Handle(GEOM_Function) aRefBase = Handle(GEOM_Function)::DownCast(anItem);
1276           if(aRefBase.IsNull()) {
1277             if(aCI) delete aCI;
1278             Standard_ConstructionError::Raise("Invalid subbase shape");
1279           }
1280           TopoDS_Shape aSh = aRefBase->GetValue();
1281           if(aSh.IsNull()) {
1282             if(aCI) delete aCI;
1283             Standard_ConstructionError::Raise("Invalid subbase shape");
1284           }
1285           if(aSh.ShapeType()!=TopAbs_FACE) {
1286             if(aCI) delete aCI;
1287             Standard_ConstructionError::Raise("Invalid subbase shape");
1288           }
1289           FS2 = aSh;
1290         }
1291
1292         if( !aFaces1.Contains(FS1) || !aFaces2.Contains(FS2) ) {
1293           if(aCI) delete aCI;
1294           Standard_ConstructionError::Raise("Invalid subbase shape");
1295         }
1296
1297         FF.Add(FS1,FS2);
1298
1299         // add pairs of edges to FF
1300         bool stat =  FillCorrespondingEdges(FS1, FS2, TopoDS::Vertex(VLocs(i)),
1301                                             TopoDS::Vertex(VLocs(i+1)), WPath, FF);
1302         if( !stat ) {
1303           if(aCI) delete aCI;
1304           Standard_ConstructionError::Raise("Can not create correct pipe");
1305         }
1306       }
1307
1308       FindNextPairOfFaces(FS1, aMapEdgeFaces1, aMapEdgeFaces2, FF, aCI);
1309
1310
1311       // make pipe for each pair of faces
1312       for(j=1; j<=FF.Extent(); j++) {
1313         TopoDS_Shape F1 = FF.FindKey(j);
1314         if( F1.ShapeType() != TopAbs_FACE )
1315           continue;
1316         TopoDS_Shape F2 = FF.FindFromIndex(j);
1317         TopExp_Explorer aExpW1(F1,TopAbs_WIRE);
1318         TopoDS_Wire aWire1 = TopoDS::Wire(aExpW1.Current());
1319         TopExp_Explorer aExpW2(F2,TopAbs_WIRE);
1320         TopoDS_Wire aWire2 = TopoDS::Wire(aExpW2.Current());
1321         // make pipe using aWire1 and aWire2
1322         if( !aWire1.IsNull() && !aWire2.IsNull() ) {
1323           BRepOffsetAPI_MakePipeShell aBuilder(WPath);
1324           aBuilder.Add(aWire1, TopoDS::Vertex(VLocs(i)),
1325                        aWithContact, aWithCorrect);
1326           aBuilder.Add(aWire2, TopoDS::Vertex(VLocs(i+1)),
1327                        aWithContact, aWithCorrect);
1328           if(!aBuilder.IsReady()) {
1329             if(aCI) delete aCI;
1330             Standard_ConstructionError::Raise("Invalid input data for building PIPE: bases are invalid");
1331           }
1332           aBuilder.Build();
1333           TopoDS_Shape aShape = aBuilder.Shape();
1334           TopoDS_Shell aShell;
1335           B.MakeShell(aShell);
1336           for ( anExp.Init( aShape, TopAbs_FACE ); anExp.More(); anExp.Next() ) {
1337             B.Add(aShell,anExp.Current());
1338           }
1339
1340           B.Add(aShell,F1);
1341           B.Add(aShell,F2);
1342           // make sewing for this shell
1343           Handle(BRepBuilderAPI_Sewing) aSewing = new BRepBuilderAPI_Sewing;
1344           aSewing->SetTolerance(Precision::Confusion());
1345           aSewing->SetFaceMode(Standard_True);
1346           aSewing->SetFloatingEdgesMode(Standard_False);
1347           aSewing->SetNonManifoldMode(Standard_False);
1348           for ( anExp.Init( aShell, TopAbs_FACE ); anExp.More(); anExp.Next() ) {
1349             aSewing->Add(anExp.Current());
1350           }
1351           aSewing->Perform();
1352           const TopoDS_Shape aSewShape = aSewing->SewedShape();
1353           if( aSewShape.ShapeType() == TopAbs_SHELL ) {
1354             aShell = TopoDS::Shell(aSewShape);
1355             GProp_GProps aSystem;
1356             BRepGProp::VolumeProperties(aShell, aSystem);
1357             if(aSystem.Mass()<0) {
1358               //cout<<"aSewShape is reversed"<<endl;
1359               aShell.Reverse();
1360             }
1361             if(BRep_Tool::IsClosed(aShell)) {
1362               TopoDS_Solid aSolid;
1363               B.MakeSolid(aSolid);
1364               B.Add(aSolid,aShell);
1365               B.Add(aComp,aSolid);
1366             }
1367             else {
1368               B.Add(aComp,aShell);
1369             }
1370           }
1371           else {
1372             B.Add(aComp,aShell);
1373           }
1374         }
1375       }
1376
1377     }
1378   }
1379
1380   //BRepTools::Write(aComp,"/dn02/users_Linux/skl/work/Bugs/14857/comp.brep");
1381   return aComp;
1382 }
1383
1384
1385 //=======================================================================
1386 //function : CreatePipeShellsWithoutPath
1387 //purpose  : auxilary for Execute()
1388 //=======================================================================
1389 static TopoDS_Shape CreatePipeShellsWithoutPath(GEOMImpl_IPipe* aCI)
1390 {
1391   //cout<<"CreatePipeShellsWithoutPath"<<endl;
1392   int i,j;
1393   BRep_Builder B;
1394
1395   GEOMImpl_IPipeShellSect* aCIDS = (GEOMImpl_IPipeShellSect*)aCI;
1396   // shell sections
1397   Handle(TColStd_HSequenceOfTransient) aBasesObjs = aCIDS->GetBases();
1398   // vertex for recognition
1399   Handle(TColStd_HSequenceOfTransient) VObjs = aCIDS->GetLocations();
1400
1401   Standard_Integer nbBases = aBasesObjs->Length(),
1402     nbv = (VObjs.IsNull() ? 0 :VObjs->Length());
1403
1404   if( nbv != nbBases ) {
1405     if(aCI) delete aCI;
1406     Standard_ConstructionError::Raise("Number of shapes for recognition is invalid");
1407   }
1408
1409
1410   TopTools_SequenceOfShape SecVs,Bases;
1411   for(i=1; i<=nbBases; i++) {
1412     // vertex
1413     Handle(Standard_Transient) anItem = VObjs->Value(i);
1414     if(anItem.IsNull())
1415       continue;
1416     Handle(GEOM_Function) aRef = Handle(GEOM_Function)::DownCast(anItem);
1417     TopoDS_Shape V = aRef->GetValue();
1418     if(V.IsNull() || V.ShapeType() != TopAbs_VERTEX)
1419       continue;
1420     SecVs.Append(V);
1421     // section
1422     anItem = aBasesObjs->Value(i);
1423     if(anItem.IsNull())
1424       continue;
1425     aRef = Handle(GEOM_Function)::DownCast(anItem);
1426     TopoDS_Shape aSh = aRef->GetValue();
1427     if(aSh.IsNull())
1428       continue;
1429     Bases.Append(aSh);
1430   }
1431   nbv = SecVs.Length();
1432   nbBases = Bases.Length();
1433   if( nbv != nbBases ) {
1434     if(aCI) delete aCI;
1435     Standard_ConstructionError::Raise("One of shapes for recognition is not a vertex");
1436   }
1437
1438   TopoDS_Compound aComp;
1439   B.MakeCompound(aComp);
1440
1441   for(i=1 ; i<nbBases; i++) {
1442     MESSAGE ("Make pipe between sections "<<i<<" and "<<i+1);
1443     TopoDS_Shape aShBase1 = Bases.Value(i);
1444     TopoDS_Shape aShBase2 = Bases.Value(i+1);
1445     TopExp_Explorer anExp;
1446     Standard_Integer nbf1 = 0;
1447     for ( anExp.Init( aShBase1, TopAbs_FACE ); anExp.More(); anExp.Next() ) {
1448       nbf1++;
1449     }
1450     Standard_Integer nbf2 = 0;
1451     for ( anExp.Init( aShBase2, TopAbs_FACE ); anExp.More(); anExp.Next() ) {
1452       nbf2++;
1453     }
1454     //cout<<"nbf1="<<nbf1<<" nbf2="<<nbf2<<endl;
1455     if(nbf1!=nbf2) {
1456       if(aCI) delete aCI;
1457       Standard_ConstructionError::Raise("Different number of faces in the sections");
1458     }
1459
1460     TopTools_MapOfShape aFaces1,aFaces2;
1461     for ( anExp.Init( aShBase1, TopAbs_FACE ); anExp.More(); anExp.Next() ) {
1462       aFaces1.Add(anExp.Current());
1463     }
1464     for ( anExp.Init( aShBase2, TopAbs_FACE ); anExp.More(); anExp.Next() ) {
1465       aFaces2.Add(anExp.Current());
1466     }
1467
1468     // creating map of edge faces
1469     TopTools_IndexedDataMapOfShapeListOfShape aMapEdgeFaces1;
1470     TopExp::MapShapesAndAncestors(aShBase1, TopAbs_EDGE, TopAbs_FACE, aMapEdgeFaces1);
1471     TopTools_IndexedDataMapOfShapeListOfShape aMapEdgeFaces2;
1472     TopExp::MapShapesAndAncestors(aShBase2, TopAbs_EDGE, TopAbs_FACE, aMapEdgeFaces2);
1473
1474     // constuct map face->face (and subshapes)
1475     TopTools_IndexedDataMapOfShapeShape FF;
1476     //TopoDS_Shape FS1 = SecFs.Value(i), FS2 = SecFs.Value(i+1);
1477     TopoDS_Shape FS1, FS2;
1478     TopoDS_Vertex V1 = TopoDS::Vertex(SecVs(i));
1479     TopoDS_Vertex V2 = TopoDS::Vertex(SecVs(i+1));
1480     FindFirstPairFaces(aShBase1, aShBase2, V1, V2, FS1, FS2);
1481
1482     FF.Add(FS1,FS2);
1483     MESSAGE ("  first pair of corresponding faces is found");
1484
1485     // add pairs of edges and vertexes to FF
1486     bool stat =  FillCorrespondingEdges(FS1, FS2, V1, V2, FF);
1487     if( !stat ) {
1488       if(aCI) delete aCI;
1489       Standard_ConstructionError::Raise("Can not create correct pipe");
1490     }
1491     MESSAGE ("  correspondences for subshapes of first pair of faces is found");
1492
1493     FindNextPairOfFaces(FS1, aMapEdgeFaces1, aMapEdgeFaces2, FF, aCI);
1494     MESSAGE ("  other correspondences is found, make pipe for all pairs of faces");
1495
1496     // make pipe for each pair of faces
1497     // auxilary map vertex->edge for created pipe edges
1498     TopTools_IndexedDataMapOfShapeShape VPE;
1499     ShapeAnalysis_Edge sae;
1500     //cout<<"FF.Extent()="<<FF.Extent()<<endl;
1501     int nbff = 0;
1502     for(j=1; j<=FF.Extent(); j++) {
1503       TopoDS_Shape F1 = FF.FindKey(j);
1504       if( F1.ShapeType() != TopAbs_FACE )
1505         continue;
1506       TopoDS_Shape F2 = FF.FindFromIndex(j);
1507       nbff++;
1508
1509       //if(nbff!=3) continue;
1510
1511       MESSAGE ("    make pipe for "<<nbff<<" face");
1512
1513       Handle(Geom_Surface) S1 = BRep_Tool::Surface(TopoDS::Face(F1));
1514       if(S1->IsKind(STANDARD_TYPE(Geom_RectangularTrimmedSurface))) {
1515         Handle(Geom_RectangularTrimmedSurface) RTS =
1516           Handle(Geom_RectangularTrimmedSurface)::DownCast(S1);
1517         S1 = RTS->BasisSurface();
1518       }
1519       Handle(Geom_Plane) Pln1 = Handle(Geom_Plane)::DownCast(S1);
1520       if( Pln1.IsNull() ) {
1521         if(aCI) delete aCI;
1522         Standard_ConstructionError::Raise("Surface from face is not plane");
1523       }
1524       gp_Vec aDir1(Pln1->Axis().Direction());
1525
1526       Handle(Geom_Surface) S2 = BRep_Tool::Surface(TopoDS::Face(F2));
1527       if(S2->IsKind(STANDARD_TYPE(Geom_RectangularTrimmedSurface))) {
1528         Handle(Geom_RectangularTrimmedSurface) RTS =
1529           Handle(Geom_RectangularTrimmedSurface)::DownCast(S2);
1530         S2 = RTS->BasisSurface();
1531       }
1532       Handle(Geom_Plane) Pln2 =
1533           Handle(Geom_Plane)::DownCast(S2);
1534       if( Pln2.IsNull() ) {
1535         if(aCI) delete aCI;
1536         Standard_ConstructionError::Raise("Surface from face is not plane");
1537       }
1538       gp_Vec aDir2(Pln2->Axis().Direction());
1539
1540       gp_Pnt P1 = BRep_Tool::Pnt(TopoDS::Vertex(SecVs(i)));
1541       gp_Pnt P2 = BRep_Tool::Pnt(TopoDS::Vertex(SecVs(i+1)));
1542       gp_Vec aDir(P1,P2);
1543       if(fabs(aDir.Angle(aDir1))>PI/2.)
1544         aDir1.Reverse();
1545       if(fabs(aDir.Angle(aDir2))>PI/2.)
1546         aDir2.Reverse();
1547
1548       TopExp_Explorer anExpE(F1,TopAbs_EDGE);
1549       TopTools_SequenceOfShape aNewFs;
1550       //int nbee=0;
1551       for(; anExpE.More(); anExpE.Next()) {
1552         TopoDS_Edge E1 = TopoDS::Edge(anExpE.Current());
1553         //nbee++;
1554         if(!FF.Contains(E1))
1555           MESSAGE ("map FF not contains key E1");
1556
1557         if(VPE.Contains(E1)) {
1558           aNewFs.Append(VPE.FindFromKey(E1));
1559 #ifdef _DEBUG_
1560           MESSAGE ("    using existed face");
1561 #endif
1562           continue;
1563         }
1564
1565         TopoDS_Edge E3 = TopoDS::Edge(FF.FindFromKey(E1));
1566         TopoDS_Vertex V1 = sae.FirstVertex(E1);
1567         TopoDS_Vertex V2 = sae.LastVertex(E1);
1568         if(!FF.Contains(V1))
1569           MESSAGE ("map FF not contains key V1");
1570         if(!FF.Contains(V2))
1571           MESSAGE ("map FF not contains key V2");
1572         TopoDS_Vertex V3 = TopoDS::Vertex(FF.FindFromKey(V2));
1573         TopoDS_Vertex V4 = TopoDS::Vertex(FF.FindFromKey(V1));
1574         TopoDS_Vertex Vtmp = sae.FirstVertex(E3);
1575         if(Vtmp.IsSame(V4))
1576           E3.Reverse();
1577         gp_Pnt P1 = BRep_Tool::Pnt(V1);
1578         gp_Pnt P2 = BRep_Tool::Pnt(V2);
1579         gp_Pnt P3 = BRep_Tool::Pnt(V3);
1580         gp_Pnt P4 = BRep_Tool::Pnt(V4);
1581         // make E2
1582         TopoDS_Edge E2;
1583         Handle(Geom_BSplineCurve) C2;
1584         if(VPE.Contains(V2)) {
1585           E2 = TopoDS::Edge(VPE.FindFromKey(V2));
1586           double fp,lp;
1587           C2 = Handle(Geom_BSplineCurve)::DownCast(BRep_Tool::Curve(E2,fp,lp));
1588         }
1589         else {
1590           Handle(TColgp_HArray1OfPnt) HAP = new TColgp_HArray1OfPnt(1,2);
1591           HAP->SetValue(1,P2);
1592           HAP->SetValue(2,P3);
1593           GeomAPI_Interpolate anInt(HAP,Standard_False,1.e-7);
1594           anInt.Load(aDir1,aDir2);
1595           anInt.Perform();
1596           C2 = anInt.Curve();
1597           B.MakeEdge(E2,C2,1.e-7);
1598           B.Add(E2,TopoDS::Vertex(V2.Oriented(TopAbs_FORWARD)));
1599           B.Add(E2,TopoDS::Vertex(V3.Oriented(TopAbs_REVERSED)));
1600           VPE.Add(V2,E2);
1601         }
1602         // make E4
1603         TopoDS_Edge E4;
1604         Handle(Geom_BSplineCurve) C4;
1605         if(VPE.Contains(V1)) {
1606           E4 = TopoDS::Edge(VPE.FindFromKey(V1));
1607           double fp,lp;
1608           C4 = Handle(Geom_BSplineCurve)::DownCast(BRep_Tool::Curve(E4,fp,lp));
1609         }
1610         else {
1611           Handle(TColgp_HArray1OfPnt) HAP = new TColgp_HArray1OfPnt(1,2);
1612           HAP->SetValue(1,P1);
1613           HAP->SetValue(2,P4);
1614           GeomAPI_Interpolate anInt(HAP,Standard_False,1.e-7);
1615           anInt.Load(aDir1,aDir2);
1616           anInt.Perform();
1617           C4 = anInt.Curve();
1618           B.MakeEdge(E4,anInt.Curve(),1.e-7);
1619           B.Add(E4,TopoDS::Vertex(V1.Oriented(TopAbs_FORWARD)));
1620           B.Add(E4,TopoDS::Vertex(V4.Oriented(TopAbs_REVERSED)));
1621           VPE.Add(V1,E4);
1622         }
1623
1624         TopoDS_Wire W;
1625         B.MakeWire(W);
1626         B.Add(W,E1);
1627         B.Add(W,E2);
1628         B.Add(W,E3);
1629         B.Add(W,E4.Reversed());
1630         //cout<<"      wire for edge "<<nbee<<" is created"<<endl;
1631         //BRepTools::Write(W,"/dn02/users_Linux/skl/work/Bugs/14857/w.brep");
1632
1633         // make surface
1634
1635         double fp,lp;
1636         Handle(Geom_Curve) C1 = BRep_Tool::Curve(E1,fp,lp);
1637         //bool IsConicC1 = false;
1638         //if( C1->IsKind(STANDARD_TYPE(Geom_Conic)) ) {
1639         //  IsConicC1 = true;
1640         //  cout<<"C1 - Geom_Conic"<<endl;
1641         //}
1642         if( C1->IsKind(STANDARD_TYPE(Geom_Line)) || C1->IsKind(STANDARD_TYPE(Geom_Conic)) ) {
1643           C1 = new Geom_TrimmedCurve(C1,fp,lp);
1644         }
1645         //if(IsConicC1) {
1646         //  double tol = BRep_Tool::Tolerance(E1);
1647         //  GeomConvert_ApproxCurve ApxC1(C1,tol,GeomAbs_C1,10,5);
1648         //  C1 = ApxC1.Curve();
1649         //}
1650         Handle(Geom_Curve) C3 = BRep_Tool::Curve(E3,fp,lp);
1651         if( C3->IsKind(STANDARD_TYPE(Geom_Line)) || C3->IsKind(STANDARD_TYPE(Geom_Conic)) ) {
1652           C3 = new Geom_TrimmedCurve(C3,fp,lp);
1653         }
1654         //filebuf fic;
1655         //ostream os(&fic);
1656         //os.precision(15);
1657         Handle(Geom_BSplineCurve) CE1 =
1658           GeomConvert::CurveToBSplineCurve(C1,Convert_RationalC1);
1659         if(CE1->Degree()<3)
1660           CE1->IncreaseDegree(3);
1661         Handle(Geom_BSplineCurve) CE2 =
1662           GeomConvert::CurveToBSplineCurve(C2,Convert_RationalC1);
1663         if(CE2->Degree()<3)
1664           CE2->IncreaseDegree(3);
1665         Handle(Geom_BSplineCurve) CE3 =
1666           GeomConvert::CurveToBSplineCurve(C3,Convert_RationalC1);
1667         if(CE3->Degree()<3)
1668           CE3->IncreaseDegree(3);
1669         Handle(Geom_BSplineCurve) CE4 =
1670           GeomConvert::CurveToBSplineCurve(C4,Convert_RationalC1);
1671         if(CE4->Degree()<3)
1672           CE4->IncreaseDegree(3);
1673         //cout<<"CE1->Degree()="<<CE1->Degree()<<" CE2->Degree()="<<CE2->Degree()
1674         //    <<" CE3->Degree()="<<CE3->Degree()<<" CE4->Degree()="<<CE4->Degree()<<endl;
1675         //if(fic.open("/dn02/users_Linux/skl/work/Bugs/14857/ce1.brep",ios::out)) {
1676         //  os<<"DrawTrSurf_BSplineCurve"<<endl;
1677         //  GeomTools::Write(CE1,os);
1678         //  fic.close();
1679         //}
1680
1681         Handle(Geom_Surface) BS;
1682         try {
1683           GeomFill_BSplineCurves GF(CE1,CE2,CE3,CE4,GeomFill_CoonsStyle);
1684           //GeomFill_BSplineCurves GF(CE1,CE2,CE3,CE4,GeomFill_StretchStyle);
1685           BS = GF.Surface();
1686         }
1687         catch(...) {
1688           MESSAGE ("      can not create BSplineSurface - create Bezier");
1689           int NbP=26;
1690           TColgp_Array2OfPnt Points(1,NbP,1,NbP);
1691           double fp1,lp1,fp2,lp2;
1692           Handle(Geom_Curve) C1 = BRep_Tool::Curve(E1,fp1,lp1);
1693           Handle(Geom_Curve) C3 = BRep_Tool::Curve(E3,fp2,lp2);
1694           gp_Pnt P1C1,P2C1;
1695           C1->D0(fp1,P1C1);
1696           C1->D0(lp1,P2C1);
1697           gp_Pnt P1C3,P2C3;
1698           C3->D0(fp2,P1C3);
1699           C3->D0(lp2,P2C3);
1700           int n1,n2;
1701           double fp,lp;
1702           // get points from C1
1703           if(P1.Distance(P1C1)<1.e-6) {
1704             fp = fp1;
1705             lp = lp1;
1706           }
1707           else {
1708             fp = lp1;
1709             lp = fp1;
1710           }
1711           double step = (lp-fp)/(NbP-1);
1712           Points.SetValue(1,1,P1);
1713           double par = fp;
1714           for(n1=2; n1<NbP; n1++) {
1715             gp_Pnt P;
1716             par += step;
1717             C1->D0(par,P);
1718             Points.SetValue(1,n1,P);
1719           }
1720           Points.SetValue(1,NbP,P2);
1721           // get points from C3
1722           if(P4.Distance(P1C3)<1.e-6) {
1723             fp = fp2;
1724             lp = lp2;
1725           }
1726           else {
1727             fp = lp2;
1728             lp = fp2;
1729           }
1730           step = (lp-fp)/(NbP-1);
1731           Points.SetValue(NbP,1,P4);
1732           par = fp;
1733           for(n1=2; n1<NbP; n1++) {
1734             gp_Pnt P;
1735             par += step;
1736             C3->D0(par,P);
1737             Points.SetValue(NbP,n1,P);
1738           }
1739           Points.SetValue(NbP,NbP,P3);
1740           // create isolines and get points from them
1741           for(n1=1; n1<=NbP; n1++) {
1742             gp_Pnt PI1 = Points.Value(1,n1);
1743             gp_Pnt PI2 = Points.Value(NbP,n1);
1744             Handle(TColgp_HArray1OfPnt) HAP = new TColgp_HArray1OfPnt(1,2);
1745             HAP->SetValue(1,PI1);
1746             HAP->SetValue(2,PI2);
1747             GeomAPI_Interpolate anInt(HAP,Standard_False,1.e-7);
1748             anInt.Load(aDir1,aDir2);
1749             anInt.Perform();
1750             Handle(Geom_Curve) iso = anInt.Curve();
1751             fp = iso->FirstParameter();
1752             lp = iso->LastParameter();
1753             step = (lp-fp)/(NbP-1);
1754             par = fp;
1755             TopoDS_Compound VComp;
1756             B.MakeCompound(VComp);
1757             for(n2=2; n2<NbP; n2++) {
1758               gp_Pnt P;
1759               par += step;
1760               iso->D0(par,P);
1761               Points.SetValue(n2,n1,P);
1762             }
1763           }
1764           // create surface and face
1765           //Handle(Geom_BezierSurface) BS = new Geom_BezierSurface(Points);
1766           BS = new Geom_BezierSurface(Points);
1767         }
1768
1769         BRepBuilderAPI_MakeFace BB(BS,W);
1770         TopoDS_Face NewF = BB.Face();
1771         Handle(ShapeFix_Face) sff = new ShapeFix_Face(NewF);
1772         sff->Perform();
1773         sff->FixOrientation();
1774         TopoDS_Face FixedFace = sff->Face();
1775         aNewFs.Append(FixedFace);
1776         VPE.Add(E1,FixedFace);
1777         //cout<<"      face for edge "<<nbee<<" is created"<<endl;
1778         //BRepTools::Write(FixedFace,"/dn02/users_Linux/skl/work/Bugs/14857/f.brep");
1779       }
1780       // make shell
1781       TopoDS_Shell aShell;
1782       B.MakeShell(aShell);
1783       for(int nf=1; nf<=aNewFs.Length(); nf++) {
1784         B.Add(aShell,aNewFs(nf));
1785       }
1786       B.Add(aShell,F1);
1787       B.Add(aShell,F2);
1788
1789       // make sewing for this shell
1790       Handle(BRepBuilderAPI_Sewing) aSewing = new BRepBuilderAPI_Sewing;
1791       aSewing->SetTolerance(Precision::Confusion());
1792       aSewing->SetFaceMode(Standard_True);
1793       aSewing->SetFloatingEdgesMode(Standard_False);
1794       aSewing->SetNonManifoldMode(Standard_False);
1795       for ( anExp.Init( aShell, TopAbs_FACE ); anExp.More(); anExp.Next() ) {
1796         aSewing->Add(anExp.Current());
1797       }
1798       aSewing->Perform();
1799       MESSAGE ("    shell for face "<<nbff<<" is created");
1800       const TopoDS_Shape aSewShape = aSewing->SewedShape();
1801       //BRepTools::Write(aSewShape,"/dn02/users_Linux/skl/work/Bugs/14857/sew.brep");
1802       if( aSewShape.ShapeType() == TopAbs_SHELL ) {
1803         aShell = TopoDS::Shell(aSewShape);
1804         GProp_GProps aSystem;
1805         BRepGProp::VolumeProperties(aShell, aSystem);
1806         if(aSystem.Mass()<0) {
1807           //cout<<"aSewShape is reversed"<<endl;
1808           aShell.Reverse();
1809         }
1810         if(BRep_Tool::IsClosed(aShell)) {
1811           TopoDS_Solid aSolid;
1812           B.MakeSolid(aSolid);
1813           B.Add(aSolid,aShell);
1814           B.Add(aComp,aSolid);
1815           MESSAGE ("    solid for face "<<nbff<<" is created");
1816         }
1817         else {
1818           B.Add(aComp,aShell);
1819           MESSAGE ("    solid for face "<<nbff<<" is not created");
1820         }
1821       }
1822       else {
1823         B.Add(aComp,aShell);
1824         MESSAGE ("    solid for face "<<nbff<<" is not created");
1825       }
1826       //cout<<"    solid for face "<<nbff<<" is created"<<endl;
1827
1828       //Handle(ShapeFix_Shell) sfs = new ShapeFix_Shell(aShell);
1829       //sfs->Perform();
1830       //TopoDS_Shell FixedShell = sfs->Shell();
1831       /*
1832       GProp_GProps aSystem;
1833       BRepGProp::VolumeProperties(FixedShell, aSystem);
1834       if(aSystem.Mass()<0) {
1835         //cout<<"aSewShape is reversed"<<endl;
1836         FixedShell.Reverse();
1837       }
1838       if(BRep_Tool::IsClosed(FixedShell)) {
1839         TopoDS_Solid aSolid;
1840         B.MakeSolid(aSolid);
1841         B.Add(aSolid,aShell);
1842         B.Add(aComp,aSolid);
1843       }
1844       else {
1845         B.Add(aComp,FixedShell);
1846       }
1847       */
1848     }
1849   }
1850
1851   //BRepTools::Write(aComp,"/dn02/users_Linux/skl/work/Bugs/14857/comp.brep");
1852   return aComp;
1853 }
1854
1855
1856 //=======================================================================
1857 //function : CreatePipeBiNormalAlongVector
1858 //purpose  : auxilary for Execute()
1859 //=======================================================================
1860 static TopoDS_Shape CreatePipeBiNormalAlongVector(const TopoDS_Wire& aWirePath,
1861                                                   GEOMImpl_IPipe* aCI)
1862 {
1863   GEOMImpl_IPipeBiNormal* aCIBN = (GEOMImpl_IPipeBiNormal*)aCI;
1864
1865   Handle(GEOM_Function) aRefBase = aCIBN->GetBase();
1866   Handle(GEOM_Function) aRefVec = aCIBN->GetVector();
1867   TopoDS_Shape aShapeBase = aRefBase->GetValue();
1868   TopoDS_Shape aShapeVec = aRefVec->GetValue();
1869
1870   if (aShapeBase.IsNull()) {
1871     if(aCIBN) delete aCIBN;
1872     Standard_NullObject::Raise("MakePipe aborted : null base argument");
1873   }
1874
1875   TopoDS_Shape aProf;
1876   if( aShapeBase.ShapeType() == TopAbs_VERTEX ) {
1877     aProf = aShapeBase;
1878   }
1879   else if( aShapeBase.ShapeType() == TopAbs_EDGE) {
1880     aProf = BRepBuilderAPI_MakeWire(TopoDS::Edge(aShapeBase)).Shape();
1881   }
1882   else if( aShapeBase.ShapeType() == TopAbs_WIRE) {
1883     aProf = aShapeBase;
1884   }
1885   else if( aShapeBase.ShapeType() == TopAbs_FACE) {
1886     TopExp_Explorer wexp(aShapeBase,TopAbs_WIRE);
1887     aProf = wexp.Current();
1888   }
1889   else {
1890     Standard_TypeMismatch::Raise
1891       ("MakePipe aborted : invalid type of base");
1892   }
1893   BRepOffsetAPI_MakePipeShell PipeBuilder(aWirePath);
1894   PipeBuilder.Add(aProf);
1895
1896   if (aShapeVec.IsNull()) {
1897     if(aCIBN) delete aCIBN;
1898     Standard_NullObject::Raise
1899       ("MakePipe aborted : null vector argument");
1900   }
1901   if (aShapeVec.ShapeType() != TopAbs_EDGE)
1902     Standard_TypeMismatch::Raise
1903       ("MakePipe aborted: invalid type of vector");
1904   TopoDS_Edge anEdge = TopoDS::Edge(aShapeVec);
1905   TopoDS_Vertex V1, V2;
1906   TopExp::Vertices(anEdge, V1, V2, Standard_True);
1907   if (V1.IsNull() || V2.IsNull())
1908     Standard_NullObject::Raise
1909       ("MakePipe aborted: vector is not defined");
1910   gp_Vec aVec(BRep_Tool::Pnt(V1), BRep_Tool::Pnt(V2));
1911   gp_Dir BiNormal(aVec);
1912   PipeBuilder.SetMode(BiNormal);
1913   PipeBuilder.Build();
1914   if( aShapeBase.ShapeType() == TopAbs_FACE) {
1915       PipeBuilder.MakeSolid();
1916   }
1917
1918   return PipeBuilder.Shape();
1919 }
1920
1921
1922 //=======================================================================
1923 //function : Execute
1924 //purpose  :
1925 //=======================================================================
1926 Standard_Integer GEOMImpl_PipeDriver::Execute(TFunction_Logbook& log) const
1927 {
1928   //cout<<"PipeDriver::Execute"<<endl;
1929   if (Label().IsNull()) return 0;
1930   Handle(GEOM_Function) aFunction = GEOM_Function::GetFunction(Label());
1931   GEOMImpl_IPipe* aCI= 0;
1932   Standard_Integer aType = aFunction->GetType();
1933   if(aType == PIPE_BASE_PATH)
1934     aCI = new GEOMImpl_IPipe(aFunction);
1935   else if(aType == PIPE_DIFFERENT_SECTIONS)
1936     aCI = new GEOMImpl_IPipeDiffSect(aFunction);
1937   else if(aType == PIPE_SHELL_SECTIONS)
1938     aCI = new GEOMImpl_IPipeShellSect(aFunction);
1939   else if(aType == PIPE_SHELLS_WITHOUT_PATH)
1940     aCI = new GEOMImpl_IPipeShellSect(aFunction);
1941   else if(aType == PIPE_BI_NORMAL_ALONG_VECTOR)
1942     aCI = new GEOMImpl_IPipeBiNormal(aFunction);
1943   else
1944     return 0;
1945
1946   TopoDS_Wire aWirePath;
1947   if(aType != PIPE_SHELLS_WITHOUT_PATH) {
1948     // working with path
1949     Handle(GEOM_Function) aRefPath = aCI->GetPath();
1950     TopoDS_Shape aShapePath = aRefPath->GetValue();
1951
1952     if (aShapePath.IsNull()) {
1953       MESSAGE ("Driver : path is null");
1954       if(aCI) delete aCI;
1955       Standard_NullObject::Raise("MakePipe aborted : null path argument");
1956     }
1957
1958     // Get path contour
1959     if (aShapePath.ShapeType() == TopAbs_WIRE) {
1960       aWirePath = TopoDS::Wire(aShapePath);
1961     }
1962     else {
1963       if (aShapePath.ShapeType() == TopAbs_EDGE) {
1964         TopoDS_Edge anEdge = TopoDS::Edge(aShapePath);
1965         aWirePath = BRepBuilderAPI_MakeWire(anEdge);
1966       }
1967       else {
1968         if(aCI) delete aCI;
1969         Standard_TypeMismatch::Raise("MakePipe aborted : path shape is neither a wire nor an edge");
1970       }
1971     }
1972   }
1973
1974   TopoDS_Shape aShape;
1975
1976   if (aType == PIPE_BASE_PATH)
1977   {
1978     Handle(GEOM_Function) aRefBase = aCI->GetBase();
1979     TopoDS_Shape aShapeBase = aRefBase->GetValue();
1980
1981     if (aShapeBase.IsNull()) {
1982       if(aCI) delete aCI;
1983       Standard_NullObject::Raise("MakePipe aborted : null base argument");
1984     }
1985
1986     // Make pipe
1987     aShape = BRepOffsetAPI_MakePipe(aWirePath, aShapeBase);
1988   }
1989
1990   //building pipe with different sections
1991   else if (aType == PIPE_DIFFERENT_SECTIONS) {
1992     GEOMImpl_IPipeDiffSect* aCIDS = (GEOMImpl_IPipeDiffSect*)aCI;
1993     //GEOMImpl_IPipeDiffSect* aCIDS = static_cast<GEOMImpl_IPipeDiffSect*>(aCI);
1994     //BRepOffsetAPI_MakePipeShell aBuilder(aWirePath);
1995     Handle(TColStd_HSequenceOfTransient) aBasesObjs = aCIDS->GetBases ();
1996     Handle(TColStd_HSequenceOfTransient) aLocObjs = aCIDS->GetLocations ();
1997     Standard_Boolean aWithContact = (aCIDS->GetWithContactMode());
1998     Standard_Boolean aWithCorrect = (aCIDS->GetWithCorrectionMode());
1999
2000     Standard_Integer i =1, nbBases = aBasesObjs->Length(),
2001       nbLocs = (aLocObjs.IsNull() ? 0 :aLocObjs->Length());
2002
2003     if(nbLocs && nbLocs != nbBases) {
2004       if(aCI) delete aCI;
2005       Standard_ConstructionError::Raise("Number of sections is not equal to number of locations ");
2006     }
2007     TopTools_SequenceOfShape aSeqBases;
2008     TopTools_SequenceOfShape aSeqLocs;
2009     TopTools_SequenceOfShape aSeqFaces;
2010     for( ; i <= nbBases; i++) {
2011       Handle(Standard_Transient) anItem = aBasesObjs->Value(i);
2012       if(anItem.IsNull())
2013         continue;
2014       Handle(GEOM_Function) aRefBase = Handle(GEOM_Function)::DownCast(anItem);
2015       if(aRefBase.IsNull())
2016         continue;
2017       TopoDS_Shape aShapeBase = aRefBase->GetValue();
2018       if(aShapeBase.IsNull())
2019         continue;
2020       TopAbs_ShapeEnum aTypeBase = aShapeBase.ShapeType();
2021
2022       //if for section was specified face with a few wires then a few
2023       //    pipes were build and make solid
2024       Standard_Boolean NeedCreateSolid = Standard_False;
2025       if(aTypeBase == TopAbs_SHELL) {
2026         // create wire as boundary contour if shell is no closed
2027         // get free boundary shapes
2028         ShapeAnalysis_FreeBounds anAnalizer( aShapeBase );
2029         TopoDS_Compound aClosed = anAnalizer.GetClosedWires();
2030         TopExp_Explorer anExp;
2031         TopoDS_Shape aWire;
2032         Standard_Integer NbWires = 0;
2033         for ( anExp.Init( aClosed, TopAbs_WIRE ); anExp.More(); anExp.Next() ) {
2034           NbWires++;
2035           aWire = anExp.Current();
2036         }
2037         if(NbWires!=1) {
2038           // bad case
2039           if(aCI) delete aCI;
2040           Standard_ConstructionError::Raise("Bad shell is used as section ");
2041         }
2042         NeedCreateSolid = Standard_True;
2043         aSeqFaces.Append(aShapeBase);
2044         aSeqBases.Append(aWire);
2045       }
2046       else if(aTypeBase == TopAbs_FACE) {
2047         NeedCreateSolid = Standard_True;
2048         //for case one path should be used other type function
2049         aSeqFaces.Append(aShapeBase);
2050         TopExp_Explorer aExpW(aShapeBase,TopAbs_WIRE);
2051         for( ; aExpW.More(); aExpW.Next())
2052         {
2053           TopoDS_Shape aWireProf = aExpW.Current();
2054           aSeqBases.Append(aWireProf);
2055         }
2056       }
2057       else if(aTypeBase == TopAbs_WIRE || aTypeBase == TopAbs_VERTEX) {
2058         aSeqBases.Append(aShapeBase);
2059       }
2060       else if(aTypeBase == TopAbs_EDGE) {
2061         TopoDS_Edge anEdge = TopoDS::Edge(aShapeBase);
2062         TopoDS_Shape aWireProf = BRepBuilderAPI_MakeWire(anEdge);
2063         aSeqBases.Append(aWireProf);
2064       }
2065       if(nbLocs) {
2066         Handle(Standard_Transient) anItemLoc = aLocObjs->Value(i);
2067         if(anItemLoc.IsNull())
2068           continue;
2069         Handle(GEOM_Function) aRefLoc = Handle(GEOM_Function)::DownCast(anItemLoc);
2070         TopoDS_Shape aShapeLoc = aRefLoc->GetValue();
2071         if(aShapeLoc.IsNull() || aShapeLoc.ShapeType() != TopAbs_VERTEX)
2072           continue;
2073         aSeqLocs.Append(aShapeLoc);
2074       }
2075     }
2076
2077     nbLocs = aSeqLocs.Length();
2078
2079     // skl 02.05.2007
2080     TopTools_SequenceOfShape Edges;
2081     if(nbLocs>0) {
2082       // we have to check that each location shape is a vertex from
2083       // path and update aSeqLocs if it is needed (and possible)
2084       TColgp_SequenceOfPnt PLocs;
2085       for(i=1; i<=nbLocs; i++) {
2086         TopoDS_Vertex V = TopoDS::Vertex(aSeqLocs.Value(i));
2087         PLocs.Append(BRep_Tool::Pnt(V));
2088       }
2089       //TopTools_SequenceOfShape Edges;
2090       TopExp_Explorer anExp;
2091       for ( anExp.Init( aWirePath, TopAbs_EDGE ); anExp.More(); anExp.Next() ) {
2092         Edges.Append(anExp.Current());
2093       }
2094       int nbEdges = Edges.Length();
2095       ShapeAnalysis_Edge sae;
2096       TopoDS_Edge edge = TopoDS::Edge(Edges.First());
2097       double tol = BRep_Tool::Tolerance(edge);
2098       TopoDS_Vertex VF = sae.FirstVertex(edge);
2099       gp_Pnt PF = BRep_Tool::Pnt(VF);
2100       //cout<<"PF("<<PF.X()<<","<<PF.Y()<<","<<PF.Z()<<")"<<endl;
2101       if( PF.Distance(PLocs.First()) > tol ) {
2102         if(aCI) delete aCI;
2103         Standard_ConstructionError::Raise
2104           ("First location shapes is not coincided with first vertex of aWirePath");
2105       }
2106       aSeqLocs.ChangeValue(1) = VF;
2107       edge = TopoDS::Edge(Edges.Last());
2108       tol = BRep_Tool::Tolerance(edge);
2109       TopoDS_Vertex VL = sae.LastVertex(edge);
2110       gp_Pnt PL = BRep_Tool::Pnt(VL);
2111       if( PL.Distance(PLocs.Last()) > tol ) {
2112         if(aCI) delete aCI;
2113         Standard_ConstructionError::Raise
2114           ("Last location shapes is not coincided with last vertex of aWirePath");
2115       }
2116       aSeqLocs.ChangeValue(nbLocs) = VL;
2117       int jcurr = 2;
2118       for(i=1; i<=Edges.Length() && jcurr<nbLocs; i++) {
2119         TopoDS_Edge E = TopoDS::Edge(Edges.Value(i));
2120         tol = BRep_Tool::Tolerance(edge);
2121         TopoDS_Vertex V1 = sae.FirstVertex(E);
2122         TopoDS_Vertex V2 = sae.LastVertex(E);
2123         gp_Pnt P1 = BRep_Tool::Pnt(V1);
2124         gp_Pnt P2 = BRep_Tool::Pnt(V2);
2125         if( P2.Distance(PLocs.Value(jcurr)) < tol ) {
2126           aSeqLocs.ChangeValue(jcurr) = V2;
2127           jcurr++;
2128         }
2129         else {
2130           // find distance between E and aLocs(jcurr)
2131           double fp,lp;
2132           Handle(Geom_Curve) C = BRep_Tool::Curve(E,fp,lp);
2133           GeomAPI_ProjectPointOnCurve PPC (PLocs.Value(jcurr),C);
2134           if( PPC.NbPoints()>0 &&
2135               PLocs.Value(jcurr).Distance(PPC.Point(1)) < tol ) {
2136             double param = PPC.Parameter(1);
2137             gp_Pnt PC1;
2138             C->D0(param,PC1);
2139             // split current edge
2140             Handle(Geom_TrimmedCurve) tc1 = new Geom_TrimmedCurve(C,fp,param);
2141             Handle(Geom_TrimmedCurve) tc2 = new Geom_TrimmedCurve(C,param,lp);
2142             TopoDS_Edge E1,E2;
2143             BRep_Builder B;
2144             gp_Pnt Pfp;
2145             C->D0(fp,Pfp);
2146             if(Pfp.Distance(P1)<tol) {
2147               B.MakeEdge(E1,tc1,tol);
2148               B.Add(E1,V1);
2149               TopoDS_Shape tmpV = aSeqLocs.Value(jcurr).Oriented(TopAbs_REVERSED);
2150               B.Add(E1,TopoDS::Vertex(tmpV));
2151               B.MakeEdge(E2,tc2,tol);
2152               tmpV = aSeqLocs.Value(jcurr).Oriented(TopAbs_FORWARD);
2153               B.Add(E2,TopoDS::Vertex(tmpV));
2154               B.Add(E2,V2);
2155             }
2156             else {
2157               B.MakeEdge(E1,tc2,tol);
2158               TopoDS_Shape tmpV = aSeqLocs.Value(jcurr).Oriented(TopAbs_FORWARD);
2159               B.Add(E1,TopoDS::Vertex(tmpV));
2160               B.Add(E1,V1);
2161               E1.Reverse();
2162               B.MakeEdge(E2,tc1,tol);
2163               B.Add(E2,V2);
2164               tmpV = aSeqLocs.Value(jcurr).Oriented(TopAbs_REVERSED);
2165               B.Add(E2,TopoDS::Vertex(tmpV));
2166               E2.Reverse();
2167             }
2168             jcurr++;
2169             Edges.Remove(i);
2170             Edges.InsertAfter(i-1,E1);
2171             Edges.InsertAfter(i,E2);
2172           }
2173         }
2174       }
2175       if(nbEdges<Edges.Length()) {
2176         // one of edges was splitted => we have to update WirePath
2177         BRep_Builder B;
2178         TopoDS_Wire W;
2179         B.MakeWire(W);
2180         for(i=1; i<=Edges.Length(); i++) {
2181           B.Add(W,TopoDS::Edge(Edges.Value(i)));
2182         }
2183         aWirePath = W;
2184       }
2185     }
2186
2187     // check curvature of wire for condition that
2188     // max summary angle between directions along
2189     // wire path must be < 4*PI. If not - split wire
2190     // and seguences of shapes, perform pipe for each
2191     // and make sewing after that
2192     double fp,lp;
2193     Handle(Geom_Curve) C = BRep_Tool::Curve(TopoDS::Edge(Edges.Value(1)),fp,lp);
2194     gp_Pnt P1,P2;
2195     gp_Vec Vec1,Vec2;
2196     C->D1(fp,P1,Vec1);
2197     C->D1(lp,P2,Vec2);
2198     double SumAng = fabs(Vec1.Angle(Vec2));
2199     Vec1 = Vec2;
2200     P1 = P2;
2201     TColStd_SequenceOfInteger SplitEdgeNums,SplitLocNums;
2202     int LastLoc = 1;
2203     //cout<<"Edges.Length()="<<Edges.Length()<<endl;
2204     for(i=2; i<=Edges.Length(); i++) {
2205       TopoDS_Edge edge = TopoDS::Edge(Edges.Value(i));
2206       double tol = BRep_Tool::Tolerance(edge);
2207       Handle(Geom_Curve) C = BRep_Tool::Curve(edge,fp,lp);
2208       C->D1(lp,P2,Vec2);
2209       double ang = fabs(Vec1.Angle(Vec2));
2210       SumAng += ang;
2211       if(SumAng>4*PI) {
2212         SumAng = ang;
2213         SplitEdgeNums.Append(i-1);
2214         int j;
2215         for(j=LastLoc+1; j<=aSeqLocs.Length(); j++) {
2216           TopoDS_Vertex aVert = TopoDS::Vertex(aSeqLocs.Value(j));
2217           gp_Pnt P = BRep_Tool::Pnt(aVert);
2218           if( P1.Distance(P) < tol ) {
2219             SplitLocNums.Append(j);
2220             LastLoc = j;
2221             break;
2222           }
2223         }
2224       }
2225       Vec1 = Vec2;
2226       P1 = P2;
2227     }
2228
2229     //cout<<"SplitEdgeNums.Length()="<<SplitEdgeNums.Length()<<endl;
2230     //cout<<"SplitLocNums.Length()="<<SplitLocNums.Length()<<endl;
2231     if( SplitLocNums.Length()==SplitEdgeNums.Length() && SplitEdgeNums.Length()>0 ) {
2232       TopTools_SequenceOfShape aSeqRes;
2233       int nn, num1 = 1, num2 = 1;
2234       for(nn=1; nn<=SplitEdgeNums.Length(); nn++) {
2235         // create wirepath and sequences of shapes
2236         BRep_Builder B;
2237         TopoDS_Wire tmpW;
2238         B.MakeWire(tmpW);
2239         for(i=num1; i<=SplitEdgeNums.Value(nn); i++) {
2240           B.Add(tmpW,TopoDS::Edge(Edges.Value(i)));
2241         }
2242         num1 = SplitEdgeNums.Value(nn) + 1;
2243         TopTools_SequenceOfShape aTmpSeqBases;
2244         TopTools_SequenceOfShape aTmpSeqLocs;
2245         for(i=num2; i<=SplitLocNums.Value(nn); i++) {
2246           aTmpSeqBases.Append(aSeqBases.Value(i));
2247           aTmpSeqLocs.Append(aSeqLocs.Value(i));
2248         }
2249         num2 = SplitLocNums.Value(nn);
2250         // make pipe
2251         BRepOffsetAPI_MakePipeShell aBuilder(tmpW);
2252         Standard_Integer nbShapes = aTmpSeqBases.Length();
2253         for(i=1; i<=nbShapes; i++) {
2254           TopoDS_Shape aShapeLoc = aTmpSeqLocs.Value(i);
2255           TopoDS_Vertex aVert = TopoDS::Vertex(aShapeLoc);
2256           aBuilder.Add(aTmpSeqBases.Value(i), aVert, aWithContact, aWithCorrect);
2257         }
2258         if(!aBuilder.IsReady()) {
2259           if(aCI) delete aCI;
2260           Standard_ConstructionError::Raise("Invalid input data for building PIPE: bases are invalid");
2261         }
2262         aBuilder.Build();
2263         TopoDS_Shape resShape = aBuilder.Shape();
2264         aSeqRes.Append(resShape);
2265       }
2266       // create wirepath and sequences of shapes for last part
2267       BRep_Builder B;
2268       TopoDS_Wire tmpW;
2269       B.MakeWire(tmpW);
2270       for(i=num1; i<=Edges.Length(); i++) {
2271         B.Add(tmpW,TopoDS::Edge(Edges.Value(i)));
2272       }
2273       TopTools_SequenceOfShape aTmpSeqBases;
2274       TopTools_SequenceOfShape aTmpSeqLocs;
2275       for(i=num2; i<=aSeqLocs.Length(); i++) {
2276         aTmpSeqBases.Append(aSeqBases.Value(i));
2277         aTmpSeqLocs.Append(aSeqLocs.Value(i));
2278       }
2279       // make pipe for last part
2280       BRepOffsetAPI_MakePipeShell aBuilder(tmpW);
2281       Standard_Integer nbShapes = aTmpSeqBases.Length();
2282       for(i=1; i<=nbShapes; i++) {
2283         TopoDS_Shape aShapeLoc = aTmpSeqLocs.Value(i);
2284         TopoDS_Vertex aVert = TopoDS::Vertex(aShapeLoc);
2285         aBuilder.Add(aTmpSeqBases.Value(i), aVert, aWithContact, aWithCorrect);
2286       }
2287       if(!aBuilder.IsReady()) {
2288         if(aCI) delete aCI;
2289         Standard_ConstructionError::Raise("Invalid input data for building PIPE: bases are invalid");
2290       }
2291       aBuilder.Build();
2292       TopoDS_Shape resShape = aBuilder.Shape();
2293       aSeqRes.Append(resShape);
2294       // make sewing for result
2295       Handle(BRepBuilderAPI_Sewing) aSewing = new BRepBuilderAPI_Sewing;
2296       aSewing->SetTolerance(Precision::Confusion());
2297       aSewing->SetFaceMode(Standard_True);
2298       aSewing->SetFloatingEdgesMode(Standard_False);
2299       aSewing->SetNonManifoldMode(Standard_False);
2300       for(i=1; i<=aSeqRes.Length(); i++) {
2301         aSewing->Add(aSeqRes.Value(i));
2302       }
2303       aSewing->Perform();
2304       aShape = aSewing->SewedShape();
2305     }
2306     else {
2307       // old implementation without splitting
2308       BRepOffsetAPI_MakePipeShell aBuilder(aWirePath);
2309
2310       Standard_Integer nbShapes = aSeqBases.Length();
2311       Standard_Integer step = nbShapes/nbBases;
2312
2313       if(nbShapes < nbBases || fmod((double)nbShapes, (double)nbBases)) {
2314         if(aCI) delete aCI;
2315         Standard_ConstructionError::Raise("Invalid sections were specified for building pipe");
2316       }
2317       Standard_Integer ind =0;
2318       for( i=1; i  <= nbShapes && ind < nbShapes; i++) { //i+nbBases <= nbShapes
2319         TopTools_SequenceOfShape usedBases;
2320         Standard_Integer j = 1;
2321         for( ; j <= nbBases ; j++) {
2322           ind = i + (j-1)*step;
2323           TopoDS_Shape aWireProf = aSeqBases.Value(ind);
2324           usedBases.Append(aWireProf);
2325           if(nbLocs) {
2326             TopoDS_Shape aShapeLoc = aSeqLocs.Value(j);
2327             TopoDS_Vertex aVert = TopoDS::Vertex(aShapeLoc);
2328             aBuilder.Add(aWireProf,aVert,aWithContact,aWithCorrect);
2329           }
2330           else
2331             aBuilder.Add(aWireProf,aWithContact,aWithCorrect);
2332         }
2333       if(!aBuilder.IsReady()) {
2334         if(aCI) delete aCI;
2335         Standard_ConstructionError::Raise("Invalid input data for building PIPE: bases are invalid");
2336       }
2337       aBuilder.Build();
2338       aShape = aBuilder.Shape();
2339       aSeqFaces.Append(aShape);
2340       for( j = 1; j <=usedBases.Length(); j++)
2341         aBuilder.Delete(usedBases.Value(j));
2342       }
2343
2344       //for case if section is face
2345       if(aSeqFaces.Length() >1) {
2346         BRep_Builder aB;
2347         TopoDS_Compound aComp;
2348         aB.MakeCompound(aComp);
2349         for( i = 1; i <= aSeqFaces.Length(); i++)
2350           aB.Add(aComp,aSeqFaces.Value(i));
2351         aShape = aComp;
2352       }
2353     }
2354   }
2355
2356   //building pipe with shell sections
2357   else if (aType == PIPE_SHELL_SECTIONS) {
2358     aShape = CreatePipeForShellSections(aWirePath,aCI);
2359   }
2360
2361   //building pipe shell sections without path
2362   else if (aType == PIPE_SHELLS_WITHOUT_PATH) {
2363     aShape = CreatePipeShellsWithoutPath(aCI);
2364   }
2365
2366   //building a pipe with constant bi-normal along given vector
2367   else if (aType == PIPE_BI_NORMAL_ALONG_VECTOR) {
2368     aShape = CreatePipeBiNormalAlongVector(aWirePath, aCI);
2369   }
2370
2371   if (aCI) {
2372     delete aCI;
2373     aCI = 0;
2374   }
2375
2376   if (aShape.IsNull()) return 0;
2377
2378   BRepCheck_Analyzer ana (aShape, Standard_False);
2379   if (!ana.IsValid()) {
2380     ShapeFix_ShapeTolerance aSFT;
2381     aSFT.LimitTolerance(aShape,Precision::Confusion(),Precision::Confusion());
2382     Handle(ShapeFix_Shape) aSfs = new ShapeFix_Shape(aShape);
2383     aSfs->SetPrecision(Precision::Confusion());
2384     aSfs->Perform();
2385     aShape = aSfs->Shape();
2386
2387     ana.Init(aShape, Standard_False);
2388     if (!ana.IsValid())
2389       Standard_ConstructionError::Raise("Algorithm have produced an invalid shape result");
2390   }
2391
2392   TopoDS_Shape aRes = GEOMImpl_IShapesOperations::CompsolidToCompound(aShape);
2393   aFunction->SetValue(aRes);
2394
2395   log.SetTouched(Label());
2396   return 1;
2397 }
2398
2399
2400 //=======================================================================
2401 //function :  GEOMImpl_PipeDriver_Type_
2402 //purpose  :
2403 //=======================================================================
2404 Standard_EXPORT Handle_Standard_Type& GEOMImpl_PipeDriver_Type_()
2405 {
2406
2407   static Handle_Standard_Type aType1 = STANDARD_TYPE(TFunction_Driver);
2408   if ( aType1.IsNull()) aType1 = STANDARD_TYPE(TFunction_Driver);
2409   static Handle_Standard_Type aType2 = STANDARD_TYPE(MMgt_TShared);
2410   if ( aType2.IsNull()) aType2 = STANDARD_TYPE(MMgt_TShared);
2411   static Handle_Standard_Type aType3 = STANDARD_TYPE(Standard_Transient);
2412   if ( aType3.IsNull()) aType3 = STANDARD_TYPE(Standard_Transient);
2413
2414
2415   static Handle_Standard_Transient _Ancestors[]= {aType1,aType2,aType3,NULL};
2416   static Handle_Standard_Type _aType = new Standard_Type("GEOMImpl_PipeDriver",
2417                                                          sizeof(GEOMImpl_PipeDriver),
2418                                                          1,
2419                                                          (Standard_Address)_Ancestors,
2420                                                          (Standard_Address)NULL);
2421
2422   return _aType;
2423 }
2424
2425 //=======================================================================
2426 //function : DownCast
2427 //purpose  :
2428 //=======================================================================
2429 const Handle(GEOMImpl_PipeDriver) Handle(GEOMImpl_PipeDriver)::DownCast(const Handle(Standard_Transient)& AnObject)
2430 {
2431   Handle(GEOMImpl_PipeDriver) _anOtherObject;
2432
2433   if (!AnObject.IsNull()) {
2434      if (AnObject->IsKind(STANDARD_TYPE(GEOMImpl_PipeDriver))) {
2435        _anOtherObject = Handle(GEOMImpl_PipeDriver)((Handle(GEOMImpl_PipeDriver)&)AnObject);
2436      }
2437   }
2438
2439   return _anOtherObject ;
2440 }
2441