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