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.
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.
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
16 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
19 #include <HYDROData_Tool.h>
20 #include <HYDROData_ArtificialObject.h>
21 #include <HYDROData_Document.h>
22 #include <HYDROData_Entity.h>
23 #include <HYDROData_Iterator.h>
24 #include <HYDROData_NaturalObject.h>
25 #include <HYDROData_ShapesGroup.h>
26 #include <HYDROData_PolylineXY.h>
29 #include <QStringList>
30 #include <QTextStream>
32 #include <BRep_Tool.hxx>
33 #include <BRepAdaptor_Surface.hxx>
34 #include <BRepTopAdaptor_FClass2d.hxx>
36 #include <Geom_Curve.hxx>
38 #include <Quantity_Color.hxx>
39 #include <TopExp_Explorer.hxx>
41 #include <TopoDS_Face.hxx>
42 #include <TopoDS_Shape.hxx>
43 #include <TopoDS_Wire.hxx>
48 #include <BRepTools.hxx>
49 #include <NCollection_Map.hxx>
50 #include <TopTools_ShapeMapHasher.hxx>
51 #include <BRep_Builder.hxx>
52 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
54 #include <NCollection_List.hxx>
55 #include <TopTools_ListIteratorOfListOfShape.hxx>
57 #include <BRepBuilderAPI_MakeFace.hxx>
59 #include <TopExp_Explorer.hxx>
60 #include <TopTools_ListIteratorOfListOfShape.hxx>
61 #include <TopTools_HSequenceOfShape.hxx>
63 #include <BRep_Builder.hxx>
64 #include <BRepAlgo_FaceRestrictor.hxx>
65 #include <BRepCheck_Analyzer.hxx>
67 #include <ShapeAnalysis.hxx>
68 #include <ShapeAnalysis_FreeBounds.hxx>
71 HYDROData_Tool::ExecStatus HYDROData_Tool::myTriangulationStatus = ExecStatus::None;
73 static int aMaxNameId = INT_MAX;
74 static int aMaxColorNb = 92000;
75 void HYDROData_Tool::WriteStringsToFile( QFile& theFile,
76 const QStringList& theStrings,
77 const QString& theSep )
79 if ( !theFile.isOpen() || theStrings.isEmpty() )
82 QString aWriteStr = theStrings.join( theSep );
83 if ( aWriteStr.isEmpty() )
86 QTextStream anOutStream( &theFile );
87 anOutStream << aWriteStr.toUtf8() << theSep << theSep;
90 bool HYDROData_Tool::ExtractGeneratedObjectName(const QString& theName, int& outValue, QString& thePrefName)
92 QStringList aLs = theName.split('_');
94 QString last = aLs.last();
95 outValue = last.toInt(&ok);
98 int last_len = last.length();
99 int total_len = theName.length();
100 thePrefName = theName.left(total_len-last_len-1);
104 QString HYDROData_Tool::GenerateObjectName( const Handle(HYDROData_Document)& theDoc,
105 const QString& thePrefix,
106 const QStringList& theUsedNames,
107 const bool theIsTryToUsePurePrefix )
109 QStringList aNamesList( theUsedNames );
111 // Collect all used names in the document
112 HYDROData_Iterator anIter( theDoc );
113 for( ; anIter.More(); anIter.Next() )
115 Handle(HYDROData_Entity) anObject = anIter.Current();
116 if( anObject.IsNull() )
119 QString anObjName = anObject->GetName();
120 if ( anObjName.isEmpty() )
123 aNamesList.append( anObjName );
128 if ( theIsTryToUsePurePrefix && !aNamesList.contains( thePrefix ) ) {
132 while( anId < aMaxNameId )
134 aName = QString( "%1_%2" ).arg( thePrefix ).arg( QString::number( anId++ ) );
136 // check that there are no other objects with the same name in the document
137 if ( !aNamesList.contains( aName ) )
145 bool HYDROData_Tool::IsGeometryObject( const Handle(HYDROData_Entity)& theObject )
147 if ( theObject.IsNull() )
150 return theObject->IsKind( STANDARD_TYPE(HYDROData_ArtificialObject) ) ||
151 theObject->IsKind( STANDARD_TYPE(HYDROData_NaturalObject) );
154 void HYDROData_Tool::UpdateChildObjectName( const QString& theOldStr,
155 const QString& theNewStr,
156 const Handle(HYDROData_Entity)& theObject )
158 if ( theObject.IsNull() )
161 QString anObjName = theObject->GetName();
162 if ( theOldStr.isEmpty() )
164 while ( anObjName.startsWith( '_' ) )
165 anObjName.remove( 0, 1 );
167 anObjName.prepend( theNewStr + "_" );
169 else if ( anObjName.startsWith( theOldStr ) )
171 anObjName.replace( 0, theOldStr.length(), theNewStr );
176 theObject->SetName( anObjName );
179 QString HYDROData_Tool::GenerateNameForPython( const MapOfTreatedObjects& theTreatedObjects,
180 const QString& thePrefix )
182 QString aName = thePrefix;
183 if ( !theTreatedObjects.contains( aName ) )
187 while( anId < aMaxNameId )
189 aName = QString( "%1_%2" ).arg( thePrefix ).arg( QString::number( anId++ ) );
191 // check that there are no other objects with the same name
192 if ( !theTreatedObjects.contains( aName ) )
198 //======================================================================================================
199 TopAbs_State HYDROData_Tool::ComputePointState( const gp_XY& theXY, const TopoDS_Face& theFace )
201 TopAbs_State aState(TopAbs_UNKNOWN);
202 if(theFace.IsNull()) return aState;
203 Standard_Real aTol = BRep_Tool::Tolerance(theFace);
204 BRepAdaptor_Surface Ads ( theFace, Standard_False );
205 Standard_Real toluv = Min ( Ads.UResolution(aTol), Ads.VResolution(aTol) );
207 toluv = 0.01; // there is no need to be more precise than 1cm a any case !
208 // another solution could be to compute a tolerance related to the distance between the border nodes
209 const gp_Pln& aPlane = Ads.Surface().Plane();
210 gp_Pnt aPnt(theXY.X(), theXY.Y(), 0.);
211 Standard_Real aU1, aV1;
212 ElSLib::Parameters(aPlane,aPnt, aU1, aV1);
213 BRepTopAdaptor_FClass2d aClassifier( theFace, toluv );
214 aState = aClassifier.Perform( gp_Pnt2d(aU1, aV1), Standard_False );
218 double HYDROData_Tool::GetAltitudeForEdge( const TopoDS_Edge& theEdge,
219 const gp_XY& thePoint,
220 double theParameterTolerance,
221 double theSquareDistanceTolerance,
222 double theInvalidAltitude )
224 double aFirst, aLast;
225 Handle(Geom_Curve) aCurve = BRep_Tool::Curve( theEdge, aFirst, aLast );
226 if( aCurve.IsNull() )
227 return theInvalidAltitude;
229 gp_Pnt aFirstPnt, aLastPnt;
231 aCurve->D0( aFirst, aFirstPnt );
232 aCurve->D0( aLast, aLastPnt );
234 gp_Pnt2d aFirstPnt2d( aFirstPnt.X(), aFirstPnt.Y() );
235 gp_Pnt2d aLastPnt2d( aLastPnt.X(), aLastPnt.Y() );
237 double aFirstDist = 0;
238 double aLastDist = aFirstPnt2d.SquareDistance( aLastPnt2d );
239 double aNecDist = aFirstPnt2d.SquareDistance( thePoint );
241 while( fabs( aLast - aFirst ) > theParameterTolerance )
243 double aMid = ( aFirst + aLast ) / 2;
245 aCurve->D0( aMid, aMidPnt );
246 double aDist = aFirstPnt2d.SquareDistance( gp_Pnt2d( aMidPnt.X(), aMidPnt.Y() ) );
248 if( aDist < aNecDist )
254 double aMid = ( aFirst + aLast ) / 2;
256 aCurve->D0( aMid, aMidPnt );
258 gp_Pnt2d aMidPnt2d( aMidPnt.X(), aMidPnt.Y() );
259 if( aMidPnt2d.SquareDistance( thePoint ) < theSquareDistanceTolerance )
262 return theInvalidAltitude;
265 double HYDROData_Tool::GetAltitudeForWire( const TopoDS_Wire& theWire,
266 const gp_XY& thePoint,
267 double theParameterTolerance,
268 double theSquareDistanceTolerance,
269 double theInvalidAltitude )
271 TopExp_Explorer anExp( theWire, TopAbs_EDGE );
272 for( ; anExp.More(); anExp.Next() )
274 double anAltitude = GetAltitudeForEdge( TopoDS::Edge( anExp.Current() ), thePoint,
275 theParameterTolerance, theSquareDistanceTolerance, theInvalidAltitude );
276 if( anAltitude != theInvalidAltitude )
279 return theInvalidAltitude;
282 TopoDS_Shape HYDROData_Tool::getFirstShapeFromGroup( const HYDROData_SequenceOfObjects& theGroups,
283 const int theGroupId )
285 TopoDS_Shape aResShape;
286 if ( theGroupId < 1 || theGroupId > theGroups.Length() )
289 Handle(HYDROData_ShapesGroup) aGroup =
290 Handle(HYDROData_ShapesGroup)::DownCast( theGroups.Value( theGroupId ) );
291 if ( aGroup.IsNull() )
294 TopTools_SequenceOfShape aGroupShapes;
295 aGroup->GetShapes( aGroupShapes );
297 if ( !aGroupShapes.IsEmpty() )
298 aResShape = aGroupShapes.First();
303 TCollection_ExtendedString HYDROData_Tool::toExtString( const QString& theStr )
305 TCollection_ExtendedString aRes;
306 if( !theStr.isEmpty() )
308 Standard_ExtString extStr = new Standard_ExtCharacter[ ( theStr.length() + 1 ) * 2 ];
309 memcpy( (void*)extStr, theStr.unicode(), theStr.length() * 2 );
310 ((short*)extStr)[theStr.length()] = '\0';
311 aRes = TCollection_ExtendedString( extStr );
317 QString HYDROData_Tool::toQString( const TCollection_ExtendedString& theStr )
319 return QString( (QChar*)theStr.ToExtString(), theStr.Length() );
322 Quantity_Color HYDROData_Tool::toOccColor( const QColor& theColor )
324 double r = theColor.red() / 255.0;
325 double g = theColor.green() / 255.0;
326 double b = theColor.blue() / 255.0;
328 return Quantity_Color( r, g, b, Quantity_TOC_RGB );
331 QColor HYDROData_Tool::toQtColor( const Quantity_Color& theColor )
333 int r = 255 * theColor.Red();
334 int g = 255 * theColor.Green();
335 int b = 255 * theColor.Blue();
336 return QColor( r, g, b );
339 QColor HYDROData_Tool::GenerateRandColor()
341 float aHue = ( rand()%1000 ) * 0.001f;
344 aColor.setHsl( (int)(aHue*255.), 200, 128 );
345 int r = aColor.red();
346 int g = aColor.green();
347 int b = aColor.blue();
348 return ( aColor.isValid() ? aColor : Qt::darkBlue );
351 void HYDROData_Tool::GenerateRepeatableRandColors(int nbColorsToGen, QVector<QColor>& theColors)
353 for (int i = 1; i <= nbColorsToGen; i++)
354 theColors.append(HYDROData_Tool::GenerateRandColor());
357 bool HYDROData_Tool::GenerateNonRepeatableRandColors(int nbColorsToGen, QVector<QColor>& theColors)
359 if (nbColorsToGen > aMaxColorNb)
370 if (Codes.contains(Code))
372 aColor.setHsl( H, S, 128 );
373 if (aColor.isValid())
375 theColors.append(aColor);
378 } while (theColors.size() <= nbColorsToGen);
383 bool HYDROData_Tool::IsNan( double theValue )
386 return _isnan( theValue );
388 return isnan( theValue );
392 bool HYDROData_Tool::IsInf( double theValue )
395 return (!_finite( theValue ) );
397 return isinf( theValue );
401 static void MakeShellG(const NCollection_Map<TopoDS_Face, TopTools_ShapeMapHasher>& FG,
405 NCollection_Map<TopoDS_Face, TopTools_ShapeMapHasher>::Iterator itFG(FG);
408 //face nb > 1 => make shell
409 TopoDS_Shell outShell;
410 bb.MakeShell(outShell);
411 for (;itFG.More();itFG.Next())
412 bb.Add(outShell, itFG.Value());
415 else if (FG.Extent() == 1)
417 outSh = itFG.Value(); //one face
421 TopoDS_Shape HYDROData_Tool::RebuildCmp(const TopoDS_Shape& in)
423 TopTools_IndexedDataMapOfShapeListOfShape mE2LF;
424 TopExp::MapShapesAndAncestors(in, TopAbs_EDGE, TopAbs_FACE, mE2LF);
426 return TopoDS_Shape();
427 NCollection_Map<TopoDS_Face, TopTools_ShapeMapHasher> dfm;
428 //TopExp::MapShapes(aFuseShape, TopAbs_FACE, dfm);
429 TopExp_Explorer expf(in, TopAbs_FACE);
430 for (;expf.More(); expf.Next())
431 dfm.Add(TopoDS::Face(expf.Current()));
433 int nbF = dfm.Extent();
434 TopExp_Explorer exp_f(in, TopAbs_FACE);
435 const TopoDS_Face& FF = TopoDS::Face(exp_f.Current());
436 NCollection_List<TopoDS_Face> CurrFS;
437 NCollection_List<TopoDS_Face> NeighFS;
438 NCollection_Map<TopoDS_Face, TopTools_ShapeMapHasher> PrF;
440 NCollection_List<NCollection_Map<TopoDS_Face, TopTools_ShapeMapHasher>> GL_F;
441 NCollection_Map<TopoDS_Face, TopTools_ShapeMapHasher> OneGr;
445 NCollection_List<TopoDS_Face>::Iterator it_currfs(CurrFS);
447 for (;it_currfs.More();it_currfs.Next())
449 const TopoDS_Face& CF = it_currfs.Value();
450 TopExp_Explorer exp_edge(CF, TopAbs_EDGE);
451 for (;exp_edge.More();exp_edge.Next())
453 const TopoDS_Shape& CE = exp_edge.Current();
454 const TopTools_ListOfShape& lsf = mE2LF.FindFromKey(CE);
455 TopTools_ListIteratorOfListOfShape ls_it(lsf); //always one face (since all faces are planar)
456 for (;ls_it.More();ls_it.Next())
458 const TopoDS_Face& F = TopoDS::Face(ls_it.Value());
461 if (!PrF.Contains(F))
472 if (NeighFS.IsEmpty())
481 NCollection_Map<TopoDS_Face, TopTools_ShapeMapHasher>::Iterator itDm(dfm);
482 const TopoDS_Face& nsh = itDm.Key();
491 if (GL_F.Extent() > 1)
494 NCollection_List<NCollection_Map<TopoDS_Face, TopTools_ShapeMapHasher>>::Iterator itGL_F(GL_F);
496 bb.MakeCompound(cmp);
497 for (;itGL_F.More();itGL_F.Next())
499 MakeShellG(itGL_F.Value(), sh);
505 else if (GL_F.Extent() == 1)
507 MakeShellG(GL_F.First(), sh);
513 TopoDS_Shape HYDROData_Tool::PolyXY2Face( const Handle(HYDROData_PolylineXY)& aPolyline )
515 //DEBTRACE("generateTopShape");
516 TopoDS_Face aResultFace = TopoDS_Face(); // --- result: default = null face
518 if (!aPolyline.IsNull())
520 TopoDS_Shape aPolylineShape = aPolyline->GetShape();
522 std::string brepName = "imz.brep";
523 BRepTools::Write(aPolylineShape, brepName.c_str());
525 TopTools_ListOfShape aWiresList;
527 if (!aPolylineShape.IsNull() && aPolylineShape.ShapeType() == TopAbs_WIRE)
529 // --- only one wire: try to make a face
530 //DEBTRACE("one wire: try to build a face");
531 const TopoDS_Wire& aPolylineWire = TopoDS::Wire(aPolylineShape);
532 if (!aPolylineWire.IsNull())
534 BRepBuilderAPI_MakeFace aMakeFace(aPolylineWire, Standard_True);
536 if (aMakeFace.IsDone())
538 //DEBTRACE(" a face with the only wire given");
539 aResultFace = aMakeFace.Face();
545 // --- a list of wires ? inventory of wires and edges
546 Handle(TopTools_HSequenceOfShape) aSeqWires = new TopTools_HSequenceOfShape;
547 Handle(TopTools_HSequenceOfShape) aSeqEdges = new TopTools_HSequenceOfShape;
548 TopExp_Explorer anExp(aPolylineShape, TopAbs_WIRE);
549 //DEBTRACE("list of wires ?");
550 for (; anExp.More(); anExp.Next())
552 if (!anExp.Current().IsNull())
554 const TopoDS_Wire& aWire = TopoDS::Wire(anExp.Current());
555 aWiresList.Append(aWire);
556 //DEBTRACE(" append wire");
557 TopExp_Explorer it2(aWire, TopAbs_EDGE);
558 for (; it2.More(); it2.Next())
559 aSeqEdges->Append(it2.Current());
562 if (aWiresList.IsEmpty())
563 return aResultFace; // --- no wires: null result
565 if (aSeqEdges->Length() > 1)
567 //DEBTRACE("try to connect all the edges together, build a unique wire and a face");
568 // --- try to create one wire by connecting edges with a distance tolerance (no necessity of sharing points)
569 ShapeAnalysis_FreeBounds::ConnectEdgesToWires(aSeqEdges, 1E-5, Standard_False, aSeqWires);
571 if (aSeqWires->Length() == 1)
573 // --- one wire: try to make a face
574 const TopoDS_Wire& aPolylineWire = TopoDS::Wire(aSeqWires->Value(1));
575 if (!aPolylineWire.IsNull())
577 BRepBuilderAPI_MakeFace aMakeFace(aPolylineWire, Standard_True);
579 if (aMakeFace.IsDone())
581 //DEBTRACE(" a face from all the wires connected");
582 aResultFace = aMakeFace.Face();
588 if (aResultFace.IsNull())
590 //DEBTRACE("try to make a face with the first wire of the list and other wires as restrictions");
591 // --- try to make a face with the first wire of the list and other wires as restrictions
592 BRepAlgo_FaceRestrictor aFR;
593 TopoDS_Face aRefFace;
594 TopoDS_Shape aS = aWiresList.First();
595 BRepBuilderAPI_MakeFace aMakeFace(TopoDS::Wire(aWiresList.First()), Standard_True);
597 if (aMakeFace.IsDone())
599 //DEBTRACE(" a face with first wire");
600 aRefFace = aMakeFace.Face();
602 if (!aRefFace.IsNull())
604 aFR.Init(aRefFace, Standard_False, Standard_True);
605 TopTools_ListIteratorOfListOfShape anIt(aWiresList);
606 for (; anIt.More(); anIt.Next())
608 TopoDS_Wire& aWire = TopoDS::Wire(anIt.Value());
616 for (; aFR.More(); aFR.Next())
618 //DEBTRACE(" a restricted face");
619 aResultFace = aFR.Current();
628 if (aResultFace.IsNull())
631 //DEBTRACE("check the face");
632 BRepCheck_Analyzer anAnalyzer(aResultFace);
633 if (anAnalyzer.IsValid() && aResultFace.ShapeType() == TopAbs_FACE)
635 //DEBTRACE("face OK");
640 //DEBTRACE("bad face");
642 return TopoDS_Face();
645 void HYDROData_Tool::SetSIProgress(const Handle(Message_ProgressIndicator)& thePI)
647 StricklerInterpolationProgress() = thePI;
650 const Handle(Message_ProgressIndicator)& HYDROData_Tool::GetSIProgress()
652 return StricklerInterpolationProgress();
655 Handle(Message_ProgressIndicator)& HYDROData_Tool::StricklerInterpolationProgress()
657 static Handle(Message_ProgressIndicator) aPI = NULL;
661 void HYDROData_Tool::SetZIProgress(const Handle(Message_ProgressIndicator)& thePI)
663 BathymetryInterpolationProgress() = thePI;
666 const Handle(Message_ProgressIndicator)& HYDROData_Tool::GetZIProgress()
668 return BathymetryInterpolationProgress();
671 Handle(Message_ProgressIndicator)& HYDROData_Tool::BathymetryInterpolationProgress()
673 static Handle(Message_ProgressIndicator) aPI = NULL;
677 void HYDROData_Tool::SetTriangulationStatus(const ExecStatus& theStatus)
679 myTriangulationStatus = theStatus;
682 const HYDROData_Tool::ExecStatus& HYDROData_Tool::GetTriangulationStatus()
684 return myTriangulationStatus;
687 std::ostream& operator<<( std::ostream& theStream, const QString& theText )
689 theStream << theText.toStdString();
693 std::ostream& operator<<( std::ostream& theStream, const QColor& theColor )
695 theStream << "[" << theColor.red() << ", " << theColor.green() << ", " << theColor.blue() << "]";
699 std::ostream& operator<<( std::ostream& theStream, const TopoDS_Shape& theShape )
701 theStream << "[" << theShape.TShape().operator->() << "]";
705 std::ostream& operator<<( std::ostream& theStream, const TopoDS_Face& theFace )
707 theStream << "[" << theFace.TShape().operator->() << "]";
711 std::ostream& operator<<( std::ostream& theStream, const gp_XY& theXY )
713 theStream << "(" << theXY.X() << "; " << theXY.Y() << ")";
717 bool operator == ( const gp_XY& thePoint1, const gp_XY& thePoint2 )
719 const double EPS = 1E-3;
721 fabs( thePoint1.X() - thePoint2.X() ) < EPS &&
722 fabs( thePoint1.Y() - thePoint2.Y() ) < EPS;