Salome HOME
0afa865a0b05595fecdbc187fd52ff9c4fc3aa28
[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::Iterator 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->FixReorder();
273     Handle(ShapeExtend_WireData) aSEWD = aSFW->WireData();
274     Standard_Integer nbE = aSEWD->NbEdges();
275     if (nbE == 0)
276       continue;
277     //
278     anPartStart.push_back(x.size());
279     NCollection_Sequence<gp_Pnt2d> aPnts;
280     for (Standard_Integer i = 1; i <= nbE; i++)
281     {
282       TopoDS_Edge E = aSEWD->Edge(i);
283       TopoDS_Vertex aV = TopExp::LastVertex(E, 1);
284       if (aV.IsNull())
285         continue;
286       gp_Pnt P = BRep_Tool::Pnt(aV);
287       aPnts.Append(gp_Pnt2d(P.X(), P.Y()));
288     }
289     NCollection_Sequence<gp_Pnt2d> aNPnts;
290     aNPnts.Append(aPnts.First());
291     for (int j = 1; j <= aPnts.Size() - 1; j++)
292     {
293       if (!aPnts(j).IsEqual(aPnts(j + 1), Precision::Confusion())) 
294         aNPnts.Append(aPnts(j + 1));
295     }
296
297     if (k == 1)
298     {
299       //an outer wire
300       //clockwise direction
301       for (int j = 1; j <= aNPnts.Size(); j++)
302       { 
303         x.push_back( aNPnts(j).X());
304         y.push_back( aNPnts(j).Y()); 
305       }
306       x.push_back( aNPnts(1).X());
307       y.push_back( aNPnts(1).Y()); 
308     }
309     else
310     {
311       //holes
312       //counter-clockwise direction
313       for (int j = aNPnts.Size(); j > 0; j--)
314       { 
315         x.push_back( aNPnts(j).X());
316         y.push_back( aNPnts(j).Y()); 
317       }
318       x.push_back( aNPnts(aNPnts.Size()).X());
319       y.push_back( aNPnts(aNPnts.Size()).Y()); 
320     }
321   }
322   
323   aSHPObj = SHPCreateObject( SHPT_POLYGON, -1, NbWires, &anPartStart[0], NULL, x.size(), &x[0], &y[0], NULL, NULL );
324   SHPWriteObject( theShpHandle, -1, aSHPObj );
325   SHPDestroyObject( aSHPObj );
326
327 }
328
329 bool HYDROData_ShapeFile::Parse(SHPHandle theHandle, ShapeType theType, int& theShapeTypeOfFile)
330 {
331   int aShapeType;
332   mySHPObjects.clear();
333   SHPGetInfo( theHandle, NULL, &aShapeType, NULL, NULL );
334   theShapeTypeOfFile = aShapeType;
335   bool ToRead = (theType == ShapeType_Polyline && (aShapeType == 3 || aShapeType == 13 || aShapeType == 23)) ||
336    (theType == ShapeType_Polygon && aShapeType == 5);
337   if (ToRead) 
338   {
339     for (int i = 0; i < theHandle->nRecords; i++) 
340       mySHPObjects.push_back(SHPReadObject(theHandle, i));
341     return true;
342   }
343   else
344     return false;
345 }
346
347 void HYDROData_ShapeFile::ReadSHPPolygon(SHPObject* anObj, int i, TopoDS_Face& F)
348 {
349   if (!anObj)
350     return;
351   TopoDS_Wire W;
352   TopoDS_Edge E; 
353   int nParts = anObj->nParts;
354   gp_Pln pln(gp_Pnt(0,0,0), gp_Dir(0,0,1));
355
356   //Handle(ShapeFix_Shape) sfs = new ShapeFix_Shape;
357   //sfs->FixFaceTool()->FixOrientationMode() = 1;
358   TopTools_SequenceOfShape aWires;
359   for ( int i = 0 ; i < nParts ; i++ )
360   { 
361     BRepBuilderAPI_MakeWire aBuilder;
362     int StartIndex = anObj->panPartStart[i];
363     int EndIndex;
364     if (i != nParts - 1)
365       EndIndex = anObj->panPartStart[i + 1];
366     else
367       EndIndex = anObj->nVertices;
368
369     for ( int k = StartIndex; k < EndIndex - 1  ; k++ )
370     {
371       gp_Pnt P1 (anObj->padfX[k], anObj->padfY[k], 0);
372       gp_Pnt P2 (anObj->padfX[k+1], anObj->padfY[k+1], 0);
373       if (P1.Distance(P2) < Precision::Confusion())
374         continue;
375       BRepBuilderAPI_MakeEdge aMakeEdge(P1, P2);
376       aBuilder.Add(TopoDS::Edge(aMakeEdge.Shape()));
377     }
378     
379     aBuilder.Build();
380     W = TopoDS::Wire(aBuilder.Shape());
381     W.Orientation(TopAbs_FORWARD);
382     BRepBuilderAPI_MakeFace aDB(pln, W);
383     TopoDS_Face aDummyFace = TopoDS::Face(aDB.Shape());
384     BRepTopAdaptor_FClass2d FClass(aDummyFace, Precision::PConfusion());
385     if ( i == 0 && FClass.PerformInfinitePoint() == TopAbs_OUT) 
386       W.Reverse();
387     if ( i > 0 && FClass.PerformInfinitePoint() != TopAbs_IN) 
388       W.Reverse();
389    
390     aWires.Append(W);
391   }
392   
393   BRepBuilderAPI_MakeFace aFBuilder(pln, TopoDS::Wire(aWires(1)));
394   for (int i = 2; i <= aWires.Length(); i++)
395     aFBuilder.Add(TopoDS::Wire(aWires(i)));
396   F = TopoDS::Face(aFBuilder.Shape());
397
398   BRepLib::BuildCurves3d(F);  
399 }
400
401 int HYDROData_ShapeFile::ImportPolygons(const QString theFileName, QStringList& thePolygonsList, TopTools_SequenceOfShape& theFaces, int& theShapeTypeOfFile)
402 {
403   Free();
404   int Stat = TryOpenShapeFile(theFileName);
405   if (Stat != 0)
406     return Stat;
407   myHSHP = SHPOpen( theFileName.toAscii().data(), "rb" );
408   if (!Parse(myHSHP, HYDROData_ShapeFile::ShapeType_Polygon, theShapeTypeOfFile))
409     return 0;
410   for (size_t i = 0; i < mySHPObjects.size(); i++)
411     thePolygonsList.append("polygon_" + QString::number(i + 1));
412    
413   TopoDS_Face aF;
414   if (myHSHP->nShapeType == 5)
415   {
416     for (size_t i = 0; i < mySHPObjects.size(); i++) 
417     {
418        ReadSHPPolygon(mySHPObjects[i], i, aF);
419        theFaces.Append(aF);
420     }
421     return 1;
422   }
423   else
424     return 0;
425 }
426
427 void HYDROData_ShapeFile::Free()
428 {  
429   for (size_t i = 0; i < mySHPObjects.size(); i++ )
430     free (mySHPObjects[i]);
431
432   mySHPObjects.clear();
433   if (myHSHP != NULL)
434   {
435     SHPClose(myHSHP);
436     myHSHP = NULL; 
437   }
438 }
439
440
441 void HYDROData_ShapeFile::ReadSHPPolyXY(Handle(HYDROData_Document) theDocument, SHPObject* anObj, QString theFileName, 
442   int theInd, NCollection_Sequence<Handle_HYDROData_Entity>& theEntities)
443 {
444
445   Handle(HYDROData_PolylineXY) aPolylineXY = Handle(HYDROData_PolylineXY)::DownCast( theDocument->CreateObject( KIND_POLYLINEXY ) );
446   
447   int nParts = anObj->nParts;
448   for ( int i = 0 ; i < nParts ; i++ )
449   {
450     int StartIndex = anObj->panPartStart[i];
451     int EndIndex;
452     if (i != nParts - 1)
453       EndIndex = anObj->panPartStart[i + 1];
454     else
455       EndIndex = anObj->nVertices;
456
457     bool IsClosed = false;
458     HYDROData_PolylineXY::SectionType aSectType = HYDROData_PolylineXY::SECTION_POLYLINE; 
459     if (anObj->padfX[StartIndex] == anObj->padfX[EndIndex - 1] &&
460         anObj->padfY[StartIndex] == anObj->padfY[EndIndex - 1] )
461     {
462       IsClosed = true;
463       aPolylineXY->AddSection( TCollection_AsciiString( ("poly_section_" + QString::number(i)).data()->toAscii()), aSectType, true);
464     }
465     else
466       aPolylineXY->AddSection( TCollection_AsciiString( ("poly_section_" + QString::number(i)).data()->toAscii()), aSectType, false);
467     
468     if (IsClosed)
469       EndIndex--;
470     for ( int k = StartIndex; k < EndIndex ; k++ )
471     {
472       HYDROData_PolylineXY::Point aSectPoint;
473       aSectPoint.SetX( anObj->padfX[k] );
474       aSectPoint.SetY( anObj->padfY[k] );
475       aPolylineXY->AddPoint( i, aSectPoint );
476     }
477
478   }
479   
480   aPolylineXY->SetWireColor( HYDROData_PolylineXY::DefaultWireColor() );
481   aPolylineXY->SetName( theFileName + "_PolyXY_" + QString::number(theInd) );
482   
483   aPolylineXY->Update();
484   theEntities.Append(aPolylineXY);
485
486 }
487
488 void HYDROData_ShapeFile::ReadSHPPoly3D(Handle(HYDROData_Document) theDocument, SHPObject* anObj, QString theFileName, 
489   int theInd, NCollection_Sequence<Handle_HYDROData_Entity>& theEntities)
490 {
491   Handle(HYDROData_PolylineXY) aPolylineXY = Handle(HYDROData_PolylineXY)::DownCast( theDocument->CreateObject( KIND_POLYLINEXY ) );
492
493   Handle(HYDROData_Polyline3D) aPolylineObj = Handle(HYDROData_Polyline3D)::DownCast( theDocument->CreateObject( KIND_POLYLINE ) );
494
495   Handle(HYDROData_Bathymetry) aBath = Handle(HYDROData_Bathymetry)::DownCast( theDocument->CreateObject( KIND_BATHYMETRY ) );
496   HYDROData_Bathymetry::AltitudePoints aAPoints;
497
498   int nParts = anObj->nParts;
499   for ( int i = 0 ; i < nParts ; i++ )
500   {
501     //bool aSectClosure = true;
502     int StartIndex = anObj->panPartStart[i];
503     int EndIndex;
504     if (i != nParts - 1)
505       EndIndex = anObj->panPartStart[i + 1];
506     else
507       EndIndex = anObj->nVertices;
508
509     bool IsClosed = false;
510     HYDROData_PolylineXY::SectionType aSectType = HYDROData_PolylineXY::SECTION_POLYLINE; 
511     if (anObj->padfX[StartIndex] == anObj->padfX[EndIndex - 1] &&
512         anObj->padfY[StartIndex] == anObj->padfY[EndIndex - 1] &&
513         anObj->padfZ[StartIndex] == anObj->padfZ[EndIndex - 1])
514     {
515       IsClosed = true;
516       aPolylineXY->AddSection( TCollection_AsciiString( ("poly_section_" + QString::number(i)).data()->toAscii()), aSectType, true );
517     }
518     else
519       aPolylineXY->AddSection( TCollection_AsciiString( ("poly_section_" + QString::number(i)).data()->toAscii()), aSectType, false  );
520     
521     if (IsClosed)
522       EndIndex--;
523     for ( int k = StartIndex ; k < EndIndex ; k++ )
524     {
525       HYDROData_PolylineXY::Point aSectPoint;
526       aSectPoint.SetX( anObj->padfX[k] );
527       aSectPoint.SetY( anObj->padfY[k] );
528       aPolylineXY->AddPoint( i, aSectPoint );
529       aAPoints.Append(gp_XYZ (anObj->padfX[k], anObj->padfY[k], anObj->padfZ[k]));
530     }
531   }
532
533
534   QString aBathName = theFileName + "_bath_" + QString::number(theInd);
535   QString aPolyXYName = theFileName + "_polyXY_" + QString::number(theInd);
536   QString aPoly3DName = theFileName + "_poly3D_" + QString::number(theInd);
537
538   aPolylineXY->SetName( aPolyXYName );
539   aPolylineXY->SetWireColor(HYDROData_PolylineXY::DefaultWireColor());
540   aPolylineXY->Update();
541   
542   aBath->SetAltitudePoints(aAPoints);
543   aBath->SetName( aBathName );
544
545   aPolylineObj->SetPolylineXY (aPolylineXY, false);
546   aPolylineObj->SetAltitudeObject(aBath);
547
548   aPolylineObj->SetBorderColor( aPolylineObj->DefaultBorderColor() );
549   aPolylineObj->SetName( aPoly3DName );
550   
551   aPolylineObj->Update();
552   theEntities.Append(aPolylineXY);
553   theEntities.Append(aPolylineObj);
554
555 }
556
557
558
559 int HYDROData_ShapeFile::ImportPolylines(Handle(HYDROData_Document) theDocument, const QString& theFileName, 
560   NCollection_Sequence<Handle_HYDROData_Entity>& theEntities, int& theShapeTypeOfFile)
561 {
562   //Free();
563   int aStat = TryOpenShapeFile(theFileName);
564   if (aStat != 0)
565     return aStat;
566
567   HYDROData_Iterator anIter( theDocument );
568   int anInd = 0;
569   QStringList anExistingNames;
570   std::vector<int> anAllowedIndexes;
571   for( ; anIter.More(); anIter.Next() )
572     anExistingNames.push_back(anIter.Current()->GetName());
573
574   SHPHandle aHSHP;
575   aHSHP = SHPOpen( theFileName.toAscii().data(), "rb" );
576   
577   QFileInfo aFileInfo(theFileName);
578   QString aBaseFileName = aFileInfo.baseName();
579
580   if (!Parse(aHSHP, HYDROData_ShapeFile::ShapeType_Polyline, theShapeTypeOfFile))
581     return 0;
582   if (aHSHP->nShapeType == 3 || aHSHP->nShapeType == 23)
583   {
584     anInd = 0;
585     for (;anAllowedIndexes.size() < mySHPObjects.size();)
586     {
587       if (!anExistingNames.contains(aBaseFileName + "_PolyXY_" + QString::number(anInd)))
588       {
589         anAllowedIndexes.push_back(anInd);
590         anInd++;
591       }
592       else
593         anInd++;
594     }
595     
596     for (size_t i = 0; i < mySHPObjects.size(); i++ )
597     {
598       ReadSHPPolyXY(theDocument, mySHPObjects[i], aBaseFileName, anAllowedIndexes[i], theEntities);
599     }
600     aStat = 1;
601   }
602   else if (aHSHP->nShapeType == 13)
603   {
604     anInd = 0;
605     for (;anAllowedIndexes.size() < mySHPObjects.size();)
606     {
607       if (!anExistingNames.contains(aBaseFileName + "_PolyXY_" + QString::number(anInd)) &&
608           !anExistingNames.contains(aBaseFileName + "_Poly3D_" + QString::number(anInd)) &&
609           !anExistingNames.contains(aBaseFileName + "_Bath_" + QString::number(anInd)))
610       {
611         anAllowedIndexes.push_back(anInd);
612         anInd++;
613       }
614       else
615         anInd++;
616     }
617     for (size_t i = 0; i < mySHPObjects.size(); i++ )
618       ReadSHPPoly3D(theDocument, mySHPObjects[i], aBaseFileName, anAllowedIndexes[i], theEntities);
619     aStat = 1;
620   }
621   else  
622   {
623     aStat = 0;
624   }
625   
626   for (size_t i = 0; i < mySHPObjects.size(); i++ )
627     free (mySHPObjects[i]);
628
629   mySHPObjects.clear();
630   SHPClose(aHSHP);
631   return aStat;
632 }
633
634 QString HYDROData_ShapeFile::GetShapeTypeName(int theType)
635 {
636   switch (theType)
637   {
638     case 0:
639       return "null shape";
640     case 1:
641       return "point (unsupported by HYDRO)";
642     case 3:
643       return "arc/polyline (supported by HYDRO)";
644     case 5:
645       return "polygon (supported by HYDRO)";
646     case 8:
647       return "multipoint (unsupported by HYDRO)";
648     case 11:
649       return "pointZ (unsupported by HYDRO)";
650     case 13:
651       return "arcZ/polyline (supported by HYDRO)";
652     case 15:
653       return "polygonZ (unsupported by HYDRO)";
654     case 18:
655       return "multipointZ (unsupported by HYDRO)";
656     case 21:
657       return "pointM (unsupported by HYDRO)";
658     case 23:
659       return "arcM/polyline (supported by HYDRO)";
660     case 25:
661       return "polygonM (unsupported by HYDRO)";
662     case 28:
663       return "multipointM (unsupported by HYDRO)";
664     case 31:
665       return "multipatch (unsupported by HYDRO)";
666     default:
667       return "unknown";
668   }
669 }
670
671 int HYDROData_ShapeFile::TryOpenShapeFile(QString theFileName)
672 {
673   QString aSHPfile = theFileName.simplified();
674   QString aSHXfile = theFileName.simplified().replace( ".shp", ".shx", Qt::CaseInsensitive);
675   FILE* pFileSHP = NULL;
676   pFileSHP = fopen (aSHPfile.toAscii().data(), "r");
677   FILE* pFileSHX = NULL;
678   pFileSHX = fopen (aSHXfile.toAscii().data(), "r");
679
680   if (pFileSHP == NULL || pFileSHX == NULL)
681   {
682     if (pFileSHP == NULL)
683       return -1;
684     if (pFileSHX == NULL)
685       return -2;
686   }
687   
688   fclose (pFileSHP);
689   fclose (pFileSHX);
690   return 0;
691 }
692
693
694 bool HYDROData_ShapeFile::CheckDBFFileExisting(const QString& theSHPFilePath, QString& thePathToDBFFile)
695 {
696   QString aSHPfile = theSHPFilePath.simplified();
697   QString aDBFfile = theSHPFilePath.simplified().replace( ".shp", ".dbf", Qt::CaseInsensitive);
698   FILE* pFileDBF = NULL;
699   pFileDBF = fopen (aDBFfile.toAscii().data(), "r");
700
701   if (pFileDBF == NULL)
702   {
703     return false;
704   }
705   
706   fclose (pFileDBF);
707   thePathToDBFFile = aDBFfile;
708   return true;
709 }
710
711
712 bool HYDROData_ShapeFile::DBF_OpenDBF(const QString& thePathToDBFFile)
713 {
714   myHDBF = DBFOpen( thePathToDBFFile.toAscii().data(), "r" );
715   if(myHDBF != NULL)
716     return true;
717   else
718     return false;
719 }
720
721 int HYDROData_ShapeFile::DBF_GetNbFields()
722 {
723   if(myHDBF == NULL)
724     return 0;
725   return DBFGetFieldCount(myHDBF);
726 }
727
728 void HYDROData_ShapeFile::DBF_CloseDBF()
729 {
730   if(myHDBF != NULL)
731      DBFClose( myHDBF );
732 }
733
734 QStringList HYDROData_ShapeFile::DBF_GetFieldList()
735 {
736   QStringList FieldList;
737   int   nWidth, nDecimals;
738   char chField[12];
739
740   for( int i = 0; i < DBFGetFieldCount(myHDBF); i++ )
741   {
742       DBFFieldType eType;
743       eType = DBFGetFieldInfo( myHDBF, i, chField, &nWidth, &nDecimals );
744       FieldList.append(QString(chField));
745   }
746
747   return FieldList;
748 }
749
750 void HYDROData_ShapeFile::DBF_GetFieldTypeList(std::vector<DBF_FieldType>& FTVect)
751 {
752   int   nWidth, nDecimals;
753   char chField[12];
754   DBF_FieldType FT;
755   for( int i = 0; i < DBFGetFieldCount(myHDBF); i++ )
756   {
757     DBFFieldType eType;
758     eType = DBFGetFieldInfo( myHDBF, i, chField, &nWidth, &nDecimals );
759     if( eType == FTString )
760       FT = DBF_FieldType_String;
761     else if( eType == FTInteger )
762       FT = DBF_FieldType_Integer;
763     else if( eType == FTDouble )
764       FT = DBF_FieldType_Double;
765     else if( eType == FTInvalid )
766       FT = DBF_FieldType_Invalid;
767
768     FTVect.push_back(FT);
769   }
770
771 }
772
773 int HYDROData_ShapeFile::DBF_GetNbRecords()
774 {
775   if(myHDBF == NULL)
776     return 0;
777   return DBFGetRecordCount(myHDBF);
778 }
779
780 void HYDROData_ShapeFile::DBF_GetAttributeList(int theIndexOfField, std::vector<DBF_AttrValue>& theAttrV)
781 {
782   int nWidth, nDecimals;
783   char chField[12];
784   
785   for( int i = 0; i < DBFGetRecordCount(myHDBF); i++ )
786   {      
787     DBFFieldType eType;
788     DBF_AttrValue anAttr;
789     eType = DBFGetFieldInfo( myHDBF, theIndexOfField, chField, &nWidth, &nDecimals );
790
791     if( DBFIsAttributeNULL( myHDBF, i, theIndexOfField ) )
792     {
793       anAttr.myIsNull = true;
794       DBF_FieldType FT = DBF_FieldType_None;
795       if( eType == FTString )
796         FT = DBF_FieldType_String;
797       else if( eType == FTInteger )
798         FT = DBF_FieldType_Integer;
799       else if( eType == FTDouble )
800         FT = DBF_FieldType_Double;
801       else if( eType == FTInvalid )
802         FT = DBF_FieldType_Invalid;
803       anAttr.myFieldType = FT;
804     }
805     else
806     {
807       switch( eType )
808       {
809         case FTString:
810         {
811           const char* chAttr = DBFReadStringAttribute( myHDBF, i, theIndexOfField );
812           anAttr.myIsNull = false;
813           anAttr.myFieldType = DBF_FieldType_String;
814           anAttr.myRawValue = chAttr;
815           anAttr.myStrVal = QString(chAttr);
816           break;
817         }
818        
819         case FTInteger:
820         {
821           int iAttr = DBFReadIntegerAttribute( myHDBF, i, theIndexOfField );
822           anAttr.myIsNull = false;
823           anAttr.myFieldType = DBF_FieldType_Integer;
824           anAttr.myRawValue = DBFReadStringAttribute( myHDBF, i, theIndexOfField );
825           anAttr.myIntVal = iAttr;
826           break;
827         }
828           
829         case FTDouble:
830         {
831           double dAttr = DBFReadDoubleAttribute( myHDBF, i, theIndexOfField );
832           anAttr.myIsNull = false;
833           anAttr.myFieldType = DBF_FieldType_Double;
834           anAttr.myRawValue = DBFReadStringAttribute( myHDBF, i, theIndexOfField );
835           anAttr.myDoubleVal = dAttr;
836           break;
837         }
838         default:
839           break;
840       }
841     }
842     theAttrV.push_back(anAttr);
843   }
844
845 }
846
847 bool HYDROData_ShapeFile::DBF_WriteFieldAndValues(const QString& theFileName, const QString& theFieldName, DBF_FieldType theType, const std::vector<DBF_AttrValue>& theAttrV, bool bUseRawValue)
848 {
849   // Check that given field type is equal to field types of attributes values
850   for (size_t i = 0; i < theAttrV.size(); i++)
851   {
852     if (theAttrV[i].myFieldType != theType)
853       return false;
854   }
855
856   DBFHandle     hDBF;
857   hDBF = DBFCreate( theFileName.toStdString().c_str() );
858   if( hDBF == NULL )
859           return false;
860   
861   if (theType != DBF_FieldType_String && theType != DBF_FieldType_Integer && theType != DBF_FieldType_Double) 
862   {
863     DBFClose( hDBF );
864     return false; //cant handle any other cases
865   }
866
867   int nWidth = 20;
868   switch( theType )
869   {
870     case DBF_FieldType_String:
871     {
872       DBFAddField (hDBF, theFieldName.toStdString().c_str(), FTString, nWidth, 0);
873       break;
874     }
875    
876     case DBF_FieldType_Integer:
877     {
878       DBFAddField (hDBF, theFieldName.toStdString().c_str(), FTInteger, nWidth, 0);
879       break;
880     }
881       
882     case DBF_FieldType_Double:
883     {
884       DBFAddField (hDBF, theFieldName.toStdString().c_str(), FTDouble, nWidth, 0);
885       break;
886     }
887     default:
888       break;
889   }
890
891   if (DBFGetFieldCount( hDBF ) != 1) 
892   {
893     DBFClose( hDBF );
894     return false;
895   }
896   if (DBFGetRecordCount( hDBF ) != 0)
897   {
898     DBFClose( hDBF );
899     return false;
900   }
901   int stat = -1;
902
903   if (bUseRawValue)
904   {
905     for (size_t i = 0; i < theAttrV.size(); i++)
906     {
907       if (!theAttrV[i].myIsNull)
908         stat = DBFWriteStringAttribute(hDBF, (int)i, 0, theAttrV[i].myRawValue.c_str());
909       else
910         stat = DBFWriteNULLAttribute(hDBF, (int)i, 0 );
911
912       if (stat != 1)
913       {
914         DBFClose( hDBF );
915         return false;
916       }
917     }
918   }
919   else
920   {
921     for (size_t i = 0; i < theAttrV.size(); i++)
922     {
923       if (!theAttrV[i].myIsNull)
924         switch( theType )
925         {
926           case DBF_FieldType_String:
927           {
928             stat = DBFWriteStringAttribute(hDBF, (int)i, 0, theAttrV[i].myStrVal.toStdString().c_str());
929             break;
930           }
931          
932           case DBF_FieldType_Integer:
933           {
934             stat = DBFWriteIntegerAttribute(hDBF, (int)i, 0, theAttrV[i].myIntVal);
935             break;
936           }
937             
938           case DBF_FieldType_Double:
939           {
940             stat = DBFWriteDoubleAttribute(hDBF, (int)i, 0, theAttrV[i].myDoubleVal);
941             break;
942           }
943           default:
944             break;
945         }
946       else
947         stat = DBFWriteNULLAttribute(hDBF, (int)i, 0 );
948
949       if (stat != 1)
950       {
951         DBFClose( hDBF );
952         return false;
953       }
954     }
955   }
956
957   DBFClose( hDBF );
958   return true;
959
960 }