Salome HOME
workaround for bug #16280 / #1514: tolerance for nodes on the border fixed to 0.01...
[modules/hydro.git] / src / HYDROData / HYDROData_Tool.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_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 <QColor>
27 #include <QFile>
28 #include <QStringList>
29 #include <QTextStream>
30 #include <QSet>
31 #include <BRep_Tool.hxx>
32 #include <BRepAdaptor_Surface.hxx>
33 #include <BRepTopAdaptor_FClass2d.hxx>
34 #include <ElSLib.hxx>
35 #include <Geom_Curve.hxx>
36 #include <gp_Pln.hxx>
37 #include <Quantity_Color.hxx>
38 #include <TopExp_Explorer.hxx>
39 #include <TopoDS.hxx>
40 #include <TopoDS_Face.hxx>
41 #include <TopoDS_Shape.hxx>
42 #include <TopoDS_Wire.hxx>
43 #include <limits>
44 #include <math.h>
45
46
47 #include <BRepTools.hxx>
48 #include <NCollection_Map.hxx>
49 #include <TopExp_Explorer.hxx>
50 #include <TopoDS_Face.hxx>
51 #include <TopTools_ShapeMapHasher.hxx>
52 #include <BRep_Builder.hxx>
53 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
54 #include <TopExp.hxx>
55 #include <NCollection_List.hxx>
56 #include <TopTools_ListIteratorOfListOfShape.hxx>
57
58 static int aMaxNameId = INT_MAX;
59 static int aMaxColorNb = 92000;
60 void HYDROData_Tool::WriteStringsToFile( QFile&             theFile,
61                                          const QStringList& theStrings,
62                                          const QString&     theSep )
63 {
64   if ( !theFile.isOpen() || theStrings.isEmpty() )
65     return;
66   
67   QString aWriteStr = theStrings.join( theSep );
68   if ( aWriteStr.isEmpty() )
69     return;
70
71   QTextStream anOutStream( &theFile );
72   anOutStream << aWriteStr.toUtf8() << theSep << theSep;
73 }
74
75 bool HYDROData_Tool::ExtractGeneratedObjectName(const QString& theName, int& outValue, QString& thePrefName)
76 {
77   QStringList aLs = theName.split('_');
78   bool ok = false;
79   QString last = aLs.last();
80   outValue = last.toInt(&ok);
81   if (!ok)
82     return false;
83   int last_len = last.length();
84   int total_len = theName.length();
85   thePrefName = theName.left(total_len-last_len-1);
86   return true;
87 }
88
89 QString HYDROData_Tool::GenerateObjectName( const Handle(HYDROData_Document)& theDoc,
90                                             const QString&                    thePrefix,
91                                             const QStringList&                theUsedNames,
92                                             const bool                        theIsTryToUsePurePrefix )
93 {
94   QStringList aNamesList( theUsedNames );
95
96   // Collect all used names in the document
97   HYDROData_Iterator anIter( theDoc );
98   for( ; anIter.More(); anIter.Next() )
99   {
100     Handle(HYDROData_Entity) anObject = anIter.Current();
101     if( anObject.IsNull() )
102       continue;
103
104     QString anObjName = anObject->GetName();
105     if ( anObjName.isEmpty() )
106       continue;
107
108     aNamesList.append( anObjName );
109   }
110
111   QString aName;
112
113   if ( theIsTryToUsePurePrefix && !aNamesList.contains( thePrefix ) ) {
114     aName = thePrefix;
115   } else {
116     int anId = 1;
117     while( anId < aMaxNameId )
118     {
119       aName = QString( "%1_%2" ).arg( thePrefix ).arg( QString::number( anId++ ) );
120
121       // check that there are no other objects with the same name in the document
122       if ( !aNamesList.contains( aName ) )
123         break;
124     }
125   }
126
127   return aName;
128 }
129
130 bool HYDROData_Tool::IsGeometryObject( const Handle(HYDROData_Entity)& theObject )
131 {
132   if ( theObject.IsNull() )
133     return false;
134   
135   return theObject->IsKind( STANDARD_TYPE(HYDROData_ArtificialObject) ) ||
136          theObject->IsKind( STANDARD_TYPE(HYDROData_NaturalObject) );
137 }
138
139 void HYDROData_Tool::UpdateChildObjectName( const QString&                  theOldStr,
140                                             const QString&                  theNewStr,
141                                             const Handle(HYDROData_Entity)& theObject )
142 {
143   if ( theObject.IsNull() )
144     return;
145
146   QString anObjName = theObject->GetName();
147   if ( theOldStr.isEmpty() )
148   {
149     while ( anObjName.startsWith( '_' ) )
150       anObjName.remove( 0, 1 );
151
152     anObjName.prepend( theNewStr + "_" );
153   }
154   else if ( anObjName.startsWith( theOldStr ) )
155   {
156     anObjName.replace( 0, theOldStr.length(), theNewStr );
157   }
158   else
159     return;
160
161   theObject->SetName( anObjName );
162 }
163
164 QString HYDROData_Tool::GenerateNameForPython( const MapOfTreatedObjects& theTreatedObjects,
165                                                const QString&             thePrefix )
166 {
167   QString aName = thePrefix;
168   if ( !theTreatedObjects.contains( aName ) )
169     return aName;
170
171   int anId = 1;
172   while( anId < aMaxNameId )
173   {
174     aName = QString( "%1_%2" ).arg( thePrefix ).arg( QString::number( anId++ ) );
175
176     // check that there are no other objects with the same name
177     if ( !theTreatedObjects.contains( aName ) )
178       break;
179   }
180
181   return aName;
182 }
183 //======================================================================================================
184 TopAbs_State HYDROData_Tool::ComputePointState( const gp_XY& theXY, const TopoDS_Face& theFace )
185 {
186   TopAbs_State aState(TopAbs_UNKNOWN);
187   if(theFace.IsNull()) return aState;  
188   Standard_Real aTol = BRep_Tool::Tolerance(theFace);
189   BRepAdaptor_Surface Ads ( theFace, Standard_False );
190   Standard_Real toluv = Min ( Ads.UResolution(aTol), Ads.VResolution(aTol) ); 
191   if (toluv < 0.01)
192     toluv = 0.01; // there is no need to be more precise than 1cm a any case ! 
193                   // another solution could be to compute a tolerance related to the distance between the border nodes 
194   const gp_Pln& aPlane = Ads.Surface().Plane();
195   gp_Pnt aPnt(theXY.X(), theXY.Y(), 0.);
196   Standard_Real aU1, aV1;
197   ElSLib::Parameters(aPlane,aPnt, aU1, aV1);
198   BRepTopAdaptor_FClass2d aClassifier( theFace, toluv ); 
199   aState = aClassifier.Perform( gp_Pnt2d(aU1, aV1), Standard_False );
200   return aState;
201 }
202
203 double HYDROData_Tool::GetAltitudeForEdge( const TopoDS_Edge& theEdge,
204                                            const gp_XY& thePoint,
205                                            double theParameterTolerance,
206                                            double theSquareDistanceTolerance,
207                                            double theInvalidAltitude )
208 {
209   double aFirst, aLast;
210   Handle(Geom_Curve) aCurve = BRep_Tool::Curve( theEdge, aFirst, aLast );
211   if( aCurve.IsNull() )
212     return theInvalidAltitude;
213
214   gp_Pnt aFirstPnt, aLastPnt;
215
216   aCurve->D0( aFirst, aFirstPnt );
217   aCurve->D0( aLast, aLastPnt );
218
219   gp_Pnt2d aFirstPnt2d( aFirstPnt.X(), aFirstPnt.Y() );
220   gp_Pnt2d aLastPnt2d( aLastPnt.X(), aLastPnt.Y() );
221
222   double aFirstDist = 0;
223   double aLastDist = aFirstPnt2d.SquareDistance( aLastPnt2d );
224   double aNecDist = aFirstPnt2d.SquareDistance( thePoint );
225
226   while( fabs( aLast - aFirst ) > theParameterTolerance )
227   {
228     double aMid = ( aFirst + aLast ) / 2;
229     gp_Pnt aMidPnt;
230     aCurve->D0( aMid, aMidPnt );
231     double aDist = aFirstPnt2d.SquareDistance( gp_Pnt2d( aMidPnt.X(), aMidPnt.Y() ) );
232
233     if( aDist < aNecDist )
234       aFirst = aMid;
235     else
236       aLast = aMid;
237   }
238
239   double aMid = ( aFirst + aLast ) / 2;
240   gp_Pnt aMidPnt;
241   aCurve->D0( aMid, aMidPnt );
242
243   gp_Pnt2d aMidPnt2d( aMidPnt.X(), aMidPnt.Y() );
244   if( aMidPnt2d.SquareDistance( thePoint ) < theSquareDistanceTolerance )
245     return aMidPnt.Z();
246   else
247     return theInvalidAltitude;
248 }
249
250 double HYDROData_Tool::GetAltitudeForWire( const TopoDS_Wire& theWire,
251                                            const gp_XY& thePoint,
252                                            double theParameterTolerance,
253                                            double theSquareDistanceTolerance,
254                                            double theInvalidAltitude )
255 {
256   TopExp_Explorer anExp( theWire, TopAbs_EDGE );
257   for( ; anExp.More(); anExp.Next() )
258   {
259     double anAltitude = GetAltitudeForEdge( TopoDS::Edge( anExp.Current() ), thePoint,
260       theParameterTolerance, theSquareDistanceTolerance, theInvalidAltitude );
261     if( anAltitude != theInvalidAltitude )
262       return anAltitude;
263   }
264   return theInvalidAltitude;
265 }
266
267 TopoDS_Shape HYDROData_Tool::getFirstShapeFromGroup( const HYDROData_SequenceOfObjects& theGroups,
268                                                      const int                          theGroupId )
269 {
270   TopoDS_Shape aResShape;
271   if ( theGroupId < 1 || theGroupId > theGroups.Length() )
272     return aResShape;
273
274   Handle(HYDROData_ShapesGroup) aGroup =
275     Handle(HYDROData_ShapesGroup)::DownCast( theGroups.Value( theGroupId ) );
276   if ( aGroup.IsNull() )
277     return aResShape;
278
279   TopTools_SequenceOfShape aGroupShapes;
280   aGroup->GetShapes( aGroupShapes );
281
282   if ( !aGroupShapes.IsEmpty() )
283     aResShape = aGroupShapes.First();
284
285   return aResShape;
286 }
287
288 TCollection_ExtendedString HYDROData_Tool::toExtString( const QString& theStr )
289 {
290   TCollection_ExtendedString aRes;
291   if( !theStr.isEmpty() )
292   {
293           Standard_ExtString extStr = new Standard_ExtCharacter[ ( theStr.length() + 1 ) * 2 ];
294           memcpy( (void*)extStr, theStr.unicode(), theStr.length() * 2 );
295           ((short*)extStr)[theStr.length()] = '\0';
296     aRes = TCollection_ExtendedString( extStr );
297           delete [] extStr;
298   }
299   return aRes;
300 }
301
302 QString HYDROData_Tool::toQString( const TCollection_ExtendedString& theStr )
303 {
304   return QString( (QChar*)theStr.ToExtString(), theStr.Length() );
305 }
306
307 Quantity_Color HYDROData_Tool::toOccColor( const QColor& theColor )
308 {
309   double r = theColor.red() / 255.0;
310   double g = theColor.green() / 255.0;
311   double b = theColor.blue() / 255.0;
312
313   return Quantity_Color( r, g, b, Quantity_TOC_RGB );
314 }
315
316 QColor HYDROData_Tool::toQtColor( const Quantity_Color& theColor )
317 {
318   int r = 255 * theColor.Red();
319   int g = 255 * theColor.Green();
320   int b = 255 * theColor.Blue();
321   return QColor( r, g, b );
322 }
323
324 QColor HYDROData_Tool::GenerateRandColor()
325 {
326   float aHue = ( rand()%1000 ) * 0.001f;
327
328   QColor aColor;
329   aColor.setHsl( (int)(aHue*255.), 200, 128 );
330   int r = aColor.red();
331   int g = aColor.green();
332   int b = aColor.blue();
333   return ( aColor.isValid() ? aColor : Qt::darkBlue );
334 }
335
336 void HYDROData_Tool::GenerateRepeatableRandColors(int nbColorsToGen, QVector<QColor>& theColors)
337 {
338   for (int i = 1; i <= nbColorsToGen; i++)
339     theColors.append(HYDROData_Tool::GenerateRandColor());
340 }
341
342 bool HYDROData_Tool::GenerateNonRepeatableRandColors(int nbColorsToGen, QVector<QColor>& theColors)
343 {
344   if (nbColorsToGen > aMaxColorNb)
345     return false;
346   QSet<int> Codes;
347   float aHue;
348   theColors.clear();
349   do 
350   {
351     QColor aColor;
352     int H = rand()%360;
353     int S = rand()%256;
354     int Code = H*256+S;
355     if (Codes.contains(Code))
356       continue;
357     aColor.setHsl( H, S, 128 );
358     if (aColor.isValid())
359     {
360       theColors.append(aColor);
361       Codes.insert(Code);
362     }
363   } while (theColors.size() <= nbColorsToGen);
364   return true;
365 }
366
367
368 bool HYDROData_Tool::IsNan( double theValue )
369 {
370 #ifdef WIN32
371   return _isnan( theValue );
372 #else
373   return isnan( theValue );
374 #endif
375 }
376
377 bool HYDROData_Tool::IsInf( double theValue )
378 {
379 #ifdef WIN32
380   return (!_finite( theValue  ) );
381 #else
382   return isinf( theValue );
383 #endif  
384 }
385
386 static void MakeShellG(const NCollection_Map<TopoDS_Face, TopTools_ShapeMapHasher>& FG,
387   TopoDS_Shape& outSh)
388 {
389   BRep_Builder bb;
390   NCollection_Map<TopoDS_Face, TopTools_ShapeMapHasher>::Iterator itFG(FG);
391   if (FG.Extent() > 1)
392   {
393     //face nb > 1 => make shell
394     TopoDS_Shell outShell;
395     bb.MakeShell(outShell);
396     for (;itFG.More();itFG.Next())
397       bb.Add(outShell, itFG.Value());
398     outSh = outShell;
399   }
400   else if (FG.Extent() == 1)
401   {
402     outSh = itFG.Value(); //one face
403   }
404 }
405
406 TopoDS_Shape HYDROData_Tool::RebuildCmp(const TopoDS_Shape& in)
407 {
408   TopTools_IndexedDataMapOfShapeListOfShape mE2LF;
409   TopExp::MapShapesAndAncestors(in, TopAbs_EDGE, TopAbs_FACE, mE2LF);
410   if (mE2LF.IsEmpty())
411     return TopoDS_Shape();
412   NCollection_Map<TopoDS_Face, TopTools_ShapeMapHasher> dfm;
413   //TopExp::MapShapes(aFuseShape, TopAbs_FACE, dfm);
414   TopExp_Explorer expf(in, TopAbs_FACE);
415   for (;expf.More(); expf.Next())
416     dfm.Add(TopoDS::Face(expf.Current()));
417
418   int nbF = dfm.Extent();
419   TopExp_Explorer exp_f(in, TopAbs_FACE);
420   const TopoDS_Face& FF = TopoDS::Face(exp_f.Current());
421   NCollection_List<TopoDS_Face> CurrFS;
422   NCollection_List<TopoDS_Face> NeighFS;
423   NCollection_Map<TopoDS_Face, TopTools_ShapeMapHasher> PrF;
424   CurrFS.Append(FF);
425   NCollection_List<NCollection_Map<TopoDS_Face, TopTools_ShapeMapHasher>> GL_F;
426   NCollection_Map<TopoDS_Face, TopTools_ShapeMapHasher> OneGr;
427   bool end = false;
428   while (!end)
429   {
430     NCollection_List<TopoDS_Face>::Iterator it_currfs(CurrFS);
431     NeighFS.Clear();
432     for (;it_currfs.More();it_currfs.Next())
433     {
434       const TopoDS_Face& CF = it_currfs.Value();
435       TopExp_Explorer exp_edge(CF, TopAbs_EDGE);
436       for (;exp_edge.More();exp_edge.Next())
437       {
438         const TopoDS_Shape& CE = exp_edge.Current();
439         const TopTools_ListOfShape& lsf = mE2LF.FindFromKey(CE);
440         TopTools_ListIteratorOfListOfShape ls_it(lsf); //always one face (since all faces are planar)
441         for (;ls_it.More();ls_it.Next())
442         {
443           const TopoDS_Face& F = TopoDS::Face(ls_it.Value());
444           if (F.IsSame(CF))
445             continue;
446           if (!PrF.Contains(F))
447           {
448             OneGr.Add(F);
449             NeighFS.Append(F);
450             PrF.Add(F);
451           }
452         }
453       }
454       OneGr.Add(CF);
455       PrF.Add(CF);
456     }
457     if (NeighFS.IsEmpty())
458     {
459       GL_F.Append(OneGr);
460       OneGr.Clear();
461       dfm.Subtract(PrF);
462       if (dfm.IsEmpty())
463         end = true;
464       else
465       {
466         NCollection_Map<TopoDS_Face, TopTools_ShapeMapHasher>::Iterator itDm(dfm);
467         const TopoDS_Face& nsh = itDm.Key();
468         NeighFS.Append(nsh);
469       }
470     }
471     CurrFS = NeighFS;
472   }
473
474   TopoDS_Shape sh;
475
476   if (GL_F.Extent() > 1)
477   {
478     TopoDS_Compound cmp;
479     NCollection_List<NCollection_Map<TopoDS_Face, TopTools_ShapeMapHasher>>::Iterator itGL_F(GL_F);  
480     BRep_Builder bb;
481     bb.MakeCompound(cmp);
482     for (;itGL_F.More();itGL_F.Next())
483     {
484       MakeShellG(itGL_F.Value(), sh);
485       if (!sh.IsNull())
486         bb.Add(cmp, sh);
487     }
488     return  cmp;
489   }
490   else if (GL_F.Extent() == 1)
491   {
492     MakeShellG(GL_F.First(), sh);
493     return sh;
494   }
495   
496 }
497
498
499 std::ostream& operator<<( std::ostream& theStream, const QString& theText )
500 {
501   theStream << theText.toStdString();
502   return theStream;
503 }
504
505 std::ostream& operator<<( std::ostream& theStream, const QColor& theColor )
506 {
507   theStream << "[" << theColor.red() << ", " << theColor.green() << ", " << theColor.blue() << "]";
508   return theStream;
509 }
510
511 std::ostream& operator<<( std::ostream& theStream, const TopoDS_Shape& theShape )
512 {
513   theStream << "[" << theShape.TShape().operator->() << "]";
514   return theStream;
515 }
516
517 std::ostream& operator<<( std::ostream& theStream, const TopoDS_Face& theFace )
518 {
519   theStream << "[" << theFace.TShape().operator->() << "]";
520   return theStream;
521 }
522
523 std::ostream& operator<<( std::ostream& theStream, const gp_XY& theXY )
524 {
525   theStream << "(" << theXY.X() << "; " << theXY.Y() << ")";
526   return theStream;
527 }
528
529 bool operator == ( const gp_XY& thePoint1, const gp_XY& thePoint2 )
530 {
531   const double EPS = 1E-3;
532   return
533     fabs( thePoint1.X() - thePoint2.X() ) < EPS &&
534     fabs( thePoint1.Y() - thePoint2.Y() ) < EPS;
535
536 }