Salome HOME
Merge remote-tracking branch 'remotes/origin/BR_2017' into HEAD
[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 <TColgp_Array1OfPnt.hxx>
43 #include <TColgp_HArray1OfPnt.hxx>
44
45 #include <TopoDS.hxx>
46 #include <TopoDS_Wire.hxx>
47 #include <TopoDS_Shell.hxx>
48 #include <TopoDS_Face.hxx>
49 #include <TopoDS_Edge.hxx>
50 #include <TopoDS_Vertex.hxx>
51 #include <TopExp.hxx>
52 #include <TopExp_Explorer.hxx>
53
54 #include <Bnd_Box.hxx>
55
56 #include <BRep_Builder.hxx>
57 #include <BRepBuilderAPI_MakeEdge.hxx>
58 #include <BRepBuilderAPI_MakeWire.hxx>
59 #include <BRepBuilderAPI_MakeFace.hxx>
60
61 #include <BRepBndLib.hxx>
62 #include <BRepProj_Projection.hxx>
63 #include <BRepExtrema_ExtCC.hxx>
64 #include <BRepCheck_Analyzer.hxx>
65
66 #include <gp.hxx>
67 #include <gp_Ax1.hxx>
68 #include <gp_Ax2.hxx>
69 #include <gp_Ax3.hxx>
70 #include <gp_Vec.hxx>
71 #include <gp_Pnt.hxx>
72 #include <gp_Pln.hxx>
73
74 #include <GeomAPI_Interpolate.hxx>
75 #include <Geom_BSplineCurve.hxx>
76
77 #include <TopTools_HArray1OfShape.hxx>
78 #include <TopTools_IndexedMapOfOrientedShape.hxx>
79 #include <TopTools_ListIteratorOfListOfShape.hxx>
80 #include <TopTools_SequenceOfShape.hxx>
81 #include <TopTools_IndexedMapOfShape.hxx>
82
83 #include <QColor>
84 #include <QStringList>
85 #include <QVector>
86
87 //#define DEB_STREAM 1
88 #ifdef DEB_STREAM
89 //#define DEB_HASINT 1
90 //#define DEB_UPDATE 1
91 #include <BRepTools.hxx>
92 #include <TCollection_AsciiString.hxx>
93 #endif
94
95 #define _DEVDEBUG_
96 #include "HYDRO_trace.hxx"
97
98 #include <assert.h>
99
100 typedef NCollection_DataMap<Standard_Real, Handle(HYDROData_Profile)> HYDROData_DataMapOfRealOfHDProfile;
101
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 = OutInlet;
222   thePrs.myOutlet = OutOutlet;
223   thePrs.myLeftBank = OutLeftB;
224   thePrs.myRightBank = 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     {
427       DEBTRACE("aProfileWire.IsNull");
428       return false;
429     }
430
431   //BRepProj_Projection aProjector (aProfileWire, thePlane, gp::OZ().Direction());
432   BRepAlgo_NormalProjection nproj(thePlane);
433   nproj.Add(aProfileWire);
434   nproj.SetDefaultParams();
435   nproj.Build();
436   if(!nproj.IsDone())
437     {
438       DEBTRACE("!nproj.IsDone");
439       return false;
440     }
441   TopoDS_Shape aPrjProfile = nproj.Projection();
442   if(aPrjProfile.IsNull())
443     {
444       DEBTRACE("aPrjProfile.IsNull");
445       return false;
446     }
447   TopoDS_Vertex aV1, aV2;
448   if(aPrjProfile.ShapeType() == TopAbs_EDGE)
449     TopExp::Vertices(TopoDS::Edge(aPrjProfile), aV1, aV2);
450   else if(aPrjProfile.ShapeType() == TopAbs_WIRE)  
451     TopExp::Vertices(TopoDS::Wire(aPrjProfile), aV1, aV2);
452   else if(aPrjProfile.ShapeType() == TopAbs_COMPOUND){
453     TopExp_Explorer anExp(aPrjProfile, TopAbs_WIRE);
454     if(anExp.More()) {
455       TopExp::Vertices(TopoDS::Wire(anExp.Current()), aV1, aV2);
456     } else {
457       anExp.Init(aPrjProfile, TopAbs_EDGE);
458       if(anExp.More()) {
459         TopExp::Vertices(TopoDS::Edge(anExp.Current()), aV1, aV2);
460       }
461     }
462   }
463   if(aV1.IsNull() || aV2.IsNull())
464     {
465       DEBTRACE("aV1.IsNull() || aV2.IsNull()");
466       return false;
467     }
468   gp_Pnt aPnt1 = BRep_Tool::Pnt(aV1);
469   gp_Pnt aPnt2 = BRep_Tool::Pnt(aV2);
470   aPnt1.SetZ(0.0);
471   aPnt2.SetZ(0.0);
472   BRepBuilderAPI_MakeEdge aMk(aPnt1, aPnt2); 
473   if(!aMk.IsDone())
474     {
475       DEBTRACE("!aMk.IsDone()");
476       return false;
477     }
478   const TopoDS_Edge& anEdg2 = aMk.Edge();//Section edge
479   Standard_Integer aNum(0);
480   
481   TopExp_Explorer anExplo(aHydraulicWire, TopAbs_EDGE);
482   for(;anExplo.More();anExplo.Next()) aNum++;
483   // check for self-intersection
484   const Standard_Real SquareTolerance = Precision::Confusion()*Precision::Confusion();
485   Standard_Boolean hasInt(false);
486   Standard_Real aSqDist(DBL_MAX);
487   Standard_Integer anIndx(0);
488   BRepExtrema_ExtCC aCC;
489   aCC.Initialize(anEdg2);
490   theOutPar = 0.0;
491   anExplo.Init(aHydraulicWire, TopAbs_EDGE);
492   for(Standard_Integer j=1;anExplo.More();anExplo.Next(),j++) {
493     const TopoDS_Edge& anEdg1 = TopoDS::Edge(anExplo.Current());
494     if(anEdg1.IsNull())
495       continue;
496     Standard_Boolean hasSol(false);
497     aCC.Perform(anEdg1);
498     if(aCC.IsDone()) {
499     // find minimal dist
500     for(Standard_Integer i=1; i<= aCC.NbExt();i++)
501       if(aCC.SquareDistance(i) < aSqDist) {
502         aSqDist = aCC.SquareDistance(i);
503         anIndx = i;
504         hasSol = true;
505       }  
506     }
507     if(hasSol) {
508       if(aSqDist <= SquareTolerance) { // hasInt
509         const gp_Pnt& aPnt = aCC.PointOnE1(anIndx);
510         if(aNum > 1) {
511           TopExp::Vertices(anEdg1, aV1, aV2, Standard_True);
512           theOutPar += BRep_Tool::Pnt(aV1).Distance(aPnt);
513         } else {
514           Standard_Real aPar = aCC.ParameterOnE1(anIndx);
515           theOutPar = aPar;
516         }
517         hasInt = true;
518         break;
519       } else {
520           // no ints-n
521         if(aNum > 1) {
522           TopExp::Vertices(anEdg1, aV1, aV2);
523           theOutPar += BRep_Tool::Pnt(aV1).Distance(BRep_Tool::Pnt(aV2));
524         }
525       }
526     } else if(aNum > 1) {
527       TopExp::Vertices(anEdg1, aV1, aV2);
528       theOutPar += BRep_Tool::Pnt(aV1).Distance(BRep_Tool::Pnt(aV2));
529     }
530   }
531   if(hasInt)
532     return true;
533   DEBTRACE("!hasInt " << aPnt1.X() << " " << aPnt1.Y() << " " << aPnt2.X() << " " << aPnt2.Y() << " --- " << aSqDist);
534   return false;
535 }
536
537 bool HYDROData_Stream::AddProfile( const Handle(HYDROData_Profile)& theProfile )
538 {
539   if ( theProfile.IsNull() )
540     return false;
541
542  // Handle(HYDROData_PolylineXY) aHydAxis = GetHydraulicAxis();
543  // if ( aHydAxis.IsNull() )
544  //   return false;
545
546   TopoDS_Face aPlane;
547   BuildRefFace( aPlane );
548
549   Standard_Real aPar(.0);
550   if ( HasReference( theProfile, DataTag_Profile ) || !HasIntersection( theProfile, aPlane, aPar ) )
551     return false; // Object is already in reference list or it has no intersection
552   //DEBTRACE("AddProfile - insertParameter " << aPar);
553   int aProfileIndex = insertParameter( aPar );
554   insertProfileInToOrder( theProfile, aProfileIndex );
555
556   DTM()->SetProfiles( GetProfiles() );
557   
558   // Indicate model of the need to update the stream presentation
559   Changed( Geom_3d );
560
561   return true;
562 }
563
564 bool HYDROData_Stream::SetProfiles( const HYDROData_SequenceOfObjects& theProfiles,
565                                     const bool&                        theIsToOrder )
566 {
567   DEBTRACE(" --- SetProfiles " <<theIsToOrder );
568   if ( theIsToOrder )
569   {
570     for ( int i = 1; i <= theProfiles.Length(); ++i )
571     {
572       Handle(HYDROData_Profile) aProfile = 
573         Handle(HYDROData_Profile)::DownCast( theProfiles.Value( i ) );
574       if ( aProfile.IsNull() )
575         continue;
576
577       if ( !AddProfile( aProfile ) )
578       {
579         DTM()->SetProfiles( HYDROData_SequenceOfObjects() );
580         return false;
581       }
582     }
583   }
584   else // Just store the sequence of objects as is
585   {
586     bool anIsToUpdate = true;
587
588     HYDROData_SequenceOfObjects anOldProfiles = GetProfiles();
589     if ( anOldProfiles.Length() == theProfiles.Length() )
590     {
591       anIsToUpdate = false;
592
593       for ( int i = 1; i <= theProfiles.Length(); ++i )
594       {
595         Handle(HYDROData_Entity) anOldProfile = anOldProfiles.Value( i );
596         Handle(HYDROData_Entity) aNewProfile = theProfiles.Value( i );
597         if ( !IsEqual( anOldProfile, aNewProfile ) )
598         {
599           anIsToUpdate = true;
600           break;
601         }
602       }
603     }
604     
605     SetReferenceObjects( theProfiles, DataTag_Profile );
606
607     if ( anIsToUpdate )
608       Changed( Geom_3d );
609   }
610
611   DTM()->SetProfiles( GetProfiles() );
612   return true;
613 }
614
615 HYDROData_SequenceOfObjects HYDROData_Stream::GetProfiles() const
616 {
617   return GetReferenceObjects( DataTag_Profile );
618 }
619
620 bool HYDROData_Stream::RemoveProfile( const Handle(HYDROData_Profile)& theProfile )
621 {
622   if ( theProfile.IsNull() )
623     return false;
624
625   int aProfileIndex = -1;
626
627   HYDROData_SequenceOfObjects aRefProfiles = GetProfiles();
628   HYDROData_SequenceOfObjects::Iterator anIter( aRefProfiles );
629   for ( int i = 0 ; anIter.More(); anIter.Next(), ++i )
630   {
631     Handle(HYDROData_Profile) aProfile =
632       Handle(HYDROData_Profile)::DownCast( anIter.Value() );
633     if ( aProfile.IsNull() )
634       continue;
635
636     if ( IsEqual( theProfile, aProfile ) )
637     {
638       aProfileIndex = i;
639       break;
640     }
641   }
642
643   if ( aProfileIndex == -1 )
644     return false;
645
646   RemoveReferenceObject( theProfile->Label(), DataTag_Profile );
647
648   // Remove parameter for removed profile
649   removeParameter( aProfileIndex );
650
651   // Indicate model of the need to update the stream presentation
652   Changed( Geom_3d );
653
654   return true;
655 }
656
657 void HYDROData_Stream::RemoveProfiles()
658 {
659   ClearReferenceObjects( DataTag_Profile );
660
661   // Remove the parameters array
662   removeParametersArray();
663
664   // Indicate model of the need to update the stream presentation
665   Changed( Geom_3d );
666 }
667
668 void HYDROData_Stream::insertProfileInToOrder( const Handle(HYDROData_Profile)& theProfile,
669                                                const int                        theBeforeIndex )
670 {
671   //Handle(HYDROData_PolylineXY) aHydAxis = GetHydraulicAxis();
672   if ( theProfile.IsNull() )
673     return; 
674
675   //TopoDS_Wire aHydraulicWire = TopoDS::Wire( aHydAxis->GetShape() );
676   TopoDS_Wire aProfileWire = TopoDS::Wire( theProfile->GetTopShape() );
677   if ( aProfileWire.IsNull() )
678     return;
679
680   if ( theBeforeIndex == -1 )
681     AddReferenceObject( theProfile, DataTag_Profile );
682   else
683     InsertReferenceObject( theProfile, DataTag_Profile, theBeforeIndex );
684 }
685
686 void HYDROData_Stream::BuildRefFace( TopoDS_Face& thePlane )
687 {
688   thePlane = BRepBuilderAPI_MakeFace(gp_Pln(gp_Pnt(0,0,0),gp_Dir(0,0,1))).Face();
689 }
690
691 void HYDROData_Stream::updateProfilesOrder()
692 {
693   HYDROData_SequenceOfObjects aRefProfiles = GetProfiles();
694   if ( aRefProfiles.IsEmpty() )
695     return;
696
697   // At first we remove all profiles from order
698   RemoveProfiles();
699
700   Handle(HYDROData_PolylineXY) aHydAxis = GetHydraulicAxis();
701   if ( aHydAxis.IsNull() )
702     return; 
703
704   TopoDS_Face aPlane;
705   BuildRefFace( aPlane );
706
707   Standard_Real aPar( .0 );
708
709 #ifdef DEB_HASINT
710   BRep_Builder aBB;
711   TopoDS_Compound aCmp;
712   aBB.MakeCompound(aCmp);
713 #endif
714
715   HYDROData_DataMapOfRealOfHDProfile aDM;  
716   TColStd_ListOfReal aList;
717   HYDROData_SequenceOfObjects::Iterator anIter( aRefProfiles );
718   for (int i = 1 ; anIter.More(); anIter.Next(), i++ )
719   {
720     Handle(HYDROData_Profile) aProfile =
721       Handle(HYDROData_Profile)::DownCast( anIter.Value() );
722 #ifdef DEB_HASINT
723   TopoDS_Wire aProfileWire = TopoDS::Wire( aProfile->GetTopShape() );
724   aBB.Add( aCmp, aProfileWire ); 
725 #endif
726     if ( aProfile.IsNull() || !HasIntersection( aProfile, aPlane, aPar ) )
727       continue;
728     
729     aDM.Bind( aPar, aProfile );
730     aList.Append( aPar );
731   }
732   
733   if ( aList.IsEmpty() )
734     return;
735
736   QVector<double> anArr( aList.Extent() );
737
738   TColStd_ListIteratorOfListOfReal it( aList );
739   for ( int j = 1; it.More(); it.Next(), j++ )
740     anArr[j-1] = it.Value();
741
742   // sorting
743   if ( aList.Extent() > 1 )
744   {
745     //TCollection_CompareOfReal Compar;
746     //SortTools_QuickSortOfReal::Sort( anArr, Compar );
747     std::sort( anArr.begin(), anArr.end() );
748
749     for (int j = 1; j <= anArr.size(); j++) {
750       const Standard_Real aKey =  anArr[j-1];
751       const Handle(HYDROData_Profile)& aProfile = aDM.Find(aKey);
752       insertProfileInToOrder( aProfile );
753     }
754   } else if ( aList.Extent() == 1 ) {
755      const Standard_Real aKey = aList.Last();
756      const Handle(HYDROData_Profile)& aProfile = aDM.Find(aKey);
757      insertProfileInToOrder( aProfile );
758   } 
759
760   setParametersArray( anArr );
761
762 #ifdef DEB_HASINT
763   TopoDS_Wire aHydraulicWire = TopoDS::Wire( aHydAxis->GetShape() );
764   BRepTools::Write(aHydraulicWire, "Path.brep");
765   BRepTools::Write(aCmp, "Prof.brep");
766 #endif
767 }
768
769 ObjectKind HYDROData_Stream::getAltitudeObjectType() const
770 {
771   return KIND_DTM;
772 }
773
774 void HYDROData_Stream::setParametersArray( const QVector<double>& theArray )
775 {
776   if ( theArray.size() == 0 )
777   {
778     removeParametersArray();
779     return;
780   }
781
782   TDF_Label aLabel = myLab.FindChild( DataTag_ParamsArray );
783   
784   int n = theArray.size();
785   Handle(TDataStd_RealArray) aParamsArray = 
786     TDataStd_RealArray::Set( aLabel, 1, n );
787   aParamsArray->SetID(TDataStd_RealArray::GetID());
788   for ( int i = 0; i < n; ++i )
789   {
790     const Standard_Real& aParam = theArray[i];
791     aParamsArray->SetValue( i+1, aParam );
792   }
793 }
794
795 TColStd_Array1OfReal* HYDROData_Stream::getParametersArray() const
796 {
797   TColStd_Array1OfReal* anArray = NULL;
798
799   TDF_Label aLabel = myLab.FindChild( DataTag_ParamsArray, false );
800   if ( !aLabel.IsNull() )
801   {
802     Handle(TDataStd_RealArray) aParamsArray;
803     if ( aLabel.FindAttribute( TDataStd_RealArray::GetID(), aParamsArray ) )
804     {
805       anArray = new TColStd_Array1OfReal( aParamsArray->Lower(), aParamsArray->Upper() );
806       for ( int i = aParamsArray->Lower(), n = aParamsArray->Upper(); i <= n; ++i )
807       {
808         const Standard_Real& aParam = aParamsArray->Value( i );
809         anArray->SetValue( i, aParam );
810       }
811     }
812   }
813
814   return anArray;
815 }
816
817 void HYDROData_Stream::removeParametersArray()
818 {
819   TDF_Label aLabel = myLab.FindChild( DataTag_ParamsArray, false );
820   if ( !aLabel.IsNull() )
821     aLabel.ForgetAllAttributes();
822 }
823
824 int HYDROData_Stream::insertParameter( const Standard_Real& theParam )
825 {
826   int aResIndex = -1;
827
828   TColStd_Array1OfReal* anArr = getParametersArray();
829   if ( anArr )
830   {
831     aResIndex = 0;
832
833     QVector<double> aNewArr( anArr->Upper() +1 );
834     bool isInserted = false;
835     for ( int i = anArr->Lower(), j = i, n = anArr->Upper(); i <= n; ++i, ++j )
836     {
837       const Standard_Real& aStoredParam = anArr->Value( i );
838       if ( !isInserted )
839       {
840         if ( theParam > aStoredParam )
841         {
842           aResIndex++;
843         }
844         else
845         {
846           if (j<=n+1)
847             aNewArr[j-1] = theParam;
848           isInserted = true;
849           ++j;
850         }
851       }
852       if (j<=n+1)
853         aNewArr[j-1] = aStoredParam;
854     }
855
856     if ( !isInserted )
857     {
858       aResIndex = -1;
859       aNewArr[aNewArr.size()-1] = theParam;
860     }
861     
862     setParametersArray( aNewArr );
863     delete anArr;
864   }
865   else
866   {
867     QVector<double> aNewArr( 1 );
868     aNewArr[0] = theParam;
869     setParametersArray( aNewArr );
870   }
871
872   return aResIndex;
873 }
874
875 void HYDROData_Stream::removeParameter( const int& theIndex )
876 {
877   TDF_Label aLabel = myLab.FindChild( DataTag_ParamsArray, false );
878   if ( aLabel.IsNull() )
879     return;
880
881   Handle(TDataStd_RealArray) aParamsArray;
882   if ( !aLabel.FindAttribute( TDataStd_RealArray::GetID(), aParamsArray ) )
883     return;
884
885   if ( aParamsArray->Length() == 1 )
886   {
887     removeParametersArray();
888     return;
889   }
890
891   QVector<double> aNewArr( aParamsArray->Upper() - 2 );
892
893   for ( int i = aParamsArray->Lower(), j = i, k = 0, n = aParamsArray->Upper(); i <= n; ++i, ++k )
894   {
895     const Standard_Real& aStoredParam = aParamsArray->Value( i );
896     if ( k == theIndex )
897       continue;
898
899     aNewArr[j-1] = aStoredParam;
900     ++j;
901   }
902
903   setParametersArray( aNewArr );
904 }
905
906 bool HYDROData_Stream::GenerateBottomPolyline()
907 {
908   // Get the document
909   Handle(HYDROData_Document) aDocument = HYDROData_Document::Document( myLab );
910   if ( aDocument.IsNull() ) {
911     return false;
912   }
913
914   // Collect bottom points ( one bottom point from each profile of the stream )
915   HYDROData_Profile::ProfilePoints aBottomPoints;
916   
917   HYDROData_SequenceOfObjects aSeqOfProfiles = GetProfiles();
918   for ( int i = 1, aNb = aSeqOfProfiles.Size(); i <= aNb; i++ ) {
919     const Handle(HYDROData_Profile) aProfile = 
920       Handle(HYDROData_Profile)::DownCast( aSeqOfProfiles.Value( i ) );
921     if ( aProfile.IsNull() ) {
922       continue;
923     }
924     
925     aBottomPoints.Append( aProfile->GetBottomPoint() );
926   }
927
928   int aNbBottomPoints = aBottomPoints.Size();
929
930   if ( aNbBottomPoints < 2 ) {
931     return false;
932   }
933
934   // Create bottom polyline object if the stream doesn't contain it yet
935   Handle(HYDROData_Polyline3D) aBottom = GetBottomPolyline();
936   if ( aBottom.IsNull() ) {
937     aBottom = Handle(HYDROData_Polyline3D)::DownCast( aDocument->CreateObject( KIND_POLYLINE ) );  
938     QString aBaseName = GetName() + "_bottom";
939     QString aName = HYDROData_Tool::GenerateObjectName( aDocument, aBaseName, QStringList(), true );
940     aBottom->SetName( aName );
941
942     SetReferenceObject( aBottom, DataTag_BottomPolyline );
943   }
944   
945   // Create 2D polyline if the bottom polyline doesn't contain it yet
946   Handle(HYDROData_PolylineXY) aPolylineXY = aBottom->GetPolylineXY();
947   if ( aPolylineXY.IsNull() ) {
948     aPolylineXY = Handle(HYDROData_PolylineXY)::DownCast( aDocument->CreateObject( KIND_POLYLINEXY ) );
949     QString aBaseName = GetName() + "_bottom_2d";
950     QString aName = HYDROData_Tool::GenerateObjectName( aDocument, aBaseName, QStringList(), true );
951     aPolylineXY->SetName( aName );
952     aBottom->SetPolylineXY( aPolylineXY, false );
953   }
954
955   aPolylineXY->RemoveSections();
956   aPolylineXY->AddSection( "", HYDROData_PolylineXY::SECTION_SPLINE, false );
957   
958   // Create profile if the bottom polyline doesn't contain it yet
959   Handle(HYDROData_ProfileUZ) aProfileUZ = aBottom->GetProfileUZ();
960   if ( aProfileUZ.IsNull() ) {
961     Handle(HYDROData_Profile) aProfile = 
962       Handle(HYDROData_Profile)::DownCast( aDocument->CreateObject( KIND_PROFILE ) );
963     QString aBaseName = GetName() + "_bottom_profile";
964     QString aName = HYDROData_Tool::GenerateObjectName( aDocument, aBaseName, QStringList(), true );
965     aProfile->SetName( aName );
966     aProfileUZ = aProfile->GetProfileUZ( true );
967     aBottom->SetProfileUZ( aProfileUZ );
968   }
969   
970   aProfileUZ->RemoveSection( 0 );
971
972   aProfileUZ->CalculateAndAddPoints(aBottomPoints, aPolylineXY);
973   
974   return true;
975 }
976
977 Handle(HYDROData_Polyline3D) HYDROData_Stream::GetBottomPolyline() const
978 {
979   return Handle(HYDROData_Polyline3D)::DownCast( 
980            GetReferenceObject( DataTag_BottomPolyline ) );
981 }
982
983 bool HYDROData_Stream::SetBottomPolyline( const Handle(HYDROData_Polyline3D)& theBottom )
984 {
985   if ( theBottom.IsNull() ) {
986     return false;
987   }
988
989   SetReferenceObject( theBottom, DataTag_BottomPolyline );
990
991   return true;
992 }
993
994 bool HYDROData_Stream::Interpolate( HYDROData_IProfilesInterpolator* theInterpolator )
995 {
996   // Get the document
997   Handle(HYDROData_Document) aDocument = HYDROData_Document::Document( myLab );
998   if ( aDocument.IsNull() ) {
999     return false;
1000   }
1001   
1002   if ( theInterpolator->GetCalculatedProfilesNumber() < 1 ) {
1003     theInterpolator->Calculate();
1004   }
1005
1006   if ( theInterpolator->GetErrorCode() != OK ) {
1007     return false;
1008   }
1009
1010   bool isOK = true;
1011
1012   for ( int aProfileInd = 0; aProfileInd < theInterpolator->GetCalculatedProfilesNumber(); aProfileInd++ ) {
1013     // Get calculated point coordinates
1014     HYDROData_Profile::ProfilePoints aResultPoints = theInterpolator->GetResultProfilePoints( aProfileInd );
1015     if ( aResultPoints.IsEmpty() ) {
1016       isOK = false;
1017       continue;
1018     }
1019         
1020     // Create profile object
1021     Handle(HYDROData_Profile) aProfile = 
1022       Handle(HYDROData_Profile)::DownCast( aDocument->CreateObject( KIND_PROFILE ) );
1023     QString aBaseName = GetName() + "_interp_profile";
1024     QString aName = HYDROData_Tool::GenerateObjectName( aDocument, aBaseName );
1025     aProfile->SetName( aName );
1026
1027     // Fill the profile with points
1028     aProfile->SetProfilePoints( aResultPoints );
1029
1030     // Add profile to the stream
1031     bool isAdded = AddProfile( aProfile );
1032     if ( !isAdded ) {
1033       aProfile->Remove();
1034     }
1035     else
1036       aProfile->Update();
1037   }
1038
1039   if ( isOK )
1040     Update();
1041
1042   return isOK;
1043 }
1044
1045 void HYDROData_Stream::CopyTo( const Handle(HYDROData_Entity)& theDestination,
1046                                bool isGenerateNewName ) const
1047 {
1048   // Get the document
1049   Handle(HYDROData_Document) aDocument = HYDROData_Document::Document( myLab );
1050   if ( aDocument.IsNull() ) {
1051     return;
1052   }
1053
1054   // Call base method
1055   HYDROData_Entity::CopyTo( theDestination, isGenerateNewName );
1056
1057   Handle(HYDROData_Stream) aStreamCopy = 
1058     Handle(HYDROData_Stream)::DownCast( theDestination );
1059
1060   // Copy bottom polyline if exists
1061   if ( !aStreamCopy.IsNull() ) {
1062     const Handle(HYDROData_Polyline3D) aBottom = GetBottomPolyline();
1063     if ( !aBottom.IsNull() ) {
1064       aStreamCopy->ClearReferenceObjects( DataTag_BottomPolyline );
1065       aStreamCopy->GenerateBottomPolyline();
1066       const Handle(HYDROData_Polyline3D) aBottomCopy = aStreamCopy->GetBottomPolyline();
1067       if ( !aBottomCopy.IsNull() && !aBottomCopy->GetPolylineXY().IsNull() ) {
1068         aBottomCopy->GetPolylineXY()->Update();
1069         aBottomCopy->Update();
1070       }
1071     }
1072   }
1073 }
1074 void HYDROData_Stream::CreatePresentations( const Handle(TColgp_HArray1OfPnt)     theArrayOfFPnt,
1075                                             const Handle(TColgp_HArray1OfPnt)     theArrayOfLPnt,
1076                                             const Handle(TopTools_HArray1OfShape) theArrOfProfiles,
1077                                             PrsDefinition&                        thePrs )
1078 {
1079
1080   HYDROData_Bathymetry::AltitudePoints left;
1081   for (int i = theArrayOfLPnt->Lower(); i <= theArrayOfLPnt->Upper(); i++)
1082   {
1083     left.push_back(HYDROData_Bathymetry::AltitudePoint(theArrayOfLPnt->Value(i).X(), 
1084       theArrayOfLPnt->Value(i).Y(),
1085       theArrayOfLPnt->Value(i).Z()));
1086   }
1087
1088   HYDROData_Bathymetry::AltitudePoints right;
1089   for (int i = theArrayOfFPnt->Lower(); i <= theArrayOfFPnt->Upper(); i++)
1090   {
1091     right.push_back(HYDROData_Bathymetry::AltitudePoint(theArrayOfFPnt->Value(i).X(), 
1092       theArrayOfFPnt->Value(i).Y(),
1093       theArrayOfFPnt->Value(i).Z()));
1094   }
1095
1096   std::vector<HYDROData_Bathymetry::AltitudePoints> dummy;
1097   TopTools_IndexedMapOfOrientedShape ll = HYDROData_DTM::Create3DShape(left, right, dummy);
1098
1099   TopoDS_Shape LB, RB, IL, OL;
1100
1101   if (!ll.IsEmpty())
1102   {
1103     TopAbs_ShapeEnum ll1_sht = ll(1).ShapeType();
1104     TopAbs_ShapeEnum ll2_sht = ll(2).ShapeType();
1105     if ((ll1_sht == TopAbs_WIRE || ll1_sht == TopAbs_EDGE) &&
1106       (ll2_sht == TopAbs_WIRE || ll2_sht == TopAbs_EDGE))
1107     {
1108       LB = ll(1);
1109       RB = ll(2);
1110     }
1111   }
1112
1113   IL = TopoDS::Wire(theArrOfProfiles->Value(theArrOfProfiles->Lower())); //TODO check that
1114   OL = TopoDS::Wire(theArrOfProfiles->Value(theArrOfProfiles->Upper()));
1115
1116   //make new compound so it's shapes will be in known order to build correct projection
1117   BRep_Builder BB;
1118   TopoDS_Compound newCmp;
1119   BB.MakeCompound(newCmp);
1120   BB.Add(newCmp, LB);
1121   BB.Add(newCmp, IL);
1122   BB.Add(newCmp, OL);
1123   BB.Add(newCmp, RB);
1124
1125   thePrs.myPrs3D = newCmp;
1126
1127   TopTools_SequenceOfShape LS;
1128   //HYDROData_DTM::Get2dFaceFrom3dPres( newCmp, TopoDS::Face(thePrs.myPrs2D), &LS, ind );
1129   
1130   HYDROData_DTM::GetPlanarFaceFromBanks(TopoDS::Edge(LB), TopoDS::Edge(RB), TopoDS::Face(thePrs.myPrs2D), &LS);
1131
1132 #ifndef NDEBUG
1133   TopTools_IndexedMapOfShape EE;
1134   TopExp::MapShapes(thePrs.myPrs2D, TopAbs_EDGE, EE);
1135   int noncontNb = 0;
1136   for (int i = 1; i <= 4; i++)
1137   {
1138     TopoDS_Shape W = LS(i);
1139     TopTools_IndexedMapOfShape EW;
1140     TopExp::MapShapes(W, TopAbs_EDGE, EW);
1141     for (int k = 1; k <= EW.Extent(); k++)
1142       noncontNb += !EE.Contains(EW(k));
1143   }
1144   //noncontNb > 0 => some problem with edge history
1145   assert(noncontNb == 0);
1146 #endif
1147
1148   thePrs.myLeftBank = LS(1);  
1149   thePrs.myInlet = LS(2);  
1150   thePrs.myOutlet = LS(3);  
1151   thePrs.myRightBank = LS(4);
1152
1153 }