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