Salome HOME
5f48cb2adfbb4e921ddbf7ed649143c0ebf715e5
[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   NCollection_Sequence<NCollection_Sequence<TopoDS_Edge> > allEdges;
380
381   TopTools_SequenceOfShape aWires;
382   for ( int i = 0 ; i < nParts ; i++ )
383   { 
384     BRepBuilderAPI_MakeWire aBuilder;
385     int StartIndex = anObj->panPartStart[i];
386     int EndIndex;
387     if (i != nParts - 1)
388       EndIndex = anObj->panPartStart[i + 1];
389     else
390       EndIndex = anObj->nVertices;
391
392     NCollection_Sequence<TopoDS_Edge> EPerW;
393
394     //First point is same as the last point 
395     int NbPnts = EndIndex - StartIndex - 1;
396     NCollection_Array1<TopoDS_Vertex> VPoints(0, NbPnts);
397     int j = NbPnts;
398     for ( int k = StartIndex; k < EndIndex; k++ )
399     {
400       gp_Pnt P (anObj->padfX[k], anObj->padfY[k], 0);
401       VPoints.ChangeValue(j) = BRepLib_MakeVertex(P).Vertex();
402       j--;
403     }
404       
405     for ( int k = 0; k < VPoints.Size() - 1; k++ )
406     {
407       gp_Pnt P1 = BRep_Tool::Pnt(VPoints(k));
408       gp_Pnt P2 = BRep_Tool::Pnt(VPoints(k + 1));
409       if (P1.Distance(P2) < Precision::Confusion())
410         continue;
411       Handle_Geom_TrimmedCurve aTC = GC_MakeSegment(P1, P2).Value();
412       TopoDS_Edge E;
413       if ( k != VPoints.Size() - 2)
414         E = BRepLib_MakeEdge(aTC, VPoints(k), VPoints(k + 1)).Edge();
415       else
416         //the last edge => use first and last vertices
417         E = BRepLib_MakeEdge(aTC, VPoints.First(), VPoints.Value(VPoints.Upper() - 1)).Edge();
418       //Add edge to wire
419       //If SHP file is correct then the outer wire and the holes will have the correct orientations
420       
421       EPerW.Append(E);
422     }
423     allEdges.Append(EPerW);
424   }
425
426   for (int i = 1; i <= allEdges.Size(); i++)
427   {
428     TopoDS_Wire W;
429     BB.MakeWire(W);
430     for (int j = 1; j <= allEdges(i).Size(); j++)
431       BB.Add(W, allEdges(i)(j));
432     W.Closed (Standard_True);
433     W.Orientation(TopAbs_FORWARD);
434     //check on the dummy face first
435     TopoDS_Face DF;
436     BB.MakeFace(DF);
437     BB.Add(DF, W);
438     BB.UpdateFace(DF, aPlaneSur, TopLoc_Location(), Precision::Confusion());
439     //
440     BRepTopAdaptor_FClass2d FClass(DF, Precision::PConfusion());
441     if ( i == 1 && FClass.PerformInfinitePoint() != TopAbs_OUT) 
442       W.Reverse();
443     if ( i > 1 && FClass.PerformInfinitePoint() != TopAbs_IN) 
444       W.Reverse();
445     //
446     BB.Add(F, W);
447   }
448   
449   //Add surface to the face
450   BB.UpdateFace(F, aPlaneSur, TopLoc_Location(), Precision::Confusion());
451   F.Closed(Standard_True);
452 }
453
454 int HYDROData_ShapeFile::ImportPolygons(const QString theFileName, QStringList& thePolygonsList, TopTools_SequenceOfShape& theFaces, int& theShapeTypeOfFile)
455 {
456   Free();
457   int Stat = TryOpenShapeFile(theFileName);
458   if (Stat != 0)
459     return Stat;
460   myHSHP = SHPOpen( theFileName.toAscii().data(), "rb" );
461   if (!Parse(myHSHP, HYDROData_ShapeFile::ShapeType_Polygon, theShapeTypeOfFile))
462     return 0;
463   for (size_t i = 0; i < mySHPObjects.size(); i++)
464     thePolygonsList.append("polygon_" + QString::number(i + 1));
465    
466   TopoDS_Face aF;
467   if (myHSHP->nShapeType == 5)
468   {
469 #ifdef OSD_TIMER
470     OSD_Timer timer;
471     timer.Start();
472 #endif
473     for (size_t i = 0; i < mySHPObjects.size(); i++) 
474     {
475        ReadSHPPolygon(mySHPObjects[i], i, aF);
476        theFaces.Append(aF);
477     }
478 #ifdef OSD_TIMER
479     timer.Stop();
480     timer.Show();
481 #endif
482     return 1;
483   }
484   else
485     return 0;
486 }
487
488 void HYDROData_ShapeFile::Free()
489 {  
490   for (size_t i = 0; i < mySHPObjects.size(); i++ )
491     free (mySHPObjects[i]);
492
493   mySHPObjects.clear();
494   if (myHSHP != NULL)
495   {
496     SHPClose(myHSHP);
497     myHSHP = NULL; 
498   }
499 }
500
501
502 void HYDROData_ShapeFile::ReadSHPPolyXY(Handle(HYDROData_Document) theDocument, SHPObject* anObj, QString theFileName, 
503   int theInd, NCollection_Sequence<Handle_HYDROData_Entity>& theEntities)
504 {
505
506   Handle(HYDROData_PolylineXY) aPolylineXY = Handle(HYDROData_PolylineXY)::DownCast( theDocument->CreateObject( KIND_POLYLINEXY ) );
507   
508   int nParts = anObj->nParts;
509   for ( int i = 0 ; i < nParts ; i++ )
510   {
511     int StartIndex = anObj->panPartStart[i];
512     int EndIndex;
513     if (i != nParts - 1)
514       EndIndex = anObj->panPartStart[i + 1];
515     else
516       EndIndex = anObj->nVertices;
517
518     bool IsClosed = false;
519     HYDROData_PolylineXY::SectionType aSectType = HYDROData_PolylineXY::SECTION_POLYLINE; 
520     if (anObj->padfX[StartIndex] == anObj->padfX[EndIndex - 1] &&
521         anObj->padfY[StartIndex] == anObj->padfY[EndIndex - 1] )
522     {
523       IsClosed = true;
524       aPolylineXY->AddSection( TCollection_AsciiString( ("poly_section_" + QString::number(i)).data()->toAscii()), aSectType, true);
525     }
526     else
527       aPolylineXY->AddSection( TCollection_AsciiString( ("poly_section_" + QString::number(i)).data()->toAscii()), aSectType, false);
528     
529     if (IsClosed)
530       EndIndex--;
531     for ( int k = StartIndex; k < EndIndex ; k++ )
532     {
533       HYDROData_PolylineXY::Point aSectPoint;
534       aSectPoint.SetX( anObj->padfX[k] );
535       aSectPoint.SetY( anObj->padfY[k] );
536       aPolylineXY->AddPoint( i, aSectPoint );
537     }
538
539   }
540   
541   aPolylineXY->SetWireColor( HYDROData_PolylineXY::DefaultWireColor() );
542   aPolylineXY->SetName( theFileName + "_PolyXY_" + QString::number(theInd) );
543   
544   aPolylineXY->Update();
545   theEntities.Append(aPolylineXY);
546
547 }
548
549 void HYDROData_ShapeFile::ReadSHPPoly3D(Handle(HYDROData_Document) theDocument, SHPObject* anObj, QString theFileName, 
550   int theInd, NCollection_Sequence<Handle_HYDROData_Entity>& theEntities)
551 {
552   Handle(HYDROData_PolylineXY) aPolylineXY = Handle(HYDROData_PolylineXY)::DownCast( theDocument->CreateObject( KIND_POLYLINEXY ) );
553
554   Handle(HYDROData_Polyline3D) aPolylineObj = Handle(HYDROData_Polyline3D)::DownCast( theDocument->CreateObject( KIND_POLYLINE ) );
555
556   Handle(HYDROData_Bathymetry) aBath = Handle(HYDROData_Bathymetry)::DownCast( theDocument->CreateObject( KIND_BATHYMETRY ) );
557   HYDROData_Bathymetry::AltitudePoints aAPoints;
558
559   int nParts = anObj->nParts;
560   for ( int i = 0 ; i < nParts ; i++ )
561   {
562     //bool aSectClosure = true;
563     int StartIndex = anObj->panPartStart[i];
564     int EndIndex;
565     if (i != nParts - 1)
566       EndIndex = anObj->panPartStart[i + 1];
567     else
568       EndIndex = anObj->nVertices;
569
570     bool IsClosed = false;
571     HYDROData_PolylineXY::SectionType aSectType = HYDROData_PolylineXY::SECTION_POLYLINE; 
572     if (anObj->padfX[StartIndex] == anObj->padfX[EndIndex - 1] &&
573         anObj->padfY[StartIndex] == anObj->padfY[EndIndex - 1] &&
574         anObj->padfZ[StartIndex] == anObj->padfZ[EndIndex - 1])
575     {
576       IsClosed = true;
577       aPolylineXY->AddSection( TCollection_AsciiString( ("poly_section_" + QString::number(i)).data()->toAscii()), aSectType, true );
578     }
579     else
580       aPolylineXY->AddSection( TCollection_AsciiString( ("poly_section_" + QString::number(i)).data()->toAscii()), aSectType, false  );
581     
582     if (IsClosed)
583       EndIndex--;
584     for ( int k = StartIndex ; k < EndIndex ; k++ )
585     {
586       HYDROData_PolylineXY::Point aSectPoint;
587       aSectPoint.SetX( anObj->padfX[k] );
588       aSectPoint.SetY( anObj->padfY[k] );
589       aPolylineXY->AddPoint( i, aSectPoint );
590       aAPoints.Append(gp_XYZ (anObj->padfX[k], anObj->padfY[k], anObj->padfZ[k]));
591     }
592   }
593
594
595   QString aBathName = theFileName + "_bath_" + QString::number(theInd);
596   QString aPolyXYName = theFileName + "_polyXY_" + QString::number(theInd);
597   QString aPoly3DName = theFileName + "_poly3D_" + QString::number(theInd);
598
599   aPolylineXY->SetName( aPolyXYName );
600   aPolylineXY->SetWireColor(HYDROData_PolylineXY::DefaultWireColor());
601   aPolylineXY->Update();
602   
603   aBath->SetAltitudePoints(aAPoints);
604   aBath->SetName( aBathName );
605
606   aPolylineObj->SetPolylineXY (aPolylineXY, false);
607   aPolylineObj->SetAltitudeObject(aBath);
608
609   aPolylineObj->SetBorderColor( aPolylineObj->DefaultBorderColor() );
610   aPolylineObj->SetName( aPoly3DName );
611   
612   aPolylineObj->Update();
613   theEntities.Append(aPolylineXY);
614   theEntities.Append(aPolylineObj);
615
616 }
617
618
619
620 int HYDROData_ShapeFile::ImportPolylines(Handle(HYDROData_Document) theDocument, const QString& theFileName, 
621   NCollection_Sequence<Handle_HYDROData_Entity>& theEntities, int& theShapeTypeOfFile)
622 {
623   //Free();
624   int aStat = TryOpenShapeFile(theFileName);
625   if (aStat != 0)
626     return aStat;
627
628   HYDROData_Iterator anIter( theDocument );
629   int anInd = 0;
630   QStringList anExistingNames;
631   std::vector<int> anAllowedIndexes;
632   for( ; anIter.More(); anIter.Next() )
633     anExistingNames.push_back(anIter.Current()->GetName());
634
635   SHPHandle aHSHP;
636   aHSHP = SHPOpen( theFileName.toAscii().data(), "rb" );
637   
638   QFileInfo aFileInfo(theFileName);
639   QString aBaseFileName = aFileInfo.baseName();
640
641   if (!Parse(aHSHP, HYDROData_ShapeFile::ShapeType_Polyline, theShapeTypeOfFile))
642     return 0;
643   if (aHSHP->nShapeType == 3 || aHSHP->nShapeType == 23)
644   {
645     anInd = 0;
646     for (;anAllowedIndexes.size() < mySHPObjects.size();)
647     {
648       if (!anExistingNames.contains(aBaseFileName + "_PolyXY_" + QString::number(anInd)))
649       {
650         anAllowedIndexes.push_back(anInd);
651         anInd++;
652       }
653       else
654         anInd++;
655     }
656     
657     for (size_t i = 0; i < mySHPObjects.size(); i++ )
658     {
659       ReadSHPPolyXY(theDocument, mySHPObjects[i], aBaseFileName, anAllowedIndexes[i], theEntities);
660     }
661     aStat = 1;
662   }
663   else if (aHSHP->nShapeType == 13)
664   {
665     anInd = 0;
666     for (;anAllowedIndexes.size() < mySHPObjects.size();)
667     {
668       if (!anExistingNames.contains(aBaseFileName + "_PolyXY_" + QString::number(anInd)) &&
669           !anExistingNames.contains(aBaseFileName + "_Poly3D_" + QString::number(anInd)) &&
670           !anExistingNames.contains(aBaseFileName + "_Bath_" + QString::number(anInd)))
671       {
672         anAllowedIndexes.push_back(anInd);
673         anInd++;
674       }
675       else
676         anInd++;
677     }
678     for (size_t i = 0; i < mySHPObjects.size(); i++ )
679       ReadSHPPoly3D(theDocument, mySHPObjects[i], aBaseFileName, anAllowedIndexes[i], theEntities);
680     aStat = 1;
681   }
682   else  
683   {
684     aStat = 0;
685   }
686   
687   for (size_t i = 0; i < mySHPObjects.size(); i++ )
688     free (mySHPObjects[i]);
689
690   mySHPObjects.clear();
691   SHPClose(aHSHP);
692   return aStat;
693 }
694
695 QString HYDROData_ShapeFile::GetShapeTypeName(int theType)
696 {
697   switch (theType)
698   {
699     case 0:
700       return "null shape";
701     case 1:
702       return "point (unsupported by HYDRO)";
703     case 3:
704       return "arc/polyline (supported by HYDRO)";
705     case 5:
706       return "polygon (supported by HYDRO)";
707     case 8:
708       return "multipoint (unsupported by HYDRO)";
709     case 11:
710       return "pointZ (unsupported by HYDRO)";
711     case 13:
712       return "arcZ/polyline (supported by HYDRO)";
713     case 15:
714       return "polygonZ (unsupported by HYDRO)";
715     case 18:
716       return "multipointZ (unsupported by HYDRO)";
717     case 21:
718       return "pointM (unsupported by HYDRO)";
719     case 23:
720       return "arcM/polyline (supported by HYDRO)";
721     case 25:
722       return "polygonM (unsupported by HYDRO)";
723     case 28:
724       return "multipointM (unsupported by HYDRO)";
725     case 31:
726       return "multipatch (unsupported by HYDRO)";
727     default:
728       return "unknown";
729   }
730 }
731
732 int HYDROData_ShapeFile::TryOpenShapeFile(QString theFileName)
733 {
734   QString aSHPfile = theFileName.simplified();
735   QString aSHXfile = theFileName.simplified().replace( theFileName.simplified().size() - 4, 4, ".shx");
736
737   QString anExt = theFileName.split('.', QString::SkipEmptyParts).back();
738   if (anExt.toLower() != "shp")
739     return -3;
740
741   FILE* pFileSHP = NULL;
742   pFileSHP = fopen (aSHPfile.toAscii().data(), "r");
743   FILE* pFileSHX = NULL;
744   pFileSHX = fopen (aSHXfile.toAscii().data(), "r");
745
746   if (pFileSHP == NULL || pFileSHX == NULL)
747   {
748     if (pFileSHP == NULL)
749       return -1;
750     if (pFileSHX == NULL)
751       return -2;
752   }
753   
754   fclose (pFileSHP);
755   fclose (pFileSHX);
756   return 0;
757 }
758
759
760 bool HYDROData_ShapeFile::CheckDBFFileExisting(const QString& theSHPFilePath, QString& thePathToDBFFile)
761 {
762   QString aSHPfile = theSHPFilePath.simplified();
763   QString aDBFfile = theSHPFilePath.simplified().replace( theSHPFilePath.simplified().size() - 4, 4, ".dbf");
764   FILE* pFileDBF = NULL;
765   pFileDBF = fopen (aDBFfile.toAscii().data(), "r");
766
767   if (pFileDBF == NULL)
768   {
769     return false;
770   }
771   
772   fclose (pFileDBF);
773   thePathToDBFFile = aDBFfile;
774   return true;
775 }
776
777
778 bool HYDROData_ShapeFile::DBF_OpenDBF(const QString& thePathToDBFFile)
779 {
780   myHDBF = DBFOpen( thePathToDBFFile.toAscii().data(), "r" );
781   if(myHDBF != NULL)
782     return true;
783   else
784     return false;
785 }
786
787 int HYDROData_ShapeFile::DBF_GetNbFields()
788 {
789   if(myHDBF == NULL)
790     return 0;
791   return DBFGetFieldCount(myHDBF);
792 }
793
794 void HYDROData_ShapeFile::DBF_CloseDBF()
795 {
796   if(myHDBF != NULL)
797      DBFClose( myHDBF );
798 }
799
800 QStringList HYDROData_ShapeFile::DBF_GetFieldList()
801 {
802   QStringList FieldList;
803   int   nWidth, nDecimals;
804   char chField[12];
805
806   for( int i = 0; i < DBFGetFieldCount(myHDBF); i++ )
807   {
808       DBFFieldType eType;
809       eType = DBFGetFieldInfo( myHDBF, i, chField, &nWidth, &nDecimals );
810       FieldList.append(QString(chField));
811   }
812
813   return FieldList;
814 }
815
816 void HYDROData_ShapeFile::DBF_GetFieldTypeList(std::vector<DBF_FieldType>& FTVect)
817 {
818   int   nWidth, nDecimals;
819   char chField[12];
820   DBF_FieldType FT;
821   for( int i = 0; i < DBFGetFieldCount(myHDBF); i++ )
822   {
823     DBFFieldType eType;
824     eType = DBFGetFieldInfo( myHDBF, i, chField, &nWidth, &nDecimals );
825     if( eType == FTString )
826       FT = DBF_FieldType_String;
827     else if( eType == FTInteger )
828       FT = DBF_FieldType_Integer;
829     else if( eType == FTDouble )
830       FT = DBF_FieldType_Double;
831     else if( eType == FTInvalid )
832       FT = DBF_FieldType_Invalid;
833
834     FTVect.push_back(FT);
835   }
836
837 }
838
839 int HYDROData_ShapeFile::DBF_GetNbRecords()
840 {
841   if(myHDBF == NULL)
842     return 0;
843   return DBFGetRecordCount(myHDBF);
844 }
845
846 void HYDROData_ShapeFile::DBF_GetAttributeList(int theIndexOfField, std::vector<DBF_AttrValue>& theAttrV)
847 {
848   int nWidth, nDecimals;
849   char chField[12];
850   
851   for( int i = 0; i < DBFGetRecordCount(myHDBF); i++ )
852   {      
853     DBFFieldType eType;
854     DBF_AttrValue anAttr;
855     eType = DBFGetFieldInfo( myHDBF, theIndexOfField, chField, &nWidth, &nDecimals );
856
857     if( DBFIsAttributeNULL( myHDBF, i, theIndexOfField ) )
858     {
859       anAttr.myIsNull = true;
860       DBF_FieldType FT = DBF_FieldType_None;
861       if( eType == FTString )
862         FT = DBF_FieldType_String;
863       else if( eType == FTInteger )
864         FT = DBF_FieldType_Integer;
865       else if( eType == FTDouble )
866         FT = DBF_FieldType_Double;
867       else if( eType == FTInvalid )
868         FT = DBF_FieldType_Invalid;
869       anAttr.myFieldType = FT;
870     }
871     else
872     {
873       switch( eType )
874       {
875         case FTString:
876         {
877           const char* chAttr = DBFReadStringAttribute( myHDBF, i, theIndexOfField );
878           anAttr.myIsNull = false;
879           anAttr.myFieldType = DBF_FieldType_String;
880           anAttr.myRawValue = chAttr;
881           anAttr.myStrVal = QString(chAttr);
882           break;
883         }
884        
885         case FTInteger:
886         {
887           int iAttr = DBFReadIntegerAttribute( myHDBF, i, theIndexOfField );
888           anAttr.myIsNull = false;
889           anAttr.myFieldType = DBF_FieldType_Integer;
890           anAttr.myRawValue = DBFReadStringAttribute( myHDBF, i, theIndexOfField );
891           anAttr.myIntVal = iAttr;
892           break;
893         }
894           
895         case FTDouble:
896         {
897           double dAttr = DBFReadDoubleAttribute( myHDBF, i, theIndexOfField );
898           anAttr.myIsNull = false;
899           anAttr.myFieldType = DBF_FieldType_Double;
900           anAttr.myRawValue = DBFReadStringAttribute( myHDBF, i, theIndexOfField );
901           anAttr.myDoubleVal = dAttr;
902           break;
903         }
904         default:
905           break;
906       }
907     }
908     theAttrV.push_back(anAttr);
909   }
910
911 }
912
913 bool HYDROData_ShapeFile::DBF_WriteFieldAndValues(const QString& theFileName, const QString& theFieldName, DBF_FieldType theType, const std::vector<DBF_AttrValue>& theAttrV, bool bUseRawValue)
914 {
915   // Check that given field type is equal to field types of attributes values
916   for (size_t i = 0; i < theAttrV.size(); i++)
917   {
918     if (theAttrV[i].myFieldType != theType)
919       return false;
920   }
921
922   DBFHandle     hDBF;
923   hDBF = DBFCreate( theFileName.toStdString().c_str() );
924   if( hDBF == NULL )
925           return false;
926   
927   if (theType != DBF_FieldType_String && theType != DBF_FieldType_Integer && theType != DBF_FieldType_Double) 
928   {
929     DBFClose( hDBF );
930     return false; //cant handle any other cases
931   }
932
933   int nWidth = 20;
934   switch( theType )
935   {
936     case DBF_FieldType_String:
937     {
938       DBFAddField (hDBF, theFieldName.toStdString().c_str(), FTString, nWidth, 0);
939       break;
940     }
941    
942     case DBF_FieldType_Integer:
943     {
944       DBFAddField (hDBF, theFieldName.toStdString().c_str(), FTInteger, nWidth, 0);
945       break;
946     }
947       
948     case DBF_FieldType_Double:
949     {
950       DBFAddField (hDBF, theFieldName.toStdString().c_str(), FTDouble, nWidth, 0);
951       break;
952     }
953     default:
954       break;
955   }
956
957   if (DBFGetFieldCount( hDBF ) != 1) 
958   {
959     DBFClose( hDBF );
960     return false;
961   }
962   if (DBFGetRecordCount( hDBF ) != 0)
963   {
964     DBFClose( hDBF );
965     return false;
966   }
967   int stat = -1;
968
969   if (bUseRawValue)
970   {
971     for (size_t i = 0; i < theAttrV.size(); i++)
972     {
973       if (!theAttrV[i].myIsNull)
974         stat = DBFWriteStringAttribute(hDBF, (int)i, 0, theAttrV[i].myRawValue.c_str());
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   else
986   {
987     for (size_t i = 0; i < theAttrV.size(); i++)
988     {
989       if (!theAttrV[i].myIsNull)
990         switch( theType )
991         {
992           case DBF_FieldType_String:
993           {
994             stat = DBFWriteStringAttribute(hDBF, (int)i, 0, theAttrV[i].myStrVal.toStdString().c_str());
995             break;
996           }
997          
998           case DBF_FieldType_Integer:
999           {
1000             stat = DBFWriteIntegerAttribute(hDBF, (int)i, 0, theAttrV[i].myIntVal);
1001             break;
1002           }
1003             
1004           case DBF_FieldType_Double:
1005           {
1006             stat = DBFWriteDoubleAttribute(hDBF, (int)i, 0, theAttrV[i].myDoubleVal);
1007             break;
1008           }
1009           default:
1010             break;
1011         }
1012       else
1013         stat = DBFWriteNULLAttribute(hDBF, (int)i, 0 );
1014
1015       if (stat != 1)
1016       {
1017         DBFClose( hDBF );
1018         return false;
1019       }
1020     }
1021   }
1022
1023   DBFClose( hDBF );
1024   return true;
1025
1026 }
1027