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