Salome HOME
final variant of the first merge test
[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
24 #include <BOPAlgo_BOP.hxx>
25 #include <BOPAlgo_Builder.hxx>
26 #include <BOPAlgo_PaveFiller.hxx>
27 #include <BOPCol_ListOfShape.hxx>
28 #include <BRep_Builder.hxx>
29 #include <BRepAdaptor_Curve.hxx>
30 #include <BRepAlgoAPI_Fuse.hxx>
31 #include <BRepBuilderAPI_MakeFace.hxx>
32 #include <GCPnts_QuasiUniformDeflection.hxx>
33 #include <NCollection_IndexedMap.hxx>
34 #include <TopoDS.hxx>
35 #include <TopoDS_Compound.hxx>
36 #include <TopoDS_Edge.hxx>
37 #include <TopoDS_Face.hxx>
38 #include <TopoDS_Iterator.hxx>
39 #include <TopoDS_Shell.hxx>
40 #include <TopExp_Explorer.hxx>
41 #include <TopTools_ListIteratorOfListOfShape.hxx>
42 #include <BOPAlgo_PaveFiller.hxx>
43 #include <BRepTools.hxx>
44 #include <TopExp_Explorer.hxx>
45 #include <ShapeUpgrade_UnifySameDomain.hxx>
46
47 #include <QFile>
48 #include <QString>
49 #include <QTextStream>
50
51 const char TELEMAC_FORMAT = 'f';
52 const int TELEMAC_PRECISION = 3;
53
54
55 IMPLEMENT_STANDARD_HANDLE(HYDROData_LandCoverMap, HYDROData_Entity)
56 IMPLEMENT_STANDARD_RTTIEXT(HYDROData_LandCoverMap, HYDROData_Entity)
57
58 class HYDROData_MapOfFaceToStricklerType : public NCollection_IndexedDataMap<TopoDS_Face, QString>
59 {
60 };
61
62 /**
63   Constructor
64   @param theMap the land cover map to iterate through
65 */
66 HYDROData_LandCoverMap::Iterator::Iterator( const HYDROData_LandCoverMap& theMap )
67 {
68   Init( theMap );
69 }
70
71 HYDROData_LandCoverMap::Iterator::Iterator( const Handle( HYDROData_LandCoverMap )& theMap )
72 {
73   if( theMap.IsNull() )
74   {
75     myIterator = 0;
76     myIndex = -1;
77   }
78   else
79     Init( *theMap );
80 }
81
82 /**
83   Initialize the iterator
84   @param theMap the land cover map to iterate through
85 */
86 void HYDROData_LandCoverMap::Iterator::Init( const HYDROData_LandCoverMap& theMap )
87 {
88   TopoDS_Shape aShape = theMap.GetShape();
89   if( aShape.IsNull() )
90     myIterator = 0;
91   else
92     myIterator = new TopoDS_Iterator( aShape );
93   myIndex = 0;
94   theMap.myLab.FindChild( DataTag_Types ).FindAttribute( TDataStd_ExtStringArray::GetID(), myArray );
95 }
96
97 /**
98   Destructor
99 */
100 HYDROData_LandCoverMap::Iterator::~Iterator()
101 {
102   delete myIterator;
103 }
104
105 /**
106   Return if the iterator has more elements
107   @return if the iterator has more elements
108 */
109 bool HYDROData_LandCoverMap::Iterator::More() const
110 {
111   return !myArray.IsNull() && myIterator && myIterator->More();
112 }
113
114 /**
115   Move iterator to the next element
116 */
117 void HYDROData_LandCoverMap::Iterator::Next()
118 {
119   if( myIterator )
120   {
121     myIterator->Next();
122     myIndex++;
123   }
124 }
125
126 /**
127   Get the current land cover (face)
128   @return the land cover's face
129 */
130 TopoDS_Face HYDROData_LandCoverMap::Iterator::Face() const
131 {
132   if( myIterator )
133     return TopoDS::Face( myIterator->Value() );
134   else
135     return TopoDS_Face();
136 }
137
138 /**
139   Get the current land cover's Strickler type 
140   @return the land cover's Strickler type 
141 */
142 QString HYDROData_LandCoverMap::Iterator::StricklerType() const
143 {
144   if( myArray.IsNull() || myIndex < myArray->Lower() || myIndex > myArray->Upper() )
145     return "";
146   else
147     return HYDROData_Tool::toQString( myArray->Value( myIndex ) );
148 }
149
150 /**
151   Constructor
152 */
153 HYDROData_LandCoverMap::HYDROData_LandCoverMap()
154   : HYDROData_Entity( Geom_No )
155 {
156 }
157
158 /**
159   Destructor
160 */
161 HYDROData_LandCoverMap::~HYDROData_LandCoverMap()
162 {
163 }
164
165 /**
166   Get object's kind
167   @return object's kind
168 */
169 const ObjectKind HYDROData_LandCoverMap::GetKind() const
170 {
171   return KIND_LAND_COVER_MAP;
172 }
173
174 /**
175   Import the land cover map from QGIS
176   @param theFileName the name of file
177   @return if the import is successful
178 */
179 bool HYDROData_LandCoverMap::ImportQGIS( const QString& theFileName )
180 {
181   //TODO
182   return false;
183 }
184
185 /**
186   Export the land cover map to QGIS
187   @param theFileName the name of file
188   @return if the export is successful
189 */
190 bool HYDROData_LandCoverMap::ExportQGIS( const QString& theFileName ) const
191 {
192   //TODO
193   return false;
194 }
195
196 int HashCode( const gp_Pnt& thePoint, const Standard_Integer theUpper )
197 {
198   int aHashX = HashCode( thePoint.X(), theUpper );
199   int aHashY = HashCode( thePoint.Y(), theUpper );
200   return (aHashX^aHashY)%theUpper;
201 }
202
203 bool operator == ( const gp_Pnt& thePoint1, const gp_Pnt& thePoint2 )
204 {
205   return thePoint1.IsEqual( thePoint2, Precision::Confusion() );
206 }
207
208 bool EdgeDiscretization( const TopoDS_Edge& theEdge, 
209                          Standard_Real theDeflection,
210                          NCollection_IndexedMap<gp_Pnt>& theVerticesMap,
211                          QList<int>& theVerticesIds )
212 {
213   BRepAdaptor_Curve aCurve( theEdge );
214   GCPnts_QuasiUniformDeflection aDiscrete( aCurve, theDeflection );
215   if( !aDiscrete.IsDone() )
216     return false;
217
218   int n = aDiscrete.NbPoints();
219   for( int i=1; i<=n; i++ )
220   {
221     gp_Pnt aPnt = aDiscrete.Value( i );
222     int anId;
223     if( theVerticesMap.Contains( aPnt ) )
224       anId = theVerticesMap.FindIndex( aPnt );
225     else
226     {
227       anId = theVerticesMap.Size();
228       theVerticesMap.Add( aPnt );
229     }
230     theVerticesIds.append( anId );
231   }
232   return true;
233 }
234
235 /**
236   Export the land cover map for the solver (Telemac)
237   @param theFileName the name of file
238   @return if the export is successful
239 */
240 bool HYDROData_LandCoverMap::ExportTelemac( const QString& theFileName, Standard_Real theDeflection ) const
241 {
242   TopoDS_Shell aShell;  //TODO: unite all the faces of land covers into the shell
243
244   NCollection_IndexedMap<gp_Pnt> aVerticesMap;
245   NCollection_IndexedDataMap< TopoDS_Edge, QList<int> > anEdgesMap;
246   NCollection_IndexedDataMap< TopoDS_Face, QList<int> > aFacesMap;
247
248   // add into the map all edges existing in the shell
249   TopExp_Explorer anExp1( aShell, TopAbs_EDGE );
250   for( ; anExp1.More(); anExp1.Next() )
251   {
252     TopoDS_Edge anEdge = TopoDS::Edge( anExp1.Current() );
253     QList<int> aVerticesIdsList;
254     if( EdgeDiscretization( anEdge, theDeflection, aVerticesMap, aVerticesIdsList ) )
255       anEdgesMap.Add( anEdge, aVerticesIdsList );
256   }
257
258   // add into the map all faces existing in the shell and correspondence between face and edges ids
259   TopExp_Explorer anExp2( aShell, TopAbs_FACE );
260   for( ; anExp2.More(); anExp2.Next() )
261   {
262     TopoDS_Face aFace = TopoDS::Face( anExp2.Current() );
263     TopExp_Explorer anExp3( aFace, TopAbs_EDGE );
264     QList<int> anEdgesIdsList;
265     for( ; anExp3.More(); anExp3.Next() )
266     {
267       TopoDS_Edge anEdge = TopoDS::Edge( anExp3.Current() );
268       int anEdgeId = anEdgesMap.FindIndex( anEdge );
269       anEdgesIdsList.append( anEdgeId );
270     }
271     aFacesMap.Add( aFace, anEdgesIdsList );
272   }
273
274   QFile aFile( theFileName );
275   if( !aFile.open( QFile::WriteOnly | QFile::Text ) )
276     return false;
277
278   QTextStream aStream( &aFile );
279   aStream << "# nodes\n";
280   NCollection_IndexedMap<gp_Pnt>::Iterator anIt1( aVerticesMap );
281   for( ; anIt1.More(); anIt1.Next() )
282   {
283     gp_Pnt aPnt = anIt1.Value();
284     aStream << QString::number( aPnt.X(), TELEMAC_FORMAT, TELEMAC_PRECISION );
285     aStream << " ";
286     aStream << QString::number( aPnt.Y(), TELEMAC_FORMAT, TELEMAC_PRECISION );
287     aStream << " ";
288     aStream << QString::number( aPnt.Z(), TELEMAC_FORMAT, TELEMAC_PRECISION );
289     aStream << "\n";
290   }
291   aStream << "\n";
292
293   aStream << "# edges\n";
294   NCollection_IndexedDataMap< TopoDS_Edge, QList<int> >::Iterator anIt2( anEdgesMap );
295   for( ; anIt2.More(); anIt2.Next() )
296   {
297     QList<int> aVerticesIds = anIt2.Value();
298     foreach( int anId, aVerticesIds )
299       aStream << anId << " ";
300     aStream << "\n";
301   }
302   aStream << "\n";
303
304   aStream << "# faces\n";
305   NCollection_IndexedDataMap< TopoDS_Face, QList<int> >::Iterator anIt3( aFacesMap );
306   for( ; anIt3.More(); anIt3.Next() )
307   {
308     QList<int> anEdgesIds = anIt3.Value();
309     foreach( int anId, anEdgesIds )
310       aStream << anId << " ";
311     aStream << "\n";
312   }
313   aStream << "\n";
314
315   aFile.close();
316   return true;
317 }
318
319 /**
320   Add a new object as land cover
321   @param theObject the object to add as land cover
322   @param theType the Strickler type for the new land cover
323   @return if the addition is successful
324 */
325 bool HYDROData_LandCoverMap::Add( const Handle( HYDROData_Object )& theObject, const QString& theType )
326 {
327   if( theObject.IsNull() )
328     return false;
329
330   TopoDS_Shape aShape = theObject->GetTopShape();
331   if( aShape.ShapeType()!=TopAbs_FACE )
332     return false;
333
334   TopoDS_Face aFace = TopoDS::Face( aShape );
335   return LocalPartition( aFace, theType );
336 }
337
338 /**
339   Add a new polyline as land cover
340   @param thePolyline the polyline to add as land cover
341   @param theType the Strickler type for the new land cover
342   @return if the addition is successful
343 */
344 bool HYDROData_LandCoverMap::Add( const Handle( HYDROData_PolylineXY )& thePolyline, const QString& theType )
345 {
346   if( thePolyline.IsNull() )
347     return false;
348
349   TopoDS_Shape aShape = thePolyline->GetShape();
350   if( aShape.ShapeType()!=TopAbs_WIRE )
351     return false;
352
353   TopoDS_Wire aWire = TopoDS::Wire( aShape );
354   if( !aWire.Closed() )
355     return false;
356
357   TopoDS_Face aFace = BRepBuilderAPI_MakeFace( aWire, Standard_True ).Face();
358   return LocalPartition( aFace, theType );
359 }
360
361 /**
362   Remove the given face from land cover map
363   @param theFace the face to be removed
364   @return if the removing is successful
365 */
366 bool HYDROData_LandCoverMap::Remove( const TopoDS_Face& theFace )
367 {
368   TopTools_ListOfShape aList;
369   aList.Append( theFace );
370   return Remove( aList );
371 }
372
373 /**
374   Remove the given faces from land cover map
375   @param theFacesToRemove the face list to be removed
376   @return if the removing is successful
377 */
378 bool HYDROData_LandCoverMap::Remove( const TopTools_ListOfShape& theFacesToRemove )
379 {
380   HYDROData_MapOfFaceToStricklerType aFacesToRemove, aNewFaces;
381   TopTools_ListIteratorOfListOfShape aFIt( theFacesToRemove );
382   for( ; aFIt.More(); aFIt.Next() )
383   {
384     TopoDS_Shape aShape = aFIt.Value();
385     if( aShape.ShapeType()==TopAbs_FACE )
386       aFacesToRemove.Add( TopoDS::Face( aShape ), "" );
387   }
388
389   Iterator anIt( *this );
390   for( ; anIt.More(); anIt.Next() )
391     if( !aFacesToRemove.Contains( anIt.Face() ) )
392       aNewFaces.Add( anIt.Face(), anIt.StricklerType() );
393
394   StoreLandCovers( aNewFaces );
395   return true;
396 }
397
398 /**
399   Split the land cover map by the given polyline
400   @param thePolyline the tool polyline to split the land cover map
401   @return if the removing is successful
402 */
403 bool HYDROData_LandCoverMap::Split( const Handle( HYDROData_PolylineXY )& thePolyline )
404 {
405   if( thePolyline.IsNull() )
406     return false;
407
408   TopoDS_Shape aShape = thePolyline->GetShape();
409   return LocalPartition( aShape, "" );
410 }
411
412 /**
413   Merge the given faces in the land cover
414   @param theFaces the faces to merge in the land cover map
415   @param theType the Strickler type for the merged land cover
416   @return if the merge is successful
417 */
418 bool HYDROData_LandCoverMap::Merge( const TopTools_ListOfShape& theFaces, const QString& theType )
419 {
420   // 1. to fuse the faces into the new face
421   TopoDS_Shape aMergedFace;
422   if( MergeFaces( theFaces, true, aMergedFace ) )
423   {
424     if( aMergedFace.ShapeType()==TopAbs_FACE )
425     {
426       // 2. to remove the merged faces from the current map
427       Remove( theFaces );
428
429       // 3. to add the face into the map
430       return LocalPartition( TopoDS::Face( aMergedFace ), theType );
431     }
432   }
433   return false;
434 }
435
436 bool HYDROData_LandCoverMap::MergeFaces(const TopTools_ListOfShape& theFaces, bool IsToUnify, TopoDS_Shape& outSh)
437 {
438   int iErr;
439   TopTools_ListIteratorOfListOfShape aIt;
440   BOPCol_ListOfShape aLC;
441   aIt.Initialize(theFaces);
442   for (; aIt.More(); aIt.Next()) {
443     const TopoDS_Shape& aS=aIt.Value();
444     aLC.Append(aS);
445   }
446   BOPAlgo_PaveFiller aPF;
447   aPF.SetArguments(aLC);
448   aPF.SetRunParallel(Standard_False);
449   aPF.SetFuzzyValue(1e-02);
450
451   aPF.Perform();
452   iErr=aPF.ErrorStatus();
453   if (iErr)
454     return false;
455
456   BOPAlgo_Builder aBuilder;
457   aIt.Initialize(theFaces);
458   for (; aIt.More(); aIt.Next()) {
459     const TopoDS_Shape& aS=aIt.Value();
460     aBuilder.AddArgument(aS);
461   }
462
463   aBuilder.PerformWithFiller(aPF); 
464   iErr = aBuilder.ErrorStatus();
465   if (iErr)
466     return false;
467   const TopoDS_Shape& aMergedShape=aBuilder.Shape();
468
469   //
470   BRep_Builder BB;
471   TopoDS_Shell she; 
472   BB.MakeShell(she); 
473   she.Closed(Standard_False);
474   TopExp_Explorer ff(aMergedShape, TopAbs_FACE);
475   for(; ff.More(); ff.Next()) 
476   {
477     const TopoDS_Face& F = TopoDS::Face(ff.Current());
478     if (F.IsNull()) 
479       continue;
480     if (F.ShapeType() == TopAbs_FACE) {
481       BB.Add(she, F);
482       she.Closed (Standard_False);
483     }
484   }
485
486   if (IsToUnify)
487   {
488     ShapeUpgrade_UnifySameDomain USD;
489     USD.Initialize(she);
490     USD.Build();
491     outSh = USD.Shape();
492   }
493   else
494   {
495     outSh = she;
496   }
497
498   ff.Init(outSh, TopAbs_FACE);
499   int i = 0;
500   TopoDS_Face OneF;
501   for(; ff.More(); ff.Next(), i++) 
502     OneF = TopoDS::Face(ff.Current());
503   if (i == 1)
504     outSh = OneF;
505
506   return true;
507
508 }
509
510 /**
511   Get the shape of the land cover map
512 */
513 TopoDS_Shape HYDROData_LandCoverMap::GetShape() const
514 {
515   return HYDROData_Entity::GetShape( DataTag_Shape );
516 }
517
518 /**
519   Set the shape of the land cover map
520   @param theShape the new shape for the land cover map
521 */
522 void HYDROData_LandCoverMap::SetShape( const TopoDS_Shape& theShape )
523 {
524   HYDROData_Entity::SetShape( DataTag_Shape, theShape );
525 }
526
527 /**
528   Perform the local partition algorithm on the land cover
529   @param theNewShape the new shape to add into the land cover
530   @param theNewType the new Strickler type for the new land cover
531   @return if the local partition is successful
532 */
533 bool HYDROData_LandCoverMap::LocalPartition( const TopoDS_Shape& theNewShape, const QString& theNewType )
534 {
535   if( theNewShape.IsNull() )
536     return false;
537
538   BOPCol_ListOfShape aShapesList;
539   BOPAlgo_PaveFiller aPaveFiller;
540   HYDROData_MapOfFaceToStricklerType aNewFaces;
541
542   // add faces to shapes list
543   Iterator anIt( *this );
544   for( ; anIt.More(); anIt.Next() )
545     aShapesList.Append( anIt.Face() );
546   aShapesList.Append( theNewShape );
547
548   if( aShapesList.Size()==1 && theNewShape.ShapeType()==TopAbs_FACE )
549   {
550     aNewFaces.Add( TopoDS::Face( theNewShape ), theNewType );
551     StoreLandCovers( aNewFaces );
552     return true;
553   }
554
555   // prepare pave filler
556   aPaveFiller.SetArguments( aShapesList );
557   aPaveFiller.Perform();
558   Standard_Integer anError = aPaveFiller.ErrorStatus();
559   if( anError )
560     return false;
561
562   // add faces to builder
563   BOPAlgo_Builder aBuilder;
564   anIt.Init( *this );
565   for( ; anIt.More(); anIt.Next() )
566     aBuilder.AddArgument( anIt.Face() );
567   aBuilder.AddArgument( theNewShape );
568
569   // perform the partition with the pave filler
570   aBuilder.PerformWithFiller( aPaveFiller );
571   anError = aBuilder.ErrorStatus();
572   if( anError )
573     return false;
574
575   // analysis of the history
576   //     a. to fill map of shapes which come from the new face
577   NCollection_IndexedMap<TopoDS_Shape> aShapesFromNewFace;
578   //std::cout << "new: " << theNewShape << " " << theNewType << std::endl;
579   TopTools_ListOfShape aModified = aBuilder.Modified( theNewShape );
580   TopTools_ListIteratorOfListOfShape aMIt( aModified );
581   for( ; aMIt.More(); aMIt.Next() )
582   {
583     //std::cout << "   " << aMIt.Value() << std::endl;
584     aShapesFromNewFace.Add( aMIt.Value() );
585   }
586
587   //     b. to fill map of parts except parts from new face
588   anIt.Init( *this );
589   for( ; anIt.More(); anIt.Next() )
590   {
591     QString aSType = anIt.StricklerType();
592     //std::cout << anIt.Face() << " " << anIt.StricklerType() << std::endl;
593     TopTools_ListOfShape aModified = aBuilder.Modified( anIt.Face() );
594     TopTools_ListIteratorOfListOfShape aMIt( aModified );
595     for( ; aMIt.More(); aMIt.Next() )
596     {
597       TopoDS_Shape aShape = aMIt.Value();
598       bool isFace = aShape.ShapeType()==TopAbs_FACE;
599       bool isAlsoFromNew = aShapesFromNewFace.Contains( aShape );
600       //std::cout << "   " << aShape << " " << isAlsoFromNew << std::endl;
601       if( isFace && !isAlsoFromNew )
602         aNewFaces.Add( TopoDS::Face( aShape ), aSType );
603     }
604   }
605
606   //     c. add the new shape if it is face with its type
607   if( theNewShape.ShapeType()==TopAbs_FACE )
608     aNewFaces.Add( TopoDS::Face( theNewShape ), theNewType );
609   
610   // convert map of shape to type to compound and list of types
611   StoreLandCovers( aNewFaces );
612   return true;
613 }
614
615 /**
616   Replace the set of land covers in the land cover map
617   @param theMap the map of shape (face) to Strickler type (string)
618 */
619 void HYDROData_LandCoverMap::StoreLandCovers( const HYDROData_MapOfFaceToStricklerType& theMap )
620 {
621   TopoDS_Compound aCompound;
622   BRep_Builder aCompoundBuilder;
623   aCompoundBuilder.MakeCompound( aCompound );
624
625   int n = theMap.Size();
626   Handle( TDataStd_ExtStringArray ) aTypes = 
627     TDataStd_ExtStringArray::Set( myLab.FindChild( DataTag_Types ), 0, n-1, Standard_True );
628   HYDROData_MapOfFaceToStricklerType::Iterator aNFIt( theMap );
629   for( int i=0; aNFIt.More(); aNFIt.Next(), i++ )
630   {
631     TopoDS_Face aFace = aNFIt.Key();
632     QString aType = aNFIt.Value();
633     aCompoundBuilder.Add( aCompound, aFace );
634     aTypes->SetValue( i, HYDROData_Tool::toExtString( aType ) );
635   }
636
637   SetShape( aCompound );
638 }
639
640 /**
641   Find the land cover for the given point
642   @param thePoint the point laying in some land cover
643   @param theType the returned type
644   @return the found land cover's face
645 */
646 TopoDS_Face HYDROData_LandCoverMap::FindByPoint( const gp_Pnt2d& thePoint, QString& theType ) const
647 {
648   //TODO: some more optimal algorithm
649   Iterator anIt( *this );
650   for( ; anIt.More(); anIt.Next() )
651     if( HYDROData_Tool::ComputePointState( thePoint.XY(), anIt.Face() ) == TopAbs_IN )
652     {
653       theType = anIt.StricklerType();
654       return anIt.Face();
655     }
656
657   theType = "";
658   return TopoDS_Face();
659 }