]> SALOME platform Git repositories - modules/hydro.git/blob - src/HYDROData/HYDROData_LandCoverMap.cxx
Salome HOME
aceb28a9700db1c50e73cf7f6a596a2b66c3a5aa
[modules/hydro.git] / src / HYDROData / HYDROData_LandCoverMap.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_LandCoverMap.h>
20 #include <HYDROData_Object.h>
21 #include <HYDROData_PolylineXY.h>
22 #include <HYDROData_Tool.h>
23 #include <HYDROData_ShapeFile.h>
24 #include <HYDROData_Document.h>
25
26 #include <BOPAlgo_BOP.hxx>
27 #include <BOPAlgo_Builder.hxx>
28 #include <BOPAlgo_PaveFiller.hxx>
29 #include <BOPCol_ListOfShape.hxx>
30 #include <BRep_Builder.hxx>
31 #include <BRepAdaptor_Curve.hxx>
32 #include <BRepAlgoAPI_Fuse.hxx>
33 #include <BRepBuilderAPI_MakeFace.hxx>
34 #include <GCPnts_QuasiUniformDeflection.hxx>
35 #include <TopoDS.hxx>
36 #include <TopoDS_Compound.hxx>
37 #include <TopoDS_Edge.hxx>
38 #include <TopoDS_Face.hxx>
39 #include <TopoDS_Iterator.hxx>
40 #include <TopoDS_Shell.hxx>
41 #include <TopExp_Explorer.hxx>
42 #include <TopTools_ListIteratorOfListOfShape.hxx>
43 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
44 #include <BOPAlgo_PaveFiller.hxx>
45 #include <BRepTools.hxx>
46 #include <TopExp_Explorer.hxx>
47 #include <ShapeUpgrade_UnifySameDomain.hxx>
48 #include <TopExp.hxx>
49 #include <TDataStd_Real.hxx>
50 #include <TopTools_IndexedMapOfShape.hxx>
51 #include <ShapeBuild_ReShape.hxx>
52 #include <ShapeFix_Shape.hxx>
53
54
55 #include <QFile>
56 #include <QString>
57 #include <QTextStream>
58
59 const char TELEMAC_FORMAT = 'f';
60 const int TELEMAC_PRECISION = 3;
61
62
63 IMPLEMENT_STANDARD_HANDLE(HYDROData_LandCoverMap, HYDROData_Entity)
64 IMPLEMENT_STANDARD_RTTIEXT(HYDROData_LandCoverMap, HYDROData_Entity)
65
66 /**
67   Constructor
68   @param theMap the land cover map to iterate through
69 */
70 HYDROData_LandCoverMap::Iterator::Iterator( const HYDROData_LandCoverMap& theMap )
71 {
72   Init( theMap );
73 }
74
75 HYDROData_LandCoverMap::Iterator::Iterator( const Handle( HYDROData_LandCoverMap )& theMap )
76 {
77   if( theMap.IsNull() )
78   {
79     myIterator = 0;
80     myIndex = -1;
81   }
82   else
83     Init( *theMap );
84 }
85
86 /**
87   Initialize the iterator
88   @param theMap the land cover map to iterate through
89 */
90 void HYDROData_LandCoverMap::Iterator::Init( const HYDROData_LandCoverMap& theMap )
91 {
92   TopoDS_Shape aShape = theMap.GetShape();
93   if( aShape.IsNull() )
94     myIterator = 0;
95   else
96     myIterator = new TopoDS_Iterator( aShape );
97   
98   theMap.myLab.FindChild( DataTag_Types ).FindAttribute( TDataStd_ExtStringArray::GetID(), myArray );
99   if( myArray.IsNull() )
100     myIndex = -1;
101   else
102     myIndex = myArray->Lower();
103 }
104
105 /**
106   Destructor
107 */
108 HYDROData_LandCoverMap::Iterator::~Iterator()
109 {
110   delete myIterator;
111 }
112
113 /**
114   Return the current 0-based index of the iterator
115   @return the current index
116 */
117 int HYDROData_LandCoverMap::Iterator::Index() const
118 {
119   if( myArray.IsNull() )
120     return -1;
121   else
122     return myIndex - myArray->Lower();
123 }
124
125 /**
126   Return if the iterator has more elements
127   @return if the iterator has more elements
128 */
129 bool HYDROData_LandCoverMap::Iterator::More() const
130 {
131   return !myArray.IsNull() && myIterator && myIterator->More();
132 }
133
134 /**
135   Move iterator to the next element
136 */
137 void HYDROData_LandCoverMap::Iterator::Next()
138 {
139   if( myIterator )
140   {
141     myIterator->Next();
142     myIndex++;
143   }
144 }
145
146 /**
147   Get the current land cover (face)
148   @return the land cover's face
149 */
150 TopoDS_Face HYDROData_LandCoverMap::Iterator::Face() const
151 {
152   if( myIterator )
153     return TopoDS::Face( myIterator->Value() );
154   else
155     return TopoDS_Face();
156 }
157
158 /**
159   Get the current land cover's Strickler type 
160   @return the land cover's Strickler type 
161 */
162 QString HYDROData_LandCoverMap::Iterator::StricklerType() const
163 {
164   if( myArray.IsNull() || myIndex < myArray->Lower() || myIndex > myArray->Upper() )
165     return "";
166   else
167     return HYDROData_Tool::toQString( myArray->Value( myIndex ) );
168 }
169
170 /**
171   Set the Strickler type for the current land cover
172   @param theType the Strickler type
173 */
174 void HYDROData_LandCoverMap::Iterator::SetStricklerType( const QString& theType )
175 {
176   if( myArray.IsNull() || myIndex < myArray->Lower() || myIndex > myArray->Upper() )
177     return;
178   else
179     myArray->SetValue( myIndex, HYDROData_Tool::toExtString( theType ) );
180 }
181
182 /**
183   Constructor
184 */
185 HYDROData_LandCoverMap::HYDROData_LandCoverMap()
186   : HYDROData_Entity( Geom_No )
187 {
188 }
189
190 /**
191   Destructor
192 */
193 HYDROData_LandCoverMap::~HYDROData_LandCoverMap()
194 {
195 }
196
197 /**
198   Get object's kind
199   @return object's kind
200 */
201 const ObjectKind HYDROData_LandCoverMap::GetKind() const
202 {
203   return KIND_LAND_COVER_MAP;
204 }
205
206 int HYDROData_LandCoverMap::GetLCCount() const
207 {
208   Iterator anIt( *this );
209   int i = 0;
210   for( ; anIt.More(); anIt.Next() )
211     i++;
212   return i;
213 }
214
215 bool HYDROData_LandCoverMap::IsEmpty() const
216 {
217   Iterator anIt( *this );
218   if ( !anIt.More() )
219     return true;
220   else
221     return false;
222 }
223
224 /**
225   Load attributes from DBF File
226 ///
227 */
228 HYDROData_LandCoverMap::DBFStatus HYDROData_LandCoverMap::ImportDBF( const QString& theDBFFileName, 
229                                                                      const QString& theFieldName, 
230                                                                      const QStringList& theDBFValues,
231                                                                      const QStringList& theStricklerTypes,
232                                                                      const QList<int>& theIndices )
233 {
234   if (theDBFValues.size() != theStricklerTypes.size())
235     return DBFStatus_DIFF_SIZE_ERROR;
236   HYDROData_ShapeFile aDBFImporter;
237   if (!aDBFImporter.DBF_OpenDBF(theDBFFileName))
238     return DBFStatus_OPEN_FILE_ERROR; //cant open file
239
240   QStringList FieldList = aDBFImporter.DBF_GetFieldList();
241   int FieldNameIndex = FieldList.indexOf(theFieldName);
242   if (FieldNameIndex == -1)
243     return DBFStatus_NO_SUCH_FIELD_ERROR; //no such field
244
245   std::vector<HYDROData_ShapeFile::DBF_AttrValue> theAttrV;
246   aDBFImporter.DBF_GetAttributeList(FieldNameIndex, theAttrV ); 
247
248   bool allOK = true;
249   Iterator anIt( *this );
250   for( ; anIt.More(); anIt.Next() )
251   {
252     int CurIndex = anIt.Index();
253     int anIndex = CurIndex;
254     if( !theIndices.isEmpty() )
255       anIndex = theIndices[CurIndex];
256
257     HYDROData_ShapeFile::DBF_AttrValue AValue = theAttrV[anIndex];
258     int StricklerTypesInd = theDBFValues.indexOf( QString( AValue.myStrVal ) );
259     if ( StricklerTypesInd != -1)
260       anIt.SetStricklerType( theStricklerTypes[StricklerTypesInd] );
261     else
262       allOK = false;
263   }
264   if (allOK)
265     return DBFStatus_OK;
266   else
267     return DBFStatus_NO_DBFVALUES_CORRESPONDENCE_WARNING;
268 }
269
270 /**
271   Export attributes to DBF File
272 ///
273 */
274 void HYDROData_LandCoverMap::ExportDBF( const QString& theDBFFileName, 
275                                         const QString& theFieldName, 
276                                         const QStringList& theDBFValues,
277                                         const QStringList& theStricklerTypes) const
278 {
279   if (theDBFValues.size() != theStricklerTypes.size())
280     return;
281   HYDROData_ShapeFile anExporter; 
282   std::vector<HYDROData_ShapeFile::DBF_AttrValue> theAttrV;
283   Iterator anIt( *this );
284   for( ; anIt.More(); anIt.Next() )
285   {
286     QString CurST = anIt.StricklerType();
287     HYDROData_ShapeFile::DBF_AttrValue aCurAttrV;
288     aCurAttrV.myIsNull = false;
289     int StricklerTypesInd = theStricklerTypes.indexOf(CurST);
290     if (StricklerTypesInd != -1)
291     {
292       aCurAttrV.myStrVal = theDBFValues[StricklerTypesInd];
293       aCurAttrV.myFieldType = HYDROData_ShapeFile::DBF_FieldType_String;
294       theAttrV.push_back(aCurAttrV);
295     }
296     else
297       aCurAttrV.myIsNull = true;
298   }
299   //use actual str value; not the raw value
300   anExporter.DBF_WriteFieldAndValues(theDBFFileName, theFieldName, HYDROData_ShapeFile::DBF_FieldType_String, theAttrV, false);
301
302 }
303
304 int HashCode( const gp_Pnt& thePoint, const Standard_Integer theUpper )
305 {
306   int aHashX = HashCode( thePoint.X(), theUpper );
307   int aHashY = HashCode( thePoint.Y(), theUpper );
308   return (aHashX^aHashY)%theUpper;
309 }
310
311 bool operator == ( const gp_Pnt& thePoint1, const gp_Pnt& thePoint2 )
312 {
313   return thePoint1.IsEqual( thePoint2, Precision::Confusion() );
314 }
315
316 bool EdgeDiscretization( const TopoDS_Edge& theEdge, 
317                          Standard_Real theDeflection,
318                          NCollection_IndexedMap<gp_Pnt>& theVerticesMap,
319                          QList<int>& theVerticesIds )
320 {
321   BRepAdaptor_Curve aCurve( theEdge );
322   GCPnts_QuasiUniformDeflection aDiscrete( aCurve, theDeflection );
323   if( !aDiscrete.IsDone() )
324     return false;
325
326   int n = aDiscrete.NbPoints();
327   for( int i=1; i<=n; i++ )
328   {
329     gp_Pnt aPnt = aDiscrete.Value( i );
330     int anId;
331     if( theVerticesMap.Contains( aPnt ) )
332       anId = theVerticesMap.FindIndex( aPnt );
333     else
334     {
335       anId = theVerticesMap.Size();
336       theVerticesMap.Add( aPnt );
337     }
338     theVerticesIds.append( anId );
339   }
340   return true;
341 }
342
343 /**
344   Export the land cover map for the solver (Telemac)
345   @param theFileName the name of file
346   @return if the export is successful
347 */
348 bool HYDROData_LandCoverMap::ExportTelemac( const QString& theFileName, Standard_Real theDeflection ) const
349 {
350   TopoDS_Shape aLandCoverMapShape = GetShape();
351   TopTools_ListOfShape aListOfFaces;
352   Iterator anIt( *this );
353   QMap<Handle(TopoDS_TShape), QString> aTypesMap;
354   for( ; anIt.More(); anIt.Next() )
355   {
356     aListOfFaces.Append( anIt.Face() );
357     aTypesMap.insert( anIt.Face().TShape(), anIt.StricklerType() );
358   }
359
360   TopoDS_Shape aShape = MergeFaces( aListOfFaces, false );
361
362   NCollection_IndexedMap<gp_Pnt> aVerticesMap;
363   NCollection_IndexedDataMap< TopoDS_Edge, QList<int> > anEdgesMap;
364   typedef QPair< QString, QList<int> > FaceData;
365   NCollection_IndexedDataMap< TopoDS_Face, FaceData > aFacesMap;
366
367   // add into the map all edges existing in the shell
368   TopExp_Explorer anExp1( aShape, TopAbs_EDGE );
369   for( ; anExp1.More(); anExp1.Next() )
370   {
371     TopoDS_Edge anEdge = TopoDS::Edge( anExp1.Current() );
372     QList<int> aVerticesIdsList;
373     if( EdgeDiscretization( anEdge, theDeflection, aVerticesMap, aVerticesIdsList ) )
374       anEdgesMap.Add( anEdge, aVerticesIdsList );
375   }
376
377   // add into the map all faces existing in the shell and correspondence between face and edges ids
378   TopExp_Explorer anExp2( aShape, TopAbs_FACE );
379   for( ; anExp2.More(); anExp2.Next() )
380   {
381     TopoDS_Face aFace = TopoDS::Face( anExp2.Current() );
382     TopExp_Explorer anExp3( aFace, TopAbs_EDGE );
383     QList<int> anEdgesIdsList;
384     for( ; anExp3.More(); anExp3.Next() )
385     {
386       TopoDS_Edge anEdge = TopoDS::Edge( anExp3.Current() );
387       int anEdgeId = anEdgesMap.FindIndex( anEdge );
388       anEdgesIdsList.append( anEdgeId );
389     }
390
391     FaceData aData;
392     aData.first = aTypesMap[aFace.TShape()];
393     aData.second = anEdgesIdsList;
394     aFacesMap.Add( aFace, aData );
395   }
396
397   QFile aFile( theFileName );
398   if( !aFile.open( QFile::WriteOnly | QFile::Text ) )
399     return false;
400
401   QTextStream aStream( &aFile );
402   aStream << "# nodes\n";
403   NCollection_IndexedMap<gp_Pnt>::Iterator anIt1( aVerticesMap );
404   for( ; anIt1.More(); anIt1.Next() )
405   {
406     gp_Pnt aPnt = anIt1.Value();
407     aStream << QString::number( aPnt.X(), TELEMAC_FORMAT, TELEMAC_PRECISION );
408     aStream << " ";
409     aStream << QString::number( aPnt.Y(), TELEMAC_FORMAT, TELEMAC_PRECISION );
410     aStream << " ";
411     aStream << QString::number( aPnt.Z(), TELEMAC_FORMAT, TELEMAC_PRECISION );
412     aStream << "\n";
413   }
414   aStream << "\n";
415
416   aStream << "# edges\n";
417   NCollection_IndexedDataMap< TopoDS_Edge, QList<int> >::Iterator anIt2( anEdgesMap );
418   for( ; anIt2.More(); anIt2.Next() )
419   {
420     QList<int> aVerticesIds = anIt2.Value();
421     foreach( int anId, aVerticesIds )
422       aStream << anId << " ";
423     aStream << "\n";
424   }
425   aStream << "\n";
426
427   aStream << "# faces\n";
428   NCollection_IndexedDataMap< TopoDS_Face, FaceData >::Iterator anIt3( aFacesMap );
429   for( ; anIt3.More(); anIt3.Next() )
430   {
431     QString aType = anIt3.Value().first;
432     QList<int> anEdgesIds = anIt3.Value().second;
433     aStream << "\"" << aType << "\" ";
434     foreach( int anId, anEdgesIds )
435       aStream << anId << " ";
436     aStream << "\n";
437   }
438   aStream << "\n";
439
440   aFile.close();
441   return true;
442 }
443
444 /**
445   Add a new object as land cover
446   @param theObject the object to add as land cover
447   @param theType the Strickler type for the new land cover
448   @return if the addition is successful
449 */
450 bool HYDROData_LandCoverMap::Add( const Handle( HYDROData_Object )& theObject, const QString& theType )
451 {
452   if( theObject.IsNull() )
453     return false;
454
455   TopoDS_Shape aShape = theObject->GetTopShape();
456   if( aShape.ShapeType()!=TopAbs_FACE )
457     return false;
458
459   TopoDS_Face aFace = TopoDS::Face( aShape );
460   return LocalPartition( aFace, theType );
461 }
462
463 bool HYDROData_LandCoverMap::Add( const TopoDS_Wire& theWire, const QString& theType )
464 {
465   if( !theWire.Closed() )
466     return false;
467
468   TopoDS_Face aFace = BRepBuilderAPI_MakeFace( theWire, Standard_True ).Face();
469   return LocalPartition( aFace, theType );
470 }
471
472 /**
473   Add a new polyline as land cover
474   @param thePolyline the polyline to add as land cover
475   @param theType the Strickler type for the new land cover
476   @return if the addition is successful
477 */
478 bool HYDROData_LandCoverMap::Add( const Handle( HYDROData_PolylineXY )& thePolyline, const QString& theType )
479 {
480   if( thePolyline.IsNull() )
481     return false;
482
483   TopoDS_Shape aShape = thePolyline->GetShape();
484   if( aShape.ShapeType()==TopAbs_WIRE )
485     return Add( TopoDS::Wire( aShape ), theType );
486
487   if( aShape.ShapeType()==TopAbs_COMPOUND )
488   {
489     TopExp_Explorer anExp( aShape, TopAbs_WIRE );
490     for( ; anExp.More(); anExp.Next() )
491     {
492       TopoDS_Wire aPart = TopoDS::Wire( anExp.Current() );
493       if( !Add( aPart, theType ) )
494         return false;
495     }
496     return true;
497   }
498
499   return false;
500 }
501
502 /**
503   Remove the given face from land cover map
504   @param theFace the face to be removed
505   @return if the removing is successful
506 */
507 bool HYDROData_LandCoverMap::Remove( const TopoDS_Face& theFace )
508 {
509   TopTools_ListOfShape aList;
510   aList.Append( theFace );
511   return Remove( aList );
512 }
513
514 /**
515   Remove the given faces from land cover map
516   @param theFacesToRemove the face list to be removed
517   @return if the removing is successful
518 */
519 bool HYDROData_LandCoverMap::Remove( const TopTools_ListOfShape& theFacesToRemove )
520 {
521   HYDROData_MapOfFaceToStricklerType aFacesToRemove, aNewFaces;
522   TopTools_ListIteratorOfListOfShape aFIt( theFacesToRemove );
523   for( ; aFIt.More(); aFIt.Next() )
524   {
525     TopoDS_Shape aShape = aFIt.Value();
526     if( aShape.ShapeType()==TopAbs_FACE )
527       aFacesToRemove.Add( TopoDS::Face( aShape ), "" );
528   }
529
530   Iterator anIt( *this );
531   for( ; anIt.More(); anIt.Next() )
532     if( !aFacesToRemove.Contains( anIt.Face() ) )
533       aNewFaces.Add( anIt.Face(), anIt.StricklerType() );
534
535   if ( aNewFaces.IsEmpty() )
536     return false;
537
538   StoreLandCovers( aNewFaces );
539   return true;
540 }
541
542 /**
543   Split the land cover map by the given polyline
544   @param thePolyline the tool polyline to split the land cover map
545   @return if the removing is successful
546 */
547 bool HYDROData_LandCoverMap::Split( const Handle( HYDROData_PolylineXY )& thePolyline )
548 {
549   if( thePolyline.IsNull() )
550     return false;
551
552   TopoDS_Shape aShape = thePolyline->GetShape();
553   return Split( aShape );
554 }
555
556
557 /**
558   Split the land cover map by the given polyline
559   @param theShape the tool polyline to split the land cover map
560   @return if the removing is successful
561 */
562 bool HYDROData_LandCoverMap::Split( const TopoDS_Shape& theShape )
563 {
564   return LocalPartition( theShape, "" );
565 }
566
567
568 /**
569   Merge the given faces in the land cover
570   @param theFaces the faces to merge in the land cover map
571   @param theType the Strickler type for the merged land cover
572   @return if the merge is successful
573 */
574 bool HYDROData_LandCoverMap::Merge( const TopTools_ListOfShape& theFaces, const QString& theType )
575 {
576   // 1. to fuse the faces into the new face
577   TopoDS_Shape aMergedFace = MergeFaces( theFaces, true );
578   if( !aMergedFace.IsNull() && aMergedFace.ShapeType()==TopAbs_FACE )
579   {
580     // 2. to remove the merged faces from the current map
581     Remove( theFaces );
582
583     // 3. to add the face into the map
584     return LocalPartition( TopoDS::Face( aMergedFace ), theType );
585   }
586   return false;
587 }
588
589 /**
590   Merge the given faces into the shell/face
591   @param theFaces the faces to merge
592   @param IsToUnify if the common edges should be removed (fused)
593   @param theTolerance the operation's tolerance
594   @return result shape (face or shell)
595 */
596 TopoDS_Shape HYDROData_LandCoverMap::MergeFaces( const TopTools_ListOfShape& theFaces,
597                                                  bool IsToUnify, double theTolerance )
598 {
599   int anError;
600   TopTools_ListIteratorOfListOfShape anIt;
601   BOPCol_ListOfShape aLC;
602   anIt.Initialize(theFaces);
603   for( ; anIt.More(); anIt.Next() )
604   {
605     if (anIt.Value().ShapeType() != TopAbs_FACE)
606       return TopoDS_Shape();
607     aLC.Append( anIt.Value() );
608   }
609
610   BOPAlgo_PaveFiller aPF;
611   aPF.SetArguments( aLC );
612   aPF.SetRunParallel( Standard_False );
613   aPF.SetFuzzyValue( theTolerance );
614
615   aPF.Perform();
616   anError = aPF.ErrorStatus();
617   if( anError )
618     return TopoDS_Shape();
619
620   BOPAlgo_Builder anAlgo;
621   anIt.Initialize( theFaces );
622   for( ; anIt.More(); anIt.Next() )
623     anAlgo.AddArgument( anIt.Value() );
624
625   anAlgo.PerformWithFiller( aPF ); 
626   anError = anAlgo.ErrorStatus();
627   if( anError )
628     return TopoDS_Shape();
629
630   const TopoDS_Shape& aMergedShape = anAlgo.Shape();
631
632   BRep_Builder aBuilder;
633   TopoDS_Shell aShell; 
634   aBuilder.MakeShell( aShell ); 
635   aShell.Closed( Standard_False );
636   TopExp_Explorer anExplorer( aMergedShape, TopAbs_FACE );
637   for( ; anExplorer.More(); anExplorer.Next() ) 
638   {
639     const TopoDS_Face& aFace = TopoDS::Face(anExplorer.Current());
640     if( aFace.IsNull() ) 
641       continue;
642     if( aFace.ShapeType() == TopAbs_FACE )
643     {
644       aBuilder.Add( aShell, aFace );
645       aShell.Closed( Standard_False );
646     }
647   }
648
649   TopoDS_Shape aResult;
650   if( IsToUnify )
651   {
652     ShapeUpgrade_UnifySameDomain aUSD;
653     aUSD.Initialize( aShell );
654     aUSD.Build();
655     aResult = aUSD.Shape();
656   }
657   else
658     aResult = aShell;
659
660   anExplorer.Init( aResult, TopAbs_FACE );
661   int n = 0;
662   TopoDS_Face anOneFace;
663   for( ; anExplorer.More(); anExplorer.Next(), n++ ) 
664     anOneFace = TopoDS::Face( anExplorer.Current() );
665
666   if( n == 1 )
667     aResult = anOneFace;
668
669   return aResult;
670 }
671
672 /**
673   Change Strickler type for the list of faces to the given one
674   @param theFaces the faces to change type
675   @param theType the Strickler type for the given land cover(s)
676   @return if the change type operation is successful
677 */
678 bool HYDROData_LandCoverMap::ChangeType( const TopTools_ListOfShape& theFaces, const QString& theType )
679 {
680   HYDROData_MapOfFaceToStricklerType aFacesToChangeType;
681   TopTools_ListIteratorOfListOfShape aFIt( theFaces );
682   for( ; aFIt.More(); aFIt.Next() )
683   {
684     TopoDS_Shape aShape = aFIt.Value();
685     if( aShape.ShapeType()==TopAbs_FACE )
686       aFacesToChangeType.Add( TopoDS::Face( aShape ), "" );
687   }
688
689   int aNbChanges = 0;
690   Iterator anIt( *this );
691   for( ; anIt.More(); anIt.Next() )
692     if( aFacesToChangeType.Contains( anIt.Face() ) )
693     {
694       anIt.SetStricklerType( theType );
695       aNbChanges++;
696     }
697   if ( aNbChanges != theFaces.Extent() )
698     return false;
699
700   return true;
701 }
702
703 /**
704   Get the shape of the land cover map
705 */
706 TopoDS_Shape HYDROData_LandCoverMap::GetShape() const
707 {
708   return HYDROData_Entity::GetShape( DataTag_Shape );
709 }
710
711 /**
712   Get Strickler type of the given land cover
713   @param theLandCover the land cover to get Strickler type of
714   @return name of Strickler type
715 */
716 QString HYDROData_LandCoverMap::StricklerType( const TopoDS_Face& theLandCover ) const
717 {
718   QString aType = "";
719
720   Iterator anIt( *this );
721   for( ; anIt.More(); anIt.Next() )
722     if( anIt.Face().IsEqual( theLandCover) )
723     {
724       aType = anIt.StricklerType();
725       break;
726     }
727
728   return aType;
729 }
730
731 /**
732   Set the shape of the land cover map
733   @param theShape the new shape for the land cover map
734 */
735 void HYDROData_LandCoverMap::SetShape( const TopoDS_Shape& theShape )
736 {
737   HYDROData_Entity::SetShape( DataTag_Shape, theShape );
738 }
739
740 /**
741   Perform the local partition algorithm on the land cover
742   @param theNewShape the new shape to add into the land cover
743   @param theNewType the new Strickler type for the new land cover
744   @return if the local partition is successful
745 */
746 bool HYDROData_LandCoverMap::LocalPartition( const TopoDS_Shape& theNewShape, const QString& theNewType )
747 {
748   if( theNewShape.IsNull() )
749     return false;
750
751   BOPCol_ListOfShape aShapesList;
752   BOPAlgo_PaveFiller aPaveFiller;
753   HYDROData_MapOfFaceToStricklerType aNewFaces;
754
755   // add faces to shapes list
756   Iterator anIt( *this );
757   for( ; anIt.More(); anIt.Next() )
758     aShapesList.Append( anIt.Face() );
759   aShapesList.Append( theNewShape );
760
761   if( aShapesList.Size()==1 && theNewShape.ShapeType()==TopAbs_FACE )
762   {
763     aNewFaces.Add( TopoDS::Face( theNewShape ), theNewType );
764     StoreLandCovers( aNewFaces );
765     return true;
766   }
767
768   // prepare pave filler
769   aPaveFiller.SetArguments( aShapesList );
770   aPaveFiller.Perform();
771   Standard_Integer anError = aPaveFiller.ErrorStatus();
772   if( anError )
773     return false;
774
775   // add faces to builder
776   BOPAlgo_Builder aBuilder;
777   anIt.Init( *this );
778   for( ; anIt.More(); anIt.Next() )
779     aBuilder.AddArgument( anIt.Face() );
780   aBuilder.AddArgument( theNewShape );
781
782   // perform the partition with the pave filler
783   aBuilder.PerformWithFiller( aPaveFiller );
784   anError = aBuilder.ErrorStatus();
785   if( anError )
786     return false;
787
788   //std::cout << "History:" << std::endl;
789   // analysis of the history
790   //     a. to fill map of shapes which come from the new face
791   NCollection_IndexedMap<int> aShapesFromNewFace;
792   //std::cout << "from NEW " << theNewShape << ":" << theNewType << std::endl;
793   TopTools_ListOfShape aModified = aBuilder.Modified( theNewShape );
794   TopTools_ListIteratorOfListOfShape aMIt( aModified );
795   for( ; aMIt.More(); aMIt.Next() )
796   {
797     //std::cout << "   " << aMIt.Value() << std::endl;
798     int aKey = (int)(uintptr_t)aMIt.Value().TShape().operator->();
799     aShapesFromNewFace.Add( aKey );
800   }
801
802   //     b. to fill map of parts except parts from new face
803   anIt.Init( *this );
804   for( ; anIt.More(); anIt.Next() )
805   {
806     QString aSType = anIt.StricklerType();
807     //std::cout << "from " << anIt.Face() << ": " << anIt.StricklerType() << std::endl;
808     TopTools_ListOfShape aModified = aBuilder.Modified( anIt.Face() );
809     if( aModified.Extent() == 0 )
810       aModified.Append( anIt.Face() );
811
812     TopTools_ListIteratorOfListOfShape aMIt( aModified );
813     for( ; aMIt.More(); aMIt.Next() )
814     {
815       TopoDS_Shape aShape = aMIt.Value();
816       bool isFace = aShape.ShapeType()==TopAbs_FACE;
817       int aKey = (int)(uintptr_t)aShape.TShape().operator->();
818       bool isAlsoFromNew = aShapesFromNewFace.Contains( aKey );
819       //std::cout << "   " << aShape << " " << isAlsoFromNew << std::endl;
820       if( isFace && !isAlsoFromNew )
821         aNewFaces.Add( TopoDS::Face( aShape ), aSType );
822     }
823   }
824
825   //     c. add the new shape if it is face with its type
826   if( theNewShape.ShapeType()==TopAbs_FACE )
827     aNewFaces.Add( TopoDS::Face( theNewShape ), theNewType );
828   
829   // convert map of shape to type to compound and list of types
830   StoreLandCovers( aNewFaces );
831   return true;
832 }
833
834 /**
835   Replace the set of land covers in the land cover map
836   @param theMap the map of shape (face) to Strickler type (string)
837 */
838 void HYDROData_LandCoverMap::StoreLandCovers( const HYDROData_MapOfFaceToStricklerType& theMap )
839 {
840   TopTools_ListOfShape aListOfFaces;
841
842   int n = theMap.Size();
843
844   Handle( TDataStd_ExtStringArray ) aTypes = 
845     TDataStd_ExtStringArray::Set( myLab.FindChild( DataTag_Types ), 0, n-1, Standard_True );
846
847   HYDROData_MapOfFaceToStricklerType::Iterator aNFIt( theMap );
848   for( int i=0; aNFIt.More(); aNFIt.Next(), i++ )
849   {
850     TopoDS_Face aFace = aNFIt.Key();
851     if( aFace.IsNull() )
852       continue;
853     QString aType = aNFIt.Value();
854     aListOfFaces.Append(aFace);
855     aTypes->SetValue( i, HYDROData_Tool::toExtString( aType ) );
856   }
857
858   TopoDS_Shape aResult;
859   if( aListOfFaces.Extent() == 1 )
860   {
861     TopoDS_Shell aShell;
862     BRep_Builder aShellBuilder;
863     aShellBuilder.MakeShell( aShell );
864     aShell.Closed( Standard_False );
865     aShellBuilder.Add( aShell, aListOfFaces.First() );
866     aResult = aShell;
867   }
868   else if( aListOfFaces.Extent() > 1 )
869     aResult = MergeFaces( aListOfFaces, false );
870
871   //remove internal edges
872   aResult = RemoveInternal(aResult);
873   SetShape( aResult );
874 }
875
876 /**
877    Checks that object has 2D presentation. Reimlemented to retun true.
878 */
879 bool HYDROData_LandCoverMap::IsHas2dPrs() const
880 {
881   return true;
882 }
883
884 /**
885   Find the land cover for the given point
886   @param thePoint the point laying in some land cover
887   @param theType the returned type
888   @return the found land cover's face
889 */
890 TopoDS_Face HYDROData_LandCoverMap::FindByPoint( const gp_Pnt2d& thePoint, QString& theType ) const
891 {
892   //TODO: some more optimal algorithm
893   Iterator anIt( *this );
894   for( ; anIt.More(); anIt.Next() )
895     if( HYDROData_Tool::ComputePointState( thePoint.XY(), anIt.Face() ) == TopAbs_IN )
896     {
897       theType = anIt.StricklerType();
898       return anIt.Face();
899     }
900
901   theType = "";
902   return TopoDS_Face();
903 }
904
905 void Dump( const QString& theName, const QStringList& theList, QStringList& theLines )
906 {
907   theLines.append( QString( "%1 = QStringList()" ).arg( theName ) );
908   foreach( QString anItem, theList )
909     theLines.append( QString( "%1.append( u\"%2\" )" ).arg( theName ).arg( anItem ) );
910 }
911
912 /**
913   Dump to Python
914   @param theTreatedObjects the map of treated objects
915 */
916 QStringList HYDROData_LandCoverMap::DumpToPython( const QString&       thePyScriptPath,
917                                                   MapOfTreatedObjects& theTreatedObjects ) const
918 {
919   QStringList aResList = dumpObjectCreation( theTreatedObjects );
920   QString aName = GetObjPyName();
921
922   QString aShapeFileName = thePyScriptPath;
923   aShapeFileName.replace( ".py", ".shp" );
924   QString aDbfFileName = thePyScriptPath;
925   aDbfFileName.replace( ".py", ".dbf" );
926
927   //TODO: export shape file
928
929   QString anAttr = "CODE_06"; //TODO: some custom choice
930   QStringList anAttrValues, aTypes;
931   HYDROData_Document::Document( myLab )->CollectQGISValues( anAttr, anAttrValues, aTypes );
932   ExportDBF( aDbfFileName, anAttr, anAttrValues, aTypes );
933
934   //TODO: insert command to import shape file
935
936   Dump( "attr_values", anAttrValues, aResList );
937   Dump( "types", aTypes, aResList );
938   aResList << QString( "%1.ImportDBF( '%2', '%3', attr_values, types )" ).
939     arg( aName ).arg( aDbfFileName ).arg( anAttr );
940
941   return aResList;
942 }
943
944 TopoDS_Shape HYDROData_LandCoverMap::RemoveInternal(const TopoDS_Shape& InSh)
945 {
946   //Shape must be topologically correct
947   TopExp_Explorer anExp(InSh, TopAbs_EDGE);
948   TopTools_ListOfShape anEdgesToRemove;
949
950   for(; anExp.More(); anExp.Next() )
951   {
952     TopoDS_Edge CurEdge = TopoDS::Edge(anExp.Current());
953     if (CurEdge.Orientation() == TopAbs_INTERNAL)
954       anEdgesToRemove.Append(CurEdge);
955   }
956  
957   Handle_ShapeBuild_ReShape aReshape = new ShapeBuild_ReShape();
958   TopoDS_Shape OutSh = aReshape->Apply(InSh);
959   TopTools_ListIteratorOfListOfShape aIt(anEdgesToRemove);
960   for (; aIt.More(); aIt.Next()) 
961     aReshape->Remove(aIt.Value());
962   OutSh = aReshape->Apply(InSh);
963
964   Handle(ShapeFix_Shape) sfs = new ShapeFix_Shape;
965   sfs->Init(OutSh);
966   sfs->Perform();
967   return sfs->Shape();
968
969 }
970
971 void HYDROData_LandCoverMap::SetTransparency( double theTransparency )
972 {
973   Handle(TDataStd_Real) anAttr;
974   TDF_Label aLabel = myLab.FindChild( DataTag_Transparency );
975   if( !aLabel.FindAttribute( TDataStd_Real::GetID(), anAttr ) )
976     aLabel.AddAttribute( anAttr = new TDataStd_Real() );
977   anAttr->Set( theTransparency );
978 }
979
980 double HYDROData_LandCoverMap::GetTransparency() const
981 {
982   Handle(TDataStd_Real) anAttr;
983   TDF_Label aLabel = myLab.FindChild( DataTag_Transparency );
984   if( !aLabel.FindAttribute( TDataStd_Real::GetID(), anAttr ) )
985     return 0.5;
986
987   return anAttr->Get();
988   
989 }