Salome HOME
correct update status of stream and DTM
[modules/hydro.git] / src / HYDROData / HYDROData_DTM.cxx
1
2 #include <HYDROData_DTM.h>
3 #include <HYDROData_Profile.h>
4
5 #include <Geom2d_BSplineCurve.hxx>
6 #include <Geom2dAPI_Interpolate.hxx>
7 #include <TColgp_HArray1OfPnt2d.hxx>
8 #include <TColgp_Array1OfVec2d.hxx>
9 #include <TColStd_HArray1OfBoolean.hxx>
10 #include <TopoDS.hxx>
11 #include <TopoDS_Edge.hxx>
12 #include <TopoDS_Wire.hxx>
13 #include <TopExp_Explorer.hxx>
14 #include <BRep_Tool.hxx>
15 #include <gp_Ax3.hxx>
16 #include <Geom_Line.hxx>
17 #include <Geom2d_Line.hxx>
18 #include <Geom2d_TrimmedCurve.hxx>
19 #include <Geom_BSplineCurve.hxx>
20 #include <Geom2d_BSplineCurve.hxx>
21 #include <GeomAPI_Interpolate.hxx>
22 #include <TColStd_Array1OfReal.hxx>
23 #include <TColStd_Array1OfInteger.hxx>
24 #include <TColgp_Array1OfPnt.hxx>
25 #include <TColgp_Array1OfVec.hxx>
26 #include <TColgp_HArray1OfPnt.hxx>
27 #include <Geom2dAPI_InterCurveCurve.hxx>
28 #include <Geom2dAPI_ProjectPointOnCurve.hxx>
29 #include <Geom2dAdaptor_Curve.hxx>
30 #include <GCPnts_AbscissaPoint.hxx>
31 #include <BRepBuilderAPI_MakeEdge.hxx>
32 #include <limits>
33
34 #include <BRepLib_MakeEdge.hxx>
35 #include <BRepLib_MakeWire.hxx>
36 #include <BRep_Builder.hxx>
37 #include <GeomProjLib.hxx>
38 #include <Geom_TrimmedCurve.hxx>
39 #include <Geom_Plane.hxx>
40 #include <BRepTools_WireExplorer.hxx>
41 #include <TopTools_IndexedMapOfShape.hxx>
42 #include <BRepBuilderAPI_MakeFace.hxx>
43 #include <TopExp.hxx>
44 #include <TopTools_IndexedMapOfOrientedShape.hxx>
45
46 #include <BRepLib_MakeEdge.hxx>
47 #include <BRepLib_MakeWire.hxx>
48 #include <BRep_Builder.hxx>
49
50
51
52 IMPLEMENT_STANDARD_HANDLE( HYDROData_DTM, HYDROData_Bathymetry )
53 IMPLEMENT_STANDARD_RTTIEXT( HYDROData_DTM, HYDROData_Bathymetry )
54
55
56 HYDROData_DTM::CurveUZ::CurveUZ( double theXCurv, const gp_Vec2d& theProfileDir, double theDeltaZ )
57   : myXcurv( theXCurv ), myProfileDir( theProfileDir ), myDeltaZ( theDeltaZ )
58 {
59 }
60
61 HYDROData_DTM::CurveUZ::~CurveUZ()
62 {
63 }
64
65 double HYDROData_DTM::CurveUZ::Xcurv() const
66 {
67   return myXcurv;
68 }
69
70 gp_Vec2d HYDROData_DTM::CurveUZ::ProfileDir() const
71 {
72   return myProfileDir;
73 }
74
75 double HYDROData_DTM::CurveUZ::DeltaZ() const
76 {
77   return myDeltaZ;
78 }
79
80 HYDROData_DTM::CurveUZ HYDROData_DTM::CurveUZ::operator + ( const CurveUZ& c ) const
81 {
82   HYDROData_DTM::CurveUZ res( Xcurv() + c.Xcurv(), ProfileDir() + c.ProfileDir(), DeltaZ() + c.DeltaZ() );
83   size_t n = size(), n1 = c.size();
84   if( n!=n1 )
85   {
86     std::cout << "Warning: different number of points in curves: " << n << ", " << n1 << std::endl;
87   }
88   res.reserve( n );
89   for( int i=0; i<n; i++ )
90   {
91     PointUZ p;
92     p.U = operator[]( i ).U + c[i].U;
93     p.Z = operator[]( i ).Z;
94     res.push_back( p );
95   }
96   return res;
97 }
98
99 HYDROData_DTM::CurveUZ HYDROData_DTM::CurveUZ::operator * ( double d ) const
100 {
101   HYDROData_DTM::CurveUZ res( Xcurv()*d, ProfileDir()*d, DeltaZ()*d );
102   size_t n = size();
103   res.reserve( n );
104   for( int i=0; i<n; i++ )
105   {
106     PointUZ p;
107     p.U = operator[]( i ).U * d;
108     p.Z = operator[]( i ).Z;
109     res.push_back( p );
110   }
111   return res;
112 }
113
114
115
116
117 HYDROData_DTM::HYDROData_DTM()
118 {
119 }
120
121 HYDROData_DTM::~HYDROData_DTM()
122 {
123 }
124
125 HYDROData_SequenceOfObjects HYDROData_DTM::GetProfiles() const
126 {
127   return GetReferenceObjects( DataTag_Profiles );
128 }
129
130 void HYDROData_DTM::SetProfiles( const HYDROData_SequenceOfObjects& theProfiles )
131 {
132   SetReferenceObjects( theProfiles, DataTag_Profiles );
133   Changed( Geom_3d );
134 }
135
136 double HYDROData_DTM::GetDDZ() const
137 {
138   return GetDouble( DataTag_DDZ );
139 }
140
141 void HYDROData_DTM::SetDDZ( double theDDZ )
142 {
143   SetDouble( DataTag_DDZ, theDDZ );
144   Changed( Geom_3d );
145 }
146
147 double HYDROData_DTM::GetSpatialStep() const
148 {
149   return GetDouble( DataTag_SpatialStep );
150 }
151
152 void HYDROData_DTM::SetSpatialStep( double theSpatialStep )
153 {
154   SetDouble( DataTag_SpatialStep, theSpatialStep );
155   Changed( Geom_3d );
156 }
157
158 void HYDROData_DTM::PointToWire(const AltitudePoints& pnts, TopoDS_Wire& W )
159 {
160   BRepLib_MakeWire WM;
161   if (pnts.empty())
162     return;
163   for (int i = 0; i < pnts.size() - 1; i++)
164   {
165     gp_Pnt p1(pnts[i].X, pnts[i].Y, pnts[i].Z);
166     gp_Pnt p2(pnts[i+1].X, pnts[i+1].Y, pnts[i+1].Z);    
167     WM.Add(BRepLib_MakeEdge(p1, p2).Edge()); 
168   }
169   if (WM.IsDone())
170     W = WM.Wire();
171 }
172
173 TopTools_IndexedMapOfOrientedShape HYDROData_DTM::Create3DShape(const AltitudePoints& left,
174                                                                 const AltitudePoints& right,
175                                                                 const std::vector<AltitudePoints>& main_profiles)
176 {  
177   TopTools_IndexedMapOfOrientedShape ll;
178   TopoDS_Wire LWire, RWire;
179   PointToWire(left, LWire);
180   PointToWire(right, RWire);
181   if (!LWire.IsNull())
182     ll.Add(LWire.Oriented(TopAbs_FORWARD));
183
184   for (int k = 0; k < main_profiles.size(); k++)
185   {
186     TopoDS_Wire W;
187     PointToWire(main_profiles[k], W);
188     TopAbs_Orientation Ori = TopAbs_INTERNAL;
189     if (k == 0 || k == main_profiles.size() - 1)
190       Ori = TopAbs_FORWARD;
191     ll.Add(W.Oriented(Ori));
192   }
193
194   if (!RWire.IsNull())
195     ll.Add(RWire.Oriented(TopAbs_FORWARD)); 
196   //yes, add subshapes in this order (left + profiles + right)
197   //otherwise the projected wire will be non-manifold
198
199   return ll;
200 }
201
202
203 void HYDROData_DTM::Update()
204 {
205   AltitudePoints points;
206   TopoDS_Shape Out3dPres;
207   TopoDS_Shape Out2dPres;
208   TopoDS_Shape OutLeftB;
209   TopoDS_Shape OutRightB;
210   TopoDS_Shape OutInlet;
211   TopoDS_Shape OutOutlet;
212
213   HYDROData_SequenceOfObjects objs = GetProfiles();  
214   double ddz = GetDDZ();
215   double step = GetSpatialStep();
216   std::set<int> InvInd;
217   CreateProfilesFromDTM( objs, ddz, step, points, Out3dPres, Out2dPres, OutLeftB, OutRightB, OutInlet, OutOutlet, true, true, InvInd, -1 );
218   SetAltitudePoints( points );  
219
220   SetShape( DataTag_LeftBankShape, OutLeftB);
221   SetShape( DataTag_RightBankShape, OutRightB);
222   SetShape( DataTag_InletShape, OutInlet);
223   SetShape( DataTag_OutletShape, OutOutlet );
224   SetShape( DataTag_3DShape, Out3dPres );
225   SetShape( DataTag_2DShape, Out2dPres );
226
227   HYDROData_Bathymetry::Update();
228 }
229
230 void HYDROData_DTM::GetPresentationShapes( TopoDS_Shape& Out3dPres,
231                                            TopoDS_Shape& Out2dPres,
232                                            TopoDS_Shape& OutLeftB,
233                                            TopoDS_Shape& OutRightB,
234                                            TopoDS_Shape& OutInlet,
235                                            TopoDS_Shape& OutOutlet )
236 {
237   //without update!
238   OutLeftB = GetShape( DataTag_LeftBankShape);
239   OutRightB = GetShape( DataTag_RightBankShape);
240   OutInlet = GetShape( DataTag_InletShape);
241   OutOutlet = GetShape( DataTag_OutletShape );
242   Out3dPres = GetShape( DataTag_3DShape );
243   Out2dPres = GetShape( DataTag_2DShape );
244 }
245
246 void HYDROData_DTM::CreateProfilesFromDTM (const HYDROData_SequenceOfObjects& InpProfiles,
247                                            double ddz,
248                                            double step, 
249                                            AltitudePoints& points,
250                                            TopoDS_Shape& Out3dPres,
251                                            TopoDS_Shape& Out2dPres,
252                                            TopoDS_Shape& OutLeftB,
253                                            TopoDS_Shape& OutRightB,
254                                            TopoDS_Shape& OutInlet,
255                                            TopoDS_Shape& OutOutlet,
256                                            bool Create3dPres,
257                                            bool Create2dPres,
258                                            std::set<int>& InvInd,
259                                            int thePntsLimit )
260 {
261   int aLower = InpProfiles.Lower(), anUpper = InpProfiles.Upper();
262   size_t n = anUpper - aLower + 1;
263
264   std::vector<Handle_HYDROData_Profile> profiles;
265   profiles.reserve( n ); 
266   for( int i=aLower; i<=anUpper; i++ )
267   {
268     Handle(HYDROData_Profile) aProfile = Handle(HYDROData_Profile)::DownCast( InpProfiles.Value( i ) );
269     if( !aProfile.IsNull() )
270       profiles.push_back( aProfile );
271   }
272   const double EPS = 1E-3;
273   AltitudePoints left;
274   AltitudePoints right;
275   std::vector<AltitudePoints> main_profiles;
276
277   if( thePntsLimit > 0 )
278   {
279     int aNbPoints = EstimateNbPoints( profiles, ddz, step );
280     if( aNbPoints < 0 || aNbPoints > thePntsLimit )
281       return;
282   }
283
284   if( ddz>EPS && step>EPS )
285     CreateProfiles(profiles, ddz, step, left, right, points, main_profiles, 
286     Out3dPres, Out2dPres, OutLeftB, OutRightB, OutInlet, OutOutlet, Create3dPres, Create2dPres, InvInd );
287 }
288
289 void HYDROData_DTM::ProjWireOnPlane(const TopoDS_Wire& inpWire, const Handle_Geom_Plane& RefPlane, TopoDS_Wire& outWire)
290 {
291   //its also possible to use BrepAlgo_NormalProjection here!
292   BRepTools_WireExplorer ex(TopoDS::Wire(inpWire.Oriented(TopAbs_FORWARD)));
293   BRepLib_MakeWire WM;
294   for (;ex.More();ex.Next())
295   {
296     const TopoDS_Edge& CE = ex.Current(); 
297     double f, l;
298     Handle(Geom_Curve) C3d = BRep_Tool::Curve(CE, f, l);
299     Handle(Geom_Curve) ProjectedCurve = GeomProjLib::ProjectOnPlane(new Geom_TrimmedCurve(C3d, f, l), RefPlane, RefPlane->Position().Direction(), Standard_True);
300     TopoDS_Edge ProjEdge = BRepLib_MakeEdge(ProjectedCurve);
301     WM.Add(ProjEdge); //auto sharing between edges if vertex is coincident
302   }
303   outWire = WM.Wire();
304   outWire.Orientation(inpWire.Orientation()); //take from the original wire
305 }
306
307
308 void HYDROData_DTM::Get2dFaceFrom3dPres(const TopoDS_Compound& cmp, TopoDS_Face& outF )
309 {
310   Handle_Geom_Plane refpl = new Geom_Plane(gp_Pnt(0,0,0), gp_Dir(0,0,1));
311   BRepLib_MakeWire WM;
312   TopoDS_Iterator it(cmp);
313   //TopTools_IndexedMapOfShape IntW;
314   for (;it.More(); it.Next())
315   {
316     const TopoDS_Wire& W = TopoDS::Wire(it.Value());
317     if (W.Orientation() != TopAbs_INTERNAL)
318     {
319       //use list of edges to protect againts non-manifold cases.
320       //auto sharing between edges will be added automatically
321       TopTools_IndexedMapOfShape ME;
322       TopTools_ListOfShape LE;
323       TopExp::MapShapes(W, TopAbs_EDGE, ME);
324       for (int i = 1; i <= ME.Extent(); i++)
325         LE.Append(ME(i));
326       WM.Add(LE);
327     }
328     //else
329     //  IntW.Add(W);
330   }
331
332   TopoDS_Wire outW;
333   ProjWireOnPlane(WM.Wire(), refpl, outW);
334   BRepBuilderAPI_MakeFace mf(refpl, outW); //check inside is true by def
335   outF = mf.Face();
336
337   ///!!! the internal wires cant be added with 'internal' ori.
338   // it's possible to do with brep builder yet the result will not be correct!
339   // more proper way is to use BOP operation here.
340   /*for (int i = 1; i <= IntW.Extent(); i++)
341   {
342   TopoDS_Wire outIW;
343   const TopoDS_Wire& W = TopoDS::Wire(IntW(i));
344   ProjWireOnPlane(W, refpl, outIW);
345   BB.Add(outF, outIW);
346   }*/
347 }
348
349 void HYDROData_DTM::CreateProfiles(const std::vector<Handle_HYDROData_Profile>& theProfiles,
350                                    double theDDZ,
351                                    double theSpatialStep,
352                                    AltitudePoints& theOutLeft,
353                                    AltitudePoints& theOutRight,
354                                    AltitudePoints& theOutPoints,
355                                    std::vector<AltitudePoints>& theOutMainProfiles,
356                                    TopoDS_Shape& Out3dPres,
357                                    TopoDS_Shape& Out2dPres,
358                                    TopoDS_Shape& OutLeftB,
359                                    TopoDS_Shape& OutRightB,
360                                    TopoDS_Shape& OutInlet,
361                                    TopoDS_Shape& OutOutlet,
362                                    bool Create3dPres,
363                                    bool Create2dPres,
364                                    std::set<int>& InvInd)
365 {
366   if (theProfiles.empty())
367     return;
368   theOutPoints = Interpolate( theProfiles, theDDZ, theSpatialStep, theOutLeft, theOutRight, theOutMainProfiles, InvInd );
369   //note that if Create3dPres is false => Create2dPres flag is meaningless!
370   if (Create3dPres)
371   {
372     TopTools_IndexedMapOfOrientedShape ll = Create3DShape( theOutLeft, theOutRight, theOutMainProfiles);
373     
374     if (ll.IsEmpty())
375       return;
376     BRep_Builder BB;
377     TopoDS_Compound cmp;
378     BB.MakeCompound(cmp);
379     for (int i = 1; i <= ll.Extent(); i++)
380       BB.Add(cmp, ll(i));
381
382     Out3dPres = cmp;
383
384     //same order as in HYDROData_DTM::Update()
385     OutLeftB = ll(1);
386     OutRightB = ll(ll.Extent());
387     OutInlet = ll(2);
388     OutOutlet = ll(ll.Extent() - 1);
389
390     if (Create2dPres)
391     {
392       TopoDS_Face outF;
393       Get2dFaceFrom3dPres(cmp, outF);
394       Out2dPres = outF;
395     };
396   }
397 }
398
399
400
401
402 void HYDROData_DTM::GetProperties( const Handle_HYDROData_Profile& theProfile,
403                     gp_Pnt& theLowestPoint, gp_Vec2d& theDir,
404                     bool isNormalDir,
405                     double& theZMin, double& theZMax )
406 {
407   theLowestPoint = theProfile->GetBottomPoint();
408   
409   gp_XY aLeft, aRight;
410   theProfile->GetLeftPoint( aLeft, true, true );
411   theProfile->GetRightPoint( aRight, true, true );
412   double x = aRight.X()-aLeft.X();
413   double y = aRight.Y()-aLeft.Y();
414   if( isNormalDir )
415     theDir = gp_Vec2d( -y, x );
416   else
417     theDir = gp_Vec2d( x, y );
418
419   HYDROData_Profile::ProfilePoints points = theProfile->GetProfilePoints();
420   int lo = points.Lower();
421   int up = points.Upper();
422   theZMin = std::numeric_limits<double>::max();
423   theZMax = -theZMin;
424   for( int i=lo; i<=up; i++ )
425   {
426     double z = points.Value( i ).Z();
427     if( z>theZMax )
428       theZMax = z;
429     if( z<theZMin )
430       theZMin = z;
431   }
432 }
433
434 inline gp_Pnt2d To2D( const gp_Pnt& thePnt, const gp_Trsf& theTr,
435                       double& theUMin, double& theUMax )
436 {
437   gp_Pnt p = thePnt.Transformed( theTr );
438   double u = p.X();
439   double z = p.Z();
440   if( u<theUMin )
441     theUMin = u;
442   if( u>theUMax )
443     theUMax = u;
444   return gp_Pnt2d( u, z );
445 }
446
447 Handle(TColgp_HArray1OfPnt2d) To2D( const TColgp_Array1OfPnt& thePoints,
448                                     const gp_Trsf& theTr,
449                                     double& theUMin, double& theUMax )
450 {
451   int low = thePoints.Lower(), up = thePoints.Upper();
452   Handle(TColgp_HArray1OfPnt2d) points = new TColgp_HArray1OfPnt2d( low, up );
453   for( int i=low; i<=up; i++ )
454     points->SetValue( i, To2D( thePoints.Value( i ), theTr, theUMin, theUMax ) );
455   return points;
456 }
457
458 Handle(Geom2d_Curve) CurveTo2D( const Handle(Geom_Curve)& theCurve, 
459                                 Standard_Real theFirst, Standard_Real theLast,
460                                 const gp_Trsf& theTr,
461                                 double& theUMin, double& theUMax )
462 {
463   if( theCurve->IsKind( STANDARD_TYPE( Geom_Line ) ) )
464   {
465     gp_Pnt aFirstPnt, aLastPnt;
466     theCurve->D0( theFirst, aFirstPnt );
467     theCurve->D0( theLast, aLastPnt );
468
469     gp_Pnt2d
470       aFirst2d = To2D( aFirstPnt, theTr, theUMin, theUMax ),
471       aLast2d = To2D( aLastPnt, theTr, theUMin, theUMax );
472
473     gp_Vec2d dir( aFirst2d, aLast2d );
474     Handle_Geom2d_Line aLine2d = new Geom2d_Line( aFirst2d, gp_Dir2d( dir.X(), dir.Y() ) );
475     return new Geom2d_TrimmedCurve( aLine2d, 0, aLast2d.Distance( aFirst2d ) );
476   }
477
478   if( theCurve->IsKind( STANDARD_TYPE( Geom_BSplineCurve ) ) )
479   {
480     Handle(Geom_BSplineCurve) aSpline = Handle(Geom_BSplineCurve)::DownCast( theCurve );
481
482     Handle(TColgp_HArray1OfPnt2d) poles = To2D( aSpline->Poles(), theTr, theUMin, theUMax );
483     const TColStd_Array1OfReal& knots = aSpline->Knots();
484     const TColStd_Array1OfInteger& multiplicities = aSpline->Multiplicities();
485     int aDegree = aSpline->Degree();
486
487     return new Geom2d_BSplineCurve( poles->Array1(), knots, multiplicities, aDegree );
488   }
489
490   return Handle(Geom2d_Curve)();
491 }
492
493 Handle_Geom2d_BSplineCurve HYDROData_DTM::CreateHydraulicAxis( 
494   const std::vector<Handle_HYDROData_Profile>& theProfiles,
495   std::vector<double>& theDistances )
496 {
497   size_t n = theProfiles.size();
498   Handle_Geom2d_BSplineCurve aResult;
499
500   Handle(TColgp_HArray1OfPnt2d) points = new TColgp_HArray1OfPnt2d( 1, (int)n );
501   TColgp_Array1OfVec2d tangents( 1, (int)n );
502   Handle(TColStd_HArray1OfBoolean) flags = new TColStd_HArray1OfBoolean( 1, (int)n );
503
504   for( size_t i = 1; i <= n; i++ )
505   {
506     Handle_HYDROData_Profile aProfile = theProfiles[i-1];
507     aProfile->Update();
508
509     gp_Pnt aLowest;
510     gp_Vec2d aTangent;
511     double zmin, zmax;
512     GetProperties( aProfile, aLowest, aTangent, true, zmin, zmax );
513     aTangent.Normalize();
514
515     points->SetValue( (int)i, gp_Pnt2d( aLowest.X(), aLowest.Y() ) );
516     tangents.SetValue( (int)i, aTangent );
517     flags->SetValue( (int)i, Standard_True );
518   }
519
520   Geom2dAPI_Interpolate anInterpolator( points, Standard_False, Standard_False );
521   anInterpolator.Load( tangents, flags );
522   anInterpolator.Perform();
523   if( anInterpolator.IsDone() )
524   {
525     aResult = anInterpolator.Curve();
526
527     //fill the distances vector
528     Geom2dAdaptor_Curve anAdaptor( aResult );
529
530     theDistances.clear();
531     theDistances.reserve( n );
532     Standard_Real aParamFirst = anAdaptor.FirstParameter(), aParamLast = anAdaptor.LastParameter();
533     for( size_t i = 1; i <= n; i++ )
534     {
535       gp_Pnt2d aPnt = points->Value( (Standard_Integer)i );
536       Geom2dAPI_ProjectPointOnCurve aProject( aPnt, aResult );
537       Standard_Real aParam = aProject.LowerDistanceParameter();
538       double aDistance = GCPnts_AbscissaPoint::Length( anAdaptor, aParamFirst, aParam );  
539       theDistances.push_back( aDistance );
540     }
541   }
542   return aResult;
543 }
544
545 std::vector<Handle_Geom2d_Curve> HYDROData_DTM::ProfileToParametric( 
546   const Handle_HYDROData_Profile& theProfile,
547   double& theUMin, double& theUMax, gp_Vec2d& theDir )
548 {
549   std::vector<Handle_Geom2d_Curve> curves;
550   
551   // Transformation of the coordinate systems
552   gp_Pnt aLowest;
553   double zmin, zmax;
554   GetProperties( theProfile, aLowest, theDir, false, zmin, zmax );
555
556   gp_Ax3 aStd3d( gp_Pnt( 0, 0, 0 ), gp_Dir( 0, 0, 1 ), gp_Dir( 1, 0, 0 ) );
557   gp_Ax3 aLocal( gp_Pnt( aLowest.X(), aLowest.Y(), 0 ), gp_Dir( 0, 0, 1 ), gp_Dir( theDir.X(), theDir.Y(), 0 ) );
558
559   gp_Trsf aTransf;
560   aTransf.SetTransformation( aStd3d, aLocal );
561
562   // Iteration via edges
563   TopoDS_Wire aWire = TopoDS::Wire( theProfile->GetShape3D() );
564   TopExp_Explorer anExp( aWire, TopAbs_EDGE );
565   for( ; anExp.More(); anExp.Next() )
566   {
567     // Extract an edge from wire
568     TopoDS_Edge anEdge = TopoDS::Edge( anExp.Current() );
569
570     // Extract a curve corresponding to the edge
571     TopLoc_Location aLoc;
572     Standard_Real aFirst, aLast;
573     Handle(Geom_Curve) aCurve = BRep_Tool::Curve( anEdge, aLoc, aFirst, aLast );
574
575     // Convert the curve to 2d CS
576     Handle(Geom2d_Curve) aCurve2d = CurveTo2D( aCurve, aFirst, aLast, aTransf, theUMin, theUMax );
577     if( !aCurve2d.IsNull() )
578       curves.push_back( aCurve2d );
579   }
580   return curves;
581 }
582
583
584 bool CalcMidWidth( const std::set<double>& intersections, double& theMid, double& theWid )
585 {
586   double umin = std::numeric_limits<double>::max(),
587          umax = -umin;
588
589   size_t n = intersections.size();
590   if( n <= 0 )
591     return false;
592
593   std::set<double>::const_iterator it = intersections.begin(), last = intersections.end();
594   for( ; it!=last; it++ )
595   {
596     double u = *it;
597     if( u<umin )
598       umin = u;
599     if( u>umax )
600       umax = u;
601   }
602   theMid = ( umin+umax )/2;
603   theWid = umax-umin;
604   return true;
605 }
606
607 void HYDROData_DTM::ProfileDiscretization( const Handle_HYDROData_Profile& theProfile, 
608                                            double theXCurv, double theMinZ, double theMaxZ, double theDDZ,
609                                            CurveUZ& theMidPointCurve,
610                                            CurveUZ& theWidthCurve,                                           
611                                            int& intersection_nb,
612                                            double theTolerance)
613 {
614   double aDblMax = std::numeric_limits<double>::max(),
615          aUMin = aDblMax,
616          aUMax = -aUMin,
617          aVMax = 1000000;
618   
619   gp_Vec2d aProfileDir;
620   std::vector<Handle_Geom2d_Curve> curves = ProfileToParametric( theProfile, aUMin, aUMax, aProfileDir );
621   size_t n = curves.size();
622
623   if( n==0 )
624     return;
625
626   // we add the "virtual" vertical lines to simulate the intersection with profile 
627   gp_Pnt2d aFirst, aLast;
628   curves[0]->D0( curves[0]->FirstParameter(), aFirst );
629   curves[n-1]->D0( curves[n-1]->LastParameter(), aLast );
630   Handle(Geom2d_Line) aV1 = new Geom2d_Line( aFirst, gp_Dir2d( 0, 1 ) );
631   Handle(Geom2d_TrimmedCurve) aT1 = new Geom2d_TrimmedCurve( aV1, 0.0, aVMax );
632   
633   Handle(Geom2d_Line) aV2 = new Geom2d_Line( aLast, gp_Dir2d( 0, 1 ) );
634   Handle(Geom2d_TrimmedCurve) aT2 = new Geom2d_TrimmedCurve( aV2, 0.0, aVMax );
635
636   curves.push_back( aT1 );
637   curves.push_back( aT2 );
638   
639   int psize = ( int )( ( theMaxZ-theMinZ ) / theDDZ + 1 );
640   theMidPointCurve = CurveUZ( theXCurv, aProfileDir, theMinZ );
641   theMidPointCurve.reserve( psize );
642   theWidthCurve = CurveUZ( theXCurv, aProfileDir, theMinZ );
643   theWidthCurve.reserve( psize );
644
645   n = curves.size();
646   // for each discrete value of z we search intersection with profile
647   for( double z1 = theMinZ; z1 <= theMaxZ; z1 += theDDZ )
648   {
649     Handle(Geom2d_Line) aLine = new Geom2d_Line( gp_Pnt2d( 0, z1 ), gp_Dir2d( 1, 0 ) );
650     std::set<double> intersections;
651     for( size_t i = 0; i < n; i++ )
652     {
653       Handle_Geom2d_Curve aCurve = curves[i];
654       Geom2dAPI_InterCurveCurve anIntersect( aCurve, aLine, theTolerance );
655       for( int k=1, m=anIntersect.NbPoints(); k<=m; k++ )
656         intersections.insert( anIntersect.Point( k ).X() );
657     }
658
659     intersection_nb = intersections.size();
660     if( intersection_nb >= 1 )
661     {
662       double u_mid, u_wid;
663       if( !CalcMidWidth( intersections, u_mid, u_wid ) )
664         continue;
665
666       double z = z1 - theMinZ;
667       PointUZ p_mid;
668       p_mid.U = u_mid;
669       p_mid.Z = z;
670       theMidPointCurve.push_back( p_mid );
671
672       PointUZ p_wid;
673       p_wid.U = u_wid;
674       p_wid.Z = z;
675       theWidthCurve.push_back( p_wid );
676     }
677   }
678 }
679
680 void HYDROData_DTM::Interpolate( const CurveUZ& theCurveA, const CurveUZ& theCurveB, 
681                                  int theNbSteps, std::vector<CurveUZ>& theInterpolation,
682                                  bool isAddSecond )
683 {
684   theInterpolation.clear();
685   int d = isAddSecond ? 2 : 1;
686   theInterpolation.reserve( theNbSteps+d );
687   double dt = 1.0 / double( theNbSteps + 1 );
688   double t = dt;
689   theInterpolation.push_back( theCurveA );
690   for( int i=0; i<theNbSteps; i++, t+=dt )
691   {
692     CurveUZ anInterp = theCurveA*(1-t) + theCurveB*t;
693     theInterpolation.push_back( anInterp );
694   }
695   if( isAddSecond )
696     theInterpolation.push_back( theCurveB );
697 }
698 #include <BRepLib_MakeEdge2d.hxx>
699 void HYDROData_DTM::CurveTo3D( const Handle_Geom2d_BSplineCurve& theHydraulicAxis,
700                                const CurveUZ& theMidCurve, const CurveUZ& theWidthCurve,
701                                AltitudePoints& thePoints )
702 {
703   Geom2dAdaptor_Curve anAdaptor( theHydraulicAxis );
704   TopoDS_Edge E2d = BRepLib_MakeEdge2d(theHydraulicAxis).Edge();
705   GCPnts_AbscissaPoint ap( anAdaptor, theMidCurve.Xcurv(), anAdaptor.FirstParameter() );  
706   double aParam = ap.Parameter();
707
708   gp_Pnt2d point;
709   anAdaptor.D0( aParam, point );
710   gp_Vec2d profile_dir = theMidCurve.ProfileDir();
711   //gp_Dir tangent_n( -profile_dir.Y(), profile_dir.X(), dz );
712   profile_dir.Normalize();
713   
714   size_t n = theMidCurve.size();
715   std::map<double, AltitudePoint> sorted_points;
716   for( size_t i=0; i<n; i++ )
717   {
718     double param1 = theMidCurve[i].U - theWidthCurve[i].U / 2;
719     double param2 = theMidCurve[i].U + theWidthCurve[i].U / 2;
720
721     gp_Pnt2d p1 = point.Translated( param1 * profile_dir);
722     gp_Pnt2d p2 = point.Translated( param2 * profile_dir);
723
724     double z = theMidCurve[i].Z + theMidCurve.DeltaZ();
725
726     AltitudePoint p3d_1( p1.X(), p1.Y(), z ), p3d_2( p2.X(), p2.Y(), z );
727
728     sorted_points[param1] = p3d_1;
729     sorted_points[param2] = p3d_2;
730   }
731
732   thePoints.reserve( sorted_points.size() );
733   std::map<double, AltitudePoint>::const_iterator it = sorted_points.begin(), last = sorted_points.end();
734   for( ; it!=last; it++ )
735     thePoints.push_back( it->second );
736 }
737
738 inline double max( double a, double b )
739 {
740   if( a>b )
741     return a;
742   else
743     return b;
744 }
745
746 inline double min( double a, double b )
747 {
748   if( a<b )
749     return a;
750   else
751     return b;
752 }
753
754 #include <BRepLib_MakeWire.hxx>
755
756 std::vector<HYDROData_Bathymetry::AltitudePoints> HYDROData_DTM::Interpolate
757   ( const Handle_Geom2d_BSplineCurve& theHydraulicAxis,
758     const Handle_HYDROData_Profile& theProfileA,
759     double theXCurvA,
760     const Handle_HYDROData_Profile& theProfileB,
761     double theXCurvB,
762     double theDDZ, int theNbSteps, bool isAddSecond,
763     int& inter_nb_1, int& inter_nb_2)
764 {
765   double zminA, zmaxA, zminB, zmaxB;
766   gp_Pnt lowestA, lowestB;
767   gp_Vec2d dirA, dirB;
768
769   GetProperties( theProfileA, lowestA, dirA, false, zminA, zmaxA ); 
770   GetProperties( theProfileB, lowestB, dirB, false, zminB, zmaxB ); 
771
772   
773   double hmax = max( zmaxA-zminA, zmaxB-zminB );
774
775   //double dz = zminB - zminA;
776   //double zmin = min( zminA, zminB );
777   //double zmax = max( zmaxA, zmaxB );
778
779   CurveUZ midA(0, gp_Vec2d(), 0), midB(0, gp_Vec2d(), 0);
780   CurveUZ widA(0, gp_Vec2d(), 0), widB(0, gp_Vec2d(), 0);
781
782   ProfileDiscretization( theProfileA, theXCurvA, zminA, zminA+hmax, theDDZ, midA, widA, inter_nb_1 ); 
783   ProfileDiscretization( theProfileB, theXCurvB, zminB, zminB+hmax, theDDZ, midB, widB, inter_nb_2 );
784
785   std::vector<CurveUZ> mid, wid;
786   Interpolate( midA, midB, theNbSteps, mid, isAddSecond );
787   Interpolate( widA, widB, theNbSteps, wid, isAddSecond );
788
789   size_t p = mid.size();
790   size_t q = p>0 ? 2*mid[0].size() : 1;
791   std::vector<AltitudePoints> points;
792   points.resize( p );
793
794   for( size_t i=0; i<p; i++ )
795   {
796     points[i].reserve( q );
797     CurveTo3D( theHydraulicAxis, mid[i], wid[i], points[i] );
798   }
799
800   return points;
801 }
802
803 HYDROData_Bathymetry::AltitudePoints HYDROData_DTM::Interpolate
804   ( const std::vector<Handle_HYDROData_Profile>& theProfiles,
805     double theDDZ, double theSpatialStep,
806     AltitudePoints& theLeft,
807     AltitudePoints& theRight,
808     std::vector<AltitudePoints>& theMainProfiles,
809     std::set<int>& invalInd)
810 {
811   AltitudePoints points;
812   size_t n = theProfiles.size();
813   if( n<=1 )
814     return points;
815
816   std::vector<double> distances;
817   Handle_Geom2d_BSplineCurve aHydraulicAxis = CreateHydraulicAxis( theProfiles, distances );
818   if( aHydraulicAxis.IsNull() )
819     return points;
820
821   theMainProfiles.reserve( n );
822
823   for( size_t i=0, n1=n-1; i<n1; i++ )
824   {
825     double aDistance = distances[i+1]-distances[i];
826     int aNbSteps = int(aDistance/theSpatialStep);
827     bool isAddSecond = i==n1-1;
828
829     // 1. Calculate interpolated profiles
830     int inter_nb_1, inter_nb_2;
831     std::vector<AltitudePoints> local_points = Interpolate( aHydraulicAxis, theProfiles[i], distances[i], 
832       theProfiles[i+1], distances[i+1], theDDZ, aNbSteps, isAddSecond, inter_nb_1, inter_nb_2 );
833     int lps = local_points.size();
834
835     if (inter_nb_1 > 2)
836       invalInd.insert(i);
837
838     if (inter_nb_2 > 2)
839       invalInd.insert(i+1);
840
841     // 2. Put all points into the global container
842     for( size_t j=0; j<lps; j++ )
843     {
844       const AltitudePoints& lp = local_points[j];
845       if( i==0 && j==0 )
846         points.reserve( lp.size() * n );
847       for( size_t k=0, ks=lp.size(); k<ks; k++ )
848         points.push_back( lp[k] );
849     }
850
851     // 3. Get left/right banks' points
852     if( i==0 )
853     {
854       theLeft.reserve( lps * n );
855       theRight.reserve( lps * n );
856     }
857     for( size_t j=0; j<lps; j++ )
858     {
859       const AltitudePoints& lp = local_points[j];
860       theLeft.push_back( lp[0] );
861       theRight.push_back( lp[lp.size()-1] );
862     }
863
864     // 4. Get main profiles points
865     theMainProfiles.push_back( local_points[0] );
866     if( isAddSecond )
867       theMainProfiles.push_back( local_points[lps-1] );
868   }
869   return points;
870 }
871
872 int HYDROData_DTM::EstimateNbPoints( const std::vector<Handle_HYDROData_Profile>& theProfiles,
873                                      double theDDZ, double theSpatialStep )
874 {
875   size_t n = theProfiles.size();
876   if( n<=1 )
877     return 0;
878   if( theDDZ<1E-6 || theSpatialStep<1E-6 )
879     return 1 << 20;
880
881   std::vector<double> distances;
882   Handle_Geom2d_BSplineCurve aHydraulicAxis = CreateHydraulicAxis( theProfiles, distances );
883   if( aHydraulicAxis.IsNull() )
884     return 0;
885
886   double aCompleteDistance = distances[n-1];
887   int aNbSteps = int( aCompleteDistance / theSpatialStep ) + 1;
888   gp_Pnt aLowest;
889   gp_Vec2d aDir;
890   double aZMin, aZMax;
891   GetProperties( theProfiles[0], aLowest, aDir, true, aZMin, aZMax );
892   int aNbZSteps = (aZMax-aZMin)/theDDZ;
893
894   if( aNbSteps > ( 1<<16 ) || aNbZSteps > ( 1<<16 ) )
895     return 1 << 20;
896
897   return aNbSteps * aNbZSteps;
898 }