1 // Copyright (C) 2007-2011 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 <BRepAdaptor_Curve.hxx>
44 #include <BRepLProp.hxx>
45 #include <BRep_Tool.hxx>
46 #include <GCPnts_AbscissaPoint.hxx>
47 #include <GeomAdaptor_Curve.hxx>
48 #include <Geom_Surface.hxx>
50 #include <TopLoc_Location.hxx>
51 #include <TopTools_ListIteratorOfListOfShape.hxx>
52 #include <TopTools_ListOfShape.hxx>
54 #include <TopoDS_Edge.hxx>
55 #include <TopoDS_Face.hxx>
56 #include <TopoDS_Vertex.hxx>
58 #include <gp_Pnt2d.hxx>
61 #include <Standard_ErrorHandler.hxx>
62 #include <Standard_Failure.hxx>
64 #include "utilities.h"
71 //=============================================================================
75 //=============================================================================
77 SMESH_Algo::SMESH_Algo (int hypId, int studyId, SMESH_Gen * gen)
78 : SMESH_Hypothesis(hypId, studyId, gen)
80 gen->_mapAlgo[hypId] = this;
82 _onlyUnaryInput = _requireDescretBoundary = _requireShape = true;
83 _quadraticMesh = _supportSubmeshes = false;
87 //=============================================================================
91 //=============================================================================
93 SMESH_Algo::~SMESH_Algo()
97 //=============================================================================
99 * Usually an algoritm has nothing to save
101 //=============================================================================
103 ostream & SMESH_Algo::SaveTo(ostream & save) { return save; }
104 istream & SMESH_Algo::LoadFrom(istream & load) { return load; }
106 //=============================================================================
110 //=============================================================================
112 const vector < string > &SMESH_Algo::GetCompatibleHypothesis()
114 return _compatibleHypothesis;
117 //=============================================================================
119 * List the hypothesis used by the algorithm associated to the shape.
120 * Hypothesis associated to father shape -are- taken into account (see
121 * GetAppliedHypothesis). Relevant hypothesis have a name (type) listed in
122 * the algorithm. This method could be surcharged by specific algorithms, in
123 * case of several hypothesis simultaneously applicable.
125 //=============================================================================
127 const list <const SMESHDS_Hypothesis *> &
128 SMESH_Algo::GetUsedHypothesis(SMESH_Mesh & aMesh,
129 const TopoDS_Shape & aShape,
130 const bool ignoreAuxiliary)
132 _usedHypList.clear();
133 SMESH_HypoFilter filter;
134 if ( InitCompatibleHypoFilter( filter, ignoreAuxiliary ))
136 aMesh.GetHypotheses( aShape, filter, _usedHypList, true );
137 if ( ignoreAuxiliary && _usedHypList.size() > 1 )
138 _usedHypList.clear(); //only one compatible hypothesis allowed
143 //=============================================================================
145 * List the relevant hypothesis associated to the shape. Relevant hypothesis
146 * have a name (type) listed in the algorithm. Hypothesis associated to
147 * father shape -are not- taken into account (see GetUsedHypothesis)
149 //=============================================================================
151 const list<const SMESHDS_Hypothesis *> &
152 SMESH_Algo::GetAppliedHypothesis(SMESH_Mesh & aMesh,
153 const TopoDS_Shape & aShape,
154 const bool ignoreAuxiliary)
156 _appliedHypList.clear();
157 SMESH_HypoFilter filter;
158 if ( InitCompatibleHypoFilter( filter, ignoreAuxiliary ))
159 aMesh.GetHypotheses( aShape, filter, _appliedHypList, false );
161 return _appliedHypList;
164 //=============================================================================
166 * Compute length of an edge
168 //=============================================================================
170 double SMESH_Algo::EdgeLength(const TopoDS_Edge & E)
172 double UMin = 0, UMax = 0;
173 if (BRep_Tool::Degenerated(E))
176 Handle(Geom_Curve) C = BRep_Tool::Curve(E, L, UMin, UMax);
177 GeomAdaptor_Curve AdaptCurve(C, UMin, UMax); //range is important for periodic curves
178 double length = GCPnts_AbscissaPoint::Length(AdaptCurve, UMin, UMax);
182 //================================================================================
184 * \brief Calculate normal of a mesh face
186 //================================================================================
188 bool SMESH_Algo::FaceNormal(const SMDS_MeshElement* F, gp_XYZ& normal, bool normalized)
190 if ( !F || F->GetType() != SMDSAbs_Face )
193 normal.SetCoord(0,0,0);
194 int nbNodes = F->IsQuadratic() ? F->NbNodes()/2 : F->NbNodes();
195 for ( int i = 0; i < nbNodes-2; ++i )
198 for ( int n = 0; n < 3; ++n )
200 const SMDS_MeshNode* node = F->GetNode( i + n );
201 p[n].SetCoord( node->X(), node->Y(), node->Z() );
203 normal += ( p[2] - p[1] ) ^ ( p[0] - p[1] );
205 double size2 = normal.SquareModulus();
206 bool ok = ( size2 > numeric_limits<double>::min() * numeric_limits<double>::min());
207 if ( normalized && ok )
208 normal /= sqrt( size2 );
213 //================================================================================
215 * \brief Find out elements orientation on a geometrical face
216 * \param theFace - The face correctly oriented in the shape being meshed
217 * \param theMeshDS - The mesh data structure
218 * \retval bool - true if the face normal and the normal of first element
219 * in the correspoding submesh point in different directions
221 //================================================================================
223 bool SMESH_Algo::IsReversedSubMesh (const TopoDS_Face& theFace,
224 SMESHDS_Mesh* theMeshDS)
226 if ( theFace.IsNull() || !theMeshDS )
229 // find out orientation of a meshed face
230 int faceID = theMeshDS->ShapeToIndex( theFace );
231 TopoDS_Shape aMeshedFace = theMeshDS->IndexToShape( faceID );
232 bool isReversed = ( theFace.Orientation() != aMeshedFace.Orientation() );
234 const SMESHDS_SubMesh * aSubMeshDSFace = theMeshDS->MeshElements( faceID );
235 if ( !aSubMeshDSFace )
238 // find element with node located on face and get its normal
239 const SMDS_FacePosition* facePos = 0;
243 bool normalOK = false;
244 SMDS_ElemIteratorPtr iteratorElem = aSubMeshDSFace->GetElements();
245 while ( iteratorElem->more() ) // loop on elements on theFace
247 const SMDS_MeshElement* elem = iteratorElem->next();
248 if ( elem && elem->NbNodes() > 2 ) {
249 SMDS_ElemIteratorPtr nodesIt = elem->nodesIterator();
250 const SMDS_FacePosition* fPos = 0;
252 while ( nodesIt->more() ) { // loop on nodes
253 const SMDS_MeshNode* node
254 = static_cast<const SMDS_MeshNode *>(nodesIt->next());
256 nPnt[ i++ ].SetCoord( node->X(), node->Y(), node->Z() );
258 const SMDS_PositionPtr& pos = node->GetPosition();
259 if ( !pos ) continue;
260 if ( pos->GetTypeOfPosition() == SMDS_TOP_FACE ) {
261 fPos = dynamic_cast< const SMDS_FacePosition* >( pos );
263 else if ( pos->GetTypeOfPosition() == SMDS_TOP_VERTEX ) {
264 vID = node->getshapeId();
267 if ( fPos || ( !normalOK && vID )) {
269 gp_Vec v01( nPnt[0], nPnt[1] ), v02( nPnt[0], nPnt[2] );
270 if ( v01.SquareMagnitude() > RealSmall() &&
271 v02.SquareMagnitude() > RealSmall() )
274 normalOK = ( Ne.SquareMagnitude() > RealSmall() );
276 // we need position on theFace or at least on vertex
279 if ((facePos = fPos))
288 // node position on face
291 u = facePos->GetUParameter();
292 v = facePos->GetVParameter();
294 else if ( vertexID ) {
295 TopoDS_Shape V = theMeshDS->IndexToShape( vertexID );
296 if ( V.IsNull() || V.ShapeType() != TopAbs_VERTEX )
298 gp_Pnt2d uv = BRep_Tool::Parameters( TopoDS::Vertex( V ), theFace );
307 // face normal at node position
309 Handle(Geom_Surface) surf = BRep_Tool::Surface( theFace, loc );
310 if ( surf.IsNull() || surf->Continuity() < GeomAbs_C1 ) return isReversed;
312 surf->D1( u, v, nPnt[0], d1u, d1v );
313 gp_Vec Nf = (d1u ^ d1v).Transformed( loc );
315 if ( theFace.Orientation() == TopAbs_REVERSED )
321 //================================================================================
323 * \brief Just return false as the algorithm does not hold parameters values
325 //================================================================================
327 bool SMESH_Algo::SetParametersByMesh(const SMESH_Mesh* /*theMesh*/,
328 const TopoDS_Shape& /*theShape*/)
332 bool SMESH_Algo::SetParametersByDefaults(const TDefaults& , const SMESH_Mesh*)
336 //================================================================================
338 * \brief Fill vector of node parameters on geometrical edge, including vertex nodes
339 * \param theMesh - The mesh containing nodes
340 * \param theEdge - The geometrical edge of interest
341 * \param theParams - The resulting vector of sorted node parameters
342 * \retval bool - false if not all parameters are OK
344 //================================================================================
346 bool SMESH_Algo::GetNodeParamOnEdge(const SMESHDS_Mesh* theMesh,
347 const TopoDS_Edge& theEdge,
348 vector< double > & theParams)
352 if ( !theMesh || theEdge.IsNull() )
355 SMESHDS_SubMesh * eSubMesh = theMesh->MeshElements( theEdge );
356 if ( !eSubMesh || !eSubMesh->GetElements()->more() )
357 return false; // edge is not meshed
359 //int nbEdgeNodes = 0;
360 set < double > paramSet;
363 // loop on nodes of an edge: sort them by param on edge
364 SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
365 while ( nIt->more() )
367 const SMDS_MeshNode* node = nIt->next();
368 const SMDS_PositionPtr& pos = node->GetPosition();
369 if ( pos->GetTypeOfPosition() != SMDS_TOP_EDGE )
371 const SMDS_EdgePosition* epos =
372 static_cast<const SMDS_EdgePosition*>(node->GetPosition());
373 if ( !paramSet.insert( epos->GetUParameter() ).second )
374 return false; // equal parameters
377 // add vertex nodes params
379 TopExp::Vertices( theEdge, V1, V2);
380 if ( VertexNode( V1, theMesh ) &&
381 !paramSet.insert( BRep_Tool::Parameter(V1,theEdge) ).second )
382 return false; // there are equal parameters
383 if ( VertexNode( V2, theMesh ) &&
384 !paramSet.insert( BRep_Tool::Parameter(V2,theEdge) ).second )
385 return false; // there are equal parameters
388 theParams.resize( paramSet.size() );
389 set < double >::iterator par = paramSet.begin();
390 vector< double >::iterator vecPar = theParams.begin();
391 for ( ; par != paramSet.end(); ++par, ++vecPar )
394 return theParams.size() > 1;
397 //================================================================================
399 * \brief Fill vector of node parameters on geometrical edge, including vertex nodes
400 * \param theMesh - The mesh containing nodes
401 * \param theEdge - The geometrical edge of interest
402 * \param theParams - The resulting vector of sorted node parameters
403 * \retval bool - false if not all parameters are OK
405 //================================================================================
407 bool SMESH_Algo::GetSortedNodesOnEdge(const SMESHDS_Mesh* theMesh,
408 const TopoDS_Edge& theEdge,
409 const bool ignoreMediumNodes,
410 map< double, const SMDS_MeshNode* > & theNodes)
414 if ( !theMesh || theEdge.IsNull() )
417 SMESHDS_SubMesh * eSubMesh = theMesh->MeshElements( theEdge );
418 if ( !eSubMesh || !eSubMesh->GetElements()->more() )
419 return false; // edge is not meshed
422 set < double > paramSet;
425 // loop on nodes of an edge: sort them by param on edge
426 SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
427 while ( nIt->more() )
429 const SMDS_MeshNode* node = nIt->next();
430 if ( ignoreMediumNodes ) {
431 SMDS_ElemIteratorPtr elemIt = node->GetInverseElementIterator();
432 if ( elemIt->more() && elemIt->next()->IsMediumNode( node ))
435 const SMDS_PositionPtr& pos = node->GetPosition();
436 if ( pos->GetTypeOfPosition() != SMDS_TOP_EDGE )
438 const SMDS_EdgePosition* epos =
439 static_cast<const SMDS_EdgePosition*>(node->GetPosition());
440 theNodes.insert( make_pair( epos->GetUParameter(), node ));
441 //MESSAGE("U " << epos->GetUParameter() << " ID " << node->GetID());
446 TopoDS_Vertex v1, v2;
447 TopExp::Vertices(theEdge, v1, v2);
448 const SMDS_MeshNode* n1 = VertexNode( v1, (SMESHDS_Mesh*) theMesh );
449 const SMDS_MeshNode* n2 = VertexNode( v2, (SMESHDS_Mesh*) theMesh );
450 //MESSAGE("Vertices ID " << n1->GetID() << " " << n2->GetID());
452 BRep_Tool::Range(theEdge, f, l);
453 if ( v1.Orientation() != TopAbs_FORWARD )
455 if ( n1 && ++nbNodes )
456 theNodes.insert( make_pair( f, n1 ));
457 if ( n2 && ++nbNodes )
458 theNodes.insert( make_pair( l, n2 ));
460 return theNodes.size() == nbNodes;
463 //================================================================================
465 * \brief Make filter recognize only compatible hypotheses
466 * \param theFilter - the filter to initialize
467 * \param ignoreAuxiliary - make filter ignore compatible auxiliary hypotheses
469 //================================================================================
471 bool SMESH_Algo::InitCompatibleHypoFilter( SMESH_HypoFilter & theFilter,
472 const bool ignoreAuxiliary) const
474 if ( !_compatibleHypothesis.empty() )
476 theFilter.Init( theFilter.HasName( _compatibleHypothesis[0] ));
477 for ( int i = 1; i < _compatibleHypothesis.size(); ++i )
478 theFilter.Or( theFilter.HasName( _compatibleHypothesis[ i ] ));
480 if ( ignoreAuxiliary )
481 theFilter.AndNot( theFilter.IsAuxiliary() );
488 //================================================================================
490 * \brief Return continuity of two edges
491 * \param E1 - the 1st edge
492 * \param E2 - the 2nd edge
493 * \retval GeomAbs_Shape - regularity at the junction between E1 and E2
495 //================================================================================
497 GeomAbs_Shape SMESH_Algo::Continuity(TopoDS_Edge E1,
500 //E1.Orientation(TopAbs_FORWARD), E2.Orientation(TopAbs_FORWARD); // avoid pb with internal edges
501 if (E1.Orientation() > TopAbs_REVERSED) // INTERNAL
502 E1.Orientation( TopAbs_FORWARD );
503 if (E2.Orientation() > TopAbs_REVERSED) // INTERNAL
504 E2.Orientation( TopAbs_FORWARD );
505 TopoDS_Vertex V = TopExp::LastVertex (E1, true);
506 if ( !V.IsSame( TopExp::FirstVertex(E2, true )))
507 if ( !TopExp::CommonVertex( E1, E2, V ))
509 Standard_Real u1 = BRep_Tool::Parameter( V, E1 );
510 Standard_Real u2 = BRep_Tool::Parameter( V, E2 );
511 BRepAdaptor_Curve C1( E1 ), C2( E2 );
512 Standard_Real tol = BRep_Tool::Tolerance( V );
513 Standard_Real angTol = 2e-3;
515 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
518 return BRepLProp::Continuity(C1, C2, u1, u2, tol, angTol);
520 catch (Standard_Failure) {
525 //================================================================================
527 * \brief Return the node built on a vertex
528 * \param V - the vertex
529 * \param meshDS - mesh
530 * \retval const SMDS_MeshNode* - found node or NULL
532 //================================================================================
534 const SMDS_MeshNode* SMESH_Algo::VertexNode(const TopoDS_Vertex& V,
535 const SMESHDS_Mesh* meshDS)
537 if ( SMESHDS_SubMesh* sm = meshDS->MeshElements(V) ) {
538 SMDS_NodeIteratorPtr nIt= sm->GetNodes();
545 //=======================================================================
546 //function : GetCommonNodes
547 //purpose : Return nodes common to two elements
548 //=======================================================================
550 vector< const SMDS_MeshNode*> SMESH_Algo::GetCommonNodes(const SMDS_MeshElement* e1,
551 const SMDS_MeshElement* e2)
553 vector< const SMDS_MeshNode*> common;
554 for ( int i = 0 ; i < e1->NbNodes(); ++i )
555 if ( e2->GetNodeIndex( e1->GetNode( i )) >= 0 )
556 common.push_back( e1->GetNode( i ));
560 //=======================================================================
561 //function : GetMeshError
562 //purpose : Finds topological errors of a sub-mesh
563 //WARNING : 1D check is NOT implemented so far
564 //=======================================================================
566 SMESH_Algo::EMeshError SMESH_Algo::GetMeshError(SMESH_subMesh* subMesh)
568 EMeshError err = MEr_OK;
570 SMESHDS_SubMesh* smDS = subMesh->GetSubMeshDS();
574 switch ( subMesh->GetSubShape().ShapeType() )
576 case TopAbs_FACE: { // ====================== 2D =====================
578 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
582 // We check that olny links on EDGEs encouter once, the rest links, twice
583 set< SMESH_TLink > links;
584 while ( fIt->more() )
586 const SMDS_MeshElement* f = fIt->next();
587 int nbNodes = f->NbCornerNodes(); // ignore medium nodes
588 for ( int i = 0; i < nbNodes; ++i )
590 const SMDS_MeshNode* n1 = f->GetNode( i );
591 const SMDS_MeshNode* n2 = f->GetNode(( i+1 ) % nbNodes);
592 std::pair< set< SMESH_TLink >::iterator, bool > it_added =
593 links.insert( SMESH_TLink( n1, n2 ));
594 if ( !it_added.second )
595 // As we do NOT(!) check if mesh is manifold, we believe that a link can
596 // encounter once or twice only (not three times), we erase a link as soon
597 // as it encounters twice to speed up search in the <links> map.
598 links.erase( it_added.first );
601 // the links remaining in the <links> should all be on EDGE
602 set< SMESH_TLink >::iterator linkIt = links.begin();
603 for ( ; linkIt != links.end(); ++linkIt )
605 const SMESH_TLink& link = *linkIt;
606 if ( link.node1()->GetPosition()->GetTypeOfPosition() > SMDS_TOP_EDGE ||
607 link.node2()->GetPosition()->GetTypeOfPosition() > SMDS_TOP_EDGE )
610 // TODO: to check orientation
613 case TopAbs_SOLID: { // ====================== 3D =====================
615 SMDS_ElemIteratorPtr vIt = smDS->GetElements();
619 SMDS_VolumeTool vTool;
620 while ( !vIt->more() )
622 if (!vTool.Set( vIt->next() ))
625 for ( int iF = 0; iF < vTool.NbFaces(); ++iF )
626 if ( vTool.IsFreeFace( iF ))
628 int nbN = vTool.NbFaceNodes( iF );
629 const SMDS_MeshNode** nodes = vTool.GetFaceNodes( iF );
630 for ( int i = 0; i < nbN; ++i )
631 if ( nodes[i]->GetPosition()->GetTypeOfPosition() > SMDS_TOP_FACE )
642 //================================================================================
644 * \brief Sets event listener to submeshes if necessary
645 * \param subMesh - submesh where algo is set
647 * After being set, event listener is notified on each event of a submesh.
648 * By default non listener is set
650 //================================================================================
652 void SMESH_Algo::SetEventListener(SMESH_subMesh* /*subMesh*/)
656 //================================================================================
658 * \brief Allow algo to do something after persistent restoration
659 * \param subMesh - restored submesh
661 * This method is called only if a submesh has HYP_OK algo_state.
663 //================================================================================
665 void SMESH_Algo::SubmeshRestored(SMESH_subMesh* /*subMesh*/)
669 //================================================================================
671 * \brief Computes mesh without geometry
672 * \param aMesh - the mesh
673 * \param aHelper - helper that must be used for adding elements to \aaMesh
674 * \retval bool - is a success
676 //================================================================================
678 bool SMESH_Algo::Compute(SMESH_Mesh & /*aMesh*/, SMESH_MesherHelper* /*aHelper*/)
680 return error( COMPERR_BAD_INPUT_MESH, "Mesh built on shape expected");
683 #ifdef WITH_SMESH_CANCEL_COMPUTE
684 void SMESH_Algo::CancelCompute()
689 //================================================================================
691 * \brief store error and comment and then return ( error == COMPERR_OK )
693 //================================================================================
695 bool SMESH_Algo::error(int error, const SMESH_Comment& comment)
699 return ( error == COMPERR_OK );
702 //================================================================================
704 * \brief store error and return ( error == COMPERR_OK )
706 //================================================================================
708 bool SMESH_Algo::error(SMESH_ComputeErrorPtr error)
711 _error = error->myName;
712 _comment = error->myComment;
713 _badInputElements = error->myBadElements;
714 return error->IsOK();
719 //================================================================================
721 * \brief return compute error
723 //================================================================================
725 SMESH_ComputeErrorPtr SMESH_Algo::GetComputeError() const
727 SMESH_ComputeErrorPtr err = SMESH_ComputeError::New( _error, _comment, this );
728 // hope this method is called by only SMESH_subMesh after this->Compute()
729 err->myBadElements.splice( err->myBadElements.end(),
730 (list<const SMDS_MeshElement*>&) _badInputElements );
734 //================================================================================
736 * \brief initialize compute error
738 //================================================================================
740 void SMESH_Algo::InitComputeError()
744 list<const SMDS_MeshElement*>::iterator elem = _badInputElements.begin();
745 for ( ; elem != _badInputElements.end(); ++elem )
746 if ( (*elem)->GetID() < 1 )
748 _badInputElements.clear();
751 //================================================================================
753 * \brief store a bad input element preventing computation,
754 * which may be a temporary one i.e. not residing the mesh,
755 * then it will be deleted by InitComputeError()
757 //================================================================================
759 void SMESH_Algo::addBadInputElement(const SMDS_MeshElement* elem)
762 _badInputElements.push_back( elem );