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