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