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