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