1 // Copyright (C) 2007-2012 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
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.
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.
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
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
23 // SMESH SMESH : implementaion of SMESH idl descriptions
24 // File : SMESH_Algo.cxx
25 // Author : Paul RASCLE, EDF
28 #include "SMESH_Algo.hxx"
30 #include "SMDS_EdgePosition.hxx"
31 #include "SMDS_FacePosition.hxx"
32 #include "SMDS_MeshElement.hxx"
33 #include "SMDS_MeshNode.hxx"
34 #include "SMDS_VolumeTool.hxx"
35 #include "SMESHDS_Mesh.hxx"
36 #include "SMESHDS_SubMesh.hxx"
37 #include "SMESH_Comment.hxx"
38 #include "SMESH_Gen.hxx"
39 #include "SMESH_HypoFilter.hxx"
40 #include "SMESH_Mesh.hxx"
41 #include "SMESH_TypeDefs.hxx"
43 #include <Basics_OCCTVersion.hxx>
45 #include <BRepAdaptor_Curve.hxx>
46 #include <BRepLProp.hxx>
47 #include <BRep_Tool.hxx>
48 #include <GCPnts_AbscissaPoint.hxx>
49 #include <GeomAdaptor_Curve.hxx>
50 #include <Geom_Surface.hxx>
52 #include <TopLoc_Location.hxx>
53 #include <TopTools_ListIteratorOfListOfShape.hxx>
54 #include <TopTools_ListOfShape.hxx>
56 #include <TopoDS_Edge.hxx>
57 #include <TopoDS_Face.hxx>
58 #include <TopoDS_Vertex.hxx>
60 #include <gp_Pnt2d.hxx>
63 #include <Standard_ErrorHandler.hxx>
64 #include <Standard_Failure.hxx>
66 #include "utilities.h"
73 //=============================================================================
77 //=============================================================================
79 SMESH_Algo::SMESH_Algo (int hypId, int studyId, SMESH_Gen * gen)
80 : SMESH_Hypothesis(hypId, studyId, gen)
82 gen->_mapAlgo[hypId] = this;
84 _onlyUnaryInput = _requireDiscreteBoundary = _requireShape = true;
85 _quadraticMesh = _supportSubmeshes = false;
89 //=============================================================================
93 //=============================================================================
95 SMESH_Algo::~SMESH_Algo()
99 //=============================================================================
101 * Usually an algoritm has nothing to save
103 //=============================================================================
105 ostream & SMESH_Algo::SaveTo(ostream & save) { return save; }
106 istream & SMESH_Algo::LoadFrom(istream & load) { return load; }
108 //=============================================================================
112 //=============================================================================
114 const vector < string > &SMESH_Algo::GetCompatibleHypothesis()
116 return _compatibleHypothesis;
119 //=============================================================================
121 * List the hypothesis used by the algorithm associated to the shape.
122 * Hypothesis associated to father shape -are- taken into account (see
123 * GetAppliedHypothesis). Relevant hypothesis have a name (type) listed in
124 * the algorithm. This method could be surcharged by specific algorithms, in
125 * case of several hypothesis simultaneously applicable.
127 //=============================================================================
129 const list <const SMESHDS_Hypothesis *> &
130 SMESH_Algo::GetUsedHypothesis(SMESH_Mesh & aMesh,
131 const TopoDS_Shape & aShape,
132 const bool ignoreAuxiliary)
134 _usedHypList.clear();
135 SMESH_HypoFilter filter;
136 if ( InitCompatibleHypoFilter( filter, ignoreAuxiliary ))
138 aMesh.GetHypotheses( aShape, filter, _usedHypList, true );
139 if ( ignoreAuxiliary && _usedHypList.size() > 1 )
140 _usedHypList.clear(); //only one compatible hypothesis allowed
145 //=============================================================================
147 * List the relevant hypothesis associated to the shape. Relevant hypothesis
148 * have a name (type) listed in the algorithm. Hypothesis associated to
149 * father shape -are not- taken into account (see GetUsedHypothesis)
151 //=============================================================================
153 const list<const SMESHDS_Hypothesis *> &
154 SMESH_Algo::GetAppliedHypothesis(SMESH_Mesh & aMesh,
155 const TopoDS_Shape & aShape,
156 const bool ignoreAuxiliary)
158 _appliedHypList.clear();
159 SMESH_HypoFilter filter;
160 if ( InitCompatibleHypoFilter( filter, ignoreAuxiliary ))
161 aMesh.GetHypotheses( aShape, filter, _appliedHypList, false );
163 return _appliedHypList;
166 //=============================================================================
168 * Compute length of an edge
170 //=============================================================================
172 double SMESH_Algo::EdgeLength(const TopoDS_Edge & E)
174 double UMin = 0, UMax = 0;
175 if (BRep_Tool::Degenerated(E))
178 Handle(Geom_Curve) C = BRep_Tool::Curve(E, L, UMin, UMax);
179 GeomAdaptor_Curve AdaptCurve(C, UMin, UMax); //range is important for periodic curves
180 double length = GCPnts_AbscissaPoint::Length(AdaptCurve, UMin, UMax);
184 //================================================================================
186 * \brief Calculate normal of a mesh face
188 //================================================================================
190 bool SMESH_Algo::FaceNormal(const SMDS_MeshElement* F, gp_XYZ& normal, bool normalized)
192 if ( !F || F->GetType() != SMDSAbs_Face )
195 normal.SetCoord(0,0,0);
196 int nbNodes = F->IsQuadratic() ? F->NbNodes()/2 : F->NbNodes();
197 for ( int i = 0; i < nbNodes-2; ++i )
200 for ( int n = 0; n < 3; ++n )
202 const SMDS_MeshNode* node = F->GetNode( i + n );
203 p[n].SetCoord( node->X(), node->Y(), node->Z() );
205 normal += ( p[2] - p[1] ) ^ ( p[0] - p[1] );
207 double size2 = normal.SquareModulus();
208 bool ok = ( size2 > numeric_limits<double>::min() * numeric_limits<double>::min());
209 if ( normalized && ok )
210 normal /= sqrt( size2 );
215 //================================================================================
217 * \brief Find out elements orientation on a geometrical face
218 * \param theFace - The face correctly oriented in the shape being meshed
219 * \param theMeshDS - The mesh data structure
220 * \retval bool - true if the face normal and the normal of first element
221 * in the correspoding submesh point in different directions
223 //================================================================================
225 bool SMESH_Algo::IsReversedSubMesh (const TopoDS_Face& theFace,
226 SMESHDS_Mesh* theMeshDS)
228 if ( theFace.IsNull() || !theMeshDS )
231 // find out orientation of a meshed face
232 int faceID = theMeshDS->ShapeToIndex( theFace );
233 TopoDS_Shape aMeshedFace = theMeshDS->IndexToShape( faceID );
234 bool isReversed = ( theFace.Orientation() != aMeshedFace.Orientation() );
236 const SMESHDS_SubMesh * aSubMeshDSFace = theMeshDS->MeshElements( faceID );
237 if ( !aSubMeshDSFace )
240 // find element with node located on face and get its normal
241 const SMDS_FacePosition* facePos = 0;
245 bool normalOK = false;
246 SMDS_ElemIteratorPtr iteratorElem = aSubMeshDSFace->GetElements();
247 while ( iteratorElem->more() ) // loop on elements on theFace
249 const SMDS_MeshElement* elem = iteratorElem->next();
250 if ( elem && elem->NbNodes() > 2 ) {
251 SMDS_ElemIteratorPtr nodesIt = elem->nodesIterator();
252 const SMDS_FacePosition* fPos = 0;
254 while ( nodesIt->more() ) { // loop on nodes
255 const SMDS_MeshNode* node
256 = static_cast<const SMDS_MeshNode *>(nodesIt->next());
258 nPnt[ i++ ].SetCoord( node->X(), node->Y(), node->Z() );
260 const SMDS_PositionPtr& pos = node->GetPosition();
261 if ( !pos ) continue;
262 if ( pos->GetTypeOfPosition() == SMDS_TOP_FACE ) {
263 fPos = dynamic_cast< const SMDS_FacePosition* >( pos );
265 else if ( pos->GetTypeOfPosition() == SMDS_TOP_VERTEX ) {
266 vID = node->getshapeId();
269 if ( fPos || ( !normalOK && vID )) {
271 gp_Vec v01( nPnt[0], nPnt[1] ), v02( nPnt[0], nPnt[2] );
272 if ( v01.SquareMagnitude() > RealSmall() &&
273 v02.SquareMagnitude() > RealSmall() )
276 normalOK = ( Ne.SquareMagnitude() > RealSmall() );
278 // we need position on theFace or at least on vertex
281 if ((facePos = fPos))
290 // node position on face
293 u = facePos->GetUParameter();
294 v = facePos->GetVParameter();
296 else if ( vertexID ) {
297 TopoDS_Shape V = theMeshDS->IndexToShape( vertexID );
298 if ( V.IsNull() || V.ShapeType() != TopAbs_VERTEX )
300 gp_Pnt2d uv = BRep_Tool::Parameters( TopoDS::Vertex( V ), theFace );
309 // face normal at node position
311 Handle(Geom_Surface) surf = BRep_Tool::Surface( theFace, loc );
312 if ( surf.IsNull() || surf->Continuity() < GeomAbs_C1 ) return isReversed;
314 surf->D1( u, v, nPnt[0], d1u, d1v );
315 gp_Vec Nf = (d1u ^ d1v).Transformed( loc );
317 if ( theFace.Orientation() == TopAbs_REVERSED )
323 //================================================================================
325 * \brief Just return false as the algorithm does not hold parameters values
327 //================================================================================
329 bool SMESH_Algo::SetParametersByMesh(const SMESH_Mesh* /*theMesh*/,
330 const TopoDS_Shape& /*theShape*/)
334 bool SMESH_Algo::SetParametersByDefaults(const TDefaults& , const SMESH_Mesh*)
338 //================================================================================
340 * \brief Fill vector of node parameters on geometrical edge, including vertex nodes
341 * \param theMesh - The mesh containing nodes
342 * \param theEdge - The geometrical edge of interest
343 * \param theParams - The resulting vector of sorted node parameters
344 * \retval bool - false if not all parameters are OK
346 //================================================================================
348 bool SMESH_Algo::GetNodeParamOnEdge(const SMESHDS_Mesh* theMesh,
349 const TopoDS_Edge& theEdge,
350 vector< double > & theParams)
354 if ( !theMesh || theEdge.IsNull() )
357 SMESHDS_SubMesh * eSubMesh = theMesh->MeshElements( theEdge );
358 if ( !eSubMesh || !eSubMesh->GetElements()->more() )
359 return false; // edge is not meshed
361 //int nbEdgeNodes = 0;
362 set < double > paramSet;
365 // loop on nodes of an edge: sort them by param on edge
366 SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
367 while ( nIt->more() )
369 const SMDS_MeshNode* node = nIt->next();
370 const SMDS_PositionPtr& pos = node->GetPosition();
371 if ( pos->GetTypeOfPosition() != SMDS_TOP_EDGE )
373 const SMDS_EdgePosition* epos =
374 static_cast<const SMDS_EdgePosition*>(node->GetPosition());
375 if ( !paramSet.insert( epos->GetUParameter() ).second )
376 return false; // equal parameters
379 // add vertex nodes params
381 TopExp::Vertices( theEdge, V1, V2);
382 if ( VertexNode( V1, theMesh ) &&
383 !paramSet.insert( BRep_Tool::Parameter(V1,theEdge) ).second )
384 return false; // there are equal parameters
385 if ( VertexNode( V2, theMesh ) &&
386 !paramSet.insert( BRep_Tool::Parameter(V2,theEdge) ).second )
387 return false; // there are equal parameters
390 theParams.resize( paramSet.size() );
391 set < double >::iterator par = paramSet.begin();
392 vector< double >::iterator vecPar = theParams.begin();
393 for ( ; par != paramSet.end(); ++par, ++vecPar )
396 return theParams.size() > 1;
399 //================================================================================
401 * \brief Fill vector of node parameters on geometrical edge, including vertex nodes
402 * \param theMesh - The mesh containing nodes
403 * \param theEdge - The geometrical edge of interest
404 * \param theParams - The resulting vector of sorted node parameters
405 * \retval bool - false if not all parameters are OK
407 //================================================================================
409 bool SMESH_Algo::GetSortedNodesOnEdge(const SMESHDS_Mesh* theMesh,
410 const TopoDS_Edge& theEdge,
411 const bool ignoreMediumNodes,
412 map< double, const SMDS_MeshNode* > & theNodes)
416 if ( !theMesh || theEdge.IsNull() )
419 SMESHDS_SubMesh * eSubMesh = theMesh->MeshElements( theEdge );
420 if ( !eSubMesh || !eSubMesh->GetElements()->more() )
421 return false; // edge is not meshed
424 set < double > paramSet;
427 // loop on nodes of an edge: sort them by param on edge
428 SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
429 while ( nIt->more() )
431 const SMDS_MeshNode* node = nIt->next();
432 if ( ignoreMediumNodes ) {
433 SMDS_ElemIteratorPtr elemIt = node->GetInverseElementIterator();
434 if ( elemIt->more() && elemIt->next()->IsMediumNode( node ))
437 const SMDS_PositionPtr& pos = node->GetPosition();
438 if ( pos->GetTypeOfPosition() != SMDS_TOP_EDGE )
440 const SMDS_EdgePosition* epos =
441 static_cast<const SMDS_EdgePosition*>(node->GetPosition());
442 theNodes.insert( theNodes.end(), make_pair( epos->GetUParameter(), node ));
443 //MESSAGE("U " << epos->GetUParameter() << " ID " << node->GetID());
448 TopoDS_Vertex v1, v2;
449 TopExp::Vertices(theEdge, v1, v2);
450 const SMDS_MeshNode* n1 = VertexNode( v1, (SMESHDS_Mesh*) theMesh );
451 const SMDS_MeshNode* n2 = VertexNode( v2, (SMESHDS_Mesh*) theMesh );
452 //MESSAGE("Vertices ID " << n1->GetID() << " " << n2->GetID());
454 BRep_Tool::Range(theEdge, f, l);
455 if ( v1.Orientation() != TopAbs_FORWARD )
457 if ( n1 && ++nbNodes )
458 theNodes.insert( make_pair( f, n1 ));
459 if ( n2 && ++nbNodes )
460 theNodes.insert( make_pair( l, n2 ));
462 return theNodes.size() == nbNodes;
465 //================================================================================
467 * \brief Make filter recognize only compatible hypotheses
468 * \param theFilter - the filter to initialize
469 * \param ignoreAuxiliary - make filter ignore compatible auxiliary hypotheses
471 //================================================================================
473 bool SMESH_Algo::InitCompatibleHypoFilter( SMESH_HypoFilter & theFilter,
474 const bool ignoreAuxiliary) const
476 if ( !_compatibleHypothesis.empty() )
478 theFilter.Init( theFilter.HasName( _compatibleHypothesis[0] ));
479 for ( int i = 1; i < _compatibleHypothesis.size(); ++i )
480 theFilter.Or( theFilter.HasName( _compatibleHypothesis[ i ] ));
482 if ( ignoreAuxiliary )
483 theFilter.AndNot( theFilter.IsAuxiliary() );
490 //================================================================================
492 * \brief Return continuity of two edges
493 * \param E1 - the 1st edge
494 * \param E2 - the 2nd edge
495 * \retval GeomAbs_Shape - regularity at the junction between E1 and E2
497 //================================================================================
499 GeomAbs_Shape SMESH_Algo::Continuity(TopoDS_Edge E1,
502 //E1.Orientation(TopAbs_FORWARD), E2.Orientation(TopAbs_FORWARD); // avoid pb with internal edges
503 if (E1.Orientation() > TopAbs_REVERSED) // INTERNAL
504 E1.Orientation( TopAbs_FORWARD );
505 if (E2.Orientation() > TopAbs_REVERSED) // INTERNAL
506 E2.Orientation( TopAbs_FORWARD );
507 TopoDS_Vertex V = TopExp::LastVertex (E1, true);
508 if ( !V.IsSame( TopExp::FirstVertex(E2, true )))
509 if ( !TopExp::CommonVertex( E1, E2, V ))
511 Standard_Real u1 = BRep_Tool::Parameter( V, E1 );
512 Standard_Real u2 = BRep_Tool::Parameter( V, E2 );
513 BRepAdaptor_Curve C1( E1 ), C2( E2 );
514 Standard_Real tol = BRep_Tool::Tolerance( V );
515 Standard_Real angTol = 2e-3;
517 #if OCC_VERSION_LARGE > 0x06010000
520 return BRepLProp::Continuity(C1, C2, u1, u2, tol, angTol);
522 catch (Standard_Failure) {
527 //================================================================================
529 * \brief Return the node built on a vertex
530 * \param V - the vertex
531 * \param meshDS - mesh
532 * \retval const SMDS_MeshNode* - found node or NULL
534 //================================================================================
536 const SMDS_MeshNode* SMESH_Algo::VertexNode(const TopoDS_Vertex& V,
537 const SMESHDS_Mesh* meshDS)
539 if ( SMESHDS_SubMesh* sm = meshDS->MeshElements(V) ) {
540 SMDS_NodeIteratorPtr nIt= sm->GetNodes();
547 //=======================================================================
548 //function : GetCommonNodes
549 //purpose : Return nodes common to two elements
550 //=======================================================================
552 vector< const SMDS_MeshNode*> SMESH_Algo::GetCommonNodes(const SMDS_MeshElement* e1,
553 const SMDS_MeshElement* e2)
555 vector< const SMDS_MeshNode*> common;
556 for ( int i = 0 ; i < e1->NbNodes(); ++i )
557 if ( e2->GetNodeIndex( e1->GetNode( i )) >= 0 )
558 common.push_back( e1->GetNode( i ));
562 //=======================================================================
563 //function : GetMeshError
564 //purpose : Finds topological errors of a sub-mesh
565 //WARNING : 1D check is NOT implemented so far
566 //=======================================================================
568 SMESH_Algo::EMeshError SMESH_Algo::GetMeshError(SMESH_subMesh* subMesh)
570 EMeshError err = MEr_OK;
572 SMESHDS_SubMesh* smDS = subMesh->GetSubMeshDS();
576 switch ( subMesh->GetSubShape().ShapeType() )
578 case TopAbs_FACE: { // ====================== 2D =====================
580 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
584 // We check that olny links on EDGEs encouter once, the rest links, twice
585 set< SMESH_TLink > links;
586 while ( fIt->more() )
588 const SMDS_MeshElement* f = fIt->next();
589 int nbNodes = f->NbCornerNodes(); // ignore medium nodes
590 for ( int i = 0; i < nbNodes; ++i )
592 const SMDS_MeshNode* n1 = f->GetNode( i );
593 const SMDS_MeshNode* n2 = f->GetNode(( i+1 ) % nbNodes);
594 std::pair< set< SMESH_TLink >::iterator, bool > it_added =
595 links.insert( SMESH_TLink( n1, n2 ));
596 if ( !it_added.second )
597 // As we do NOT(!) check if mesh is manifold, we believe that a link can
598 // encounter once or twice only (not three times), we erase a link as soon
599 // as it encounters twice to speed up search in the <links> map.
600 links.erase( it_added.first );
603 // the links remaining in the <links> should all be on EDGE
604 set< SMESH_TLink >::iterator linkIt = links.begin();
605 for ( ; linkIt != links.end(); ++linkIt )
607 const SMESH_TLink& link = *linkIt;
608 if ( link.node1()->GetPosition()->GetTypeOfPosition() > SMDS_TOP_EDGE ||
609 link.node2()->GetPosition()->GetTypeOfPosition() > SMDS_TOP_EDGE )
612 // TODO: to check orientation
615 case TopAbs_SOLID: { // ====================== 3D =====================
617 SMDS_ElemIteratorPtr vIt = smDS->GetElements();
621 SMDS_VolumeTool vTool;
622 while ( !vIt->more() )
624 if (!vTool.Set( vIt->next() ))
627 for ( int iF = 0; iF < vTool.NbFaces(); ++iF )
628 if ( vTool.IsFreeFace( iF ))
630 int nbN = vTool.NbFaceNodes( iF );
631 const SMDS_MeshNode** nodes = vTool.GetFaceNodes( iF );
632 for ( int i = 0; i < nbN; ++i )
633 if ( nodes[i]->GetPosition()->GetTypeOfPosition() > SMDS_TOP_FACE )
644 //================================================================================
646 * \brief Sets event listener to submeshes if necessary
647 * \param subMesh - submesh where algo is set
649 * After being set, event listener is notified on each event of a submesh.
650 * By default non listener is set
652 //================================================================================
654 void SMESH_Algo::SetEventListener(SMESH_subMesh* /*subMesh*/)
658 //================================================================================
660 * \brief Allow algo to do something after persistent restoration
661 * \param subMesh - restored submesh
663 * This method is called only if a submesh has HYP_OK algo_state.
665 //================================================================================
667 void SMESH_Algo::SubmeshRestored(SMESH_subMesh* /*subMesh*/)
671 //================================================================================
673 * \brief Computes mesh without geometry
674 * \param aMesh - the mesh
675 * \param aHelper - helper that must be used for adding elements to \aaMesh
676 * \retval bool - is a success
678 //================================================================================
680 bool SMESH_Algo::Compute(SMESH_Mesh & /*aMesh*/, SMESH_MesherHelper* /*aHelper*/)
682 return error( COMPERR_BAD_INPUT_MESH, "Mesh built on shape expected");
685 //=======================================================================
686 //function : CancelCompute
687 //purpose : Sets _computeCanceled to true. It's usage depends on
688 // * implementation of a particular mesher.
689 //=======================================================================
691 void SMESH_Algo::CancelCompute()
693 _computeCanceled = true;
694 _error = COMPERR_CANCELED;
697 //================================================================================
699 * \brief store error and comment and then return ( error == COMPERR_OK )
701 //================================================================================
703 bool SMESH_Algo::error(int error, const SMESH_Comment& comment)
707 return ( error == COMPERR_OK );
710 //================================================================================
712 * \brief store error and return ( error == COMPERR_OK )
714 //================================================================================
716 bool SMESH_Algo::error(SMESH_ComputeErrorPtr error)
719 _error = error->myName;
720 _comment = error->myComment;
721 _badInputElements = error->myBadElements;
722 return error->IsOK();
727 //================================================================================
729 * \brief return compute error
731 //================================================================================
733 SMESH_ComputeErrorPtr SMESH_Algo::GetComputeError() const
735 SMESH_ComputeErrorPtr err = SMESH_ComputeError::New( _error, _comment, this );
736 // hope this method is called by only SMESH_subMesh after this->Compute()
737 err->myBadElements.splice( err->myBadElements.end(),
738 (list<const SMDS_MeshElement*>&) _badInputElements );
742 //================================================================================
744 * \brief initialize compute error
746 //================================================================================
748 void SMESH_Algo::InitComputeError()
752 list<const SMDS_MeshElement*>::iterator elem = _badInputElements.begin();
753 for ( ; elem != _badInputElements.end(); ++elem )
754 if ( (*elem)->GetID() < 1 )
756 _badInputElements.clear();
758 _computeCanceled = false;
761 //================================================================================
763 * \brief store a bad input element preventing computation,
764 * which may be a temporary one i.e. not residing the mesh,
765 * then it will be deleted by InitComputeError()
767 //================================================================================
769 void SMESH_Algo::addBadInputElement(const SMDS_MeshElement* elem)
772 _badInputElements.push_back( elem );