Salome HOME
0019292: EDF 672 SMESH : extend Composite side discretisation to 2D
[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, SMESH_Gen * gen)
75   : 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 Fill vector of node parameters on geometrical edge, including vertex nodes
366  * \param theMesh - The mesh containing nodes
367  * \param theEdge - The geometrical edge of interest
368  * \param theParams - The resulting vector of sorted node parameters
369  * \retval bool - false if not all parameters are OK
370  */
371 //================================================================================
372
373 bool SMESH_Algo::GetSortedNodesOnEdge(const SMESHDS_Mesh*                   theMesh,
374                                       const TopoDS_Edge&                    theEdge,
375                                       const bool                            ignoreMediumNodes,
376                                       map< double, const SMDS_MeshNode* > & theNodes)
377 {
378   theNodes.clear();
379
380   if ( !theMesh || theEdge.IsNull() )
381     return false;
382
383   SMESHDS_SubMesh * eSubMesh = theMesh->MeshElements( theEdge );
384   if ( !eSubMesh || !eSubMesh->GetElements()->more() )
385     return false; // edge is not meshed
386
387   int nbNodes = 0;
388   set < double > paramSet;
389   if ( eSubMesh )
390   {
391     // loop on nodes of an edge: sort them by param on edge
392     SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
393     while ( nIt->more() )
394     {
395       const SMDS_MeshNode* node = nIt->next();
396       if ( ignoreMediumNodes ) {
397         SMDS_ElemIteratorPtr elemIt = node->GetInverseElementIterator();
398         if ( elemIt->more() && elemIt->next()->IsMediumNode( node ))
399           continue;
400       }
401       const SMDS_PositionPtr& pos = node->GetPosition();
402       if ( pos->GetTypeOfPosition() != SMDS_TOP_EDGE )
403         return false;
404       const SMDS_EdgePosition* epos =
405         static_cast<const SMDS_EdgePosition*>(node->GetPosition().get());
406       theNodes.insert( make_pair( epos->GetUParameter(), node ));
407       ++nbNodes;
408     }
409   }
410   // add vertex nodes
411   TopoDS_Vertex v1, v2;
412   TopExp::Vertices(theEdge, v1, v2);
413   const SMDS_MeshNode* n1 = VertexNode( v1, (SMESHDS_Mesh*) theMesh );
414   const SMDS_MeshNode* n2 = VertexNode( v2, (SMESHDS_Mesh*) theMesh );
415   Standard_Real f, l;
416   BRep_Tool::Range(theEdge, f, l);
417   if ( v1.Orientation() != TopAbs_FORWARD )
418     std::swap( f, l );
419   if ( n1 && ++nbNodes )
420     theNodes.insert( make_pair( f, n1 ));
421   if ( n2 && ++nbNodes )
422     theNodes.insert( make_pair( l, n2 ));
423
424   return theNodes.size() == nbNodes;
425 }
426
427 //================================================================================
428 /*!
429  * \brief Make filter recognize only compatible hypotheses
430  * \param theFilter - the filter to initialize
431  * \param ignoreAuxiliary - make filter ignore compatible auxiliary hypotheses
432  */
433 //================================================================================
434
435 bool SMESH_Algo::InitCompatibleHypoFilter( SMESH_HypoFilter & theFilter,
436                                            const bool         ignoreAuxiliary) const
437 {
438   if ( !_compatibleHypothesis.empty() )
439   {
440     theFilter.Init( theFilter.HasName( _compatibleHypothesis[0] ));
441     for ( int i = 1; i < _compatibleHypothesis.size(); ++i )
442       theFilter.Or( theFilter.HasName( _compatibleHypothesis[ i ] ));
443
444     if ( ignoreAuxiliary )
445       theFilter.AndNot( theFilter.IsAuxiliary() );
446
447     return true;
448   }
449   return false;
450 }
451
452 //================================================================================
453 /*!
454  * \brief Return continuity of two edges
455  * \param E1 - the 1st edge
456  * \param E2 - the 2nd edge
457  * \retval GeomAbs_Shape - regularity at the junction between E1 and E2
458  */
459 //================================================================================
460
461 GeomAbs_Shape SMESH_Algo::Continuity(const TopoDS_Edge & E1,
462                                      const TopoDS_Edge & E2)
463 {
464   TopoDS_Vertex V = TopExp::LastVertex (E1, true);
465   if ( !V.IsSame( TopExp::FirstVertex(E2, true )))
466     if ( !TopExp::CommonVertex( E1, E2, V ))
467       return GeomAbs_C0;
468   Standard_Real u1 = BRep_Tool::Parameter( V, E1 );
469   Standard_Real u2 = BRep_Tool::Parameter( V, E2 );
470   BRepAdaptor_Curve C1( E1 ), C2( E2 );
471   Standard_Real tol = BRep_Tool::Tolerance( V );
472   Standard_Real angTol = 2e-3;
473   try {
474 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
475     OCC_CATCH_SIGNALS;
476 #endif
477     return BRepLProp::Continuity(C1, C2, u1, u2, tol, angTol);
478   }
479   catch (Standard_Failure) {
480   }
481   return GeomAbs_C0;
482 }
483
484 //================================================================================
485 /*!
486  * \brief Return the node built on a vertex
487  * \param V - the vertex
488  * \param meshDS - mesh
489  * \retval const SMDS_MeshNode* - found node or NULL
490  */
491 //================================================================================
492
493 const SMDS_MeshNode* SMESH_Algo::VertexNode(const TopoDS_Vertex& V,
494                                             SMESHDS_Mesh*        meshDS)
495 {
496   if ( SMESHDS_SubMesh* sm = meshDS->MeshElements(V) ) {
497     SMDS_NodeIteratorPtr nIt= sm->GetNodes();
498     if (nIt->more())
499       return nIt->next();
500   }
501   return 0;
502 }
503
504 //================================================================================
505 /*!
506  * \brief Sets event listener to submeshes if necessary
507  * \param subMesh - submesh where algo is set
508  * 
509  * After being set, event listener is notified on each event of a submesh.
510  * By default non listener is set
511  */
512 //================================================================================
513
514 void SMESH_Algo::SetEventListener(SMESH_subMesh* /*subMesh*/)
515 {
516 }
517
518 //================================================================================
519 /*!
520  * \brief Allow algo to do something after persistent restoration
521  * \param subMesh - restored submesh
522  *
523  * This method is called only if a submesh has HYP_OK algo_state.
524  */
525 //================================================================================
526
527 void SMESH_Algo::SubmeshRestored(SMESH_subMesh* /*subMesh*/)
528 {
529 }
530
531 //================================================================================
532 /*!
533  * \brief Computes mesh without geometry
534  * \param aMesh - the mesh
535  * \param aHelper - helper that must be used for adding elements to \aaMesh
536  * \retval bool - is a success
537  */
538 //================================================================================
539
540 bool SMESH_Algo::Compute(SMESH_Mesh & /*aMesh*/, SMESH_MesherHelper* /*aHelper*/)
541 {
542   return error( COMPERR_BAD_INPUT_MESH, "Mesh built on shape expected");
543 }
544
545 //================================================================================
546 /*!
547  * \brief store error and comment and then return ( error == COMPERR_OK )
548  */
549 //================================================================================
550
551 bool SMESH_Algo::error(int error, const SMESH_Comment& comment)
552 {
553   _error   = error;
554   _comment = comment;
555   return ( error == COMPERR_OK );
556 }
557
558 //================================================================================
559 /*!
560  * \brief store error and return ( error == COMPERR_OK )
561  */
562 //================================================================================
563
564 bool SMESH_Algo::error(SMESH_ComputeErrorPtr error)
565 {
566   if ( error ) {
567     _error   = error->myName;
568     _comment = error->myComment;
569     _badInputElements = error->myBadElements;
570     return error->IsOK();
571   }
572   return true;
573 }
574
575 //================================================================================
576 /*!
577  * \brief return compute error
578  */
579 //================================================================================
580
581 SMESH_ComputeErrorPtr SMESH_Algo::GetComputeError() const
582 {
583   SMESH_ComputeErrorPtr err = SMESH_ComputeError::New( _error, _comment, this );
584   // hope this method is called by only SMESH_subMesh after this->Compute()
585   err->myBadElements.splice( err->myBadElements.end(),
586                              (list<const SMDS_MeshElement*>&) _badInputElements );
587   return err;
588 }
589
590 //================================================================================
591 /*!
592  * \brief initialize compute error
593  */
594 //================================================================================
595
596 void SMESH_Algo::InitComputeError()
597 {
598   _error = COMPERR_OK;
599   _comment.clear();
600   list<const SMDS_MeshElement*>::iterator elem = _badInputElements.begin();
601   for ( ; elem != _badInputElements.end(); ++elem )
602     if ( (*elem)->GetID() < 1 )
603       delete *elem;
604   _badInputElements.clear();
605 }
606
607 //================================================================================
608 /*!
609  * \brief store a bad input element preventing computation,
610  *        which may be a temporary one i.e. not residing the mesh,
611  *        then it will be deleted by InitComputeError()
612  */
613 //================================================================================
614
615 void SMESH_Algo::addBadInputElement(const SMDS_MeshElement* elem)
616 {
617   if ( elem )
618     _badInputElements.push_back( elem );
619 }