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