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