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