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