Salome HOME
copyrights are updated
[modules/hydro.git] / src / HYDROData / HYDROData_LandCoverMap.cxx
index f384999d11989ae221cc289c50543da1c91bb8d3..a429e381ae43931784e002cf925fac6169926e8a 100644 (file)
 #include <HYDROData_Object.h>
 #include <HYDROData_PolylineXY.h>
 #include <HYDROData_Tool.h>
+#include <HYDROData_ShapeFile.h>
 
+#include <BOPAlgo_BOP.hxx>
 #include <BOPAlgo_Builder.hxx>
 #include <BOPAlgo_PaveFiller.hxx>
 #include <BOPCol_ListOfShape.hxx>
 #include <BRep_Builder.hxx>
+#include <BRepAdaptor_Curve.hxx>
+#include <BRepAlgoAPI_Fuse.hxx>
+#include <BRepBuilderAPI_MakeFace.hxx>
+#include <GCPnts_QuasiUniformDeflection.hxx>
 #include <NCollection_IndexedMap.hxx>
-#include <TNaming_Builder.hxx>
-#include <TNaming_NamedShape.hxx>
 #include <TopoDS.hxx>
 #include <TopoDS_Compound.hxx>
+#include <TopoDS_Edge.hxx>
 #include <TopoDS_Face.hxx>
 #include <TopoDS_Iterator.hxx>
 #include <TopoDS_Shell.hxx>
+#include <TopExp_Explorer.hxx>
 #include <TopTools_ListIteratorOfListOfShape.hxx>
+#include <BOPAlgo_PaveFiller.hxx>
+#include <BRepTools.hxx>
+#include <TopExp_Explorer.hxx>
+#include <ShapeUpgrade_UnifySameDomain.hxx>
 
+#include <QFile>
 #include <QString>
+#include <QTextStream>
+
+const char TELEMAC_FORMAT = 'f';
+const int TELEMAC_PRECISION = 3;
+
 
 IMPLEMENT_STANDARD_HANDLE(HYDROData_LandCoverMap, HYDROData_Entity)
 IMPLEMENT_STANDARD_RTTIEXT(HYDROData_LandCoverMap, HYDROData_Entity)
@@ -75,8 +91,12 @@ void HYDROData_LandCoverMap::Iterator::Init( const HYDROData_LandCoverMap& theMa
     myIterator = 0;
   else
     myIterator = new TopoDS_Iterator( aShape );
-  myIndex = 0;
+  
   theMap.myLab.FindChild( DataTag_Types ).FindAttribute( TDataStd_ExtStringArray::GetID(), myArray );
+  if( myArray.IsNull() )
+    myIndex = -1;
+  else
+    myIndex = myArray->Lower();
 }
 
 /**
@@ -87,6 +107,18 @@ HYDROData_LandCoverMap::Iterator::~Iterator()
   delete myIterator;
 }
 
+/**
+  Return the current 0-based index of the iterator
+  @return the current index
+*/
+int HYDROData_LandCoverMap::Iterator::Index() const
+{
+  if( myArray.IsNull() )
+    return -1;
+  else
+    return myIndex - myArray->Lower();
+}
+
 /**
   Return if the iterator has more elements
   @return if the iterator has more elements
@@ -132,10 +164,23 @@ QString HYDROData_LandCoverMap::Iterator::StricklerType() const
     return HYDROData_Tool::toQString( myArray->Value( myIndex ) );
 }
 
+/**
+  Set the Strickler type for the current land cover
+  @param theType the Strickler type
+*/
+void HYDROData_LandCoverMap::Iterator::SetStricklerType( const QString& theType )
+{
+  if( myArray.IsNull() || myIndex < myArray->Lower() || myIndex > myArray->Upper() )
+    return;
+  else
+    myArray->SetValue( myIndex, HYDROData_Tool::toExtString( theType ) );
+}
+
 /**
   Constructor
 */
 HYDROData_LandCoverMap::HYDROData_LandCoverMap()
+  : HYDROData_Entity( Geom_No )
 {
 }
 
@@ -156,25 +201,116 @@ const ObjectKind HYDROData_LandCoverMap::GetKind() const
 }
 
 /**
-  Import the land cover map from QGIS
-  @param theFileName the name of file
-  @return if the import is successful
+  Load attributes from DBF File
+///
 */
-bool HYDROData_LandCoverMap::ImportQGIS( const QString& theFileName )
+HYDROData_LandCoverMap::DBFStatus HYDROData_LandCoverMap::ImportDBF( const QString& theDBFFileName, 
+                                                                     const QString& theFieldName, 
+                                                                     const QStringList& theDBFValues,
+                                                                     const QStringList& theStricklerTypes,
+                                                                     const QList<int>& theIndices )
 {
-  //TODO
-  return false;
+  if (theDBFValues.size() != theStricklerTypes.size())
+    return DBFStatus_DIFF_SIZE_ERROR;
+  HYDROData_ShapeFile aDBFImporter;
+  if (!aDBFImporter.DBF_OpenDBF(theDBFFileName))
+    return DBFStatus_OPEN_FILE_ERROR; //cant open file
+
+  QStringList FieldList = aDBFImporter.DBF_GetFieldList();
+  int FieldNameIndex = FieldList.indexOf(theFieldName);
+  if (FieldNameIndex == -1)
+    return DBFStatus_NO_SUCH_FIELD_ERROR; //no such field
+
+  std::vector<HYDROData_ShapeFile::DBF_AttrValue> theAttrV;
+  aDBFImporter.DBF_GetAttributeList(FieldNameIndex, theAttrV ); 
+
+  bool allOK = true;
+  Iterator anIt( *this );
+  for( ; anIt.More(); anIt.Next() )
+  {
+    int CurIndex = anIt.Index();
+    HYDROData_ShapeFile::DBF_AttrValue AValue = theAttrV[theIndices[CurIndex]];
+    int StricklerTypesInd = theDBFValues.indexOf(QString(AValue.myStrVal));
+    if ( StricklerTypesInd != -1)
+      anIt.SetStricklerType(theStricklerTypes[StricklerTypesInd]);
+    else
+      allOK = false;
+  }
+  if (allOK)
+    return DBFStatus_OK;
+  else
+    return DBFStatus_NO_DBFVALUES_CORRESPONDENCE_WARNING;
 }
 
 /**
-  Export the land cover map to QGIS
-  @param theFileName the name of file
-  @return if the export is successful
+  Export attributes to DBF File
+///
 */
-bool HYDROData_LandCoverMap::ExportQGIS( const QString& theFileName ) const
+void HYDROData_LandCoverMap::ExportDBF( const QString& theDBFFileName, 
+                                        const QString& theFieldName, 
+                                        const QStringList& theDBFValues,
+                                        const QStringList& theStricklerTypes) const
 {
-  //TODO
-  return false;
+  HYDROData_ShapeFile anExporter; 
+  std::vector<HYDROData_ShapeFile::DBF_AttrValue> theAttrV;
+  Iterator anIt( *this );
+  for( ; anIt.More(); anIt.Next() )
+  {
+    QString CurST = anIt.StricklerType();
+    HYDROData_ShapeFile::DBF_AttrValue aCurAttrV;
+    aCurAttrV.myIsNull = false;
+    int StricklerTypesInd = theStricklerTypes.indexOf(CurST);
+    if (StricklerTypesInd != -1)
+    {
+      aCurAttrV.myStrVal = theDBFValues[StricklerTypesInd];
+      aCurAttrV.myFieldType = HYDROData_ShapeFile::DBF_FieldType_String;
+      theAttrV.push_back(aCurAttrV);
+    }
+    else
+      aCurAttrV.myIsNull = true;
+  }
+
+  anExporter.DBF_WriteFieldAndValues(theDBFFileName, theFieldName, HYDROData_ShapeFile::DBF_FieldType_String, theAttrV, true);
+
+}
+
+int HashCode( const gp_Pnt& thePoint, const Standard_Integer theUpper )
+{
+  int aHashX = HashCode( thePoint.X(), theUpper );
+  int aHashY = HashCode( thePoint.Y(), theUpper );
+  return (aHashX^aHashY)%theUpper;
+}
+
+bool operator == ( const gp_Pnt& thePoint1, const gp_Pnt& thePoint2 )
+{
+  return thePoint1.IsEqual( thePoint2, Precision::Confusion() );
+}
+
+bool EdgeDiscretization( const TopoDS_Edge& theEdge, 
+                         Standard_Real theDeflection,
+                         NCollection_IndexedMap<gp_Pnt>& theVerticesMap,
+                         QList<int>& theVerticesIds )
+{
+  BRepAdaptor_Curve aCurve( theEdge );
+  GCPnts_QuasiUniformDeflection aDiscrete( aCurve, theDeflection );
+  if( !aDiscrete.IsDone() )
+    return false;
+
+  int n = aDiscrete.NbPoints();
+  for( int i=1; i<=n; i++ )
+  {
+    gp_Pnt aPnt = aDiscrete.Value( i );
+    int anId;
+    if( theVerticesMap.Contains( aPnt ) )
+      anId = theVerticesMap.FindIndex( aPnt );
+    else
+    {
+      anId = theVerticesMap.Size();
+      theVerticesMap.Add( aPnt );
+    }
+    theVerticesIds.append( anId );
+  }
+  return true;
 }
 
 /**
@@ -182,10 +318,89 @@ bool HYDROData_LandCoverMap::ExportQGIS( const QString& theFileName ) const
   @param theFileName the name of file
   @return if the export is successful
 */
-bool HYDROData_LandCoverMap::ExportTelemac( const QString& theFileName ) const
+bool HYDROData_LandCoverMap::ExportTelemac( const QString& theFileName, Standard_Real theDeflection ) const
 {
-  //TODO
-  return false;
+  TopoDS_Shape aLandCoverMapShape = GetShape();
+  TopTools_ListOfShape aListOfFaces;
+  TopExp_Explorer anExp( aLandCoverMapShape, TopAbs_FACE );
+  for( ; anExp.More(); anExp.Next() )
+    aListOfFaces.Append( anExp.Current() );
+
+  TopoDS_Shape aShape = MergeFaces( aListOfFaces, false );
+
+  NCollection_IndexedMap<gp_Pnt> aVerticesMap;
+  NCollection_IndexedDataMap< TopoDS_Edge, QList<int> > anEdgesMap;
+  NCollection_IndexedDataMap< TopoDS_Face, QList<int> > aFacesMap;
+
+  // add into the map all edges existing in the shell
+  TopExp_Explorer anExp1( aShape, TopAbs_EDGE );
+  for( ; anExp1.More(); anExp1.Next() )
+  {
+    TopoDS_Edge anEdge = TopoDS::Edge( anExp1.Current() );
+    QList<int> aVerticesIdsList;
+    if( EdgeDiscretization( anEdge, theDeflection, aVerticesMap, aVerticesIdsList ) )
+      anEdgesMap.Add( anEdge, aVerticesIdsList );
+  }
+
+  // add into the map all faces existing in the shell and correspondence between face and edges ids
+  TopExp_Explorer anExp2( aShape, TopAbs_FACE );
+  for( ; anExp2.More(); anExp2.Next() )
+  {
+    TopoDS_Face aFace = TopoDS::Face( anExp2.Current() );
+    TopExp_Explorer anExp3( aFace, TopAbs_EDGE );
+    QList<int> anEdgesIdsList;
+    for( ; anExp3.More(); anExp3.Next() )
+    {
+      TopoDS_Edge anEdge = TopoDS::Edge( anExp3.Current() );
+      int anEdgeId = anEdgesMap.FindIndex( anEdge );
+      anEdgesIdsList.append( anEdgeId );
+    }
+    aFacesMap.Add( aFace, anEdgesIdsList );
+  }
+
+  QFile aFile( theFileName );
+  if( !aFile.open( QFile::WriteOnly | QFile::Text ) )
+    return false;
+
+  QTextStream aStream( &aFile );
+  aStream << "# nodes\n";
+  NCollection_IndexedMap<gp_Pnt>::Iterator anIt1( aVerticesMap );
+  for( ; anIt1.More(); anIt1.Next() )
+  {
+    gp_Pnt aPnt = anIt1.Value();
+    aStream << QString::number( aPnt.X(), TELEMAC_FORMAT, TELEMAC_PRECISION );
+    aStream << " ";
+    aStream << QString::number( aPnt.Y(), TELEMAC_FORMAT, TELEMAC_PRECISION );
+    aStream << " ";
+    aStream << QString::number( aPnt.Z(), TELEMAC_FORMAT, TELEMAC_PRECISION );
+    aStream << "\n";
+  }
+  aStream << "\n";
+
+  aStream << "# edges\n";
+  NCollection_IndexedDataMap< TopoDS_Edge, QList<int> >::Iterator anIt2( anEdgesMap );
+  for( ; anIt2.More(); anIt2.Next() )
+  {
+    QList<int> aVerticesIds = anIt2.Value();
+    foreach( int anId, aVerticesIds )
+      aStream << anId << " ";
+    aStream << "\n";
+  }
+  aStream << "\n";
+
+  aStream << "# faces\n";
+  NCollection_IndexedDataMap< TopoDS_Face, QList<int> >::Iterator anIt3( aFacesMap );
+  for( ; anIt3.More(); anIt3.Next() )
+  {
+    QList<int> anEdgesIds = anIt3.Value();
+    foreach( int anId, anEdgesIds )
+      aStream << anId << " ";
+    aStream << "\n";
+  }
+  aStream << "\n";
+
+  aFile.close();
+  return true;
 }
 
 /**
@@ -215,8 +430,19 @@ bool HYDROData_LandCoverMap::Add( const Handle( HYDROData_Object )& theObject, c
 */
 bool HYDROData_LandCoverMap::Add( const Handle( HYDROData_PolylineXY )& thePolyline, const QString& theType )
 {
-  //TODO
-  return false;
+  if( thePolyline.IsNull() )
+    return false;
+
+  TopoDS_Shape aShape = thePolyline->GetShape();
+  if( aShape.ShapeType()!=TopAbs_WIRE )
+    return false;
+
+  TopoDS_Wire aWire = TopoDS::Wire( aShape );
+  if( !aWire.Closed() )
+    return false;
+
+  TopoDS_Face aFace = BRepBuilderAPI_MakeFace( aWire, Standard_True ).Face();
+  return LocalPartition( aFace, theType );
 }
 
 /**
@@ -233,16 +459,26 @@ bool HYDROData_LandCoverMap::Remove( const TopoDS_Face& theFace )
 
 /**
   Remove the given faces from land cover map
-  @param theFacesList the face list to be removed
+  @param theFacesToRemove the face list to be removed
   @return if the removing is successful
 */
-bool HYDROData_LandCoverMap::Remove( const TopTools_ListOfShape& theFacesList )
+bool HYDROData_LandCoverMap::Remove( const TopTools_ListOfShape& theFacesToRemove )
 {
-  TopoDS_Compound aCompound = TopoDS::Compound( GetShape() );
-  BRep_Builder aCompoundBuilder;
-  //TODO: aCompoundBuilder.Remove( aCompound, theFace );
-  //TODO: update types
-  SetShape( aCompound );
+  HYDROData_MapOfFaceToStricklerType aFacesToRemove, aNewFaces;
+  TopTools_ListIteratorOfListOfShape aFIt( theFacesToRemove );
+  for( ; aFIt.More(); aFIt.Next() )
+  {
+    TopoDS_Shape aShape = aFIt.Value();
+    if( aShape.ShapeType()==TopAbs_FACE )
+      aFacesToRemove.Add( TopoDS::Face( aShape ), "" );
+  }
+
+  Iterator anIt( *this );
+  for( ; anIt.More(); anIt.Next() )
+    if( !aFacesToRemove.Contains( anIt.Face() ) )
+      aNewFaces.Add( anIt.Face(), anIt.StricklerType() );
+
+  StoreLandCovers( aNewFaces );
   return true;
 }
 
@@ -268,15 +504,93 @@ bool HYDROData_LandCoverMap::Split( const Handle( HYDROData_PolylineXY )& thePol
 */
 bool HYDROData_LandCoverMap::Merge( const TopTools_ListOfShape& theFaces, const QString& theType )
 {
-  // 1. to remove the merged faces from the current map
-  Remove( theFaces );
+  // 1. to fuse the faces into the new face
+  TopoDS_Shape aMergedFace = MergeFaces( theFaces, true );
+  if( aMergedFace.ShapeType()==TopAbs_FACE )
+  {
+    // 2. to remove the merged faces from the current map
+    Remove( theFaces );
 
-  // 2. to fuse the faces into the new face
-  // TODO
-  TopoDS_Face aMergedFace;
+    // 3. to add the face into the map
+    return LocalPartition( TopoDS::Face( aMergedFace ), theType );
+  }
+  return false;
+}
 
-  // 3. to add the face into the map
-  return LocalPartition( aMergedFace, theType );
+TopoDS_Shape HYDROData_LandCoverMap::MergeFaces( const TopTools_ListOfShape& theFaces,
+                                                 bool IsToUnify, double theTolerance )
+{
+  int anError;
+  TopTools_ListIteratorOfListOfShape anIt;
+  BOPCol_ListOfShape aLC;
+  anIt.Initialize(theFaces);
+  for( ; anIt.More(); anIt.Next() )
+  {
+    if (anIt.Value().ShapeType() != TopAbs_FACE)
+      return TopoDS_Shape();
+    aLC.Append( anIt.Value() );
+  }
+
+  BOPAlgo_PaveFiller aPF;
+  aPF.SetArguments( aLC );
+  aPF.SetRunParallel( Standard_False );
+  aPF.SetFuzzyValue( theTolerance );
+
+  aPF.Perform();
+  anError = aPF.ErrorStatus();
+  if( anError )
+    return TopoDS_Shape();
+
+  BOPAlgo_Builder anAlgo;
+  anIt.Initialize( theFaces );
+  for( ; anIt.More(); anIt.Next() )
+    anAlgo.AddArgument( anIt.Value() );
+
+  anAlgo.PerformWithFiller( aPF ); 
+  anError = anAlgo.ErrorStatus();
+  if( anError )
+    return TopoDS_Shape();
+
+  const TopoDS_Shape& aMergedShape = anAlgo.Shape();
+
+  BRep_Builder aBuilder;
+  TopoDS_Shell aShell; 
+  aBuilder.MakeShell( aShell ); 
+  aShell.Closed( Standard_False );
+  TopExp_Explorer anExplorer( aMergedShape, TopAbs_FACE );
+  for( ; anExplorer.More(); anExplorer.Next() ) 
+  {
+    const TopoDS_Face& aFace = TopoDS::Face(anExplorer.Current());
+    if( aFace.IsNull() ) 
+      continue;
+    if( aFace.ShapeType() == TopAbs_FACE )
+    {
+      aBuilder.Add( aShell, aFace );
+      aShell.Closed( Standard_False );
+    }
+  }
+
+  TopoDS_Shape aResult;
+  if( IsToUnify )
+  {
+    ShapeUpgrade_UnifySameDomain aUSD;
+    aUSD.Initialize( aShell );
+    aUSD.Build();
+    aResult = aUSD.Shape();
+  }
+  else
+    aResult = aShell;
+
+  anExplorer.Init( aResult, TopAbs_FACE );
+  int i = 0;
+  TopoDS_Face anOneFace;
+  for( ; anExplorer.More(); anExplorer.Next(), i++ ) 
+    anOneFace = TopoDS::Face( anExplorer.Current() );
+
+  if( i == 1 )
+    aResult = anOneFace;
+
+  return aResult;
 }
 
 /**
@@ -284,14 +598,7 @@ bool HYDROData_LandCoverMap::Merge( const TopTools_ListOfShape& theFaces, const
 */
 TopoDS_Shape HYDROData_LandCoverMap::GetShape() const
 {
-  TDF_Label aLabel = myLab.FindChild( DataTag_Shape, false );
-  if ( !aLabel.IsNull() )
-  {
-    Handle(TNaming_NamedShape) aNamedShape;
-    if( aLabel.FindAttribute( TNaming_NamedShape::GetID(), aNamedShape ) )
-      return aNamedShape->Get();
-  }
-  return TopoDS_Shape();
+  return HYDROData_Entity::GetShape( DataTag_Shape );
 }
 
 /**
@@ -300,8 +607,7 @@ TopoDS_Shape HYDROData_LandCoverMap::GetShape() const
 */
 void HYDROData_LandCoverMap::SetShape( const TopoDS_Shape& theShape )
 {
-  TNaming_Builder aBuilder( myLab.FindChild( DataTag_Shape ) );
-  aBuilder.Generated( theShape );
+  HYDROData_Entity::SetShape( DataTag_Shape, theShape );
 }
 
 /**
@@ -398,9 +704,11 @@ bool HYDROData_LandCoverMap::LocalPartition( const TopoDS_Shape& theNewShape, co
 */
 void HYDROData_LandCoverMap::StoreLandCovers( const HYDROData_MapOfFaceToStricklerType& theMap )
 {
-  TopoDS_Compound aCompound;
-  BRep_Builder aCompoundBuilder;
-  aCompoundBuilder.MakeCompound( aCompound );
+  TopoDS_Shell aShell;
+  BRep_Builder aShellBuilder;
+  aShellBuilder.MakeShell( aShell );
+  aShell.Closed( Standard_False );
+  TopTools_ListOfShape aListOfFaces;
 
   int n = theMap.Size();
   Handle( TDataStd_ExtStringArray ) aTypes = 
@@ -409,10 +717,59 @@ void HYDROData_LandCoverMap::StoreLandCovers( const HYDROData_MapOfFaceToStrickl
   for( int i=0; aNFIt.More(); aNFIt.Next(), i++ )
   {
     TopoDS_Face aFace = aNFIt.Key();
+    if (aFace.IsNull())
+      continue;
     QString aType = aNFIt.Value();
-    aCompoundBuilder.Add( aCompound, aFace );
+    aShellBuilder.Add( aShell, aFace );
+    aListOfFaces.Append(aFace);
     aTypes->SetValue( i, HYDROData_Tool::toExtString( aType ) );
   }
+  TopoDS_Shape aMF = MergeFaces(aListOfFaces, false);
+
+  SetShape( aListOfFaces.Extent() < 2 ? aShell : MergeFaces(aListOfFaces, false));
+}
+
+/**
+  Find the land cover for the given point
+  @param thePoint the point laying in some land cover
+  @param theType the returned type
+  @return the found land cover's face
+*/
+TopoDS_Face HYDROData_LandCoverMap::FindByPoint( const gp_Pnt2d& thePoint, QString& theType ) const
+{
+  //TODO: some more optimal algorithm
+  Iterator anIt( *this );
+  for( ; anIt.More(); anIt.Next() )
+    if( HYDROData_Tool::ComputePointState( thePoint.XY(), anIt.Face() ) == TopAbs_IN )
+    {
+      theType = anIt.StricklerType();
+      return anIt.Face();
+    }
+
+  theType = "";
+  return TopoDS_Face();
+}
+
+/**
+  Dump to Python
+  @param theTreatedObjects the map of treated objects
+*/
+QStringList HYDROData_LandCoverMap::DumpToPython( MapOfTreatedObjects& theTreatedObjects ) const
+{
+  QStringList aResList = dumpObjectCreation( theTreatedObjects );
+  QString aName = GetObjPyName();
+
+  //Handle(HYDROData_PolylineXY) aHydAxis = GetHydraulicAxis();
+  //setPythonReferenceObject( theTreatedObjects, aResList, aHydAxis, "SetHydraulicAxis" );
+
+  //HYDROData_SequenceOfObjects aSeqOfProfiles = GetProfiles();
+  //for ( int i = 1, aNb = aSeqOfProfiles.Size(); i <= aNb; ++i )
+  //{
+    //const Handle(HYDROData_Entity) aProfile = aSeqOfProfiles.Value( i );
+    //setPythonReferenceObject( theTreatedObjects, aResList, aProfile, "AddProfile" );
+  //}
+
+  //TODO
 
-  SetShape( aCompound );
+  return aResList;
 }