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