Salome HOME
987b1f3d2c42fa3a9dc99ae76d6e6ff3a699fbd8
[modules/hydro.git] / src / HYDROData / HYDROData_ShapeFile.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_ShapeFile.h>
20 #include <HYDROData_PolylineXY.h>
21 #include <HYDROData_Polyline3D.h>
22 #include <HYDROData_Bathymetry.h>
23 #include <HYDROData_Profile.h>
24 #include <HYDROData_Iterator.h>
25 #include <HYDROData_LandCoverMap.h>
26
27 #include <QFile>
28 #include <QFileInfo>
29 #include <TopoDS.hxx>
30 #include <TopExp_Explorer.hxx>
31 #include <TopoDS_Wire.hxx>
32 #include <TopoDS_Vertex.hxx>
33 #include <TopoDS_Edge.hxx>
34 #include <TopoDS_Face.hxx>
35 #include <BRep_Tool.hxx>
36 #include <BRepTools.hxx>
37 #include <Precision.hxx>
38 #include <Handle_Geom_Curve.hxx>
39 #include <Handle_Geom_Line.hxx>
40 #include <Handle_Geom_TrimmedCurve.hxx>
41 #include <Geom_TrimmedCurve.hxx>
42 #include <BRepBuilderAPI_MakeEdge.hxx>
43 #include <BRepBuilderAPI_MakeWire.hxx>
44 #include <BRepBuilderAPI_MakeFace.hxx>
45 #include <gp_Pln.hxx>
46 #include <BRepLib.hxx>
47 #include <ShapeFix_Shape.hxx>
48 #include <TopTools_SequenceOfShape.hxx>
49 #include <QColor>
50 #include <BRepTopAdaptor_FClass2d.hxx>
51 #include <TopExp.hxx>
52
53 #ifdef WIN32
54   #pragma warning( disable: 4996 )
55 #endif
56
57 HYDROData_ShapeFile::HYDROData_ShapeFile() : myHSHP(NULL)
58
59 }
60
61 HYDROData_ShapeFile::~HYDROData_ShapeFile()
62 {
63   Free();
64 }
65
66 void HYDROData_ShapeFile::Export(const QString& aFileName, 
67   NCollection_Sequence<Handle_HYDROData_PolylineXY> aPolyXYSeq,
68   NCollection_Sequence<Handle_HYDROData_Polyline3D> aPoly3DSeq,
69   QStringList& aNonExpList)
70 {
71   SHPHandle hSHPHandle;
72   if (!aPolyXYSeq.IsEmpty() && aPoly3DSeq.IsEmpty())
73   {
74     hSHPHandle = SHPCreate( aFileName.toAscii().data(), SHPT_ARC );        
75     for (int i = 1; i <= aPolyXYSeq.Size(); i++)
76       if (WriteObjectPolyXY(hSHPHandle, aPolyXYSeq(i)) != 1)
77         aNonExpList.append(aPolyXYSeq(i)->GetName());
78   }
79   else if (aPolyXYSeq.IsEmpty() && !aPoly3DSeq.IsEmpty())
80   {
81     hSHPHandle = SHPCreate( aFileName.toAscii().data(), SHPT_ARCZ );
82     for (int i = 1; i <= aPoly3DSeq.Size(); i++)
83       if (WriteObjectPoly3D(hSHPHandle, aPoly3DSeq(i)) != 1)
84         aNonExpList.append(aPoly3DSeq(i)->GetName());
85   }
86   if (hSHPHandle->nRecords > 0)
87     SHPClose( hSHPHandle );
88   else
89   {
90     SHPClose( hSHPHandle );
91     QString aFN = aFileName.simplified();
92     remove (aFN.toStdString().c_str());
93     remove (aFN.replace( ".shp", ".shx", Qt::CaseInsensitive).toStdString().c_str());
94   }
95 }
96
97 void HYDROData_ShapeFile::Export(const QString& aFileName,
98   const Handle_HYDROData_LandCoverMap& aLCM, QStringList& aNonExpList)
99 {
100   SHPHandle hSHPHandle;
101   if ( !aLCM.IsNull() && !aLCM->IsEmpty())
102   {
103     hSHPHandle = SHPCreate( aFileName.toAscii().data(), SHPT_POLYGON );
104     HYDROData_LandCoverMap::Explorer It( aLCM );
105     for( ; It.More(); It.Next())
106     {
107       TopoDS_Face aFace = It.Face();
108       if (WriteObjectPolygon(hSHPHandle, aFace) != 1)
109         aNonExpList.append(aLCM->GetName() + "_" +  QString::number(It.Index()));
110     }
111   }
112   if (hSHPHandle->nRecords > 0)
113     SHPClose( hSHPHandle );
114   else
115   {
116     SHPClose( hSHPHandle );
117     QString aFN = aFileName.simplified();
118     remove (aFN.toStdString().c_str());
119     remove (aFN.replace( ".shp", ".shx", Qt::CaseInsensitive).toStdString().c_str());
120   }
121 }
122
123
124 int HYDROData_ShapeFile::WriteObjectPolyXY(SHPHandle theShpHandle, Handle_HYDROData_PolylineXY thePoly )
125 {
126   SHPObject     *aSHPObj;
127   std::vector<double> x, y;
128   std::vector<int> anPartStart;
129   
130   for (int i = 0; i < thePoly->NbSections(); i++)    
131     if (thePoly->GetSectionType(i) == HYDROData_IPolyline::SECTION_SPLINE)
132       return -1;
133
134   for (int i = 0; i < thePoly->NbSections(); i++)
135   {
136     anPartStart.push_back(x.size());
137     HYDROData_PolylineXY::PointsList aPointList = thePoly->GetPoints(i);
138     for (int j = 1; j <= aPointList.Size(); j++)
139     {
140       x.push_back( aPointList(j).X());
141       y.push_back( aPointList(j).Y()); 
142     }
143     if (thePoly->IsClosedSection(i))
144     {
145       x.push_back( aPointList(1).X());
146       y.push_back( aPointList(1).Y()); 
147     }
148   }
149     
150   aSHPObj = SHPCreateObject( SHPT_ARC, -1, thePoly->NbSections(), &anPartStart[0], NULL, x.size(), &x[0], &y[0], NULL, NULL );
151   SHPWriteObject( theShpHandle, -1, aSHPObj );
152   SHPDestroyObject( aSHPObj );
153   return 1;
154 }
155
156 int HYDROData_ShapeFile::WriteObjectPoly3D(SHPHandle theShpHandle, Handle_HYDROData_Polyline3D thePoly )
157 {
158   SHPObject     *aSHPObj;
159   std::vector<double> x, y, z;
160   std::vector<int> anPartStart;
161
162   for (int i = 0; i < thePoly->GetPolylineXY()->NbSections(); i++)    
163     if (thePoly->GetPolylineXY()->GetSectionType(i) == HYDROData_IPolyline::SECTION_SPLINE)
164       return -1;
165   
166   for (int i = 0; i < thePoly->GetPolylineXY()->NbSections(); i++)
167   {
168     anPartStart.push_back(x.size());
169     HYDROData_PolylineXY::PointsList aPointList = thePoly->GetPolylineXY()->GetPoints(i);
170     for (int j = 1; j <= aPointList.Size(); j++)
171     {
172       x.push_back( aPointList(j).X());
173       y.push_back( aPointList(j).Y()); 
174       z.push_back(thePoly->GetAltitudeObject()->GetAltitudeForPoint(gp_XY (aPointList(j).X(), aPointList(j).Y())));
175     }
176     if ( thePoly->GetPolylineXY()->IsClosedSection(i))
177     {
178       x.push_back( aPointList(1).X());
179       y.push_back( aPointList(1).Y()); 
180       z.push_back(thePoly->GetAltitudeObject()->GetAltitudeForPoint(gp_XY (aPointList(1).X(), aPointList(1).Y())));
181
182     }
183   }
184   
185   aSHPObj = SHPCreateObject( SHPT_ARCZ, -1, thePoly->GetPolylineXY()->NbSections(), &anPartStart[0], NULL, x.size(), &x[0], &y[0], &z[0], NULL );
186   SHPWriteObject( theShpHandle, -1, aSHPObj );
187   SHPDestroyObject( aSHPObj );
188   return 1;
189 }
190
191 int HYDROData_ShapeFile::WriteObjectPolygon(SHPHandle theShpHandle, const TopoDS_Shape& theInputShape )
192 {
193   if (theInputShape.IsNull())
194     return 0;
195   TopExp_Explorer anEdgeEx(theInputShape, TopAbs_EDGE);
196   for (; anEdgeEx.More(); anEdgeEx.Next()) 
197   {
198     TopoDS_Edge E = TopoDS::Edge(anEdgeEx.Current());
199     double aFP, aLP;
200     Handle_Geom_Curve aCur = BRep_Tool::Curve(E, aFP, aLP);
201     Handle(Geom_Line) aLine = Handle(Geom_Line)::DownCast(aCur);
202     if (aLine.IsNull())
203     {
204       Handle(Geom_TrimmedCurve) aTC = Handle(Geom_TrimmedCurve)::DownCast(aCur);
205       if (!aTC.IsNull())
206       {
207         Handle(Geom_Line) aLine = Handle(Geom_Line)::DownCast(aTC->BasisCurve());
208         if (aLine.IsNull())
209           return -1;
210       }
211       else
212         return -1;
213     }
214
215   }
216   if (theInputShape.ShapeType() == TopAbs_FACE)
217   {
218     ProcessFace(TopoDS::Face(theInputShape), theShpHandle);
219   }
220   else if (theInputShape.ShapeType() == TopAbs_COMPOUND)
221   {
222     TopExp_Explorer Ex(theInputShape, TopAbs_FACE);
223     for (; Ex.More(); Ex.Next()) 
224     {
225       TopoDS_Face aF = TopoDS::Face(Ex.Current());   
226       if (aF.IsNull())
227         continue;
228       ProcessFace(aF, theShpHandle);
229     }
230   }
231   else
232     return 0;
233
234   return 1;
235  
236 }
237
238 void HYDROData_ShapeFile::ProcessFace(TopoDS_Face theFace, SHPHandle theShpHandle)
239 {
240   if (theFace.ShapeType() != TopAbs_FACE)
241      return;
242   SHPObject     *aSHPObj;
243   std::vector<double> x, y;
244   std::vector<int> anPartStart;
245   TopoDS_Wire OuterW = BRepTools::OuterWire(theFace);
246   NCollection_Sequence<TopoDS_Wire> aWires;
247
248   //write an outer wire first
249   aWires.Append(OuterW); 
250   TopExp_Explorer Ex(theFace, TopAbs_WIRE);  
251   for (; Ex.More(); Ex.Next()) 
252   {
253     TopoDS_Wire aW = TopoDS::Wire(Ex.Current());
254     if (aW.IsEqual(OuterW))
255       continue;
256     aWires.Append(aW); 
257   }
258
259   //TopExp_Explorer Ex(theFace, TopAbs_WIRE);
260   int NbWires = 0;
261   for (int k = 1; k <= aWires.Length(); k++) 
262   {
263     TopoDS_Wire aW = aWires(k);   
264     if (aW.IsNull())
265       continue;
266     NbWires++;
267     if (aW.Orientation() == TopAbs_INTERNAL)
268       //cant write internal wires/edges
269       continue; 
270     // Try to reorder edges
271     Handle(ShapeFix_Wire) aSFW = new ShapeFix_Wire( aW, theFace, Precision::Confusion() );
272     aSFW->ModifyTopologyMode() = Standard_False;
273     aSFW->ModifyGeometryMode() = Standard_False;
274     aSFW->FixReorder();
275     Handle(ShapeExtend_WireData) aSEWD = aSFW->WireData();
276     Standard_Integer nbE = aSEWD->NbEdges();
277     if (nbE == 0)
278       continue;
279     //
280     anPartStart.push_back(x.size());
281     NCollection_Sequence<gp_Pnt2d> aPnts;
282     for (Standard_Integer i = 1; i <= nbE; i++)
283     {
284       TopoDS_Edge E = aSEWD->Edge(i);
285       TopoDS_Vertex aV = TopExp::LastVertex(E, 1);
286       if (aV.IsNull())
287         continue;
288       gp_Pnt P = BRep_Tool::Pnt(aV);
289       aPnts.Append(gp_Pnt2d(P.X(), P.Y()));
290     }
291     NCollection_Sequence<gp_Pnt2d> aNPnts;
292     aNPnts.Append(aPnts.First());
293     for (int j = 1; j <= aPnts.Size() - 1; j++)
294     {
295       if (!aPnts(j).IsEqual(aPnts(j + 1), Precision::Confusion())) 
296         aNPnts.Append(aPnts(j + 1));
297     }
298
299     //assume that the orientation of extrenal wire & internal wires is correct
300     //so just write all points "as-is"
301     //External wire will be written in clockwise direction
302     //any other wires (holes) - in anticlockwise direction
303     for (int j = 1; j <= aNPnts.Size(); j++)
304     { 
305       x.push_back( aNPnts(j).X());
306       y.push_back( aNPnts(j).Y()); 
307     }
308     x.push_back( aNPnts(1).X());
309     y.push_back( aNPnts(1).Y()); 
310   }
311   
312   aSHPObj = SHPCreateObject( SHPT_POLYGON, -1, NbWires, &anPartStart[0], NULL, x.size(), &x[0], &y[0], NULL, NULL );
313   SHPWriteObject( theShpHandle, -1, aSHPObj );
314   SHPDestroyObject( aSHPObj );
315
316 }
317
318 bool HYDROData_ShapeFile::Parse(SHPHandle theHandle, ShapeType theType, int& theShapeTypeOfFile)
319 {
320   int aShapeType;
321   mySHPObjects.clear();
322   SHPGetInfo( theHandle, NULL, &aShapeType, NULL, NULL );
323   theShapeTypeOfFile = aShapeType;
324   bool ToRead = (theType == ShapeType_Polyline && (aShapeType == 3 || aShapeType == 13 || aShapeType == 23)) ||
325    (theType == ShapeType_Polygon && aShapeType == 5);
326   if (ToRead) 
327   {
328     for (int i = 0; i < theHandle->nRecords; i++) 
329       mySHPObjects.push_back(SHPReadObject(theHandle, i));
330     return true;
331   }
332   else
333     return false;
334 }
335
336 void HYDROData_ShapeFile::ReadSHPPolygon(SHPObject* anObj, int i, TopoDS_Face& F)
337 {
338   if (!anObj)
339     return;
340   TopoDS_Wire W;
341   TopoDS_Edge E; 
342   int nParts = anObj->nParts;
343   gp_Pln pln(gp_Pnt(0,0,0), gp_Dir(0,0,1));
344
345   //Handle(ShapeFix_Shape) sfs = new ShapeFix_Shape;
346   //sfs->FixFaceTool()->FixOrientationMode() = 1;
347   TopTools_SequenceOfShape aWires;
348   for ( int i = 0 ; i < nParts ; i++ )
349   { 
350     BRepBuilderAPI_MakeWire aBuilder;
351     int StartIndex = anObj->panPartStart[i];
352     int EndIndex;
353     if (i != nParts - 1)
354       EndIndex = anObj->panPartStart[i + 1];
355     else
356       EndIndex = anObj->nVertices;
357
358     for ( int k = StartIndex; k < EndIndex - 1  ; k++ )
359     {
360       gp_Pnt P1 (anObj->padfX[k], anObj->padfY[k], 0);
361       gp_Pnt P2 (anObj->padfX[k+1], anObj->padfY[k+1], 0);
362       if (P1.Distance(P2) < Precision::Confusion())
363         continue;
364       BRepBuilderAPI_MakeEdge aMakeEdge(P1, P2);
365       aBuilder.Add(TopoDS::Edge(aMakeEdge.Shape()));
366     }
367     
368     aBuilder.Build();
369     W = TopoDS::Wire(aBuilder.Shape());
370     W.Orientation(TopAbs_FORWARD);
371     BRepBuilderAPI_MakeFace aDB(pln, W);
372     TopoDS_Face aDummyFace = TopoDS::Face(aDB.Shape());
373     BRepTopAdaptor_FClass2d FClass(aDummyFace, Precision::PConfusion());
374     if ( i == 0 && FClass.PerformInfinitePoint() == TopAbs_OUT) 
375       W.Reverse();
376     if ( i > 0 && FClass.PerformInfinitePoint() != TopAbs_IN) 
377       W.Reverse();
378    
379     aWires.Append(W);
380   }
381   
382   BRepBuilderAPI_MakeFace aFBuilder(pln, TopoDS::Wire(aWires(1)));
383   for (int i = 2; i <= aWires.Length(); i++)
384     aFBuilder.Add(TopoDS::Wire(aWires(i)));
385   F = TopoDS::Face(aFBuilder.Shape());
386
387   BRepLib::BuildCurves3d(F);  
388 }
389
390 int HYDROData_ShapeFile::ImportPolygons(const QString theFileName, QStringList& thePolygonsList, TopTools_SequenceOfShape& theFaces, int& theShapeTypeOfFile)
391 {
392   Free();
393   int Stat = TryOpenShapeFile(theFileName);
394   if (Stat != 0)
395     return Stat;
396   myHSHP = SHPOpen( theFileName.toAscii().data(), "rb" );
397   if (!Parse(myHSHP, HYDROData_ShapeFile::ShapeType_Polygon, theShapeTypeOfFile))
398     return 0;
399   for (size_t i = 0; i < mySHPObjects.size(); i++)
400     thePolygonsList.append("polygon_" + QString::number(i + 1));
401    
402   TopoDS_Face aF;
403   if (myHSHP->nShapeType == 5)
404   {
405     for (size_t i = 0; i < mySHPObjects.size(); i++) 
406     {
407        ReadSHPPolygon(mySHPObjects[i], i, aF);
408        theFaces.Append(aF);
409     }
410     return 1;
411   }
412   else
413     return 0;
414 }
415
416 void HYDROData_ShapeFile::Free()
417 {  
418   for (size_t i = 0; i < mySHPObjects.size(); i++ )
419     free (mySHPObjects[i]);
420
421   mySHPObjects.clear();
422   if (myHSHP != NULL)
423   {
424     SHPClose(myHSHP);
425     myHSHP = NULL; 
426   }
427 }
428
429
430 void HYDROData_ShapeFile::ReadSHPPolyXY(Handle(HYDROData_Document) theDocument, SHPObject* anObj, QString theFileName, 
431   int theInd, NCollection_Sequence<Handle_HYDROData_Entity>& theEntities)
432 {
433
434   Handle(HYDROData_PolylineXY) aPolylineXY = Handle(HYDROData_PolylineXY)::DownCast( theDocument->CreateObject( KIND_POLYLINEXY ) );
435   
436   int nParts = anObj->nParts;
437   for ( int i = 0 ; i < nParts ; i++ )
438   {
439     int StartIndex = anObj->panPartStart[i];
440     int EndIndex;
441     if (i != nParts - 1)
442       EndIndex = anObj->panPartStart[i + 1];
443     else
444       EndIndex = anObj->nVertices;
445
446     bool IsClosed = false;
447     HYDROData_PolylineXY::SectionType aSectType = HYDROData_PolylineXY::SECTION_POLYLINE; 
448     if (anObj->padfX[StartIndex] == anObj->padfX[EndIndex - 1] &&
449         anObj->padfY[StartIndex] == anObj->padfY[EndIndex - 1] )
450     {
451       IsClosed = true;
452       aPolylineXY->AddSection( TCollection_AsciiString( ("poly_section_" + QString::number(i)).data()->toAscii()), aSectType, true);
453     }
454     else
455       aPolylineXY->AddSection( TCollection_AsciiString( ("poly_section_" + QString::number(i)).data()->toAscii()), aSectType, false);
456     
457     if (IsClosed)
458       EndIndex--;
459     for ( int k = StartIndex; k < EndIndex ; k++ )
460     {
461       HYDROData_PolylineXY::Point aSectPoint;
462       aSectPoint.SetX( anObj->padfX[k] );
463       aSectPoint.SetY( anObj->padfY[k] );
464       aPolylineXY->AddPoint( i, aSectPoint );
465     }
466
467   }
468   
469   aPolylineXY->SetWireColor( HYDROData_PolylineXY::DefaultWireColor() );
470   aPolylineXY->SetName( theFileName + "_PolyXY_" + QString::number(theInd) );
471   
472   aPolylineXY->Update();
473   theEntities.Append(aPolylineXY);
474
475 }
476
477 void HYDROData_ShapeFile::ReadSHPPoly3D(Handle(HYDROData_Document) theDocument, SHPObject* anObj, QString theFileName, 
478   int theInd, NCollection_Sequence<Handle_HYDROData_Entity>& theEntities)
479 {
480   Handle(HYDROData_PolylineXY) aPolylineXY = Handle(HYDROData_PolylineXY)::DownCast( theDocument->CreateObject( KIND_POLYLINEXY ) );
481
482   Handle(HYDROData_Polyline3D) aPolylineObj = Handle(HYDROData_Polyline3D)::DownCast( theDocument->CreateObject( KIND_POLYLINE ) );
483
484   Handle(HYDROData_Bathymetry) aBath = Handle(HYDROData_Bathymetry)::DownCast( theDocument->CreateObject( KIND_BATHYMETRY ) );
485   HYDROData_Bathymetry::AltitudePoints aAPoints;
486
487   int nParts = anObj->nParts;
488   for ( int i = 0 ; i < nParts ; i++ )
489   {
490     //bool aSectClosure = true;
491     int StartIndex = anObj->panPartStart[i];
492     int EndIndex;
493     if (i != nParts - 1)
494       EndIndex = anObj->panPartStart[i + 1];
495     else
496       EndIndex = anObj->nVertices;
497
498     bool IsClosed = false;
499     HYDROData_PolylineXY::SectionType aSectType = HYDROData_PolylineXY::SECTION_POLYLINE; 
500     if (anObj->padfX[StartIndex] == anObj->padfX[EndIndex - 1] &&
501         anObj->padfY[StartIndex] == anObj->padfY[EndIndex - 1] &&
502         anObj->padfZ[StartIndex] == anObj->padfZ[EndIndex - 1])
503     {
504       IsClosed = true;
505       aPolylineXY->AddSection( TCollection_AsciiString( ("poly_section_" + QString::number(i)).data()->toAscii()), aSectType, true );
506     }
507     else
508       aPolylineXY->AddSection( TCollection_AsciiString( ("poly_section_" + QString::number(i)).data()->toAscii()), aSectType, false  );
509     
510     if (IsClosed)
511       EndIndex--;
512     for ( int k = StartIndex ; k < EndIndex ; k++ )
513     {
514       HYDROData_PolylineXY::Point aSectPoint;
515       aSectPoint.SetX( anObj->padfX[k] );
516       aSectPoint.SetY( anObj->padfY[k] );
517       aPolylineXY->AddPoint( i, aSectPoint );
518       aAPoints.Append(gp_XYZ (anObj->padfX[k], anObj->padfY[k], anObj->padfZ[k]));
519     }
520   }
521
522
523   QString aBathName = theFileName + "_bath_" + QString::number(theInd);
524   QString aPolyXYName = theFileName + "_polyXY_" + QString::number(theInd);
525   QString aPoly3DName = theFileName + "_poly3D_" + QString::number(theInd);
526
527   aPolylineXY->SetName( aPolyXYName );
528   aPolylineXY->SetWireColor(HYDROData_PolylineXY::DefaultWireColor());
529   aPolylineXY->Update();
530   
531   aBath->SetAltitudePoints(aAPoints);
532   aBath->SetName( aBathName );
533
534   aPolylineObj->SetPolylineXY (aPolylineXY, false);
535   aPolylineObj->SetAltitudeObject(aBath);
536
537   aPolylineObj->SetBorderColor( aPolylineObj->DefaultBorderColor() );
538   aPolylineObj->SetName( aPoly3DName );
539   
540   aPolylineObj->Update();
541   theEntities.Append(aPolylineXY);
542   theEntities.Append(aPolylineObj);
543
544 }
545
546
547
548 int HYDROData_ShapeFile::ImportPolylines(Handle(HYDROData_Document) theDocument, const QString& theFileName, 
549   NCollection_Sequence<Handle_HYDROData_Entity>& theEntities, int& theShapeTypeOfFile)
550 {
551   //Free();
552   int aStat = TryOpenShapeFile(theFileName);
553   if (aStat != 0)
554     return aStat;
555
556   HYDROData_Iterator anIter( theDocument );
557   int anInd = 0;
558   QStringList anExistingNames;
559   std::vector<int> anAllowedIndexes;
560   for( ; anIter.More(); anIter.Next() )
561     anExistingNames.push_back(anIter.Current()->GetName());
562
563   SHPHandle aHSHP;
564   aHSHP = SHPOpen( theFileName.toAscii().data(), "rb" );
565   
566   QFileInfo aFileInfo(theFileName);
567   QString aBaseFileName = aFileInfo.baseName();
568
569   if (!Parse(aHSHP, HYDROData_ShapeFile::ShapeType_Polyline, theShapeTypeOfFile))
570     return 0;
571   if (aHSHP->nShapeType == 3 || aHSHP->nShapeType == 23)
572   {
573     anInd = 0;
574     for (;anAllowedIndexes.size() < mySHPObjects.size();)
575     {
576       if (!anExistingNames.contains(aBaseFileName + "_PolyXY_" + QString::number(anInd)))
577       {
578         anAllowedIndexes.push_back(anInd);
579         anInd++;
580       }
581       else
582         anInd++;
583     }
584     
585     for (size_t i = 0; i < mySHPObjects.size(); i++ )
586     {
587       ReadSHPPolyXY(theDocument, mySHPObjects[i], aBaseFileName, anAllowedIndexes[i], theEntities);
588     }
589     aStat = 1;
590   }
591   else if (aHSHP->nShapeType == 13)
592   {
593     anInd = 0;
594     for (;anAllowedIndexes.size() < mySHPObjects.size();)
595     {
596       if (!anExistingNames.contains(aBaseFileName + "_PolyXY_" + QString::number(anInd)) &&
597           !anExistingNames.contains(aBaseFileName + "_Poly3D_" + QString::number(anInd)) &&
598           !anExistingNames.contains(aBaseFileName + "_Bath_" + QString::number(anInd)))
599       {
600         anAllowedIndexes.push_back(anInd);
601         anInd++;
602       }
603       else
604         anInd++;
605     }
606     for (size_t i = 0; i < mySHPObjects.size(); i++ )
607       ReadSHPPoly3D(theDocument, mySHPObjects[i], aBaseFileName, anAllowedIndexes[i], theEntities);
608     aStat = 1;
609   }
610   else  
611   {
612     aStat = 0;
613   }
614   
615   for (size_t i = 0; i < mySHPObjects.size(); i++ )
616     free (mySHPObjects[i]);
617
618   mySHPObjects.clear();
619   SHPClose(aHSHP);
620   return aStat;
621 }
622
623 QString HYDROData_ShapeFile::GetShapeTypeName(int theType)
624 {
625   switch (theType)
626   {
627     case 0:
628       return "null shape";
629     case 1:
630       return "point (unsupported by HYDRO)";
631     case 3:
632       return "arc/polyline (supported by HYDRO)";
633     case 5:
634       return "polygon (supported by HYDRO)";
635     case 8:
636       return "multipoint (unsupported by HYDRO)";
637     case 11:
638       return "pointZ (unsupported by HYDRO)";
639     case 13:
640       return "arcZ/polyline (supported by HYDRO)";
641     case 15:
642       return "polygonZ (unsupported by HYDRO)";
643     case 18:
644       return "multipointZ (unsupported by HYDRO)";
645     case 21:
646       return "pointM (unsupported by HYDRO)";
647     case 23:
648       return "arcM/polyline (supported by HYDRO)";
649     case 25:
650       return "polygonM (unsupported by HYDRO)";
651     case 28:
652       return "multipointM (unsupported by HYDRO)";
653     case 31:
654       return "multipatch (unsupported by HYDRO)";
655     default:
656       return "unknown";
657   }
658 }
659
660 int HYDROData_ShapeFile::TryOpenShapeFile(QString theFileName)
661 {
662   QString aSHPfile = theFileName.simplified();
663   QString aSHXfile = theFileName.simplified().replace( ".shp", ".shx", Qt::CaseInsensitive);
664   FILE* pFileSHP = NULL;
665   pFileSHP = fopen (aSHPfile.toAscii().data(), "r");
666   FILE* pFileSHX = NULL;
667   pFileSHX = fopen (aSHXfile.toAscii().data(), "r");
668
669   if (pFileSHP == NULL || pFileSHX == NULL)
670   {
671     if (pFileSHP == NULL)
672       return -1;
673     if (pFileSHX == NULL)
674       return -2;
675   }
676   
677   fclose (pFileSHP);
678   fclose (pFileSHX);
679   return 0;
680 }
681
682
683 bool HYDROData_ShapeFile::CheckDBFFileExisting(const QString& theSHPFilePath, QString& thePathToDBFFile)
684 {
685   QString aSHPfile = theSHPFilePath.simplified();
686   QString aDBFfile = theSHPFilePath.simplified().replace( ".shp", ".dbf", Qt::CaseInsensitive);
687   FILE* pFileDBF = NULL;
688   pFileDBF = fopen (aDBFfile.toAscii().data(), "r");
689
690   if (pFileDBF == NULL)
691   {
692     return false;
693   }
694   
695   fclose (pFileDBF);
696   thePathToDBFFile = aDBFfile;
697   return true;
698 }
699
700
701 bool HYDROData_ShapeFile::DBF_OpenDBF(const QString& thePathToDBFFile)
702 {
703   myHDBF = DBFOpen( thePathToDBFFile.toAscii().data(), "r" );
704   if(myHDBF != NULL)
705     return true;
706   else
707     return false;
708 }
709
710 int HYDROData_ShapeFile::DBF_GetNbFields()
711 {
712   if(myHDBF == NULL)
713     return 0;
714   return DBFGetFieldCount(myHDBF);
715 }
716
717 void HYDROData_ShapeFile::DBF_CloseDBF()
718 {
719   if(myHDBF != NULL)
720      DBFClose( myHDBF );
721 }
722
723 QStringList HYDROData_ShapeFile::DBF_GetFieldList()
724 {
725   QStringList FieldList;
726   int   nWidth, nDecimals;
727   char chField[12];
728
729   for( int i = 0; i < DBFGetFieldCount(myHDBF); i++ )
730   {
731       DBFFieldType eType;
732       eType = DBFGetFieldInfo( myHDBF, i, chField, &nWidth, &nDecimals );
733       FieldList.append(QString(chField));
734   }
735
736   return FieldList;
737 }
738
739 void HYDROData_ShapeFile::DBF_GetFieldTypeList(std::vector<DBF_FieldType>& FTVect)
740 {
741   int   nWidth, nDecimals;
742   char chField[12];
743   DBF_FieldType FT;
744   for( int i = 0; i < DBFGetFieldCount(myHDBF); i++ )
745   {
746     DBFFieldType eType;
747     eType = DBFGetFieldInfo( myHDBF, i, chField, &nWidth, &nDecimals );
748     if( eType == FTString )
749       FT = DBF_FieldType_String;
750     else if( eType == FTInteger )
751       FT = DBF_FieldType_Integer;
752     else if( eType == FTDouble )
753       FT = DBF_FieldType_Double;
754     else if( eType == FTInvalid )
755       FT = DBF_FieldType_Invalid;
756
757     FTVect.push_back(FT);
758   }
759
760 }
761
762 int HYDROData_ShapeFile::DBF_GetNbRecords()
763 {
764   if(myHDBF == NULL)
765     return 0;
766   return DBFGetRecordCount(myHDBF);
767 }
768
769 void HYDROData_ShapeFile::DBF_GetAttributeList(int theIndexOfField, std::vector<DBF_AttrValue>& theAttrV)
770 {
771   int nWidth, nDecimals;
772   char chField[12];
773   
774   for( int i = 0; i < DBFGetRecordCount(myHDBF); i++ )
775   {      
776     DBFFieldType eType;
777     DBF_AttrValue anAttr;
778     eType = DBFGetFieldInfo( myHDBF, theIndexOfField, chField, &nWidth, &nDecimals );
779
780     if( DBFIsAttributeNULL( myHDBF, i, theIndexOfField ) )
781     {
782       anAttr.myIsNull = true;
783       DBF_FieldType FT = DBF_FieldType_None;
784       if( eType == FTString )
785         FT = DBF_FieldType_String;
786       else if( eType == FTInteger )
787         FT = DBF_FieldType_Integer;
788       else if( eType == FTDouble )
789         FT = DBF_FieldType_Double;
790       else if( eType == FTInvalid )
791         FT = DBF_FieldType_Invalid;
792       anAttr.myFieldType = FT;
793     }
794     else
795     {
796       switch( eType )
797       {
798         case FTString:
799         {
800           const char* chAttr = DBFReadStringAttribute( myHDBF, i, theIndexOfField );
801           anAttr.myIsNull = false;
802           anAttr.myFieldType = DBF_FieldType_String;
803           anAttr.myRawValue = chAttr;
804           anAttr.myStrVal = QString(chAttr);
805           break;
806         }
807        
808         case FTInteger:
809         {
810           int iAttr = DBFReadIntegerAttribute( myHDBF, i, theIndexOfField );
811           anAttr.myIsNull = false;
812           anAttr.myFieldType = DBF_FieldType_Integer;
813           anAttr.myRawValue = DBFReadStringAttribute( myHDBF, i, theIndexOfField );
814           anAttr.myIntVal = iAttr;
815           break;
816         }
817           
818         case FTDouble:
819         {
820           double dAttr = DBFReadDoubleAttribute( myHDBF, i, theIndexOfField );
821           anAttr.myIsNull = false;
822           anAttr.myFieldType = DBF_FieldType_Double;
823           anAttr.myRawValue = DBFReadStringAttribute( myHDBF, i, theIndexOfField );
824           anAttr.myDoubleVal = dAttr;
825           break;
826         }
827         default:
828           break;
829       }
830     }
831     theAttrV.push_back(anAttr);
832   }
833
834 }
835
836 bool HYDROData_ShapeFile::DBF_WriteFieldAndValues(const QString& theFileName, const QString& theFieldName, DBF_FieldType theType, const std::vector<DBF_AttrValue>& theAttrV, bool bUseRawValue)
837 {
838   // Check that given field type is equal to field types of attributes values
839   for (size_t i = 0; i < theAttrV.size(); i++)
840   {
841     if (theAttrV[i].myFieldType != theType)
842       return false;
843   }
844
845   DBFHandle     hDBF;
846   hDBF = DBFCreate( theFileName.toStdString().c_str() );
847   if( hDBF == NULL )
848           return false;
849   
850   if (theType != DBF_FieldType_String && theType != DBF_FieldType_Integer && theType != DBF_FieldType_Double) 
851   {
852     DBFClose( hDBF );
853     return false; //cant handle any other cases
854   }
855
856   int nWidth = 20;
857   switch( theType )
858   {
859     case DBF_FieldType_String:
860     {
861       DBFAddField (hDBF, theFieldName.toStdString().c_str(), FTString, nWidth, 0);
862       break;
863     }
864    
865     case DBF_FieldType_Integer:
866     {
867       DBFAddField (hDBF, theFieldName.toStdString().c_str(), FTInteger, nWidth, 0);
868       break;
869     }
870       
871     case DBF_FieldType_Double:
872     {
873       DBFAddField (hDBF, theFieldName.toStdString().c_str(), FTDouble, nWidth, 0);
874       break;
875     }
876     default:
877       break;
878   }
879
880   if (DBFGetFieldCount( hDBF ) != 1) 
881   {
882     DBFClose( hDBF );
883     return false;
884   }
885   if (DBFGetRecordCount( hDBF ) != 0)
886   {
887     DBFClose( hDBF );
888     return false;
889   }
890   int stat = -1;
891
892   if (bUseRawValue)
893   {
894     for (size_t i = 0; i < theAttrV.size(); i++)
895     {
896       if (!theAttrV[i].myIsNull)
897         stat = DBFWriteStringAttribute(hDBF, (int)i, 0, theAttrV[i].myRawValue.c_str());
898       else
899         stat = DBFWriteNULLAttribute(hDBF, (int)i, 0 );
900
901       if (stat != 1)
902       {
903         DBFClose( hDBF );
904         return false;
905       }
906     }
907   }
908   else
909   {
910     for (size_t i = 0; i < theAttrV.size(); i++)
911     {
912       if (!theAttrV[i].myIsNull)
913         switch( theType )
914         {
915           case DBF_FieldType_String:
916           {
917             stat = DBFWriteStringAttribute(hDBF, (int)i, 0, theAttrV[i].myStrVal.toStdString().c_str());
918             break;
919           }
920          
921           case DBF_FieldType_Integer:
922           {
923             stat = DBFWriteIntegerAttribute(hDBF, (int)i, 0, theAttrV[i].myIntVal);
924             break;
925           }
926             
927           case DBF_FieldType_Double:
928           {
929             stat = DBFWriteDoubleAttribute(hDBF, (int)i, 0, theAttrV[i].myDoubleVal);
930             break;
931           }
932           default:
933             break;
934         }
935       else
936         stat = DBFWriteNULLAttribute(hDBF, (int)i, 0 );
937
938       if (stat != 1)
939       {
940         DBFClose( hDBF );
941         return false;
942       }
943     }
944   }
945
946   DBFClose( hDBF );
947   return true;
948
949 }