Salome HOME
export of 3D poly to SHP (lot 5)
[modules/hydro.git] / src / HYDROData / HYDROData_Tool.cxx
old mode 100644 (file)
new mode 100755 (executable)
index 50c1ef7..f5b1acf
@@ -1,8 +1,4 @@
-// Copyright (C) 2007-2015  CEA/DEN, EDF R&D, OPEN CASCADE
-//
-// Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
-// CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
-//
+// Copyright (C) 2014-2015  EDF-R&D
 // This library is free software; you can redistribute it and/or
 // modify it under the terms of the GNU Lesser General Public
 // License as published by the Free Software Foundation; either
 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
 //
 
-#include "HYDROData_Tool.h"
-
-#include "HYDROData_ArtificialObject.h"
-#include "HYDROData_Image.h"
-#include "HYDROData_Iterator.h"
-#include "HYDROData_NaturalObject.h"
-
+#include <HYDROData_Tool.h>
+#include <HYDROData_ArtificialObject.h>
+#include <HYDROData_Document.h>
+#include <HYDROData_Entity.h>
+#include <HYDROData_Iterator.h>
+#include <HYDROData_NaturalObject.h>
+#include <HYDROData_ShapesGroup.h>
+#include <HYDROData_PolylineXY.h>
+#include <QColor>
 #include <QFile>
 #include <QStringList>
 #include <QTextStream>
-
-#include <limits>
-#include <gp_Pnt.hxx>
-#include <gp_Pln.hxx>
-#include <ElSLib.hxx>
-#include <TopAbs_State.hxx>
+#include <QSet>
+#include <BRep_Tool.hxx>
 #include <BRepAdaptor_Surface.hxx>
 #include <BRepTopAdaptor_FClass2d.hxx>
-#include <BRep_Tool.hxx>
+#include <ElSLib.hxx>
+#include <Geom_Curve.hxx>
+#include <gp_Pln.hxx>
+#include <Quantity_Color.hxx>
+#include <TopExp_Explorer.hxx>
+#include <TopoDS.hxx>
+#include <TopoDS_Face.hxx>
+#include <TopoDS_Shape.hxx>
+#include <TopoDS_Wire.hxx>
+#include <limits>
+#include <math.h>
+
+
+#include <BRepTools.hxx>
+#include <NCollection_Map.hxx>
+#include <TopTools_ShapeMapHasher.hxx>
+#include <BRep_Builder.hxx>
+#include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
+#include <TopExp.hxx>
+#include <NCollection_List.hxx>
+#include <TopTools_ListIteratorOfListOfShape.hxx>
+
+#include <BRepBuilderAPI_MakeFace.hxx>
+
+#include <TopExp_Explorer.hxx>
+#include <TopTools_ListIteratorOfListOfShape.hxx>
+#include <TopTools_HSequenceOfShape.hxx>
 
-static int aMaxNameId = std::numeric_limits<int>::max();
+#include <BRep_Builder.hxx>
+#include <BRepAlgo_FaceRestrictor.hxx>
+#include <BRepCheck_Analyzer.hxx>
 
+#include <ShapeAnalysis.hxx>
+#include <ShapeAnalysis_FreeBounds.hxx>
+
+#include <HYDROData_PolylineXY.h>
+#include <HYDROData_Polyline3D.h>
+#include <HYDROData_Bathymetry.h>
+
+#include <QFileInfo>
+#define BLOCK_SIZE 10000
+
+HYDROData_Tool::ExecStatus HYDROData_Tool::myTriangulationStatus = ExecStatus::None;
+
+static int aMaxNameId = INT_MAX;
+static int aMaxColorNb = 92000;
 void HYDROData_Tool::WriteStringsToFile( QFile&             theFile,
                                          const QStringList& theStrings,
                                          const QString&     theSep )
@@ -54,39 +90,21 @@ void HYDROData_Tool::WriteStringsToFile( QFile&             theFile,
     return;
 
   QTextStream anOutStream( &theFile );
-  anOutStream << aWriteStr << theSep << theSep;
+  anOutStream << aWriteStr.toUtf8() << theSep << theSep;
 }
 
-void HYDROData_Tool::SetMustBeUpdatedObjects(
-  const Handle(HYDROData_Document)& theDoc  )
+bool HYDROData_Tool::ExtractGeneratedObjectName(const QString& theName, int& outValue, QString& thePrefName)
 {
-  bool anIsChanged = true;
-
-  // iterate until there is no changes because objects on all level of dependency must be updated
-  while ( anIsChanged )
-  {
-    anIsChanged = false;
-
-    HYDROData_Iterator anIter( theDoc );
-    for ( ; anIter.More(); anIter.Next() )
-    {
-      Handle(HYDROData_Entity) anObject = anIter.Current();
-      if ( anObject.IsNull() || anObject->IsMustBeUpdated() )
-        continue;
-
-      HYDROData_SequenceOfObjects aRefSeq = anObject->GetAllReferenceObjects();
-      for ( int i = 1, n = aRefSeq.Length(); i <= n; ++i )
-      {
-        Handle(HYDROData_Entity) aRefObject = aRefSeq.Value( i );
-        if ( aRefObject.IsNull() || !aRefObject->IsMustBeUpdated() )
-          continue;
-
-        anObject->SetToUpdate( true );
-        anIsChanged = true;
-        break;
-      }
-    }
-  }
+  QStringList aLs = theName.split('_');
+  bool ok = false;
+  QString last = aLs.last();
+  outValue = last.toInt(&ok);
+  if (!ok)
+    return false;
+  int last_len = last.length();
+  int total_len = theName.length();
+  thePrefName = theName.left(total_len-last_len-1);
+  return true;
 }
 
 QString HYDROData_Tool::GenerateObjectName( const Handle(HYDROData_Document)& theDoc,
@@ -191,6 +209,9 @@ TopAbs_State HYDROData_Tool::ComputePointState( const gp_XY& theXY, const TopoDS
   Standard_Real aTol = BRep_Tool::Tolerance(theFace);
   BRepAdaptor_Surface Ads ( theFace, Standard_False );
   Standard_Real toluv = Min ( Ads.UResolution(aTol), Ads.VResolution(aTol) ); 
+  if (toluv < 0.01)
+    toluv = 0.01; // there is no need to be more precise than 1cm a any case ! 
+                  // another solution could be to compute a tolerance related to the distance between the border nodes 
   const gp_Pln& aPlane = Ads.Surface().Plane();
   gp_Pnt aPnt(theXY.X(), theXY.Y(), 0.);
   Standard_Real aU1, aV1;
@@ -198,4 +219,721 @@ TopAbs_State HYDROData_Tool::ComputePointState( const gp_XY& theXY, const TopoDS
   BRepTopAdaptor_FClass2d aClassifier( theFace, toluv ); 
   aState = aClassifier.Perform( gp_Pnt2d(aU1, aV1), Standard_False );
   return aState;
-}
\ No newline at end of file
+}
+
+double HYDROData_Tool::GetAltitudeForEdge( const TopoDS_Edge& theEdge,
+                                           const gp_XY& thePoint,
+                                           double theParameterTolerance,
+                                           double theSquareDistanceTolerance,
+                                           double theInvalidAltitude )
+{
+  double aFirst, aLast;
+  Handle(Geom_Curve) aCurve = BRep_Tool::Curve( theEdge, aFirst, aLast );
+  if( aCurve.IsNull() )
+    return theInvalidAltitude;
+
+  gp_Pnt aFirstPnt, aLastPnt;
+
+  aCurve->D0( aFirst, aFirstPnt );
+  aCurve->D0( aLast, aLastPnt );
+
+  gp_Pnt2d aFirstPnt2d( aFirstPnt.X(), aFirstPnt.Y() );
+  gp_Pnt2d aLastPnt2d( aLastPnt.X(), aLastPnt.Y() );
+
+  double aFirstDist = 0;
+  double aLastDist = aFirstPnt2d.SquareDistance( aLastPnt2d );
+  double aNecDist = aFirstPnt2d.SquareDistance( thePoint );
+
+  while( fabs( aLast - aFirst ) > theParameterTolerance )
+  {
+    double aMid = ( aFirst + aLast ) / 2;
+    gp_Pnt aMidPnt;
+    aCurve->D0( aMid, aMidPnt );
+    double aDist = aFirstPnt2d.SquareDistance( gp_Pnt2d( aMidPnt.X(), aMidPnt.Y() ) );
+
+    if( aDist < aNecDist )
+      aFirst = aMid;
+    else
+      aLast = aMid;
+  }
+
+  double aMid = ( aFirst + aLast ) / 2;
+  gp_Pnt aMidPnt;
+  aCurve->D0( aMid, aMidPnt );
+
+  gp_Pnt2d aMidPnt2d( aMidPnt.X(), aMidPnt.Y() );
+  if( aMidPnt2d.SquareDistance( thePoint ) < theSquareDistanceTolerance )
+    return aMidPnt.Z();
+  else
+    return theInvalidAltitude;
+}
+
+double HYDROData_Tool::GetAltitudeForWire( const TopoDS_Wire& theWire,
+                                           const gp_XY& thePoint,
+                                           double theParameterTolerance,
+                                           double theSquareDistanceTolerance,
+                                           double theInvalidAltitude )
+{
+  TopExp_Explorer anExp( theWire, TopAbs_EDGE );
+  for( ; anExp.More(); anExp.Next() )
+  {
+    double anAltitude = GetAltitudeForEdge( TopoDS::Edge( anExp.Current() ), thePoint,
+      theParameterTolerance, theSquareDistanceTolerance, theInvalidAltitude );
+    if( anAltitude != theInvalidAltitude )
+      return anAltitude;
+  }
+  return theInvalidAltitude;
+}
+
+TopoDS_Shape HYDROData_Tool::getFirstShapeFromGroup( const HYDROData_SequenceOfObjects& theGroups,
+                                                     const int                          theGroupId )
+{
+  TopoDS_Shape aResShape;
+  if ( theGroupId < 1 || theGroupId > theGroups.Length() )
+    return aResShape;
+
+  Handle(HYDROData_ShapesGroup) aGroup =
+    Handle(HYDROData_ShapesGroup)::DownCast( theGroups.Value( theGroupId ) );
+  if ( aGroup.IsNull() )
+    return aResShape;
+
+  TopTools_SequenceOfShape aGroupShapes;
+  aGroup->GetShapes( aGroupShapes );
+
+  if ( !aGroupShapes.IsEmpty() )
+    aResShape = aGroupShapes.First();
+
+  return aResShape;
+}
+
+TCollection_ExtendedString HYDROData_Tool::toExtString( const QString& theStr )
+{
+  TCollection_ExtendedString aRes;
+  if( !theStr.isEmpty() )
+  {
+         Standard_ExtString extStr = new Standard_ExtCharacter[ ( theStr.length() + 1 ) * 2 ];
+         memcpy( (void*)extStr, theStr.unicode(), theStr.length() * 2 );
+         ((short*)extStr)[theStr.length()] = '\0';
+    aRes = TCollection_ExtendedString( extStr );
+         delete [] extStr;
+  }
+  return aRes;
+}
+
+QString HYDROData_Tool::toQString( const TCollection_ExtendedString& theStr )
+{
+  return QString( (QChar*)theStr.ToExtString(), theStr.Length() );
+}
+
+Quantity_Color HYDROData_Tool::toOccColor( const QColor& theColor )
+{
+  double r = theColor.red() / 255.0;
+  double g = theColor.green() / 255.0;
+  double b = theColor.blue() / 255.0;
+
+  return Quantity_Color( r, g, b, Quantity_TOC_RGB );
+}
+
+QColor HYDROData_Tool::toQtColor( const Quantity_Color& theColor )
+{
+  int r = 255 * theColor.Red();
+  int g = 255 * theColor.Green();
+  int b = 255 * theColor.Blue();
+  return QColor( r, g, b );
+}
+
+QColor HYDROData_Tool::GenerateRandColor()
+{
+  float aHue = ( rand()%1000 ) * 0.001f;
+
+  QColor aColor;
+  aColor.setHsl( (int)(aHue*255.), 200, 128 );
+  int r = aColor.red();
+  int g = aColor.green();
+  int b = aColor.blue();
+  return ( aColor.isValid() ? aColor : Qt::darkBlue );
+}
+
+void HYDROData_Tool::GenerateRepeatableRandColors(int nbColorsToGen, QVector<QColor>& theColors)
+{
+  for (int i = 1; i <= nbColorsToGen; i++)
+    theColors.append(HYDROData_Tool::GenerateRandColor());
+}
+
+bool HYDROData_Tool::GenerateNonRepeatableRandColors(int nbColorsToGen, QVector<QColor>& theColors)
+{
+  if (nbColorsToGen > aMaxColorNb)
+    return false;
+  QSet<int> Codes;
+  float aHue;
+  theColors.clear();
+  do 
+  {
+    QColor aColor;
+    int H = rand()%360;
+    int S = rand()%256;
+    int Code = H*256+S;
+    if (Codes.contains(Code))
+      continue;
+    aColor.setHsl( H, S, 128 );
+    if (aColor.isValid())
+    {
+      theColors.append(aColor);
+      Codes.insert(Code);
+    }
+  } while (theColors.size() <= nbColorsToGen);
+  return true;
+}
+
+
+bool HYDROData_Tool::IsNan( double theValue )
+{
+#ifdef WIN32
+  return _isnan( theValue );
+#else
+  return isnan( theValue );
+#endif
+}
+
+bool HYDROData_Tool::IsInf( double theValue )
+{
+#ifdef WIN32
+  return (!_finite( theValue  ) );
+#else
+  return isinf( theValue );
+#endif  
+}
+
+static void MakeShellG(const NCollection_Map<TopoDS_Face, TopTools_ShapeMapHasher>& FG,
+  TopoDS_Shape& outSh)
+{
+  BRep_Builder bb;
+  NCollection_Map<TopoDS_Face, TopTools_ShapeMapHasher>::Iterator itFG(FG);
+  if (FG.Extent() > 1)
+  {
+    //face nb > 1 => make shell
+    TopoDS_Shell outShell;
+    bb.MakeShell(outShell);
+    for (;itFG.More();itFG.Next())
+      bb.Add(outShell, itFG.Value());
+    outSh = outShell;
+  }
+  else if (FG.Extent() == 1)
+  {
+    outSh = itFG.Value(); //one face
+  }
+}
+
+TopoDS_Shape HYDROData_Tool::RebuildCmp(const TopoDS_Shape& in)
+{
+  TopTools_IndexedDataMapOfShapeListOfShape mE2LF;
+  TopExp::MapShapesAndAncestors(in, TopAbs_EDGE, TopAbs_FACE, mE2LF);
+  if (mE2LF.IsEmpty())
+    return TopoDS_Shape();
+  NCollection_Map<TopoDS_Face, TopTools_ShapeMapHasher> dfm;
+  //TopExp::MapShapes(aFuseShape, TopAbs_FACE, dfm);
+  TopExp_Explorer expf(in, TopAbs_FACE);
+  for (;expf.More(); expf.Next())
+    dfm.Add(TopoDS::Face(expf.Current()));
+
+  int nbF = dfm.Extent();
+  TopExp_Explorer exp_f(in, TopAbs_FACE);
+  const TopoDS_Face& FF = TopoDS::Face(exp_f.Current());
+  NCollection_List<TopoDS_Face> CurrFS;
+  NCollection_List<TopoDS_Face> NeighFS;
+  NCollection_Map<TopoDS_Face, TopTools_ShapeMapHasher> PrF;
+  CurrFS.Append(FF);
+  NCollection_List<NCollection_Map<TopoDS_Face, TopTools_ShapeMapHasher>> GL_F;
+  NCollection_Map<TopoDS_Face, TopTools_ShapeMapHasher> OneGr;
+  bool end = false;
+  while (!end)
+  {
+    NCollection_List<TopoDS_Face>::Iterator it_currfs(CurrFS);
+    NeighFS.Clear();
+    for (;it_currfs.More();it_currfs.Next())
+    {
+      const TopoDS_Face& CF = it_currfs.Value();
+      TopExp_Explorer exp_edge(CF, TopAbs_EDGE);
+      for (;exp_edge.More();exp_edge.Next())
+      {
+        const TopoDS_Shape& CE = exp_edge.Current();
+        const TopTools_ListOfShape& lsf = mE2LF.FindFromKey(CE);
+        TopTools_ListIteratorOfListOfShape ls_it(lsf); //always one face (since all faces are planar)
+        for (;ls_it.More();ls_it.Next())
+        {
+          const TopoDS_Face& F = TopoDS::Face(ls_it.Value());
+          if (F.IsSame(CF))
+            continue;
+          if (!PrF.Contains(F))
+          {
+            OneGr.Add(F);
+            NeighFS.Append(F);
+            PrF.Add(F);
+          }
+        }
+      }
+      OneGr.Add(CF);
+      PrF.Add(CF);
+    }
+    if (NeighFS.IsEmpty())
+    {
+      GL_F.Append(OneGr);
+      OneGr.Clear();
+      dfm.Subtract(PrF);
+      if (dfm.IsEmpty())
+        end = true;
+      else
+      {
+        NCollection_Map<TopoDS_Face, TopTools_ShapeMapHasher>::Iterator itDm(dfm);
+        const TopoDS_Face& nsh = itDm.Key();
+        NeighFS.Append(nsh);
+      }
+    }
+    CurrFS = NeighFS;
+  }
+
+  TopoDS_Shape sh;
+
+  if (GL_F.Extent() > 1)
+  {
+    TopoDS_Compound cmp;
+    NCollection_List<NCollection_Map<TopoDS_Face, TopTools_ShapeMapHasher>>::Iterator itGL_F(GL_F);  
+    BRep_Builder bb;
+    bb.MakeCompound(cmp);
+    for (;itGL_F.More();itGL_F.Next())
+    {
+      MakeShellG(itGL_F.Value(), sh);
+      if (!sh.IsNull())
+        bb.Add(cmp, sh);
+    }
+    return  cmp;
+  }
+  else if (GL_F.Extent() == 1)
+  {
+    MakeShellG(GL_F.First(), sh);
+    return sh;
+  }
+  
+}
+
+TopoDS_Shape HYDROData_Tool::PolyXY2Face( const Handle(HYDROData_PolylineXY)& aPolyline )
+{
+  //DEBTRACE("generateTopShape");
+  TopoDS_Face aResultFace = TopoDS_Face(); // --- result: default = null face
+
+  if (!aPolyline.IsNull())
+    {
+      TopoDS_Shape aPolylineShape = aPolyline->GetShape();
+#ifdef DEB_IMZ
+      std::string brepName = "imz.brep";
+      BRepTools::Write(aPolylineShape, brepName.c_str());
+#endif
+      TopTools_ListOfShape aWiresList;
+
+      if (!aPolylineShape.IsNull() && aPolylineShape.ShapeType() == TopAbs_WIRE)
+        {
+          // --- only one wire: try to make a face
+          //DEBTRACE("one wire: try to build a face");
+          const TopoDS_Wire& aPolylineWire = TopoDS::Wire(aPolylineShape);
+          if (!aPolylineWire.IsNull())
+            {
+              BRepBuilderAPI_MakeFace aMakeFace(aPolylineWire, Standard_True);
+              aMakeFace.Build();
+              if (aMakeFace.IsDone())
+                {
+                  //DEBTRACE(" a face with the only wire given");
+                  aResultFace = aMakeFace.Face();
+                }
+            }
+        }
+      else
+        {
+          // --- a list of wires ? inventory of wires and edges
+          Handle(TopTools_HSequenceOfShape) aSeqWires = new TopTools_HSequenceOfShape;
+          Handle(TopTools_HSequenceOfShape) aSeqEdges = new TopTools_HSequenceOfShape;
+          TopExp_Explorer anExp(aPolylineShape, TopAbs_WIRE);
+          //DEBTRACE("list of wires ?");
+          for (; anExp.More(); anExp.Next())
+            {
+              if (!anExp.Current().IsNull())
+                {
+                  const TopoDS_Wire& aWire = TopoDS::Wire(anExp.Current());
+                  aWiresList.Append(aWire);
+                  //DEBTRACE("  append wire");
+                  TopExp_Explorer it2(aWire, TopAbs_EDGE);
+                  for (; it2.More(); it2.Next())
+                    aSeqEdges->Append(it2.Current());
+                }
+            }
+          if (aWiresList.IsEmpty())
+            return aResultFace; // --- no wires: null result
+
+          if (aSeqEdges->Length() > 1)
+            {
+              //DEBTRACE("try to connect all the edges together, build a unique wire and a face");
+              // --- try to create one wire by connecting edges with a distance tolerance (no necessity of sharing points)
+              ShapeAnalysis_FreeBounds::ConnectEdgesToWires(aSeqEdges, 1E-5, Standard_False, aSeqWires);
+
+              if (aSeqWires->Length() == 1)
+                {
+                  // --- one wire: try to make a face
+                  const TopoDS_Wire& aPolylineWire = TopoDS::Wire(aSeqWires->Value(1));
+                  if (!aPolylineWire.IsNull())
+                    {
+                      BRepBuilderAPI_MakeFace aMakeFace(aPolylineWire, Standard_True);
+                      aMakeFace.Build();
+                      if (aMakeFace.IsDone())
+                        {
+                          //DEBTRACE("  a face from all the wires connected");
+                          aResultFace = aMakeFace.Face();
+                        }
+                    }
+                }
+            }
+
+          if (aResultFace.IsNull())
+            {
+              //DEBTRACE("try to make a face with the first wire of the list and other wires as restrictions");
+              // --- try to make a face with the first wire of the list and other wires as restrictions
+              BRepAlgo_FaceRestrictor aFR;
+              TopoDS_Face aRefFace;
+              TopoDS_Shape aS = aWiresList.First();
+              BRepBuilderAPI_MakeFace aMakeFace(TopoDS::Wire(aWiresList.First()), Standard_True);
+              aMakeFace.Build();
+              if (aMakeFace.IsDone())
+                {
+                  //DEBTRACE("  a face with first wire");
+                  aRefFace = aMakeFace.Face();
+                }
+              if (!aRefFace.IsNull())
+                {
+                  aFR.Init(aRefFace, Standard_False, Standard_True);
+                  TopTools_ListIteratorOfListOfShape anIt(aWiresList);
+                  for (; anIt.More(); anIt.Next())
+                    {
+                      TopoDS_Wire& aWire = TopoDS::Wire(anIt.Value());
+                      if (aWire.IsNull())
+                        continue;
+                      aFR.Add(aWire);
+                    }
+                  aFR.Perform();
+                  if (aFR.IsDone())
+                    {
+                      for (; aFR.More(); aFR.Next())
+                        {
+                          //DEBTRACE("  a restricted face");
+                          aResultFace = aFR.Current();
+                          break;
+                        }
+                    }
+                }
+            }
+        }
+    }
+
+  if (aResultFace.IsNull())
+    return aResultFace;
+
+  //DEBTRACE("check the face");
+  BRepCheck_Analyzer anAnalyzer(aResultFace);
+  if (anAnalyzer.IsValid() && aResultFace.ShapeType() == TopAbs_FACE)
+  {
+    //DEBTRACE("face OK");
+    return aResultFace;
+  }
+  else
+  {
+    //DEBTRACE("bad face");
+  }
+  return TopoDS_Face();
+}
+
+void HYDROData_Tool::SetSIProgress(const Handle(Message_ProgressIndicator)& thePI)
+{
+  StricklerInterpolationProgress() = thePI;
+}
+  
+const Handle(Message_ProgressIndicator)& HYDROData_Tool::GetSIProgress()
+{
+  return StricklerInterpolationProgress();
+}
+
+Handle(Message_ProgressIndicator)& HYDROData_Tool::StricklerInterpolationProgress()
+{
+  static Handle(Message_ProgressIndicator) aPI = NULL;
+  return aPI;
+}
+
+void HYDROData_Tool::SetZIProgress(const Handle(Message_ProgressIndicator)& thePI)
+{
+  BathymetryInterpolationProgress() = thePI;
+}
+  
+const Handle(Message_ProgressIndicator)& HYDROData_Tool::GetZIProgress()
+{
+  return BathymetryInterpolationProgress();
+}
+
+Handle(Message_ProgressIndicator)& HYDROData_Tool::BathymetryInterpolationProgress()
+{
+  static Handle(Message_ProgressIndicator) aPI = NULL;
+  return aPI;
+}
+
+void HYDROData_Tool::SetTriangulationStatus(const ExecStatus& theStatus)
+{
+  myTriangulationStatus = theStatus;
+}
+
+const HYDROData_Tool::ExecStatus& HYDROData_Tool::GetTriangulationStatus()
+{
+  return myTriangulationStatus;
+}
+
+static bool AddXYZ(bool bImportXY, 
+                   double x,
+                   double y, 
+                   double z,
+                   std::vector<gp_XYZ>& thePointsXYZ,
+                   std::vector<gp_XY>& thePointsXY)
+{
+  if (!bImportXY)
+  {
+    if ( HYDROData_Tool::IsNan( x ) || HYDROData_Tool::IsInf( x ) ||
+      HYDROData_Tool::IsNan( y ) || HYDROData_Tool::IsInf( y ) ||
+      HYDROData_Tool::IsNan( z ) || HYDROData_Tool::IsInf( z ) )
+      return false;
+
+    if( thePointsXYZ.size()>=thePointsXYZ.capacity() )
+      thePointsXYZ.reserve( thePointsXYZ.size()+BLOCK_SIZE );
+
+    thePointsXYZ.push_back(gp_XYZ(x,y,z));
+  }
+  else
+  {
+    if ( HYDROData_Tool::IsNan( x ) || HYDROData_Tool::IsInf( x ) ||
+      HYDROData_Tool::IsNan( y ) || HYDROData_Tool::IsInf( y ) )
+      return false;
+
+    if( thePointsXY.size()>=thePointsXY.capacity() )
+      thePointsXY.reserve( thePointsXY.size()+BLOCK_SIZE );
+
+    thePointsXY.push_back(gp_XY(x,y));
+  }
+  return true;
+}
+
+bool HYDROData_Tool::importFromXYZ( QString& theFileName,  
+                                    bool bImportXY, 
+                                    std::vector<gp_XYZ>& thePointsXYZ,
+                                    std::vector<gp_XY>& thePointsXY)
+{
+  QFile aFile( theFileName );
+  if ( !aFile.exists() || !aFile.open( QIODevice::ReadOnly ) )
+    return false;
+
+  QString aFileSuf = QFileInfo( aFile ).suffix().toLower();
+
+  double x,y;
+  if ( aFileSuf == "xyz" )
+  {
+    double z;
+    while ( !aFile.atEnd() )
+    {
+      std::string aLine = aFile.readLine().simplified().toStdString();
+      if ( aLine.empty() )
+        continue;
+
+      x = 0;
+      y = 0;
+      z = 0;
+
+      if( sscanf( aLine.c_str(), "%lf %lf %lf", &x, &y, &z )!=3 )
+      {
+        aFile.close();
+        return false;
+      }
+
+      if (!AddXYZ(bImportXY, x, y, z, thePointsXYZ, thePointsXY ))
+      {
+        aFile.close();
+        return false;
+      }
+    }
+  }
+  else if (aFileSuf == "xy" )
+  {
+    while ( !aFile.atEnd() )
+    {
+      std::string aLine = aFile.readLine().simplified().toStdString();
+      if ( aLine.empty() )
+        continue;
+
+      x = 0;
+      y = 0;
+
+      if( sscanf( aLine.c_str(), "%lf %lf", &x, &y )!=2 )
+      {
+        aFile.close();
+        return false;
+      }
+
+      if (!AddXYZ(true, x, y, 0, thePointsXYZ, thePointsXY ))
+      {
+        aFile.close();
+        return false;
+      }
+    }
+  }
+
+  aFile.close();
+
+  return true;
+}
+
+bool HYDROData_Tool::importPolylineFromXYZ(QString aFileName, Handle(HYDROData_Document) theDocument, 
+  bool importXY, NCollection_Sequence<Handle(HYDROData_Entity)>& importedEntities)
+{
+  if (importXY)
+  {
+    std::vector<gp_XY> aPoints2d;
+    std::vector<gp_XYZ> aDPoints3d;
+
+    if (HYDROData_Tool::importFromXYZ(aFileName, importXY, aDPoints3d, aPoints2d))
+    {
+      QString basename = QFileInfo( aFileName ).baseName();
+
+      Handle(HYDROData_PolylineXY) aPolylineXY = Handle(HYDROData_PolylineXY)::DownCast( theDocument->CreateObject( KIND_POLYLINEXY ) );
+      HYDROData_PolylineXY::SectionType aSectType = HYDROData_PolylineXY::SECTION_POLYLINE;    
+      bool IsClosed = false;
+      if ((aPoints2d.front()-aPoints2d.back()).Modulus()<Precision::Confusion())
+      {
+        IsClosed = true;
+        aPolylineXY->AddSection( TCollection_AsciiString("poly_section"), aSectType, true);
+      }
+      else
+        aPolylineXY->AddSection( TCollection_AsciiString("poly_section"), aSectType, false);
+
+      int n = aPoints2d.size();
+      if (IsClosed)
+        n--;
+
+      for ( int i = 0; i < n; i++ )
+      {
+        gp_XY aSectPoint = aPoints2d[i];
+        theDocument->Transform(aSectPoint, true);
+        aPolylineXY->AddPoint( 0, aSectPoint );
+      }      
+
+      aPolylineXY->SetWireColor( HYDROData_PolylineXY::DefaultWireColor() );
+      aPolylineXY->SetName( basename + "_PolyXY_" );
+      aPolylineXY->Update();
+      importedEntities.Append(aPolylineXY);
+      return true;
+    }
+    else 
+      return false;
+  }
+  else //xyz 
+  {
+    std::vector<gp_XY> aDPoints2d;
+    std::vector<gp_XYZ> aPoints3d;
+    if (HYDROData_Tool::importFromXYZ(aFileName, false, aPoints3d, aDPoints2d))
+    {
+      QString basename = QFileInfo( aFileName ).baseName();
+      Handle(HYDROData_PolylineXY) aPolylineXY = Handle(HYDROData_PolylineXY)::DownCast( theDocument->CreateObject( KIND_POLYLINEXY ) );
+      Handle(HYDROData_Polyline3D) aPolylineObj = Handle(HYDROData_Polyline3D)::DownCast( theDocument->CreateObject( KIND_POLYLINE ) );
+      Handle(HYDROData_Bathymetry) aBath = Handle(HYDROData_Bathymetry)::DownCast( theDocument->CreateObject( KIND_BATHYMETRY ) );
+      HYDROData_Bathymetry::AltitudePoints aAPoints;
+      HYDROData_PolylineXY::SectionType aSectType = HYDROData_PolylineXY::SECTION_POLYLINE;    
+      bool IsClosed = false;
+      if ((aPoints3d.front()-aPoints3d.back()).Modulus()<Precision::Confusion())
+      {
+        IsClosed = true;
+        aPolylineXY->AddSection( TCollection_AsciiString("poly_section"), aSectType, true);
+      }
+      else
+        aPolylineXY->AddSection( TCollection_AsciiString("poly_section"), aSectType, false);
+
+      int n = aPoints3d.size();
+      if (IsClosed)
+        n--;
+
+      for ( int i = 0; i < n; i++ )
+      {
+        gp_XY aSectPoint(aPoints3d[i].X(), aPoints3d[i].Y());
+        theDocument->Transform(aSectPoint, true);
+        aPolylineXY->AddPoint( 0, aSectPoint );
+        HYDROData_Bathymetry::AltitudePoint p;
+        p.X = aSectPoint.X();
+        p.Y = aSectPoint.Y();
+        p.Z = aPoints3d[i].Z();
+        aAPoints.push_back(p);
+      }
+
+      QString aBathName = basename + "_bath_";
+      QString aPolyXYName = basename + "_polyXY_";
+      QString aPoly3DName = basename + "_poly3D_";
+
+      aPolylineXY->SetName( aPolyXYName );
+      aPolylineXY->SetWireColor(HYDROData_PolylineXY::DefaultWireColor());
+      aPolylineXY->Update();
+
+      aBath->SetAltitudePoints(aAPoints);
+      aBath->SetName( aBathName );
+
+      aPolylineObj->SetPolylineXY (aPolylineXY, false);
+      aPolylineObj->SetAltitudeObject(aBath);
+
+      aPolylineObj->SetBorderColor( aPolylineObj->DefaultBorderColor() );
+      aPolylineObj->SetName( aPoly3DName );
+
+      aPolylineObj->Update();
+      importedEntities.Append(aPolylineXY);
+      importedEntities.Append(aPolylineObj);
+      return true;
+    }
+    else 
+      return false;
+  }
+}
+
+
+std::ostream& operator<<( std::ostream& theStream, const QString& theText )
+{
+  theStream << theText.toStdString();
+  return theStream;
+}
+
+std::ostream& operator<<( std::ostream& theStream, const QColor& theColor )
+{
+  theStream << "[" << theColor.red() << ", " << theColor.green() << ", " << theColor.blue() << "]";
+  return theStream;
+}
+
+std::ostream& operator<<( std::ostream& theStream, const TopoDS_Shape& theShape )
+{
+  theStream << "[" << theShape.TShape().operator->() << "]";
+  return theStream;
+}
+
+std::ostream& operator<<( std::ostream& theStream, const TopoDS_Face& theFace )
+{
+  theStream << "[" << theFace.TShape().operator->() << "]";
+  return theStream;
+}
+
+std::ostream& operator<<( std::ostream& theStream, const gp_XY& theXY )
+{
+  theStream << "(" << theXY.X() << "; " << theXY.Y() << ")";
+  return theStream;
+}
+
+bool operator == ( const gp_XY& thePoint1, const gp_XY& thePoint2 )
+{
+  const double EPS = 1E-3;
+  return
+    fabs( thePoint1.X() - thePoint2.X() ) < EPS &&
+    fabs( thePoint1.Y() - thePoint2.Y() ) < EPS;
+
+}