]> SALOME platform Git repositories - modules/hydro.git/blob - src/HYDROData/HYDROData_DTM.cxx
Salome HOME
debug of 1 profile case
[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( theOutPoints.empty() )
499     return;
500
501   if (Create3dPres)
502   {
503     TopTools_IndexedMapOfOrientedShape ll = Create3DShape( theOutLeft, theOutRight, theOutMainProfiles);
504     
505     if (ll.IsEmpty())
506       return;
507     BRep_Builder BB;
508     TopoDS_Compound cmp;
509     BB.MakeCompound(cmp);
510     for (int i = 1; i <= ll.Extent(); i++)
511       BB.Add(cmp, ll(i));
512
513     Out3dPres = cmp;
514
515     //same order as in HYDROData_DTM::Update()
516     OutLeftB = ll(1);
517     OutRightB = ll(ll.Extent());
518     OutInlet = ll(2);
519     OutOutlet = ll(ll.Extent() - 1);
520
521     if (Create2dPres)
522     {
523       TopoDS_Face outF;
524       WireIntersections = Get2dFaceFrom3dPres(cmp, outF); //__TODO
525       Out2dPres = outF;
526     };
527   }
528 }
529
530
531
532
533 void HYDROData_DTM::GetProperties( const Handle_HYDROData_Profile& theProfile,
534                     gp_Pnt& theLowestPoint, gp_Vec2d& theDir,
535                     double& theZMin, double& theZMax )
536 {
537   theLowestPoint = theProfile->GetBottomPoint();
538   
539   gp_XY aLeft, aRight;
540   theProfile->GetLeftPoint( aLeft, true, true );
541   theProfile->GetRightPoint( aRight, true, true );
542   double x = aRight.X()-aLeft.X();
543   double y = aRight.Y()-aLeft.Y();
544   theDir = gp_Vec2d( x, y );
545
546   HYDROData_Profile::ProfilePoints points = theProfile->GetProfilePoints();
547   int lo = points.Lower();
548   int up = points.Upper();
549   theZMin = std::numeric_limits<double>::max();
550   theZMax = -theZMin;
551   for( int i=lo; i<=up; i++ )
552   {
553     double z = points.Value( i ).Z();
554     if( z>theZMax )
555       theZMax = z;
556     if( z<theZMin )
557       theZMin = z;
558   }
559 }
560
561 inline gp_Pnt2d To2D( const gp_Pnt& thePnt, const gp_Trsf& theTr,
562                       double& theUMin, double& theUMax )
563 {
564   gp_Pnt p = thePnt.Transformed( theTr );
565   double u = p.X();
566   double z = p.Z();
567   if( u<theUMin )
568     theUMin = u;
569   if( u>theUMax )
570     theUMax = u;
571   return gp_Pnt2d( u, z );
572 }
573
574 Handle(TColgp_HArray1OfPnt2d) To2D( const TColgp_Array1OfPnt& thePoints,
575                                     const gp_Trsf& theTr,
576                                     double& theUMin, double& theUMax )
577 {
578   int low = thePoints.Lower(), up = thePoints.Upper();
579   Handle(TColgp_HArray1OfPnt2d) points = new TColgp_HArray1OfPnt2d( low, up );
580   for( int i=low; i<=up; i++ )
581     points->SetValue( i, To2D( thePoints.Value( i ), theTr, theUMin, theUMax ) );
582   return points;
583 }
584
585 Handle(Geom2d_Curve) CurveTo2D( const Handle(Geom_Curve)& theCurve, 
586                                 Standard_Real theFirst, Standard_Real theLast,
587                                 const gp_Trsf& theTr,
588                                 double& theUMin, double& theUMax )
589 {
590   if( theCurve->IsKind( STANDARD_TYPE( Geom_Line ) ) )
591   {
592     gp_Pnt aFirstPnt, aLastPnt;
593     theCurve->D0( theFirst, aFirstPnt );
594     theCurve->D0( theLast, aLastPnt );
595
596     gp_Pnt2d
597       aFirst2d = To2D( aFirstPnt, theTr, theUMin, theUMax ),
598       aLast2d = To2D( aLastPnt, theTr, theUMin, theUMax );
599
600     gp_Vec2d dir( aFirst2d, aLast2d );
601     Handle_Geom2d_Line aLine2d = new Geom2d_Line( aFirst2d, gp_Dir2d( dir.X(), dir.Y() ) );
602     return new Geom2d_TrimmedCurve( aLine2d, 0, aLast2d.Distance( aFirst2d ) );
603   }
604
605   if( theCurve->IsKind( STANDARD_TYPE( Geom_BSplineCurve ) ) )
606   {
607     Handle(Geom_BSplineCurve) aSpline = Handle(Geom_BSplineCurve)::DownCast( theCurve );
608
609     Handle(TColgp_HArray1OfPnt2d) poles = To2D( aSpline->Poles(), theTr, theUMin, theUMax );
610     const TColStd_Array1OfReal& knots = aSpline->Knots();
611     const TColStd_Array1OfInteger& multiplicities = aSpline->Multiplicities();
612     int aDegree = aSpline->Degree();
613
614     return new Geom2d_BSplineCurve( poles->Array1(), knots, multiplicities, aDegree );
615   }
616
617   return Handle(Geom2d_Curve)();
618 }
619
620 #include <GCE2d_MakeSegment.hxx>
621 #include <Geom2dAPI_InterCurveCurve.hxx>
622 bool IsCooriented( const Handle_HYDROData_Profile& theProfile1,
623                    const Handle_HYDROData_Profile& theProfile2 ) 
624 {
625   if( theProfile1==theProfile2 )
626     return true;
627   
628   gp_XY lp1, rp1, lp2, rp2;
629   theProfile1->GetLeftPoint(lp1);
630   theProfile1->GetRightPoint(rp1);
631   theProfile2->GetLeftPoint(lp2);
632   theProfile2->GetRightPoint(rp2);
633
634   GCE2d_MakeSegment s1(lp1, lp2);
635   GCE2d_MakeSegment s2(rp1, rp2);
636
637   Geom2dAPI_InterCurveCurve inter;
638   inter.Init(s1, s2);
639   if (inter.NbPoints() == 0)
640     return true;
641   else
642     return false;
643 }
644
645 Handle_Geom2d_BSplineCurve HYDROData_DTM::CreateHydraulicAxis( 
646   const std::vector<Handle_HYDROData_Profile>& theProfiles,
647   std::vector<double>& theDistances )
648 {
649   size_t n = theProfiles.size();
650   if( n==1 )
651     return Handle_Geom2d_BSplineCurve();
652
653   Handle_Geom2d_BSplineCurve aResult;
654
655   Handle(TColgp_HArray1OfPnt2d) points = new TColgp_HArray1OfPnt2d( 1, (int)n );
656   TColgp_Array1OfVec2d tangents( 1, (int)n );
657   Handle(TColStd_HArray1OfBoolean) flags = new TColStd_HArray1OfBoolean( 1, (int)n );
658
659   for( size_t i = 1; i <= n; i++ )
660   {
661     Handle_HYDROData_Profile aProfile = theProfiles[i-1];
662     Handle_HYDROData_Profile aPrevProfile = i==1 ? theProfiles[i-1] : theProfiles[i-2];
663     Handle_HYDROData_Profile aNextProfile = i==n ? theProfiles[i-1] : theProfiles[i];
664
665     if( !IsCooriented( aProfile, aNextProfile ) )
666     {
667       gp_XY lp, rp;
668       aProfile->GetLeftPoint( lp, true );
669       aProfile->GetRightPoint( rp, true );
670       aProfile->SetLeftPoint( rp, true );
671       aProfile->SetRightPoint( lp, true );
672     }
673     aProfile->Update();
674
675     gp_Pnt aLowest;
676     gp_Vec2d aNormal;
677     double zmin, zmax;
678
679     gp_XYZ curP = aProfile->GetBottomPoint();
680     gp_XY curP2d = gp_XY(curP.X(), curP.Y());
681
682     gp_XYZ nextP;
683     if( i==n )
684       nextP = aPrevProfile->GetBottomPoint(true);
685     else
686       nextP = aNextProfile->GetBottomPoint(true);
687
688     gp_XY nextP2d = gp_XY(nextP.X(), nextP.Y());
689
690     gp_Vec2d aPrTangent;
691     GetProperties( aProfile, aLowest, aPrTangent, zmin, zmax );
692     aNormal.SetCoord( -aPrTangent.Y(), aPrTangent.X() );
693
694     gp_Vec2d aDirToNextProfile(nextP2d.X() - curP2d.X(), nextP2d.Y() - curP2d.Y() );
695     if( i==n )
696       aDirToNextProfile.Reverse();
697     if (aNormal.Dot(aDirToNextProfile) < 0)
698       aNormal.Reverse();
699
700     aNormal.Normalize();
701
702     points->SetValue( (int)i, gp_Pnt2d( aLowest.X(), aLowest.Y() ) );
703     tangents.SetValue( (int)i, aNormal );
704     flags->SetValue( (int)i, Standard_True );
705   }
706
707   Geom2dAPI_Interpolate anInterpolator( points, Standard_False, Standard_False );
708   anInterpolator.Load( tangents, flags );
709   anInterpolator.Perform();
710   if( anInterpolator.IsDone() )
711   {
712     aResult = anInterpolator.Curve();
713
714     //fill the distances vector
715     Geom2dAdaptor_Curve anAdaptor( aResult );
716
717     theDistances.clear();
718     theDistances.reserve( n );
719     Standard_Real aParamFirst = anAdaptor.FirstParameter(), aParamLast = anAdaptor.LastParameter();
720     for( size_t i = 1; i <= n; i++ )
721     {
722       gp_Pnt2d aPnt = points->Value( (Standard_Integer)i );
723       Geom2dAPI_ProjectPointOnCurve aProject( aPnt, aResult );
724       Standard_Real aParam = aProject.LowerDistanceParameter();
725       double aDistance = GCPnts_AbscissaPoint::Length( anAdaptor, aParamFirst, aParam );  
726       theDistances.push_back( aDistance );
727     }
728   }
729   return aResult;
730 }
731
732 std::vector<Handle_Geom2d_Curve> HYDROData_DTM::ProfileToParametric( 
733   const Handle_HYDROData_Profile& theProfile,
734   double& theUMin, double& theUMax, gp_Vec2d& theDir )
735 {
736   std::vector<Handle_Geom2d_Curve> curves;
737   
738   // Transformation of the coordinate systems
739   gp_Pnt aLowest;
740   double zmin, zmax;
741   GetProperties( theProfile, aLowest, theDir, zmin, zmax );
742
743   gp_Ax3 aStd3d( gp_Pnt( 0, 0, 0 ), gp_Dir( 0, 0, 1 ), gp_Dir( 1, 0, 0 ) );
744   gp_Ax3 aLocal( gp_Pnt( aLowest.X(), aLowest.Y(), 0 ), gp_Dir( 0, 0, 1 ), gp_Dir( theDir.X(), theDir.Y(), 0 ) );
745
746   gp_Trsf aTransf;
747   aTransf.SetTransformation( aStd3d, aLocal );
748
749   // Iteration via edges
750   TopoDS_Wire aWire = TopoDS::Wire( theProfile->GetShape3D() );
751   TopExp_Explorer anExp( aWire, TopAbs_EDGE );
752   for( ; anExp.More(); anExp.Next() )
753   {
754     // Extract an edge from wire
755     TopoDS_Edge anEdge = TopoDS::Edge( anExp.Current() );
756
757     // Extract a curve corresponding to the edge
758     TopLoc_Location aLoc;
759     Standard_Real aFirst, aLast;
760     Handle(Geom_Curve) aCurve = BRep_Tool::Curve( anEdge, aLoc, aFirst, aLast );
761
762     // Convert the curve to 2d CS
763     Handle(Geom2d_Curve) aCurve2d = CurveTo2D( aCurve, aFirst, aLast, aTransf, theUMin, theUMax );
764     if( !aCurve2d.IsNull() )
765       curves.push_back( aCurve2d );
766   }
767   return curves;
768 }
769
770
771 bool CalcMidWidth( const std::set<double>& intersections, double& theMid, double& theWid )
772 {
773   double umin = std::numeric_limits<double>::max(),
774          umax = -umin;
775
776   size_t n = intersections.size();
777   if( n <= 0 )
778     return false;
779
780   std::set<double>::const_iterator it = intersections.begin(), last = intersections.end();
781   for( ; it!=last; it++ )
782   {
783     double u = *it;
784     if( u<umin )
785       umin = u;
786     if( u>umax )
787       umax = u;
788   }
789   theMid = ( umin+umax )/2;
790   theWid = umax-umin;
791   return true;
792 }
793
794 void HYDROData_DTM::ProfileDiscretization( const Handle_HYDROData_Profile& theProfile, 
795                                            double theXCurv, double theMinZ, double theMaxZ, double theDDZ,
796                                            CurveUZ& theMidPointCurve,
797                                            CurveUZ& theWidthCurve,                                           
798                                            int& intersection_nb,
799                                            double theTolerance)
800 {
801   double aDblMax = std::numeric_limits<double>::max(),
802          aUMin = aDblMax,
803          aUMax = -aUMin,
804          aVMax = 1000000;
805   
806   gp_Vec2d aProfileDir;
807   std::vector<Handle_Geom2d_Curve> curves = ProfileToParametric( theProfile, aUMin, aUMax, aProfileDir );
808   size_t n = curves.size();
809
810   if( n==0 )
811     return;
812
813   // we add the "virtual" vertical lines to simulate the intersection with profile 
814   gp_Pnt2d aFirst, aLast;
815   curves[0]->D0( curves[0]->FirstParameter(), aFirst );
816   curves[n-1]->D0( curves[n-1]->LastParameter(), aLast );
817   Handle(Geom2d_Line) aV1 = new Geom2d_Line( aFirst, gp_Dir2d( 0, 1 ) );
818   Handle(Geom2d_TrimmedCurve) aT1 = new Geom2d_TrimmedCurve( aV1, 0.0, aVMax );
819   
820   Handle(Geom2d_Line) aV2 = new Geom2d_Line( aLast, gp_Dir2d( 0, 1 ) );
821   Handle(Geom2d_TrimmedCurve) aT2 = new Geom2d_TrimmedCurve( aV2, 0.0, aVMax );
822
823   curves.push_back( aT1 );
824   curves.push_back( aT2 );
825   
826   int psize = ( int )( ( theMaxZ-theMinZ ) / theDDZ + 1 );
827   theMidPointCurve = CurveUZ( theXCurv, aProfileDir, theMinZ );
828   theMidPointCurve.reserve( psize );
829   theWidthCurve = CurveUZ( theXCurv, aProfileDir, theMinZ );
830   theWidthCurve.reserve( psize );
831
832   n = curves.size();
833   // for each discrete value of z we search intersection with profile
834   for( double z1 = theMinZ; z1 <= theMaxZ; z1 += theDDZ )
835   {
836     Handle(Geom2d_Line) aLine = new Geom2d_Line( gp_Pnt2d( 0, z1 ), gp_Dir2d( 1, 0 ) );
837     std::set<double> intersections;
838     for( size_t i = 0; i < n; i++ )
839     {
840       Handle_Geom2d_Curve aCurve = curves[i];
841       Geom2dAPI_InterCurveCurve anIntersect( aCurve, aLine, theTolerance );
842       for( int k=1, m=anIntersect.NbPoints(); k<=m; k++ )
843         intersections.insert( anIntersect.Point( k ).X() );
844     }
845
846     intersection_nb = intersections.size();
847     if( intersection_nb >= 1 )
848     {
849       double u_mid, u_wid;
850       if( !CalcMidWidth( intersections, u_mid, u_wid ) )
851         continue;
852
853       double z = z1 - theMinZ;
854       PointUZ p_mid;
855       p_mid.U = u_mid;
856       p_mid.Z = z;
857       theMidPointCurve.push_back( p_mid );
858
859       PointUZ p_wid;
860       p_wid.U = u_wid;
861       p_wid.Z = z;
862       theWidthCurve.push_back( p_wid );
863     }
864   }
865 }
866
867 void HYDROData_DTM::Interpolate( const CurveUZ& theCurveA, const CurveUZ& theCurveB, 
868                                  int theNbSteps, std::vector<CurveUZ>& theInterpolation,
869                                  bool isAddSecond )
870 {
871   theInterpolation.clear();
872   int d = isAddSecond ? 2 : 1;
873   theInterpolation.reserve( theNbSteps+d );
874   double dt = 1.0 / double( theNbSteps + 1 );
875   double t = dt;
876   theInterpolation.push_back( theCurveA );
877   for( int i=0; i<theNbSteps; i++, t+=dt )
878   {
879     CurveUZ anInterp = theCurveA*(1-t) + theCurveB*t;
880     theInterpolation.push_back( anInterp );
881   }
882   if( isAddSecond )
883     theInterpolation.push_back( theCurveB );
884 }
885 #include <BRepLib_MakeEdge2d.hxx>
886 void HYDROData_DTM::CurveTo3D( const Handle_Geom2d_BSplineCurve& theHydraulicAxis,
887                                const CurveUZ& theMidCurve, const CurveUZ& theWidthCurve,
888                                AltitudePoints& thePoints )
889 {
890   Geom2dAdaptor_Curve anAdaptor( theHydraulicAxis );
891   TopoDS_Edge E2d = BRepLib_MakeEdge2d(theHydraulicAxis).Edge();
892   GCPnts_AbscissaPoint ap( anAdaptor, theMidCurve.Xcurv(), anAdaptor.FirstParameter() );  
893   double aParam = ap.Parameter();
894
895   gp_Pnt2d point;
896   anAdaptor.D0( aParam, point );
897   gp_Vec2d profile_dir = theMidCurve.ProfileDir();
898   //gp_Dir tangent_n( -profile_dir.Y(), profile_dir.X(), dz );
899   profile_dir.Normalize();
900   
901   size_t n = theMidCurve.size();
902   std::map<double, AltitudePoint> sorted_points;
903   for( size_t i=0; i<n; i++ )
904   {
905     double param1 = theMidCurve[i].U - theWidthCurve[i].U / 2;
906     double param2 = theMidCurve[i].U + theWidthCurve[i].U / 2;
907
908     gp_Pnt2d p1 = point.Translated( param1 * profile_dir);
909     gp_Pnt2d p2 = point.Translated( param2 * profile_dir);
910
911     double z = theMidCurve[i].Z + theMidCurve.DeltaZ();
912
913     AltitudePoint p3d_1( p1.X(), p1.Y(), z ), p3d_2( p2.X(), p2.Y(), z );
914
915     sorted_points[param1] = p3d_1;
916     sorted_points[param2] = p3d_2;
917   }
918
919   thePoints.reserve( sorted_points.size() );
920   const double EPS = 1E-12;
921   std::map<double, AltitudePoint>::const_iterator it = sorted_points.begin(), last = sorted_points.end();
922   for( ; it!=last; it++ )
923     if( thePoints.empty() || thePoints.back().SquareDistance( it->second ) > EPS )
924       thePoints.push_back( it->second );
925 }
926
927 inline double max( double a, double b )
928 {
929   if( a>b )
930     return a;
931   else
932     return b;
933 }
934
935 inline double min( double a, double b )
936 {
937   if( a<b )
938     return a;
939   else
940     return b;
941 }
942
943 #include <BRepLib_MakeWire.hxx>
944
945 std::vector<HYDROData_Bathymetry::AltitudePoints> HYDROData_DTM::Interpolate
946   ( const Handle_Geom2d_BSplineCurve& theHydraulicAxis,
947     const Handle_HYDROData_Profile& theProfileA,
948     double theXCurvA,
949     const Handle_HYDROData_Profile& theProfileB,
950     double theXCurvB,
951     double theDDZ, int theNbSteps, bool isAddSecond,
952     int& inter_nb_1, int& inter_nb_2)
953 {
954   double zminA, zmaxA, zminB, zmaxB;
955   gp_Pnt lowestA, lowestB;
956   gp_Vec2d dirA, dirB;
957
958   GetProperties( theProfileA, lowestA, dirA, zminA, zmaxA ); 
959   GetProperties( theProfileB, lowestB, dirB, zminB, zmaxB ); 
960
961   
962   double hmax = max( zmaxA-zminA, zmaxB-zminB );
963
964   //double dz = zminB - zminA;
965   //double zmin = min( zminA, zminB );
966   //double zmax = max( zmaxA, zmaxB );
967
968   CurveUZ midA(0, gp_Vec2d(), 0), midB(0, gp_Vec2d(), 0);
969   CurveUZ widA(0, gp_Vec2d(), 0), widB(0, gp_Vec2d(), 0);
970
971   ProfileDiscretization( theProfileA, theXCurvA, zminA, zminA+hmax, theDDZ, midA, widA, inter_nb_1 ); 
972   ProfileDiscretization( theProfileB, theXCurvB, zminB, zminB+hmax, theDDZ, midB, widB, inter_nb_2 );
973
974   std::vector<CurveUZ> mid, wid;
975   Interpolate( midA, midB, theNbSteps, mid, isAddSecond );
976   Interpolate( widA, widB, theNbSteps, wid, isAddSecond );
977
978   size_t p = mid.size();
979   size_t q = p>0 ? 2*mid[0].size() : 1;
980   std::vector<AltitudePoints> points;
981   points.resize( p );
982
983   for( size_t i=0; i<p; i++ )
984   {
985     points[i].reserve( q );
986     CurveTo3D( theHydraulicAxis, mid[i], wid[i], points[i] );
987   }
988
989   return points;
990 }
991
992 HYDROData_Bathymetry::AltitudePoints HYDROData_DTM::Interpolate
993   ( const std::vector<Handle_HYDROData_Profile>& theProfiles,
994     double theDDZ, double theSpatialStep,
995     AltitudePoints& theLeft,
996     AltitudePoints& theRight,
997     std::vector<AltitudePoints>& theMainProfiles,
998     std::set<int>& invalInd)
999 {
1000   AltitudePoints points;
1001   size_t n = theProfiles.size();
1002   if( n<=1 )
1003     return points;
1004
1005   std::vector<double> distances;
1006   Handle_Geom2d_BSplineCurve aHydraulicAxis = CreateHydraulicAxis( theProfiles, distances );
1007   if( aHydraulicAxis.IsNull() )
1008     return points;
1009
1010   theMainProfiles.reserve( n );
1011
1012   for( size_t i=0, n1=n-1; i<n1; i++ )
1013   {
1014     double aDistance = distances[i+1]-distances[i];
1015     int aNbSteps = int(aDistance/theSpatialStep);
1016     bool isAddSecond = i==n1-1;
1017
1018     // 1. Calculate interpolated profiles
1019     int inter_nb_1, inter_nb_2;
1020     std::vector<AltitudePoints> local_points = Interpolate( aHydraulicAxis, theProfiles[i], distances[i], 
1021       theProfiles[i+1], distances[i+1], theDDZ, aNbSteps, isAddSecond, inter_nb_1, inter_nb_2 );
1022     int lps = local_points.size();
1023
1024     if (inter_nb_1 > 2)
1025       invalInd.insert(i);
1026
1027     if (inter_nb_2 > 2)
1028       invalInd.insert(i+1);
1029
1030     // 2. Put all points into the global container
1031     for( size_t j=0; j<lps; j++ )
1032     {
1033       const AltitudePoints& lp = local_points[j];
1034       if( i==0 && j==0 )
1035         points.reserve( lp.size() * n );
1036       for( size_t k=0, ks=lp.size(); k<ks; k++ )
1037         points.push_back( lp[k] );
1038     }
1039
1040     // 3. Get left/right banks' points
1041     if( i==0 )
1042     {
1043       theLeft.reserve( lps * n );
1044       theRight.reserve( lps * n );
1045     }
1046     for( size_t j=0; j<lps; j++ )
1047     {
1048       const AltitudePoints& lp = local_points[j];
1049       theLeft.push_back( lp[0] );
1050       theRight.push_back( lp[lp.size()-1] );
1051     }
1052
1053     // 4. Get main profiles points
1054     theMainProfiles.push_back( local_points[0] );
1055     if( isAddSecond )
1056       theMainProfiles.push_back( local_points[lps-1] );
1057   }
1058   return points;
1059 }
1060
1061 int HYDROData_DTM::EstimateNbPoints( const std::vector<Handle_HYDROData_Profile>& theProfiles,
1062                                      double theDDZ, double theSpatialStep )
1063 {
1064   size_t n = theProfiles.size();
1065   if( n<=1 )
1066     return 0;
1067   if( theDDZ<1E-6 || theSpatialStep<1E-6 )
1068     return 1 << 20;
1069
1070   std::vector<double> distances;
1071   Handle_Geom2d_BSplineCurve aHydraulicAxis = CreateHydraulicAxis( theProfiles, distances );
1072   if( aHydraulicAxis.IsNull() )
1073     return 0;
1074
1075   double aCompleteDistance = distances[n-1];
1076   int aNbSteps = int( aCompleteDistance / theSpatialStep ) + 1;
1077   gp_Pnt aLowest;
1078   gp_Vec2d aDir;
1079   double aZMin, aZMax;
1080   GetProperties( theProfiles[0], aLowest, aDir, aZMin, aZMax );
1081   int aNbZSteps = (aZMax-aZMin)/theDDZ;
1082
1083   if( aNbSteps > ( 1<<16 ) || aNbZSteps > ( 1<<16 ) )
1084     return 1 << 20;
1085
1086   return aNbSteps * aNbZSteps;
1087 }