Salome HOME
Merge remote-tracking branch 'origin/BR_SHP_FORMAT' into BR_v14_rc
[modules/hydro.git] / src / HYDROData / HYDROData_Stream.cxx
1 // Copyright (C) 2014-2015  EDF-R&D
2 // This library is free software; you can redistribute it and/or
3 // modify it under the terms of the GNU Lesser General Public
4 // License as published by the Free Software Foundation; either
5 // version 2.1 of the License, or (at your option) any later version.
6 //
7 // This library is distributed in the hope that it will be useful,
8 // but WITHOUT ANY WARRANTY; without even the implied warranty of
9 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
10 // Lesser General Public License for more details.
11 //
12 // You should have received a copy of the GNU Lesser General Public
13 // License along with this library; if not, write to the Free Software
14 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
15 //
16 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
17 //
18
19 #include "HYDROData_Stream.h"
20
21 #include "HYDROData_Document.h"
22 #include "HYDROData_PolylineXY.h"
23 #include "HYDROData_Polyline3D.h"
24 #include "HYDROData_Profile.h"
25 #include "HYDROData_ShapesGroup.h"
26 #include "HYDROData_ShapesTool.h"
27 #include "HYDROData_IAltitudeObject.h"
28 #include "HYDROData_IProfilesInterpolator.h"
29 #include "HYDROData_Tool.h"
30
31 #include <TDataStd_RealArray.hxx>
32
33 #include <Precision.hxx>
34
35 #include <NCollection_DataMap.hxx>
36
37 #include <TColStd_Array1OfReal.hxx>
38 #include <TColStd_ListOfReal.hxx>
39 #include <TColStd_ListIteratorOfListOfReal.hxx>
40 #include <TCollection_CompareOfReal.hxx>
41 #include <TColgp_Array1OfPnt.hxx>
42 #include <TColgp_HArray1OfPnt.hxx>
43
44 #include <TopoDS.hxx>
45 #include <TopoDS_Wire.hxx>
46 #include <TopoDS_Shell.hxx>
47 #include <TopoDS_Face.hxx>
48 #include <TopoDS_Edge.hxx>
49 #include <TopoDS_Vertex.hxx>
50 #include <TopExp.hxx>
51 #include <TopExp_Explorer.hxx>
52
53 #include <Bnd_Box.hxx>
54
55 #include <BRep_Builder.hxx>
56 #include <BRepBuilderAPI_MakeEdge.hxx>
57 #include <BRepBuilderAPI_MakeWire.hxx>
58 #include <BRepBuilderAPI_MakeFace.hxx>
59
60 #include <BRepBndLib.hxx>
61 #include <BRepProj_Projection.hxx>
62 #include <BRepExtrema_ExtCC.hxx>
63 #include <BRepCheck_Analyzer.hxx>
64
65 #include <gp.hxx>
66 #include <gp_Ax1.hxx>
67 #include <gp_Ax2.hxx>
68 #include <gp_Ax3.hxx>
69 #include <gp_Vec.hxx>
70 #include <gp_Pnt.hxx>
71 #include <gp_Pln.hxx>
72
73 #include <GeomAPI_Interpolate.hxx>
74 #include <Geom_BSplineCurve.hxx>
75
76 #include <TopTools_Array1OfShape.hxx>
77
78 #include <SortTools_QuickSortOfReal.hxx>
79
80 #include <QColor>
81 #include <QStringList>
82
83 //#define DEB_STREAM 1
84 #ifdef DEB_STREAM
85 //#define DEB_HASINT 1
86 //#define DEB_UPDATE 1
87 #include <BRepTools.hxx>
88 #include <TCollection_AsciiString.hxx>
89 #endif
90
91 typedef NCollection_DataMap<Standard_Real, Handle(HYDROData_Profile)> HYDROData_DataMapOfRealOfHDProfile;
92
93 IMPLEMENT_STANDARD_HANDLE(HYDROData_Stream,HYDROData_NaturalObject)
94 IMPLEMENT_STANDARD_RTTIEXT(HYDROData_Stream,HYDROData_NaturalObject)
95
96
97 HYDROData_Stream::HYDROData_Stream()
98 : HYDROData_NaturalObject()
99 {
100 }
101
102 HYDROData_Stream::~HYDROData_Stream()
103 {
104 }
105
106 QStringList HYDROData_Stream::DumpToPython( MapOfTreatedObjects& theTreatedObjects ) const
107 {
108   QStringList aResList = dumpObjectCreation( theTreatedObjects );
109   QString aName = GetObjPyName();
110
111   Handle(HYDROData_PolylineXY) aHydAxis = GetHydraulicAxis();
112   setPythonReferenceObject( theTreatedObjects, aResList, aHydAxis, "SetHydraulicAxis" );
113
114   HYDROData_SequenceOfObjects aSeqOfProfiles = GetProfiles();
115   for ( int i = 1, aNb = aSeqOfProfiles.Size(); i <= aNb; ++i )
116   {
117     const Handle(HYDROData_Entity) aProfile = aSeqOfProfiles.Value( i );
118     setPythonReferenceObject( theTreatedObjects, aResList, aProfile, "AddProfile" );
119   }
120
121   // Set bottom polyline if exists
122   const Handle(HYDROData_Polyline3D) aBottomPolyline = GetBottomPolyline();
123   if ( !aBottomPolyline.IsNull() ) {
124     setPythonReferenceObject( theTreatedObjects, aResList, aBottomPolyline, "SetBottomPolyline" );
125   }
126
127   aResList << QString( "" );
128   aResList << QString( "%1.Update();" ).arg( aName );
129   aResList << QString( "" );
130
131   return aResList;
132 }
133
134 HYDROData_SequenceOfObjects HYDROData_Stream::GetAllReferenceObjects() const
135 {
136   HYDROData_SequenceOfObjects aResSeq = HYDROData_Object::GetAllReferenceObjects();
137
138   Handle(HYDROData_PolylineXY) aHydAxis = GetHydraulicAxis();
139   if ( !aHydAxis.IsNull() )
140     aResSeq.Append( aHydAxis );
141
142   HYDROData_SequenceOfObjects aSeqOfProfiles = GetProfiles();
143   aResSeq.Append( aSeqOfProfiles );
144
145   return aResSeq;
146 }
147
148 TopoDS_Shape HYDROData_Stream::GetTopShape() const
149 {
150   return getTopShape();
151 }
152
153 TopoDS_Shape HYDROData_Stream::GetShape3D() const
154 {
155   return getShape3D();
156 }
157
158 Handle(Geom_BSplineCurve) HYDROData_Stream::buildInterpolationCurve( 
159   const Handle(TColgp_HArray1OfPnt)& theArrayOfPnt )
160 {
161   Handle(Geom_BSplineCurve) aBSpline;
162   GeomAPI_Interpolate anInterpolator (theArrayOfPnt, Standard_False, 1.0e-5); 
163   anInterpolator.Perform() ;
164   if (anInterpolator.IsDone()) 
165     aBSpline = anInterpolator.Curve();
166   return aBSpline; 
167 }
168
169 void HYDROData_Stream::Update()
170 {
171   updateProfilesOrder();
172
173   // Update bottom polyline if exists
174   const Handle(HYDROData_Polyline3D) aBottomPolyline = GetBottomPolyline();
175   if ( !aBottomPolyline.IsNull() ) {
176     if ( GenerateBottomPolyline() ) {
177       Handle(HYDROData_PolylineXY) aPolylineXY = aBottomPolyline->GetPolylineXY();
178       if ( !aPolylineXY.IsNull() ) {
179         aPolylineXY->Update();
180       }
181       aBottomPolyline->Update();
182     }
183   }
184
185   UpdatePrs();
186 }
187
188 bool HYDROData_Stream::IsHas2dPrs() const
189 {
190   return true;
191 }
192
193 bool HYDROData_Stream::CreatePresentations( const Handle(HYDROData_PolylineXY)& theHydAxis,
194                                             const HYDROData_SequenceOfObjects&  theProfiles,
195                                             PrsDefinition&                      thePrs )
196 {
197   if ( theHydAxis.IsNull() || theProfiles.Length() < 2 )
198     return false;
199
200   gp_Pnt aPrevFirstPoint, aPrevLastPoint;
201   Handle(TColgp_HArray1OfPnt) anArrayOfFPnt    = new TColgp_HArray1OfPnt(1, theProfiles.Length());
202   Handle(TColgp_HArray1OfPnt) anArrayOfLPnt    = new TColgp_HArray1OfPnt(1, theProfiles.Length());  
203   TopTools_Array1OfShape anArrOfProfiles(1, theProfiles.Length());
204   TopTools_Array1OfShape anArrOf2DProfiles(1, theProfiles.Length());
205
206   // Pre-processing
207   HYDROData_SequenceOfObjects::Iterator anIter( theProfiles );
208   for (int i=1 ; anIter.More(); anIter.Next(),i++ )
209   {
210     Handle(HYDROData_Profile) aProfile =
211       Handle(HYDROData_Profile)::DownCast( anIter.Value() );
212     if ( aProfile.IsNull() )
213       continue;
214
215     const TopoDS_Shape& aProf3d = aProfile->GetShape3D();
216     gp_XY aPnt1, aPnt2;
217     if ( !aProfile->GetLeftPoint( aPnt1, false ) || !aProfile->GetRightPoint( aPnt2, false ) )
218       continue;
219
220     anArrOfProfiles.SetValue(i,aProfile->GetShape3D());//aProfile->GetTopShape();
221     anArrOf2DProfiles.SetValue(i,aProfile->GetTopShape());
222
223     gp_Pnt aCurFirstPoint( aPnt1.X(), aPnt1.Y(), 0 ), aCurFP;
224     gp_Pnt aCurLastPoint(  aPnt2.X(), aPnt2.Y(), 0 ), aCurLP;
225     TopoDS_Vertex aV1, aV2;
226     TopExp::Vertices(TopoDS::Wire(aProf3d), aV1, aV2);
227        gp_Pnt aP1 = BRep_Tool::Pnt(aV1);
228     if(aP1.X() == aPnt1.X() && aP1.Y() == aPnt1.Y())
229       aCurFP = aP1;
230     else
231       aCurLP = aP1;
232     aP1 = BRep_Tool::Pnt(aV2);
233     if(aP1.X() == aPnt2.X() && aP1.Y() == aPnt2.Y())
234       aCurLP = aP1;
235     else
236       aCurFP = aP1;
237     anArrayOfFPnt->SetValue(i,aCurFP);
238     anArrayOfLPnt->SetValue(i,aCurLP);
239   }
240
241   // Construct of the 3D presentation
242   Handle(Geom_BSplineCurve) aBSpline = buildInterpolationCurve (anArrayOfFPnt);
243   if(aBSpline.IsNull())
244     return false;
245
246   TopoDS_Edge anEdgLeft, anEdgRight;
247   
248   BRepBuilderAPI_MakeEdge aMakeEdge(aBSpline);
249   if(aMakeEdge.IsDone()) 
250     anEdgLeft = aMakeEdge.Edge();
251
252   if(anEdgLeft.IsNull())
253     return false;
254
255   aBSpline.Nullify();
256   aBSpline = buildInterpolationCurve (anArrayOfLPnt);  
257   if(aBSpline.IsNull())
258     return false;
259
260   aMakeEdge.Init(aBSpline);
261   if(aMakeEdge.IsDone()) 
262     anEdgRight = aMakeEdge.Edge();
263
264   if(anEdgRight.IsNull())
265     return false;
266
267   BRep_Builder aBB;
268   TopoDS_Compound aCmp;
269   aBB.MakeCompound(aCmp);
270   anIter.Init( theProfiles );
271   for (int i=1 ; i < anArrOfProfiles.Length() +1; i++ )  
272     aBB.Add(aCmp, anArrOfProfiles.Value(i));
273
274   aBB.Add(aCmp,anEdgLeft);
275   aBB.Add(aCmp,anEdgRight);
276   BRepCheck_Analyzer aCh(aCmp);
277   if(aCh.IsValid())
278     thePrs.myPrs3D = aCmp;
279 #ifdef DEB_UPDATE
280   else {
281     BRepTools::Write(aCmp, "str3d.brep");
282     thePrs.myPrs3D = aCmp;
283   }
284 #endif
285
286   // Construct the top presentation
287   for(int i=1;i<= anArrayOfLPnt->Length();i++) {
288       gp_Pnt aPnt = anArrayOfFPnt->Value(i);
289       aPnt.SetZ(.0); // make 2d
290       anArrayOfFPnt->SetValue(i, aPnt);
291       aPnt = anArrayOfLPnt->Value(i);
292       aPnt.SetZ(.0);
293       anArrayOfLPnt->SetValue(i, aPnt);
294   }
295
296   aBSpline.Nullify();
297   aBSpline = buildInterpolationCurve (anArrayOfFPnt);  
298   if(aBSpline.IsNull())
299     return false; 
300
301   aMakeEdge.Init(aBSpline);
302   if(aMakeEdge.IsDone()) 
303       anEdgLeft = aMakeEdge.Edge();
304
305   aBSpline.Nullify();
306   aBSpline = buildInterpolationCurve (anArrayOfLPnt);  
307   if(aBSpline.IsNull())
308     return false; 
309
310   aMakeEdge.Init(aBSpline);
311   if(aMakeEdge.IsDone()) 
312     anEdgRight = aMakeEdge.Edge();
313   if(anEdgRight.IsNull())
314     return false;
315
316   BRepBuilderAPI_MakeEdge aMakeEdge2(anArrayOfFPnt->Value(1),anArrayOfLPnt->Value(1));
317   TopoDS_Edge aBotEdge, aTopEdge;
318   if(aMakeEdge2.IsDone()) 
319     aBotEdge = aMakeEdge2.Edge();
320
321   BRepBuilderAPI_MakeEdge aMakeEdge3(anArrayOfFPnt->Value(anArrayOfFPnt->Length()),anArrayOfLPnt->Value(anArrayOfLPnt->Length()));
322   if(aMakeEdge3.IsDone()) 
323     aTopEdge = aMakeEdge3.Edge();
324
325   // Make wire for 2D presentation with updating of corresponding edges
326   BRepBuilderAPI_MakeWire aMakeWire;
327   
328   aMakeWire.Add( aBotEdge );
329   thePrs.myInlet = aMakeWire.Edge();
330
331   aMakeWire.Add( anEdgLeft );
332   thePrs.myLeftBank = aMakeWire.Edge();
333
334   aMakeWire.Add( aTopEdge );
335   thePrs.myOutlet = aMakeWire.Edge();
336
337   aMakeWire.Add( anEdgRight );
338   thePrs.myRightBank = aMakeWire.Edge();
339
340   TopoDS_Wire aSectProfileWire;
341   if(aMakeWire.IsDone())
342     aSectProfileWire = aMakeWire.Wire();
343
344   BRepBuilderAPI_MakeFace aMakeFace( aSectProfileWire, Standard_True );
345   TopoDS_Face aFace;
346   aMakeFace.Build();
347   if( aMakeFace.IsDone() )
348     aFace = aMakeFace.Face();
349
350   aCmp.Nullify();
351   aBB.MakeCompound(aCmp);
352   aBB.Add(aCmp,aFace);
353   for(int i=1;i <= anArrOf2DProfiles.Length(); i++)
354     aBB.Add(aCmp,anArrOf2DProfiles.Value(i));
355
356   aCh.Init(aCmp);
357   if(aCh.IsValid())
358    thePrs.myPrs2D = aCmp;
359 #ifdef DEB_UPDATE
360   else {
361     BRepTools::Write(aCmp, "str2d.brep");
362     thePrs.myPrs2D = aCmp;
363   }
364 #endif
365
366   return true;
367 }
368
369 void HYDROData_Stream::UpdatePrs()
370 {
371   HYDROData_NaturalObject::Update();
372
373   Handle(HYDROData_PolylineXY) aHydAxis = GetHydraulicAxis();
374   HYDROData_SequenceOfObjects aRefProfiles = GetProfiles();
375
376   PrsDefinition aResultPrs;
377   if ( !CreatePresentations( aHydAxis, aRefProfiles, aResultPrs ) )
378     return;
379
380   SetShape3D( aResultPrs.myPrs3D );
381   SetTopShape( aResultPrs.myPrs2D );
382
383   // Create the stream groups
384   QString aLeftGroupName = GetName() + "_Left_Bank";
385
386   Handle(HYDROData_ShapesGroup) aLeftGroup = createGroupObject();
387   aLeftGroup->SetName( aLeftGroupName );
388   aLeftGroup->AddShape( aResultPrs.myLeftBank );
389
390   QString aRightGroupName = GetName() + "_Right_Bank";
391
392   Handle(HYDROData_ShapesGroup) aRightGroup = createGroupObject();
393   aRightGroup->SetName( aRightGroupName );
394   aRightGroup->AddShape( aResultPrs.myRightBank );
395
396   QString anInGroupName = GetName() + "_Inlet";
397
398   Handle(HYDROData_ShapesGroup) anInGroup = createGroupObject();
399   anInGroup->SetName( anInGroupName );
400   anInGroup->AddShape( aResultPrs.myInlet );
401
402   QString anOutGroupName = GetName() + "_Outlet";
403   
404   Handle(HYDROData_ShapesGroup) anOutGroup = createGroupObject();
405   anOutGroup->SetName( anOutGroupName );
406   anOutGroup->AddShape( aResultPrs.myOutlet );
407 }
408
409 QColor HYDROData_Stream::DefaultFillingColor()
410 {
411   return QColor( Qt::green );
412 }
413
414 QColor HYDROData_Stream::DefaultBorderColor()
415 {
416   return QColor( Qt::transparent );
417 }
418
419 bool HYDROData_Stream::IsValidAsAxis( const Handle(HYDROData_PolylineXY)& theHydAxis )
420 {
421   if ( theHydAxis.IsNull() )
422     return false;
423
424   TopoDS_Shape aHydraulicShape = theHydAxis->GetShape();
425   if ( aHydraulicShape.IsNull() || 
426        aHydraulicShape.ShapeType() != TopAbs_WIRE ||
427        BRep_Tool::IsClosed( aHydraulicShape ) )
428     return false; // The polyline must be a single not closed wire
429
430   return true;
431 }
432
433 TopoDS_Shape getShapeFromGroup( const HYDROData_SequenceOfObjects& theGroups,
434                                 const int                          theGroupId )
435 {
436   TopoDS_Shape aResShape;
437   if ( theGroups.Length() != 4 )
438     return aResShape;
439
440   Handle(HYDROData_ShapesGroup) aGroup =
441     Handle(HYDROData_ShapesGroup)::DownCast( theGroups.Value( theGroupId ) );
442   if ( aGroup.IsNull() )
443     return aResShape;
444
445   TopTools_SequenceOfShape aGroupShapes;
446   aGroup->GetShapes( aGroupShapes );
447
448   if ( !aGroupShapes.IsEmpty() )
449     aResShape = aGroupShapes.First();
450
451   return aResShape;
452 }
453
454 TopoDS_Shape HYDROData_Stream::GetLeftShape() const
455 {
456   HYDROData_SequenceOfObjects aGroups = GetGroups();
457   return getShapeFromGroup( aGroups, 1 );
458 }
459
460 TopoDS_Shape HYDROData_Stream::GetRightShape() const
461 {
462   HYDROData_SequenceOfObjects aGroups = GetGroups();
463   return getShapeFromGroup( aGroups, 2 );
464 }
465
466 TopoDS_Shape HYDROData_Stream::GetInletShape() const
467 {
468   HYDROData_SequenceOfObjects aGroups = GetGroups();
469   return getShapeFromGroup( aGroups, 3 );
470 }
471
472 TopoDS_Shape HYDROData_Stream::GetOutletShape() const
473 {
474   HYDROData_SequenceOfObjects aGroups = GetGroups();
475   return getShapeFromGroup( aGroups, 4 );
476 }
477
478 QColor HYDROData_Stream::getDefaultFillingColor() const
479 {
480   return DefaultFillingColor();
481 }
482
483 QColor HYDROData_Stream::getDefaultBorderColor() const
484 {
485   return DefaultBorderColor();
486 }
487
488 bool HYDROData_Stream::SetHydraulicAxis( const Handle(HYDROData_PolylineXY)& theAxis )
489 {
490   if ( !IsValidAsAxis( theAxis ) )
491     return false;
492
493   Handle(HYDROData_PolylineXY) aPrevAxis = GetHydraulicAxis();
494   if ( IsEqual( aPrevAxis, theAxis ) )
495     return true;
496
497   SetReferenceObject( theAxis, DataTag_HydraulicAxis );
498
499   // Update the order of profiles
500   updateProfilesOrder();
501
502   // Indicate model of the need to update the stream presentation
503   SetToUpdate( true );
504
505   return true;
506 }
507
508 Handle(HYDROData_PolylineXY) HYDROData_Stream::GetHydraulicAxis() const
509 {
510   return Handle(HYDROData_PolylineXY)::DownCast( 
511            GetReferenceObject( DataTag_HydraulicAxis ) );
512 }
513
514 void HYDROData_Stream::RemoveHydraulicAxis()
515 {
516   Handle(HYDROData_PolylineXY) aPrevAxis = GetHydraulicAxis();
517   if ( aPrevAxis.IsNull() )
518     return;
519
520   ClearReferenceObjects( DataTag_HydraulicAxis );
521
522   // We remove the reference profiles
523   RemoveProfiles();
524
525   // Indicate model of the need to update the stream presentation
526   SetToUpdate( true );
527 }
528
529 bool HYDROData_Stream::HasIntersection( const Handle(HYDROData_Profile)& theProfile,
530                                         const TopoDS_Face&               thePlane,
531                                         Standard_Real&                   theOutPar ) const
532 {
533   Handle(HYDROData_PolylineXY) aHydAxis = GetHydraulicAxis();
534   return HasIntersection( aHydAxis, theProfile, thePlane, theOutPar );
535 }
536
537 bool HYDROData_Stream::HasIntersection( const Handle(HYDROData_PolylineXY)& theHydAxis, 
538                                         const Handle(HYDROData_Profile)&    theProfile, 
539                                         const TopoDS_Face&                  thePlane,
540                                         Standard_Real&                      theOutPar )
541 {
542   if ( theProfile.IsNull() || !IsValidAsAxis( theHydAxis ) )
543     return false; 
544
545   TopoDS_Wire aHydraulicWire = TopoDS::Wire( theHydAxis->GetShape() ); //guide line
546   TopoDS_Wire aProfileWire = TopoDS::Wire( theProfile->GetTopShape() );
547   if ( aHydraulicWire.IsNull() || aProfileWire.IsNull() )
548     return false;
549
550   BRepProj_Projection aProjector (aProfileWire, thePlane, gp::OZ().Direction());
551   if(!aProjector.IsDone())
552     return false;
553   TopoDS_Shape aPrjProfile = aProjector.Shape();
554   if(aPrjProfile.IsNull())
555     return false;
556   TopoDS_Vertex aV1, aV2;
557   if(aPrjProfile.ShapeType() == TopAbs_EDGE)
558     TopExp::Vertices(TopoDS::Edge(aPrjProfile), aV1, aV2);
559   else if(aPrjProfile.ShapeType() == TopAbs_WIRE)  
560     TopExp::Vertices(TopoDS::Wire(aPrjProfile), aV1, aV2);
561   else if(aPrjProfile.ShapeType() == TopAbs_COMPOUND){
562     TopExp_Explorer anExp(aPrjProfile, TopAbs_WIRE);
563     if(anExp.More()) {
564       TopExp::Vertices(TopoDS::Wire(anExp.Current()), aV1, aV2);
565     } else {
566       anExp.Init(aPrjProfile, TopAbs_EDGE);
567       if(anExp.More()) {
568         TopExp::Vertices(TopoDS::Edge(anExp.Current()), aV1, aV2);
569       }
570     }
571   }
572   if(aV1.IsNull() || aV2.IsNull())
573     return false;
574   gp_Pnt aPnt1 = BRep_Tool::Pnt(aV1);
575   gp_Pnt aPnt2 = BRep_Tool::Pnt(aV2);
576   aPnt1.SetZ(0.0);
577   aPnt2.SetZ(0.0);
578   BRepBuilderAPI_MakeEdge aMk(aPnt1, aPnt2); 
579   if(!aMk.IsDone())
580     return false;
581   const TopoDS_Edge& anEdg2 = aMk.Edge();//Section edge
582   Standard_Integer aNum(0);
583   
584   TopExp_Explorer anExplo(aHydraulicWire, TopAbs_EDGE);
585   for(;anExplo.More();anExplo.Next()) aNum++;
586   // check for self-intersection
587   const Standard_Real SquareTolerance = Precision::Confusion()*Precision::Confusion();
588   Standard_Boolean hasInt(false);
589   Standard_Real aSqDist(DBL_MAX);
590   Standard_Integer anIndx(0);
591   BRepExtrema_ExtCC aCC;
592   aCC.Initialize(anEdg2);
593   theOutPar = 0.0;
594   anExplo.Init(aHydraulicWire, TopAbs_EDGE);
595   for(Standard_Integer j=1;anExplo.More();anExplo.Next(),j++) {
596     const TopoDS_Edge& anEdg1 = TopoDS::Edge(anExplo.Current());
597     if(anEdg1.IsNull())
598       continue;
599     Standard_Boolean hasSol(false);
600     aCC.Perform(anEdg1);
601     if(aCC.IsDone()) {
602     // find minimal dist
603     for(Standard_Integer i=1; i<= aCC.NbExt();i++)
604       if(aCC.SquareDistance(i) < aSqDist) {
605         aSqDist = aCC.SquareDistance(i);
606         anIndx = i;
607         hasSol = true;
608       }  
609     }
610     if(hasSol) {
611       if(aSqDist <= SquareTolerance) { // hasInt
612         const gp_Pnt& aPnt = aCC.PointOnE1(anIndx);
613         if(aNum > 1) {
614           TopExp::Vertices(anEdg1, aV1, aV2, Standard_True);
615           theOutPar += BRep_Tool::Pnt(aV1).Distance(aPnt);
616         } else {
617           Standard_Real aPar = aCC.ParameterOnE1(anIndx);
618           theOutPar = aPar;
619         }
620         hasInt = true;
621         break;
622       } else {
623           // no ints-n
624         if(aNum > 1) {
625           TopExp::Vertices(anEdg1, aV1, aV2);
626           theOutPar += BRep_Tool::Pnt(aV1).Distance(BRep_Tool::Pnt(aV2));
627         }
628       }
629     } else if(aNum > 1) {
630       TopExp::Vertices(anEdg1, aV1, aV2);
631       theOutPar += BRep_Tool::Pnt(aV1).Distance(BRep_Tool::Pnt(aV2));
632     }
633   }
634   if(hasInt)
635     return true;
636   return false;
637 }
638
639 bool HYDROData_Stream::AddProfile( const Handle(HYDROData_Profile)& theProfile )
640 {
641   if ( theProfile.IsNull() )
642     return false;
643
644   Handle(HYDROData_PolylineXY) aHydAxis = GetHydraulicAxis();
645   if ( aHydAxis.IsNull() )
646     return false;
647
648   TopoDS_Face aPlane;
649   if(!BuildFace(aHydAxis, aPlane))
650     return false;
651
652   Standard_Real aPar(.0);
653   if ( HasReference( theProfile, DataTag_Profile ) || !HasIntersection( theProfile, aPlane, aPar ) )
654     return false; // Object is already in reference list or it has no intersection
655   
656   int aProfileIndex = insertParameter( aPar );
657   insertProfileInToOrder( theProfile, aProfileIndex );
658   
659   // Indicate model of the need to update the stream presentation
660   SetToUpdate( true );
661
662   return true;
663 }
664
665 bool HYDROData_Stream::SetProfiles( const HYDROData_SequenceOfObjects& theProfiles,
666                                     const bool&                        theIsToOrder )
667 {
668   if ( theIsToOrder )
669   {
670     for ( int i = 1; i <= theProfiles.Length(); ++i )
671     {
672       Handle(HYDROData_Profile) aProfile = 
673         Handle(HYDROData_Profile)::DownCast( theProfiles.Value( i ) );
674       if ( aProfile.IsNull() )
675         continue;
676
677       if ( !AddProfile( aProfile ) )
678         return false;
679     }
680   }
681   else // Just store the sequence of objects as is
682   {
683     bool anIsToUpdate = true;
684
685     HYDROData_SequenceOfObjects anOldProfiles = GetProfiles();
686     if ( anOldProfiles.Length() == theProfiles.Length() )
687     {
688       anIsToUpdate = false;
689
690       for ( int i = 1; i <= theProfiles.Length(); ++i )
691       {
692         Handle(HYDROData_Entity) anOldProfile = anOldProfiles.Value( i );
693         Handle(HYDROData_Entity) aNewProfile = theProfiles.Value( i );
694         if ( !IsEqual( anOldProfile, aNewProfile ) )
695         {
696           anIsToUpdate = true;
697           break;
698         }
699       }
700     }
701     
702     SetReferenceObjects( theProfiles, DataTag_Profile );
703
704     if ( anIsToUpdate )
705       SetToUpdate( true );
706   }
707
708   return true;
709 }
710
711 HYDROData_SequenceOfObjects HYDROData_Stream::GetProfiles() const
712 {
713   return GetReferenceObjects( DataTag_Profile );
714 }
715
716 bool HYDROData_Stream::RemoveProfile( const Handle(HYDROData_Profile)& theProfile )
717 {
718   if ( theProfile.IsNull() )
719     return false;
720
721   int aProfileIndex = -1;
722
723   HYDROData_SequenceOfObjects aRefProfiles = GetProfiles();
724   HYDROData_SequenceOfObjects::Iterator anIter( aRefProfiles );
725   for ( int i = 0 ; anIter.More(); anIter.Next(), ++i )
726   {
727     Handle(HYDROData_Profile) aProfile =
728       Handle(HYDROData_Profile)::DownCast( anIter.Value() );
729     if ( aProfile.IsNull() )
730       continue;
731
732     if ( IsEqual( theProfile, aProfile ) )
733     {
734       aProfileIndex = i;
735       break;
736     }
737   }
738
739   if ( aProfileIndex == -1 )
740     return false;
741
742   RemoveReferenceObject( theProfile->Label(), DataTag_Profile );
743
744   // Remove parameter for removed profile
745   removeParameter( aProfileIndex );
746
747   // Indicate model of the need to update the stream presentation
748   SetToUpdate( true );
749
750   return true;
751 }
752
753 void HYDROData_Stream::RemoveProfiles()
754 {
755   bool anIsToUpdate = IsMustBeUpdated() || NbReferenceObjects( DataTag_Profile ) > 0;
756
757   ClearReferenceObjects( DataTag_Profile );
758
759   // Remove the parameters array
760   removeParametersArray();
761
762   // Indicate model of the need to update the stream presentation
763   SetToUpdate( anIsToUpdate );
764 }
765
766 void HYDROData_Stream::insertProfileInToOrder( const Handle(HYDROData_Profile)& theProfile,
767                                                const int                        theBeforeIndex )
768 {
769   Handle(HYDROData_PolylineXY) aHydAxis = GetHydraulicAxis();
770   if ( theProfile.IsNull() || aHydAxis.IsNull() )
771     return; 
772
773   TopoDS_Wire aHydraulicWire = TopoDS::Wire( aHydAxis->GetShape() );
774   TopoDS_Wire aProfileWire = TopoDS::Wire( theProfile->GetTopShape() );
775   if ( aHydraulicWire.IsNull() || aProfileWire.IsNull() )
776     return;
777
778   if ( theBeforeIndex == -1 )
779     AddReferenceObject( theProfile, DataTag_Profile );
780   else
781     InsertReferenceObject( theProfile, DataTag_Profile, theBeforeIndex );
782 }
783
784 bool HYDROData_Stream::BuildFace( const Handle(HYDROData_PolylineXY)& theHydAxis,
785                                   TopoDS_Face&                        thePlane )
786 {
787   if ( !IsValidAsAxis( theHydAxis ) )
788     return false;
789
790   TopoDS_Wire aHydraulicWire = TopoDS::Wire( theHydAxis->GetShape() );
791
792   gp_Ax2 aX2(gp::XOY());
793   gp_Ax3 aX3(aX2);
794   gp_Pln aPln(aX3);   
795   Bnd_Box B;
796   BRepBndLib::Add(aHydraulicWire,B);
797   Standard_Real axmin,aymin,azmin,axmax,aymax,azmax;
798   B.Get(axmin,aymin,azmin,axmax,aymax,azmax);
799   BRepBuilderAPI_MakeFace aMkr(aPln, axmin-500., axmax+500., aymin-500., aymax+500.); // to be tuned later according max/ Profile deviation
800   if(!aMkr.IsDone() || aMkr.Shape().IsNull()) return false;
801   thePlane = TopoDS::Face(aMkr.Shape());
802   return true;
803 }
804
805 void HYDROData_Stream::updateProfilesOrder()
806 {
807   HYDROData_SequenceOfObjects aRefProfiles = GetProfiles();
808   if ( aRefProfiles.IsEmpty() )
809     return;
810
811   // At first we remove all profiles from order
812   RemoveProfiles();
813
814   Handle(HYDROData_PolylineXY) aHydAxis = GetHydraulicAxis();
815   if ( aHydAxis.IsNull() )
816     return; 
817
818   TopoDS_Face aPlane;
819   if ( !BuildFace( aHydAxis, aPlane ) )
820     return;
821
822   Standard_Real aPar( .0 );
823
824 #ifdef DEB_HASINT
825   BRep_Builder aBB;
826   TopoDS_Compound aCmp;
827   aBB.MakeCompound(aCmp);
828 #endif
829
830   HYDROData_DataMapOfRealOfHDProfile aDM;  
831   TColStd_ListOfReal aList;
832   HYDROData_SequenceOfObjects::Iterator anIter( aRefProfiles );
833   for (int i = 1 ; anIter.More(); anIter.Next(), i++ )
834   {
835     Handle(HYDROData_Profile) aProfile =
836       Handle(HYDROData_Profile)::DownCast( anIter.Value() );
837 #ifdef DEB_HASINT
838   TopoDS_Wire aProfileWire = TopoDS::Wire( aProfile->GetTopShape() );
839   aBB.Add( aCmp, aProfileWire ); 
840 #endif
841     if ( aProfile.IsNull() || !HasIntersection( aProfile, aPlane, aPar ) )
842       continue;
843     
844     aDM.Bind( aPar, aProfile );
845     aList.Append( aPar );
846   }
847   
848   if ( aList.IsEmpty() )
849     return;
850
851   TColStd_Array1OfReal anArr( 1, aList.Extent() );
852
853   TColStd_ListIteratorOfListOfReal it( aList );
854   for ( int j = 1; it.More(); it.Next(), j++ )
855     anArr( j ) = it.Value();
856
857   // sorting
858   if ( aList.Extent() > 1 )
859   {
860     TCollection_CompareOfReal Compar;
861     SortTools_QuickSortOfReal::Sort( anArr, Compar );
862
863     for (int j = 1; j <= anArr.Length(); j++) {
864       const Standard_Real aKey =  anArr(j);
865       const Handle(HYDROData_Profile)& aProfile = aDM.Find(aKey);
866       insertProfileInToOrder( aProfile );
867     }
868   } else if ( aList.Extent() == 1 ) {
869      const Standard_Real aKey = aList.Last();
870      const Handle(HYDROData_Profile)& aProfile = aDM.Find(aKey);
871      insertProfileInToOrder( aProfile );
872   } 
873
874   setParametersArray( anArr );
875
876 #ifdef DEB_HASINT
877   TopoDS_Wire aHydraulicWire = TopoDS::Wire( aHydAxis->GetShape() );
878   BRepTools::Write(aHydraulicWire, "Path.brep");
879   BRepTools::Write(aCmp, "Prof.brep");
880 #endif
881 }
882
883 ObjectKind HYDROData_Stream::getAltitudeObjectType() const
884 {
885   return KIND_STREAM_ALTITUDE;
886 }
887
888 void HYDROData_Stream::setParametersArray( const TColStd_Array1OfReal& theArray )
889 {
890   if ( theArray.Length() == 0 )
891   {
892     removeParametersArray();
893     return;
894   }
895
896   TDF_Label aLabel = myLab.FindChild( DataTag_ParamsArray );
897   
898   Handle(TDataStd_RealArray) aParamsArray = 
899     TDataStd_RealArray::Set( aLabel, theArray.Lower(), theArray.Upper() );
900
901   for ( int i = theArray.Lower(), n = theArray.Upper(); i <= n; ++i )
902   {
903     const Standard_Real& aParam = theArray( i );
904     aParamsArray->SetValue( i, aParam );
905   }
906 }
907
908 TColStd_Array1OfReal* HYDROData_Stream::getParametersArray() const
909 {
910   TColStd_Array1OfReal* anArray = NULL;
911
912   TDF_Label aLabel = myLab.FindChild( DataTag_ParamsArray, false );
913   if ( !aLabel.IsNull() )
914   {
915     Handle(TDataStd_RealArray) aParamsArray;
916     if ( aLabel.FindAttribute( TDataStd_RealArray::GetID(), aParamsArray ) )
917     {
918       anArray = new TColStd_Array1OfReal( aParamsArray->Lower(), aParamsArray->Upper() );
919       for ( int i = aParamsArray->Lower(), n = aParamsArray->Upper(); i <= n; ++i )
920       {
921         const Standard_Real& aParam = aParamsArray->Value( i );
922         anArray->SetValue( i, aParam );
923       }
924     }
925   }
926
927   return anArray;
928 }
929
930 void HYDROData_Stream::removeParametersArray()
931 {
932   TDF_Label aLabel = myLab.FindChild( DataTag_ParamsArray, false );
933   if ( !aLabel.IsNull() )
934     aLabel.ForgetAllAttributes();
935 }
936
937 int HYDROData_Stream::insertParameter( const Standard_Real& theParam )
938 {
939   int aResIndex = -1;
940
941   TColStd_Array1OfReal* anArr = getParametersArray();
942   if ( anArr )
943   {
944     aResIndex = 0;
945
946     TColStd_Array1OfReal aNewArr( anArr->Lower(), anArr->Upper() + 1 );
947
948     bool isInserted = false;
949     for ( int i = anArr->Lower(), j = i, n = anArr->Upper(); i <= n; ++i, ++j )
950     {
951       const Standard_Real& aStoredParam = anArr->Value( i );
952       if ( !isInserted )
953       {
954         if ( theParam > aStoredParam )
955         {
956           aResIndex++;
957         }
958         else
959         {
960           aNewArr( j ) = theParam;
961           isInserted = true;
962           ++j;
963         }
964       }
965
966       aNewArr( j ) = aStoredParam;
967     }
968
969     if ( !isInserted )
970     {
971       aResIndex = -1;
972       aNewArr( aNewArr.Upper() ) = theParam;
973     }
974     
975     setParametersArray( aNewArr );
976     delete anArr;
977   }
978   else
979   {
980     TColStd_Array1OfReal aNewArr( 1, 1 );
981     aNewArr.SetValue( 1, theParam );
982     setParametersArray( aNewArr );
983   }
984
985   return aResIndex;
986 }
987
988 void HYDROData_Stream::removeParameter( const int& theIndex )
989 {
990   TDF_Label aLabel = myLab.FindChild( DataTag_ParamsArray, false );
991   if ( aLabel.IsNull() )
992     return;
993
994   Handle(TDataStd_RealArray) aParamsArray;
995   if ( !aLabel.FindAttribute( TDataStd_RealArray::GetID(), aParamsArray ) )
996     return;
997
998   if ( aParamsArray->Length() == 1 )
999   {
1000     removeParametersArray();
1001     return;
1002   }
1003
1004   TColStd_Array1OfReal aNewArr( aParamsArray->Lower(), aParamsArray->Upper() - 1 );
1005
1006   for ( int i = aParamsArray->Lower(), j = i, k = 0, n = aParamsArray->Upper(); i <= n; ++i, ++k )
1007   {
1008     const Standard_Real& aStoredParam = aParamsArray->Value( i );
1009     if ( k == theIndex )
1010       continue;
1011
1012     aNewArr.SetValue( j, aStoredParam );
1013     ++j;
1014   }
1015
1016   setParametersArray( aNewArr );
1017 }
1018
1019 bool HYDROData_Stream::GenerateBottomPolyline()
1020 {
1021   // Get the document
1022   Handle(HYDROData_Document) aDocument = HYDROData_Document::Document( myLab );
1023   if ( aDocument.IsNull() ) {
1024     return false;
1025   }
1026
1027   // Collect bottom points ( one bottom point from each profile of the stream )
1028   HYDROData_Profile::ProfilePoints aBottomPoints;
1029   
1030   HYDROData_SequenceOfObjects aSeqOfProfiles = GetProfiles();
1031   for ( int i = 1, aNb = aSeqOfProfiles.Size(); i <= aNb; i++ ) {
1032     const Handle(HYDROData_Profile) aProfile = 
1033       Handle(HYDROData_Profile)::DownCast( aSeqOfProfiles.Value( i ) );
1034     if ( aProfile.IsNull() ) {
1035       continue;
1036     }
1037     
1038     aBottomPoints.Append( aProfile->GetBottomPoint() );
1039   }
1040
1041   int aNbBottomPoints = aBottomPoints.Size();
1042
1043   if ( aNbBottomPoints < 2 ) {
1044     return false;
1045   }
1046
1047   // Create bottom polyline object if the stream doesn't contain it yet
1048   Handle(HYDROData_Polyline3D) aBottom = GetBottomPolyline();
1049   if ( aBottom.IsNull() ) {
1050     aBottom = Handle(HYDROData_Polyline3D)::DownCast( aDocument->CreateObject( KIND_POLYLINE ) );  
1051     QString aBaseName = GetName() + "_bottom";
1052     QString aName = HYDROData_Tool::GenerateObjectName( aDocument, aBaseName, QStringList(), true );
1053     aBottom->SetName( aName );
1054
1055     SetReferenceObject( aBottom, DataTag_BottomPolyline );
1056   }
1057   
1058   // Create 2D polyline if the bottom polyline doesn't contain it yet
1059   Handle(HYDROData_PolylineXY) aPolylineXY = aBottom->GetPolylineXY();
1060   if ( aPolylineXY.IsNull() ) {
1061     aPolylineXY = Handle(HYDROData_PolylineXY)::DownCast( aDocument->CreateObject( KIND_POLYLINEXY ) );
1062     QString aBaseName = GetName() + "_bottom_2d";
1063     QString aName = HYDROData_Tool::GenerateObjectName( aDocument, aBaseName, QStringList(), true );
1064     aPolylineXY->SetName( aName );
1065     aBottom->SetPolylineXY( aPolylineXY, false );
1066   }
1067
1068   aPolylineXY->RemoveSections();
1069   aPolylineXY->AddSection( "", HYDROData_PolylineXY::SECTION_SPLINE, false );
1070   
1071   // Create profile if the bottom polyline doesn't contain it yet
1072   Handle(HYDROData_ProfileUZ) aProfileUZ = aBottom->GetProfileUZ();
1073   if ( aProfileUZ.IsNull() ) {
1074     Handle(HYDROData_Profile) aProfile = 
1075       Handle(HYDROData_Profile)::DownCast( aDocument->CreateObject( KIND_PROFILE ) );
1076     QString aBaseName = GetName() + "_bottom_profile";
1077     QString aName = HYDROData_Tool::GenerateObjectName( aDocument, aBaseName, QStringList(), true );
1078     aProfile->SetName( aName );
1079     aProfileUZ = aProfile->GetProfileUZ( true );
1080     aBottom->SetProfileUZ( aProfileUZ );
1081   }
1082   
1083   aProfileUZ->RemoveSection( 0 );
1084
1085   aProfileUZ->CalculateAndAddPoints(aBottomPoints, aPolylineXY);
1086   
1087   return true;
1088 }
1089
1090 Handle(HYDROData_Polyline3D) HYDROData_Stream::GetBottomPolyline() const
1091 {
1092   return Handle(HYDROData_Polyline3D)::DownCast( 
1093            GetReferenceObject( DataTag_BottomPolyline ) );
1094 }
1095
1096 bool HYDROData_Stream::SetBottomPolyline( const Handle(HYDROData_Polyline3D)& theBottom )
1097 {
1098   if ( theBottom.IsNull() ) {
1099     return false;
1100   }
1101
1102   SetReferenceObject( theBottom, DataTag_BottomPolyline );
1103
1104   return true;
1105 }
1106
1107 bool HYDROData_Stream::Interpolate( HYDROData_IProfilesInterpolator* theInterpolator )
1108 {
1109   // Get the document
1110   Handle(HYDROData_Document) aDocument = HYDROData_Document::Document( myLab );
1111   if ( aDocument.IsNull() ) {
1112     return false;
1113   }
1114   
1115   if ( theInterpolator->GetCalculatedProfilesNumber() < 1 ) {
1116     theInterpolator->Calculate();
1117   }
1118
1119   if ( theInterpolator->GetErrorCode() != OK ) {
1120     return false;
1121   }
1122
1123   bool isOK = true;
1124
1125   for ( int aProfileInd = 0; aProfileInd < theInterpolator->GetCalculatedProfilesNumber(); aProfileInd++ ) {
1126     // Get calculated point coordinates
1127     HYDROData_Profile::ProfilePoints aResultPoints = theInterpolator->GetResultProfilePoints( aProfileInd );
1128     if ( aResultPoints.IsEmpty() ) {
1129       isOK = false;
1130       continue;
1131     }
1132         
1133     // Create profile object
1134     Handle(HYDROData_Profile) aProfile = 
1135       Handle(HYDROData_Profile)::DownCast( aDocument->CreateObject( KIND_PROFILE ) );
1136     QString aBaseName = GetName() + "_interp_profile";
1137     QString aName = HYDROData_Tool::GenerateObjectName( aDocument, aBaseName );
1138     aProfile->SetName( aName );
1139
1140     // Fill the profile with points
1141     aProfile->SetProfilePoints( aResultPoints );
1142
1143     // Add profile to the stream
1144     bool isAdded = AddProfile( aProfile );
1145     if ( !isAdded ) {
1146       aProfile->Remove();
1147     }
1148     else
1149       aProfile->Update();
1150   }
1151
1152   if ( isOK )
1153     Update();
1154
1155   return isOK;
1156 }
1157
1158 void HYDROData_Stream::CopyTo( const Handle(HYDROData_Entity)& theDestination ) const
1159 {
1160   // Get the document
1161   Handle(HYDROData_Document) aDocument = HYDROData_Document::Document( myLab );
1162   if ( aDocument.IsNull() ) {
1163     return;
1164   }
1165
1166   // Call base method
1167   HYDROData_Entity::CopyTo( theDestination );
1168
1169   Handle(HYDROData_Stream) aStreamCopy = 
1170     Handle(HYDROData_Stream)::DownCast( theDestination );
1171
1172   // Copy bottom polyline if exists
1173   if ( !aStreamCopy.IsNull() ) {
1174     const Handle(HYDROData_Polyline3D) aBottom = GetBottomPolyline();
1175     if ( !aBottom.IsNull() ) {
1176       aStreamCopy->ClearReferenceObjects( DataTag_BottomPolyline );
1177       aStreamCopy->GenerateBottomPolyline();
1178       const Handle(HYDROData_Polyline3D) aBottomCopy = aStreamCopy->GetBottomPolyline();
1179       if ( !aBottomCopy.IsNull() && !aBottomCopy->GetPolylineXY().IsNull() ) {
1180         aBottomCopy->GetPolylineXY()->Update();
1181         aBottomCopy->Update();
1182       }
1183     }
1184   }
1185 }