1 // Copyright (C) 2007-2013 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
22 // File : SMESH_MeshAlgos.hxx
23 // Created : Tue Apr 30 18:00:36 2013
24 // Author : Edward AGAPOV (eap)
26 // This file holds some low level algorithms extracted from SMESH_MeshEditor
27 // to make them accessible from Controls package
29 #include "SMESH_MeshAlgos.hxx"
31 #include "SMDS_LinearEdge.hxx"
32 #include "SMDS_VolumeTool.hxx"
33 #include "SMDS_Mesh.hxx"
34 #include "SMESH_OctreeNode.hxx"
36 #include <GC_MakeSegment.hxx>
37 #include <GeomAPI_ExtremaCurveCurve.hxx>
38 #include <Geom_Line.hxx>
39 #include <IntAna_IntConicQuad.hxx>
40 #include <IntAna_Quadric.hxx>
49 //=======================================================================
51 * \brief Implementation of search for the node closest to point
53 //=======================================================================
55 struct SMESH_NodeSearcherImpl: public SMESH_NodeSearcher
57 //---------------------------------------------------------------------
61 SMESH_NodeSearcherImpl( const SMDS_Mesh* theMesh )
63 myMesh = ( SMDS_Mesh* ) theMesh;
65 TIDSortedNodeSet nodes;
67 SMDS_NodeIteratorPtr nIt = theMesh->nodesIterator(/*idInceasingOrder=*/true);
69 nodes.insert( nodes.end(), nIt->next() );
71 myOctreeNode = new SMESH_OctreeNode(nodes) ;
73 // get max size of a leaf box
74 SMESH_OctreeNode* tree = myOctreeNode;
75 while ( !tree->isLeaf() )
77 SMESH_OctreeNodeIteratorPtr cIt = tree->GetChildrenIterator();
81 myHalfLeafSize = tree->maxSize() / 2.;
84 //---------------------------------------------------------------------
86 * \brief Move node and update myOctreeNode accordingly
88 void MoveNode( const SMDS_MeshNode* node, const gp_Pnt& toPnt )
90 myOctreeNode->UpdateByMoveNode( node, toPnt );
91 myMesh->MoveNode( node, toPnt.X(), toPnt.Y(), toPnt.Z() );
94 //---------------------------------------------------------------------
98 const SMDS_MeshNode* FindClosestTo( const gp_Pnt& thePnt )
100 map<double, const SMDS_MeshNode*> dist2Nodes;
101 myOctreeNode->NodesAround( thePnt.Coord(), dist2Nodes, myHalfLeafSize );
102 if ( !dist2Nodes.empty() )
103 return dist2Nodes.begin()->second;
104 list<const SMDS_MeshNode*> nodes;
105 //myOctreeNode->NodesAround( &tgtNode, &nodes, myHalfLeafSize );
107 double minSqDist = DBL_MAX;
108 if ( nodes.empty() ) // get all nodes of OctreeNode's closest to thePnt
110 // sort leafs by their distance from thePnt
111 typedef map< double, SMESH_OctreeNode* > TDistTreeMap;
112 TDistTreeMap treeMap;
113 list< SMESH_OctreeNode* > treeList;
114 list< SMESH_OctreeNode* >::iterator trIt;
115 treeList.push_back( myOctreeNode );
117 gp_XYZ pointNode( thePnt.X(), thePnt.Y(), thePnt.Z() );
118 bool pointInside = myOctreeNode->isInside( pointNode, myHalfLeafSize );
119 for ( trIt = treeList.begin(); trIt != treeList.end(); ++trIt)
121 SMESH_OctreeNode* tree = *trIt;
122 if ( !tree->isLeaf() ) // put children to the queue
124 if ( pointInside && !tree->isInside( pointNode, myHalfLeafSize )) continue;
125 SMESH_OctreeNodeIteratorPtr cIt = tree->GetChildrenIterator();
126 while ( cIt->more() )
127 treeList.push_back( cIt->next() );
129 else if ( tree->NbNodes() ) // put a tree to the treeMap
131 const Bnd_B3d& box = *tree->getBox();
132 double sqDist = thePnt.SquareDistance( 0.5 * ( box.CornerMin() + box.CornerMax() ));
133 pair<TDistTreeMap::iterator,bool> it_in = treeMap.insert( make_pair( sqDist, tree ));
134 if ( !it_in.second ) // not unique distance to box center
135 treeMap.insert( it_in.first, make_pair( sqDist + 1e-13*treeMap.size(), tree ));
138 // find distance after which there is no sense to check tree's
139 double sqLimit = DBL_MAX;
140 TDistTreeMap::iterator sqDist_tree = treeMap.begin();
141 if ( treeMap.size() > 5 ) {
142 SMESH_OctreeNode* closestTree = sqDist_tree->second;
143 const Bnd_B3d& box = *closestTree->getBox();
144 double limit = sqrt( sqDist_tree->first ) + sqrt ( box.SquareExtent() );
145 sqLimit = limit * limit;
147 // get all nodes from trees
148 for ( ; sqDist_tree != treeMap.end(); ++sqDist_tree) {
149 if ( sqDist_tree->first > sqLimit )
151 SMESH_OctreeNode* tree = sqDist_tree->second;
152 tree->NodesAround( tree->GetNodeIterator()->next(), &nodes );
155 // find closest among nodes
157 const SMDS_MeshNode* closestNode = 0;
158 list<const SMDS_MeshNode*>::iterator nIt = nodes.begin();
159 for ( ; nIt != nodes.end(); ++nIt ) {
160 double sqDist = thePnt.SquareDistance( SMESH_TNodeXYZ( *nIt ) );
161 if ( minSqDist > sqDist ) {
169 //---------------------------------------------------------------------
173 ~SMESH_NodeSearcherImpl() { delete myOctreeNode; }
175 //---------------------------------------------------------------------
177 * \brief Return the node tree
179 const SMESH_OctreeNode* getTree() const { return myOctreeNode; }
182 SMESH_OctreeNode* myOctreeNode;
184 double myHalfLeafSize; // max size of a leaf box
187 // ========================================================================
188 namespace // Utils used in SMESH_ElementSearcherImpl::FindElementsByPoint()
190 const int MaxNbElemsInLeaf = 10; // maximal number of elements in a leaf of tree
191 const int MaxLevel = 7; // maximal tree height -> nb terminal boxes: 8^7 = 2097152
192 const double NodeRadius = 1e-9; // to enlarge bnd box of element
194 //=======================================================================
196 * \brief Octal tree of bounding boxes of elements
198 //=======================================================================
200 class ElementBndBoxTree : public SMESH_Octree
204 ElementBndBoxTree(const SMDS_Mesh& mesh,
205 SMDSAbs_ElementType elemType,
206 SMDS_ElemIteratorPtr theElemIt = SMDS_ElemIteratorPtr(),
207 double tolerance = NodeRadius );
208 void getElementsNearPoint( const gp_Pnt& point, TIDSortedElemSet& foundElems );
209 void getElementsNearLine ( const gp_Ax1& line, TIDSortedElemSet& foundElems);
210 void getElementsInSphere ( const gp_XYZ& center,
211 const double radius, TIDSortedElemSet& foundElems);
212 size_t getSize() { return std::max( _size, _elements.size() ); }
213 virtual ~ElementBndBoxTree();
216 ElementBndBoxTree():_size(0) {}
217 SMESH_Octree* newChild() const { return new ElementBndBoxTree; }
218 void buildChildrenData();
219 Bnd_B3d* buildRootBox();
221 //!< Bounding box of element
222 struct ElementBox : public Bnd_B3d
224 const SMDS_MeshElement* _element;
225 int _refCount; // an ElementBox can be included in several tree branches
226 ElementBox(const SMDS_MeshElement* elem, double tolerance);
228 vector< ElementBox* > _elements;
232 //================================================================================
234 * \brief ElementBndBoxTree creation
236 //================================================================================
238 ElementBndBoxTree::ElementBndBoxTree(const SMDS_Mesh& mesh, SMDSAbs_ElementType elemType, SMDS_ElemIteratorPtr theElemIt, double tolerance)
239 :SMESH_Octree( new SMESH_TreeLimit( MaxLevel, /*minSize=*/0. ))
241 int nbElems = mesh.GetMeshInfo().NbElements( elemType );
242 _elements.reserve( nbElems );
244 SMDS_ElemIteratorPtr elemIt = theElemIt ? theElemIt : mesh.elementsIterator( elemType );
245 while ( elemIt->more() )
246 _elements.push_back( new ElementBox( elemIt->next(),tolerance ));
251 //================================================================================
255 //================================================================================
257 ElementBndBoxTree::~ElementBndBoxTree()
259 for ( int i = 0; i < _elements.size(); ++i )
260 if ( --_elements[i]->_refCount <= 0 )
264 //================================================================================
266 * \brief Return the maximal box
268 //================================================================================
270 Bnd_B3d* ElementBndBoxTree::buildRootBox()
272 Bnd_B3d* box = new Bnd_B3d;
273 for ( int i = 0; i < _elements.size(); ++i )
274 box->Add( *_elements[i] );
278 //================================================================================
280 * \brief Redistrubute element boxes among children
282 //================================================================================
284 void ElementBndBoxTree::buildChildrenData()
286 for ( int i = 0; i < _elements.size(); ++i )
288 for (int j = 0; j < 8; j++)
290 if ( !_elements[i]->IsOut( *myChildren[j]->getBox() ))
292 _elements[i]->_refCount++;
293 ((ElementBndBoxTree*)myChildren[j])->_elements.push_back( _elements[i]);
296 _elements[i]->_refCount--;
298 _size = _elements.size();
299 SMESHUtils::FreeVector( _elements ); // = _elements.clear() + free memory
301 for (int j = 0; j < 8; j++)
303 ElementBndBoxTree* child = static_cast<ElementBndBoxTree*>( myChildren[j]);
304 if ( child->_elements.size() <= MaxNbElemsInLeaf )
305 child->myIsLeaf = true;
307 if ( child->_elements.capacity() - child->_elements.size() > 1000 )
308 SMESHUtils::CompactVector( child->_elements );
312 //================================================================================
314 * \brief Return elements which can include the point
316 //================================================================================
318 void ElementBndBoxTree::getElementsNearPoint( const gp_Pnt& point,
319 TIDSortedElemSet& foundElems)
321 if ( getBox()->IsOut( point.XYZ() ))
326 for ( int i = 0; i < _elements.size(); ++i )
327 if ( !_elements[i]->IsOut( point.XYZ() ))
328 foundElems.insert( _elements[i]->_element );
332 for (int i = 0; i < 8; i++)
333 ((ElementBndBoxTree*) myChildren[i])->getElementsNearPoint( point, foundElems );
337 //================================================================================
339 * \brief Return elements which can be intersected by the line
341 //================================================================================
343 void ElementBndBoxTree::getElementsNearLine( const gp_Ax1& line,
344 TIDSortedElemSet& foundElems)
346 if ( getBox()->IsOut( line ))
351 for ( int i = 0; i < _elements.size(); ++i )
352 if ( !_elements[i]->IsOut( line ))
353 foundElems.insert( _elements[i]->_element );
357 for (int i = 0; i < 8; i++)
358 ((ElementBndBoxTree*) myChildren[i])->getElementsNearLine( line, foundElems );
362 //================================================================================
364 * \brief Return elements from leaves intersecting the sphere
366 //================================================================================
368 void ElementBndBoxTree::getElementsInSphere ( const gp_XYZ& center,
370 TIDSortedElemSet& foundElems)
372 if ( getBox()->IsOut( center, radius ))
377 for ( int i = 0; i < _elements.size(); ++i )
378 if ( !_elements[i]->IsOut( center, radius ))
379 foundElems.insert( _elements[i]->_element );
383 for (int i = 0; i < 8; i++)
384 ((ElementBndBoxTree*) myChildren[i])->getElementsInSphere( center, radius, foundElems );
388 //================================================================================
390 * \brief Construct the element box
392 //================================================================================
394 ElementBndBoxTree::ElementBox::ElementBox(const SMDS_MeshElement* elem, double tolerance)
398 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
399 while ( nIt->more() )
400 Add( SMESH_TNodeXYZ( nIt->next() ));
401 Enlarge( tolerance );
406 //=======================================================================
408 * \brief Implementation of search for the elements by point and
409 * of classification of point in 2D mesh
411 //=======================================================================
413 SMESH_ElementSearcher::~SMESH_ElementSearcher()
417 struct SMESH_ElementSearcherImpl: public SMESH_ElementSearcher
420 SMDS_ElemIteratorPtr _meshPartIt;
421 ElementBndBoxTree* _ebbTree;
422 SMESH_NodeSearcherImpl* _nodeSearcher;
423 SMDSAbs_ElementType _elementType;
425 bool _outerFacesFound;
426 set<const SMDS_MeshElement*> _outerFaces; // empty means "no internal faces at all"
428 SMESH_ElementSearcherImpl( SMDS_Mesh& mesh, SMDS_ElemIteratorPtr elemIt=SMDS_ElemIteratorPtr())
429 : _mesh(&mesh),_meshPartIt(elemIt),_ebbTree(0),_nodeSearcher(0),_tolerance(-1),_outerFacesFound(false) {}
430 virtual ~SMESH_ElementSearcherImpl()
432 if ( _ebbTree ) delete _ebbTree; _ebbTree = 0;
433 if ( _nodeSearcher ) delete _nodeSearcher; _nodeSearcher = 0;
435 virtual int FindElementsByPoint(const gp_Pnt& point,
436 SMDSAbs_ElementType type,
437 vector< const SMDS_MeshElement* >& foundElements);
438 virtual TopAbs_State GetPointState(const gp_Pnt& point);
439 virtual const SMDS_MeshElement* FindClosestTo( const gp_Pnt& point,
440 SMDSAbs_ElementType type );
442 void GetElementsNearLine( const gp_Ax1& line,
443 SMDSAbs_ElementType type,
444 vector< const SMDS_MeshElement* >& foundElems);
445 double getTolerance();
446 bool getIntersParamOnLine(const gp_Lin& line, const SMDS_MeshElement* face,
447 const double tolerance, double & param);
448 void findOuterBoundary(const SMDS_MeshElement* anyOuterFace);
449 bool isOuterBoundary(const SMDS_MeshElement* face) const
451 return _outerFaces.empty() || _outerFaces.count(face);
453 struct TInters //!< data of intersection of the line and the mesh face (used in GetPointState())
455 const SMDS_MeshElement* _face;
457 bool _coincides; //!< the line lays in face plane
458 TInters(const SMDS_MeshElement* face, const gp_Vec& faceNorm, bool coinc=false)
459 : _face(face), _faceNorm( faceNorm ), _coincides( coinc ) {}
461 struct TFaceLink //!< link and faces sharing it (used in findOuterBoundary())
464 TIDSortedElemSet _faces;
465 TFaceLink( const SMDS_MeshNode* n1, const SMDS_MeshNode* n2, const SMDS_MeshElement* face)
466 : _link( n1, n2 ), _faces( &face, &face + 1) {}
470 ostream& operator<< (ostream& out, const SMESH_ElementSearcherImpl::TInters& i)
472 return out << "TInters(face=" << ( i._face ? i._face->GetID() : 0)
473 << ", _coincides="<<i._coincides << ")";
476 //=======================================================================
478 * \brief define tolerance for search
480 //=======================================================================
482 double SMESH_ElementSearcherImpl::getTolerance()
484 if ( _tolerance < 0 )
486 const SMDS_MeshInfo& meshInfo = _mesh->GetMeshInfo();
489 if ( _nodeSearcher && meshInfo.NbNodes() > 1 )
491 double boxSize = _nodeSearcher->getTree()->maxSize();
492 _tolerance = 1e-8 * boxSize/* / meshInfo.NbNodes()*/;
494 else if ( _ebbTree && meshInfo.NbElements() > 0 )
496 double boxSize = _ebbTree->maxSize();
497 _tolerance = 1e-8 * boxSize/* / meshInfo.NbElements()*/;
499 if ( _tolerance == 0 )
501 // define tolerance by size of a most complex element
502 int complexType = SMDSAbs_Volume;
503 while ( complexType > SMDSAbs_All &&
504 meshInfo.NbElements( SMDSAbs_ElementType( complexType )) < 1 )
506 if ( complexType == SMDSAbs_All ) return 0; // empty mesh
508 if ( complexType == int( SMDSAbs_Node ))
510 SMDS_NodeIteratorPtr nodeIt = _mesh->nodesIterator();
512 if ( meshInfo.NbNodes() > 2 )
513 elemSize = SMESH_TNodeXYZ( nodeIt->next() ).Distance( nodeIt->next() );
517 SMDS_ElemIteratorPtr elemIt =
518 _mesh->elementsIterator( SMDSAbs_ElementType( complexType ));
519 const SMDS_MeshElement* elem = elemIt->next();
520 SMDS_ElemIteratorPtr nodeIt = elem->nodesIterator();
521 SMESH_TNodeXYZ n1( nodeIt->next() );
523 while ( nodeIt->more() )
525 double dist = n1.Distance( static_cast<const SMDS_MeshNode*>( nodeIt->next() ));
526 elemSize = max( dist, elemSize );
529 _tolerance = 1e-4 * elemSize;
535 //================================================================================
537 * \brief Find intersection of the line and an edge of face and return parameter on line
539 //================================================================================
541 bool SMESH_ElementSearcherImpl::getIntersParamOnLine(const gp_Lin& line,
542 const SMDS_MeshElement* face,
549 GeomAPI_ExtremaCurveCurve anExtCC;
550 Handle(Geom_Curve) lineCurve = new Geom_Line( line );
552 int nbNodes = face->IsQuadratic() ? face->NbNodes()/2 : face->NbNodes();
553 for ( int i = 0; i < nbNodes && nbInts < 2; ++i )
555 GC_MakeSegment edge( SMESH_TNodeXYZ( face->GetNode( i )),
556 SMESH_TNodeXYZ( face->GetNode( (i+1)%nbNodes) ));
557 anExtCC.Init( lineCurve, edge);
558 if ( anExtCC.NbExtrema() > 0 && anExtCC.LowerDistance() <= tol)
560 Quantity_Parameter pl, pe;
561 anExtCC.LowerDistanceParameters( pl, pe );
567 if ( nbInts > 0 ) param /= nbInts;
570 //================================================================================
572 * \brief Find all faces belonging to the outer boundary of mesh
574 //================================================================================
576 void SMESH_ElementSearcherImpl::findOuterBoundary(const SMDS_MeshElement* outerFace)
578 if ( _outerFacesFound ) return;
580 // Collect all outer faces by passing from one outer face to another via their links
581 // and BTW find out if there are internal faces at all.
583 // checked links and links where outer boundary meets internal one
584 set< SMESH_TLink > visitedLinks, seamLinks;
586 // links to treat with already visited faces sharing them
587 list < TFaceLink > startLinks;
589 // load startLinks with the first outerFace
590 startLinks.push_back( TFaceLink( outerFace->GetNode(0), outerFace->GetNode(1), outerFace));
591 _outerFaces.insert( outerFace );
593 TIDSortedElemSet emptySet;
594 while ( !startLinks.empty() )
596 const SMESH_TLink& link = startLinks.front()._link;
597 TIDSortedElemSet& faces = startLinks.front()._faces;
599 outerFace = *faces.begin();
600 // find other faces sharing the link
601 const SMDS_MeshElement* f;
602 while (( f = SMESH_MeshAlgos::FindFaceInSet(link.node1(), link.node2(), emptySet, faces )))
605 // select another outer face among the found
606 const SMDS_MeshElement* outerFace2 = 0;
607 if ( faces.size() == 2 )
609 outerFace2 = (outerFace == *faces.begin() ? *faces.rbegin() : *faces.begin());
611 else if ( faces.size() > 2 )
613 seamLinks.insert( link );
615 // link direction within the outerFace
616 gp_Vec n1n2( SMESH_TNodeXYZ( link.node1()),
617 SMESH_TNodeXYZ( link.node2()));
618 int i1 = outerFace->GetNodeIndex( link.node1() );
619 int i2 = outerFace->GetNodeIndex( link.node2() );
620 bool rev = ( abs(i2-i1) == 1 ? i1 > i2 : i2 > i1 );
621 if ( rev ) n1n2.Reverse();
623 gp_XYZ ofNorm, fNorm;
624 if ( SMESH_MeshAlgos::FaceNormal( outerFace, ofNorm, /*normalized=*/false ))
626 // direction from the link inside outerFace
627 gp_Vec dirInOF = gp_Vec( ofNorm ) ^ n1n2;
628 // sort all other faces by angle with the dirInOF
629 map< double, const SMDS_MeshElement* > angle2Face;
630 set< const SMDS_MeshElement*, TIDCompare >::const_iterator face = faces.begin();
631 for ( ; face != faces.end(); ++face )
633 if ( !SMESH_MeshAlgos::FaceNormal( *face, fNorm, /*normalized=*/false ))
635 gp_Vec dirInF = gp_Vec( fNorm ) ^ n1n2;
636 double angle = dirInOF.AngleWithRef( dirInF, n1n2 );
637 if ( angle < 0 ) angle += 2. * M_PI;
638 angle2Face.insert( make_pair( angle, *face ));
640 if ( !angle2Face.empty() )
641 outerFace2 = angle2Face.begin()->second;
644 // store the found outer face and add its links to continue seaching from
647 _outerFaces.insert( outerFace );
648 int nbNodes = outerFace2->NbNodes()/( outerFace2->IsQuadratic() ? 2 : 1 );
649 for ( int i = 0; i < nbNodes; ++i )
651 SMESH_TLink link2( outerFace2->GetNode(i), outerFace2->GetNode((i+1)%nbNodes));
652 if ( visitedLinks.insert( link2 ).second )
653 startLinks.push_back( TFaceLink( link2.node1(), link2.node2(), outerFace2 ));
656 startLinks.pop_front();
658 _outerFacesFound = true;
660 if ( !seamLinks.empty() )
662 // There are internal boundaries touching the outher one,
663 // find all faces of internal boundaries in order to find
664 // faces of boundaries of holes, if any.
673 //=======================================================================
675 * \brief Find elements of given type where the given point is IN or ON.
676 * Returns nb of found elements and elements them-selves.
678 * 'ALL' type means elements of any type excluding nodes, balls and 0D elements
680 //=======================================================================
682 int SMESH_ElementSearcherImpl::
683 FindElementsByPoint(const gp_Pnt& point,
684 SMDSAbs_ElementType type,
685 vector< const SMDS_MeshElement* >& foundElements)
687 foundElements.clear();
689 double tolerance = getTolerance();
691 // =================================================================================
692 if ( type == SMDSAbs_Node || type == SMDSAbs_0DElement || type == SMDSAbs_Ball)
694 if ( !_nodeSearcher )
695 _nodeSearcher = new SMESH_NodeSearcherImpl( _mesh );
697 const SMDS_MeshNode* closeNode = _nodeSearcher->FindClosestTo( point );
698 if ( !closeNode ) return foundElements.size();
700 if ( point.Distance( SMESH_TNodeXYZ( closeNode )) > tolerance )
701 return foundElements.size(); // to far from any node
703 if ( type == SMDSAbs_Node )
705 foundElements.push_back( closeNode );
709 SMDS_ElemIteratorPtr elemIt = closeNode->GetInverseElementIterator( type );
710 while ( elemIt->more() )
711 foundElements.push_back( elemIt->next() );
714 // =================================================================================
715 else // elements more complex than 0D
717 if ( !_ebbTree || _elementType != type )
719 if ( _ebbTree ) delete _ebbTree;
720 _ebbTree = new ElementBndBoxTree( *_mesh, _elementType = type, _meshPartIt, tolerance );
722 TIDSortedElemSet suspectElems;
723 _ebbTree->getElementsNearPoint( point, suspectElems );
724 TIDSortedElemSet::iterator elem = suspectElems.begin();
725 for ( ; elem != suspectElems.end(); ++elem )
726 if ( !SMESH_MeshAlgos::IsOut( *elem, point, tolerance ))
727 foundElements.push_back( *elem );
729 return foundElements.size();
732 //=======================================================================
734 * \brief Find an element of given type most close to the given point
736 * WARNING: Only face search is implemeneted so far
738 //=======================================================================
740 const SMDS_MeshElement*
741 SMESH_ElementSearcherImpl::FindClosestTo( const gp_Pnt& point,
742 SMDSAbs_ElementType type )
744 const SMDS_MeshElement* closestElem = 0;
746 if ( type == SMDSAbs_Face )
748 if ( !_ebbTree || _elementType != type )
750 if ( _ebbTree ) delete _ebbTree;
751 _ebbTree = new ElementBndBoxTree( *_mesh, _elementType = type, _meshPartIt );
753 TIDSortedElemSet suspectElems;
754 _ebbTree->getElementsNearPoint( point, suspectElems );
756 if ( suspectElems.empty() && _ebbTree->maxSize() > 0 )
758 gp_Pnt boxCenter = 0.5 * ( _ebbTree->getBox()->CornerMin() +
759 _ebbTree->getBox()->CornerMax() );
761 if ( _ebbTree->getBox()->IsOut( point.XYZ() ))
762 radius = point.Distance( boxCenter ) - 0.5 * _ebbTree->maxSize();
764 radius = _ebbTree->maxSize() / pow( 2., _ebbTree->getHeight()) / 2;
765 while ( suspectElems.empty() )
767 _ebbTree->getElementsInSphere( point.XYZ(), radius, suspectElems );
771 double minDist = std::numeric_limits<double>::max();
772 multimap< double, const SMDS_MeshElement* > dist2face;
773 TIDSortedElemSet::iterator elem = suspectElems.begin();
774 for ( ; elem != suspectElems.end(); ++elem )
776 double dist = SMESH_MeshAlgos::GetDistance( dynamic_cast<const SMDS_MeshFace*>(*elem),
778 if ( dist < minDist + 1e-10)
781 dist2face.insert( dist2face.begin(), make_pair( dist, *elem ));
784 if ( !dist2face.empty() )
786 multimap< double, const SMDS_MeshElement* >::iterator d2f = dist2face.begin();
787 closestElem = d2f->second;
788 // if there are several elements at the same distance, select one
789 // with GC closest to the point
790 typedef SMDS_StdIterator< SMESH_TNodeXYZ, SMDS_ElemIteratorPtr > TXyzIterator;
791 double minDistToGC = 0;
792 for ( ++d2f; d2f != dist2face.end() && fabs( d2f->first - minDist ) < 1e-10; ++d2f )
794 if ( minDistToGC == 0 )
797 gc = accumulate( TXyzIterator(closestElem->nodesIterator()),
798 TXyzIterator(), gc ) / closestElem->NbNodes();
799 minDistToGC = point.SquareDistance( gc );
802 gc = accumulate( TXyzIterator( d2f->second->nodesIterator()),
803 TXyzIterator(), gc ) / d2f->second->NbNodes();
804 double d = point.SquareDistance( gc );
805 if ( d < minDistToGC )
808 closestElem = d2f->second;
811 // cout << "FindClosestTo( " <<point.X()<<", "<<point.Y()<<", "<<point.Z()<<" ) FACE "
812 // <<closestElem->GetID() << " DIST " << minDist << endl;
817 // NOT IMPLEMENTED SO FAR
823 //================================================================================
825 * \brief Classify the given point in the closed 2D mesh
827 //================================================================================
829 TopAbs_State SMESH_ElementSearcherImpl::GetPointState(const gp_Pnt& point)
831 double tolerance = getTolerance();
832 if ( !_ebbTree || _elementType != SMDSAbs_Face )
834 if ( _ebbTree ) delete _ebbTree;
835 _ebbTree = new ElementBndBoxTree( *_mesh, _elementType = SMDSAbs_Face, _meshPartIt );
837 // Algo: analyse transition of a line starting at the point through mesh boundary;
838 // try three lines parallel to axis of the coordinate system and perform rough
839 // analysis. If solution is not clear perform thorough analysis.
841 const int nbAxes = 3;
842 gp_Dir axisDir[ nbAxes ] = { gp::DX(), gp::DY(), gp::DZ() };
843 map< double, TInters > paramOnLine2TInters[ nbAxes ];
844 list< TInters > tangentInters[ nbAxes ]; // of faces whose plane includes the line
845 multimap< int, int > nbInt2Axis; // to find the simplest case
846 for ( int axis = 0; axis < nbAxes; ++axis )
848 gp_Ax1 lineAxis( point, axisDir[axis]);
849 gp_Lin line ( lineAxis );
851 TIDSortedElemSet suspectFaces; // faces possibly intersecting the line
852 _ebbTree->getElementsNearLine( lineAxis, suspectFaces );
854 // Intersect faces with the line
856 map< double, TInters > & u2inters = paramOnLine2TInters[ axis ];
857 TIDSortedElemSet::iterator face = suspectFaces.begin();
858 for ( ; face != suspectFaces.end(); ++face )
862 if ( !SMESH_MeshAlgos::FaceNormal( *face, fNorm, /*normalized=*/false)) continue;
863 gp_Pln facePlane( SMESH_TNodeXYZ( (*face)->GetNode(0)), fNorm );
865 // perform intersection
866 IntAna_IntConicQuad intersection( line, IntAna_Quadric( facePlane ));
867 if ( !intersection.IsDone() )
869 if ( intersection.IsInQuadric() )
871 tangentInters[ axis ].push_back( TInters( *face, fNorm, true ));
873 else if ( ! intersection.IsParallel() && intersection.NbPoints() > 0 )
875 gp_Pnt intersectionPoint = intersection.Point(1);
876 if ( !SMESH_MeshAlgos::IsOut( *face, intersectionPoint, tolerance ))
877 u2inters.insert(make_pair( intersection.ParamOnConic(1), TInters( *face, fNorm )));
880 // Analyse intersections roughly
882 int nbInter = u2inters.size();
886 double f = u2inters.begin()->first, l = u2inters.rbegin()->first;
887 if ( nbInter == 1 ) // not closed mesh
888 return fabs( f ) < tolerance ? TopAbs_ON : TopAbs_UNKNOWN;
890 if ( fabs( f ) < tolerance || fabs( l ) < tolerance )
893 if ( (f<0) == (l<0) )
896 int nbIntBeforePoint = std::distance( u2inters.begin(), u2inters.lower_bound(0));
897 int nbIntAfterPoint = nbInter - nbIntBeforePoint;
898 if ( nbIntBeforePoint == 1 || nbIntAfterPoint == 1 )
901 nbInt2Axis.insert( make_pair( min( nbIntBeforePoint, nbIntAfterPoint ), axis ));
903 if ( _outerFacesFound ) break; // pass to thorough analysis
905 } // three attempts - loop on CS axes
907 // Analyse intersections thoroughly.
908 // We make two loops maximum, on the first one we only exclude touching intersections,
909 // on the second, if situation is still unclear, we gather and use information on
910 // position of faces (internal or outer). If faces position is already gathered,
911 // we make the second loop right away.
913 for ( int hasPositionInfo = _outerFacesFound; hasPositionInfo < 2; ++hasPositionInfo )
915 multimap< int, int >::const_iterator nb_axis = nbInt2Axis.begin();
916 for ( ; nb_axis != nbInt2Axis.end(); ++nb_axis )
918 int axis = nb_axis->second;
919 map< double, TInters > & u2inters = paramOnLine2TInters[ axis ];
921 gp_Ax1 lineAxis( point, axisDir[axis]);
922 gp_Lin line ( lineAxis );
924 // add tangent intersections to u2inters
926 list< TInters >::const_iterator tgtInt = tangentInters[ axis ].begin();
927 for ( ; tgtInt != tangentInters[ axis ].end(); ++tgtInt )
928 if ( getIntersParamOnLine( line, tgtInt->_face, tolerance, param ))
929 u2inters.insert(make_pair( param, *tgtInt ));
930 tangentInters[ axis ].clear();
932 // Count intersections before and after the point excluding touching ones.
933 // If hasPositionInfo we count intersections of outer boundary only
935 int nbIntBeforePoint = 0, nbIntAfterPoint = 0;
936 double f = numeric_limits<double>::max(), l = -numeric_limits<double>::max();
937 map< double, TInters >::iterator u_int1 = u2inters.begin(), u_int2 = u_int1;
938 bool ok = ! u_int1->second._coincides;
939 while ( ok && u_int1 != u2inters.end() )
941 double u = u_int1->first;
942 bool touchingInt = false;
943 if ( ++u_int2 != u2inters.end() )
945 // skip intersections at the same point (if the line passes through edge or node)
947 while ( u_int2 != u2inters.end() && fabs( u_int2->first - u ) < tolerance )
953 // skip tangent intersections
955 const SMDS_MeshElement* prevFace = u_int1->second._face;
956 while ( ok && u_int2->second._coincides )
958 if ( SMESH_MeshAlgos::GetCommonNodes(prevFace , u_int2->second._face).empty() )
964 ok = ( u_int2 != u2inters.end() );
969 // skip intersections at the same point after tangent intersections
972 double u2 = u_int2->first;
974 while ( u_int2 != u2inters.end() && fabs( u_int2->first - u2 ) < tolerance )
980 // decide if we skipped a touching intersection
981 if ( nbSamePnt + nbTgt > 0 )
983 double minDot = numeric_limits<double>::max(), maxDot = -numeric_limits<double>::max();
984 map< double, TInters >::iterator u_int = u_int1;
985 for ( ; u_int != u_int2; ++u_int )
987 if ( u_int->second._coincides ) continue;
988 double dot = u_int->second._faceNorm * line.Direction();
989 if ( dot > maxDot ) maxDot = dot;
990 if ( dot < minDot ) minDot = dot;
992 touchingInt = ( minDot*maxDot < 0 );
997 if ( !hasPositionInfo || isOuterBoundary( u_int1->second._face ))
1008 u_int1 = u_int2; // to next intersection
1010 } // loop on intersections with one line
1014 if ( fabs( f ) < tolerance || fabs( l ) < tolerance )
1017 if ( nbIntBeforePoint == 0 || nbIntAfterPoint == 0)
1020 if ( nbIntBeforePoint + nbIntAfterPoint == 1 ) // not closed mesh
1021 return fabs( f ) < tolerance ? TopAbs_ON : TopAbs_UNKNOWN;
1023 if ( nbIntBeforePoint == 1 || nbIntAfterPoint == 1 )
1026 if ( (f<0) == (l<0) )
1029 if ( hasPositionInfo )
1030 return nbIntBeforePoint % 2 ? TopAbs_IN : TopAbs_OUT;
1032 } // loop on intersections of the tree lines - thorough analysis
1034 if ( !hasPositionInfo )
1036 // gather info on faces position - is face in the outer boundary or not
1037 map< double, TInters > & u2inters = paramOnLine2TInters[ 0 ];
1038 findOuterBoundary( u2inters.begin()->second._face );
1041 } // two attempts - with and w/o faces position info in the mesh
1043 return TopAbs_UNKNOWN;
1046 //=======================================================================
1048 * \brief Return elements possibly intersecting the line
1050 //=======================================================================
1052 void SMESH_ElementSearcherImpl::GetElementsNearLine( const gp_Ax1& line,
1053 SMDSAbs_ElementType type,
1054 vector< const SMDS_MeshElement* >& foundElems)
1056 if ( !_ebbTree || _elementType != type )
1058 if ( _ebbTree ) delete _ebbTree;
1059 _ebbTree = new ElementBndBoxTree( *_mesh, _elementType = type, _meshPartIt );
1061 TIDSortedElemSet suspectFaces; // elements possibly intersecting the line
1062 _ebbTree->getElementsNearLine( line, suspectFaces );
1063 foundElems.assign( suspectFaces.begin(), suspectFaces.end());
1066 //=======================================================================
1068 * \brief Return true if the point is IN or ON of the element
1070 //=======================================================================
1072 bool SMESH_MeshAlgos::IsOut( const SMDS_MeshElement* element, const gp_Pnt& point, double tol )
1074 if ( element->GetType() == SMDSAbs_Volume)
1076 return SMDS_VolumeTool( element ).IsOut( point.X(), point.Y(), point.Z(), tol );
1079 // get ordered nodes
1081 vector< gp_XYZ > xyz;
1082 vector<const SMDS_MeshNode*> nodeList;
1084 SMDS_ElemIteratorPtr nodeIt = element->nodesIterator();
1085 if ( element->IsQuadratic() ) {
1086 nodeIt = element->interlacedNodesElemIterator();
1087 // if (const SMDS_VtkFace* f=dynamic_cast<const SMDS_VtkFace*>(element))
1088 // nodeIt = f->interlacedNodesElemIterator();
1089 // else if (const SMDS_VtkEdge* e =dynamic_cast<const SMDS_VtkEdge*>(element))
1090 // nodeIt = e->interlacedNodesElemIterator();
1092 while ( nodeIt->more() )
1094 SMESH_TNodeXYZ node = nodeIt->next();
1095 xyz.push_back( node );
1096 nodeList.push_back(node._node);
1099 int i, nbNodes = (int) nodeList.size(); // central node of biquadratic is missing
1101 if ( element->GetType() == SMDSAbs_Face ) // --------------------------------------------------
1103 // compute face normal
1104 gp_Vec faceNorm(0,0,0);
1105 xyz.push_back( xyz.front() );
1106 nodeList.push_back( nodeList.front() );
1107 for ( i = 0; i < nbNodes; ++i )
1109 gp_Vec edge1( xyz[i+1], xyz[i]);
1110 gp_Vec edge2( xyz[i+1], xyz[(i+2)%nbNodes] );
1111 faceNorm += edge1 ^ edge2;
1113 double normSize = faceNorm.Magnitude();
1114 if ( normSize <= tol )
1116 // degenerated face: point is out if it is out of all face edges
1117 for ( i = 0; i < nbNodes; ++i )
1119 SMDS_LinearEdge edge( nodeList[i], nodeList[i+1] );
1120 if ( !IsOut( &edge, point, tol ))
1125 faceNorm /= normSize;
1127 // check if the point lays on face plane
1128 gp_Vec n2p( xyz[0], point );
1129 if ( fabs( n2p * faceNorm ) > tol )
1130 return true; // not on face plane
1132 // check if point is out of face boundary:
1133 // define it by closest transition of a ray point->infinity through face boundary
1134 // on the face plane.
1135 // First, find normal of a plane perpendicular to face plane, to be used as a cutting tool
1136 // to find intersections of the ray with the boundary.
1138 gp_Vec plnNorm = ray ^ faceNorm;
1139 normSize = plnNorm.Magnitude();
1140 if ( normSize <= tol ) return false; // point coincides with the first node
1141 plnNorm /= normSize;
1142 // for each node of the face, compute its signed distance to the plane
1143 vector<double> dist( nbNodes + 1);
1144 for ( i = 0; i < nbNodes; ++i )
1146 gp_Vec n2p( xyz[i], point );
1147 dist[i] = n2p * plnNorm;
1149 dist.back() = dist.front();
1150 // find the closest intersection
1152 double rClosest, distClosest = 1e100;;
1154 for ( i = 0; i < nbNodes; ++i )
1157 if ( fabs( dist[i]) < tol )
1159 else if ( fabs( dist[i+1]) < tol )
1161 else if ( dist[i] * dist[i+1] < 0 )
1162 r = dist[i] / ( dist[i] - dist[i+1] );
1164 continue; // no intersection
1165 gp_Pnt pInt = xyz[i] * (1.-r) + xyz[i+1] * r;
1166 gp_Vec p2int ( point, pInt);
1167 if ( p2int * ray > -tol ) // right half-space
1169 double intDist = p2int.SquareMagnitude();
1170 if ( intDist < distClosest )
1175 distClosest = intDist;
1180 return true; // no intesections - out
1182 // analyse transition
1183 gp_Vec edge( xyz[iClosest], xyz[iClosest+1] );
1184 gp_Vec edgeNorm = -( edge ^ faceNorm ); // normal to intersected edge pointing out of face
1185 gp_Vec p2int ( point, pClosest );
1186 bool out = (edgeNorm * p2int) < -tol;
1187 if ( rClosest > 0. && rClosest < 1. ) // not node intersection
1190 // ray pass through a face node; analyze transition through an adjacent edge
1191 gp_Pnt p1 = xyz[ (rClosest == 0.) ? ((iClosest+nbNodes-1) % nbNodes) : (iClosest+1) ];
1192 gp_Pnt p2 = xyz[ (rClosest == 0.) ? iClosest : ((iClosest+2) % nbNodes) ];
1193 gp_Vec edgeAdjacent( p1, p2 );
1194 gp_Vec edgeNorm2 = -( edgeAdjacent ^ faceNorm );
1195 bool out2 = (edgeNorm2 * p2int) < -tol;
1197 bool covexCorner = ( edgeNorm * edgeAdjacent * (rClosest==1. ? 1. : -1.)) < 0;
1198 return covexCorner ? (out || out2) : (out && out2);
1200 if ( element->GetType() == SMDSAbs_Edge ) // --------------------------------------------------
1202 // point is out of edge if it is NOT ON any straight part of edge
1203 // (we consider quadratic edge as being composed of two straight parts)
1204 for ( i = 1; i < nbNodes; ++i )
1206 gp_Vec edge( xyz[i-1], xyz[i]);
1207 gp_Vec n1p ( xyz[i-1], point);
1208 double dist = ( edge ^ n1p ).Magnitude() / edge.Magnitude();
1211 gp_Vec n2p( xyz[i], point );
1212 if ( fabs( edge.Magnitude() - n1p.Magnitude() - n2p.Magnitude()) > tol )
1214 return false; // point is ON this part
1218 // Node or 0D element -------------------------------------------------------------------------
1220 gp_Vec n2p ( xyz[0], point );
1221 return n2p.Magnitude() <= tol;
1226 //=======================================================================
1229 // Position of a point relative to a segment
1233 // VERTEX 1 o----ON-----> VERTEX 2
1237 enum PositionName { POS_LEFT = 1, POS_VERTEX = 2, POS_RIGHT = 4, //POS_ON = 8,
1238 POS_ALL = POS_LEFT | POS_RIGHT | POS_VERTEX };
1242 int _index; // index of vertex or segment
1244 PointPos( PositionName n, int i=-1 ): _name(n), _index(i) {}
1245 bool operator < (const PointPos& other ) const
1247 if ( _name == other._name )
1248 return ( _index < 0 || other._index < 0 ) ? false : _index < other._index;
1249 return _name < other._name;
1253 //================================================================================
1255 * \brief Return of a point relative to a segment
1256 * \param point2D - the point to analyze position of
1257 * \param xyVec - end points of segments
1258 * \param index0 - 0-based index of the first point of segment
1259 * \param posToFindOut - flags of positions to detect
1260 * \retval PointPos - point position
1262 //================================================================================
1264 PointPos getPointPosition( const gp_XY& point2D,
1265 const gp_XY* segEnds,
1266 const int index0 = 0,
1267 const int posToFindOut = POS_ALL)
1269 const gp_XY& p1 = segEnds[ index0 ];
1270 const gp_XY& p2 = segEnds[ index0+1 ];
1271 const gp_XY grad = p2 - p1;
1273 if ( posToFindOut & POS_VERTEX )
1275 // check if the point2D is at "vertex 1" zone
1276 gp_XY pp1[2] = { p1, gp_XY( p1.X() - grad.Y(),
1277 p1.Y() + grad.X() ) };
1278 if ( getPointPosition( point2D, pp1, 0, POS_LEFT|POS_RIGHT )._name == POS_LEFT )
1279 return PointPos( POS_VERTEX, index0 );
1281 // check if the point2D is at "vertex 2" zone
1282 gp_XY pp2[2] = { p2, gp_XY( p2.X() - grad.Y(),
1283 p2.Y() + grad.X() ) };
1284 if ( getPointPosition( point2D, pp2, 0, POS_LEFT|POS_RIGHT )._name == POS_RIGHT )
1285 return PointPos( POS_VERTEX, index0 + 1);
1287 double edgeEquation =
1288 ( point2D.X() - p1.X() ) * grad.Y() - ( point2D.Y() - p1.Y() ) * grad.X();
1289 return PointPos( edgeEquation < 0 ? POS_LEFT : POS_RIGHT, index0 );
1293 //=======================================================================
1295 * \brief Return minimal distance from a point to a face
1297 * Currently we ignore non-planarity and 2nd order of face
1299 //=======================================================================
1301 double SMESH_MeshAlgos::GetDistance( const SMDS_MeshFace* face,
1302 const gp_Pnt& point )
1304 double badDistance = -1;
1305 if ( !face ) return badDistance;
1307 // coordinates of nodes (medium nodes, if any, ignored)
1308 typedef SMDS_StdIterator< SMESH_TNodeXYZ, SMDS_ElemIteratorPtr > TXyzIterator;
1309 vector<gp_XYZ> xyz( TXyzIterator( face->nodesIterator()), TXyzIterator() );
1310 xyz.resize( face->NbCornerNodes()+1 );
1312 // transformation to get xyz[0] lies on the origin, xyz[1] lies on the Z axis,
1313 // and xyz[2] lies in the XZ plane. This is to pass to 2D space on XZ plane.
1315 gp_Vec OZ ( xyz[0], xyz[1] );
1316 gp_Vec OX ( xyz[0], xyz[2] );
1317 if ( OZ.Magnitude() < std::numeric_limits<double>::min() )
1319 if ( xyz.size() < 4 ) return badDistance;
1320 OZ = gp_Vec ( xyz[0], xyz[2] );
1321 OX = gp_Vec ( xyz[0], xyz[3] );
1325 tgtCS = gp_Ax3( xyz[0], OZ, OX );
1327 catch ( Standard_Failure ) {
1330 trsf.SetTransformation( tgtCS );
1332 // move all the nodes to 2D
1333 vector<gp_XY> xy( xyz.size() );
1334 for ( size_t i = 0;i < xyz.size()-1; ++i )
1336 gp_XYZ p3d = xyz[i];
1337 trsf.Transforms( p3d );
1338 xy[i].SetCoord( p3d.X(), p3d.Z() );
1340 xyz.back() = xyz.front();
1341 xy.back() = xy.front();
1343 // // move the point in 2D
1344 gp_XYZ tmpPnt = point.XYZ();
1345 trsf.Transforms( tmpPnt );
1346 gp_XY point2D( tmpPnt.X(), tmpPnt.Z() );
1348 // loop on segments of the face to analyze point position ralative to the face
1349 set< PointPos > pntPosSet;
1350 for ( size_t i = 1; i < xy.size(); ++i )
1352 PointPos pos = getPointPosition( point2D, &xy[0], i-1 );
1353 pntPosSet.insert( pos );
1357 PointPos pos = *pntPosSet.begin();
1358 // cout << "Face " << face->GetID() << " DIST: ";
1359 switch ( pos._name )
1362 // point is most close to a segment
1363 gp_Vec p0p1( point, xyz[ pos._index ] );
1364 gp_Vec p1p2( xyz[ pos._index ], xyz[ pos._index+1 ]); // segment vector
1366 double projDist = p0p1 * p1p2; // distance projected to the segment
1367 gp_Vec projVec = p1p2 * projDist;
1368 gp_Vec distVec = p0p1 - projVec;
1369 // cout << distVec.Magnitude() << ", SEG " << face->GetNode(pos._index)->GetID()
1370 // << " - " << face->GetNodeWrap(pos._index+1)->GetID() << endl;
1371 return distVec.Magnitude();
1374 // point is inside the face
1375 double distToFacePlane = tmpPnt.Y();
1376 // cout << distToFacePlane << ", INSIDE " << endl;
1377 return Abs( distToFacePlane );
1380 // point is most close to a node
1381 gp_Vec distVec( point, xyz[ pos._index ]);
1382 // cout << distVec.Magnitude() << " VERTEX " << face->GetNode(pos._index)->GetID() << endl;
1383 return distVec.Magnitude();
1389 //=======================================================================
1390 //function : FindFaceInSet
1391 //purpose : Return a face having linked nodes n1 and n2 and which is
1392 // - not in avoidSet,
1393 // - in elemSet provided that !elemSet.empty()
1394 // i1 and i2 optionally returns indices of n1 and n2
1395 //=======================================================================
1397 const SMDS_MeshElement*
1398 SMESH_MeshAlgos::FindFaceInSet(const SMDS_MeshNode* n1,
1399 const SMDS_MeshNode* n2,
1400 const TIDSortedElemSet& elemSet,
1401 const TIDSortedElemSet& avoidSet,
1407 const SMDS_MeshElement* face = 0;
1409 SMDS_ElemIteratorPtr invElemIt = n1->GetInverseElementIterator(SMDSAbs_Face);
1410 //MESSAGE("n1->GetInverseElementIterator(SMDSAbs_Face) " << invElemIt);
1411 while ( invElemIt->more() && !face ) // loop on inverse faces of n1
1413 //MESSAGE("in while ( invElemIt->more() && !face )");
1414 const SMDS_MeshElement* elem = invElemIt->next();
1415 if (avoidSet.count( elem ))
1417 if ( !elemSet.empty() && !elemSet.count( elem ))
1420 i1 = elem->GetNodeIndex( n1 );
1421 // find a n2 linked to n1
1422 int nbN = elem->IsQuadratic() ? elem->NbNodes()/2 : elem->NbNodes();
1423 for ( int di = -1; di < 2 && !face; di += 2 )
1425 i2 = (i1+di+nbN) % nbN;
1426 if ( elem->GetNode( i2 ) == n2 )
1429 if ( !face && elem->IsQuadratic())
1431 // analysis for quadratic elements using all nodes
1432 // const SMDS_VtkFace* F = dynamic_cast<const SMDS_VtkFace*>(elem);
1433 // if (!F) throw SALOME_Exception(LOCALIZED("not an SMDS_VtkFace"));
1434 // use special nodes iterator
1435 SMDS_ElemIteratorPtr anIter = elem->interlacedNodesElemIterator();
1436 const SMDS_MeshNode* prevN = static_cast<const SMDS_MeshNode*>( anIter->next() );
1437 for ( i1 = -1, i2 = 0; anIter->more() && !face; i1++, i2++ )
1439 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( anIter->next() );
1440 if ( n1 == prevN && n2 == n )
1444 else if ( n2 == prevN && n1 == n )
1446 face = elem; swap( i1, i2 );
1452 if ( n1ind ) *n1ind = i1;
1453 if ( n2ind ) *n2ind = i2;
1457 //================================================================================
1459 * \brief Calculate normal of a mesh face
1461 //================================================================================
1463 bool SMESH_MeshAlgos::FaceNormal(const SMDS_MeshElement* F, gp_XYZ& normal, bool normalized)
1465 if ( !F || F->GetType() != SMDSAbs_Face )
1468 normal.SetCoord(0,0,0);
1469 int nbNodes = F->IsQuadratic() ? F->NbNodes()/2 : F->NbNodes();
1470 for ( int i = 0; i < nbNodes-2; ++i )
1473 for ( int n = 0; n < 3; ++n )
1475 const SMDS_MeshNode* node = F->GetNode( i + n );
1476 p[n].SetCoord( node->X(), node->Y(), node->Z() );
1478 normal += ( p[2] - p[1] ) ^ ( p[0] - p[1] );
1480 double size2 = normal.SquareModulus();
1481 bool ok = ( size2 > numeric_limits<double>::min() * numeric_limits<double>::min());
1482 if ( normalized && ok )
1483 normal /= sqrt( size2 );
1488 //=======================================================================
1489 //function : GetCommonNodes
1490 //purpose : Return nodes common to two elements
1491 //=======================================================================
1493 vector< const SMDS_MeshNode*> SMESH_MeshAlgos::GetCommonNodes(const SMDS_MeshElement* e1,
1494 const SMDS_MeshElement* e2)
1496 vector< const SMDS_MeshNode*> common;
1497 for ( int i = 0 ; i < e1->NbNodes(); ++i )
1498 if ( e2->GetNodeIndex( e1->GetNode( i )) >= 0 )
1499 common.push_back( e1->GetNode( i ));
1503 //=======================================================================
1505 * \brief Return SMESH_NodeSearcher
1507 //=======================================================================
1509 SMESH_NodeSearcher* SMESH_MeshAlgos::GetNodeSearcher(SMDS_Mesh& mesh)
1511 return new SMESH_NodeSearcherImpl( &mesh );
1514 //=======================================================================
1516 * \brief Return SMESH_ElementSearcher
1518 //=======================================================================
1520 SMESH_ElementSearcher* SMESH_MeshAlgos::GetElementSearcher(SMDS_Mesh& mesh)
1522 return new SMESH_ElementSearcherImpl( mesh );
1525 //=======================================================================
1527 * \brief Return SMESH_ElementSearcher acting on a sub-set of elements
1529 //=======================================================================
1531 SMESH_ElementSearcher* SMESH_MeshAlgos::GetElementSearcher(SMDS_Mesh& mesh,
1532 SMDS_ElemIteratorPtr elemIt)
1534 return new SMESH_ElementSearcherImpl( mesh, elemIt );