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