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