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