Salome HOME
Merge branch 'BR_HYDRO_IMPS_WIN' of ssh://gitolite3@git.salome-platform.org/modules...
[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 #include <BRepAlgo_NormalProjection.hxx>
51 #include <ShapeUpgrade_UnifySameDomain.hxx>
52 #include <BRepBuilderAPI_MakePolygon.hxx>
53 #include <BOPAlgo_Builder.hxx>
54
55 #include <TopTools_IndexedDataMapOfShapeShape.hxx>
56 #include <TopTools_ListIteratorOfListOfShape.hxx>
57 #include <TopTools_SequenceOfShape.hxx>
58
59 IMPLEMENT_STANDARD_HANDLE( HYDROData_DTM, HYDROData_Bathymetry )
60 IMPLEMENT_STANDARD_RTTIEXT( HYDROData_DTM, HYDROData_Bathymetry )
61
62 HYDROData_DTM::CurveUZ::CurveUZ( double theXCurv, const gp_Vec2d& theProfileDir, double theDeltaZ )
63   : myXcurv( theXCurv ), myProfileDir( theProfileDir ), myDeltaZ( theDeltaZ )
64 {
65 }
66
67 HYDROData_DTM::CurveUZ::~CurveUZ()
68 {
69 }
70
71 double HYDROData_DTM::CurveUZ::Xcurv() const
72 {
73   return myXcurv;
74 }
75
76 gp_Vec2d HYDROData_DTM::CurveUZ::ProfileDir() const
77 {
78   return myProfileDir;
79 }
80
81 double HYDROData_DTM::CurveUZ::DeltaZ() const
82 {
83   return myDeltaZ;
84 }
85
86 HYDROData_DTM::CurveUZ HYDROData_DTM::CurveUZ::operator + ( const CurveUZ& c ) const
87 {
88   HYDROData_DTM::CurveUZ res( Xcurv() + c.Xcurv(), ProfileDir() + c.ProfileDir(), DeltaZ() + c.DeltaZ() );
89   size_t n = size(), n1 = c.size();
90   if( n!=n1 )
91   {
92     std::cout << "Warning: different number of points in curves: " << n << ", " << n1 << std::endl;
93   }
94   res.reserve( n );
95   for( int i=0; i<n; i++ )
96   {
97     PointUZ p;
98     p.U = operator[]( i ).U + c[i].U;
99     p.Z = operator[]( i ).Z;
100     res.push_back( p );
101   }
102   return res;
103 }
104
105 HYDROData_DTM::CurveUZ HYDROData_DTM::CurveUZ::operator * ( double d ) const
106 {
107   HYDROData_DTM::CurveUZ res( Xcurv()*d, ProfileDir()*d, DeltaZ()*d );
108   size_t n = size();
109   res.reserve( n );
110   for( int i=0; i<n; i++ )
111   {
112     PointUZ p;
113     p.U = operator[]( i ).U * d;
114     p.Z = operator[]( i ).Z;
115     res.push_back( p );
116   }
117   return res;
118 }
119
120
121
122
123 HYDROData_DTM::HYDROData_DTM()
124 {
125 }
126
127 HYDROData_DTM::~HYDROData_DTM()
128 {
129 }
130
131 HYDROData_SequenceOfObjects HYDROData_DTM::GetProfiles() const
132 {
133   return GetReferenceObjects( DataTag_Profiles );
134 }
135
136 void HYDROData_DTM::SetProfiles( const HYDROData_SequenceOfObjects& theProfiles )
137 {
138   SetReferenceObjects( theProfiles, DataTag_Profiles );
139   Changed( Geom_3d );
140 }
141
142 double HYDROData_DTM::GetDDZ() const
143 {
144   return GetDouble( DataTag_DDZ );
145 }
146
147 void HYDROData_DTM::SetDDZ( double theDDZ )
148 {
149   SetDouble( DataTag_DDZ, theDDZ );
150   Changed( Geom_3d );
151 }
152
153 double HYDROData_DTM::GetSpatialStep() const
154 {
155   return GetDouble( DataTag_SpatialStep );
156 }
157
158 void HYDROData_DTM::SetSpatialStep( double theSpatialStep )
159 {
160   SetDouble( DataTag_SpatialStep, theSpatialStep );
161   Changed( Geom_3d );
162 }
163
164 void HYDROData_DTM::PointToWire(const AltitudePoints& pnts, TopoDS_Wire& W )
165 {
166   /*BRepLib_MakeWire WM;
167   if (pnts.empty())
168     return;
169   for (int i = 0; i < pnts.size() - 1; i++)
170   {
171     gp_Pnt p1(pnts[i].X, pnts[i].Y, pnts[i].Z);
172     gp_Pnt p2(pnts[i+1].X, pnts[i+1].Y, pnts[i+1].Z);    
173     WM.Add(BRepLib_MakeEdge(p1, p2).Edge()); 
174   }
175   if (WM.IsDone())*/
176   
177   BRepBuilderAPI_MakePolygon PM;
178   for (int i = 0; i < pnts.size(); i++)
179     PM.Add(gp_Pnt(pnts[i].X, pnts[i].Y, pnts[i].Z));
180   
181   W = PM.Wire();
182 }
183
184 TopTools_IndexedMapOfOrientedShape HYDROData_DTM::Create3DShape(const AltitudePoints& left,
185                                                                 const AltitudePoints& right,
186                                                                 const std::vector<AltitudePoints>& main_profiles)
187 {  
188   TopTools_IndexedMapOfOrientedShape ll;
189   TopoDS_Wire LWire, RWire;
190   PointToWire(left, LWire);
191   PointToWire(right, RWire);
192   if (!LWire.IsNull())
193     ll.Add(LWire.Oriented(TopAbs_FORWARD));
194
195   for (int k = 0; k < main_profiles.size(); k++)
196   {
197     TopoDS_Wire W;
198     PointToWire(main_profiles[k], W);
199     TopAbs_Orientation Ori = TopAbs_INTERNAL;
200     if (k == 0 || k == main_profiles.size() - 1)
201       Ori = TopAbs_FORWARD;
202     ll.Add(W.Oriented(Ori));
203   }
204
205   if (!RWire.IsNull())
206     ll.Add(RWire.Oriented(TopAbs_FORWARD)); 
207   //yes, add subshapes in this order (left + profiles + right)
208   //otherwise the projected wire will be non-manifold
209
210   return ll;
211 }
212
213
214 void HYDROData_DTM::Update()
215 {
216   AltitudePoints points;
217   TopoDS_Shape Out3dPres;
218   TopoDS_Shape Out2dPres;
219   TopoDS_Shape OutLeftB;
220   TopoDS_Shape OutRightB;
221   TopoDS_Shape OutInlet;
222   TopoDS_Shape OutOutlet;
223
224   HYDROData_SequenceOfObjects objs = GetProfiles();  
225   double ddz = GetDDZ();
226   double step = GetSpatialStep();
227   std::set<int> InvInd;
228   bool WireIntersections; //__TODO
229   CreateProfilesFromDTM( objs, ddz, step, points, Out3dPres, Out2dPres, OutLeftB, OutRightB, OutInlet, OutOutlet, true, true, InvInd, -1, WireIntersections );
230   SetAltitudePoints( points );  
231
232   SetShape( DataTag_LeftBankShape, OutLeftB);
233   SetShape( DataTag_RightBankShape, OutRightB);
234   SetShape( DataTag_InletShape, OutInlet);
235   SetShape( DataTag_OutletShape, OutOutlet );
236   SetShape( DataTag_3DShape, Out3dPres );
237   SetShape( DataTag_2DShape, Out2dPres );
238
239   HYDROData_Bathymetry::Update();
240 }
241
242 void HYDROData_DTM::GetPresentationShapes( TopoDS_Shape& Out3dPres,
243                                            TopoDS_Shape& Out2dPres,
244                                            TopoDS_Shape& OutLeftB,
245                                            TopoDS_Shape& OutRightB,
246                                            TopoDS_Shape& OutInlet,
247                                            TopoDS_Shape& OutOutlet )
248 {
249   //without update!
250   OutLeftB = GetShape( DataTag_LeftBankShape);
251   OutRightB = GetShape( DataTag_RightBankShape);
252   OutInlet = GetShape( DataTag_InletShape);
253   OutOutlet = GetShape( DataTag_OutletShape );
254   Out3dPres = GetShape( DataTag_3DShape );
255   Out2dPres = GetShape( DataTag_2DShape );
256 }
257 void HYDROData_DTM::CreateProfilesFromDTM (const HYDROData_SequenceOfObjects& InpProfiles,
258                                            double ddz,
259                                            double step, 
260                                            AltitudePoints& points,
261                                            TopoDS_Shape& Out3dPres,
262                                            TopoDS_Shape& Out2dPres,
263                                            TopoDS_Shape& OutLeftB,
264                                            TopoDS_Shape& OutRightB,
265                                            TopoDS_Shape& OutInlet,
266                                            TopoDS_Shape& OutOutlet,
267                                            bool Create3dPres,
268                                            bool Create2dPres,
269                                            std::set<int>& InvInd,
270                                            int thePntsLimit,
271                                            bool& WireIntersections)
272 {
273   int aLower = InpProfiles.Lower(), anUpper = InpProfiles.Upper();
274   size_t n = anUpper - aLower + 1;
275
276   std::vector<Handle_HYDROData_Profile> profiles;
277   profiles.reserve( n ); 
278   for( int i=aLower; i<=anUpper; i++ )
279   {
280     Handle(HYDROData_Profile) aProfile = Handle(HYDROData_Profile)::DownCast( InpProfiles.Value( i ) );
281     if( !aProfile.IsNull() )
282       profiles.push_back( aProfile );
283   }
284   const double EPS = 1E-3;
285   AltitudePoints left;
286   AltitudePoints right;
287   std::vector<AltitudePoints> main_profiles;
288
289   if( thePntsLimit > 0 )
290   {
291     int aNbPoints = EstimateNbPoints( profiles, ddz, step );
292     if( aNbPoints < 0 || aNbPoints > thePntsLimit )
293       return;
294   }
295
296   if( ddz>EPS && step>EPS )
297     CreateProfiles(profiles, ddz, step, left, right, points, main_profiles, 
298     Out3dPres, Out2dPres, OutLeftB, OutRightB, OutInlet, OutOutlet, Create3dPres, Create2dPres, InvInd, WireIntersections );
299 }
300
301 void HYDROData_DTM::ProjWireOnPlane(const TopoDS_Shape& inpWire, const Handle_Geom_Plane& RefPlane, 
302   TopTools_DataMapOfShapeListOfShape* E2PE)
303 {
304   BRep_Builder BB;
305
306   //project shape (edges) on planar face
307   TopoDS_Face F;
308   BB.MakeFace(F, RefPlane, Precision::Confusion());
309   BRepAlgo_NormalProjection nproj(F);
310   nproj.Add(inpWire);
311   nproj.SetDefaultParams();
312   nproj.Build();
313   if(!nproj.IsDone())
314     return;
315
316   TopoDS_Shape projRes = nproj.Projection();
317
318   // unite all vertexes/edges from projected result
319   BOPAlgo_Builder anAlgo;
320   TopExp_Explorer exp(projRes, TopAbs_EDGE);
321   for (;exp.More(); exp.Next())
322   {
323     const TopoDS_Edge& E = TopoDS::Edge(exp.Current());
324     if (E.Orientation() != TopAbs_INTERNAL)
325       anAlgo.AddArgument(E);
326   }
327   anAlgo.Perform(); 
328   int stat = anAlgo.ErrorStatus();
329   TopoDS_Shape projResConn = anAlgo.Shape();
330
331   // make wire => vertexes and edges should be untouched after this operation!
332   exp.Init(projResConn, TopAbs_EDGE);
333   //TopTools_ListOfShape llE;
334   //TopoDS_Wire RW;
335   //BRepLib_MakeWire WM;
336
337   //for (;exp.More();exp.Next()) 
338   //  llE.Append(exp.Current());
339   //
340   //WM.Add(llE);
341   //outWire = WM.Wire();
342
343   //outWire.Orientation(inpWire.Orientation()); //take from the original wire
344
345   //history mode: edge to projected edges
346   if (E2PE)
347   {
348     TopExp_Explorer ex(inpWire, TopAbs_EDGE);
349     for (;ex.More();ex.Next())
350     {
351       const TopoDS_Edge& CE = TopoDS::Edge(ex.Current());
352       TopTools_ListOfShape NEL;
353       const TopTools_ListOfShape& LS = nproj.Generated(CE);
354       TopTools_ListIteratorOfListOfShape it(LS);
355       for (;it.More();it.Next())
356       {
357         const TopoDS_Shape& PCE = it.Value();
358         TopTools_ListOfShape PLS = anAlgo.Modified(PCE);
359         if (PLS.IsEmpty())
360           PLS.Append(PCE);
361         TopTools_ListIteratorOfListOfShape itp(PLS);
362         for (;itp.More();itp.Next())
363           NEL.Append(itp.Value());
364       }
365
366       E2PE->Bind(CE, NEL);
367     }
368   }
369 }
370 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
371 bool HYDROData_DTM::Get2dFaceFrom3dPres(const TopoDS_Compound& cmp, TopoDS_Face& outF,
372   TopTools_SequenceOfShape* Boundr, std::set<int> ind )
373 {
374   //ind : set of indices (starts with 0). index == number of boundary (inlet, outlet, etc..)
375   //in compound cmp. 
376   //if Boundr is not null => this method will return sequence of boundary wires (inlet, outlet...)
377
378   Handle_Geom_Plane refpl = new Geom_Plane(gp_Pnt(0,0,0), gp_Dir(0,0,1));
379   TopTools_DataMapOfShapeListOfShape E2PE;
380   ProjWireOnPlane(cmp, refpl, &E2PE);
381   TopTools_ListOfShape ELL;
382
383   TopoDS_Iterator it(cmp);
384   int i = 0;
385   for (;it.More(); it.Next())
386   {
387     const TopoDS_Wire& W = TopoDS::Wire(it.Value());
388     if (W.Orientation() != TopAbs_INTERNAL)
389     {
390       TopoDS_Wire PW;
391       TopExp_Explorer ex(W, TopAbs_EDGE);   
392       TopTools_ListOfShape LEpW;
393       TopTools_ListOfShape LEpWDummy;
394       for (;ex.More();ex.Next())
395       {
396         const TopoDS_Edge& CE = TopoDS::Edge(ex.Current());
397         TopTools_ListOfShape LS = E2PE.Find(CE);
398         LEpW.Append(LS);
399       }
400       
401       if (ind.count(i) != 0)
402       {
403         BRepLib_MakeWire WM;
404         WM.Add(LEpW);
405         const TopoDS_Wire& WMW = WM.Wire();
406         //assume that wire is a straight line,
407         //take first and last vertex and make simple edge (RE)
408         TopoDS_Vertex VF, VL;
409         TopExp::Vertices(WMW, VF, VL);
410         TopoDS_Edge RE = BRepLib_MakeEdge(VF, VL).Edge();
411         if (RE.IsNull())
412         {
413           LEpWDummy = LEpW; //LEpW will be nullified after appending to ELL
414           ELL.Append(LEpW);
415         }
416         else
417         {
418           LEpWDummy.Append(RE); 
419           ELL.Append(RE);
420         }
421         //TODO: in the new version of OCCT, USD can process separate wires
422         //ShapeUpgrade_UnifySameDomain USD(WMW, 1U, 0U, 1U); //concat bsplines
423         //USD.Build();
424         //const TopoDS_Shape& RSU = USD.Shape();
425         //TopExp_Explorer exp(RSU, TopAbs_EDGE);
426         //TopTools_ListOfShape DummyL;
427         //for (;it.More();it.Next())
428         //  DummyL.Append(it.Value());
429         //if (DummyL.Extent() == 1)
430         //  ELL.Append(DummyL.First()); //if one edge => accept this result 
431         //else
432         //  ELL.Append(LEpW);  //else put 'as is'
433       }
434       else
435       {
436         LEpWDummy = LEpW;
437         ELL.Append(LEpW);
438       }
439
440       if (Boundr)
441       {
442         //make inlet, outlet, left/tight banks [wires]
443         //shouldn't change topology of the edges
444         BRepLib_MakeWire IWM;
445         IWM.Add(LEpWDummy);
446         Boundr->Append(IWM.Wire());
447       }
448     }
449     i++;
450   }
451
452   //make primary wire
453   BRepLib_MakeWire WME;
454   WME.Add(ELL);
455
456   const TopoDS_Wire& resW = WME.Wire();
457   BRepBuilderAPI_MakeFace mf(refpl, resW, true); //check inside is true by def
458   outF = mf.Face();
459
460   ShapeAnalysis_Wire WA(resW, outF, Precision::Confusion());
461   bool res = WA.CheckSelfIntersection(); //TODO check that this return false if OK
462   return res;
463
464   ///!!! the internal wires cant be added with 'internal' ori.
465   // it's possible to do with brep builder yet the result will not be correct!
466   // more proper way is to use BOP operation here.
467   /*for (int i = 1; i <= IntW.Extent(); i++)
468   {
469   TopoDS_Wire outIW;
470   const TopoDS_Wire& W = TopoDS::Wire(IntW(i));
471   ProjWireOnPlane(W, refpl, outIW);
472   BB.Add(outF, outIW);
473   }*/
474 }
475
476 void HYDROData_DTM::CreateProfiles(const std::vector<Handle_HYDROData_Profile>& theProfiles,
477                                    double theDDZ,
478                                    double theSpatialStep,
479                                    AltitudePoints& theOutLeft,
480                                    AltitudePoints& theOutRight,
481                                    AltitudePoints& theOutPoints,
482                                    std::vector<AltitudePoints>& theOutMainProfiles,
483                                    TopoDS_Shape& Out3dPres,
484                                    TopoDS_Shape& Out2dPres,
485                                    TopoDS_Shape& OutLeftB,
486                                    TopoDS_Shape& OutRightB,
487                                    TopoDS_Shape& OutInlet,
488                                    TopoDS_Shape& OutOutlet,
489                                    bool Create3dPres,
490                                    bool Create2dPres,
491                                    std::set<int>& InvInd,
492                                    bool& WireIntersections)
493 {
494   if (theProfiles.empty())
495     return;
496   theOutPoints = Interpolate( theProfiles, theDDZ, theSpatialStep, theOutLeft, theOutRight, theOutMainProfiles, InvInd );
497   //note that if Create3dPres is false => Create2dPres flag is meaningless!
498   if (Create3dPres)
499   {
500     TopTools_IndexedMapOfOrientedShape ll = Create3DShape( theOutLeft, theOutRight, theOutMainProfiles);
501     
502     if (ll.IsEmpty())
503       return;
504     BRep_Builder BB;
505     TopoDS_Compound cmp;
506     BB.MakeCompound(cmp);
507     for (int i = 1; i <= ll.Extent(); i++)
508       BB.Add(cmp, ll(i));
509
510     Out3dPres = cmp;
511
512     //same order as in HYDROData_DTM::Update()
513     OutLeftB = ll(1);
514     OutRightB = ll(ll.Extent());
515     OutInlet = ll(2);
516     OutOutlet = ll(ll.Extent() - 1);
517
518     if (Create2dPres)
519     {
520       TopoDS_Face outF;
521       WireIntersections = Get2dFaceFrom3dPres(cmp, outF); //__TODO
522       Out2dPres = outF;
523     };
524   }
525 }
526
527
528
529
530 void HYDROData_DTM::GetProperties( const Handle_HYDROData_Profile& theProfile,
531                     gp_Pnt& theLowestPoint, gp_Vec2d& theDir,
532                     double& theZMin, double& theZMax )
533 {
534   theLowestPoint = theProfile->GetBottomPoint();
535   
536   gp_XY aLeft, aRight;
537   theProfile->GetLeftPoint( aLeft, true, true );
538   theProfile->GetRightPoint( aRight, true, true );
539   double x = aRight.X()-aLeft.X();
540   double y = aRight.Y()-aLeft.Y();
541   theDir = gp_Vec2d( x, y );
542
543   HYDROData_Profile::ProfilePoints points = theProfile->GetProfilePoints();
544   int lo = points.Lower();
545   int up = points.Upper();
546   theZMin = std::numeric_limits<double>::max();
547   theZMax = -theZMin;
548   for( int i=lo; i<=up; i++ )
549   {
550     double z = points.Value( i ).Z();
551     if( z>theZMax )
552       theZMax = z;
553     if( z<theZMin )
554       theZMin = z;
555   }
556 }
557
558 inline gp_Pnt2d To2D( const gp_Pnt& thePnt, const gp_Trsf& theTr,
559                       double& theUMin, double& theUMax )
560 {
561   gp_Pnt p = thePnt.Transformed( theTr );
562   double u = p.X();
563   double z = p.Z();
564   if( u<theUMin )
565     theUMin = u;
566   if( u>theUMax )
567     theUMax = u;
568   return gp_Pnt2d( u, z );
569 }
570
571 Handle(TColgp_HArray1OfPnt2d) To2D( const TColgp_Array1OfPnt& thePoints,
572                                     const gp_Trsf& theTr,
573                                     double& theUMin, double& theUMax )
574 {
575   int low = thePoints.Lower(), up = thePoints.Upper();
576   Handle(TColgp_HArray1OfPnt2d) points = new TColgp_HArray1OfPnt2d( low, up );
577   for( int i=low; i<=up; i++ )
578     points->SetValue( i, To2D( thePoints.Value( i ), theTr, theUMin, theUMax ) );
579   return points;
580 }
581
582 Handle(Geom2d_Curve) CurveTo2D( const Handle(Geom_Curve)& theCurve, 
583                                 Standard_Real theFirst, Standard_Real theLast,
584                                 const gp_Trsf& theTr,
585                                 double& theUMin, double& theUMax )
586 {
587   if( theCurve->IsKind( STANDARD_TYPE( Geom_Line ) ) )
588   {
589     gp_Pnt aFirstPnt, aLastPnt;
590     theCurve->D0( theFirst, aFirstPnt );
591     theCurve->D0( theLast, aLastPnt );
592
593     gp_Pnt2d
594       aFirst2d = To2D( aFirstPnt, theTr, theUMin, theUMax ),
595       aLast2d = To2D( aLastPnt, theTr, theUMin, theUMax );
596
597     gp_Vec2d dir( aFirst2d, aLast2d );
598     Handle_Geom2d_Line aLine2d = new Geom2d_Line( aFirst2d, gp_Dir2d( dir.X(), dir.Y() ) );
599     return new Geom2d_TrimmedCurve( aLine2d, 0, aLast2d.Distance( aFirst2d ) );
600   }
601
602   if( theCurve->IsKind( STANDARD_TYPE( Geom_BSplineCurve ) ) )
603   {
604     Handle(Geom_BSplineCurve) aSpline = Handle(Geom_BSplineCurve)::DownCast( theCurve );
605
606     Handle(TColgp_HArray1OfPnt2d) poles = To2D( aSpline->Poles(), theTr, theUMin, theUMax );
607     const TColStd_Array1OfReal& knots = aSpline->Knots();
608     const TColStd_Array1OfInteger& multiplicities = aSpline->Multiplicities();
609     int aDegree = aSpline->Degree();
610
611     return new Geom2d_BSplineCurve( poles->Array1(), knots, multiplicities, aDegree );
612   }
613
614   return Handle(Geom2d_Curve)();
615 }
616
617 #include <GCE2d_MakeSegment.hxx>
618 #include <Geom2dAPI_InterCurveCurve.hxx>
619 bool IsCooriented( const Handle_HYDROData_Profile& theProfile1,
620                    const Handle_HYDROData_Profile& theProfile2 ) 
621 {
622   if( theProfile1==theProfile2 )
623     return true;
624   
625   gp_XY lp1, rp1, lp2, rp2;
626   theProfile1->GetLeftPoint(lp1);
627   theProfile1->GetRightPoint(rp1);
628   theProfile2->GetLeftPoint(lp2);
629   theProfile2->GetRightPoint(rp2);
630
631   GCE2d_MakeSegment s1(lp1, lp2);
632   GCE2d_MakeSegment s2(rp1, rp2);
633
634   Geom2dAPI_InterCurveCurve inter;
635   inter.Init(s1, s2);
636   if (inter.NbPoints() == 0)
637     return true;
638   else
639     return false;
640 }
641
642 Handle_Geom2d_BSplineCurve HYDROData_DTM::CreateHydraulicAxis( 
643   const std::vector<Handle_HYDROData_Profile>& theProfiles,
644   std::vector<double>& theDistances )
645 {
646   size_t n = theProfiles.size();
647   if( n==1 )
648     return Handle_Geom2d_BSplineCurve();
649
650   Handle_Geom2d_BSplineCurve aResult;
651
652   Handle(TColgp_HArray1OfPnt2d) points = new TColgp_HArray1OfPnt2d( 1, (int)n );
653   TColgp_Array1OfVec2d tangents( 1, (int)n );
654   Handle(TColStd_HArray1OfBoolean) flags = new TColStd_HArray1OfBoolean( 1, (int)n );
655
656   for( size_t i = 1; i <= n; i++ )
657   {
658     Handle_HYDROData_Profile aProfile = theProfiles[i-1];
659     Handle_HYDROData_Profile aPrevProfile = i==1 ? theProfiles[i-1] : theProfiles[i-2];
660     Handle_HYDROData_Profile aNextProfile = i==n ? theProfiles[i-1] : theProfiles[i];
661
662     if( !IsCooriented( aProfile, aNextProfile ) )
663     {
664       gp_XY lp, rp;
665       aProfile->GetLeftPoint( lp, true );
666       aProfile->GetRightPoint( rp, true );
667       aProfile->SetLeftPoint( rp, true );
668       aProfile->SetRightPoint( lp, true );
669     }
670     aProfile->Update();
671
672     gp_Pnt aLowest;
673     gp_Vec2d aNormal;
674     double zmin, zmax;
675
676     gp_XYZ curP = aProfile->GetBottomPoint();
677     gp_XY curP2d = gp_XY(curP.X(), curP.Y());
678
679     gp_XYZ nextP;
680     if( i==n )
681       nextP = aPrevProfile->GetBottomPoint(true);
682     else
683       nextP = aNextProfile->GetBottomPoint(true);
684
685     gp_XY nextP2d = gp_XY(nextP.X(), nextP.Y());
686
687     gp_Vec2d aPrTangent;
688     GetProperties( aProfile, aLowest, aPrTangent, zmin, zmax );
689     aNormal.SetCoord( -aPrTangent.Y(), aPrTangent.X() );
690
691     gp_Vec2d aDirToNextProfile(nextP2d.X() - curP2d.X(), nextP2d.Y() - curP2d.Y() );
692     if( i==n )
693       aDirToNextProfile.Reverse();
694     if (aNormal.Dot(aDirToNextProfile) < 0)
695       aNormal.Reverse();
696
697     aNormal.Normalize();
698
699     points->SetValue( (int)i, gp_Pnt2d( aLowest.X(), aLowest.Y() ) );
700     tangents.SetValue( (int)i, aNormal );
701     flags->SetValue( (int)i, Standard_True );
702   }
703
704   Geom2dAPI_Interpolate anInterpolator( points, Standard_False, Standard_False );
705   anInterpolator.Load( tangents, flags );
706   anInterpolator.Perform();
707   if( anInterpolator.IsDone() )
708   {
709     aResult = anInterpolator.Curve();
710
711     //fill the distances vector
712     Geom2dAdaptor_Curve anAdaptor( aResult );
713
714     theDistances.clear();
715     theDistances.reserve( n );
716     Standard_Real aParamFirst = anAdaptor.FirstParameter(), aParamLast = anAdaptor.LastParameter();
717     for( size_t i = 1; i <= n; i++ )
718     {
719       gp_Pnt2d aPnt = points->Value( (Standard_Integer)i );
720       Geom2dAPI_ProjectPointOnCurve aProject( aPnt, aResult );
721       Standard_Real aParam = aProject.LowerDistanceParameter();
722       double aDistance = GCPnts_AbscissaPoint::Length( anAdaptor, aParamFirst, aParam );  
723       theDistances.push_back( aDistance );
724     }
725   }
726   return aResult;
727 }
728
729 std::vector<Handle_Geom2d_Curve> HYDROData_DTM::ProfileToParametric( 
730   const Handle_HYDROData_Profile& theProfile,
731   double& theUMin, double& theUMax, gp_Vec2d& theDir )
732 {
733   std::vector<Handle_Geom2d_Curve> curves;
734   
735   // Transformation of the coordinate systems
736   gp_Pnt aLowest;
737   double zmin, zmax;
738   GetProperties( theProfile, aLowest, theDir, zmin, zmax );
739
740   gp_Ax3 aStd3d( gp_Pnt( 0, 0, 0 ), gp_Dir( 0, 0, 1 ), gp_Dir( 1, 0, 0 ) );
741   gp_Ax3 aLocal( gp_Pnt( aLowest.X(), aLowest.Y(), 0 ), gp_Dir( 0, 0, 1 ), gp_Dir( theDir.X(), theDir.Y(), 0 ) );
742
743   gp_Trsf aTransf;
744   aTransf.SetTransformation( aStd3d, aLocal );
745
746   // Iteration via edges
747   TopoDS_Wire aWire = TopoDS::Wire( theProfile->GetShape3D() );
748   TopExp_Explorer anExp( aWire, TopAbs_EDGE );
749   for( ; anExp.More(); anExp.Next() )
750   {
751     // Extract an edge from wire
752     TopoDS_Edge anEdge = TopoDS::Edge( anExp.Current() );
753
754     // Extract a curve corresponding to the edge
755     TopLoc_Location aLoc;
756     Standard_Real aFirst, aLast;
757     Handle(Geom_Curve) aCurve = BRep_Tool::Curve( anEdge, aLoc, aFirst, aLast );
758
759     // Convert the curve to 2d CS
760     Handle(Geom2d_Curve) aCurve2d = CurveTo2D( aCurve, aFirst, aLast, aTransf, theUMin, theUMax );
761     if( !aCurve2d.IsNull() )
762       curves.push_back( aCurve2d );
763   }
764   return curves;
765 }
766
767
768 bool CalcMidWidth( const std::set<double>& intersections, double& theMid, double& theWid )
769 {
770   double umin = std::numeric_limits<double>::max(),
771          umax = -umin;
772
773   size_t n = intersections.size();
774   if( n <= 0 )
775     return false;
776
777   std::set<double>::const_iterator it = intersections.begin(), last = intersections.end();
778   for( ; it!=last; it++ )
779   {
780     double u = *it;
781     if( u<umin )
782       umin = u;
783     if( u>umax )
784       umax = u;
785   }
786   theMid = ( umin+umax )/2;
787   theWid = umax-umin;
788   return true;
789 }
790
791 void HYDROData_DTM::ProfileDiscretization( const Handle_HYDROData_Profile& theProfile, 
792                                            double theXCurv, double theMinZ, double theMaxZ, double theDDZ,
793                                            CurveUZ& theMidPointCurve,
794                                            CurveUZ& theWidthCurve,                                           
795                                            int& intersection_nb,
796                                            double theTolerance)
797 {
798   double aDblMax = std::numeric_limits<double>::max(),
799          aUMin = aDblMax,
800          aUMax = -aUMin,
801          aVMax = 1000000;
802   
803   gp_Vec2d aProfileDir;
804   std::vector<Handle_Geom2d_Curve> curves = ProfileToParametric( theProfile, aUMin, aUMax, aProfileDir );
805   size_t n = curves.size();
806
807   if( n==0 )
808     return;
809
810   // we add the "virtual" vertical lines to simulate the intersection with profile 
811   gp_Pnt2d aFirst, aLast;
812   curves[0]->D0( curves[0]->FirstParameter(), aFirst );
813   curves[n-1]->D0( curves[n-1]->LastParameter(), aLast );
814   Handle(Geom2d_Line) aV1 = new Geom2d_Line( aFirst, gp_Dir2d( 0, 1 ) );
815   Handle(Geom2d_TrimmedCurve) aT1 = new Geom2d_TrimmedCurve( aV1, 0.0, aVMax );
816   
817   Handle(Geom2d_Line) aV2 = new Geom2d_Line( aLast, gp_Dir2d( 0, 1 ) );
818   Handle(Geom2d_TrimmedCurve) aT2 = new Geom2d_TrimmedCurve( aV2, 0.0, aVMax );
819
820   curves.push_back( aT1 );
821   curves.push_back( aT2 );
822   
823   int psize = ( int )( ( theMaxZ-theMinZ ) / theDDZ + 1 );
824   theMidPointCurve = CurveUZ( theXCurv, aProfileDir, theMinZ );
825   theMidPointCurve.reserve( psize );
826   theWidthCurve = CurveUZ( theXCurv, aProfileDir, theMinZ );
827   theWidthCurve.reserve( psize );
828
829   n = curves.size();
830   // for each discrete value of z we search intersection with profile
831   for( double z1 = theMinZ; z1 <= theMaxZ; z1 += theDDZ )
832   {
833     Handle(Geom2d_Line) aLine = new Geom2d_Line( gp_Pnt2d( 0, z1 ), gp_Dir2d( 1, 0 ) );
834     std::set<double> intersections;
835     for( size_t i = 0; i < n; i++ )
836     {
837       Handle_Geom2d_Curve aCurve = curves[i];
838       Geom2dAPI_InterCurveCurve anIntersect( aCurve, aLine, theTolerance );
839       for( int k=1, m=anIntersect.NbPoints(); k<=m; k++ )
840         intersections.insert( anIntersect.Point( k ).X() );
841     }
842
843     intersection_nb = intersections.size();
844     if( intersection_nb >= 1 )
845     {
846       double u_mid, u_wid;
847       if( !CalcMidWidth( intersections, u_mid, u_wid ) )
848         continue;
849
850       double z = z1 - theMinZ;
851       PointUZ p_mid;
852       p_mid.U = u_mid;
853       p_mid.Z = z;
854       theMidPointCurve.push_back( p_mid );
855
856       PointUZ p_wid;
857       p_wid.U = u_wid;
858       p_wid.Z = z;
859       theWidthCurve.push_back( p_wid );
860     }
861   }
862 }
863
864 void HYDROData_DTM::Interpolate( const CurveUZ& theCurveA, const CurveUZ& theCurveB, 
865                                  int theNbSteps, std::vector<CurveUZ>& theInterpolation,
866                                  bool isAddSecond )
867 {
868   theInterpolation.clear();
869   int d = isAddSecond ? 2 : 1;
870   theInterpolation.reserve( theNbSteps+d );
871   double dt = 1.0 / double( theNbSteps + 1 );
872   double t = dt;
873   theInterpolation.push_back( theCurveA );
874   for( int i=0; i<theNbSteps; i++, t+=dt )
875   {
876     CurveUZ anInterp = theCurveA*(1-t) + theCurveB*t;
877     theInterpolation.push_back( anInterp );
878   }
879   if( isAddSecond )
880     theInterpolation.push_back( theCurveB );
881 }
882 #include <BRepLib_MakeEdge2d.hxx>
883 void HYDROData_DTM::CurveTo3D( const Handle_Geom2d_BSplineCurve& theHydraulicAxis,
884                                const CurveUZ& theMidCurve, const CurveUZ& theWidthCurve,
885                                AltitudePoints& thePoints )
886 {
887   Geom2dAdaptor_Curve anAdaptor( theHydraulicAxis );
888   TopoDS_Edge E2d = BRepLib_MakeEdge2d(theHydraulicAxis).Edge();
889   GCPnts_AbscissaPoint ap( anAdaptor, theMidCurve.Xcurv(), anAdaptor.FirstParameter() );  
890   double aParam = ap.Parameter();
891
892   gp_Pnt2d point;
893   anAdaptor.D0( aParam, point );
894   gp_Vec2d profile_dir = theMidCurve.ProfileDir();
895   //gp_Dir tangent_n( -profile_dir.Y(), profile_dir.X(), dz );
896   profile_dir.Normalize();
897   
898   size_t n = theMidCurve.size();
899   std::map<double, AltitudePoint> sorted_points;
900   for( size_t i=0; i<n; i++ )
901   {
902     double param1 = theMidCurve[i].U - theWidthCurve[i].U / 2;
903     double param2 = theMidCurve[i].U + theWidthCurve[i].U / 2;
904
905     gp_Pnt2d p1 = point.Translated( param1 * profile_dir);
906     gp_Pnt2d p2 = point.Translated( param2 * profile_dir);
907
908     double z = theMidCurve[i].Z + theMidCurve.DeltaZ();
909
910     AltitudePoint p3d_1( p1.X(), p1.Y(), z ), p3d_2( p2.X(), p2.Y(), z );
911
912     sorted_points[param1] = p3d_1;
913     sorted_points[param2] = p3d_2;
914   }
915
916   thePoints.reserve( sorted_points.size() );
917   const double EPS = 1E-12;
918   std::map<double, AltitudePoint>::const_iterator it = sorted_points.begin(), last = sorted_points.end();
919   for( ; it!=last; it++ )
920     if( thePoints.empty() || thePoints.back().SquareDistance( it->second ) > EPS )
921       thePoints.push_back( it->second );
922 }
923
924 inline double max( double a, double b )
925 {
926   if( a>b )
927     return a;
928   else
929     return b;
930 }
931
932 inline double min( double a, double b )
933 {
934   if( a<b )
935     return a;
936   else
937     return b;
938 }
939
940 #include <BRepLib_MakeWire.hxx>
941
942 std::vector<HYDROData_Bathymetry::AltitudePoints> HYDROData_DTM::Interpolate
943   ( const Handle_Geom2d_BSplineCurve& theHydraulicAxis,
944     const Handle_HYDROData_Profile& theProfileA,
945     double theXCurvA,
946     const Handle_HYDROData_Profile& theProfileB,
947     double theXCurvB,
948     double theDDZ, int theNbSteps, bool isAddSecond,
949     int& inter_nb_1, int& inter_nb_2)
950 {
951   double zminA, zmaxA, zminB, zmaxB;
952   gp_Pnt lowestA, lowestB;
953   gp_Vec2d dirA, dirB;
954
955   GetProperties( theProfileA, lowestA, dirA, zminA, zmaxA ); 
956   GetProperties( theProfileB, lowestB, dirB, zminB, zmaxB ); 
957
958   
959   double hmax = max( zmaxA-zminA, zmaxB-zminB );
960
961   //double dz = zminB - zminA;
962   //double zmin = min( zminA, zminB );
963   //double zmax = max( zmaxA, zmaxB );
964
965   CurveUZ midA(0, gp_Vec2d(), 0), midB(0, gp_Vec2d(), 0);
966   CurveUZ widA(0, gp_Vec2d(), 0), widB(0, gp_Vec2d(), 0);
967
968   ProfileDiscretization( theProfileA, theXCurvA, zminA, zminA+hmax, theDDZ, midA, widA, inter_nb_1 ); 
969   ProfileDiscretization( theProfileB, theXCurvB, zminB, zminB+hmax, theDDZ, midB, widB, inter_nb_2 );
970
971   std::vector<CurveUZ> mid, wid;
972   Interpolate( midA, midB, theNbSteps, mid, isAddSecond );
973   Interpolate( widA, widB, theNbSteps, wid, isAddSecond );
974
975   size_t p = mid.size();
976   size_t q = p>0 ? 2*mid[0].size() : 1;
977   std::vector<AltitudePoints> points;
978   points.resize( p );
979
980   for( size_t i=0; i<p; i++ )
981   {
982     points[i].reserve( q );
983     CurveTo3D( theHydraulicAxis, mid[i], wid[i], points[i] );
984   }
985
986   return points;
987 }
988
989 HYDROData_Bathymetry::AltitudePoints HYDROData_DTM::Interpolate
990   ( const std::vector<Handle_HYDROData_Profile>& theProfiles,
991     double theDDZ, double theSpatialStep,
992     AltitudePoints& theLeft,
993     AltitudePoints& theRight,
994     std::vector<AltitudePoints>& theMainProfiles,
995     std::set<int>& invalInd)
996 {
997   AltitudePoints points;
998   size_t n = theProfiles.size();
999   if( n<=1 )
1000     return points;
1001
1002   std::vector<double> distances;
1003   Handle_Geom2d_BSplineCurve aHydraulicAxis = CreateHydraulicAxis( theProfiles, distances );
1004   if( aHydraulicAxis.IsNull() )
1005     return points;
1006
1007   theMainProfiles.reserve( n );
1008
1009   for( size_t i=0, n1=n-1; i<n1; i++ )
1010   {
1011     double aDistance = distances[i+1]-distances[i];
1012     int aNbSteps = int(aDistance/theSpatialStep);
1013     bool isAddSecond = i==n1-1;
1014
1015     // 1. Calculate interpolated profiles
1016     int inter_nb_1, inter_nb_2;
1017     std::vector<AltitudePoints> local_points = Interpolate( aHydraulicAxis, theProfiles[i], distances[i], 
1018       theProfiles[i+1], distances[i+1], theDDZ, aNbSteps, isAddSecond, inter_nb_1, inter_nb_2 );
1019     int lps = local_points.size();
1020
1021     if (inter_nb_1 > 2)
1022       invalInd.insert(i);
1023
1024     if (inter_nb_2 > 2)
1025       invalInd.insert(i+1);
1026
1027     // 2. Put all points into the global container
1028     for( size_t j=0; j<lps; j++ )
1029     {
1030       const AltitudePoints& lp = local_points[j];
1031       if( i==0 && j==0 )
1032         points.reserve( lp.size() * n );
1033       for( size_t k=0, ks=lp.size(); k<ks; k++ )
1034         points.push_back( lp[k] );
1035     }
1036
1037     // 3. Get left/right banks' points
1038     if( i==0 )
1039     {
1040       theLeft.reserve( lps * n );
1041       theRight.reserve( lps * n );
1042     }
1043     for( size_t j=0; j<lps; j++ )
1044     {
1045       const AltitudePoints& lp = local_points[j];
1046       theLeft.push_back( lp[0] );
1047       theRight.push_back( lp[lp.size()-1] );
1048     }
1049
1050     // 4. Get main profiles points
1051     theMainProfiles.push_back( local_points[0] );
1052     if( isAddSecond )
1053       theMainProfiles.push_back( local_points[lps-1] );
1054   }
1055   return points;
1056 }
1057
1058 int HYDROData_DTM::EstimateNbPoints( const std::vector<Handle_HYDROData_Profile>& theProfiles,
1059                                      double theDDZ, double theSpatialStep )
1060 {
1061   size_t n = theProfiles.size();
1062   if( n<=1 )
1063     return 0;
1064   if( theDDZ<1E-6 || theSpatialStep<1E-6 )
1065     return 1 << 20;
1066
1067   std::vector<double> distances;
1068   Handle_Geom2d_BSplineCurve aHydraulicAxis = CreateHydraulicAxis( theProfiles, distances );
1069   if( aHydraulicAxis.IsNull() )
1070     return 0;
1071
1072   double aCompleteDistance = distances[n-1];
1073   int aNbSteps = int( aCompleteDistance / theSpatialStep ) + 1;
1074   gp_Pnt aLowest;
1075   gp_Vec2d aDir;
1076   double aZMin, aZMax;
1077   GetProperties( theProfiles[0], aLowest, aDir, aZMin, aZMax );
1078   int aNbZSteps = (aZMax-aZMin)/theDDZ;
1079
1080   if( aNbSteps > ( 1<<16 ) || aNbZSteps > ( 1<<16 ) )
1081     return 1 << 20;
1082
1083   return aNbSteps * aNbZSteps;
1084 }