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