Salome HOME
update for automatic tests
[modules/hydro.git] / src / HYDROData / HYDROData_Bathymetry.cxx
1 // Copyright (C) 2014-2015  EDF-R&D
2 // This library is free software; you can redistribute it and/or
3 // modify it under the terms of the GNU Lesser General Public
4 // License as published by the Free Software Foundation; either
5 // version 2.1 of the License, or (at your option) any later version.
6 //
7 // This library is distributed in the hope that it will be useful,
8 // but WITHOUT ANY WARRANTY; without even the implied warranty of
9 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
10 // Lesser General Public License for more details.
11 //
12 // You should have received a copy of the GNU Lesser General Public
13 // License along with this library; if not, write to the Free Software
14 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
15 //
16 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
17 //
18
19 #include "HYDROData_Bathymetry.h"
20 #include "HYDROData_Document.h"
21 #include "HYDROData_Tool.h"
22 #include "HYDROData_PolylineXY.h"
23 #include "HYDROData_QuadtreeNode.hxx"
24
25 #include <gp_XY.hxx>
26 #include <gp_XYZ.hxx>
27
28 #include <TDataStd_RealArray.hxx>
29 #include <TDataStd_AsciiString.hxx>
30 #include <TDataStd_Integer.hxx>
31 #include <TDataStd_ExtStringArray.hxx>
32
33 #include <QColor>
34 #include <QFile>
35 #include <QFileInfo>
36 #include <QPointF>
37 #include <QPolygonF>
38 #include <QStringList>
39 #include <QString>
40
41 #ifndef LIGHT_MODE
42 #include <vtkPoints.h>
43 #include <vtkDelaunay2D.h>
44 #include <vtkPolyData.h>
45 #include <vtkSmartPointer.h>
46 #include <vtkIdList.h>
47 #endif
48
49 #include <iostream>
50
51 #include <math.h>
52
53 // #define _TIMER
54 #ifdef _TIMER
55 #include <OSD_Timer.hxx>
56 #endif
57
58 #define _DEVDEBUG_
59 #include "HYDRO_trace.hxx"
60
61 const int BLOCK_SIZE = 1000;
62
63 IMPLEMENT_STANDARD_HANDLE(HYDROData_Bathymetry, HYDROData_IAltitudeObject)
64 IMPLEMENT_STANDARD_RTTIEXT(HYDROData_Bathymetry, HYDROData_IAltitudeObject)
65
66 //HYDROData_QuadtreeNode* HYDROData_Bathymetry::myQuadtree = 0;
67
68 std::map<int, HYDROData_QuadtreeNode*> HYDROData_Bathymetry::myQuadtrees;
69
70 #ifndef LIGHT_MODE
71 std::map<int, vtkPolyData*> HYDROData_Bathymetry::myDelaunay2D;
72 #endif
73
74
75 HYDROData_Bathymetry::HYDROData_Bathymetry()
76 : HYDROData_IAltitudeObject()
77 {
78 }
79
80 HYDROData_Bathymetry::~HYDROData_Bathymetry()
81 {
82 }
83
84 QStringList HYDROData_Bathymetry::DumpToPython( const QString& thePyScriptPath,
85                                                 MapOfTreatedObjects& theTreatedObjects ) const
86 {
87   QStringList aResList = dumpObjectCreation( theTreatedObjects );
88   QString aBathymetryName = GetObjPyName();
89
90   aResList << QString( "%1.SetAltitudesInverted( %2 )" )
91               .arg( aBathymetryName ).arg( IsAltitudesInverted() );
92
93   TCollection_AsciiString aFilePath = GetFilePath();
94   aResList << QString( "if not(%1.ImportFromFile( \"%2\" )):" )
95               .arg( aBathymetryName ).arg( aFilePath.ToCString() );
96   aResList << QString( "  raise ValueError('problem while loading bathymetry')" );
97   aResList << QString( "" );
98   aResList << QString( "%1.Update()" ).arg( aBathymetryName );
99   aResList << QString( "" );
100
101   return aResList;
102 }
103
104 void HYDROData_Bathymetry::SetAltitudePoints( const HYDROData_Bathymetry::AltitudePoints& thePoints )
105 {
106   RemoveAltitudePoints();
107
108   if ( thePoints.empty() )
109     return;
110
111   // Save coordinates
112   Handle(TDataStd_RealArray) aCoordsArray = 
113     TDataStd_RealArray::Set( myLab.FindChild( DataTag_AltitudePoints ), 0, thePoints.size() * 3 - 1 );
114
115   HYDROData_Bathymetry::AltitudePoints::const_iterator anIter = thePoints.begin(), aLast = thePoints.end();
116   for ( int i = 0 ; anIter!=aLast; ++i, ++anIter )
117   {
118     const HYDROData_Bathymetry::AltitudePoint& aPoint = *anIter;
119
120     aCoordsArray->SetValue( i * 3, aPoint.X );
121     aCoordsArray->SetValue( i * 3 + 1, aPoint.Y );
122     aCoordsArray->SetValue( i * 3 + 2, aPoint.Z );
123   }
124
125   Changed( Geom_Z );
126 }
127
128 HYDROData_Bathymetry::AltitudePoints HYDROData_Bathymetry::GetAltitudePoints(bool IsConvertToGlobal) const
129 {
130   HYDROData_Bathymetry::AltitudePoints aPoints;
131
132   TDF_Label aLabel = myLab.FindChild( DataTag_AltitudePoints, false );
133   if ( aLabel.IsNull() )
134     return aPoints;
135
136   Handle(TDataStd_RealArray) aCoordsArray;
137   if ( !aLabel.FindAttribute( TDataStd_RealArray::GetID(), aCoordsArray ) )
138     return aPoints;
139
140   Handle(HYDROData_Document) aDoc = HYDROData_Document::Document( myLab );
141   int q = ( aCoordsArray->Upper() - aCoordsArray->Lower() + 1 ) / 3;
142   aPoints.reserve( q );
143   for ( int i = aCoordsArray->Lower(), n = aCoordsArray->Upper(); i <= n; )
144   {
145     if ( i + 3 > n + 1 )
146       break;
147
148     HYDROData_Bathymetry::AltitudePoint aPoint;
149     aPoint.X = aCoordsArray->Value( i++ );
150     aPoint.Y = aCoordsArray->Value( i++ );
151     aPoint.Z = aCoordsArray->Value( i++ );
152
153     if( IsConvertToGlobal )
154       aDoc->Transform( aPoint.X, aPoint.Y, aPoint.Z, false );
155     aPoints.push_back( aPoint );
156   }
157
158   return aPoints;
159 }
160
161 HYDROData_QuadtreeNode* HYDROData_Bathymetry::GetQuadtreeNodes() const
162 {
163   TDF_Label aLabel = myLab.FindChild(DataTag_AltitudePoints, false);
164   if (aLabel.IsNull())
165     return 0;
166   int labkey = myLab.Tag();
167   //int altkey = aLabel.Tag();
168   //DEBTRACE("GetQuadtreeNodes this labkey altkey "<<this<<" "<<labkey<<" "<<altkey);
169   // if (myQuadtree->isEmpty() )
170   if (myQuadtrees.find(labkey) == myQuadtrees.end())
171     {
172       //DEBTRACE("GetQuadtreeNodes init " << this << " " << labkey);
173       HYDROData_QuadtreeNode* aQuadtree = new HYDROData_QuadtreeNode(0, 30, 5, 0.);
174       myQuadtrees[labkey] = aQuadtree;
175       TDF_Label aLabel = myLab.FindChild(DataTag_AltitudePoints, false);
176       if (aLabel.IsNull())
177         return 0;
178
179       Handle(TDataStd_RealArray) aCoordsArray;
180       if (!aLabel.FindAttribute(TDataStd_RealArray::GetID(), aCoordsArray))
181         return 0;
182
183       Nodes_3D* aListOfNodes = new Nodes_3D();
184
185       int index =0;
186       for (int i = aCoordsArray->Lower(), n = aCoordsArray->Upper(); i <= n;)
187         {
188           if (i + 3 > n + 1)
189             break;
190
191           double x = aCoordsArray->Value(i++);
192           double y = aCoordsArray->Value(i++);
193           double z = aCoordsArray->Value(i++);
194           gpi_XYZ* aPoint = new gpi_XYZ(x, y, z, index);
195           index++;
196           aListOfNodes->push_back(aPoint);
197         }
198       //DEBTRACE("  GetQuadtreeNodes call setNodesAndCompute");
199       aQuadtree->setNodesAndCompute(aListOfNodes);
200       return aQuadtree;
201     }
202   else
203     return myQuadtrees[labkey];
204 }
205
206 #ifndef LIGHT_MODE
207 vtkPolyData* HYDROData_Bathymetry::GetVtkDelaunay2D() const
208 {
209   TDF_Label aLabel = myLab.FindChild(DataTag_AltitudePoints, false);
210   if (aLabel.IsNull())
211     return 0;
212   int labkey = myLab.Tag();
213   //int altkey = aLabel.Tag();
214   //DEBTRACE("GetVtkDelaunay2D this labkey altkey "<<this<<" "<<labkey<<" "<<altkey);
215   if (myDelaunay2D.find(labkey) == myDelaunay2D.end())
216     {
217       //DEBTRACE("GetVtkDelaunay2D init " << this << " " << labkey);
218
219       TDF_Label aLabel = myLab.FindChild(DataTag_AltitudePoints, false);
220       if (aLabel.IsNull())
221         return 0;
222       Handle(TDataStd_RealArray) aCoordsArray;
223       if (!aLabel.FindAttribute(TDataStd_RealArray::GetID(), aCoordsArray))
224         return 0;
225
226       vtkPoints *points = vtkPoints::New();
227       points->Allocate(aCoordsArray->Upper() +1);
228       for (int i = aCoordsArray->Lower(), n = aCoordsArray->Upper(); i <= n;)
229         {
230           if (i + 3 > n + 1)
231             break;
232           double x = aCoordsArray->Value(i++);
233           double y = aCoordsArray->Value(i++);
234           double z = aCoordsArray->Value(i++);
235           vtkIdType index = points->InsertNextPoint(x, y, z); // same index than in GetQuadtreeNodes
236           //DEBTRACE("  " << index);
237         }
238       vtkPolyData* profile = vtkPolyData::New();
239       profile->SetPoints(points);
240       //DEBTRACE("Number of Points: "<< points->GetNumberOfPoints());
241
242       vtkDelaunay2D* delaunay2D = vtkDelaunay2D::New();
243       delaunay2D->SetInputData(profile);
244       delaunay2D->Update();
245       vtkPolyData* data = delaunay2D->GetOutput();
246       data->BuildLinks();
247       myDelaunay2D[labkey] = data;
248       return data;
249     }
250   else
251     return myDelaunay2D[labkey];
252
253 }
254 #endif
255 void HYDROData_Bathymetry::RemoveAltitudePoints()
256 {
257   TDF_Label aLabel = myLab.FindChild( DataTag_AltitudePoints, false );
258   if ( !aLabel.IsNull() )
259   {
260     aLabel.ForgetAllAttributes();
261     Changed( Geom_Z );
262   }
263 }
264
265 void interpolateAltitudeForPoints( const gp_XY&                   thePoint,
266                                    const HYDROData_Bathymetry::AltitudePoint& theFirstPoint,
267                                    const HYDROData_Bathymetry::AltitudePoint& theSecPoint,
268                                    HYDROData_Bathymetry::AltitudePoint&       theResPoint,
269                                    const bool&                    theIsVertical )
270 {
271   double aCoordX = thePoint.X();
272   double aCoordY = thePoint.Y();
273
274   if ( theIsVertical )
275   {
276     aCoordX = theFirstPoint.X;
277
278     if ( !ValuesEquals( theFirstPoint.X, theSecPoint.X ) )
279     {
280       // Recalculate X coordinate by equation of line from two points
281       aCoordX = ( ( ( thePoint.Y() - theFirstPoint.Y ) * ( theSecPoint.X - theFirstPoint.X ) ) /
282                   ( theSecPoint.Y - theFirstPoint.Y ) ) + theFirstPoint.X;
283     }
284   }
285   else
286   {
287     aCoordY = theFirstPoint.Y;
288
289     if ( !ValuesEquals( theFirstPoint.Y, theSecPoint.Y ) )
290     {
291       // Recalculate y by equation of line from two points
292       aCoordY = ( ( ( thePoint.X() - theFirstPoint.X ) * ( theSecPoint.Y - theFirstPoint.Y ) ) /
293                   ( theSecPoint.X - theFirstPoint.X ) ) + theFirstPoint.Y;
294     }
295   }
296
297   theResPoint.X = aCoordX;
298   theResPoint.Y = aCoordY;
299
300   // Calculate coefficient for interpolation
301   double aLength = Sqrt( Pow( theSecPoint.Y - theFirstPoint.Y, 2 ) +
302                          Pow( theSecPoint.X - theFirstPoint.X, 2 ) );
303
304   double aInterCoeff = 0;
305   if ( aLength != 0 )
306    aInterCoeff = ( theSecPoint.Z - theFirstPoint.Z ) / aLength;
307
308
309   double aNewLength = Sqrt( Pow( theResPoint.Y - theFirstPoint.Y, 2 ) +
310                             Pow( theResPoint.X - theFirstPoint.X, 2 ) );
311
312   // Calculate interpolated value
313   double aResVal = theFirstPoint.Z + aInterCoeff * aNewLength;
314
315   theResPoint.Z = aResVal;
316 }
317 #ifndef LIGHT_MODE
318 bool interpolZtriangle(const gp_XY& point, vtkPolyData* delaunay2D, vtkIdList* triangle, double& z)
319 {
320
321   int nbPts = triangle->GetNumberOfIds();
322   if (nbPts != 3)
323     {
324       //DEBTRACE("not a triangle ?");
325       return false;
326     }
327   vtkIdType s[3];
328   double v[3][3]; // v[i][j] = j coordinate of node i
329   for (int i=0; i<3; i++)
330     {
331       s[i] = triangle->GetId(i);
332       delaunay2D->GetPoint(s[i],v[i]);
333     }
334   //DEBTRACE("triangle node id: " << s[0] << " " << s[1] << " " << s[2]);
335   //DEBTRACE("triangle node 0: " << v[0][0]  << " " << v[0][1] << " " << v[0][2]);
336   //DEBTRACE("triangle node 1: " << v[1][0]  << " " << v[1][1] << " " << v[1][2]);
337   //DEBTRACE("triangle node 2: " << v[2][0]  << " " << v[2][1] << " " << v[2][2]);
338
339   // compute barycentric coordinates (https://en.wikipedia.org/wiki/Barycentric_coordinate_system)
340   //     det = (y2-y3)(x1-x3)+(x3-x2)(y1-y3)
341   double det = (v[1][1]-v[2][1])*(v[0][0]-v[2][0]) + (v[2][0]-v[1][0])*(v[0][1]-v[2][1]);
342   if (det == 0)
343     {
344       //DEBTRACE("flat triangle ?");
345       return false;
346     }
347
348   //     l0  = ((y2-y3)(x -x3)+(x3-x2)(y -y3))/det
349   double l0  = (v[1][1]-v[2][1])*(point.X()-v[2][0]) + (v[2][0]-v[1][0])*(point.Y()-v[2][1]);
350   l0 = l0/det;
351
352   //     l1  = ((y3-y1)(x -x3)+(x1-x3)(y -y3))/det
353   double l1  = (v[2][1]-v[0][1])*(point.X()-v[2][0]) + (v[0][0]-v[2][0])*(point.Y()-v[2][1]);
354   l1 = l1/det;
355
356   double l2  = 1 -l0 -l1;
357   //DEBTRACE("l0, l1, l2: " << l0  << " "  << l1  << " "  << l2);
358
359   if ((l0>=0) && (l0<=1) && (l1>=0) && (l1<=1) && (l2>=0) && (l2<=1))
360     {
361       z = l0*v[0][2] + l1*v[1][2] + l2*v[2][2];
362       return true;
363     }
364   return false;
365 }
366 #endif
367
368 double HYDROData_Bathymetry::GetAltitudeForPoint(const gp_XY& thePoint, int theMethod) const
369 {
370   //DEBTRACE("GetAltitudeForPoint p(" << thePoint.X() << ", " << thePoint.Y() << "), interpolation method: " << theMethod);
371   double anInvalidAltitude = GetInvalidAltitude();
372   double aResAltitude = anInvalidAltitude;
373
374   // --- find the nearest point in the bathymetry cloud, with quadtree
375
376   HYDROData_QuadtreeNode* aQuadtree = GetQuadtreeNodes();
377   if (!aQuadtree)
378     {
379       //DEBTRACE("  no Quadtree");
380       return aResAltitude;
381     }
382
383   std::map<double, const gpi_XYZ*> dist2nodes;
384   aQuadtree->NodesAround(thePoint, dist2nodes, aQuadtree->getPrecision());
385   while (dist2nodes.size() == 0)
386     {
387       aQuadtree->setPrecision(aQuadtree->getPrecision() *2);
388       //DEBTRACE("adjust precision to: " << aQuadtree->getPrecision());
389       aQuadtree->NodesAround(thePoint, dist2nodes, aQuadtree->getPrecision());
390     }
391   std::map<double, const gpi_XYZ*>::const_iterator it = dist2nodes.begin();
392   aResAltitude = it->second->Z();
393   int nodeIndex = it->second->getIndex();
394   //DEBTRACE("  number of points found: " << dist2nodes.size() << " nearest z: " << aResAltitude << " point index: " << nodeIndex);
395
396   // --- for coarse bathymetry clouds (when the TELEMAC mesh is more refined than the bathymetry cloud)
397   //     interpolation is required.
398   //     - get a Delaunay2D mesh on the bathymetry cloud,
399   //     - get the triangle containing the point in the Delaunay2D mesh,
400   //     - interpolate altitude
401
402   bool isBathyInterpolRequired = false;
403   if (theMethod)
404     isBathyInterpolRequired =true;
405
406 #ifndef LIGHT_MODE
407   if (isBathyInterpolRequired)
408     {
409       vtkPolyData* aDelaunay2D = GetVtkDelaunay2D();
410       vtkIdList* cells= vtkIdList::New();
411       cells->Allocate(64);
412       vtkIdList* points= vtkIdList::New();
413       points->Allocate(64);
414       aDelaunay2D->GetPointCells(nodeIndex, cells);
415       vtkIdType nbCells = cells->GetNumberOfIds();
416       //DEBTRACE("  triangles on nearest point: " << nbCells);
417       bool isInside = false;
418       for (int i=0; i<nbCells; i++)
419         {
420           aDelaunay2D->GetCellPoints(cells->GetId(i), points);
421           double z = 0;
422           isInside = interpolZtriangle(thePoint, aDelaunay2D, points, z);
423           if (isInside)
424             {
425               aResAltitude = z;
426               //DEBTRACE("  interpolated z: " << z);
427               break;
428             }
429         }
430       if (!isInside)
431       {
432       //    DEBTRACE("  point outside triangles, nearest z kept");
433       }
434     }
435   #endif
436   return aResAltitude;
437 }
438
439 void HYDROData_Bathymetry::SetFilePath( const TCollection_AsciiString& theFilePath )
440 {
441   TDataStd_AsciiString::Set( myLab.FindChild( DataTag_FilePath ), theFilePath );
442 }
443
444 void HYDROData_Bathymetry::SetFilePaths( const QStringList& theFilePaths )
445 {
446   int i = 1;
447   Handle_TDataStd_ExtStringArray TExtStrArr = TDataStd_ExtStringArray::Set( myLab.FindChild( DataTag_FilePaths ), 1, theFilePaths.size() );
448   foreach (QString filepath, theFilePaths)
449   {
450     std::string sstr = filepath.toStdString();
451     const char* Val = sstr.c_str();
452     TExtStrArr->SetValue(i, TCollection_ExtendedString(Val));
453     i++;
454   }
455 }
456
457 TCollection_AsciiString HYDROData_Bathymetry::GetFilePath() const
458 {
459   TCollection_AsciiString aRes;
460
461   TDF_Label aLabel = myLab.FindChild( DataTag_FilePath, false );
462   if ( !aLabel.IsNull() )
463   {
464     Handle(TDataStd_AsciiString) anAsciiStr;
465     if ( aLabel.FindAttribute( TDataStd_AsciiString::GetID(), anAsciiStr ) )
466       aRes = anAsciiStr->Get();
467   }
468   else
469   {
470     aLabel = myLab.FindChild( DataTag_FilePaths, false );
471     if ( !aLabel.IsNull() )
472     {
473       Handle(TDataStd_ExtStringArray) anExtStrArr;
474       if ( aLabel.FindAttribute( TDataStd_ExtStringArray::GetID(), anExtStrArr ) )
475         aRes = anExtStrArr->Value(1); //try take the first; convert extstring to asciistring
476     }
477   }
478
479   return aRes;
480 }
481
482 QStringList HYDROData_Bathymetry::GetFilePaths() const
483 {
484   QStringList aResL;
485
486   TDF_Label aLabel = myLab.FindChild( DataTag_FilePaths, false );
487   if ( !aLabel.IsNull() )
488   {
489     Handle(TDataStd_ExtStringArray) anExtStrArr;
490     if ( aLabel.FindAttribute( TDataStd_ExtStringArray::GetID(), anExtStrArr ) )
491     {
492       for (int i = anExtStrArr->Lower(); i <= anExtStrArr->Upper(); i++ )
493       {
494         Standard_ExtString str = anExtStrArr->Value(i).ToExtString();
495         TCollection_AsciiString aText (str);
496         aResL << QString(aText.ToCString());
497       }
498     }
499   }
500   else //backward compatibility 
501   {
502     TDF_Label anOldLabel = myLab.FindChild( DataTag_FilePath, false );
503     if ( !anOldLabel.IsNull() )
504     {
505       Handle(TDataStd_AsciiString) anAsciiStr;
506       if ( anOldLabel.FindAttribute( TDataStd_AsciiString::GetID(), anAsciiStr ) )
507         aResL << QString(anAsciiStr->Get().ToCString());
508     }
509   }
510
511   return aResL;
512 }
513
514 void HYDROData_Bathymetry::SetAltitudesInverted( const bool theIsInverted,
515                                                  const bool theIsUpdate )
516 {
517   bool anIsAltitudesInverted = IsAltitudesInverted();
518   if ( anIsAltitudesInverted == theIsInverted )
519     return;
520
521   TDataStd_Integer::Set( myLab.FindChild( DataTag_AltitudesInverted ), (Standard_Integer)theIsInverted );
522
523   Changed( Geom_Z );
524
525   if ( !theIsUpdate )
526     return;
527
528   // Update altitude points
529   HYDROData_Bathymetry::AltitudePoints anAltitudePoints = GetAltitudePoints();
530   if ( anAltitudePoints.empty() )
531     return;
532
533   HYDROData_Bathymetry::AltitudePoints::iterator anIter = anAltitudePoints.begin(), aLast = anAltitudePoints.end();
534   for ( ; anIter!=aLast; ++anIter )
535   {
536     HYDROData_Bathymetry::AltitudePoint& aPoint = *anIter;
537     aPoint.Z *= -1;
538   }
539
540   SetAltitudePoints( anAltitudePoints );
541 }
542
543 bool HYDROData_Bathymetry::IsAltitudesInverted() const
544 {
545   bool aRes = false;
546
547   TDF_Label aLabel = myLab.FindChild( DataTag_AltitudesInverted, false );
548   if ( !aLabel.IsNull() )
549   {
550     Handle(TDataStd_Integer) anIntVal;
551     if ( aLabel.FindAttribute( TDataStd_Integer::GetID(), anIntVal ) )
552       aRes = (bool)anIntVal->Get();
553   }
554
555   return aRes;
556 }
557
558 bool HYDROData_Bathymetry::ImportFromFile( const QString& theFileName )
559 {
560   return ImportFromFiles(QStringList(theFileName));
561 }
562
563 bool HYDROData_Bathymetry::ImportFromFiles( const QStringList& theFileNames )
564 {
565   AltitudePoints AllPoints;
566   bool Stat = false;
567
568   foreach (QString theFileName, theFileNames)
569   {
570     // Try to open the file
571     QFile aFile( theFileName );
572     if ( !aFile.exists() || !aFile.open( QIODevice::ReadOnly ) )
573       continue;
574
575     QString aFileSuf = QFileInfo( aFile ).suffix().toLower();
576
577     HYDROData_Bathymetry::AltitudePoints aPoints;
578
579     // Try to import the file
580     if ( aFileSuf == "xyz" )
581       Stat = importFromXYZFile( aFile, aPoints );
582     else if ( aFileSuf == "asc" )
583       Stat = importFromASCFile( aFile, aPoints );
584
585     if (!Stat)
586       continue; //ignore this points
587
588     // Close the file
589     aFile.close();
590
591     AllPoints.insert(AllPoints.end(), aPoints.begin(), aPoints.end());
592   }
593
594   // Convert from global to local CS
595   Handle_HYDROData_Document aDoc = HYDROData_Document::Document( myLab );
596   HYDROData_Bathymetry::AltitudePoints::iterator anIter = AllPoints.begin(), aLast = AllPoints.end();
597   for ( ; anIter!=aLast; ++anIter )
598   {
599     HYDROData_Bathymetry::AltitudePoint& aPoint = *anIter;
600     aDoc->Transform( aPoint.X, aPoint.Y, aPoint.Z, true );
601   }
602
603   if ( Stat )
604   {
605     // Update file path and altitude points of this Bathymetry
606     SetFilePaths (theFileNames );
607     SetAltitudePoints( AllPoints );
608   }
609
610   return Stat && !AllPoints.empty();
611 }
612
613 bool HYDROData_Bathymetry::importFromXYZFile( QFile&          theFile,
614                                               HYDROData_Bathymetry::AltitudePoints& thePoints ) const
615 {
616   if ( !theFile.isOpen() )
617     return false;
618
619   // Strings in file is written as:
620   //  1. X(float) Y(float) Z(float)
621   //  2. X(float) Y(float) Z(float)
622   //  ...
623
624 #ifdef _TIMER
625   OSD_Timer aTimer;
626   aTimer.Start();
627 #endif
628
629   bool anIsAltitudesInverted = IsAltitudesInverted();
630   while ( !theFile.atEnd() )
631   {
632     QString aLine = theFile.readLine().simplified();
633     if ( aLine.isEmpty() )
634       continue;
635
636     QStringList aValues = aLine.split( ' ', QString::SkipEmptyParts );
637     if ( aValues.length() < 3 )
638       return false;
639
640     HYDROData_Bathymetry::AltitudePoint aPoint;
641     
642     QString anX = aValues.value( 0 );
643     QString anY = aValues.value( 1 );
644     QString aZ  = aValues.value( 2 );
645
646     bool isXOk = false, isYOk = false, isZOk = false;
647
648     aPoint.X = anX.toDouble( &isXOk );
649     aPoint.Y = anY.toDouble( &isYOk );
650     aPoint.Z = aZ.toDouble( &isZOk );
651
652     if ( !isXOk || !isYOk || !isZOk )
653       return false;
654
655     if ( HYDROData_Tool::IsNan( aPoint.X ) || HYDROData_Tool::IsInf( aPoint.X ) ||
656          HYDROData_Tool::IsNan( aPoint.Y ) || HYDROData_Tool::IsInf( aPoint.Y ) ||
657          HYDROData_Tool::IsNan( aPoint.Z ) || HYDROData_Tool::IsInf( aPoint.Z ) )
658       return false;
659
660     // Invert the z value if requested
661     if ( anIsAltitudesInverted )
662       aPoint.Z = -aPoint.Z;
663
664     if( thePoints.size()>=thePoints.capacity() )
665       thePoints.reserve( thePoints.size()+BLOCK_SIZE );
666
667     thePoints.push_back( aPoint );
668   }
669
670 #ifdef _TIMER
671   aTimer.Stop();
672   std::ofstream stream( "W:/HYDRO/WORK/log.txt", std::ofstream::out );
673   aTimer.Show( stream );
674 #endif
675
676   return true;
677 }
678
679 bool HYDROData_Bathymetry::importFromASCFile( QFile&          theFile,
680                                               HYDROData_Bathymetry::AltitudePoints& thePoints ) const
681 {
682   if ( !theFile.isOpen() )
683     return false;
684
685   QString aLine;
686   QStringList aStrList;
687
688   int aNCols;
689   int aNRows;
690   double anXllCorner; 
691   double anYllCorner; 
692   double aCellSize; 
693   double aNoDataValue;
694
695   aLine = theFile.readLine().simplified();
696   aStrList = aLine.split( ' ', QString::SkipEmptyParts );
697   if ( aStrList.length() != 2 && aStrList[0].toLower() != "ncols" )
698     return false;
699   aNCols = aStrList[1].toInt();
700
701   aLine = theFile.readLine().simplified();
702   aStrList = aLine.split( ' ', QString::SkipEmptyParts );
703   if ( aStrList.length() != 2 && aStrList[0].toLower() != "nrows" )
704     return false;
705   aNRows = aStrList[1].toInt();
706
707   aLine = theFile.readLine().simplified();
708   aStrList = aLine.split( ' ', QString::SkipEmptyParts );
709   if ( aStrList.length() != 2 && aStrList[0].toLower() != "xllcorner" )
710     return false;
711   anXllCorner = aStrList[1].toDouble();
712
713   aLine = theFile.readLine().simplified();
714   aStrList = aLine.split( ' ', QString::SkipEmptyParts );
715   if ( aStrList.length() != 2 && aStrList[0].toLower() != "yllcorner" )
716     return false;
717   anYllCorner = aStrList[1].toDouble();
718
719   aLine = theFile.readLine().simplified();
720   aStrList = aLine.split( ' ', QString::SkipEmptyParts );
721   if ( aStrList.length() != 2 && aStrList[0].toLower() != "cellsize" )
722     return false;
723   aCellSize = aStrList[1].toDouble();
724
725   aLine = theFile.readLine().simplified();
726   aStrList = aLine.split( ' ', QString::SkipEmptyParts );
727   if ( aStrList.length() != 2 && aStrList[0].toLower() != "nodata_value" )
728     return false;
729   aNoDataValue = aStrList[1].toDouble();
730
731   bool anIsAltitudesInverted = IsAltitudesInverted();
732
733   int i = 0;
734   int aStrLength = 0;
735   while ( !theFile.atEnd() )
736   {
737     aLine = theFile.readLine().simplified();
738     aStrList = aLine.split( ' ', QString::SkipEmptyParts );
739
740     aStrLength =  aStrList.length();
741     if ( aStrLength == 0 )
742       continue;
743
744     if ( aStrLength != aNRows )
745       return false;
746
747     for (int j = 0; j < aNCols; j++)
748     {
749       if (aStrList[j].toDouble() != aNoDataValue)
750       {
751         HYDROData_Bathymetry::AltitudePoint aPoint;
752         aPoint.X = anXllCorner + aCellSize*(j + 0.5);
753         aPoint.Y = anYllCorner + aCellSize*(aNRows - i + 0.5);
754         aPoint.Z = aStrList[j].toDouble();
755
756         if ( anIsAltitudesInverted )
757          aPoint.Z = -aPoint.Z;
758
759         if( thePoints.size()>=thePoints.capacity() )
760           thePoints.reserve( thePoints.size()+BLOCK_SIZE );
761         thePoints.push_back(aPoint);
762       }
763     }
764     i++;
765   }
766
767   return true;
768 }
769
770
771 Handle_HYDROData_PolylineXY HYDROData_Bathymetry::CreateBoundaryPolyline() const
772 {
773   Handle(HYDROData_Document) aDocument = HYDROData_Document::Document( myLab );
774   Handle_HYDROData_PolylineXY aResult = 
775     Handle_HYDROData_PolylineXY::DownCast( aDocument->CreateObject( KIND_POLYLINEXY ) );
776
777   if( aResult.IsNull() )
778     return aResult;
779
780   //search free name
781   QString aPolylinePref = GetName() + "_Boundary";
782   QString aPolylineName = HYDROData_Tool::GenerateObjectName( aDocument, aPolylinePref );
783   aResult->SetName( aPolylineName );
784
785   double Xmin = 0.0, Xmax = 0.0, Ymin = 0.0, Ymax = 0.0;
786   bool isFirst = true;
787   HYDROData_Bathymetry::AltitudePoints aPoints = GetAltitudePoints();
788
789   HYDROData_Bathymetry::AltitudePoints::const_iterator anIter = aPoints.begin(), aLast = aPoints.end();
790   for ( ; anIter!=aLast; ++anIter )
791   {
792     const HYDROData_Bathymetry::AltitudePoint& aPoint = *anIter;
793
794     double x = aPoint.X, y = aPoint.Y;
795     if( isFirst || x<Xmin )
796       Xmin = x;
797     if( isFirst || x>Xmax )
798       Xmax = x;
799     if( isFirst || y<Ymin )
800       Ymin = y;
801     if( isFirst || y>Ymax )
802       Ymax = y;
803     isFirst = false;
804   }
805
806   aResult->AddSection( "bound", HYDROData_IPolyline::SECTION_POLYLINE, true );
807   aResult->AddPoint( 0, HYDROData_IPolyline::Point( Xmin, Ymin ) );
808   aResult->AddPoint( 0, HYDROData_IPolyline::Point( Xmin, Ymax ) );
809   aResult->AddPoint( 0, HYDROData_IPolyline::Point( Xmax, Ymax ) );
810   aResult->AddPoint( 0, HYDROData_IPolyline::Point( Xmax, Ymin ) );
811   
812   aResult->SetWireColor( HYDROData_PolylineXY::DefaultWireColor() );
813   
814   aResult->Update();
815
816   return aResult;
817 }
818
819 void HYDROData_Bathymetry::UpdateLocalCS( double theDx, double theDy )
820 {
821   gp_XYZ aDelta( theDx, theDy, 0 );
822   HYDROData_Bathymetry::AltitudePoints aPoints = GetAltitudePoints();
823   HYDROData_Bathymetry::AltitudePoints::iterator anIter = aPoints.begin(), aLast = aPoints.end();
824   for ( int i = 0; anIter!=aLast; ++i, ++anIter )
825   {
826     HYDROData_Bathymetry::AltitudePoint& aPoint = *anIter;
827     aPoint.X += aDelta.X();
828     aPoint.Y += aDelta.Y();
829     aPoint.Z += aDelta.Z();
830   }
831   SetAltitudePoints( aPoints );
832 }
833