Salome HOME
Fix SALOME_TESTS/Grids/smesh/imps_09/K0
[modules/smesh.git] / src / SMESHUtils / SMESH_MeshAlgos.cxx
1 // Copyright (C) 2007-2019  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
10 //
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 // Lesser General Public License for more details.
15 //
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22 // File      : SMESH_MeshAlgos.hxx
23 // Created   : Tue Apr 30 18:00:36 2013
24 // Author    : Edward AGAPOV (eap)
25
26 // Initially this file held some low level algorithms extracted from SMESH_MeshEditor
27 // to make them accessible from Controls package
28
29 #include "SMESH_MeshAlgos.hxx"
30
31 #include "ObjectPool.hxx"
32 #include "SMDS_FaceOfNodes.hxx"
33 #include "SMDS_LinearEdge.hxx"
34 #include "SMDS_Mesh.hxx"
35 #include "SMDS_PolygonalFaceOfNodes.hxx"
36 #include "SMDS_VolumeTool.hxx"
37 #include "SMESH_OctreeNode.hxx"
38
39 #include <Utils_SALOME_Exception.hxx>
40
41 #include <GC_MakeSegment.hxx>
42 #include <GeomAPI_ExtremaCurveCurve.hxx>
43 #include <Geom_Line.hxx>
44 #include <IntAna_IntConicQuad.hxx>
45 #include <IntAna_Quadric.hxx>
46 #include <gp_Lin.hxx>
47 #include <gp_Pln.hxx>
48 #include <NCollection_DataMap.hxx>
49
50 #include <limits>
51 #include <numeric>
52
53 #include <boost/container/flat_set.hpp>
54
55 //=======================================================================
56 /*!
57  * \brief Implementation of search for the node closest to point
58  */
59 //=======================================================================
60
61 struct SMESH_NodeSearcherImpl: public SMESH_NodeSearcher
62 {
63   //---------------------------------------------------------------------
64   /*!
65    * \brief Constructor
66    */
67   SMESH_NodeSearcherImpl( const SMDS_Mesh*     theMesh   = 0,
68                           SMDS_ElemIteratorPtr theElemIt = SMDS_ElemIteratorPtr() )
69   {
70     myMesh = ( SMDS_Mesh* ) theMesh;
71
72     TIDSortedNodeSet nodes;
73     if ( theMesh ) {
74       SMDS_NodeIteratorPtr nIt = theMesh->nodesIterator();
75       while ( nIt->more() )
76         nodes.insert( nodes.end(), nIt->next() );
77     }
78     else if ( theElemIt )
79     {
80       while ( theElemIt->more() )
81       {
82         const SMDS_MeshElement* e = theElemIt->next();
83         nodes.insert( e->begin_nodes(), e->end_nodes() );
84       }
85     }
86     myOctreeNode = new SMESH_OctreeNode(nodes) ;
87
88     // get max size of a leaf box
89     SMESH_OctreeNode* tree = myOctreeNode;
90     while ( !tree->isLeaf() )
91     {
92       SMESH_OctreeNodeIteratorPtr cIt = tree->GetChildrenIterator();
93       if ( cIt->more() )
94         tree = cIt->next();
95     }
96     myHalfLeafSize = tree->maxSize() / 2.;
97   }
98
99   //---------------------------------------------------------------------
100   /*!
101    * \brief Move node and update myOctreeNode accordingly
102    */
103   void MoveNode( const SMDS_MeshNode* node, const gp_Pnt& toPnt )
104   {
105     myOctreeNode->UpdateByMoveNode( node, toPnt );
106     myMesh->MoveNode( node, toPnt.X(), toPnt.Y(), toPnt.Z() );
107   }
108
109   //---------------------------------------------------------------------
110   /*!
111    * \brief Do it's job
112    */
113   const SMDS_MeshNode* FindClosestTo( const gp_Pnt& thePnt )
114   {
115     std::map<double, const SMDS_MeshNode*> dist2Nodes;
116     myOctreeNode->NodesAround( thePnt.Coord(), dist2Nodes, myHalfLeafSize );
117     if ( !dist2Nodes.empty() )
118       return dist2Nodes.begin()->second;
119
120     std::vector<const SMDS_MeshNode*> nodes;
121     //myOctreeNode->NodesAround( &tgtNode, &nodes, myHalfLeafSize );
122
123     double minSqDist = DBL_MAX;
124     if ( nodes.empty() )  // get all nodes of OctreeNode's closest to thePnt
125     {
126       // sort leafs by their distance from thePnt
127       typedef std::multimap< double, SMESH_OctreeNode* > TDistTreeMap;
128       TDistTreeMap treeMap;
129       std::list< SMESH_OctreeNode* > treeList;
130       std::list< SMESH_OctreeNode* >::iterator trIt;
131       treeList.push_back( myOctreeNode );
132
133       gp_XYZ pointNode( thePnt.X(), thePnt.Y(), thePnt.Z() );
134       bool pointInside = myOctreeNode->isInside( pointNode, myHalfLeafSize );
135       for ( trIt = treeList.begin(); trIt != treeList.end(); ++trIt)
136       {
137         SMESH_OctreeNode* tree = *trIt;
138         if ( !tree->isLeaf() ) // put children to the queue
139         {
140           if ( pointInside && !tree->isInside( pointNode, myHalfLeafSize )) continue;
141           SMESH_OctreeNodeIteratorPtr cIt = tree->GetChildrenIterator();
142           while ( cIt->more() )
143             treeList.push_back( cIt->next() );
144         }
145         else if ( tree->NbNodes() ) // put a tree to the treeMap
146         {
147           const Bnd_B3d& box = *tree->getBox();
148           double sqDist = thePnt.SquareDistance( 0.5 * ( box.CornerMin() + box.CornerMax() ));
149           treeMap.insert( std::make_pair( sqDist, tree ));
150         }
151       }
152       // find distance after which there is no sense to check tree's
153       double sqLimit = DBL_MAX;
154       TDistTreeMap::iterator sqDist_tree = treeMap.begin();
155       if ( treeMap.size() > 5 ) {
156         SMESH_OctreeNode* closestTree = sqDist_tree->second;
157         const Bnd_B3d& box = *closestTree->getBox();
158         double limit = sqrt( sqDist_tree->first ) + sqrt ( box.SquareExtent() );
159         sqLimit = limit * limit;
160       }
161       // get all nodes from trees
162       for ( ; sqDist_tree != treeMap.end(); ++sqDist_tree) {
163         if ( sqDist_tree->first > sqLimit )
164           break;
165         SMESH_OctreeNode* tree = sqDist_tree->second;
166         tree->AllNodesAround( tree->GetNodeIterator()->next(), &nodes );
167       }
168     }
169     // find closest among nodes
170     minSqDist = DBL_MAX;
171     const SMDS_MeshNode* closestNode = 0;
172     for ( size_t i = 0; i < nodes.size(); ++i )
173     {
174       double sqDist = thePnt.SquareDistance( SMESH_NodeXYZ( nodes[ i ]));
175       if ( minSqDist > sqDist ) {
176         closestNode = nodes[ i ];
177         minSqDist = sqDist;
178       }
179     }
180     return closestNode;
181   }
182
183   //---------------------------------------------------------------------
184   /*!
185    * \brief Finds nodes located within a tolerance near a point
186    */
187   int FindNearPoint(const gp_Pnt&                        point,
188                     const double                         tolerance,
189                     std::vector< const SMDS_MeshNode* >& foundNodes)
190   {
191     myOctreeNode->NodesAround( point.Coord(), foundNodes, tolerance );
192     return foundNodes.size();
193   }
194
195   //---------------------------------------------------------------------
196   /*!
197    * \brief Destructor
198    */
199   ~SMESH_NodeSearcherImpl() { delete myOctreeNode; }
200
201   //---------------------------------------------------------------------
202   /*!
203    * \brief Return the node tree
204    */
205   const SMESH_OctreeNode* getTree() const { return myOctreeNode; }
206
207 private:
208   SMESH_OctreeNode* myOctreeNode;
209   SMDS_Mesh*        myMesh;
210   double            myHalfLeafSize; // max size of a leaf box
211 };
212
213 // ========================================================================
214 namespace // Utils used in SMESH_ElementSearcherImpl::FindElementsByPoint()
215 {
216   const int MaxNbElemsInLeaf = 10; // maximal number of elements in a leaf of tree
217   const int MaxLevel         = 7;  // maximal tree height -> nb terminal boxes: 8^7 = 2097152
218   const double NodeRadius = 1e-9;  // to enlarge bnd box of element
219
220   //=======================================================================
221   /*!
222    * \brief Octal tree of bounding boxes of elements
223    */
224   //=======================================================================
225
226   class ElementBndBoxTree : public SMESH_Octree
227   {
228   public:
229
230     typedef boost::container::flat_set< const SMDS_MeshElement*, TIDCompare > TElemSeq;
231
232     ElementBndBoxTree(const SMDS_Mesh&     mesh,
233                       SMDSAbs_ElementType  elemType,
234                       SMDS_ElemIteratorPtr theElemIt = SMDS_ElemIteratorPtr(),
235                       double               tolerance = NodeRadius );
236     void getElementsNearPoint( const gp_Pnt& point, TElemSeq& foundElems );
237     void getElementsNearLine ( const gp_Ax1& line,  TElemSeq& foundElems );
238     void getElementsInBox    ( const Bnd_B3d& box,  TElemSeq& foundElems );
239     void getElementsInSphere ( const gp_XYZ& center, const double radius, TElemSeq& foundElems );
240     ElementBndBoxTree* getLeafAtPoint( const gp_XYZ& point );
241
242   protected:
243     ElementBndBoxTree() {}
244     SMESH_Octree* newChild() const { return new ElementBndBoxTree; }
245     void          buildChildrenData();
246     Bnd_B3d*      buildRootBox();
247   private:
248     //!< Bounding box of element
249     struct ElementBox : public Bnd_B3d
250     {
251       const SMDS_MeshElement* _element;
252       void init(const SMDS_MeshElement* elem, double tolerance);
253     };
254     std::vector< ElementBox* > _elements;
255
256     typedef ObjectPool< ElementBox > TElementBoxPool;
257
258     //!< allocator of ElementBox's and SMESH_TreeLimit
259     struct LimitAndPool : public SMESH_TreeLimit
260     {
261       TElementBoxPool _elBoPool;
262       LimitAndPool():SMESH_TreeLimit( MaxLevel, /*minSize=*/0. ) {}
263     };
264     LimitAndPool* getLimitAndPool() const
265     {
266       SMESH_TreeLimit* limitAndPool = const_cast< SMESH_TreeLimit* >( myLimit );
267       return static_cast< LimitAndPool* >( limitAndPool );
268     }
269   };
270
271   //================================================================================
272   /*!
273    * \brief ElementBndBoxTree creation
274    */
275   //================================================================================
276
277   ElementBndBoxTree::ElementBndBoxTree(const SMDS_Mesh&     mesh,
278                                        SMDSAbs_ElementType  elemType,
279                                        SMDS_ElemIteratorPtr theElemIt,
280                                        double               tolerance)
281     :SMESH_Octree( new LimitAndPool() )
282   {
283     int nbElems = mesh.GetMeshInfo().NbElements( elemType );
284     _elements.reserve( nbElems );
285
286     TElementBoxPool& elBoPool = getLimitAndPool()->_elBoPool;
287
288 #ifdef _DEBUG_
289     if ( theElemIt && !theElemIt->more() )
290       std::cout << "WARNING: ElementBndBoxTree constructed on empty iterator!" << std::endl;
291 #endif
292
293     SMDS_ElemIteratorPtr elemIt = theElemIt ? theElemIt : mesh.elementsIterator( elemType );
294     while ( elemIt->more() )
295     {
296       ElementBox* eb = elBoPool.getNew();
297       eb->init( elemIt->next(), tolerance );
298       _elements.push_back( eb );
299     }
300     compute();
301   }
302
303   //================================================================================
304   /*!
305    * \brief Return the maximal box
306    */
307   //================================================================================
308
309   Bnd_B3d* ElementBndBoxTree::buildRootBox()
310   {
311     Bnd_B3d* box = new Bnd_B3d;
312     for ( size_t i = 0; i < _elements.size(); ++i )
313       box->Add( *_elements[i] );
314     return box;
315   }
316
317   //================================================================================
318   /*!
319    * \brief Redistrubute element boxes among children
320    */
321   //================================================================================
322
323   void ElementBndBoxTree::buildChildrenData()
324   {
325     for ( size_t i = 0; i < _elements.size(); ++i )
326     {
327       for (int j = 0; j < 8; j++)
328       {
329         if ( !_elements[i]->IsOut( *myChildren[j]->getBox() ))
330           ((ElementBndBoxTree*)myChildren[j])->_elements.push_back( _elements[i]);
331       }
332     }
333     //_size = _elements.size();
334     SMESHUtils::FreeVector( _elements ); // = _elements.clear() + free memory
335
336     for (int j = 0; j < 8; j++)
337     {
338       ElementBndBoxTree* child = static_cast<ElementBndBoxTree*>( myChildren[j]);
339       if ((int) child->_elements.size() <= MaxNbElemsInLeaf )
340         child->myIsLeaf = true;
341
342       if ( child->isLeaf() && child->_elements.capacity() > child->_elements.size() )
343         SMESHUtils::CompactVector( child->_elements );
344     }
345   }
346
347   //================================================================================
348   /*!
349    * \brief Return elements which can include the point
350    */
351   //================================================================================
352
353   void ElementBndBoxTree::getElementsNearPoint( const gp_Pnt& point, TElemSeq& foundElems)
354   {
355     if ( getBox()->IsOut( point.XYZ() ))
356       return;
357
358     if ( isLeaf() )
359     {
360       for ( size_t i = 0; i < _elements.size(); ++i )
361         if ( !_elements[i]->IsOut( point.XYZ() ))
362           foundElems.insert( _elements[i]->_element );
363     }
364     else
365     {
366       for (int i = 0; i < 8; i++)
367         ((ElementBndBoxTree*) myChildren[i])->getElementsNearPoint( point, foundElems );
368     }
369   }
370
371   //================================================================================
372   /*!
373    * \brief Return elements which can be intersected by the line
374    */
375   //================================================================================
376
377   void ElementBndBoxTree::getElementsNearLine( const gp_Ax1& line, TElemSeq& foundElems )
378   {
379     if ( getBox()->IsOut( line ))
380       return;
381
382     if ( isLeaf() )
383     {
384       for ( size_t i = 0; i < _elements.size(); ++i )
385         if ( !_elements[i]->IsOut( line ) )
386           foundElems.insert( _elements[i]->_element );
387     }
388     else
389     {
390       for (int i = 0; i < 8; i++)
391         ((ElementBndBoxTree*) myChildren[i])->getElementsNearLine( line, foundElems );
392     }
393   }
394
395   //================================================================================
396   /*!
397    * \brief Return elements from leaves intersecting the sphere
398    */
399   //================================================================================
400
401   void ElementBndBoxTree::getElementsInSphere ( const gp_XYZ& center,
402                                                 const double  radius,
403                                                 TElemSeq&     foundElems)
404   {
405     if ( getBox()->IsOut( center, radius ))
406       return;
407
408     if ( isLeaf() )
409     {
410       for ( size_t i = 0; i < _elements.size(); ++i )
411         if ( !_elements[i]->IsOut( center, radius ))
412           foundElems.insert( _elements[i]->_element );
413     }
414     else
415     {
416       for (int i = 0; i < 8; i++)
417         ((ElementBndBoxTree*) myChildren[i])->getElementsInSphere( center, radius, foundElems );
418     }
419   }
420
421   //================================================================================
422   /*!
423    * \brief Return elements from leaves intersecting the box
424    */
425   //================================================================================
426
427   void ElementBndBoxTree::getElementsInBox( const Bnd_B3d& box,  TElemSeq& foundElems )
428   {
429     if ( getBox()->IsOut( box ))
430       return;
431
432     if ( isLeaf() )
433     {
434       for ( size_t i = 0; i < _elements.size(); ++i )
435         if ( !_elements[i]->IsOut( box ))
436           foundElems.insert( _elements[i]->_element );
437     }
438     else
439     {
440       for (int i = 0; i < 8; i++)
441         ((ElementBndBoxTree*) myChildren[i])->getElementsInBox( box, foundElems );
442     }
443   }
444
445   //================================================================================
446   /*!
447    * \brief Return a leaf including a point
448    */
449   //================================================================================
450
451   ElementBndBoxTree* ElementBndBoxTree::getLeafAtPoint( const gp_XYZ& point )
452   {
453     if ( getBox()->IsOut( point ))
454       return 0;
455
456     if ( isLeaf() )
457     {
458       return this;
459     }
460     else
461     {
462       for (int i = 0; i < 8; i++)
463         if ( ElementBndBoxTree* l = ((ElementBndBoxTree*) myChildren[i])->getLeafAtPoint( point ))
464           return l;
465     }
466     return 0;
467   }
468
469   //================================================================================
470   /*!
471    * \brief Construct the element box
472    */
473   //================================================================================
474
475   void ElementBndBoxTree::ElementBox::init(const SMDS_MeshElement* elem, double tolerance)
476   {
477     _element  = elem;
478     SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
479     while ( nIt->more() )
480       Add( SMESH_NodeXYZ( nIt->next() ));
481     Enlarge( tolerance );
482   }
483
484 } // namespace
485
486 //=======================================================================
487 /*!
488  * \brief Implementation of search for the elements by point and
489  *        of classification of point in 2D mesh
490  */
491 //=======================================================================
492
493 SMESH_ElementSearcher::~SMESH_ElementSearcher()
494 {
495 }
496
497 struct SMESH_ElementSearcherImpl: public SMESH_ElementSearcher
498 {
499   SMDS_Mesh*                        _mesh;
500   SMDS_ElemIteratorPtr              _meshPartIt;
501   ElementBndBoxTree*                _ebbTree      [SMDSAbs_NbElementTypes];
502   int                               _ebbTreeHeight[SMDSAbs_NbElementTypes];
503   SMESH_NodeSearcherImpl*           _nodeSearcher;
504   SMDSAbs_ElementType               _elementType;
505   double                            _tolerance;
506   bool                              _outerFacesFound;
507   std::set<const SMDS_MeshElement*> _outerFaces; // empty means "no internal faces at all"
508
509   SMESH_ElementSearcherImpl( SMDS_Mesh&           mesh,
510                              double               tol=-1,
511                              SMDS_ElemIteratorPtr elemIt=SMDS_ElemIteratorPtr())
512     : _mesh(&mesh),_meshPartIt(elemIt),_nodeSearcher(0),_tolerance(tol),_outerFacesFound(false)
513   {
514     for ( int i = 0; i < SMDSAbs_NbElementTypes; ++i )
515     {
516       _ebbTree[i] = NULL;
517       _ebbTreeHeight[i] = -1;
518     }
519     _elementType = SMDSAbs_All;
520   }
521   virtual ~SMESH_ElementSearcherImpl()
522   {
523     for ( int i = 0; i < SMDSAbs_NbElementTypes; ++i )
524     {
525       delete _ebbTree[i]; _ebbTree[i] = NULL;
526     }
527     if ( _nodeSearcher ) delete _nodeSearcher; _nodeSearcher = 0;
528   }
529   virtual int FindElementsByPoint(const gp_Pnt&                           point,
530                                   SMDSAbs_ElementType                     type,
531                                   std::vector< const SMDS_MeshElement* >& foundElements);
532   virtual TopAbs_State GetPointState(const gp_Pnt& point);
533   virtual const SMDS_MeshElement* FindClosestTo( const gp_Pnt&       point,
534                                                  SMDSAbs_ElementType type );
535
536   virtual void GetElementsNearLine( const gp_Ax1&                           line,
537                                     SMDSAbs_ElementType                     type,
538                                     std::vector< const SMDS_MeshElement* >& foundElems);
539   virtual void GetElementsInSphere( const gp_XYZ&                           center,
540                                     const double                            radius,
541                                     SMDSAbs_ElementType                     type,
542                                     std::vector< const SMDS_MeshElement* >& foundElems);
543   virtual void GetElementsInBox( const Bnd_B3d&                          box,
544                                  SMDSAbs_ElementType                     type,
545                                  std::vector< const SMDS_MeshElement* >& foundElems);
546   virtual gp_XYZ Project(const gp_Pnt&            point,
547                          SMDSAbs_ElementType      type,
548                          const SMDS_MeshElement** closestElem);
549   double getTolerance();
550   bool getIntersParamOnLine(const gp_Lin& line, const SMDS_MeshElement* face,
551                             const double tolerance, double & param);
552   void findOuterBoundary(const SMDS_MeshElement* anyOuterFace);
553   bool isOuterBoundary(const SMDS_MeshElement* face) const
554   {
555     return _outerFaces.empty() || _outerFaces.count(face);
556   }
557   int getTreeHeight()
558   {
559     if ( _ebbTreeHeight[ _elementType ] < 0 )
560       _ebbTreeHeight[ _elementType ] = _ebbTree[ _elementType ]->getHeight();
561     return _ebbTreeHeight[ _elementType ];
562   }
563
564   struct TInters //!< data of intersection of the line and the mesh face (used in GetPointState())
565   {
566     const SMDS_MeshElement* _face;
567     gp_Vec                  _faceNorm;
568     bool                    _coincides; //!< the line lays in face plane
569     TInters(const SMDS_MeshElement* face, const gp_Vec& faceNorm, bool coinc=false)
570       : _face(face), _faceNorm( faceNorm ), _coincides( coinc ) {}
571   };
572   struct TFaceLink //!< link and faces sharing it (used in findOuterBoundary())
573   {
574     SMESH_TLink      _link;
575     TIDSortedElemSet _faces;
576     TFaceLink( const SMDS_MeshNode* n1, const SMDS_MeshNode* n2, const SMDS_MeshElement* face)
577       : _link( n1, n2 ), _faces( &face, &face + 1) {}
578   };
579 };
580
581 ostream& operator<< (ostream& out, const SMESH_ElementSearcherImpl::TInters& i)
582 {
583   return out << "TInters(face=" << ( i._face ? i._face->GetID() : 0)
584              << ", _coincides="<<i._coincides << ")";
585 }
586
587 //=======================================================================
588 /*!
589  * \brief define tolerance for search
590  */
591 //=======================================================================
592
593 double SMESH_ElementSearcherImpl::getTolerance()
594 {
595   if ( _tolerance < 0 )
596   {
597     const SMDS_MeshInfo& meshInfo = _mesh->GetMeshInfo();
598
599     _tolerance = 0;
600     if ( _nodeSearcher && meshInfo.NbNodes() > 1 )
601     {
602       double boxSize = _nodeSearcher->getTree()->maxSize();
603       _tolerance = 1e-8 * boxSize/* / meshInfo.NbNodes()*/;
604     }
605     else if ( _ebbTree[_elementType] && meshInfo.NbElements() > 0 )
606     {
607       double boxSize = _ebbTree[_elementType]->maxSize();
608       _tolerance = 1e-8 * boxSize/* / meshInfo.NbElements()*/;
609     }
610     if ( _tolerance == 0 )
611     {
612       // define tolerance by size of a most complex element
613       int complexType = SMDSAbs_Volume;
614       while ( complexType > SMDSAbs_All &&
615               meshInfo.NbElements( SMDSAbs_ElementType( complexType )) < 1 )
616         --complexType;
617       if ( complexType == SMDSAbs_All ) return 0; // empty mesh
618       double elemSize;
619       if ( complexType == int( SMDSAbs_Node ))
620       {
621         SMDS_NodeIteratorPtr nodeIt = _mesh->nodesIterator();
622         elemSize = 1;
623         if ( meshInfo.NbNodes() > 2 )
624           elemSize = SMESH_TNodeXYZ( nodeIt->next() ).Distance( nodeIt->next() );
625       }
626       else
627       {
628         SMDS_ElemIteratorPtr  elemIt = _mesh->elementsIterator( SMDSAbs_ElementType( complexType ));
629         const SMDS_MeshElement* elem = elemIt->next();
630         SMDS_ElemIteratorPtr  nodeIt = elem->nodesIterator();
631         SMESH_TNodeXYZ n1( nodeIt->next() );
632         elemSize = 0;
633         while ( nodeIt->more() )
634         {
635           double dist = n1.Distance( static_cast<const SMDS_MeshNode*>( nodeIt->next() ));
636           elemSize = std::max( dist, elemSize );
637         }
638       }
639       _tolerance = 1e-4 * elemSize;
640     }
641   }
642   return _tolerance;
643 }
644
645 //================================================================================
646 /*!
647  * \brief Find intersection of the line and an edge of face and return parameter on line
648  */
649 //================================================================================
650
651 bool SMESH_ElementSearcherImpl::getIntersParamOnLine(const gp_Lin&           line,
652                                                      const SMDS_MeshElement* face,
653                                                      const double            tol,
654                                                      double &                param)
655 {
656   int nbInts = 0;
657   param = 0;
658
659   GeomAPI_ExtremaCurveCurve anExtCC;
660   Handle(Geom_Curve) lineCurve = new Geom_Line( line );
661
662   int nbNodes = face->IsQuadratic() ? face->NbNodes()/2 : face->NbNodes();
663   for ( int i = 0; i < nbNodes && nbInts < 2; ++i )
664   {
665     GC_MakeSegment edge( SMESH_TNodeXYZ( face->GetNode( i )),
666                          SMESH_TNodeXYZ( face->GetNode( (i+1)%nbNodes) ));
667     anExtCC.Init( lineCurve, edge.Value() );
668     if ( anExtCC.NbExtrema() > 0 && anExtCC.LowerDistance() <= tol)
669     {
670       Standard_Real pl, pe;
671       anExtCC.LowerDistanceParameters( pl, pe );
672       param += pl;
673       if ( ++nbInts == 2 )
674         break;
675     }
676   }
677   if ( nbInts > 0 ) param /= nbInts;
678   return nbInts > 0;
679 }
680 //================================================================================
681 /*!
682  * \brief Find all faces belonging to the outer boundary of mesh
683  */
684 //================================================================================
685
686 void SMESH_ElementSearcherImpl::findOuterBoundary(const SMDS_MeshElement* outerFace)
687 {
688   if ( _outerFacesFound ) return;
689
690   // Collect all outer faces by passing from one outer face to another via their links
691   // and BTW find out if there are internal faces at all.
692
693   // checked links and links where outer boundary meets internal one
694   std::set< SMESH_TLink > visitedLinks, seamLinks;
695
696   // links to treat with already visited faces sharing them
697   std::list < TFaceLink > startLinks;
698
699   // load startLinks with the first outerFace
700   startLinks.push_back( TFaceLink( outerFace->GetNode(0), outerFace->GetNode(1), outerFace));
701   _outerFaces.insert( outerFace );
702
703   TIDSortedElemSet emptySet;
704   while ( !startLinks.empty() )
705   {
706     const SMESH_TLink& link  = startLinks.front()._link;
707     TIDSortedElemSet&  faces = startLinks.front()._faces;
708
709     outerFace = *faces.begin();
710     // find other faces sharing the link
711     const SMDS_MeshElement* f;
712     while (( f = SMESH_MeshAlgos::FindFaceInSet(link.node1(), link.node2(), emptySet, faces )))
713       faces.insert( f );
714
715     // select another outer face among the found
716     const SMDS_MeshElement* outerFace2 = 0;
717     if ( faces.size() == 2 )
718     {
719       outerFace2 = (outerFace == *faces.begin() ? *faces.rbegin() : *faces.begin());
720     }
721     else if ( faces.size() > 2 )
722     {
723       seamLinks.insert( link );
724
725       // link direction within the outerFace
726       gp_Vec n1n2( SMESH_TNodeXYZ( link.node1()),
727                    SMESH_TNodeXYZ( link.node2()));
728       int i1 = outerFace->GetNodeIndex( link.node1() );
729       int i2 = outerFace->GetNodeIndex( link.node2() );
730       bool rev = ( abs(i2-i1) == 1 ? i1 > i2 : i2 > i1 );
731       if ( rev ) n1n2.Reverse();
732       // outerFace normal
733       gp_XYZ ofNorm, fNorm;
734       if ( SMESH_MeshAlgos::FaceNormal( outerFace, ofNorm, /*normalized=*/false ))
735       {
736         // direction from the link inside outerFace
737         gp_Vec dirInOF = gp_Vec( ofNorm ) ^ n1n2;
738         // sort all other faces by angle with the dirInOF
739         std::map< double, const SMDS_MeshElement* > angle2Face;
740         std::set< const SMDS_MeshElement*, TIDCompare >::const_iterator face = faces.begin();
741         for ( ; face != faces.end(); ++face )
742         {
743           if ( *face == outerFace ) continue;
744           if ( !SMESH_MeshAlgos::FaceNormal( *face, fNorm, /*normalized=*/false ))
745             continue;
746           gp_Vec dirInF = gp_Vec( fNorm ) ^ n1n2;
747           double angle = dirInOF.AngleWithRef( dirInF, n1n2 );
748           if ( angle < 0 ) angle += 2. * M_PI;
749           angle2Face.insert( std::make_pair( angle, *face ));
750         }
751         if ( !angle2Face.empty() )
752           outerFace2 = angle2Face.begin()->second;
753       }
754     }
755     // store the found outer face and add its links to continue searching from
756     if ( outerFace2 )
757     {
758       _outerFaces.insert( outerFace2 );
759       int nbNodes = outerFace2->NbCornerNodes();
760       for ( int i = 0; i < nbNodes; ++i )
761       {
762         SMESH_TLink link2( outerFace2->GetNode(i), outerFace2->GetNode((i+1)%nbNodes));
763         if ( visitedLinks.insert( link2 ).second )
764           startLinks.push_back( TFaceLink( link2.node1(), link2.node2(), outerFace2 ));
765       }
766     }
767     startLinks.pop_front();
768   }
769   _outerFacesFound = true;
770
771   if ( !seamLinks.empty() )
772   {
773     // There are internal boundaries touching the outher one,
774     // find all faces of internal boundaries in order to find
775     // faces of boundaries of holes, if any.
776
777   }
778   else
779   {
780     _outerFaces.clear();
781   }
782 }
783
784 //=======================================================================
785 /*!
786  * \brief Find elements of given type where the given point is IN or ON.
787  *        Returns nb of found elements and elements them-selves.
788  *
789  * 'ALL' type means elements of any type excluding nodes, balls and 0D elements
790  */
791 //=======================================================================
792
793 int SMESH_ElementSearcherImpl::
794 FindElementsByPoint(const gp_Pnt&                           point,
795                     SMDSAbs_ElementType                     type,
796                     std::vector< const SMDS_MeshElement* >& foundElements)
797 {
798   foundElements.clear();
799   _elementType = type;
800
801   double tolerance = getTolerance();
802
803   // =================================================================================
804   if ( type == SMDSAbs_Node || type == SMDSAbs_0DElement || type == SMDSAbs_Ball)
805   {
806     if ( !_nodeSearcher )
807     {
808       if ( _meshPartIt )
809         _nodeSearcher = new SMESH_NodeSearcherImpl( 0, _meshPartIt );
810       else
811         _nodeSearcher = new SMESH_NodeSearcherImpl( _mesh );
812     }
813     std::vector< const SMDS_MeshNode* > foundNodes;
814     _nodeSearcher->FindNearPoint( point, tolerance, foundNodes );
815
816     if ( type == SMDSAbs_Node )
817     {
818       foundElements.assign( foundNodes.begin(), foundNodes.end() );
819     }
820     else
821     {
822       for ( size_t i = 0; i < foundNodes.size(); ++i )
823       {
824         SMDS_ElemIteratorPtr elemIt = foundNodes[i]->GetInverseElementIterator( type );
825         while ( elemIt->more() )
826           foundElements.push_back( elemIt->next() );
827       }
828     }
829   }
830   // =================================================================================
831   else // elements more complex than 0D
832   {
833     if ( !_ebbTree[type] )
834     {
835       _ebbTree[_elementType] = new ElementBndBoxTree( *_mesh, type, _meshPartIt, tolerance );
836     }
837     ElementBndBoxTree::TElemSeq suspectElems;
838     _ebbTree[ type ]->getElementsNearPoint( point, suspectElems );
839     ElementBndBoxTree::TElemSeq::iterator elem = suspectElems.begin();
840     for ( ; elem != suspectElems.end(); ++elem )
841       if ( !SMESH_MeshAlgos::IsOut( *elem, point, tolerance ))
842         foundElements.push_back( *elem );
843   }
844   return foundElements.size();
845 }
846
847 //=======================================================================
848 /*!
849  * \brief Find an element of given type most close to the given point
850  *
851  * WARNING: Only face search is implemeneted so far
852  */
853 //=======================================================================
854
855 const SMDS_MeshElement*
856 SMESH_ElementSearcherImpl::FindClosestTo( const gp_Pnt&       point,
857                                           SMDSAbs_ElementType type )
858 {
859   const SMDS_MeshElement* closestElem = 0;
860   _elementType = type;
861
862   if ( type == SMDSAbs_Face ||
863        type == SMDSAbs_Volume ||
864        type == SMDSAbs_Edge )
865   {
866     ElementBndBoxTree*& ebbTree = _ebbTree[ type ];
867     if ( !ebbTree )
868       ebbTree = new ElementBndBoxTree( *_mesh, type, _meshPartIt );
869
870     ElementBndBoxTree::TElemSeq suspectElems;
871     ebbTree->getElementsNearPoint( point, suspectElems );
872
873     if ( suspectElems.empty() && ebbTree->maxSize() > 0 )
874     {
875       gp_Pnt boxCenter = 0.5 * ( ebbTree->getBox()->CornerMin() +
876                                  ebbTree->getBox()->CornerMax() );
877       double radius = -1;
878       if ( ebbTree->getBox()->IsOut( point.XYZ() ))
879         radius = point.Distance( boxCenter ) - 0.5 * ebbTree->maxSize();
880       if ( radius < 0 )
881         radius = ebbTree->maxSize() / pow( 2., getTreeHeight()) / 2;
882       while ( suspectElems.empty() && radius < 1e100 )
883       {
884         ebbTree->getElementsInSphere( point.XYZ(), radius, suspectElems );
885         radius *= 1.1;
886       }
887     }
888     double minDist = std::numeric_limits<double>::max();
889     std::multimap< double, const SMDS_MeshElement* > dist2face;
890     ElementBndBoxTree::TElemSeq::iterator elem = suspectElems.begin();
891     for ( ; elem != suspectElems.end(); ++elem )
892     {
893       double dist = SMESH_MeshAlgos::GetDistance( *elem, point );
894       if ( dist < minDist + 1e-10)
895       {
896         minDist = dist;
897         dist2face.insert( dist2face.begin(), std::make_pair( dist, *elem ));
898       }
899     }
900     if ( !dist2face.empty() )
901     {
902       std::multimap< double, const SMDS_MeshElement* >::iterator d2f = dist2face.begin();
903       closestElem = d2f->second;
904       // if there are several elements at the same distance, select one
905       // with GC closest to the point
906       typedef SMDS_StdIterator< SMESH_TNodeXYZ, SMDS_ElemIteratorPtr > TXyzIterator;
907       double minDistToGC = 0;
908       for ( ++d2f; d2f != dist2face.end() && fabs( d2f->first - minDist ) < 1e-10; ++d2f )
909       {
910         if ( minDistToGC == 0 )
911         {
912           gp_XYZ gc(0,0,0);
913           gc = accumulate( TXyzIterator(closestElem->nodesIterator()),
914                            TXyzIterator(), gc ) / closestElem->NbNodes();
915           minDistToGC = point.SquareDistance( gc );
916         }
917         gp_XYZ gc(0,0,0);
918         gc = accumulate( TXyzIterator( d2f->second->nodesIterator()),
919                          TXyzIterator(), gc ) / d2f->second->NbNodes();
920         double d = point.SquareDistance( gc );
921         if ( d < minDistToGC )
922         {
923           minDistToGC = d;
924           closestElem = d2f->second;
925         }
926       }
927       // cout << "FindClosestTo( " <<point.X()<<", "<<point.Y()<<", "<<point.Z()<<" ) FACE "
928       //      <<closestElem->GetID() << " DIST " << minDist << endl;
929     }
930   }
931   else
932   {
933     // NOT IMPLEMENTED SO FAR
934   }
935   return closestElem;
936 }
937
938
939 //================================================================================
940 /*!
941  * \brief Classify the given point in the closed 2D mesh
942  */
943 //================================================================================
944
945 TopAbs_State SMESH_ElementSearcherImpl::GetPointState(const gp_Pnt& point)
946 {
947   _elementType = SMDSAbs_Face;
948
949   double tolerance = getTolerance();
950
951   ElementBndBoxTree*& ebbTree = _ebbTree[ SMDSAbs_Face ];
952   if ( !ebbTree )
953     ebbTree = new ElementBndBoxTree( *_mesh, _elementType, _meshPartIt );
954
955   // Algo: analyse transition of a line starting at the point through mesh boundary;
956   // try three lines parallel to axis of the coordinate system and perform rough
957   // analysis. If solution is not clear perform thorough analysis.
958
959   const int nbAxes = 3;
960   gp_Dir axisDir[ nbAxes ] = { gp::DX(), gp::DY(), gp::DZ() };
961   std::map< double, TInters >   paramOnLine2TInters[ nbAxes ];
962   std::list< TInters > tangentInters[ nbAxes ]; // of faces whose plane includes the line
963   std::multimap< int, int > nbInt2Axis; // to find the simplest case
964   for ( int axis = 0; axis < nbAxes; ++axis )
965   {
966     gp_Ax1 lineAxis( point, axisDir[axis]);
967     gp_Lin line    ( lineAxis );
968
969     ElementBndBoxTree::TElemSeq suspectFaces; // faces possibly intersecting the line
970     ebbTree->getElementsNearLine( lineAxis, suspectFaces );
971
972     // Intersect faces with the line
973
974     std::map< double, TInters > & u2inters = paramOnLine2TInters[ axis ];
975     ElementBndBoxTree::TElemSeq::iterator face = suspectFaces.begin();
976     for ( ; face != suspectFaces.end(); ++face )
977     {
978       // get face plane
979       gp_XYZ fNorm;
980       if ( !SMESH_MeshAlgos::FaceNormal( *face, fNorm, /*normalized=*/false)) continue;
981       gp_Pln facePlane( SMESH_TNodeXYZ( (*face)->GetNode(0)), fNorm );
982
983       // perform intersection
984       IntAna_IntConicQuad intersection( line, IntAna_Quadric( facePlane ));
985       if ( !intersection.IsDone() )
986         continue;
987       if ( intersection.IsInQuadric() )
988       {
989         tangentInters[ axis ].push_back( TInters( *face, fNorm, true ));
990       }
991       else if ( ! intersection.IsParallel() && intersection.NbPoints() > 0 )
992       {
993         double tol = 1e-4 * Sqrt( fNorm.Modulus() );
994         gp_Pnt intersectionPoint = intersection.Point(1);
995         if ( !SMESH_MeshAlgos::IsOut( *face, intersectionPoint, tol ))
996           u2inters.insert( std::make_pair( intersection.ParamOnConic(1), TInters( *face, fNorm )));
997       }
998     }
999     // Analyse intersections roughly
1000
1001     int nbInter = u2inters.size();
1002     if ( nbInter == 0 )
1003       return TopAbs_OUT;
1004
1005     double f = u2inters.begin()->first, l = u2inters.rbegin()->first;
1006     if ( nbInter == 1 ) // not closed mesh
1007       return fabs( f ) < tolerance ? TopAbs_ON : TopAbs_UNKNOWN;
1008
1009     if ( fabs( f ) < tolerance || fabs( l ) < tolerance )
1010       return TopAbs_ON;
1011
1012     if ( (f<0) == (l<0) )
1013       return TopAbs_OUT;
1014
1015     int nbIntBeforePoint = std::distance( u2inters.begin(), u2inters.lower_bound(0));
1016     int nbIntAfterPoint  = nbInter - nbIntBeforePoint;
1017     if ( nbIntBeforePoint == 1 || nbIntAfterPoint == 1 )
1018       return TopAbs_IN;
1019
1020     nbInt2Axis.insert( std::make_pair( std::min( nbIntBeforePoint, nbIntAfterPoint ), axis ));
1021
1022     if ( _outerFacesFound ) break; // pass to thorough analysis
1023
1024   } // three attempts - loop on CS axes
1025
1026   // Analyse intersections thoroughly.
1027   // We make two loops maximum, on the first one we only exclude touching intersections,
1028   // on the second, if situation is still unclear, we gather and use information on
1029   // position of faces (internal or outer). If faces position is already gathered,
1030   // we make the second loop right away.
1031
1032   for ( int hasPositionInfo = _outerFacesFound; hasPositionInfo < 2; ++hasPositionInfo )
1033   {
1034     std::multimap< int, int >::const_iterator nb_axis = nbInt2Axis.begin();
1035     for ( ; nb_axis != nbInt2Axis.end(); ++nb_axis )
1036     {
1037       int axis = nb_axis->second;
1038       std::map< double, TInters > & u2inters = paramOnLine2TInters[ axis ];
1039
1040       gp_Ax1 lineAxis( point, axisDir[axis]);
1041       gp_Lin line    ( lineAxis );
1042
1043       // add tangent intersections to u2inters
1044       double param;
1045       std::list< TInters >::const_iterator tgtInt = tangentInters[ axis ].begin();
1046       for ( ; tgtInt != tangentInters[ axis ].end(); ++tgtInt )
1047         if ( getIntersParamOnLine( line, tgtInt->_face, tolerance, param ))
1048           u2inters.insert( std::make_pair( param, *tgtInt ));
1049       tangentInters[ axis ].clear();
1050
1051       // Count intersections before and after the point excluding touching ones.
1052       // If hasPositionInfo we count intersections of outer boundary only
1053
1054       int nbIntBeforePoint = 0, nbIntAfterPoint = 0;
1055       double f = std::numeric_limits<double>::max(), l = -std::numeric_limits<double>::max();
1056       std::map< double, TInters >::iterator u_int1 = u2inters.begin(), u_int2 = u_int1;
1057       bool ok = ! u_int1->second._coincides;
1058       while ( ok && u_int1 != u2inters.end() )
1059       {
1060         double u = u_int1->first;
1061         bool touchingInt = false;
1062         if ( ++u_int2 != u2inters.end() )
1063         {
1064           // skip intersections at the same point (if the line passes through edge or node)
1065           int nbSamePnt = 0;
1066           while ( u_int2 != u2inters.end() && fabs( u_int2->first - u ) < tolerance )
1067           {
1068             ++nbSamePnt;
1069             ++u_int2;
1070           }
1071
1072           // skip tangent intersections
1073           int nbTgt = 0;
1074           if ( u_int2 != u2inters.end() )
1075           {
1076             const SMDS_MeshElement* prevFace = u_int1->second._face;
1077             while ( ok && u_int2->second._coincides )
1078             {
1079               if ( SMESH_MeshAlgos::GetCommonNodes(prevFace , u_int2->second._face).empty() )
1080                 ok = false;
1081               else
1082               {
1083                 nbTgt++;
1084                 u_int2++;
1085                 ok = ( u_int2 != u2inters.end() );
1086               }
1087             }
1088           }
1089           if ( !ok ) break;
1090
1091           // skip intersections at the same point after tangent intersections
1092           if ( nbTgt > 0 )
1093           {
1094             double u2 = u_int2->first;
1095             ++u_int2;
1096             while ( u_int2 != u2inters.end() && fabs( u_int2->first - u2 ) < tolerance )
1097             {
1098               ++nbSamePnt;
1099               ++u_int2;
1100             }
1101           }
1102           // decide if we skipped a touching intersection
1103           if ( nbSamePnt + nbTgt > 0 )
1104           {
1105             double minDot = std::numeric_limits<double>::max(), maxDot = -minDot;
1106             std::map< double, TInters >::iterator u_int = u_int1;
1107             for ( ; u_int != u_int2; ++u_int )
1108             {
1109               if ( u_int->second._coincides ) continue;
1110               double dot = u_int->second._faceNorm * line.Direction();
1111               if ( dot > maxDot ) maxDot = dot;
1112               if ( dot < minDot ) minDot = dot;
1113             }
1114             touchingInt = ( minDot*maxDot < 0 );
1115           }
1116         }
1117         if ( !touchingInt )
1118         {
1119           if ( !hasPositionInfo || isOuterBoundary( u_int1->second._face ))
1120           {
1121             if ( u < 0 )
1122               ++nbIntBeforePoint;
1123             else
1124               ++nbIntAfterPoint;
1125           }
1126           if ( u < f ) f = u;
1127           if ( u > l ) l = u;
1128         }
1129
1130         u_int1 = u_int2; // to next intersection
1131
1132       } // loop on intersections with one line
1133
1134       if ( ok )
1135       {
1136         if ( fabs( f ) < tolerance || fabs( l ) < tolerance )
1137           return TopAbs_ON;
1138
1139         if ( nbIntBeforePoint == 0  || nbIntAfterPoint == 0)
1140           return TopAbs_OUT;
1141
1142         if ( nbIntBeforePoint + nbIntAfterPoint == 1 ) // not closed mesh
1143           return fabs( f ) < tolerance ? TopAbs_ON : TopAbs_UNKNOWN;
1144
1145         if ( nbIntBeforePoint == 1 || nbIntAfterPoint == 1 )
1146           return TopAbs_IN;
1147
1148         if ( (f<0) == (l<0) )
1149           return TopAbs_OUT;
1150
1151         if ( hasPositionInfo )
1152           return nbIntBeforePoint % 2 ? TopAbs_IN : TopAbs_OUT;
1153       }
1154     } // loop on intersections of the tree lines - thorough analysis
1155
1156     if ( !hasPositionInfo )
1157     {
1158       // gather info on faces position - is face in the outer boundary or not
1159       std::map< double, TInters > & u2inters = paramOnLine2TInters[ 0 ];
1160       findOuterBoundary( u2inters.begin()->second._face );
1161     }
1162
1163   } // two attempts - with and w/o faces position info in the mesh
1164
1165   return TopAbs_UNKNOWN;
1166 }
1167
1168 //=======================================================================
1169 /*!
1170  * \brief Return elements possibly intersecting the line
1171  */
1172 //=======================================================================
1173
1174 void SMESH_ElementSearcherImpl::
1175 GetElementsNearLine( const gp_Ax1&                           line,
1176                      SMDSAbs_ElementType                     type,
1177                      std::vector< const SMDS_MeshElement* >& foundElems)
1178 {
1179   _elementType = type;
1180   ElementBndBoxTree*& ebbTree = _ebbTree[ type ];
1181   if ( !ebbTree )
1182     ebbTree = new ElementBndBoxTree( *_mesh, _elementType, _meshPartIt );
1183
1184   ElementBndBoxTree::TElemSeq elems;
1185   ebbTree->getElementsNearLine( line, elems );
1186
1187   foundElems.insert( foundElems.end(), elems.begin(), elems.end() );
1188 }
1189
1190 //=======================================================================
1191 /*
1192  * Return elements whose bounding box intersects a sphere
1193  */
1194 //=======================================================================
1195
1196 void SMESH_ElementSearcherImpl::
1197 GetElementsInSphere( const gp_XYZ&                           center,
1198                      const double                            radius,
1199                      SMDSAbs_ElementType                     type,
1200                      std::vector< const SMDS_MeshElement* >& foundElems)
1201 {
1202   _elementType = type;
1203   ElementBndBoxTree*& ebbTree = _ebbTree[ type ];
1204   if ( !ebbTree )
1205     ebbTree = new ElementBndBoxTree( *_mesh, _elementType, _meshPartIt );
1206
1207   ElementBndBoxTree::TElemSeq elems;
1208   ebbTree->getElementsInSphere( center, radius, elems );
1209
1210   foundElems.insert( foundElems.end(), elems.begin(), elems.end() );
1211 }
1212
1213 //=======================================================================
1214 /*
1215  * Return elements whose bounding box intersects a given bounding box
1216  */
1217 //=======================================================================
1218
1219 void SMESH_ElementSearcherImpl::
1220 GetElementsInBox( const Bnd_B3d&                          box,
1221                   SMDSAbs_ElementType                     type,
1222                   std::vector< const SMDS_MeshElement* >& foundElems)
1223 {
1224   _elementType = type;
1225   ElementBndBoxTree*& ebbTree = _ebbTree[ type ];
1226   if ( !ebbTree )
1227     ebbTree = new ElementBndBoxTree( *_mesh, _elementType, _meshPartIt, getTolerance() );
1228
1229   ElementBndBoxTree::TElemSeq elems;
1230   ebbTree->getElementsInBox( box, elems );
1231
1232   foundElems.insert( foundElems.end(), elems.begin(), elems.end() );
1233 }
1234
1235 //=======================================================================
1236 /*
1237  * \brief Return a projection of a given point to a mesh.
1238  *        Optionally return the closest element
1239  */
1240 //=======================================================================
1241
1242 gp_XYZ SMESH_ElementSearcherImpl::Project(const gp_Pnt&            point,
1243                                           SMDSAbs_ElementType      type,
1244                                           const SMDS_MeshElement** closestElem)
1245 {
1246   _elementType = type;
1247   if ( _mesh->GetMeshInfo().NbElements( _elementType ) == 0 )
1248     throw SALOME_Exception( LOCALIZED( "No elements of given type in the mesh" ));
1249
1250   ElementBndBoxTree*& ebbTree = _ebbTree[ _elementType ];
1251   if ( !ebbTree )
1252     ebbTree = new ElementBndBoxTree( *_mesh, _elementType, _meshPartIt );
1253
1254   gp_XYZ p = point.XYZ();
1255   ElementBndBoxTree* ebbLeaf = ebbTree->getLeafAtPoint( p );
1256   const Bnd_B3d* box = ebbLeaf ? ebbLeaf->getBox() : ebbTree->getBox();
1257   gp_XYZ pMin = box->CornerMin(), pMax = box->CornerMax();
1258   double radius = Precision::Infinite();
1259   if ( ebbLeaf || !box->IsOut( p ))
1260   {
1261     for ( int i = 1; i <= 3; ++i )
1262     {
1263       double d = 0.5 * ( pMax.Coord(i) - pMin.Coord(i) );
1264       if ( d > Precision::Confusion() )
1265         radius = Min( d, radius );
1266     }
1267     if ( !ebbLeaf )
1268       radius /= ebbTree->getHeight( /*full=*/true );
1269   }
1270   else // p outside of box
1271   {
1272     for ( int i = 1; i <= 3; ++i )
1273     {
1274       double d = 0;
1275       if ( point.Coord(i) < pMin.Coord(i) )
1276         d = pMin.Coord(i) - point.Coord(i);
1277       else if ( point.Coord(i) > pMax.Coord(i) )
1278         d = point.Coord(i) - pMax.Coord(i);
1279       if ( d > Precision::Confusion() )
1280         radius = Min( d, radius );
1281     }
1282   }
1283
1284   ElementBndBoxTree::TElemSeq elems;
1285   ebbTree->getElementsInSphere( p, radius, elems );
1286   while ( elems.empty() && radius < 1e100 )
1287   {
1288     radius *= 1.1;
1289     ebbTree->getElementsInSphere( p, radius, elems );
1290   }
1291   gp_XYZ proj, bestProj;
1292   const SMDS_MeshElement* elem = 0;
1293   double minDist = Precision::Infinite();
1294   ElementBndBoxTree::TElemSeq::iterator e = elems.begin();
1295   for ( ; e != elems.end(); ++e )
1296   {
1297     double d = SMESH_MeshAlgos::GetDistance( *e, point, &proj );
1298     if ( d < minDist )
1299     {
1300       bestProj = proj;
1301       elem = *e;
1302       minDist = d;
1303     }
1304   }
1305   if ( closestElem ) *closestElem = elem;
1306
1307   return bestProj;
1308 }
1309
1310 //=======================================================================
1311 /*!
1312  * \brief Return true if the point is IN or ON of the element
1313  */
1314 //=======================================================================
1315
1316 bool SMESH_MeshAlgos::IsOut( const SMDS_MeshElement* element, const gp_Pnt& point, double tol )
1317 {
1318   if ( element->GetType() == SMDSAbs_Volume)
1319   {
1320     return SMDS_VolumeTool( element ).IsOut( point.X(), point.Y(), point.Z(), tol );
1321   }
1322
1323   // get ordered nodes
1324
1325   std::vector< SMESH_TNodeXYZ > xyz; xyz.reserve( element->NbNodes()+1 );
1326
1327   SMDS_NodeIteratorPtr nodeIt = element->interlacedNodesIterator();
1328   for ( int i = 0; nodeIt->more(); ++i )
1329     xyz.push_back( SMESH_TNodeXYZ( nodeIt->next() ));
1330
1331   int i, nbNodes = (int) xyz.size(); // central node of biquadratic is missing
1332
1333   if ( element->GetType() == SMDSAbs_Face ) // --------------------------------------------------
1334   {
1335     // compute face normal
1336     gp_Vec faceNorm(0,0,0);
1337     xyz.push_back( xyz.front() );
1338     for ( i = 0; i < nbNodes; ++i )
1339     {
1340       gp_Vec edge1( xyz[i+1], xyz[i]);
1341       gp_Vec edge2( xyz[i+1], xyz[(i+2)%nbNodes] );
1342       faceNorm += edge1 ^ edge2;
1343     }
1344     double fNormSize = faceNorm.Magnitude();
1345     if ( fNormSize <= tol )
1346     {
1347       // degenerated face: point is out if it is out of all face edges
1348       for ( i = 0; i < nbNodes; ++i )
1349       {
1350         SMDS_LinearEdge edge( xyz[i]._node, xyz[i+1]._node );
1351         if ( !IsOut( &edge, point, tol ))
1352           return false;
1353       }
1354       return true;
1355     }
1356     faceNorm /= fNormSize;
1357
1358     // check if the point lays on face plane
1359     gp_Vec n2p( xyz[0], point );
1360     double dot = n2p * faceNorm;
1361     if ( Abs( dot ) > tol ) // not on face plane
1362     {
1363       bool isOut = true;
1364       if ( nbNodes > 3 ) // maybe the face is not planar
1365       {
1366         double elemThick = 0;
1367         for ( i = 1; i < nbNodes; ++i )
1368         {
1369           gp_Vec n2n( xyz[0], xyz[i] );
1370           elemThick = Max( elemThick, Abs( n2n * faceNorm ));
1371         }
1372         isOut = Abs( dot ) > elemThick + tol;
1373       }
1374       if ( isOut )
1375         return isOut;
1376     }
1377
1378     // check if point is out of face boundary:
1379     // define it by closest transition of a ray point->infinity through face boundary
1380     // on the face plane.
1381     // First, find normal of a plane perpendicular to face plane, to be used as a cutting tool
1382     // to find intersections of the ray with the boundary.
1383     gp_Vec ray = n2p;
1384     gp_Vec plnNorm = ray ^ faceNorm;
1385     double n2pSize = plnNorm.Magnitude();
1386     if ( n2pSize <= tol ) return false; // point coincides with the first node
1387     if ( n2pSize * n2pSize > fNormSize * 100 ) return true; // point is very far
1388     plnNorm /= n2pSize;
1389     // for each node of the face, compute its signed distance to the cutting plane
1390     std::vector<double> dist( nbNodes + 1);
1391     for ( i = 0; i < nbNodes; ++i )
1392     {
1393       gp_Vec n2p( xyz[i], point );
1394       dist[i] = n2p * plnNorm;
1395     }
1396     dist.back() = dist.front();
1397     // find the closest intersection
1398     int    iClosest = -1;
1399     double rClosest = 0, distClosest = 1e100;
1400     gp_Pnt pClosest;
1401     for ( i = 0; i < nbNodes; ++i )
1402     {
1403       double r;
1404       if ( fabs( dist[i] ) < tol )
1405         r = 0.;
1406       else if ( fabs( dist[i+1]) < tol )
1407         r = 1.;
1408       else if ( dist[i] * dist[i+1] < 0 )
1409         r = dist[i] / ( dist[i] - dist[i+1] );
1410       else
1411         continue; // no intersection
1412       gp_Pnt pInt = xyz[i] * (1.-r) + xyz[i+1] * r;
1413       gp_Vec p2int( point, pInt);
1414       double intDist = p2int.SquareMagnitude();
1415       if ( intDist < distClosest )
1416       {
1417         iClosest = i;
1418         rClosest = r;
1419         pClosest = pInt;
1420         distClosest = intDist;
1421       }
1422     }
1423     if ( iClosest < 0 )
1424       return true; // no intesections - out
1425
1426     // analyse transition
1427     gp_Vec edge( xyz[iClosest], xyz[iClosest+1] );
1428     gp_Vec edgeNorm = -( edge ^ faceNorm ); // normal to intersected edge pointing out of face
1429     gp_Vec p2int ( point, pClosest );
1430     bool out = (edgeNorm * p2int) < -tol;
1431     if ( rClosest > 0. && rClosest < 1. ) // not node intersection
1432       return out;
1433
1434     // the ray passes through a face node; analyze transition through an adjacent edge
1435     gp_Pnt p1 = xyz[ (rClosest == 0.) ? ((iClosest+nbNodes-1) % nbNodes) : (iClosest+1) ];
1436     gp_Pnt p2 = xyz[ (rClosest == 0.) ? iClosest : ((iClosest+2) % nbNodes) ];
1437     gp_Vec edgeAdjacent( p1, p2 );
1438     gp_Vec edgeNorm2 = -( edgeAdjacent ^ faceNorm );
1439     bool out2 = (edgeNorm2 * p2int) < -tol;
1440
1441     bool covexCorner = ( edgeNorm * edgeAdjacent * (rClosest==1. ? 1. : -1.)) < 0;
1442     return covexCorner ? (out || out2) : (out && out2);
1443   }
1444
1445   if ( element->GetType() == SMDSAbs_Edge ) // --------------------------------------------------
1446   {
1447     // point is out of edge if it is NOT ON any straight part of edge
1448     // (we consider quadratic edge as being composed of two straight parts)
1449     for ( i = 1; i < nbNodes; ++i )
1450     {
1451       gp_Vec edge( xyz[i-1], xyz[i] );
1452       gp_Vec n1p ( xyz[i-1], point  );
1453       double u = ( edge * n1p ) / edge.SquareMagnitude(); // param [0,1] on the edge
1454       if ( u <= 0. ) {
1455         if ( n1p.SquareMagnitude() < tol * tol )
1456           return false;
1457         continue;
1458       }
1459       if ( u >= 1. ) {
1460         if ( point.SquareDistance( xyz[i] ) < tol * tol )
1461           return false;
1462         continue;
1463       }
1464       gp_XYZ proj = ( 1. - u ) * xyz[i-1] + u * xyz[i]; // projection of the point on the edge
1465       double dist2 = point.SquareDistance( proj );
1466       if ( dist2 > tol * tol )
1467         continue;
1468       return false; // point is ON this part
1469     }
1470     return true;
1471   }
1472
1473   // Node or 0D element -------------------------------------------------------------------------
1474   {
1475     gp_Vec n2p ( xyz[0], point );
1476     return n2p.SquareMagnitude() > tol * tol;
1477   }
1478   return true;
1479 }
1480
1481 //=======================================================================
1482 namespace
1483 {
1484   // Position of a point relative to a segment
1485   //            .           .
1486   //            .  LEFT     .
1487   //            .           .
1488   //  VERTEX 1  o----ON----->  VERTEX 2
1489   //            .           .
1490   //            .  RIGHT    .
1491   //            .           .
1492   enum PositionName { POS_LEFT = 1, POS_VERTEX = 2, POS_RIGHT = 4, //POS_ON = 8,
1493                       POS_ALL = POS_LEFT | POS_RIGHT | POS_VERTEX,
1494                       POS_MAX = POS_RIGHT };
1495   struct PointPos
1496   {
1497     PositionName _name;
1498     int          _index; // index of vertex or segment
1499
1500     PointPos( PositionName n, int i=-1 ): _name(n), _index(i) {}
1501     bool operator < (const PointPos& other ) const
1502     {
1503       if ( _name == other._name )
1504         return  ( _index < 0 || other._index < 0 ) ? false : _index < other._index;
1505       return _name < other._name;
1506     }
1507   };
1508
1509   //================================================================================
1510   /*!
1511    * \brief Return position of a point relative to a segment
1512    *  \param point2D      - the point to analyze position of
1513    *  \param segEnds      - end points of segments
1514    *  \param index0       - 0-based index of the first point of segment
1515    *  \param posToFindOut - flags of positions to detect
1516    *  \retval PointPos - point position
1517    */
1518   //================================================================================
1519
1520   PointPos getPointPosition( const gp_XY& point2D,
1521                              const gp_XY* segEnds,
1522                              const int    index0 = 0,
1523                              const int    posToFindOut = POS_ALL)
1524   {
1525     const gp_XY& p1 = segEnds[ index0   ];
1526     const gp_XY& p2 = segEnds[ index0+1 ];
1527     const gp_XY grad = p2 - p1;
1528
1529     if ( posToFindOut & POS_VERTEX )
1530     {
1531       // check if the point2D is at "vertex 1" zone
1532       gp_XY pp1[2] = { p1, gp_XY( p1.X() - grad.Y(),
1533                                   p1.Y() + grad.X() ) };
1534       if ( getPointPosition( point2D, pp1, 0, POS_LEFT|POS_RIGHT )._name == POS_LEFT )
1535         return PointPos( POS_VERTEX, index0 );
1536
1537       // check if the point2D is at "vertex 2" zone
1538       gp_XY pp2[2] = { p2, gp_XY( p2.X() - grad.Y(),
1539                                   p2.Y() + grad.X() ) };
1540       if ( getPointPosition( point2D, pp2, 0, POS_LEFT|POS_RIGHT )._name == POS_RIGHT )
1541         return PointPos( POS_VERTEX, index0 + 1);
1542     }
1543     double edgeEquation =
1544       ( point2D.X() - p1.X() ) * grad.Y() - ( point2D.Y() - p1.Y() ) * grad.X();
1545     return PointPos( edgeEquation < 0 ? POS_LEFT : POS_RIGHT, index0 );
1546   }
1547 }
1548
1549 //=======================================================================
1550 /*!
1551  * \brief Return minimal distance from a point to an element
1552  *
1553  * Currently we ignore non-planarity and 2nd order of face
1554  */
1555 //=======================================================================
1556
1557 double SMESH_MeshAlgos::GetDistance( const SMDS_MeshElement* elem,
1558                                      const gp_Pnt&           point,
1559                                      gp_XYZ*                 closestPnt )
1560 {
1561   switch ( elem->GetType() )
1562   {
1563   case SMDSAbs_Volume:
1564     return GetDistance( static_cast<const SMDS_MeshVolume*>( elem ), point, closestPnt );
1565   case SMDSAbs_Face:
1566     return GetDistance( static_cast<const SMDS_MeshFace*>( elem ), point, closestPnt );
1567   case SMDSAbs_Edge:
1568     return GetDistance( static_cast<const SMDS_MeshEdge*>( elem ), point, closestPnt );
1569   case SMDSAbs_Node:
1570     if ( closestPnt ) *closestPnt = SMESH_TNodeXYZ( elem );
1571     return point.Distance( SMESH_TNodeXYZ( elem ));
1572   default:;
1573   }
1574   return -1;
1575 }
1576
1577 //=======================================================================
1578 /*!
1579  * \brief Return minimal distance from a point to a face
1580  *
1581  * Currently we ignore non-planarity and 2nd order of face
1582  */
1583 //=======================================================================
1584
1585 double SMESH_MeshAlgos::GetDistance( const SMDS_MeshFace* face,
1586                                      const gp_Pnt&        point,
1587                                      gp_XYZ*              closestPnt )
1588 {
1589   const double badDistance = -1;
1590   if ( !face ) return badDistance;
1591
1592   int nbCorners = face->NbCornerNodes();
1593   if ( nbCorners > 3 )
1594   {
1595     std::vector< const SMDS_MeshNode* > nodes;
1596     int nbTria = SMESH_MeshAlgos::Triangulate().GetTriangles( face, nodes );
1597
1598     double minDist = Precision::Infinite();
1599     gp_XYZ cp;
1600     for ( int i = 0; i < 3 * nbTria; i += 3 )
1601     {
1602       SMDS_FaceOfNodes triangle( nodes[i], nodes[i+1], nodes[i+2] );
1603       double dist = GetDistance( &triangle, point, closestPnt );
1604       if ( dist < minDist )
1605       {
1606         minDist = dist;
1607         if ( closestPnt )
1608           cp = *closestPnt;
1609       }
1610     }
1611
1612     if ( closestPnt )
1613       *closestPnt = cp;
1614     return minDist;
1615   }
1616
1617   // coordinates of nodes (medium nodes, if any, ignored)
1618   typedef SMDS_StdIterator< SMESH_TNodeXYZ, SMDS_ElemIteratorPtr > TXyzIterator;
1619   std::vector<gp_XYZ> xyz( TXyzIterator( face->nodesIterator()), TXyzIterator() );
1620   xyz.resize( 4 );
1621
1622   // transformation to get xyz[0] lies on the origin, xyz[1] lies on the Z axis,
1623   // and xyz[2] lies in the XZ plane. This is to pass to 2D space on XZ plane.
1624   gp_Trsf trsf;
1625   gp_Vec OZ ( xyz[0], xyz[1] );
1626   gp_Vec OX ( xyz[0], xyz[2] );
1627   if ( OZ.Magnitude() < std::numeric_limits<double>::min() )
1628   {
1629     if ( xyz.size() < 4 ) return badDistance;
1630     OZ = gp_Vec ( xyz[0], xyz[2] );
1631     OX = gp_Vec ( xyz[0], xyz[3] );
1632   }
1633   gp_Ax3 tgtCS;
1634   try {
1635     tgtCS = gp_Ax3( xyz[0], OZ, OX );
1636   }
1637   catch ( Standard_Failure ) {
1638     return badDistance;
1639   }
1640   trsf.SetTransformation( tgtCS );
1641
1642   // move all the nodes to 2D
1643   std::vector<gp_XY> xy( xyz.size() );
1644   for ( size_t i = 0; i < 3; ++i )
1645   {
1646     gp_XYZ p3d = xyz[i];
1647     trsf.Transforms( p3d );
1648     xy[i].SetCoord( p3d.X(), p3d.Z() );
1649   }
1650   xyz.back() = xyz.front();
1651   xy.back() = xy.front();
1652
1653   // // move the point in 2D
1654   gp_XYZ tmpPnt = point.XYZ();
1655   trsf.Transforms( tmpPnt );
1656   gp_XY point2D( tmpPnt.X(), tmpPnt.Z() );
1657
1658   // loop on edges of the face to analyze point position ralative to the face
1659   std::vector< PointPos > pntPosByType[ POS_MAX + 1 ];
1660   for ( size_t i = 1; i < xy.size(); ++i )
1661   {
1662     PointPos pos = getPointPosition( point2D, &xy[0], i-1 );
1663     pntPosByType[ pos._name ].push_back( pos );
1664   }
1665
1666   // compute distance
1667
1668   double dist = badDistance;
1669
1670   if ( pntPosByType[ POS_LEFT ].size() > 0 ) // point is most close to an edge
1671   {
1672     PointPos& pos = pntPosByType[ POS_LEFT ][0];
1673
1674     gp_Vec edge( xyz[ pos._index ], xyz[ pos._index+1 ]);
1675     gp_Vec n1p ( xyz[ pos._index ], point  );
1676     double u = ( edge * n1p ) / edge.SquareMagnitude(); // param [0,1] on the edge
1677     gp_XYZ proj = xyz[ pos._index ] + u * edge.XYZ(); // projection on the edge
1678     dist = point.Distance( proj );
1679     if ( closestPnt ) *closestPnt = proj;
1680   }
1681
1682   else if ( pntPosByType[ POS_RIGHT ].size() >= 2 ) // point is inside the face
1683   {
1684     dist = Abs( tmpPnt.Y() );
1685     if ( closestPnt )
1686     {
1687       if ( dist < std::numeric_limits<double>::min() ) {
1688         *closestPnt = point.XYZ();
1689       }
1690       else {
1691         tmpPnt.SetY( 0 );
1692         trsf.Inverted().Transforms( tmpPnt );
1693         *closestPnt = tmpPnt;
1694       }
1695     }
1696   }
1697
1698   else if ( pntPosByType[ POS_VERTEX ].size() > 0 ) // point is most close to a node
1699   {
1700     double minDist2 = Precision::Infinite();
1701     for ( size_t i = 0; i < pntPosByType[ POS_VERTEX ].size(); ++i )
1702     {
1703       PointPos& pos = pntPosByType[ POS_VERTEX ][i];
1704
1705       double d2 = point.SquareDistance( xyz[ pos._index ]);
1706       if ( minDist2 > d2 )
1707       {
1708         if ( closestPnt ) *closestPnt = xyz[ pos._index ];
1709         minDist2 = d2;
1710       }
1711     }
1712     dist = Sqrt( minDist2 );
1713   }
1714
1715   return dist;
1716 }
1717
1718 //=======================================================================
1719 /*!
1720  * \brief Return minimal distance from a point to an edge
1721  */
1722 //=======================================================================
1723
1724 double SMESH_MeshAlgos::GetDistance( const SMDS_MeshEdge* seg,
1725                                      const gp_Pnt&        point,
1726                                      gp_XYZ*              closestPnt )
1727 {
1728   double dist = Precision::Infinite();
1729   if ( !seg ) return dist;
1730
1731   int i = 0, nbNodes = seg->NbNodes();
1732
1733   std::vector< SMESH_TNodeXYZ > xyz( nbNodes );
1734   for ( SMDS_NodeIteratorPtr nodeIt = seg->interlacedNodesIterator(); nodeIt->more(); i++ )
1735     xyz[ i ].Set( nodeIt->next() );
1736
1737   for ( i = 1; i < nbNodes; ++i )
1738   {
1739     gp_Vec edge( xyz[i-1], xyz[i] );
1740     gp_Vec n1p ( xyz[i-1], point  );
1741     double d, u = ( edge * n1p ) / edge.SquareMagnitude(); // param [0,1] on the edge
1742     if ( u <= 0. ) {
1743       if (( d = n1p.SquareMagnitude() ) < dist ) {
1744         dist = d;
1745         if ( closestPnt ) *closestPnt = xyz[i-1];
1746       }
1747     }
1748     else if ( u >= 1. ) {
1749       if (( d = point.SquareDistance( xyz[i] )) < dist ) {
1750         dist = d;
1751         if ( closestPnt ) *closestPnt = xyz[i];
1752       }
1753     }
1754     else {
1755       gp_XYZ proj = xyz[i-1] + u * edge.XYZ(); // projection of the point on the edge
1756       if (( d = point.SquareDistance( proj )) < dist ) {
1757         dist = d;
1758         if ( closestPnt ) *closestPnt = proj;
1759       }
1760     }
1761   }
1762   return Sqrt( dist );
1763 }
1764
1765 //=======================================================================
1766 /*!
1767  * \brief Return minimal distance from a point to a volume
1768  *
1769  * Currently we ignore non-planarity and 2nd order
1770  */
1771 //=======================================================================
1772
1773 double SMESH_MeshAlgos::GetDistance( const SMDS_MeshVolume* volume,
1774                                      const gp_Pnt&          point,
1775                                      gp_XYZ*                closestPnt )
1776 {
1777   SMDS_VolumeTool vTool( volume );
1778   vTool.SetExternalNormal();
1779   const int iQ = volume->IsQuadratic() ? 2 : 1;
1780
1781   double n[3], bc[3];
1782   double minDist = 1e100, dist;
1783   gp_XYZ closeP = point.XYZ();
1784   bool isOut = false;
1785   for ( int iF = 0; iF < vTool.NbFaces(); ++iF )
1786   {
1787     // skip a facet with normal not "looking at" the point
1788     if ( !vTool.GetFaceNormal( iF, n[0], n[1], n[2] ) ||
1789          !vTool.GetFaceBaryCenter( iF, bc[0], bc[1], bc[2] ))
1790       continue;
1791     gp_XYZ bcp = point.XYZ() - gp_XYZ( bc[0], bc[1], bc[2] );
1792     if ( gp_XYZ( n[0], n[1], n[2] ) * bcp < -1e-12 )
1793       continue;
1794
1795     // find distance to a facet
1796     const SMDS_MeshNode** nodes = vTool.GetFaceNodes( iF );
1797     switch ( vTool.NbFaceNodes( iF ) / iQ ) {
1798     case 3:
1799     {
1800       SMDS_FaceOfNodes tmpFace( nodes[0], nodes[ 1*iQ ], nodes[ 2*iQ ] );
1801       dist = GetDistance( &tmpFace, point, closestPnt );
1802       break;
1803     }
1804     case 4:
1805     {
1806       SMDS_FaceOfNodes tmpFace( nodes[0], nodes[ 1*iQ ], nodes[ 2*iQ ], nodes[ 3*iQ ]);
1807       dist = GetDistance( &tmpFace, point, closestPnt );
1808       break;
1809     }
1810     default:
1811       std::vector<const SMDS_MeshNode *> nvec( nodes, nodes + vTool.NbFaceNodes( iF ));
1812       SMDS_PolygonalFaceOfNodes tmpFace( nvec );
1813       dist = GetDistance( &tmpFace, point, closestPnt );
1814     }
1815     if ( dist < minDist )
1816     {
1817       minDist = dist;
1818       isOut = true;
1819       if ( closestPnt ) closeP = *closestPnt;
1820     }
1821   }
1822   if ( isOut )
1823   {
1824     if ( closestPnt ) *closestPnt = closeP;
1825     return minDist;
1826   }
1827
1828   return 0; // point is inside the volume
1829 }
1830
1831 //================================================================================
1832 /*!
1833  * \brief Returns barycentric coordinates of a point within a triangle.
1834  *        A not returned bc2 = 1. - bc0 - bc1.
1835  *        The point lies within the triangle if ( bc0 >= 0 && bc1 >= 0 && bc0+bc1 <= 1 )
1836  */
1837 //================================================================================
1838
1839 void SMESH_MeshAlgos::GetBarycentricCoords( const gp_XY& p,
1840                                             const gp_XY& t0,
1841                                             const gp_XY& t1,
1842                                             const gp_XY& t2,
1843                                             double &     bc0,
1844                                             double &     bc1)
1845 {
1846   const double // matrix 2x2
1847     T11 = t0.X()-t2.X(), T12 = t1.X()-t2.X(),
1848     T21 = t0.Y()-t2.Y(), T22 = t1.Y()-t2.Y();
1849   const double Tdet = T11*T22 - T12*T21; // matrix determinant
1850   if ( Abs( Tdet ) < std::numeric_limits<double>::min() )
1851   {
1852     bc0 = bc1 = 2.;
1853     return;
1854   }
1855   // matrix inverse
1856   const double t11 = T22, t12 = -T12, t21 = -T21, t22 = T11;
1857   // vector
1858   const double r11 = p.X()-t2.X(), r12 = p.Y()-t2.Y();
1859   // barycentric coordinates: multiply matrix by vector
1860   bc0 = (t11 * r11 + t12 * r12)/Tdet;
1861   bc1 = (t21 * r11 + t22 * r12)/Tdet;
1862 }
1863
1864 //=======================================================================
1865 //function : FindFaceInSet
1866 //purpose  : Return a face having linked nodes n1 and n2 and which is
1867 //           - not in avoidSet,
1868 //           - in elemSet provided that !elemSet.empty()
1869 //           i1 and i2 optionally returns indices of n1 and n2
1870 //=======================================================================
1871
1872 const SMDS_MeshElement*
1873 SMESH_MeshAlgos::FindFaceInSet(const SMDS_MeshNode*    n1,
1874                                const SMDS_MeshNode*    n2,
1875                                const TIDSortedElemSet& elemSet,
1876                                const TIDSortedElemSet& avoidSet,
1877                                int*                    n1ind,
1878                                int*                    n2ind)
1879
1880 {
1881   int i1 = 0, i2 = 0;
1882   const SMDS_MeshElement* face = 0;
1883
1884   SMDS_ElemIteratorPtr invElemIt = n1->GetInverseElementIterator(SMDSAbs_Face);
1885   while ( invElemIt->more() && !face ) // loop on inverse faces of n1
1886   {
1887     const SMDS_MeshElement* elem = invElemIt->next();
1888     if (avoidSet.count( elem ))
1889       continue;
1890     if ( !elemSet.empty() && !elemSet.count( elem ))
1891       continue;
1892     // index of n1
1893     i1 = elem->GetNodeIndex( n1 );
1894     // find a n2 linked to n1
1895     int nbN = elem->IsQuadratic() ? elem->NbNodes()/2 : elem->NbNodes();
1896     for ( int di = -1; di < 2 && !face; di += 2 )
1897     {
1898       i2 = (i1+di+nbN) % nbN;
1899       if ( elem->GetNode( i2 ) == n2 )
1900         face = elem;
1901     }
1902     if ( !face && elem->IsQuadratic())
1903     {
1904       // analysis for quadratic elements using all nodes
1905       SMDS_NodeIteratorPtr anIter = elem->interlacedNodesIterator();
1906       const SMDS_MeshNode* prevN = static_cast<const SMDS_MeshNode*>( anIter->next() );
1907       for ( i1 = -1, i2 = 0; anIter->more() && !face; i1++, i2++ )
1908       {
1909         const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( anIter->next() );
1910         if ( n1 == prevN && n2 == n )
1911         {
1912           face = elem;
1913         }
1914         else if ( n2 == prevN && n1 == n )
1915         {
1916           face = elem; std::swap( i1, i2 );
1917         }
1918         prevN = n;
1919       }
1920     }
1921   }
1922   if ( n1ind ) *n1ind = i1;
1923   if ( n2ind ) *n2ind = i2;
1924   return face;
1925 }
1926
1927 //================================================================================
1928 /*!
1929  * Return sharp edges of faces and non-manifold ones. Optionally adds existing edges.
1930  */
1931 //================================================================================
1932
1933 std::vector< SMESH_MeshAlgos::Edge >
1934 SMESH_MeshAlgos::FindSharpEdges( SMDS_Mesh* theMesh,
1935                                  double     theAngle,
1936                                  bool       theAddExisting )
1937 {
1938   std::vector< Edge > resultEdges;
1939   if ( !theMesh ) return resultEdges;
1940
1941   typedef std::pair< bool, const SMDS_MeshNode* >                            TIsSharpAndMedium;
1942   typedef NCollection_DataMap< SMESH_TLink, TIsSharpAndMedium, SMESH_TLink > TLinkSharpMap;
1943
1944   TLinkSharpMap linkIsSharp( theMesh->NbFaces() );
1945   TIsSharpAndMedium sharpMedium( true, 0 );
1946   bool                 & isSharp = sharpMedium.first;
1947   const SMDS_MeshNode* & nMedium = sharpMedium.second;
1948
1949   if ( theAddExisting )
1950   {
1951     for ( SMDS_EdgeIteratorPtr edgeIt = theMesh->edgesIterator(); edgeIt->more(); )
1952     {
1953       const SMDS_MeshElement* edge = edgeIt->next();
1954       nMedium = ( edge->IsQuadratic() ) ? edge->GetNode(2) : 0;
1955       linkIsSharp.Bind( SMESH_TLink( edge->GetNode(0), edge->GetNode(1)), sharpMedium );
1956     }
1957   }
1958
1959   // check angles between face normals
1960
1961   const double angleCos = Cos( theAngle * M_PI / 180. ), angleCos2 = angleCos * angleCos;
1962   gp_XYZ norm1, norm2;
1963   std::vector< const SMDS_MeshNode* > faceNodes, linkNodes(2);
1964   std::vector<const SMDS_MeshElement *> linkFaces;
1965
1966   int nbSharp = linkIsSharp.Extent();
1967   for ( SMDS_FaceIteratorPtr faceIt = theMesh->facesIterator(); faceIt->more(); )
1968   {
1969     const SMDS_MeshElement* face = faceIt->next();
1970     size_t             nbCorners = face->NbCornerNodes();
1971
1972     faceNodes.assign( face->begin_nodes(), face->end_nodes() );
1973     if ( faceNodes.size() == nbCorners )
1974       faceNodes.resize( nbCorners * 2, 0 );
1975
1976     const SMDS_MeshNode* nPrev = faceNodes[ nbCorners-1 ];
1977     for ( size_t i = 0; i < nbCorners; ++i )
1978     {
1979       SMESH_TLink link( nPrev, faceNodes[i] );
1980       if ( !linkIsSharp.IsBound( link ))
1981       {
1982         linkNodes[0] = link.node1();
1983         linkNodes[1] = link.node2();
1984         linkFaces.clear();
1985         theMesh->GetElementsByNodes( linkNodes, linkFaces, SMDSAbs_Face );
1986
1987         isSharp = false;
1988         if ( linkFaces.size() > 2 )
1989         {
1990           isSharp = true;
1991         }
1992         else if ( linkFaces.size() == 2 &&
1993                   FaceNormal( linkFaces[0], norm1, /*normalize=*/false ) &&
1994                   FaceNormal( linkFaces[1], norm2, /*normalize=*/false ))
1995         {
1996           double dot = norm1 * norm2; // == cos * |norm1| * |norm2|
1997           if (( dot < 0 ) == ( angleCos < 0 ))
1998           {
1999             double cos2 = dot * dot / norm1.SquareModulus() / norm2.SquareModulus();
2000             isSharp = ( angleCos < 0 ) ? ( cos2 > angleCos2 ) : ( cos2 < angleCos2 );
2001           }
2002           else
2003           {
2004             isSharp = ( angleCos > 0 );
2005           }
2006         }
2007         nMedium = faceNodes[( i-1+nbCorners ) % nbCorners + nbCorners ];
2008
2009         linkIsSharp.Bind( link, sharpMedium );
2010         nbSharp += isSharp;
2011       }
2012
2013       nPrev = faceNodes[i];
2014     }
2015   }
2016
2017   resultEdges.resize( nbSharp );
2018   TLinkSharpMap::Iterator linkIsSharpIter( linkIsSharp );
2019   for ( int i = 0; linkIsSharpIter.More() && i < nbSharp; linkIsSharpIter.Next() )
2020   {
2021     const SMESH_TLink&                link = linkIsSharpIter.Key();
2022     const TIsSharpAndMedium& isSharpMedium = linkIsSharpIter.Value();
2023     if ( isSharpMedium.first )
2024     {
2025       Edge & edge  = resultEdges[ i++ ];
2026       edge._node1  = link.node1();
2027       edge._node2  = link.node2();
2028       edge._medium = isSharpMedium.second;
2029     }
2030   }
2031
2032   return resultEdges;
2033 }
2034
2035 //================================================================================
2036 /*!
2037  * Distribute all faces of the mesh between groups using given edges as group boundaries
2038  */
2039 //================================================================================
2040
2041 std::vector< std::vector< const SMDS_MeshElement* > >
2042 SMESH_MeshAlgos::SeparateFacesByEdges( SMDS_Mesh* theMesh, const std::vector< Edge >& theEdges )
2043 {
2044   std::vector< std::vector< const SMDS_MeshElement* > > groups;
2045   if ( !theMesh ) return groups;
2046
2047   // build map of face edges (SMESH_TLink) and their faces
2048
2049   typedef std::vector< const SMDS_MeshElement* >                    TFaceVec;
2050   typedef NCollection_DataMap< SMESH_TLink, TFaceVec, SMESH_TLink > TFacesByLinks;
2051   TFacesByLinks facesByLink( theMesh->NbFaces() );
2052
2053   std::vector< const SMDS_MeshNode* > faceNodes;
2054   for ( SMDS_FaceIteratorPtr faceIt = theMesh->facesIterator(); faceIt->more(); )
2055   {
2056     const SMDS_MeshElement* face = faceIt->next();
2057     size_t             nbCorners = face->NbCornerNodes();
2058
2059     faceNodes.assign( face->begin_nodes(), face->end_nodes() );
2060     faceNodes.resize( nbCorners + 1 );
2061     faceNodes[ nbCorners ] = faceNodes[0];
2062
2063     face->setIsMarked( false );
2064
2065     for ( size_t i = 0; i < nbCorners; ++i )
2066     {
2067       SMESH_TLink link( faceNodes[i], faceNodes[i+1] );
2068       TFaceVec* linkFaces = facesByLink.ChangeSeek( link );
2069       if ( !linkFaces )
2070       {
2071         linkFaces = facesByLink.Bound( link, TFaceVec() );
2072         linkFaces->reserve(2);
2073       }
2074       linkFaces->push_back( face );
2075     }
2076   }
2077
2078   // remove the given edges from facesByLink map
2079
2080   for ( size_t i = 0; i < theEdges.size(); ++i )
2081   {
2082     SMESH_TLink link( theEdges[i]._node1, theEdges[i]._node2 );
2083     facesByLink.UnBind( link );
2084   }
2085
2086   // faces connected via links of facesByLink map form a group
2087
2088   while ( !facesByLink.IsEmpty() )
2089   {
2090     groups.push_back( TFaceVec() );
2091     TFaceVec & group = groups.back();
2092
2093     group.push_back( TFacesByLinks::Iterator( facesByLink ).Value()[0] );
2094     group.back()->setIsMarked( true );
2095
2096     for ( size_t iF = 0; iF < group.size(); ++iF )
2097     {
2098       const SMDS_MeshElement* face = group[iF];
2099       size_t             nbCorners = face->NbCornerNodes();
2100       faceNodes.assign( face->begin_nodes(), face->end_nodes() );
2101       faceNodes.resize( nbCorners + 1 );
2102       faceNodes[ nbCorners ] = faceNodes[0];
2103
2104       for ( size_t iN = 0; iN < nbCorners; ++iN )
2105       {
2106         SMESH_TLink link( faceNodes[iN], faceNodes[iN+1] );
2107         if ( const TFaceVec* faces = facesByLink.Seek( link ))
2108         {
2109           const TFaceVec& faceNeighbors = *faces;
2110           for ( size_t i = 0; i < faceNeighbors.size(); ++i )
2111             if ( !faceNeighbors[i]->isMarked() )
2112             {
2113               group.push_back( faceNeighbors[i] );
2114               faceNeighbors[i]->setIsMarked( true );
2115             }
2116           facesByLink.UnBind( link );
2117         }
2118       }
2119     }
2120   }
2121
2122   // find faces that are alone in its group; they were not in facesByLink
2123
2124   int nbInGroups = 0;
2125   for ( size_t i = 0; i < groups.size(); ++i )
2126     nbInGroups += groups[i].size();
2127   if ( nbInGroups < theMesh->NbFaces() )
2128   {
2129     for ( SMDS_FaceIteratorPtr faceIt = theMesh->facesIterator(); faceIt->more(); )
2130     {
2131       const SMDS_MeshElement* face = faceIt->next();
2132       if ( !face->isMarked() )
2133       {
2134         groups.push_back( TFaceVec() );
2135         groups.back().push_back( face );
2136       }
2137     }
2138   }
2139
2140   return groups;
2141 }
2142
2143 //================================================================================
2144 /*!
2145  * \brief Calculate normal of a mesh face
2146  */
2147 //================================================================================
2148
2149 bool SMESH_MeshAlgos::FaceNormal(const SMDS_MeshElement* F, gp_XYZ& normal, bool normalized)
2150 {
2151   if ( !F || F->GetType() != SMDSAbs_Face )
2152     return false;
2153
2154   normal.SetCoord(0,0,0);
2155   int nbNodes = F->NbCornerNodes();
2156   for ( int i = 0; i < nbNodes-2; ++i )
2157   {
2158     gp_XYZ p[3];
2159     for ( int n = 0; n < 3; ++n )
2160     {
2161       const SMDS_MeshNode* node = F->GetNode( i + n );
2162       p[n].SetCoord( node->X(), node->Y(), node->Z() );
2163     }
2164     normal += ( p[2] - p[1] ) ^ ( p[0] - p[1] );
2165   }
2166   double size2 = normal.SquareModulus();
2167   bool ok = ( size2 > std::numeric_limits<double>::min() * std::numeric_limits<double>::min());
2168   if ( normalized && ok )
2169     normal /= sqrt( size2 );
2170
2171   return ok;
2172 }
2173
2174 //=======================================================================
2175 //function : GetCommonNodes
2176 //purpose  : Return nodes common to two elements
2177 //=======================================================================
2178
2179 std::vector< const SMDS_MeshNode*> SMESH_MeshAlgos::GetCommonNodes(const SMDS_MeshElement* e1,
2180                                                                    const SMDS_MeshElement* e2)
2181 {
2182   std::vector< const SMDS_MeshNode*> common;
2183   for ( int i = 0 ; i < e1->NbNodes(); ++i )
2184     if ( e2->GetNodeIndex( e1->GetNode( i )) >= 0 )
2185       common.push_back( e1->GetNode( i ));
2186   return common;
2187 }
2188 //================================================================================
2189 /*!
2190  * \brief Return true if node1 encounters first in the face and node2, after
2191  */
2192 //================================================================================
2193
2194 bool SMESH_MeshAlgos::IsRightOrder( const SMDS_MeshElement* face,
2195                                     const SMDS_MeshNode*    node0,
2196                                     const SMDS_MeshNode*    node1 )
2197 {
2198   int i0 = face->GetNodeIndex( node0 );
2199   int i1 = face->GetNodeIndex( node1 );
2200   if ( face->IsQuadratic() )
2201   {
2202     if ( face->IsMediumNode( node0 ))
2203     {
2204       i0 -= ( face->NbNodes()/2 - 1 );
2205       i1 *= 2;
2206     }
2207     else
2208     {
2209       i1 -= ( face->NbNodes()/2 - 1 );
2210       i0 *= 2;
2211     }
2212   }
2213   int diff = i1 - i0;
2214   return ( diff == 1 ) || ( diff == -face->NbNodes()+1 );
2215 }
2216
2217 //=======================================================================
2218 /*!
2219  * \brief Partition given 1D elements into groups of contiguous edges.
2220  *        A node where number of meeting edges != 2 is a group end.
2221  *        An optional startNode is used to orient groups it belongs to.
2222  * \return a list of edge groups and a list of corresponding node groups.
2223  *         If a group is closed, the first and last nodes of the group are same.
2224  */
2225 //=======================================================================
2226
2227 void SMESH_MeshAlgos::Get1DBranches( SMDS_ElemIteratorPtr theEdgeIt,
2228                                      TElemGroupVector&    theEdgeGroups,
2229                                      TNodeGroupVector&    theNodeGroups,
2230                                      const SMDS_MeshNode* theStartNode )
2231 {
2232   if ( !theEdgeIt )
2233     return;
2234
2235   // build map of nodes and their adjacent edges
2236
2237   typedef std::vector< const SMDS_MeshNode* >                                 TNodeVec;
2238   typedef std::vector< const SMDS_MeshElement* >                              TEdgeVec;
2239   typedef NCollection_DataMap< const SMDS_MeshNode*, TEdgeVec, SMESH_Hasher > TEdgesByNodeMap;
2240   TEdgesByNodeMap edgesByNode;
2241
2242   while ( theEdgeIt->more() )
2243   {
2244     const SMDS_MeshElement* edge = theEdgeIt->next();
2245     if ( edge->GetType() != SMDSAbs_Edge )
2246       continue;
2247
2248     const SMDS_MeshNode* nodes[2] = { edge->GetNode(0), edge->GetNode(1) };
2249     for ( int i = 0; i < 2; ++i )
2250     {
2251       TEdgeVec* nodeEdges = edgesByNode.ChangeSeek( nodes[i] );
2252       if ( !nodeEdges )
2253       {
2254         nodeEdges = edgesByNode.Bound( nodes[i], TEdgeVec() );
2255         nodeEdges->reserve(2);
2256       }
2257       nodeEdges->push_back( edge );
2258     }
2259   }
2260
2261   if ( edgesByNode.IsEmpty() )
2262     return;
2263
2264
2265   // build edge branches
2266
2267   TElemGroupVector branches(2);
2268   TNodeGroupVector nodeBranches(2);
2269
2270   while ( !edgesByNode.IsEmpty() )
2271   {
2272     if ( !theStartNode || !edgesByNode.IsBound( theStartNode ))
2273     {
2274       theStartNode = TEdgesByNodeMap::Iterator( edgesByNode ).Key();
2275     }
2276
2277     size_t nbBranches = 0;
2278     bool startIsBranchEnd = false;
2279
2280     while ( edgesByNode.IsBound( theStartNode ))
2281     {
2282       // initialize a new branch
2283
2284       ++nbBranches;
2285       if ( branches.size() < nbBranches )
2286       {
2287         branches.push_back   ( TEdgeVec() );
2288         nodeBranches.push_back( TNodeVec() );
2289       }
2290       TEdgeVec & branch     = branches    [ nbBranches - 1 ];
2291       TNodeVec & nodeBranch = nodeBranches[ nbBranches - 1 ];
2292       branch.clear();
2293       nodeBranch.clear();
2294       {
2295         TEdgeVec& edges = edgesByNode( theStartNode );
2296         startIsBranchEnd = ( edges.size() != 2 );
2297
2298         int nbEdges = 0;
2299         const SMDS_MeshElement* startEdge = 0;
2300         for ( size_t i = 0; i < edges.size(); ++i )
2301         {
2302           if ( !startEdge && edges[i] )
2303           {
2304             startEdge = edges[i];
2305             edges[i] = 0;
2306           }
2307           nbEdges += bool( edges[i] );
2308         }
2309         if ( nbEdges == 0 )
2310           edgesByNode.UnBind( theStartNode );
2311         if ( !startEdge )
2312           continue;
2313
2314         branch.push_back( startEdge );
2315
2316         nodeBranch.push_back( theStartNode );
2317         nodeBranch.push_back( branch.back()->GetNode(0) );
2318         if ( nodeBranch.back() == theStartNode )
2319           nodeBranch.back() = branch.back()->GetNode(1);
2320       }
2321
2322       // fill the branch
2323
2324       bool isBranchEnd = false;
2325       TEdgeVec* edgesPtr;
2326
2327       while (( !isBranchEnd ) && ( edgesPtr = edgesByNode.ChangeSeek( nodeBranch.back() )))
2328       {
2329         TEdgeVec& edges = *edgesPtr;
2330
2331         isBranchEnd = ( edges.size() != 2 );
2332
2333         const SMDS_MeshNode* lastNode = nodeBranch.back();
2334
2335         switch ( edges.size() )
2336         {
2337         case 1:
2338           edgesByNode.UnBind( lastNode );
2339           break;
2340
2341         case 2:
2342         {
2343           if ( const SMDS_MeshElement* nextEdge = edges[ edges[0] == branch.back() ])
2344           {
2345             branch.push_back( nextEdge );
2346
2347             const SMDS_MeshNode* nextNode = nextEdge->GetNode(0);
2348             if ( nodeBranch.back() == nextNode )
2349               nextNode = nextEdge->GetNode(1);
2350             nodeBranch.push_back( nextNode );
2351           }
2352           edgesByNode.UnBind( lastNode );
2353           break;
2354         }
2355
2356         default:
2357           int nbEdges = 0;
2358           for ( size_t i = 0; i < edges.size(); ++i )
2359           {
2360             if ( edges[i] == branch.back() )
2361               edges[i] = 0;
2362             nbEdges += bool( edges[i] );
2363           }
2364           if ( nbEdges == 0 )
2365             edgesByNode.UnBind( lastNode );
2366         }
2367       }
2368     } // while ( edgesByNode.IsBound( theStartNode ))
2369
2370
2371     // put the found branches to the result
2372
2373     if ( nbBranches == 2 && !startIsBranchEnd ) // join two branches starting at the same node
2374     {
2375       std::reverse( nodeBranches[0].begin(), nodeBranches[0].end() );
2376       nodeBranches[0].pop_back();
2377       nodeBranches[0].reserve( nodeBranches[0].size() + nodeBranches[1].size() );
2378       nodeBranches[0].insert( nodeBranches[0].end(),
2379                               nodeBranches[1].begin(), nodeBranches[1].end() );
2380
2381       std::reverse( branches[0].begin(), branches[0].end() );
2382       branches[0].reserve( branches[0].size() + branches[1].size() );
2383       branches[0].insert( branches[0].end(), branches[1].begin(), branches[1].end() );
2384
2385       nodeBranches[1].clear();
2386       branches[1].clear();
2387     }
2388
2389     for ( size_t i = 0; i < nbBranches; ++i )
2390     {
2391       if ( branches[i].empty() )
2392         continue;
2393
2394       theEdgeGroups.push_back( TEdgeVec() );
2395       theEdgeGroups.back().swap( branches[i] );
2396
2397       theNodeGroups.push_back( TNodeVec() );
2398       theNodeGroups.back().swap( nodeBranches[i] );
2399     }
2400
2401   } // while ( !edgesByNode.IsEmpty() )
2402
2403   return;
2404 }
2405
2406 //=======================================================================
2407 /*!
2408  * \brief Return SMESH_NodeSearcher
2409  */
2410 //=======================================================================
2411
2412 SMESH_NodeSearcher* SMESH_MeshAlgos::GetNodeSearcher(SMDS_Mesh& mesh)
2413 {
2414   return new SMESH_NodeSearcherImpl( &mesh );
2415 }
2416
2417 //=======================================================================
2418 /*!
2419  * \brief Return SMESH_NodeSearcher
2420  */
2421 //=======================================================================
2422
2423 SMESH_NodeSearcher* SMESH_MeshAlgos::GetNodeSearcher(SMDS_ElemIteratorPtr elemIt)
2424 {
2425   return new SMESH_NodeSearcherImpl( 0, elemIt );
2426 }
2427
2428 //=======================================================================
2429 /*!
2430  * \brief Return SMESH_ElementSearcher
2431  */
2432 //=======================================================================
2433
2434 SMESH_ElementSearcher* SMESH_MeshAlgos::GetElementSearcher(SMDS_Mesh& mesh,
2435                                                            double     tolerance)
2436 {
2437   return new SMESH_ElementSearcherImpl( mesh, tolerance );
2438 }
2439
2440 //=======================================================================
2441 /*!
2442  * \brief Return SMESH_ElementSearcher acting on a sub-set of elements
2443  */
2444 //=======================================================================
2445
2446 SMESH_ElementSearcher* SMESH_MeshAlgos::GetElementSearcher(SMDS_Mesh&           mesh,
2447                                                            SMDS_ElemIteratorPtr elemIt,
2448                                                            double               tolerance)
2449 {
2450   return new SMESH_ElementSearcherImpl( mesh, tolerance, elemIt );
2451 }