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