Salome HOME
+ SMESH_Comment & operator=(const SMESH_Comment& c) {
[modules/smesh.git] / src / SMESH / SMESH_Algo.cxx
1 //  Copyright (C) 2007-2008  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 //  Copyright (C) 2003-2007  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 //  SMESH SMESH : implementaion of SMESH idl descriptions
23 //  File   : SMESH_Algo.cxx
24 //  Author : Paul RASCLE, EDF
25 //  Module : SMESH
26 //
27
28 #include "SMESH_Algo.hxx"
29 #include "SMESH_Comment.hxx"
30 #include "SMESH_Gen.hxx"
31 #include "SMESH_Mesh.hxx"
32 #include "SMESH_HypoFilter.hxx"
33 #include "SMDS_FacePosition.hxx"
34 #include "SMDS_EdgePosition.hxx"
35 #include "SMDS_MeshElement.hxx"
36 #include "SMDS_MeshNode.hxx"
37 #include "SMESHDS_Mesh.hxx"
38 #include "SMESHDS_SubMesh.hxx"
39
40 #include <BRepAdaptor_Curve.hxx>
41 #include <BRepLProp.hxx>
42 #include <BRep_Tool.hxx>
43 #include <GCPnts_AbscissaPoint.hxx>
44 #include <GeomAdaptor_Curve.hxx>
45 #include <Geom_Surface.hxx>
46 #include <TopExp.hxx>
47 #include <TopLoc_Location.hxx>
48 #include <TopTools_ListIteratorOfListOfShape.hxx>
49 #include <TopTools_ListOfShape.hxx>
50 #include <TopoDS.hxx>
51 #include <TopoDS_Edge.hxx>
52 #include <TopoDS_Face.hxx>
53 #include <TopoDS_Vertex.hxx>
54 #include <gp_Pnt.hxx>
55 #include <gp_Pnt2d.hxx>
56 #include <gp_Vec.hxx>
57
58 #include <Standard_ErrorHandler.hxx>
59 #include <Standard_Failure.hxx>
60
61 #include "utilities.h"
62
63 #include <algorithm>
64
65 using namespace std;
66
67 //=============================================================================
68 /*!
69  *  
70  */
71 //=============================================================================
72
73 SMESH_Algo::SMESH_Algo (int hypId, int studyId, SMESH_Gen * gen)
74   : SMESH_Hypothesis(hypId, studyId, gen)
75 {
76   gen->_mapAlgo[hypId] = this;
77
78   _onlyUnaryInput = _requireDescretBoundary = _requireShape = true;
79   _quadraticMesh = _supportSubmeshes = false;
80   _error = COMPERR_OK;
81 }
82
83 //=============================================================================
84 /*!
85  *  
86  */
87 //=============================================================================
88
89 SMESH_Algo::~SMESH_Algo()
90 {
91 }
92
93 //=============================================================================
94 /*!
95  * Usually an algoritm has nothing to save
96  */
97 //=============================================================================
98
99 ostream & SMESH_Algo::SaveTo(ostream & save) { return save; }
100 istream & SMESH_Algo::LoadFrom(istream & load) { return load; }
101
102 //=============================================================================
103 /*!
104  *  
105  */
106 //=============================================================================
107
108 const vector < string > &SMESH_Algo::GetCompatibleHypothesis()
109 {
110   return _compatibleHypothesis;
111 }
112
113 //=============================================================================
114 /*!
115  *  List the hypothesis used by the algorithm associated to the shape.
116  *  Hypothesis associated to father shape -are- taken into account (see
117  *  GetAppliedHypothesis). Relevant hypothesis have a name (type) listed in
118  *  the algorithm. This method could be surcharged by specific algorithms, in 
119  *  case of several hypothesis simultaneously applicable.
120  */
121 //=============================================================================
122
123 const list <const SMESHDS_Hypothesis *> &
124 SMESH_Algo::GetUsedHypothesis(SMESH_Mesh &         aMesh,
125                               const TopoDS_Shape & aShape,
126                               const bool           ignoreAuxiliary)
127 {
128   _usedHypList.clear();
129   SMESH_HypoFilter filter;
130   if ( InitCompatibleHypoFilter( filter, ignoreAuxiliary ))
131   {
132     aMesh.GetHypotheses( aShape, filter, _usedHypList, true );
133     if ( ignoreAuxiliary && _usedHypList.size() > 1 )
134       _usedHypList.clear(); //only one compatible hypothesis allowed
135   }
136   return _usedHypList;
137 }
138
139 //=============================================================================
140 /*!
141  *  List the relevant hypothesis associated to the shape. Relevant hypothesis
142  *  have a name (type) listed in the algorithm. Hypothesis associated to
143  *  father shape -are not- taken into account (see GetUsedHypothesis)
144  */
145 //=============================================================================
146
147 const list<const SMESHDS_Hypothesis *> &
148 SMESH_Algo::GetAppliedHypothesis(SMESH_Mesh &         aMesh,
149                                  const TopoDS_Shape & aShape,
150                                  const bool           ignoreAuxiliary)
151 {
152   _appliedHypList.clear();
153   SMESH_HypoFilter filter;
154   if ( InitCompatibleHypoFilter( filter, ignoreAuxiliary ))
155     aMesh.GetHypotheses( aShape, filter, _appliedHypList, false );
156
157   return _appliedHypList;
158 }
159
160 //=============================================================================
161 /*!
162  *  Compute length of an edge
163  */
164 //=============================================================================
165
166 double SMESH_Algo::EdgeLength(const TopoDS_Edge & E)
167 {
168   double UMin = 0, UMax = 0;
169   if (BRep_Tool::Degenerated(E))
170     return 0;
171   TopLoc_Location L;
172   Handle(Geom_Curve) C = BRep_Tool::Curve(E, L, UMin, UMax);
173   GeomAdaptor_Curve AdaptCurve(C);
174   double length = GCPnts_AbscissaPoint::Length(AdaptCurve, UMin, UMax);
175   return length;
176 }
177
178 //================================================================================
179 /*!
180  * \brief Calculate normal of a mesh face
181  */
182 //================================================================================
183
184 bool SMESH_Algo::FaceNormal(const SMDS_MeshElement* F, gp_XYZ& normal, bool normalized)
185 {
186   if ( !F || F->GetType() != SMDSAbs_Face )
187     return false;
188
189   normal.SetCoord(0,0,0);
190   int nbNodes = F->IsQuadratic() ? F->NbNodes()/2 : F->NbNodes();
191   for ( int i = 0; i < nbNodes-2; ++i )
192   {
193     gp_XYZ p[3];
194     for ( int n = 0; n < 3; ++n )
195     {
196       const SMDS_MeshNode* node = F->GetNode( n );
197       p[n].SetCoord( node->X(), node->Y(), node->Z() );
198     }
199     normal += ( p[0] - p[1] ) ^ ( p[2] - p[1] );
200   }
201   double size2 = normal.SquareModulus();
202   bool ok = ( size2 > numeric_limits<double>::min() * numeric_limits<double>::min());
203   if ( normalized && ok )
204     normal /= sqrt( size2 );
205
206   return ok;
207 }
208
209 //================================================================================
210 /*!
211  * \brief Find out elements orientation on a geometrical face
212  * \param theFace - The face correctly oriented in the shape being meshed
213  * \param theMeshDS - The mesh data structure
214  * \retval bool - true if the face normal and the normal of first element
215  *                in the correspoding submesh point in different directions
216  */
217 //================================================================================
218
219 bool SMESH_Algo::IsReversedSubMesh (const TopoDS_Face&  theFace,
220                                     SMESHDS_Mesh*       theMeshDS)
221 {
222   if ( theFace.IsNull() || !theMeshDS )
223     return false;
224
225   // find out orientation of a meshed face
226   int faceID = theMeshDS->ShapeToIndex( theFace );
227   TopoDS_Shape aMeshedFace = theMeshDS->IndexToShape( faceID );
228   bool isReversed = ( theFace.Orientation() != aMeshedFace.Orientation() );
229
230   const SMESHDS_SubMesh * aSubMeshDSFace = theMeshDS->MeshElements( faceID );
231   if ( !aSubMeshDSFace )
232     return isReversed;
233
234   // find element with node located on face and get its normal
235   const SMDS_FacePosition* facePos = 0;
236   int vertexID = 0;
237   gp_Pnt nPnt[3];
238   gp_Vec Ne;
239   bool normalOK = false;
240   SMDS_ElemIteratorPtr iteratorElem = aSubMeshDSFace->GetElements();
241   while ( iteratorElem->more() ) // loop on elements on theFace
242   {
243     const SMDS_MeshElement* elem = iteratorElem->next();
244     if ( elem && elem->NbNodes() > 2 ) {
245       SMDS_ElemIteratorPtr nodesIt = elem->nodesIterator();
246       const SMDS_FacePosition* fPos = 0;
247       int i = 0, vID = 0;
248       while ( nodesIt->more() ) { // loop on nodes
249         const SMDS_MeshNode* node
250           = static_cast<const SMDS_MeshNode *>(nodesIt->next());
251         if ( i == 3 ) i = 2;
252         nPnt[ i++ ].SetCoord( node->X(), node->Y(), node->Z() );
253         // check position
254         const SMDS_PositionPtr& pos = node->GetPosition();
255         if ( !pos ) continue;
256         if ( pos->GetTypeOfPosition() == SMDS_TOP_FACE ) {
257           fPos = dynamic_cast< const SMDS_FacePosition* >( pos.get() );
258         }
259         else if ( pos->GetTypeOfPosition() == SMDS_TOP_VERTEX ) {
260           vID = pos->GetShapeId();
261         }
262       }
263       if ( fPos || ( !normalOK && vID )) {
264         // compute normal
265         gp_Vec v01( nPnt[0], nPnt[1] ), v02( nPnt[0], nPnt[2] );
266         if ( v01.SquareMagnitude() > RealSmall() &&
267              v02.SquareMagnitude() > RealSmall() )
268         {
269           Ne = v01 ^ v02;
270           normalOK = ( Ne.SquareMagnitude() > RealSmall() );
271         }
272         // we need position on theFace or at least on vertex
273         if ( normalOK ) {
274           vertexID = vID;
275           if ((facePos = fPos))
276             break;
277         }
278       }
279     }
280   }
281   if ( !normalOK )
282     return isReversed;
283
284   // node position on face
285   double u,v;
286   if ( facePos ) {
287     u = facePos->GetUParameter();
288     v = facePos->GetVParameter();
289   }
290   else if ( vertexID ) {
291     TopoDS_Shape V = theMeshDS->IndexToShape( vertexID );
292     if ( V.IsNull() || V.ShapeType() != TopAbs_VERTEX )
293       return isReversed;
294     gp_Pnt2d uv = BRep_Tool::Parameters( TopoDS::Vertex( V ), theFace );
295     u = uv.X();
296     v = uv.Y();
297   }
298   else
299   {
300     return isReversed;
301   }
302
303   // face normal at node position
304   TopLoc_Location loc;
305   Handle(Geom_Surface) surf = BRep_Tool::Surface( theFace, loc );
306   if ( surf.IsNull() || surf->Continuity() < GeomAbs_C1 ) return isReversed;
307   gp_Vec d1u, d1v;
308   surf->D1( u, v, nPnt[0], d1u, d1v );
309   gp_Vec Nf = (d1u ^ d1v).Transformed( loc );
310
311   if ( theFace.Orientation() == TopAbs_REVERSED )
312     Nf.Reverse();
313
314   return Ne * Nf < 0.;
315 }
316
317 //================================================================================
318 /*!
319  * \brief Just return false as the algorithm does not hold parameters values
320  */
321 //================================================================================
322
323 bool SMESH_Algo::SetParametersByMesh(const SMESH_Mesh* /*theMesh*/,
324                                      const TopoDS_Shape& /*theShape*/)
325 {
326   return false;
327 }
328 bool SMESH_Algo::SetParametersByDefaults(const TDefaults& , const SMESH_Mesh*)
329 {
330   return false;
331 }
332 //================================================================================
333 /*!
334  * \brief Fill vector of node parameters on geometrical edge, including vertex nodes
335  * \param theMesh - The mesh containing nodes
336  * \param theEdge - The geometrical edge of interest
337  * \param theParams - The resulting vector of sorted node parameters
338  * \retval bool - false if not all parameters are OK
339  */
340 //================================================================================
341
342 bool SMESH_Algo::GetNodeParamOnEdge(const SMESHDS_Mesh* theMesh,
343                                     const TopoDS_Edge&  theEdge,
344                                     vector< double > &  theParams)
345 {
346   theParams.clear();
347
348   if ( !theMesh || theEdge.IsNull() )
349     return false;
350
351   SMESHDS_SubMesh * eSubMesh = theMesh->MeshElements( theEdge );
352   if ( !eSubMesh || !eSubMesh->GetElements()->more() )
353     return false; // edge is not meshed
354
355   //int nbEdgeNodes = 0;
356   set < double > paramSet;
357   if ( eSubMesh )
358   {
359     // loop on nodes of an edge: sort them by param on edge
360     SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
361     while ( nIt->more() )
362     {
363       const SMDS_MeshNode* node = nIt->next();
364       const SMDS_PositionPtr& pos = node->GetPosition();
365       if ( pos->GetTypeOfPosition() != SMDS_TOP_EDGE )
366         return false;
367       const SMDS_EdgePosition* epos =
368         static_cast<const SMDS_EdgePosition*>(node->GetPosition().get());
369       if ( !paramSet.insert( epos->GetUParameter() ).second )
370         return false; // equal parameters
371     }
372   }
373   // add vertex nodes params
374   TopoDS_Vertex V1,V2;
375   TopExp::Vertices( theEdge, V1, V2);
376   if ( VertexNode( V1, theMesh ) &&
377        !paramSet.insert( BRep_Tool::Parameter(V1,theEdge) ).second )
378     return false; // there are equal parameters
379   if ( VertexNode( V2, theMesh ) &&
380        !paramSet.insert( BRep_Tool::Parameter(V2,theEdge) ).second )
381     return false; // there are equal parameters
382
383   // fill the vector
384   theParams.resize( paramSet.size() );
385   set < double >::iterator   par    = paramSet.begin();
386   vector< double >::iterator vecPar = theParams.begin();
387   for ( ; par != paramSet.end(); ++par, ++vecPar )
388     *vecPar = *par;
389
390   return theParams.size() > 1;
391 }
392
393 //================================================================================
394 /*!
395  * \brief Fill vector of node parameters on geometrical edge, including vertex nodes
396  * \param theMesh - The mesh containing nodes
397  * \param theEdge - The geometrical edge of interest
398  * \param theParams - The resulting vector of sorted node parameters
399  * \retval bool - false if not all parameters are OK
400  */
401 //================================================================================
402
403 bool SMESH_Algo::GetSortedNodesOnEdge(const SMESHDS_Mesh*                   theMesh,
404                                       const TopoDS_Edge&                    theEdge,
405                                       const bool                            ignoreMediumNodes,
406                                       map< double, const SMDS_MeshNode* > & theNodes)
407 {
408   theNodes.clear();
409
410   if ( !theMesh || theEdge.IsNull() )
411     return false;
412
413   SMESHDS_SubMesh * eSubMesh = theMesh->MeshElements( theEdge );
414   if ( !eSubMesh || !eSubMesh->GetElements()->more() )
415     return false; // edge is not meshed
416
417   int nbNodes = 0;
418   set < double > paramSet;
419   if ( eSubMesh )
420   {
421     // loop on nodes of an edge: sort them by param on edge
422     SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
423     while ( nIt->more() )
424     {
425       const SMDS_MeshNode* node = nIt->next();
426       if ( ignoreMediumNodes ) {
427         SMDS_ElemIteratorPtr elemIt = node->GetInverseElementIterator();
428         if ( elemIt->more() && elemIt->next()->IsMediumNode( node ))
429           continue;
430       }
431       const SMDS_PositionPtr& pos = node->GetPosition();
432       if ( pos->GetTypeOfPosition() != SMDS_TOP_EDGE )
433         return false;
434       const SMDS_EdgePosition* epos =
435         static_cast<const SMDS_EdgePosition*>(node->GetPosition().get());
436       theNodes.insert( make_pair( epos->GetUParameter(), node ));
437       ++nbNodes;
438     }
439   }
440   // add vertex nodes
441   TopoDS_Vertex v1, v2;
442   TopExp::Vertices(theEdge, v1, v2);
443   const SMDS_MeshNode* n1 = VertexNode( v1, (SMESHDS_Mesh*) theMesh );
444   const SMDS_MeshNode* n2 = VertexNode( v2, (SMESHDS_Mesh*) theMesh );
445   Standard_Real f, l;
446   BRep_Tool::Range(theEdge, f, l);
447   if ( v1.Orientation() != TopAbs_FORWARD )
448     std::swap( f, l );
449   if ( n1 && ++nbNodes )
450     theNodes.insert( make_pair( f, n1 ));
451   if ( n2 && ++nbNodes )
452     theNodes.insert( make_pair( l, n2 ));
453
454   return theNodes.size() == nbNodes;
455 }
456
457 //================================================================================
458 /*!
459  * \brief Make filter recognize only compatible hypotheses
460  * \param theFilter - the filter to initialize
461  * \param ignoreAuxiliary - make filter ignore compatible auxiliary hypotheses
462  */
463 //================================================================================
464
465 bool SMESH_Algo::InitCompatibleHypoFilter( SMESH_HypoFilter & theFilter,
466                                            const bool         ignoreAuxiliary) const
467 {
468   if ( !_compatibleHypothesis.empty() )
469   {
470     theFilter.Init( theFilter.HasName( _compatibleHypothesis[0] ));
471     for ( int i = 1; i < _compatibleHypothesis.size(); ++i )
472       theFilter.Or( theFilter.HasName( _compatibleHypothesis[ i ] ));
473
474     if ( ignoreAuxiliary )
475       theFilter.AndNot( theFilter.IsAuxiliary() );
476
477     return true;
478   }
479   return false;
480 }
481
482 //================================================================================
483 /*!
484  * \brief Return continuity of two edges
485  * \param E1 - the 1st edge
486  * \param E2 - the 2nd edge
487  * \retval GeomAbs_Shape - regularity at the junction between E1 and E2
488  */
489 //================================================================================
490
491 GeomAbs_Shape SMESH_Algo::Continuity(const TopoDS_Edge & E1,
492                                      const TopoDS_Edge & E2)
493 {
494   TopoDS_Vertex V = TopExp::LastVertex (E1, true);
495   if ( !V.IsSame( TopExp::FirstVertex(E2, true )))
496     if ( !TopExp::CommonVertex( E1, E2, V ))
497       return GeomAbs_C0;
498   Standard_Real u1 = BRep_Tool::Parameter( V, E1 );
499   Standard_Real u2 = BRep_Tool::Parameter( V, E2 );
500   BRepAdaptor_Curve C1( E1 ), C2( E2 );
501   Standard_Real tol = BRep_Tool::Tolerance( V );
502   Standard_Real angTol = 2e-3;
503   try {
504 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
505     OCC_CATCH_SIGNALS;
506 #endif
507     return BRepLProp::Continuity(C1, C2, u1, u2, tol, angTol);
508   }
509   catch (Standard_Failure) {
510   }
511   return GeomAbs_C0;
512 }
513
514 //================================================================================
515 /*!
516  * \brief Return the node built on a vertex
517  * \param V - the vertex
518  * \param meshDS - mesh
519  * \retval const SMDS_MeshNode* - found node or NULL
520  */
521 //================================================================================
522
523 const SMDS_MeshNode* SMESH_Algo::VertexNode(const TopoDS_Vertex& V,
524                                             const SMESHDS_Mesh*  meshDS)
525 {
526   if ( SMESHDS_SubMesh* sm = meshDS->MeshElements(V) ) {
527     SMDS_NodeIteratorPtr nIt= sm->GetNodes();
528     if (nIt->more())
529       return nIt->next();
530   }
531   return 0;
532 }
533
534 //================================================================================
535 /*!
536  * \brief Sets event listener to submeshes if necessary
537  * \param subMesh - submesh where algo is set
538  * 
539  * After being set, event listener is notified on each event of a submesh.
540  * By default non listener is set
541  */
542 //================================================================================
543
544 void SMESH_Algo::SetEventListener(SMESH_subMesh* /*subMesh*/)
545 {
546 }
547
548 //================================================================================
549 /*!
550  * \brief Allow algo to do something after persistent restoration
551  * \param subMesh - restored submesh
552  *
553  * This method is called only if a submesh has HYP_OK algo_state.
554  */
555 //================================================================================
556
557 void SMESH_Algo::SubmeshRestored(SMESH_subMesh* /*subMesh*/)
558 {
559 }
560
561 //================================================================================
562 /*!
563  * \brief Computes mesh without geometry
564  * \param aMesh - the mesh
565  * \param aHelper - helper that must be used for adding elements to \aaMesh
566  * \retval bool - is a success
567  */
568 //================================================================================
569
570 bool SMESH_Algo::Compute(SMESH_Mesh & /*aMesh*/, SMESH_MesherHelper* /*aHelper*/)
571 {
572   return error( COMPERR_BAD_INPUT_MESH, "Mesh built on shape expected");
573 }
574
575 //================================================================================
576 /*!
577  * \brief store error and comment and then return ( error == COMPERR_OK )
578  */
579 //================================================================================
580
581 bool SMESH_Algo::error(int error, const SMESH_Comment& comment)
582 {
583   _error   = error;
584   _comment = comment;
585   return ( error == COMPERR_OK );
586 }
587
588 //================================================================================
589 /*!
590  * \brief store error and return ( error == COMPERR_OK )
591  */
592 //================================================================================
593
594 bool SMESH_Algo::error(SMESH_ComputeErrorPtr error)
595 {
596   if ( error ) {
597     _error   = error->myName;
598     _comment = error->myComment;
599     _badInputElements = error->myBadElements;
600     return error->IsOK();
601   }
602   return true;
603 }
604
605 //================================================================================
606 /*!
607  * \brief return compute error
608  */
609 //================================================================================
610
611 SMESH_ComputeErrorPtr SMESH_Algo::GetComputeError() const
612 {
613   SMESH_ComputeErrorPtr err = SMESH_ComputeError::New( _error, _comment, this );
614   // hope this method is called by only SMESH_subMesh after this->Compute()
615   err->myBadElements.splice( err->myBadElements.end(),
616                              (list<const SMDS_MeshElement*>&) _badInputElements );
617   return err;
618 }
619
620 //================================================================================
621 /*!
622  * \brief initialize compute error
623  */
624 //================================================================================
625
626 void SMESH_Algo::InitComputeError()
627 {
628   _error = COMPERR_OK;
629   _comment.clear();
630   list<const SMDS_MeshElement*>::iterator elem = _badInputElements.begin();
631   for ( ; elem != _badInputElements.end(); ++elem )
632     if ( (*elem)->GetID() < 1 )
633       delete *elem;
634   _badInputElements.clear();
635 }
636
637 //================================================================================
638 /*!
639  * \brief store a bad input element preventing computation,
640  *        which may be a temporary one i.e. not residing the mesh,
641  *        then it will be deleted by InitComputeError()
642  */
643 //================================================================================
644
645 void SMESH_Algo::addBadInputElement(const SMDS_MeshElement* elem)
646 {
647   if ( elem )
648     _badInputElements.push_back( elem );
649 }