]> SALOME platform Git repositories - modules/hydro.git/blob - src/HYDROData/HYDROData_LandCoverMap.cxx
Salome HOME
refs #712: show warning in GUI, if the number of land covers is not changed after...
[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   int aNbCL = GetLCCount();
577   bool aResult = LocalPartition( theShape, "" );
578   return aResult && aNbCL != GetLCCount();
579 }
580
581
582 /**
583   Merge the given faces in the land cover
584   @param theFaces the faces to merge in the land cover map
585   @param theType the Strickler type for the merged land cover
586   @return if the merge is successful
587 */
588 bool HYDROData_LandCoverMap::Merge( const TopTools_ListOfShape& theFaces, const QString& theType )
589 {
590   // 1. to fuse the faces into the new face
591   TopoDS_Shape aMergedFace = MergeFaces( theFaces, true );
592   if( !aMergedFace.IsNull() && aMergedFace.ShapeType()==TopAbs_FACE )
593   {
594     // 2. to remove the merged faces from the current map
595     Remove( theFaces );
596
597     // 3. to add the face into the map
598     return LocalPartition( TopoDS::Face( aMergedFace ), theType );
599   }
600   return false;
601 }
602
603 /**
604   Merge the given faces into the shell/face
605   @param theFaces the faces to merge
606   @param IsToUnify if the common edges should be removed (fused)
607   @param theTolerance the operation's tolerance
608   @return result shape (face or shell)
609 */
610 TopoDS_Shape HYDROData_LandCoverMap::MergeFaces( const TopTools_ListOfShape& theFaces,
611                                                  bool IsToUnify, double theTolerance )
612 {
613   int anError;
614   TopTools_ListIteratorOfListOfShape anIt;
615   BOPCol_ListOfShape aLC;
616   anIt.Initialize(theFaces);
617   for( ; anIt.More(); anIt.Next() )
618   {
619     if (anIt.Value().ShapeType() != TopAbs_FACE)
620       return TopoDS_Shape();
621     aLC.Append( anIt.Value() );
622   }
623
624   BOPAlgo_PaveFiller aPF;
625   aPF.SetArguments( aLC );
626   aPF.SetRunParallel( Standard_False );
627   aPF.SetFuzzyValue( theTolerance );
628
629   aPF.Perform();
630   anError = aPF.ErrorStatus();
631   if( anError )
632     return TopoDS_Shape();
633
634   BOPAlgo_Builder anAlgo;
635   anIt.Initialize( theFaces );
636   for( ; anIt.More(); anIt.Next() )
637     anAlgo.AddArgument( anIt.Value() );
638
639   anAlgo.PerformWithFiller( aPF ); 
640   anError = anAlgo.ErrorStatus();
641   if( anError )
642     return TopoDS_Shape();
643
644   const TopoDS_Shape& aMergedShape = anAlgo.Shape();
645
646   BRep_Builder aBuilder;
647   TopoDS_Shell aShell; 
648   aBuilder.MakeShell( aShell ); 
649   aShell.Closed( Standard_False );
650   TopExp_Explorer anExplorer( aMergedShape, TopAbs_FACE );
651   for( ; anExplorer.More(); anExplorer.Next() ) 
652   {
653     const TopoDS_Face& aFace = TopoDS::Face(anExplorer.Current());
654     if( aFace.IsNull() ) 
655       continue;
656     if( aFace.ShapeType() == TopAbs_FACE )
657     {
658       aBuilder.Add( aShell, aFace );
659       aShell.Closed( Standard_False );
660     }
661   }
662
663   TopoDS_Shape aResult;
664   if( IsToUnify )
665   {
666     ShapeUpgrade_UnifySameDomain aUSD;
667     aUSD.Initialize( aShell );
668     aUSD.Build();
669     aResult = aUSD.Shape();
670   }
671   else
672     aResult = aShell;
673
674   anExplorer.Init( aResult, TopAbs_FACE );
675   int n = 0;
676   TopoDS_Face anOneFace;
677   for( ; anExplorer.More(); anExplorer.Next(), n++ ) 
678     anOneFace = TopoDS::Face( anExplorer.Current() );
679
680   if (n == 1)
681     aResult = anOneFace;
682   else if (aResult.ShapeType() == TopAbs_SHELL)
683   {
684     BRepCheck_Shell aBCS(TopoDS::Shell(aResult));
685     if (aBCS.Status().First() != BRepCheck_NoError)
686     {
687       ShapeFix_Shell aFixer;
688       aFixer.FixFaceOrientation(TopoDS::Shell(aResult), 1);
689       aResult = aFixer.Shape();
690     }
691   }
692
693   return aResult;
694 }
695
696 /**
697   Change Strickler type for the list of faces to the given one
698   @param theFaces the faces to change type
699   @param theType the Strickler type for the given land cover(s)
700   @return if the change type operation is successful
701 */
702 bool HYDROData_LandCoverMap::ChangeType( const TopTools_ListOfShape& theFaces, const QString& theType )
703 {
704   HYDROData_MapOfFaceToStricklerType aFacesToChangeType;
705   TopTools_ListIteratorOfListOfShape aFIt( theFaces );
706   for( ; aFIt.More(); aFIt.Next() )
707   {
708     TopoDS_Shape aShape = aFIt.Value();
709     if( aShape.ShapeType()==TopAbs_FACE )
710       aFacesToChangeType.Add( TopoDS::Face( aShape ), "" );
711   }
712
713   int aNbChanges = 0;
714   Explorer anIt( *this );
715   for( ; anIt.More(); anIt.Next() )
716     if( aFacesToChangeType.Contains( anIt.Face() ) )
717     {
718       anIt.SetStricklerType( theType );
719       aNbChanges++;
720     }
721   if ( aNbChanges != theFaces.Extent() )
722     return false;
723
724   return true;
725 }
726
727 /**
728   Get the shape of the land cover map
729 */
730 TopoDS_Shape HYDROData_LandCoverMap::GetShape() const
731 {
732   return HYDROData_Entity::GetShape( DataTag_Shape );
733 }
734
735 /**
736   Get Strickler type of the given land cover
737   @param theLandCover the land cover to get Strickler type of
738   @return name of Strickler type
739 */
740 QString HYDROData_LandCoverMap::StricklerType( const TopoDS_Face& theLandCover ) const
741 {
742   QString aType = "";
743
744   Explorer anIt( *this );
745   for( ; anIt.More(); anIt.Next() )
746     if( anIt.Face().IsEqual( theLandCover) )
747     {
748       aType = anIt.StricklerType();
749       break;
750     }
751
752   return aType;
753 }
754
755 /**
756   Set the shape of the land cover map
757   @param theShape the new shape for the land cover map
758 */
759 void HYDROData_LandCoverMap::SetShape( const TopoDS_Shape& theShape )
760 {
761   HYDROData_Entity::SetShape( DataTag_Shape, theShape );
762 }
763
764 /**
765   Perform the local partition algorithm on the land cover
766   @param theNewShape the new shape to add into the land cover
767   @param theNewType the new Strickler type for the new land cover
768   @return if the local partition is successful
769 */
770 bool HYDROData_LandCoverMap::LocalPartition( const TopoDS_Shape& theNewShape, const QString& theNewType )
771 {
772   if( theNewShape.IsNull() )
773     return false;
774
775   BOPCol_ListOfShape aShapesList;
776   BOPAlgo_PaveFiller aPaveFiller;
777   HYDROData_MapOfFaceToStricklerType aNewFaces;
778
779   // add faces to shapes list
780   Explorer anIt( *this );
781   for( ; anIt.More(); anIt.Next() )
782     aShapesList.Append( anIt.Face() );
783   aShapesList.Append( theNewShape );
784
785   if( aShapesList.Size()==1 && theNewShape.ShapeType()==TopAbs_FACE )
786   {
787     aNewFaces.Add( TopoDS::Face( theNewShape ), theNewType );
788     StoreLandCovers( aNewFaces );
789     return true;
790   }
791
792   // prepare pave filler
793   aPaveFiller.SetArguments( aShapesList );
794   aPaveFiller.Perform();
795   Standard_Integer anError = aPaveFiller.ErrorStatus();
796   if( anError )
797     return false;
798
799   // add faces to builder
800   BOPAlgo_Builder aBuilder;
801   anIt.Init( *this );
802   for( ; anIt.More(); anIt.Next() )
803     aBuilder.AddArgument( anIt.Face() );
804   aBuilder.AddArgument( theNewShape );
805
806   // perform the partition with the pave filler
807   aBuilder.PerformWithFiller( aPaveFiller );
808   anError = aBuilder.ErrorStatus();
809   if( anError )
810     return false;
811
812   //std::cout << "History:" << std::endl;
813   // analysis of the history
814   //     a. to fill map of shapes which come from the new face
815   NCollection_IndexedMap<int> aShapesFromNewFace;
816   //std::cout << "from NEW " << theNewShape << ":" << theNewType << std::endl;
817   TopTools_ListOfShape aModified = aBuilder.Modified( theNewShape );
818   TopTools_ListIteratorOfListOfShape aMIt( aModified );
819   for( ; aMIt.More(); aMIt.Next() )
820   {
821     //std::cout << "   " << aMIt.Value() << std::endl;
822     int aKey = (int)(uintptr_t)aMIt.Value().TShape().operator->();
823     aShapesFromNewFace.Add( aKey );
824   }
825
826   //     b. to fill map of parts except parts from new face
827   anIt.Init( *this );
828   for( ; anIt.More(); anIt.Next() )
829   {
830     QString aSType = anIt.StricklerType();
831     //std::cout << "from " << anIt.Face() << ": " << anIt.StricklerType() << std::endl;
832     TopTools_ListOfShape aModified = aBuilder.Modified( anIt.Face() );
833     if( aModified.Extent() == 0 )
834       aModified.Append( anIt.Face() );
835
836     TopTools_ListIteratorOfListOfShape aMIt( aModified );
837     for( ; aMIt.More(); aMIt.Next() )
838     {
839       TopoDS_Shape aShape = aMIt.Value();
840       bool isFace = aShape.ShapeType()==TopAbs_FACE;
841       int aKey = (int)(uintptr_t)aShape.TShape().operator->();
842       bool isAlsoFromNew = aShapesFromNewFace.Contains( aKey );
843       //std::cout << "   " << aShape << " " << isAlsoFromNew << std::endl;
844       if( isFace && !isAlsoFromNew )
845         aNewFaces.Add( TopoDS::Face( aShape ), aSType );
846     }
847   }
848
849   //     c. add the new shape if it is face with its type
850   if( theNewShape.ShapeType()==TopAbs_FACE )
851     aNewFaces.Add( TopoDS::Face( theNewShape ), theNewType );
852   
853   // convert map of shape to type to compound and list of types
854   StoreLandCovers( aNewFaces );
855   return true;
856 }
857
858 /**
859   Replace the set of land covers in the land cover map
860   @param theMap the map of shape (face) to Strickler type (string)
861 */
862 void HYDROData_LandCoverMap::StoreLandCovers( const HYDROData_MapOfFaceToStricklerType& theMap )
863 {
864   TopTools_ListOfShape aListOfFaces;
865
866   int n = theMap.Size();
867
868   Handle( TDataStd_ExtStringArray ) aTypes = 
869     TDataStd_ExtStringArray::Set( myLab.FindChild( DataTag_Types ), 0, n-1, Standard_True );
870
871   HYDROData_MapOfFaceToStricklerType::Iterator aNFIt( theMap );
872   for( int i=0; aNFIt.More(); aNFIt.Next(), i++ )
873   {
874     TopoDS_Face aFace = aNFIt.Key();
875     if( aFace.IsNull() )
876       continue;
877     QString aType = aNFIt.Value();
878     aListOfFaces.Append(aFace);
879     aTypes->SetValue( i, HYDROData_Tool::toExtString( aType ) );
880   }
881
882   TopoDS_Shape aResult;
883   if( aListOfFaces.Extent() == 1 )
884     aResult = aListOfFaces.First();
885   else if( aListOfFaces.Extent() > 1 )
886     aResult = MergeFaces( aListOfFaces, false );
887
888   //remove internal edges
889   aResult = RemoveInternal(aResult);
890   SetShape( aResult );
891 }
892
893 /**
894    Checks that object has 2D presentation. Reimlemented to retun true.
895 */
896 bool HYDROData_LandCoverMap::IsHas2dPrs() const
897 {
898   return true;
899 }
900
901 /**
902   Find the land cover for the given point
903   @param thePoint the point laying in some land cover
904   @param theType the returned type
905   @return the found land cover's face
906 */
907 TopoDS_Face HYDROData_LandCoverMap::FindByPoint( const gp_Pnt2d& thePoint, QString& theType ) const
908 {
909   //TODO: some more optimal algorithm
910   Explorer anIt( *this );
911   for( ; anIt.More(); anIt.Next() )
912     if( HYDROData_Tool::ComputePointState( thePoint.XY(), anIt.Face() ) == TopAbs_IN )
913     {
914       theType = anIt.StricklerType();
915       return anIt.Face();
916     }
917
918   theType = "";
919   return TopoDS_Face();
920 }
921
922 void Dump( const QString& theName, const QStringList& theList, QStringList& theLines )
923 {
924   theLines.append( QString( "%1 = QStringList()" ).arg( theName ) );
925   foreach( QString anItem, theList )
926     theLines.append( QString( "%1.append( u\"%2\" )" ).arg( theName ).arg( anItem ) );
927 }
928
929 /**
930   Dump to Python
931   @param theTreatedObjects the map of treated objects
932 */
933 QStringList HYDROData_LandCoverMap::DumpToPython( const QString&       thePyScriptPath,
934                                                   MapOfTreatedObjects& theTreatedObjects ) const
935 {
936   QStringList aResList = dumpObjectCreation( theTreatedObjects );
937   QString aName = GetObjPyName();
938
939   QString aShpFileName = thePyScriptPath;
940   aShpFileName.replace( ".py", ".shp" );
941   QString aDbfFileName = thePyScriptPath;
942   aDbfFileName.replace( ".py", ".dbf" );
943
944   ExportSHP( aShpFileName, true, 1 );
945
946   QString anAttr = "CODE_06"; //TODO: some custom choice
947   QStringList anAttrValues, aTypes;
948   HYDROData_Document::Document( myLab )->CollectQGISValues( anAttr, anAttrValues, aTypes );
949   ExportDBF( aDbfFileName, anAttr, anAttrValues, aTypes );
950
951   aResList << QString( "%1.ImportSHP( '%2' )" ).
952     arg( aName ).arg( aShpFileName );
953
954   Dump( "attr_values", anAttrValues, aResList );
955   Dump( "types", aTypes, aResList );
956   aResList << QString( "%1.ImportDBF( '%2', '%3', attr_values, types )" ).
957     arg( aName ).arg( aDbfFileName ).arg( anAttr );
958
959   return aResList;
960 }
961
962 TopoDS_Shape HYDROData_LandCoverMap::RemoveInternal(const TopoDS_Shape& InSh)
963 {
964   //Shape must be topologically correct
965   TopExp_Explorer anExp(InSh, TopAbs_EDGE);
966   TopTools_ListOfShape anEdgesToRemove;
967
968   for(; anExp.More(); anExp.Next() )
969   {
970     TopoDS_Edge CurEdge = TopoDS::Edge(anExp.Current());
971     if (CurEdge.Orientation() == TopAbs_INTERNAL)
972       anEdgesToRemove.Append(CurEdge);
973   }
974  
975   Handle_ShapeBuild_ReShape aReshape = new ShapeBuild_ReShape();
976   TopoDS_Shape OutSh = aReshape->Apply(InSh);
977   TopTools_ListIteratorOfListOfShape aIt(anEdgesToRemove);
978   for (; aIt.More(); aIt.Next()) 
979     aReshape->Remove(aIt.Value());
980   OutSh = aReshape->Apply(InSh);
981
982   Handle(ShapeFix_Shape) sfs = new ShapeFix_Shape;
983   sfs->Init(OutSh);
984   sfs->Perform();
985   return sfs->Shape();
986
987 }
988
989 void HYDROData_LandCoverMap::SetTransparency( double theTransparency )
990 {
991   Handle(TDataStd_Real) anAttr;
992   TDF_Label aLabel = myLab.FindChild( DataTag_Transparency );
993   if( !aLabel.FindAttribute( TDataStd_Real::GetID(), anAttr ) )
994     aLabel.AddAttribute( anAttr = new TDataStd_Real() );
995   anAttr->Set( theTransparency );
996 }
997
998 double HYDROData_LandCoverMap::GetTransparency() const
999 {
1000   Handle(TDataStd_Real) anAttr;
1001   TDF_Label aLabel = myLab.FindChild( DataTag_Transparency );
1002   if( !aLabel.FindAttribute( TDataStd_Real::GetID(), anAttr ) )
1003     return 0.5;
1004
1005   return anAttr->Get();
1006   
1007 }
1008
1009 bool HYDROData_LandCoverMap::ImportSHP( const QString& theSHPFileName,
1010                                         const QList<int>& theIndices )
1011 {
1012   HYDROData_ShapeFile anImporter;
1013   QStringList aPolyList; 
1014   TopTools_SequenceOfShape aFaces;
1015   int aSHapeType = -1;
1016   int Stat = anImporter.ImportPolygons(theSHPFileName, aPolyList, aFaces, aSHapeType);
1017   //
1018   if (Stat != 1)
1019     return false;
1020   //
1021   HYDROData_MapOfFaceToStricklerType aMapFace2ST;
1022   int maxInd = *std::max_element(theIndices.begin(), theIndices.end());
1023   if (maxInd > aPolyList.length())
1024     return false;
1025   //
1026   if (theIndices.empty())
1027   {
1028     //import all shapes
1029     for ( int i = 1; i <=aFaces.Length(); i++ )
1030     {
1031       TopoDS_Shape aShape = aFaces(i);
1032       if ( aShape.IsNull() ) 
1033         continue;
1034       aMapFace2ST.Add( TopoDS::Face( aShape ), "" );
1035     }
1036   }
1037   else
1038   {
1039     //import given indices
1040     foreach ( int Ind, theIndices )
1041     {
1042       TopoDS_Shape aShape = aFaces(Ind + 1);
1043       if ( aShape.IsNull() ) 
1044         continue;
1045       aMapFace2ST.Add( TopoDS::Face( aShape ), "" );
1046     }
1047   }
1048   //
1049   StoreLandCovers(aMapFace2ST);
1050   return true;
1051 }
1052
1053 bool HYDROData_LandCoverMap::ExportSHP( const QString& theSHPFileName, bool bUseDiscr, double theDefl) const
1054 {
1055   HYDROData_ShapeFile anExporter;
1056   QStringList aList;
1057   anExporter.Export(theSHPFileName, this, aList, bUseDiscr, theDefl );
1058   if (aList.empty())
1059     return true;
1060   else 
1061     return false;
1062 }
1063