1 // Copyright (C) 2007-2020 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, or (at your option) any later version.
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 : implementation 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_MeshAlgos.hxx"
42 #include "SMESH_TypeDefs.hxx"
43 #include "SMESH_subMesh.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>
51 #include <LDOMParser.hxx>
53 #include <TopExp_Explorer.hxx>
54 #include <TopLoc_Location.hxx>
55 #include <TopTools_ListIteratorOfListOfShape.hxx>
56 #include <TopTools_ListOfShape.hxx>
58 #include <TopoDS_Edge.hxx>
59 #include <TopoDS_Face.hxx>
60 #include <TopoDS_Vertex.hxx>
61 #include <TopoDS_Wire.hxx>
63 #include <gp_Pnt2d.hxx>
66 #include <Standard_ErrorHandler.hxx>
67 #include <Standard_Failure.hxx>
69 #include "utilities.h"
73 #include "SMESH_ProxyMesh.hxx"
74 #include "SMESH_MesherHelper.hxx"
78 //================================================================================
80 * \brief Returns \a true if two algorithms (described by \a this and the given
81 * algo data) are compatible by their output and input types of elements.
83 //================================================================================
85 bool SMESH_Algo::Features::IsCompatible( const SMESH_Algo::Features& algo2 ) const
87 if ( _dim > algo2._dim ) return algo2.IsCompatible( *this );
88 // algo2 is of higher dimension
89 if ( _outElemTypes.empty() || algo2._inElemTypes.empty() )
91 bool compatible = true;
92 set<SMDSAbs_GeometryType>::const_iterator myOutType = _outElemTypes.begin();
93 for ( ; myOutType != _outElemTypes.end() && compatible; ++myOutType )
94 compatible = algo2._inElemTypes.count( *myOutType );
98 //================================================================================
100 * \brief Return Data of the algorithm
102 //================================================================================
104 const SMESH_Algo::Features& SMESH_Algo::GetFeatures( const std::string& algoType )
106 static map< string, SMESH_Algo::Features > theFeaturesByName;
107 if ( theFeaturesByName.empty() )
109 // Read Plugin.xml files
110 vector< string > xmlPaths = SMESH_Gen::GetPluginXMLPaths();
111 LDOMParser xmlParser;
112 for ( size_t iXML = 0; iXML < xmlPaths.size(); ++iXML )
114 bool error = xmlParser.parse( xmlPaths[iXML].c_str() );
117 TCollection_AsciiString data;
118 INFOS( xmlParser.GetError(data) );
121 // <algorithm type="Regular_1D"
124 // output="QUAD,TRIA">
126 LDOM_Document xmlDoc = xmlParser.getDocument();
127 LDOM_NodeList algoNodeList = xmlDoc.getElementsByTagName( "algorithm" );
128 for ( int i = 0; i < algoNodeList.getLength(); ++i )
130 LDOM_Node algoNode = algoNodeList.item( i );
131 LDOM_Element& algoElem = (LDOM_Element&) algoNode;
132 TCollection_AsciiString algoType = algoElem.getAttribute("type");
133 TCollection_AsciiString input = algoElem.getAttribute("input");
134 TCollection_AsciiString output = algoElem.getAttribute("output");
135 TCollection_AsciiString dim = algoElem.getAttribute("dim");
136 TCollection_AsciiString label = algoElem.getAttribute("label-id");
137 if ( algoType.IsEmpty() ) continue;
139 Features & data = theFeaturesByName[ algoType.ToCString() ];
140 data._dim = dim.IntegerValue();
141 data._label = label.ToCString();
142 for ( int isInput = 0; isInput < 2; ++isInput )
144 TCollection_AsciiString& typeStr = isInput ? input : output;
145 set<SMDSAbs_GeometryType>& typeSet = isInput ? data._inElemTypes : data._outElemTypes;
147 while ( beg <= typeStr.Length() )
149 while ( beg < typeStr.Length() && !isalpha( typeStr.Value( beg ) ))
152 while ( end < typeStr.Length() && isalpha( typeStr.Value( end + 1 ) ))
156 TCollection_AsciiString typeName = typeStr.SubString( beg, end );
157 if ( typeName == "EDGE" ) typeSet.insert( SMDSGeom_EDGE );
158 else if ( typeName == "TRIA" ) typeSet.insert( SMDSGeom_TRIANGLE );
159 else if ( typeName == "QUAD" ) typeSet.insert( SMDSGeom_QUADRANGLE );
167 return theFeaturesByName[ algoType ];
170 //=============================================================================
174 //=============================================================================
176 SMESH_Algo::SMESH_Algo (int hypId, SMESH_Gen * gen)
177 : SMESH_Hypothesis(hypId, gen)
179 _compatibleAllHypFilter = _compatibleNoAuxHypFilter = NULL;
180 _onlyUnaryInput = _requireDiscreteBoundary = _requireShape = true;
181 _quadraticMesh = _supportSubmeshes = false;
183 for ( int i = 0; i < 4; ++i )
184 _neededLowerHyps[ i ] = false;
187 //=============================================================================
191 //=============================================================================
193 SMESH_Algo::~SMESH_Algo()
195 delete _compatibleNoAuxHypFilter;
196 // delete _compatibleAllHypFilter; -- _compatibleNoAuxHypFilter does it!!!
199 //=============================================================================
203 //=============================================================================
205 SMESH_0D_Algo::SMESH_0D_Algo(int hypId, SMESH_Gen* gen)
206 : SMESH_Algo(hypId, gen)
208 _shapeType = (1 << TopAbs_VERTEX);
211 SMESH_1D_Algo::SMESH_1D_Algo(int hypId, SMESH_Gen* gen)
212 : SMESH_Algo(hypId, gen)
214 _shapeType = (1 << TopAbs_EDGE);
217 SMESH_2D_Algo::SMESH_2D_Algo(int hypId, SMESH_Gen* gen)
218 : SMESH_Algo(hypId, gen)
220 _shapeType = (1 << TopAbs_FACE);
223 SMESH_3D_Algo::SMESH_3D_Algo(int hypId, SMESH_Gen* gen)
224 : SMESH_Algo(hypId, gen)
226 _shapeType = (1 << TopAbs_SOLID);
230 //=============================================================================
232 * Usually an algorithm has nothing to save
234 //=============================================================================
236 ostream & SMESH_Algo::SaveTo(ostream & save) { return save; }
237 istream & SMESH_Algo::LoadFrom(istream & load) { return load; }
239 //=============================================================================
243 //=============================================================================
245 const vector < string > &SMESH_Algo::GetCompatibleHypothesis()
247 return _compatibleHypothesis;
250 //=============================================================================
252 * List the hypothesis used by the algorithm associated to the shape.
253 * Hypothesis associated to father shape -are- taken into account (see
254 * GetAppliedHypothesis). Relevant hypothesis have a name (type) listed in
255 * the algorithm. This method could be surcharged by specific algorithms, in
256 * case of several hypothesis simultaneously applicable.
258 //=============================================================================
260 const list <const SMESHDS_Hypothesis *> &
261 SMESH_Algo::GetUsedHypothesis(SMESH_Mesh & aMesh,
262 const TopoDS_Shape & aShape,
263 const bool ignoreAuxiliary) const
265 SMESH_Algo* me = const_cast< SMESH_Algo* >( this );
267 std::list<const SMESHDS_Hypothesis *> savedHyps; // don't delete the list if
268 savedHyps.swap( me->_usedHypList ); // it does not change (#16578)
270 me->_usedHypList.clear();
271 me->_assigedShapeList.clear();
272 if ( const SMESH_HypoFilter* filter = GetCompatibleHypoFilter( ignoreAuxiliary ))
274 aMesh.GetHypotheses( aShape, *filter, me->_usedHypList, true, & me->_assigedShapeList );
275 if ( ignoreAuxiliary && _usedHypList.size() > 1 )
277 me->_usedHypList.clear(); //only one compatible hypothesis allowed
278 me->_assigedShapeList.clear();
281 if ( _usedHypList == savedHyps )
282 savedHyps.swap( me->_usedHypList );
287 //================================================================================
289 * Return sub-shape to which hypotheses returned by GetUsedHypothesis() are assigned
291 //================================================================================
293 const std::list < TopoDS_Shape > & SMESH_Algo::GetAssignedShapes() const
295 return _assigedShapeList;
298 //=============================================================================
300 * Compute length of an edge
302 //=============================================================================
304 double SMESH_Algo::EdgeLength(const TopoDS_Edge & E)
306 double UMin = 0, UMax = 0;
308 Handle(Geom_Curve) C = BRep_Tool::Curve(E, L, UMin, UMax);
311 GeomAdaptor_Curve AdaptCurve(C, UMin, UMax); //range is important for periodic curves
312 double length = GCPnts_AbscissaPoint::Length(AdaptCurve, UMin, UMax);
316 //================================================================================
318 * \brief Just return false as the algorithm does not hold parameters values
320 //================================================================================
322 bool SMESH_Algo::SetParametersByMesh(const SMESH_Mesh* /*theMesh*/,
323 const TopoDS_Shape& /*theShape*/)
327 bool SMESH_Algo::SetParametersByDefaults(const TDefaults& , const SMESH_Mesh*)
331 //================================================================================
333 * \brief Fill vector of node parameters on geometrical edge, including vertex nodes
334 * \param theMesh - The mesh containing nodes
335 * \param theEdge - The geometrical edge of interest
336 * \param theParams - The resulting vector of sorted node parameters
337 * \retval bool - false if not all parameters are OK
339 //================================================================================
341 bool SMESH_Algo::GetNodeParamOnEdge(const SMESHDS_Mesh* theMesh,
342 const TopoDS_Edge& theEdge,
343 vector< double > & theParams)
347 if ( !theMesh || theEdge.IsNull() )
350 SMESHDS_SubMesh * eSubMesh = theMesh->MeshElements( theEdge );
351 if ( !eSubMesh || !eSubMesh->GetElements()->more() )
352 return false; // edge is not meshed
354 //int nbEdgeNodes = 0;
355 set < double > paramSet;
358 // loop on nodes of an edge: sort them by param on edge
359 SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
360 while ( nIt->more() )
362 SMDS_EdgePositionPtr epos = nIt->next()->GetPosition();
365 if ( !paramSet.insert( epos->GetUParameter() ).second )
366 return false; // equal parameters
369 // add vertex nodes params
371 TopExp::Vertices( theEdge, V1, V2);
372 if ( VertexNode( V1, theMesh ) &&
373 !paramSet.insert( BRep_Tool::Parameter(V1,theEdge) ).second )
374 return false; // there are equal parameters
375 if ( VertexNode( V2, theMesh ) &&
376 !paramSet.insert( BRep_Tool::Parameter(V2,theEdge) ).second )
377 return false; // there are equal parameters
380 theParams.resize( paramSet.size() );
381 set < double >::iterator par = paramSet.begin();
382 vector< double >::iterator vecPar = theParams.begin();
383 for ( ; par != paramSet.end(); ++par, ++vecPar )
386 return theParams.size() > 1;
389 //================================================================================
391 * \brief Fill vector of node parameters on geometrical edge, including vertex nodes
392 * \param theMesh - The mesh containing nodes
393 * \param theEdge - The geometrical edge of interest
394 * \param theParams - The resulting vector of sorted node parameters
395 * \retval bool - false if not all parameters are OK
397 //================================================================================
399 bool SMESH_Algo::GetSortedNodesOnEdge(const SMESHDS_Mesh* theMesh,
400 const TopoDS_Edge& theEdge,
401 const bool ignoreMediumNodes,
402 map< double, const SMDS_MeshNode* > & theNodes,
403 const SMDSAbs_ElementType typeToCheck)
407 if ( !theMesh || theEdge.IsNull() )
410 SMESHDS_SubMesh * eSubMesh = theMesh->MeshElements( theEdge );
411 if ( !eSubMesh || ( eSubMesh->NbElements() == 0 && eSubMesh->NbNodes() == 0))
412 return false; // edge is not meshed
415 set < double > paramSet;
418 // loop on nodes of an edge: sort them by param on edge
419 SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
420 while ( nIt->more() )
422 const SMDS_MeshNode* node = nIt->next();
423 if ( ignoreMediumNodes && SMESH_MesherHelper::IsMedium( node, typeToCheck ))
425 SMDS_EdgePositionPtr epos = node->GetPosition();
428 theNodes.insert( theNodes.end(), make_pair( epos->GetUParameter(), node ));
433 TopoDS_Vertex v1, v2;
434 TopExp::Vertices(theEdge, v1, v2);
435 const SMDS_MeshNode* n1 = VertexNode( v1, eSubMesh, 0 );
436 const SMDS_MeshNode* n2 = VertexNode( v2, eSubMesh, 0 );
437 const SMDS_MeshNode* nEnd[2] = { nbNodes ? theNodes.begin()->second : 0,
438 nbNodes ? theNodes.rbegin()->second : 0 };
440 BRep_Tool::Range(theEdge, f, l);
441 if ( v1.Orientation() != TopAbs_FORWARD )
443 if ( n1 && n1 != nEnd[0] && n1 != nEnd[1] && ++nbNodes )
444 theNodes.insert( make_pair( f, n1 ));
445 if ( n2 && n2 != nEnd[0] && n2 != nEnd[1] && ++nbNodes )
446 theNodes.insert( make_pair( l, n2 ));
448 return (int)theNodes.size() == nbNodes;
451 //================================================================================
453 * \brief Returns the filter recognizing only compatible hypotheses
454 * \param ignoreAuxiliary - make filter ignore auxiliary hypotheses
455 * \retval SMESH_HypoFilter* - the filter that can be NULL
457 //================================================================================
459 const SMESH_HypoFilter*
460 SMESH_Algo::GetCompatibleHypoFilter(const bool ignoreAuxiliary) const
462 if ( !_compatibleHypothesis.empty() )
464 if ( !_compatibleAllHypFilter )
466 SMESH_HypoFilter* filter = new SMESH_HypoFilter();
467 filter->Init( filter->HasName( _compatibleHypothesis[0] ));
468 for ( size_t i = 1; i < _compatibleHypothesis.size(); ++i )
469 filter->Or( filter->HasName( _compatibleHypothesis[ i ] ));
471 SMESH_HypoFilter* filterNoAux = new SMESH_HypoFilter( filter );
472 filterNoAux->AndNot( filterNoAux->IsAuxiliary() );
474 // _compatibleNoAuxHypFilter will detele _compatibleAllHypFilter!!!
475 SMESH_Algo* me = const_cast< SMESH_Algo* >( this );
476 me->_compatibleAllHypFilter = filter;
477 me->_compatibleNoAuxHypFilter = filterNoAux;
479 return ignoreAuxiliary ? _compatibleNoAuxHypFilter : _compatibleAllHypFilter;
484 //================================================================================
486 * \brief Return continuity of two edges
487 * \param E1 - the 1st edge
488 * \param E2 - the 2nd edge
489 * \retval GeomAbs_Shape - regularity at the junction between E1 and E2
491 //================================================================================
493 GeomAbs_Shape SMESH_Algo::Continuity(const TopoDS_Edge& theE1,
494 const TopoDS_Edge& theE2)
496 // avoid pb with internal edges
497 TopoDS_Edge E1 = theE1, E2 = theE2;
498 if (E1.Orientation() > TopAbs_REVERSED) // INTERNAL
499 E1.Orientation( TopAbs_FORWARD );
500 if (E2.Orientation() > TopAbs_REVERSED) // INTERNAL
501 E2.Orientation( TopAbs_FORWARD );
503 TopoDS_Vertex V, VV1[2], VV2[2];
504 TopExp::Vertices( E1, VV1[0], VV1[1], true );
505 TopExp::Vertices( E2, VV2[0], VV2[1], true );
506 if ( VV1[1].IsSame( VV2[0] )) { V = VV1[1]; }
507 else if ( VV1[0].IsSame( VV2[1] )) { V = VV1[0]; }
508 else if ( VV1[1].IsSame( VV2[1] )) { V = VV1[1]; E1.Reverse(); }
509 else if ( VV1[0].IsSame( VV2[0] )) { V = VV1[0]; E1.Reverse(); }
510 else { return GeomAbs_C0; }
512 Standard_Real u1 = BRep_Tool::Parameter( V, E1 );
513 Standard_Real u2 = BRep_Tool::Parameter( V, E2 );
514 BRepAdaptor_Curve C1( E1 ), C2( E2 );
515 Standard_Real tol = BRep_Tool::Tolerance( V );
516 Standard_Real angTol = 2e-3;
519 return BRepLProp::Continuity(C1, C2, u1, u2, tol, angTol);
521 catch (Standard_Failure) {
526 //================================================================================
528 * \brief Return true if an edge can be considered straight
530 //================================================================================
532 bool SMESH_Algo::IsStraight( const TopoDS_Edge & E,
533 const bool degenResult)
537 if ( BRep_Tool::Curve( E, f, l ).IsNull())
540 BRepAdaptor_Curve curve( E );
541 switch( curve.GetType() )
546 case GeomAbs_Ellipse:
547 case GeomAbs_Hyperbola:
548 case GeomAbs_Parabola:
550 // case GeomAbs_BezierCurve:
551 // case GeomAbs_BSplineCurve:
552 // case GeomAbs_OtherCurve:
556 // evaluate how far from a straight line connecting the curve ends
557 // stand internal points of the curve
558 double f = curve.FirstParameter();
559 double l = curve.LastParameter();
560 gp_Pnt pf = curve.Value( f );
561 gp_Pnt pl = curve.Value( l );
562 gp_Vec lineVec( pf, pl );
563 double lineLen2 = lineVec.SquareMagnitude();
564 if ( lineLen2 < std::numeric_limits< double >::min() )
565 return false; // E seems closed
567 double edgeTol = 10 * curve.Tolerance();
568 double lenTol2 = lineLen2 * 1e-4;
569 double tol2 = Min( edgeTol * edgeTol, lenTol2 );
571 const double nbSamples = 7;
572 for ( int i = 0; i < nbSamples; ++i )
574 double r = ( i + 1 ) / nbSamples;
575 gp_Pnt pi = curve.Value( f * r + l * ( 1 - r ));
577 double h2 = lineVec.Crossed( vi ).SquareMagnitude() / lineLen2;
584 //================================================================================
586 * \brief Return true if an edge has no 3D curve
588 //================================================================================
590 bool SMESH_Algo::isDegenerated( const TopoDS_Edge & E, const bool checkLength )
593 return EdgeLength( E ) == 0;
596 Handle(Geom_Curve) C = BRep_Tool::Curve( E, loc, f,l );
600 //================================================================================
602 * \brief Return the node built on a vertex
603 * \param V - the vertex
604 * \param meshDS - mesh
605 * \retval const SMDS_MeshNode* - found node or NULL
606 * \sa SMESH_MesherHelper::GetSubShapeByNode( const SMDS_MeshNode*, SMESHDS_Mesh* )
608 //================================================================================
610 const SMDS_MeshNode* SMESH_Algo::VertexNode(const TopoDS_Vertex& V,
611 const SMESHDS_Mesh* meshDS)
613 if ( SMESHDS_SubMesh* sm = meshDS->MeshElements(V) ) {
614 SMDS_NodeIteratorPtr nIt= sm->GetNodes();
621 //=======================================================================
623 * \brief Return the node built on a vertex.
624 * A node moved to other geometry by MergeNodes() is also returned.
625 * \param V - the vertex
627 * \retval const SMDS_MeshNode* - found node or NULL
629 //=======================================================================
631 const SMDS_MeshNode* SMESH_Algo::VertexNode(const TopoDS_Vertex& V,
632 const SMESH_Mesh* mesh)
634 const SMDS_MeshNode* node = VertexNode( V, mesh->GetMeshDS() );
636 if ( !node && mesh->HasModificationsToDiscard() )
638 PShapeIteratorPtr edgeIt = SMESH_MesherHelper::GetAncestors( V, *mesh, TopAbs_EDGE );
639 while ( const TopoDS_Shape* edge = edgeIt->next() )
640 if ( SMESHDS_SubMesh* edgeSM = mesh->GetMeshDS()->MeshElements( *edge ))
641 if ( edgeSM->NbElements() > 0 )
642 return VertexNode( V, edgeSM, mesh, /*checkV=*/false );
647 //=======================================================================
649 * \brief Return the node built on a vertex.
650 * A node moved to other geometry by MergeNodes() is also returned.
651 * \param V - the vertex
652 * \param edgeSM - sub-mesh of a meshed EDGE sharing the vertex
653 * \param checkV - if \c true, presence of a node on the vertex is checked
654 * \retval const SMDS_MeshNode* - found node or NULL
656 //=======================================================================
658 const SMDS_MeshNode* SMESH_Algo::VertexNode(const TopoDS_Vertex& V,
659 const SMESHDS_SubMesh* edgeSM,
660 const SMESH_Mesh* mesh,
663 const SMDS_MeshNode* node = checkV ? VertexNode( V, edgeSM->GetParent() ) : 0;
665 if ( !node && edgeSM )
667 // find nodes not shared by mesh segments
668 typedef set< const SMDS_MeshNode* > TNodeSet;
669 typedef map< const SMDS_MeshNode*, const SMDS_MeshNode* > TNodeMap;
670 TNodeMap notSharedNodes;
671 TNodeSet otherShapeNodes;
672 vector< const SMDS_MeshNode* > segNodes(3);
673 SMDS_ElemIteratorPtr segIt = edgeSM->GetElements();
674 while ( segIt->more() )
676 const SMDS_MeshElement* seg = segIt->next();
677 if ( seg->GetType() != SMDSAbs_Edge )
679 segNodes.assign( seg->begin_nodes(), seg->end_nodes() );
680 for ( int i = 0; i < 2; ++i )
682 const SMDS_MeshNode* n1 = segNodes[i];
683 const SMDS_MeshNode* n2 = segNodes[1-i];
684 pair<TNodeMap::iterator, bool> it2new = notSharedNodes.insert( make_pair( n1, n2 ));
685 if ( !it2new.second ) // n encounters twice
686 notSharedNodes.erase( it2new.first );
687 if ( n1->getshapeId() != edgeSM->GetID() )
688 otherShapeNodes.insert( n1 );
691 if ( otherShapeNodes.size() == 1 && notSharedNodes.empty() ) // a closed EDGE
692 return *otherShapeNodes.begin();
694 if ( notSharedNodes.size() == 2 ) // two end nodes found
696 SMESHDS_Mesh* meshDS = edgeSM->GetParent();
697 const TopoDS_Shape& E = meshDS->IndexToShape( edgeSM->GetID() );
698 if ( E.IsNull() || E.ShapeType() != TopAbs_EDGE )
700 const SMDS_MeshNode* n1 = notSharedNodes.begin ()->first;
701 const SMDS_MeshNode* n2 = notSharedNodes.rbegin()->first;
702 TopoDS_Shape S1 = SMESH_MesherHelper::GetSubShapeByNode( n1, meshDS );
703 if ( S1.ShapeType() == TopAbs_VERTEX && SMESH_MesherHelper::IsSubShape( S1, E ))
705 TopoDS_Shape S2 = SMESH_MesherHelper::GetSubShapeByNode( n2, meshDS );
706 if ( S2.ShapeType() == TopAbs_VERTEX && SMESH_MesherHelper::IsSubShape( S2, E ))
708 if ( edgeSM->NbElements() <= 2 || !mesh ) // one-two segments
710 gp_Pnt pV = BRep_Tool::Pnt( V );
711 double dist1 = pV.SquareDistance( SMESH_TNodeXYZ( n1 ));
712 double dist2 = pV.SquareDistance( SMESH_TNodeXYZ( n2 ));
713 return dist1 < dist2 ? n1 : n2;
717 SMESH_MesherHelper helper( const_cast<SMESH_Mesh&>( *mesh ));
718 const SMDS_MeshNode* n1i = notSharedNodes.begin ()->second;
719 const SMDS_MeshNode* n2i = notSharedNodes.rbegin()->second;
720 const TopoDS_Edge& edge = TopoDS::Edge( E );
722 double pos1 = helper.GetNodeU( edge, n1i, n2i, &posOK );
723 double pos2 = helper.GetNodeU( edge, n2i, n1i, &posOK );
724 double posV = BRep_Tool::Parameter( V, edge );
725 if ( Abs( pos1 - posV ) < Abs( pos2 - posV )) return n1;
733 //=======================================================================
734 //function : GetMeshError
735 //purpose : Finds topological errors of a sub-mesh
736 //WARNING : 1D check is NOT implemented so far
737 //=======================================================================
739 SMESH_Algo::EMeshError SMESH_Algo::GetMeshError(SMESH_subMesh* subMesh)
741 EMeshError err = MEr_OK;
743 SMESHDS_SubMesh* smDS = subMesh->GetSubMeshDS();
747 switch ( subMesh->GetSubShape().ShapeType() )
749 case TopAbs_FACE: { // ====================== 2D =====================
751 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
755 // We check that only links on EDGEs encounter once, the rest links, twice
756 set< SMESH_TLink > links;
757 while ( fIt->more() )
759 const SMDS_MeshElement* f = fIt->next();
760 int nbNodes = f->NbCornerNodes(); // ignore medium nodes
761 for ( int i = 0; i < nbNodes; ++i )
763 const SMDS_MeshNode* n1 = f->GetNode( i );
764 const SMDS_MeshNode* n2 = f->GetNode(( i+1 ) % nbNodes);
765 std::pair< set< SMESH_TLink >::iterator, bool > it_added =
766 links.insert( SMESH_TLink( n1, n2 ));
767 if ( !it_added.second )
768 // As we do NOT(!) check if mesh is manifold, we believe that a link can
769 // encounter once or twice only (not three times), we erase a link as soon
770 // as it encounters twice to speed up search in the <links> map.
771 links.erase( it_added.first );
774 // the links remaining in the <links> should all be on EDGE
775 set< SMESH_TLink >::iterator linkIt = links.begin();
776 for ( ; linkIt != links.end(); ++linkIt )
778 const SMESH_TLink& link = *linkIt;
779 if ( link.node1()->GetPosition()->GetTypeOfPosition() > SMDS_TOP_EDGE ||
780 link.node2()->GetPosition()->GetTypeOfPosition() > SMDS_TOP_EDGE )
783 // TODO: to check orientation
786 case TopAbs_SOLID: { // ====================== 3D =====================
788 SMDS_ElemIteratorPtr vIt = smDS->GetElements();
792 SMDS_VolumeTool vTool;
793 while ( !vIt->more() )
795 if (!vTool.Set( vIt->next() ))
798 for ( int iF = 0; iF < vTool.NbFaces(); ++iF )
799 if ( vTool.IsFreeFace( iF ))
801 int nbN = vTool.NbFaceNodes( iF );
802 const SMDS_MeshNode** nodes = vTool.GetFaceNodes( iF );
803 for ( int i = 0; i < nbN; ++i )
804 if ( nodes[i]->GetPosition()->GetTypeOfPosition() > SMDS_TOP_FACE )
815 //================================================================================
817 * \brief Sets event listener to submeshes if necessary
818 * \param subMesh - submesh where algo is set
820 * After being set, event listener is notified on each event of a submesh.
821 * By default non listener is set
823 //================================================================================
825 void SMESH_Algo::SetEventListener(SMESH_subMesh* /*subMesh*/)
829 //================================================================================
831 * \brief Allow algo to do something after persistent restoration
832 * \param subMesh - restored submesh
834 * This method is called only if a submesh has HYP_OK algo_state.
836 //================================================================================
838 void SMESH_Algo::SubmeshRestored(SMESH_subMesh* /*subMesh*/)
842 //================================================================================
844 * \brief Computes mesh without geometry
845 * \param aMesh - the mesh
846 * \param aHelper - helper that must be used for adding elements to \aaMesh
847 * \retval bool - is a success
849 //================================================================================
851 bool SMESH_Algo::Compute(SMESH_Mesh & /*aMesh*/, SMESH_MesherHelper* /*aHelper*/)
853 return error( COMPERR_BAD_INPUT_MESH, "Mesh built on shape expected");
856 //=======================================================================
857 //function : IsApplicableToShape
858 //purpose : Return true if the algorithm can mesh a given shape
859 //=======================================================================
861 bool SMESH_Algo::IsApplicableToShape(const TopoDS_Shape & shape, bool toCheckAll) const
866 //=======================================================================
867 //function : CancelCompute
868 //purpose : Sets _computeCanceled to true. It's usage depends on
869 // * implementation of a particular mesher.
870 //=======================================================================
872 void SMESH_Algo::CancelCompute()
874 _computeCanceled = true;
875 _error = COMPERR_CANCELED;
878 //================================================================================
880 * If possible, returns progress of computation [0.,1.]
882 //================================================================================
884 double SMESH_Algo::GetProgress() const
889 //================================================================================
891 * \brief store error and comment and then return ( error == COMPERR_OK )
893 //================================================================================
895 bool SMESH_Algo::error(int error, const SMESH_Comment& comment)
899 return ( error == COMPERR_OK );
902 //================================================================================
904 * \brief store error and return ( error == COMPERR_OK )
906 //================================================================================
908 bool SMESH_Algo::error(SMESH_ComputeErrorPtr error)
911 _error = error->myName;
912 _comment = error->myComment;
913 if ( error->HasBadElems() )
915 SMESH_BadInputElements* badElems = static_cast<SMESH_BadInputElements*>( error.get() );
916 _badInputElements = badElems->GetElements();
917 _mesh = badElems->GetMesh();
919 return error->IsOK();
924 //================================================================================
926 * \brief return compute error
928 //================================================================================
930 SMESH_ComputeErrorPtr SMESH_Algo::GetComputeError() const
932 if ( !_badInputElements.empty() && _mesh )
934 SMESH_BadInputElements* err = new SMESH_BadInputElements( _mesh, _error, _comment, this );
935 // hope this method is called by only SMESH_subMesh after this->Compute()
936 err->myBadElements.splice( err->myBadElements.end(),
937 (list<const SMDS_MeshElement*>&) _badInputElements );
938 return SMESH_ComputeErrorPtr( err );
940 return SMESH_ComputeError::New( _error, _comment, this );
943 //================================================================================
945 * \brief initialize compute error before call of Compute()
947 //================================================================================
949 void SMESH_Algo::InitComputeError()
953 list<const SMDS_MeshElement*>::iterator elem = _badInputElements.begin();
954 for ( ; elem != _badInputElements.end(); ++elem )
955 if ( (*elem)->GetID() < 1 )
957 _badInputElements.clear();
960 _computeCanceled = false;
965 //================================================================================
967 * \brief Return compute progress by nb of calls of this method
969 //================================================================================
971 double SMESH_Algo::GetProgressByTic() const
974 for ( size_t i = 0; i < _smToCompute.size(); ++i )
975 computeCost += _smToCompute[i]->GetComputeCost();
977 const_cast<SMESH_Algo*>( this )->_progressTic++;
979 double x = 5 * _progressTic;
980 x = ( x < computeCost ) ? ( x / computeCost ) : 1.;
981 return 0.9 * sin( x * M_PI / 2 );
984 //================================================================================
986 * \brief store a bad input element preventing computation,
987 * which may be a temporary one i.e. not residing the mesh,
988 * then it will be deleted by InitComputeError()
990 //================================================================================
992 void SMESH_Algo::addBadInputElement(const SMDS_MeshElement* elem)
995 _badInputElements.push_back( elem );
998 //=======================================================================
999 //function : addBadInputElements
1000 //purpose : store a bad input elements or nodes preventing computation
1001 //=======================================================================
1003 void SMESH_Algo::addBadInputElements(const SMESHDS_SubMesh* sm,
1004 const bool addNodes)
1010 SMDS_NodeIteratorPtr nIt = sm->GetNodes();
1011 while ( nIt->more() ) addBadInputElement( nIt->next() );
1015 SMDS_ElemIteratorPtr eIt = sm->GetElements();
1016 while ( eIt->more() ) addBadInputElement( eIt->next() );
1021 //=============================================================================
1025 //=============================================================================
1027 // int SMESH_Algo::NumberOfWires(const TopoDS_Shape& S)
1030 // for (TopExp_Explorer exp(S,TopAbs_WIRE); exp.More(); exp.Next())
1035 //=============================================================================
1039 //=============================================================================
1041 int SMESH_Algo::NumberOfPoints(SMESH_Mesh& aMesh, const TopoDS_Wire& W)
1044 for (TopExp_Explorer exp(W,TopAbs_EDGE); exp.More(); exp.Next()) {
1045 const TopoDS_Edge& E = TopoDS::Edge(exp.Current());
1046 int nb = aMesh.GetSubMesh(E)->GetSubMeshDS()->NbNodes();
1049 nbPoints += nb + 1; // internal points plus 1 vertex of 2 (last point ?)
1055 //================================================================================
1057 * Method in which an algorithm generating a structured mesh
1058 * fixes positions of in-face nodes after there movement
1059 * due to insertion of viscous layers.
1061 //================================================================================
1063 bool SMESH_2D_Algo::FixInternalNodes(const SMESH_ProxyMesh& mesh,
1064 const TopoDS_Face& face)
1066 const SMESHDS_SubMesh* smDS = mesh.GetSubMesh(face);
1067 if ( !smDS || smDS->NbElements() < 1 )
1070 SMESH_MesherHelper helper( *mesh.GetMesh() );
1072 // get all faces from a proxy sub-mesh
1073 typedef SMDS_StdIterator< const SMDS_MeshElement*, SMDS_ElemIteratorPtr > TIterator;
1074 TIDSortedElemSet allFaces( TIterator( smDS->GetElements() ), TIterator() );
1075 TIDSortedElemSet avoidSet, firstRowQuads;
1077 // indices of nodes to pass to a neighbour quad using SMESH_MeshAlgos::FindFaceInSet()
1080 // get two first rows of nodes by passing through the first row of faces
1081 vector< vector< const SMDS_MeshNode* > > nodeRows;
1082 int iRow1 = 0, iRow2 = 1;
1083 const SMDS_MeshElement* quad;
1085 // look for a corner quadrangle and it's corner node
1086 const SMDS_MeshElement* cornerQuad = 0;
1087 int cornerNodeInd = -1;
1088 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
1089 while ( !cornerQuad && fIt->more() )
1091 cornerQuad = fIt->next();
1092 if ( cornerQuad->NbCornerNodes() != 4 )
1094 SMDS_NodeIteratorPtr nIt = cornerQuad->nodeIterator();
1095 for ( int i = 0; i < 4; ++i )
1097 int nbInverseQuads = 0;
1098 SMDS_ElemIteratorPtr fIt = nIt->next()->GetInverseElementIterator(SMDSAbs_Face);
1099 while ( fIt->more() )
1100 nbInverseQuads += allFaces.count( fIt->next() );
1101 if ( nbInverseQuads == 1 )
1102 cornerNodeInd = i, i = 4;
1104 if ( cornerNodeInd < 0 )
1107 if ( !cornerQuad || cornerNodeInd < 0 )
1110 iN1 = helper.WrapIndex( cornerNodeInd + 1, 4 );
1111 iN2 = helper.WrapIndex( cornerNodeInd + 2, 4 );
1112 int iN3 = helper.WrapIndex( cornerNodeInd + 3, 4 );
1114 nodeRows[iRow1].push_back( cornerQuad->GetNode( cornerNodeInd ));
1115 nodeRows[iRow1].push_back( cornerQuad->GetNode( iN1 ));
1116 nodeRows[iRow2].push_back( cornerQuad->GetNode( iN3 ));
1117 nodeRows[iRow2].push_back( cornerQuad->GetNode( iN2 ));
1118 firstRowQuads.insert( cornerQuad );
1120 // pass through the rest quads in a face row
1125 avoidSet.insert( quad );
1126 if (( quad = SMESH_MeshAlgos::FindFaceInSet( nodeRows[iRow1].back(),
1127 nodeRows[iRow2].back(),
1128 allFaces, avoidSet, &iN1, &iN2)))
1130 nodeRows[iRow1].push_back( quad->GetNode( helper.WrapIndex( iN2 + 2, 4 )));
1131 nodeRows[iRow2].push_back( quad->GetNode( helper.WrapIndex( iN1 + 2, 4 )));
1132 if ( quad->NbCornerNodes() != 4 )
1136 if ( nodeRows[iRow1].size() < 3 )
1137 return true; // there is nothing to fix
1140 nodeRows.reserve( smDS->NbElements() / nodeRows[iRow1].size() );
1142 // get the rest node rows
1147 // get the first quad in the next face row
1148 if (( quad = SMESH_MeshAlgos::FindFaceInSet( nodeRows[iRow1][0],
1150 allFaces, /*avoid=*/firstRowQuads,
1153 if ( quad->NbCornerNodes() != 4 )
1155 nodeRows.resize( iRow2+1 );
1156 nodeRows[iRow2].push_back( quad->GetNode( helper.WrapIndex( iN2 + 2, 4 )));
1157 nodeRows[iRow2].push_back( quad->GetNode( helper.WrapIndex( iN1 + 2, 4 )));
1158 firstRowQuads.insert( quad );
1162 break; // no more rows
1165 // pass through the rest quads in a face row
1169 avoidSet.insert( quad );
1170 if (( quad = SMESH_MeshAlgos::FindFaceInSet( nodeRows[iRow1][ nodeRows[iRow2].size()-1 ],
1171 nodeRows[iRow2].back(),
1172 allFaces, avoidSet, &iN1, &iN2)))
1174 if ( quad->NbCornerNodes() != 4 )
1176 nodeRows[iRow2].push_back( quad->GetNode( helper.WrapIndex( iN1 + 2, 4 )));
1179 if ( nodeRows[iRow1].size() != nodeRows[iRow2].size() )
1182 if ( nodeRows.size() < 3 )
1183 return true; // there is nothing to fix
1185 // get params of the first (bottom) and last (top) node rows
1186 UVPtStructVec uvB( nodeRows[0].size() ), uvT( nodeRows[0].size() );
1187 for ( int isBot = 0; isBot < 2; ++isBot )
1189 UVPtStructVec & uvps = isBot ? uvB : uvT;
1190 vector< const SMDS_MeshNode* >& nodes = nodeRows[ isBot ? 0 : nodeRows.size()-1 ];
1191 for ( size_t i = 0; i < nodes.size(); ++i )
1193 uvps[i].node = nodes[i];
1194 gp_XY uv = helper.GetNodeUV( face, uvps[i].node );
1195 uvps[i].u = uv.Coord(1);
1196 uvps[i].v = uv.Coord(2);
1199 // calculate x (normalized param)
1200 for ( size_t i = 1; i < nodes.size(); ++i )
1201 uvps[i].x = uvps[i-1].x + SMESH_TNodeXYZ( uvps[i-1].node ).Distance( uvps[i].node );
1202 for ( size_t i = 1; i < nodes.size(); ++i )
1203 uvps[i].x /= uvps.back().x;
1206 // get params of the left and right node rows
1207 UVPtStructVec uvL( nodeRows.size() ), uvR( nodeRows.size() );
1208 for ( int isLeft = 0; isLeft < 2; ++isLeft )
1210 UVPtStructVec & uvps = isLeft ? uvL : uvR;
1211 const int iCol = isLeft ? 0 : nodeRows[0].size() - 1;
1212 for ( size_t i = 0; i < nodeRows.size(); ++i )
1214 uvps[i].node = nodeRows[i][iCol];
1215 gp_XY uv = helper.GetNodeUV( face, uvps[i].node );
1216 uvps[i].u = uv.Coord(1);
1217 uvps[i].v = uv.Coord(2);
1220 // calculate y (normalized param)
1221 for ( size_t i = 1; i < nodeRows.size(); ++i )
1222 uvps[i].y = uvps[i-1].y + SMESH_TNodeXYZ( uvps[i-1].node ).Distance( uvps[i].node );
1223 for ( size_t i = 1; i < nodeRows.size(); ++i )
1224 uvps[i].y /= uvps.back().y;
1227 // update node coordinates
1228 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
1229 Handle(Geom_Surface) S = BRep_Tool::Surface( face );
1230 gp_XY a0 ( uvB.front().u, uvB.front().v );
1231 gp_XY a1 ( uvB.back().u, uvB.back().v );
1232 gp_XY a2 ( uvT.back().u, uvT.back().v );
1233 gp_XY a3 ( uvT.front().u, uvT.front().v );
1234 for ( size_t iRow = 1; iRow < nodeRows.size()-1; ++iRow )
1236 gp_XY p1 ( uvR[ iRow ].u, uvR[ iRow ].v );
1237 gp_XY p3 ( uvL[ iRow ].u, uvL[ iRow ].v );
1238 const double y0 = uvL[ iRow ].y;
1239 const double y1 = uvR[ iRow ].y;
1240 for ( size_t iCol = 1; iCol < nodeRows[0].size()-1; ++iCol )
1242 gp_XY p0 ( uvB[ iCol ].u, uvB[ iCol ].v );
1243 gp_XY p2 ( uvT[ iCol ].u, uvT[ iCol ].v );
1244 const double x0 = uvB[ iCol ].x;
1245 const double x1 = uvT[ iCol ].x;
1246 double x = (x0 + y0 * (x1 - x0)) / (1 - (y1 - y0) * (x1 - x0));
1247 double y = y0 + x * (y1 - y0);
1248 gp_XY uv = helper.calcTFI( x, y, a0,a1,a2,a3, p0,p1,p2,p3 );
1249 gp_Pnt p = S->Value( uv.Coord(1), uv.Coord(2));
1250 const SMDS_MeshNode* n = nodeRows[iRow][iCol];
1251 meshDS->MoveNode( n, p.X(), p.Y(), p.Z() );
1252 if ( SMDS_FacePositionPtr pos = n->GetPosition() )
1253 pos->SetParameters( uv.Coord(1), uv.Coord(2) );
1259 //=======================================================================
1260 //function : IsApplicableToShape
1261 //purpose : Return true if the algorithm can mesh a given shape
1262 //=======================================================================
1264 bool SMESH_1D_Algo::IsApplicableToShape(const TopoDS_Shape & shape, bool toCheckAll) const
1266 return ( !shape.IsNull() && TopExp_Explorer( shape, TopAbs_EDGE ).More() );
1269 //=======================================================================
1270 //function : IsApplicableToShape
1271 //purpose : Return true if the algorithm can mesh a given shape
1272 //=======================================================================
1274 bool SMESH_2D_Algo::IsApplicableToShape(const TopoDS_Shape & shape, bool toCheckAll) const
1276 return ( !shape.IsNull() && TopExp_Explorer( shape, TopAbs_FACE ).More() );
1279 //=======================================================================
1280 //function : IsApplicableToShape
1281 //purpose : Return true if the algorithm can mesh a given shape
1282 //=======================================================================
1284 bool SMESH_3D_Algo::IsApplicableToShape(const TopoDS_Shape & shape, bool toCheckAll) const
1286 return ( !shape.IsNull() && TopExp_Explorer( shape, TopAbs_SOLID ).More() );