Salome HOME
Mantis issue 0021414: There is a difference between vectors and other edges in Geometry.
[modules/geom.git] / src / GEOMImpl / GEOMImpl_ShapeDriver.cxx
1 // Copyright (C) 2007-2011  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 <GEOMImpl_ShapeDriver.hxx>
23
24 #include <GEOMImpl_IShapes.hxx>
25 #include <GEOMImpl_IVector.hxx>
26 #include <GEOMImpl_Types.hxx>
27 #include <GEOMImpl_Block6Explorer.hxx>
28
29 #include <GEOM_Function.hxx>
30
31 // OCCT Includes
32 #include <ShapeFix_Wire.hxx>
33 #include <ShapeFix_Edge.hxx>
34 #include <ShapeFix_Shape.hxx>
35
36 #include <BRep_Builder.hxx>
37 #include <BRep_Tool.hxx>
38 #include <BRepAdaptor_Curve.hxx>
39 #include <BRepAlgo_FaceRestrictor.hxx>
40 #include <BRepBuilderAPI_Copy.hxx>
41 #include <BRepBuilderAPI_Sewing.hxx>
42 #include <BRepBuilderAPI_MakeWire.hxx>
43 #include <BRepBuilderAPI_MakeEdge.hxx>
44 #include <BRepCheck.hxx>
45 #include <BRepCheck_Analyzer.hxx>
46 #include <BRepCheck_Shell.hxx>
47 #include <BRepClass3d_SolidClassifier.hxx>
48 #include <BRepLib.hxx>
49 #include <BRepLib_MakeEdge.hxx>
50 #include <BRepTools_WireExplorer.hxx>
51
52 #include <ShapeAnalysis_FreeBounds.hxx>
53
54 #include <TopAbs.hxx>
55 #include <TopExp.hxx>
56 #include <TopExp_Explorer.hxx>
57 #include <TopoDS.hxx>
58 #include <TopoDS_Shape.hxx>
59 #include <TopoDS_Edge.hxx>
60 #include <TopoDS_Wire.hxx>
61 #include <TopoDS_Shell.hxx>
62 #include <TopoDS_Solid.hxx>
63 #include <TopoDS_Compound.hxx>
64 #include <TopoDS_Iterator.hxx>
65
66 #include <TopTools_MapOfShape.hxx>
67 #include <TopTools_HSequenceOfShape.hxx>
68
69 #include <ElCLib.hxx>
70
71 #include <GCPnts_AbscissaPoint.hxx>
72
73 #include <Geom_TrimmedCurve.hxx>
74 #include <GeomAbs_CurveType.hxx>
75 #include <GeomConvert_CompCurveToBSplineCurve.hxx>
76 #include <GeomConvert.hxx>
77 #include <GeomLProp.hxx>
78
79 #include <TColStd_SequenceOfReal.hxx>
80 #include <TColStd_HSequenceOfTransient.hxx>
81 #include <TColStd_Array1OfReal.hxx>
82 #include <TColGeom_SequenceOfCurve.hxx>
83 #include <TColGeom_Array1OfBSplineCurve.hxx>
84 #include <TColGeom_HArray1OfBSplineCurve.hxx>
85
86 #include <Precision.hxx>
87
88 #include <Standard_NullObject.hxx>
89 #include <Standard_TypeMismatch.hxx>
90 #include <Standard_ConstructionError.hxx>
91
92 //=======================================================================
93 //function : GetID
94 //purpose  :
95 //=======================================================================
96 const Standard_GUID& GEOMImpl_ShapeDriver::GetID()
97 {
98   static Standard_GUID aShapeDriver("FF1BBB54-5D14-4df2-980B-3A668264EA16");
99   return aShapeDriver;
100 }
101
102
103 //=======================================================================
104 //function : GEOMImpl_ShapeDriver
105 //purpose  :
106 //=======================================================================
107 GEOMImpl_ShapeDriver::GEOMImpl_ShapeDriver()
108 {
109 }
110
111 //=======================================================================
112 //function : Execute
113 //purpose  :
114 //=======================================================================
115 Standard_Integer GEOMImpl_ShapeDriver::Execute(TFunction_Logbook& log) const
116 {
117   if (Label().IsNull()) return 0;
118   Handle(GEOM_Function) aFunction = GEOM_Function::GetFunction(Label());
119
120   GEOMImpl_IShapes aCI (aFunction);
121   Standard_Integer aType = aFunction->GetType();
122
123   TopoDS_Shape aShape;
124   BRep_Builder B;
125
126   if (aType == WIRE_EDGES) {
127     Handle(TColStd_HSequenceOfTransient) aShapes = aCI.GetShapes();
128     TopoDS_Wire aWire;
129     B.MakeWire(aWire);
130
131     // add edges
132     for (unsigned int ind = 1; ind <= aShapes->Length(); ind++) {
133       Handle(GEOM_Function) aRefShape = Handle(GEOM_Function)::DownCast(aShapes->Value(ind));
134       TopoDS_Shape aShape_i = aRefShape->GetValue();
135       if (aShape_i.IsNull()) {
136         Standard_NullObject::Raise("Shape for wire construction is null");
137       }
138      if (aShape_i.ShapeType() == TopAbs_EDGE || aShape_i.ShapeType() == TopAbs_WIRE) {
139        TopExp_Explorer exp (aShape_i, TopAbs_EDGE);
140        for (; exp.More(); exp.Next())
141          B.Add(aWire, TopoDS::Edge(exp.Current()));
142      } else {
143        Standard_TypeMismatch::Raise
144          ("Shape for wire construction is neither an edge nor a wire");
145      }
146     }
147
148     // fix edges order
149     Handle(ShapeFix_Wire) aFW = new ShapeFix_Wire;
150     aFW->Load(aWire);
151     aFW->FixReorder();
152
153     if (aFW->StatusReorder(ShapeExtend_FAIL1)) {
154       Standard_ConstructionError::Raise("Wire construction failed: several loops detected");
155     } else if (aFW->StatusReorder(ShapeExtend_FAIL)) {
156       Standard_ConstructionError::Raise("Wire construction failed");
157     } else {
158     }
159
160     // IMP 0019766: Building a Wire from unconnected edges by introducing a tolerance
161     Standard_Real aTolerance = aCI.GetTolerance();
162     if (aTolerance < Precision::Confusion())
163       aTolerance = Precision::Confusion();
164
165     aFW->ClosedWireMode() = Standard_False;
166     aFW->FixConnected(aTolerance);
167     if (aFW->StatusConnected(ShapeExtend_FAIL)) {
168       Standard_ConstructionError::Raise("Wire construction failed: cannot build connected wire");
169     }
170     // IMP 0019766
171     if (aFW->StatusConnected(ShapeExtend_DONE3)) {
172       // Confused with <prec> but not Analyzer.Precision(), set the same
173       aFW->FixGapsByRangesMode() = Standard_True;
174       if (aFW->FixGaps3d()) {
175         Handle(ShapeExtend_WireData) sbwd = aFW->WireData();
176         Handle(ShapeFix_Edge) aFe = new ShapeFix_Edge;
177         for (Standard_Integer iedge = 1; iedge <= sbwd->NbEdges(); iedge++) {
178           TopoDS_Edge aEdge = TopoDS::Edge(sbwd->Edge(iedge));
179           aFe->FixVertexTolerance(aEdge);
180           aFe->FixSameParameter(aEdge);
181         }
182       }
183       else if (aFW->StatusGaps3d(ShapeExtend_FAIL)) {
184         Standard_ConstructionError::Raise("Wire construction failed: cannot fix 3d gaps");
185       }
186     }
187       aShape = aFW->WireAPIMake();
188   }
189   else if (aType == FACE_WIRE) {
190     Handle(GEOM_Function) aRefBase = aCI.GetBase();
191     TopoDS_Shape aShapeBase = aRefBase->GetValue();
192     if (aShapeBase.IsNull()) Standard_NullObject::Raise("Argument Shape is null");
193     TopoDS_Wire W;
194     if (aShapeBase.ShapeType() == TopAbs_WIRE) {
195       W = TopoDS::Wire(aShapeBase);
196       // check the wire is closed
197       TopoDS_Vertex aV1, aV2;
198       TopExp::Vertices(W, aV1, aV2);
199       if ( !aV1.IsNull() && !aV2.IsNull() && aV1.IsSame(aV2) )
200         aShapeBase.Closed(true);
201       else
202         Standard_NullObject::Raise
203           ("Shape for face construction is not closed");
204     }
205     else if (aShapeBase.ShapeType() == TopAbs_EDGE && aShapeBase.Closed()) {
206       BRepBuilderAPI_MakeWire MW;
207       MW.Add(TopoDS::Edge(aShapeBase));
208       if (!MW.IsDone()) {
209         Standard_ConstructionError::Raise("Wire construction failed");
210       }
211       W = MW;
212     }
213     else {
214       Standard_NullObject::Raise
215         ("Shape for face construction is neither a wire nor a closed edge");
216     }
217     GEOMImpl_Block6Explorer::MakeFace(W, aCI.GetIsPlanar(), aShape);
218     if (aShape.IsNull()) {
219       Standard_ConstructionError::Raise("Face construction failed");
220     }
221   }
222   else if (aType == FACE_WIRES) {
223     // Try to build a face from a set of wires and edges
224     int ind;
225
226     Handle(TColStd_HSequenceOfTransient) aShapes = aCI.GetShapes();
227     int nbshapes = aShapes->Length();
228     if (nbshapes < 1) {
229       Standard_ConstructionError::Raise("No wires or edges given");
230     }
231
232     // 1. Extract all edges from the given arguments
233     TopTools_MapOfShape aMapEdges;
234     Handle(TopTools_HSequenceOfShape) aSeqEdgesIn = new TopTools_HSequenceOfShape;
235
236     for (ind = 1; ind <= nbshapes; ind++) {
237       Handle(GEOM_Function) aRefSh_i = Handle(GEOM_Function)::DownCast(aShapes->Value(ind));
238       TopoDS_Shape aSh_i = aRefSh_i->GetValue();
239
240       TopExp_Explorer anExpE_i (aSh_i, TopAbs_EDGE);
241       for (; anExpE_i.More(); anExpE_i.Next()) {
242         if (aMapEdges.Add(anExpE_i.Current())) {
243           aSeqEdgesIn->Append(anExpE_i.Current());
244         }
245       }
246     }
247
248     // 2. Connect edges to wires of maximum length
249     Handle(TopTools_HSequenceOfShape) aSeqWiresOut;
250     ShapeAnalysis_FreeBounds::ConnectEdgesToWires(aSeqEdgesIn, Precision::Confusion(),
251                                                   /*shared*/Standard_False, aSeqWiresOut);
252
253     // 3. Separate closed wires
254     Handle(TopTools_HSequenceOfShape) aSeqClosedWires = new TopTools_HSequenceOfShape;
255     Handle(TopTools_HSequenceOfShape) aSeqOpenWires = new TopTools_HSequenceOfShape;
256     for (ind = 1; ind <= aSeqWiresOut->Length(); ind++) {
257       if (aSeqWiresOut->Value(ind).Closed())
258         aSeqClosedWires->Append(aSeqWiresOut->Value(ind));
259       else
260         aSeqOpenWires->Append(aSeqWiresOut->Value(ind));
261     }
262
263     if (aSeqClosedWires->Length() < 1) {
264       Standard_ConstructionError::Raise
265         ("There is no closed contour can be built from the given arguments");
266     }
267
268     // 4. Build a face / list of faces from all the obtained closed wires
269
270     // 4.a. Basic face
271     TopoDS_Shape aFFace;
272     TopoDS_Wire aW1 = TopoDS::Wire(aSeqClosedWires->Value(1));
273     GEOMImpl_Block6Explorer::MakeFace(aW1, aCI.GetIsPlanar(), aFFace);
274     if (aFFace.IsNull()) {
275       Standard_ConstructionError::Raise("Face construction failed");
276     }
277
278     // 4.b. Add other wires
279     if (aSeqClosedWires->Length() == 1) {
280       aShape = aFFace;
281     }
282     else {
283       TopoDS_Compound C;
284       BRep_Builder aBuilder;
285       aBuilder.MakeCompound(C);
286       BRepAlgo_FaceRestrictor FR;
287
288       TopAbs_Orientation OriF = aFFace.Orientation();
289       TopoDS_Shape aLocalS = aFFace.Oriented(TopAbs_FORWARD);
290       FR.Init(TopoDS::Face(aLocalS), Standard_False, Standard_True);
291
292       for (ind = 1; ind <= aSeqClosedWires->Length(); ind++) {
293         TopoDS_Wire aW = TopoDS::Wire(aSeqClosedWires->Value(ind));
294         FR.Add(aW);
295       }
296
297       FR.Perform();
298
299       if (FR.IsDone()) {
300         int k = 0;
301         TopoDS_Shape aFace;
302         for (; FR.More(); FR.Next()) {
303           aFace = FR.Current().Oriented(OriF);
304           aBuilder.Add(C, aFace);
305           k++;
306         }
307         if (k == 1) {
308           aShape = aFace;
309         } else {
310           aShape = C;
311         }
312       }
313     }
314
315     // 5. Add all open wires to the result
316     if (aSeqOpenWires->Length() > 0) {
317       //Standard_ConstructionError::Raise("There are some open wires");
318       TopoDS_Compound C;
319       BRep_Builder aBuilder;
320       if (aSeqClosedWires->Length() == 1) {
321         aBuilder.MakeCompound(C);
322         aBuilder.Add(C, aShape);
323       }
324       else {
325         C = TopoDS::Compound(aShape);
326       }
327
328       for (ind = 1; ind <= aSeqOpenWires->Length(); ind++) {
329         aBuilder.Add(C, aSeqOpenWires->Value(ind));
330       }
331
332       aShape = C;
333     }
334   }
335   else if (aType == SHELL_FACES) {
336     Handle(TColStd_HSequenceOfTransient) aShapes = aCI.GetShapes();
337     unsigned int ind, nbshapes = aShapes->Length();
338
339     // add faces
340     BRepBuilderAPI_Sewing aSewing(Precision::Confusion()*10.0);
341     for (ind = 1; ind <= nbshapes; ind++) {
342       Handle(GEOM_Function) aRefShape = Handle(GEOM_Function)::DownCast(aShapes->Value(ind));
343       TopoDS_Shape aShape_i = aRefShape->GetValue();
344       if (aShape_i.IsNull()) {
345         Standard_NullObject::Raise("Face for shell construction is null");
346       }
347       aSewing.Add(aShape_i);
348     }
349
350     aSewing.Perform();
351
352     TopoDS_Shape sh = aSewing.SewedShape();
353     if( sh.ShapeType()==TopAbs_FACE && nbshapes==1 ) {
354       // case for creation of shell from one face - PAL12722 (skl 26.06.2006)
355       TopoDS_Shell ss;
356       B.MakeShell(ss);
357       B.Add(ss,sh);
358       aShape = ss;
359     }
360     else {
361       //TopExp_Explorer exp (aSewing.SewedShape(), TopAbs_SHELL);
362       TopExp_Explorer exp (sh, TopAbs_SHELL);
363       Standard_Integer ish = 0;
364       for (; exp.More(); exp.Next()) {
365         aShape = exp.Current();
366         ish++;
367       }
368
369       if (ish != 1)
370         aShape = aSewing.SewedShape();
371     }
372
373   }
374   else if (aType == SOLID_SHELL) {
375     Handle(GEOM_Function) aRefShell = aCI.GetBase();
376     TopoDS_Shape aShapeShell = aRefShell->GetValue();
377     if (!aShapeShell.IsNull() && aShapeShell.ShapeType() == TopAbs_COMPOUND) {
378       TopoDS_Iterator It (aShapeShell, Standard_True, Standard_True);
379       if (It.More()) aShapeShell = It.Value();
380     }
381     if (aShapeShell.IsNull() || aShapeShell.ShapeType() != TopAbs_SHELL) {
382       Standard_NullObject::Raise("Shape for solid construction is null or not a shell");
383     }
384
385     BRepCheck_Shell chkShell(TopoDS::Shell(aShapeShell));
386     if (chkShell.Closed() == BRepCheck_NotClosed) return 0;
387
388     TopoDS_Solid Sol;
389     B.MakeSolid(Sol);
390     B.Add(Sol, aShapeShell);
391     BRepClass3d_SolidClassifier SC (Sol);
392     SC.PerformInfinitePoint(Precision::Confusion());
393     if (SC.State() == TopAbs_IN) {
394       B.MakeSolid(Sol);
395       B.Add(Sol, aShapeShell.Reversed());
396     }
397
398     aShape = Sol;
399
400   }
401   else if (aType == SOLID_SHELLS) {
402     Handle(TColStd_HSequenceOfTransient) aShapes = aCI.GetShapes();
403     unsigned int ind, nbshapes = aShapes->Length();
404     Standard_Integer ish = 0;
405     TopoDS_Solid Sol;
406     B.MakeSolid(Sol);
407
408     // add shapes
409     for (ind = 1; ind <= nbshapes; ind++) {
410       Handle(GEOM_Function) aRefShape = Handle(GEOM_Function)::DownCast(aShapes->Value(ind));
411       TopoDS_Shape aShapeShell = aRefShape->GetValue();
412       if (aShapeShell.IsNull()) {
413         Standard_NullObject::Raise("Shell for solid construction is null");
414       }
415       if (aShapeShell.ShapeType() == TopAbs_COMPOUND) {
416         TopoDS_Iterator It (aShapeShell, Standard_True, Standard_True);
417         if (It.More()) aShapeShell = It.Value();
418       }
419       if (aShapeShell.ShapeType() == TopAbs_SHELL) {
420         B.Add(Sol, aShapeShell);
421         ish++;
422       }
423     }
424     if (ish == 0) return 0;
425     BRepClass3d_SolidClassifier SC (Sol);
426     SC.PerformInfinitePoint(Precision::Confusion());
427     if (SC.State() == TopAbs_IN)
428       aShape = Sol.Reversed();
429     else
430       aShape = Sol;
431   }
432   else if (aType == COMPOUND_SHAPES) {
433     Handle(TColStd_HSequenceOfTransient) aShapes = aCI.GetShapes();
434     unsigned int ind, nbshapes = aShapes->Length();
435
436     // add shapes
437     TopoDS_Compound C;
438     B.MakeCompound(C);
439     for (ind = 1; ind <= nbshapes; ind++) {
440       Handle(GEOM_Function) aRefShape = Handle(GEOM_Function)::DownCast(aShapes->Value(ind));
441       TopoDS_Shape aShape_i = aRefShape->GetValue();
442       if (aShape_i.IsNull()) {
443         Standard_NullObject::Raise("Shape for compound construction is null");
444       }
445       B.Add(C, aShape_i);
446     }
447
448     aShape = C;
449
450   }
451   /*
452   else if (aType == REVERSE_ORIENTATION) {
453     Handle(GEOM_Function) aRefShape = aCI.GetBase();
454     TopoDS_Shape aShape_i = aRefShape->GetValue();
455     if (aShape_i.IsNull()) {
456        Standard_NullObject::Raise("Shape for reverse is null");
457     }
458
459     BRepBuilderAPI_Copy Copy(aShape_i);
460     if( Copy.IsDone() ) {
461       TopoDS_Shape tds = Copy.Shape();
462       if( tds.IsNull() ) {
463         Standard_ConstructionError::Raise("Orientation aborted : Can not reverse the shape");
464       }
465
466       if( tds.Orientation() == TopAbs_FORWARD)
467         tds.Orientation(TopAbs_REVERSED);
468       else
469         tds.Orientation(TopAbs_FORWARD);
470
471       aShape = tds;
472     }
473   }
474   */
475   else if (aType == EDGE_WIRE) {
476     Handle(GEOM_Function) aRefBase = aCI.GetBase();
477     TopoDS_Shape aWire = aRefBase->GetValue();
478     Standard_Real LinTol = aCI.GetTolerance();
479     Standard_Real AngTol = aCI.GetAngularTolerance();
480     if (aWire.IsNull()) Standard_NullObject::Raise("Argument Wire is null");
481
482     TopoDS_Edge ResEdge;
483
484     BRepLib::BuildCurves3d(aWire);
485     Handle(ShapeFix_Shape) Fixer = new ShapeFix_Shape(aWire);
486     Fixer->SetPrecision(LinTol);
487     Fixer->SetMaxTolerance(LinTol);
488     Fixer->Perform();
489     TopoDS_Wire theWire = TopoDS::Wire(Fixer->Shape());
490
491     TColGeom_SequenceOfCurve CurveSeq;
492     TopTools_SequenceOfShape LocSeq;
493     TColStd_SequenceOfReal FparSeq;
494     TColStd_SequenceOfReal LparSeq;
495     TColStd_SequenceOfReal TolSeq;
496     GeomAbs_CurveType CurType;
497     TopoDS_Vertex FirstVertex, LastVertex;
498
499     BRepTools_WireExplorer wexp(theWire) ;
500     for (; wexp.More(); wexp.Next())
501     {
502       TopoDS_Edge anEdge = wexp.Current();
503       Standard_Real fpar, lpar;
504       TopLoc_Location aLoc;
505       Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aLoc, fpar, lpar);
506       if (aCurve.IsNull())
507         continue;
508
509       BRepAdaptor_Curve BAcurve(anEdge);
510       GeomAbs_CurveType aType = BAcurve.GetType();
511
512       Handle(Geom_Curve) aBasisCurve = BAcurve.Curve().Curve();
513
514       if (aBasisCurve->IsPeriodic())
515         ElCLib::AdjustPeriodic(aBasisCurve->FirstParameter(), aBasisCurve->LastParameter(),
516                                Precision::PConfusion(), fpar, lpar);
517
518       if (CurveSeq.IsEmpty())
519       {
520         CurveSeq.Append(aCurve);
521         TopoDS_Shape aLocShape;
522         aLocShape.Location(aLoc);
523         aLocShape.Orientation(wexp.Orientation());
524         LocSeq.Append(aLocShape);
525         FparSeq.Append(fpar);
526         LparSeq.Append(lpar);
527         CurType = aType;
528         FirstVertex = wexp.CurrentVertex();
529       }
530       else
531       {
532         Standard_Boolean Done = Standard_False;
533         Standard_Real NewFpar, NewLpar;
534         GeomAdaptor_Curve GAprevcurve(CurveSeq.Last());
535         TopoDS_Vertex CurVertex = wexp.CurrentVertex();
536         TopoDS_Vertex CurFirstVer = TopExp::FirstVertex(anEdge);
537         TopAbs_Orientation ConnectByOrigin = (CurVertex.IsSame(CurFirstVer))? TopAbs_FORWARD : TopAbs_REVERSED;
538         if (aCurve == CurveSeq.Last())
539         {
540           NewFpar = fpar;
541           NewLpar = lpar;
542           if (aBasisCurve->IsPeriodic())
543           {
544             if (NewLpar < NewFpar)
545               NewLpar += aBasisCurve->Period();
546             if (ConnectByOrigin == TopAbs_FORWARD)
547               ElCLib::AdjustPeriodic(FparSeq.Last(),
548                                      FparSeq.Last() + aBasisCurve->Period(),
549                                      Precision::PConfusion(), NewFpar, NewLpar);
550             else
551               ElCLib::AdjustPeriodic(FparSeq.Last() - aBasisCurve->Period(),
552                                      FparSeq.Last(),
553                                      Precision::PConfusion(), NewFpar, NewLpar);
554           }
555           Done = Standard_True;
556         }
557         else if (aType == CurType &&
558                  aType != GeomAbs_BezierCurve &&
559                  aType != GeomAbs_BSplineCurve &&
560                  aType != GeomAbs_OtherCurve)
561         {
562           switch (aType)
563           {
564           case GeomAbs_Line:
565             {
566               gp_Lin aLine    = BAcurve.Line();
567               gp_Lin PrevLine = GAprevcurve.Line();
568               if (aLine.Contains(PrevLine.Location(), LinTol) &&
569                   aLine.Direction().IsParallel(PrevLine.Direction(), AngTol))
570               {
571                 gp_Pnt P1 = ElCLib::Value(fpar, aLine);
572                 gp_Pnt P2 = ElCLib::Value(lpar, aLine);
573                 NewFpar = ElCLib::Parameter(PrevLine, P1);
574                 NewLpar = ElCLib::Parameter(PrevLine, P2);
575                 if (NewLpar < NewFpar)
576                 {
577                   Standard_Real MemNewFpar = NewFpar;
578                   NewFpar = NewLpar;
579                   NewLpar = MemNewFpar;
580                   ConnectByOrigin = TopAbs::Reverse(ConnectByOrigin);
581                 }
582                 Done = Standard_True;
583               }
584               break;
585             }
586           case GeomAbs_Circle:
587             {
588               gp_Circ aCircle    = BAcurve.Circle();
589               gp_Circ PrevCircle = GAprevcurve.Circle();
590               if (aCircle.Location().Distance(PrevCircle.Location()) <= LinTol &&
591                   Abs(aCircle.Radius() - PrevCircle.Radius()) <= LinTol &&
592                   aCircle.Axis().IsParallel(PrevCircle.Axis(), AngTol))
593               {
594                 if (aCircle.Axis().Direction() * PrevCircle.Axis().Direction() < 0.)
595                 {
596                   Standard_Real memfpar = fpar;
597                   fpar = lpar;
598                   lpar = memfpar;
599                   ConnectByOrigin = TopAbs::Reverse(ConnectByOrigin);
600                 }
601                 gp_Pnt P1 = ElCLib::Value(fpar, aCircle);
602                 gp_Pnt P2 = ElCLib::Value(lpar, aCircle);
603                 NewFpar = ElCLib::Parameter(PrevCircle, P1);
604                 NewLpar = ElCLib::Parameter(PrevCircle, P2);
605                 if (NewLpar < NewFpar)
606                   NewLpar += 2.*PI;
607                 //Standard_Real MemNewFpar = NewFpar, MemNewLpar =  NewLpar;
608                 if (ConnectByOrigin == TopAbs_FORWARD)
609                   ElCLib::AdjustPeriodic(FparSeq.Last(),
610                                          FparSeq.Last() + 2.*PI,
611                                          Precision::PConfusion(), NewFpar, NewLpar);
612                 else
613                   ElCLib::AdjustPeriodic(FparSeq.Last() - 2.*PI,
614                                          FparSeq.Last(),
615                                          Precision::PConfusion(), NewFpar, NewLpar);
616                 Done = Standard_True;
617               }
618               break;
619             }
620           case GeomAbs_Ellipse:
621             {
622               gp_Elips anEllipse   = BAcurve.Ellipse();
623               gp_Elips PrevEllipse = GAprevcurve.Ellipse();
624               if (anEllipse.Focus1().Distance(PrevEllipse.Focus1()) <= LinTol &&
625                   anEllipse.Focus2().Distance(PrevEllipse.Focus2()) <= LinTol &&
626                   Abs(anEllipse.MajorRadius() - PrevEllipse.MajorRadius()) <= LinTol &&
627                   Abs(anEllipse.MinorRadius() - PrevEllipse.MinorRadius()) <= LinTol &&
628                   anEllipse.Axis().IsParallel(PrevEllipse.Axis(), AngTol))
629               {
630                 if (anEllipse.Axis().Direction() * PrevEllipse.Axis().Direction() < 0.)
631                 {
632                   Standard_Real memfpar = fpar;
633                   fpar = lpar;
634                   lpar = memfpar;
635                   ConnectByOrigin = TopAbs::Reverse(ConnectByOrigin);
636                 }
637                 gp_Pnt P1 = ElCLib::Value(fpar, anEllipse);
638                 gp_Pnt P2 = ElCLib::Value(lpar, anEllipse);
639                 NewFpar = ElCLib::Parameter(PrevEllipse, P1);
640                 NewLpar = ElCLib::Parameter(PrevEllipse, P2);
641                 if (NewLpar < NewFpar)
642                   NewLpar += 2.*PI;
643                 if (ConnectByOrigin == TopAbs_FORWARD)
644                   ElCLib::AdjustPeriodic(FparSeq.Last(),
645                                          FparSeq.Last() + 2.*PI,
646                                          Precision::PConfusion(), NewFpar, NewLpar);
647                 else
648                   ElCLib::AdjustPeriodic(FparSeq.Last() - 2.*PI,
649                                          FparSeq.Last(),
650                                          Precision::PConfusion(), NewFpar, NewLpar);
651                 Done = Standard_True;
652               }
653               break;
654             }
655           case GeomAbs_Hyperbola:
656             {
657               gp_Hypr aHypr    = BAcurve.Hyperbola();
658               gp_Hypr PrevHypr = GAprevcurve.Hyperbola();
659               if (aHypr.Focus1().Distance(PrevHypr.Focus1()) <= LinTol &&
660                   aHypr.Focus2().Distance(PrevHypr.Focus2()) <= LinTol &&
661                   Abs(aHypr.MajorRadius() - PrevHypr.MajorRadius()) <= LinTol &&
662                   Abs(aHypr.MinorRadius() - PrevHypr.MinorRadius()) <= LinTol &&
663                   aHypr.Axis().IsParallel(PrevHypr.Axis(), AngTol))
664               {
665                 gp_Pnt P1 = ElCLib::Value(fpar, aHypr);
666                 gp_Pnt P2 = ElCLib::Value(lpar, aHypr);
667                 NewFpar = ElCLib::Parameter(PrevHypr, P1);
668                 NewLpar = ElCLib::Parameter(PrevHypr, P2);
669                 if (NewLpar < NewFpar)
670                 {
671                   Standard_Real MemNewFpar = NewFpar;
672                   NewFpar = NewLpar;
673                   NewLpar = MemNewFpar;
674                   ConnectByOrigin = TopAbs::Reverse(ConnectByOrigin);
675                 }
676                 Done = Standard_True;
677               }
678               break;
679             }
680           case GeomAbs_Parabola:
681             {
682               gp_Parab aParab    = BAcurve.Parabola();
683               gp_Parab PrevParab = GAprevcurve.Parabola();
684               if (aParab.Location().Distance(PrevParab.Location()) <= LinTol &&
685                   aParab.Focus().Distance(PrevParab.Focus()) <= LinTol &&
686                   Abs(aParab.Focal() - PrevParab.Focal()) <= LinTol &&
687                   aParab.Axis().IsParallel(PrevParab.Axis(), AngTol))
688               {
689                 gp_Pnt P1 = ElCLib::Value(fpar, aParab);
690                 gp_Pnt P2 = ElCLib::Value(lpar, aParab);
691                 NewFpar = ElCLib::Parameter(PrevParab, P1);
692                 NewLpar = ElCLib::Parameter(PrevParab, P2);
693                 if (NewLpar < NewFpar)
694                 {
695                   Standard_Real MemNewFpar = NewFpar;
696                   NewFpar = NewLpar;
697                   NewLpar = MemNewFpar;
698                   ConnectByOrigin = TopAbs::Reverse(ConnectByOrigin);
699                 }
700                 Done = Standard_True;
701               }
702               break;
703             }
704           } //end of switch (aType)
705         } // end of else if (aType == CurType && ...
706         if (Done)
707         {
708           if (NewFpar < FparSeq.Last())
709             FparSeq(FparSeq.Length()) = NewFpar;
710           else
711             LparSeq(LparSeq.Length()) = NewLpar;
712         }
713         else
714         {
715           CurveSeq.Append(aCurve);
716           TopoDS_Shape aLocShape;
717           aLocShape.Location(aLoc);
718           aLocShape.Orientation(wexp.Orientation());
719           LocSeq.Append(aLocShape);
720           FparSeq.Append(fpar);
721           LparSeq.Append(lpar);
722           TolSeq.Append(BRep_Tool::Tolerance(CurVertex));
723           CurType = aType;
724         }
725       } // end of else (CurveSeq.IsEmpty()) -> not first time
726     } // end for (; wexp.More(); wexp.Next())
727
728     LastVertex = wexp.CurrentVertex();
729     TolSeq.Append(BRep_Tool::Tolerance(LastVertex));
730
731     if (!CurveSeq.IsEmpty())
732     {
733       Standard_Integer nb_curve = CurveSeq.Length();   //number of curves
734       TColGeom_Array1OfBSplineCurve tab(0,nb_curve-1);                    //array of the curves
735       TColStd_Array1OfReal tabtolvertex(0,nb_curve-1); //(0,nb_curve-2);  //array of the tolerances
736
737       Standard_Integer i;
738
739       if (nb_curve > 1)
740       {
741         for (i = 1; i <= nb_curve; i++)
742         {
743           if (CurveSeq(i)->IsInstance(STANDARD_TYPE(Geom_TrimmedCurve)))
744             CurveSeq(i) = (*((Handle(Geom_TrimmedCurve)*)&(CurveSeq(i))))->BasisCurve();
745
746           Handle(Geom_TrimmedCurve) aTrCurve = new Geom_TrimmedCurve(CurveSeq(i), FparSeq(i), LparSeq(i));
747           tab(i-1) = GeomConvert::CurveToBSplineCurve(aTrCurve);
748           tab(i-1)->Transform(LocSeq(i).Location().Transformation());
749           GeomConvert::C0BSplineToC1BSplineCurve(tab(i-1), Precision::Confusion());
750           if (LocSeq(i).Orientation() == TopAbs_REVERSED)
751             tab(i-1)->Reverse();
752
753           //Temporary
754           //char* name = new char[100];
755           //sprintf(name, "c%d", i);
756           //DrawTrSurf::Set(name, tab(i-1));
757
758           if (i > 1)
759             tabtolvertex(i-2) = TolSeq(i-1);
760         } // end for (i = 1; i <= nb_curve; i++)
761         tabtolvertex(nb_curve-1) = TolSeq(TolSeq.Length());
762
763         Standard_Boolean closed_flag = Standard_False;
764         Standard_Real closed_tolerance = 0.;
765         if (FirstVertex.IsSame(LastVertex) &&
766             GeomLProp::Continuity(tab(0), tab(nb_curve-1),
767                                   tab(0)->FirstParameter(),
768                                   tab(nb_curve-1)->LastParameter(),
769                                   Standard_False, Standard_False, LinTol, AngTol) >= GeomAbs_G1)
770         {
771           closed_flag = Standard_True ;
772           closed_tolerance = BRep_Tool::Tolerance(FirstVertex);
773         }
774
775         Handle(TColGeom_HArray1OfBSplineCurve)  concatcurve;     //array of the concatenated curves
776         Handle(TColStd_HArray1OfInteger)        ArrayOfIndices;  //array of the remining Vertex
777         GeomConvert::ConcatC1(tab,
778                               tabtolvertex,
779                               ArrayOfIndices,
780                               concatcurve,
781                               closed_flag,
782                               closed_tolerance);   //C1 concatenation
783
784         if (concatcurve->Length() > 1)
785         {
786           GeomConvert_CompCurveToBSplineCurve Concat(concatcurve->Value(concatcurve->Lower()));
787
788           for (i = concatcurve->Lower()+1; i <= concatcurve->Upper(); i++)
789             Concat.Add( concatcurve->Value(i), LinTol, Standard_True );
790
791           concatcurve->SetValue(concatcurve->Lower(), Concat.BSplineCurve());
792         }
793         // rnc : prevents the driver from building an edge without C1 continuity
794         if (concatcurve->Value(concatcurve->Lower())->Continuity()==GeomAbs_C0){
795           Standard_ConstructionError::Raise("Construction aborted : The given Wire has sharp bends between some Edges, no valid Edge can be built");
796         }
797         ResEdge = BRepLib_MakeEdge(concatcurve->Value(concatcurve->Lower()),
798                                    FirstVertex, LastVertex);
799       }
800       else
801       {
802         if (CurveSeq(1)->IsInstance(STANDARD_TYPE(Geom_TrimmedCurve)))
803           CurveSeq(1) = (*((Handle(Geom_TrimmedCurve)*)&(CurveSeq(i))))->BasisCurve();
804
805         CurveSeq(1)->Transform(LocSeq(1).Location().Transformation());
806         ResEdge = BRepLib_MakeEdge(CurveSeq(1),
807                                    FirstVertex, LastVertex,
808                                    FparSeq(1), LparSeq(1));
809       }
810     }
811
812     aShape = ResEdge;
813   }
814   else if (aType == EDGE_CURVE_LENGTH) {
815     GEOMImpl_IVector aVI (aFunction);
816
817     // RefCurve
818     Handle(GEOM_Function) aRefCurve = aVI.GetPoint1();
819     if (aRefCurve.IsNull()) Standard_NullObject::Raise("Argument Curve is null");
820     TopoDS_Shape aRefShape1 = aRefCurve->GetValue();
821     if (aRefShape1.ShapeType() != TopAbs_EDGE) {
822       Standard_TypeMismatch::Raise
823         ("Edge On Curve creation aborted : curve shape is not an edge");
824     }
825     TopoDS_Edge aRefEdge = TopoDS::Edge(aRefShape1);
826     TopoDS_Vertex V1, V2;
827     TopExp::Vertices(aRefEdge, V1, V2, Standard_True);
828
829     // RefPoint
830     TopoDS_Vertex aRefVertex;
831     Handle(GEOM_Function) aRefPoint = aVI.GetPoint2();
832     if (aRefPoint.IsNull()) {
833       aRefVertex = V1;
834     }
835     else {
836       TopoDS_Shape aRefShape2 = aRefPoint->GetValue();
837       if (aRefShape2.ShapeType() != TopAbs_VERTEX) {
838         Standard_TypeMismatch::Raise
839           ("Edge On Curve creation aborted : start point shape is not a vertex");
840       }
841       aRefVertex = TopoDS::Vertex(aRefShape2);
842     }
843     gp_Pnt aRefPnt = BRep_Tool::Pnt(aRefVertex);
844
845     // Length
846     Standard_Real aLength = aVI.GetParameter();
847     //Standard_Real aCurveLength = IntTools::Length(aRefEdge);
848     //if (aLength > aCurveLength) {
849     //  Standard_ConstructionError::Raise
850     //    ("Edge On Curve creation aborted : given length is greater than edges length");
851     //}
852     if (fabs(aLength) < Precision::Confusion()) {
853       Standard_ConstructionError::Raise
854         ("Edge On Curve creation aborted : given length is smaller than Precision::Confusion()");
855     }
856
857     // Check orientation
858     Standard_Real UFirst, ULast;
859     Handle(Geom_Curve) EdgeCurve = BRep_Tool::Curve(aRefEdge, UFirst, ULast);
860     Handle(Geom_Curve) ReOrientedCurve = EdgeCurve;
861
862     Standard_Real dU = ULast - UFirst;
863     Standard_Real par1 = UFirst + 0.1 * dU;
864     Standard_Real par2 = ULast  - 0.1 * dU;
865
866     gp_Pnt P1 = EdgeCurve->Value(par1);
867     gp_Pnt P2 = EdgeCurve->Value(par2);
868
869     if (aRefPnt.SquareDistance(P2) < aRefPnt.SquareDistance(P1)) {
870       ReOrientedCurve = EdgeCurve->Reversed();
871       UFirst = EdgeCurve->ReversedParameter(ULast);
872     }
873
874     // Get the point by length
875     GeomAdaptor_Curve AdapCurve = GeomAdaptor_Curve(ReOrientedCurve);
876     GCPnts_AbscissaPoint anAbsPnt (AdapCurve, aLength, UFirst); 
877     Standard_Real aParam = anAbsPnt.Parameter();
878
879     if (AdapCurve.IsClosed() && aLength < 0.0) {
880       Standard_Real aTmp = aParam;
881       aParam = UFirst;
882       UFirst = aTmp;
883     }
884
885     BRepBuilderAPI_MakeEdge aME (ReOrientedCurve, UFirst, aParam);
886     if (aME.IsDone())
887       aShape = aME.Shape();
888   }
889   else {
890   }
891
892   if (aShape.IsNull()) return 0;
893
894   // Check shape validity
895   BRepCheck_Analyzer ana (aShape, false);
896   if (!ana.IsValid()) {
897     //Standard_ConstructionError::Raise("Algorithm have produced an invalid shape result");
898   }
899
900   aFunction->SetValue(aShape);
901
902   log.SetTouched(Label());
903
904   return 1;
905 }
906
907
908 //=======================================================================
909 //function :  GEOMImpl_ShapeDriver_Type_
910 //purpose  :
911 //=======================================================================
912 Standard_EXPORT Handle_Standard_Type& GEOMImpl_ShapeDriver_Type_()
913 {
914
915   static Handle_Standard_Type aType1 = STANDARD_TYPE(TFunction_Driver);
916   if ( aType1.IsNull()) aType1 = STANDARD_TYPE(TFunction_Driver);
917   static Handle_Standard_Type aType2 = STANDARD_TYPE(MMgt_TShared);
918   if ( aType2.IsNull()) aType2 = STANDARD_TYPE(MMgt_TShared);
919   static Handle_Standard_Type aType3 = STANDARD_TYPE(Standard_Transient);
920   if ( aType3.IsNull()) aType3 = STANDARD_TYPE(Standard_Transient);
921
922
923   static Handle_Standard_Transient _Ancestors[]= {aType1,aType2,aType3,NULL};
924   static Handle_Standard_Type _aType = new Standard_Type("GEOMImpl_ShapeDriver",
925                                                          sizeof(GEOMImpl_ShapeDriver),
926                                                          1,
927                                                          (Standard_Address)_Ancestors,
928                                                          (Standard_Address)NULL);
929
930   return _aType;
931 }
932
933 //=======================================================================
934 //function : DownCast
935 //purpose  :
936 //=======================================================================
937 const Handle(GEOMImpl_ShapeDriver) Handle(GEOMImpl_ShapeDriver)::DownCast(const Handle(Standard_Transient)& AnObject)
938 {
939   Handle(GEOMImpl_ShapeDriver) _anOtherObject;
940
941   if (!AnObject.IsNull()) {
942      if (AnObject->IsKind(STANDARD_TYPE(GEOMImpl_ShapeDriver))) {
943        _anOtherObject = Handle(GEOMImpl_ShapeDriver)((Handle(GEOMImpl_ShapeDriver)&)AnObject);
944      }
945   }
946
947   return _anOtherObject;
948 }