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