Salome HOME
db07a004f118ad0ad2bccb360eb92fa612b9e17e
[modules/smesh.git] / src / SMESH / SMESH_Algo.cxx
1 //  SMESH SMESH : implementaion of SMESH idl descriptions
2 //
3 //  Copyright (C) 2003  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 //  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS 
5 // 
6 //  This library is free software; you can redistribute it and/or 
7 //  modify it under the terms of the GNU Lesser General Public 
8 //  License as published by the Free Software Foundation; either 
9 //  version 2.1 of the License. 
10 // 
11 //  This library is distributed in the hope that it will be useful, 
12 //  but WITHOUT ANY WARRANTY; without even the implied warranty of 
13 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU 
14 //  Lesser General Public License for more details. 
15 // 
16 //  You should have received a copy of the GNU Lesser General Public 
17 //  License along with this library; if not, write to the Free Software 
18 //  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA 
19 // 
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22 //
23 //
24 //  File   : SMESH_Algo.cxx
25 //  Author : Paul RASCLE, EDF
26 //  Module : SMESH
27 //  $Header$
28
29 #include "SMESH_Algo.hxx"
30 #include "SMESH_Comment.hxx"
31 #include "SMESH_Gen.hxx"
32 #include "SMESH_Mesh.hxx"
33 #include "SMESH_HypoFilter.hxx"
34 #include "SMDS_FacePosition.hxx"
35 #include "SMDS_EdgePosition.hxx"
36 #include "SMDS_MeshElement.hxx"
37 #include "SMDS_MeshNode.hxx"
38 #include "SMESHDS_Mesh.hxx"
39 #include "SMESHDS_SubMesh.hxx"
40
41 #include <BRepAdaptor_Curve.hxx>
42 #include <BRepLProp.hxx>
43 #include <BRep_Tool.hxx>
44 #include <GCPnts_AbscissaPoint.hxx>
45 #include <GeomAdaptor_Curve.hxx>
46 #include <Geom_Surface.hxx>
47 #include <TopExp.hxx>
48 #include <TopLoc_Location.hxx>
49 #include <TopTools_ListIteratorOfListOfShape.hxx>
50 #include <TopTools_ListOfShape.hxx>
51 #include <TopoDS.hxx>
52 #include <TopoDS_Edge.hxx>
53 #include <TopoDS_Face.hxx>
54 #include <TopoDS_Vertex.hxx>
55 #include <gp_Pnt.hxx>
56 #include <gp_Pnt2d.hxx>
57 #include <gp_Vec.hxx>
58
59 #include <Standard_ErrorHandler.hxx>
60 #include <Standard_Failure.hxx>
61
62 #include "utilities.h"
63
64 #include <algorithm>
65
66 using namespace std;
67
68 //=============================================================================
69 /*!
70  *  
71  */
72 //=============================================================================
73
74 SMESH_Algo::SMESH_Algo(int hypId, int studyId,
75         SMESH_Gen * gen):SMESH_Hypothesis(hypId, studyId, gen)
76 {
77   gen->_mapAlgo[hypId] = this;
78
79   _onlyUnaryInput = _requireDescretBoundary = _requireShape = true;
80   _quadraticMesh = false;
81   _error = COMPERR_OK;
82 }
83
84 //=============================================================================
85 /*!
86  *  
87  */
88 //=============================================================================
89
90 SMESH_Algo::~SMESH_Algo()
91 {
92 }
93
94 //=============================================================================
95 /*!
96  * Usually an algoritm has nothing to save
97  */
98 //=============================================================================
99
100 ostream & SMESH_Algo::SaveTo(ostream & save) { return save; }
101 istream & SMESH_Algo::LoadFrom(istream & load) { return load; }
102
103 //=============================================================================
104 /*!
105  *  
106  */
107 //=============================================================================
108
109 const vector < string > &SMESH_Algo::GetCompatibleHypothesis()
110 {
111         return _compatibleHypothesis;
112 }
113
114 //=============================================================================
115 /*!
116  *  List the hypothesis used by the algorithm associated to the shape.
117  *  Hypothesis associated to father shape -are- taken into account (see
118  *  GetAppliedHypothesis). Relevant hypothesis have a name (type) listed in
119  *  the algorithm. This method could be surcharged by specific algorithms, in 
120  *  case of several hypothesis simultaneously applicable.
121  */
122 //=============================================================================
123
124 const list <const SMESHDS_Hypothesis *> &
125 SMESH_Algo::GetUsedHypothesis(SMESH_Mesh &         aMesh,
126                               const TopoDS_Shape & aShape,
127                               const bool           ignoreAuxiliary)
128 {
129   _usedHypList.clear();
130   SMESH_HypoFilter filter;
131   if ( InitCompatibleHypoFilter( filter, ignoreAuxiliary ))
132   {
133     aMesh.GetHypotheses( aShape, filter, _usedHypList, true );
134     if ( ignoreAuxiliary && _usedHypList.size() > 1 )
135       _usedHypList.clear();     //only one compatible hypothesis allowed
136   }
137   return _usedHypList;
138 }
139
140 //=============================================================================
141 /*!
142  *  List the relevant hypothesis associated to the shape. Relevant hypothesis
143  *  have a name (type) listed in the algorithm. Hypothesis associated to
144  *  father shape -are not- taken into account (see GetUsedHypothesis)
145  */
146 //=============================================================================
147
148 const list<const SMESHDS_Hypothesis *> &
149 SMESH_Algo::GetAppliedHypothesis(SMESH_Mesh &         aMesh,
150                                  const TopoDS_Shape & aShape,
151                                  const bool           ignoreAuxiliary)
152 {
153   _appliedHypList.clear();
154   SMESH_HypoFilter filter;
155   if ( InitCompatibleHypoFilter( filter, ignoreAuxiliary ))
156     aMesh.GetHypotheses( aShape, filter, _appliedHypList, false );
157
158   return _appliedHypList;
159 }
160
161 //=============================================================================
162 /*!
163  *  Compute length of an edge
164  */
165 //=============================================================================
166
167 double SMESH_Algo::EdgeLength(const TopoDS_Edge & E)
168 {
169   double UMin = 0, UMax = 0;
170   if (BRep_Tool::Degenerated(E))
171     return 0;
172   TopLoc_Location L;
173   Handle(Geom_Curve) C = BRep_Tool::Curve(E, L, UMin, UMax);
174   GeomAdaptor_Curve AdaptCurve(C);
175   double length = GCPnts_AbscissaPoint::Length(AdaptCurve, UMin, UMax);
176   return length;
177 }
178
179 //================================================================================
180 /*!
181  * \brief Find out elements orientation on a geometrical face
182  * \param theFace - The face correctly oriented in the shape being meshed
183  * \param theMeshDS - The mesh data structure
184  * \retval bool - true if the face normal and the normal of first element
185  *                in the correspoding submesh point in different directions
186  */
187 //================================================================================
188
189 bool SMESH_Algo::IsReversedSubMesh (const TopoDS_Face&  theFace,
190                                     SMESHDS_Mesh*       theMeshDS)
191 {
192   if ( theFace.IsNull() || !theMeshDS )
193     return false;
194
195   // find out orientation of a meshed face
196   int faceID = theMeshDS->ShapeToIndex( theFace );
197   TopoDS_Shape aMeshedFace = theMeshDS->IndexToShape( faceID );
198   bool isReversed = ( theFace.Orientation() != aMeshedFace.Orientation() );
199
200   const SMESHDS_SubMesh * aSubMeshDSFace = theMeshDS->MeshElements( faceID );
201   if ( !aSubMeshDSFace )
202     return isReversed;
203
204   // find element with node located on face and get its normal
205   const SMDS_FacePosition* facePos = 0;
206   int vertexID = 0;
207   gp_Pnt nPnt[3];
208   gp_Vec Ne;
209   bool normalOK = false;
210   SMDS_ElemIteratorPtr iteratorElem = aSubMeshDSFace->GetElements();
211   while ( iteratorElem->more() ) // loop on elements on theFace
212   {
213     const SMDS_MeshElement* elem = iteratorElem->next();
214     if ( elem && elem->NbNodes() > 2 ) {
215       SMDS_ElemIteratorPtr nodesIt = elem->nodesIterator();
216       const SMDS_FacePosition* fPos = 0;
217       int i = 0, vID = 0;
218       while ( nodesIt->more() ) { // loop on nodes
219         const SMDS_MeshNode* node
220           = static_cast<const SMDS_MeshNode *>(nodesIt->next());
221         if ( i == 3 ) i = 2;
222         nPnt[ i++ ].SetCoord( node->X(), node->Y(), node->Z() );
223         // check position
224         const SMDS_PositionPtr& pos = node->GetPosition();
225         if ( !pos ) continue;
226         if ( pos->GetTypeOfPosition() == SMDS_TOP_FACE ) {
227           fPos = dynamic_cast< const SMDS_FacePosition* >( pos.get() );
228         }
229         else if ( pos->GetTypeOfPosition() == SMDS_TOP_VERTEX ) {
230           vID = pos->GetShapeId();
231         }
232       }
233       if ( fPos || ( !normalOK && vID )) {
234         // compute normal
235         gp_Vec v01( nPnt[0], nPnt[1] ), v02( nPnt[0], nPnt[2] );
236         if ( v01.SquareMagnitude() > RealSmall() &&
237              v02.SquareMagnitude() > RealSmall() )
238         {
239           Ne = v01 ^ v02;
240           normalOK = ( Ne.SquareMagnitude() > RealSmall() );
241         }
242         // we need position on theFace or at least on vertex
243         if ( normalOK ) {
244           vertexID = vID;
245           if ((facePos = fPos))
246             break;
247         }
248       }
249     }
250   }
251   if ( !normalOK )
252     return isReversed;
253
254   // node position on face
255   double u,v;
256   if ( facePos ) {
257     u = facePos->GetUParameter();
258     v = facePos->GetVParameter();
259   }
260   else if ( vertexID ) {
261     TopoDS_Shape V = theMeshDS->IndexToShape( vertexID );
262     if ( V.IsNull() || V.ShapeType() != TopAbs_VERTEX )
263       return isReversed;
264     gp_Pnt2d uv = BRep_Tool::Parameters( TopoDS::Vertex( V ), theFace );
265     u = uv.X();
266     v = uv.Y();
267   }
268   else
269   {
270     return isReversed;
271   }
272
273   // face normal at node position
274   TopLoc_Location loc;
275   Handle(Geom_Surface) surf = BRep_Tool::Surface( theFace, loc );
276   if ( surf.IsNull() || surf->Continuity() < GeomAbs_C1 ) return isReversed;
277   gp_Vec d1u, d1v;
278   surf->D1( u, v, nPnt[0], d1u, d1v );
279   gp_Vec Nf = (d1u ^ d1v).Transformed( loc );
280
281   if ( theFace.Orientation() == TopAbs_REVERSED )
282     Nf.Reverse();
283
284   return Ne * Nf < 0.;
285 }
286
287 //================================================================================
288 /*!
289  * \brief Initialize my parameter values by the mesh built on the geometry
290  * \param theMesh - the built mesh
291  * \param theShape - the geometry of interest
292  * \retval bool - true if parameter values have been successfully defined
293  *
294  * Just return false as the algorithm does not hold parameters values
295  */
296 //================================================================================
297
298 bool SMESH_Algo::SetParametersByMesh(const SMESH_Mesh* /*theMesh*/,
299                                      const TopoDS_Shape& /*theShape*/)
300 {
301   return false;
302 }
303
304 //================================================================================
305 /*!
306  * \brief Fill vector of node parameters on geometrical edge, including vertex nodes
307  * \param theMesh - The mesh containing nodes
308  * \param theEdge - The geometrical edge of interest
309  * \param theParams - The resulting vector of sorted node parameters
310  * \retval bool - false if not all parameters are OK
311  */
312 //================================================================================
313
314 bool SMESH_Algo::GetNodeParamOnEdge(const SMESHDS_Mesh* theMesh,
315                                     const TopoDS_Edge&  theEdge,
316                                     vector< double > &  theParams)
317 {
318   theParams.clear();
319
320   if ( !theMesh || theEdge.IsNull() )
321     return false;
322
323   SMESHDS_SubMesh * eSubMesh = theMesh->MeshElements( theEdge );
324   if ( !eSubMesh || !eSubMesh->GetElements()->more() )
325     return false; // edge is not meshed
326
327   int nbEdgeNodes = 0;
328   set < double > paramSet;
329   if ( eSubMesh )
330   {
331     // loop on nodes of an edge: sort them by param on edge
332     SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
333     while ( nIt->more() )
334     {
335       const SMDS_MeshNode* node = nIt->next();
336       const SMDS_PositionPtr& pos = node->GetPosition();
337       if ( pos->GetTypeOfPosition() != SMDS_TOP_EDGE )
338         return false;
339       const SMDS_EdgePosition* epos =
340         static_cast<const SMDS_EdgePosition*>(node->GetPosition().get());
341       paramSet.insert( epos->GetUParameter() );
342       ++nbEdgeNodes;
343     }
344   }
345   // add vertex nodes params
346   Standard_Real f, l;
347   BRep_Tool::Range(theEdge, f, l);
348   paramSet.insert( f );
349   paramSet.insert( l );
350   if ( paramSet.size() != nbEdgeNodes + 2 )
351     return false; // there are equal parameters
352
353   // fill the vector
354   theParams.resize( paramSet.size() );
355   set < double >::iterator   par    = paramSet.begin();
356   vector< double >::iterator vecPar = theParams.begin();
357   for ( ; par != paramSet.end(); ++par, ++vecPar )
358     *vecPar = *par;
359
360   return theParams.size() > 1;
361 }
362
363 //================================================================================
364 /*!
365  * \brief Make filter recognize only compatible hypotheses
366  * \param theFilter - the filter to initialize
367  * \param ignoreAuxiliary - make filter ignore compatible auxiliary hypotheses
368  */
369 //================================================================================
370
371 bool SMESH_Algo::InitCompatibleHypoFilter( SMESH_HypoFilter & theFilter,
372                                            const bool         ignoreAuxiliary) const
373 {
374   if ( !_compatibleHypothesis.empty() )
375   {
376     theFilter.Init( theFilter.HasName( _compatibleHypothesis[0] ));
377     for ( int i = 1; i < _compatibleHypothesis.size(); ++i )
378       theFilter.Or( theFilter.HasName( _compatibleHypothesis[ i ] ));
379
380     if ( ignoreAuxiliary )
381       theFilter.AndNot( theFilter.IsAuxiliary() );
382
383     return true;
384   }
385   return false;
386 }
387
388 //================================================================================
389 /*!
390  * \brief Return continuity of two edges
391  * \param E1 - the 1st edge
392  * \param E2 - the 2nd edge
393  * \retval GeomAbs_Shape - regularity at the junction between E1 and E2
394  */
395 //================================================================================
396
397 GeomAbs_Shape SMESH_Algo::Continuity(const TopoDS_Edge & E1,
398                                      const TopoDS_Edge & E2)
399 {
400   TopoDS_Vertex V = TopExp::LastVertex (E1, true);
401   if ( !V.IsSame( TopExp::FirstVertex(E2, true )))
402     if ( !TopExp::CommonVertex( E1, E2, V ))
403       return GeomAbs_C0;
404   Standard_Real u1 = BRep_Tool::Parameter( V, E1 );
405   Standard_Real u2 = BRep_Tool::Parameter( V, E2 );
406   BRepAdaptor_Curve C1( E1 ), C2( E2 );
407   Standard_Real tol = BRep_Tool::Tolerance( V );
408   Standard_Real angTol = 2e-3;
409   try {
410 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
411     OCC_CATCH_SIGNALS;
412 #endif
413     return BRepLProp::Continuity(C1, C2, u1, u2, tol, angTol);
414   }
415   catch (Standard_Failure) {
416   }
417   return GeomAbs_C0;
418 }
419
420 //================================================================================
421 /*!
422  * \brief Return the node built on a vertex
423  * \param V - the vertex
424  * \param meshDS - mesh
425  * \retval const SMDS_MeshNode* - found node or NULL
426  */
427 //================================================================================
428
429 const SMDS_MeshNode* SMESH_Algo::VertexNode(const TopoDS_Vertex& V,
430                                             SMESHDS_Mesh*        meshDS)
431 {
432   if ( SMESHDS_SubMesh* sm = meshDS->MeshElements(V) ) {
433     SMDS_NodeIteratorPtr nIt= sm->GetNodes();
434     if (nIt->more())
435       return nIt->next();
436   }
437   return 0;
438 }
439
440 //================================================================================
441 /*!
442  * \brief Sets event listener to submeshes if necessary
443  * \param subMesh - submesh where algo is set
444  * 
445  * After being set, event listener is notified on each event of a submesh.
446  * By default non listener is set
447  */
448 //================================================================================
449
450 void SMESH_Algo::SetEventListener(SMESH_subMesh* /*subMesh*/)
451 {
452 }
453
454 //================================================================================
455 /*!
456  * \brief Allow algo to do something after persistent restoration
457  * \param subMesh - restored submesh
458  *
459  * This method is called only if a submesh has HYP_OK algo_state.
460  */
461 //================================================================================
462
463 void SMESH_Algo::SubmeshRestored(SMESH_subMesh* /*subMesh*/)
464 {
465 }
466
467 //================================================================================
468 /*!
469  * \brief Computes mesh without geometry
470  * \param aMesh - the mesh
471  * \param aHelper - helper that must be used for adding elements to \aaMesh
472  * \retval bool - is a success
473  */
474 //================================================================================
475
476 bool SMESH_Algo::Compute(SMESH_Mesh & /*aMesh*/, SMESH_MesherHelper* /*aHelper*/)
477 {
478   return error( COMPERR_BAD_INPUT_MESH, "Mesh built on shape expected");
479 }
480
481 //================================================================================
482 /*!
483  * \brief store error and comment and then return ( error == COMPERR_OK )
484  */
485 //================================================================================
486
487 bool SMESH_Algo::error(int error, const SMESH_Comment& comment)
488 {
489   _error   = error;
490   _comment = comment;
491   return ( error == COMPERR_OK );
492 }
493
494 //================================================================================
495 /*!
496  * \brief store error and return ( error == COMPERR_OK )
497  */
498 //================================================================================
499
500 bool SMESH_Algo::error(SMESH_ComputeErrorPtr error)
501 {
502   if ( error ) {
503     _error   = error->myName;
504     _comment = error->myComment;
505     return error->IsOK();
506   }
507   return true;
508 }
509
510 //================================================================================
511 /*!
512  * \brief return compute error
513  */
514 //================================================================================
515
516 SMESH_ComputeErrorPtr SMESH_Algo::GetComputeError() const
517 {
518   return SMESH_ComputeError::New( _error, _comment, this );
519 }
520
521 //================================================================================
522 /*!
523  * \brief initialize compute error
524  */
525 //================================================================================
526
527 void SMESH_Algo::InitComputeError()
528 {
529   _error = COMPERR_OK;
530   _comment.clear();
531 }
532