Salome HOME
Merge branch 'master' of https://codev-tuleap.cea.fr/plugins/git/salome/smesh
[modules/smesh.git] / src / SMESHUtils / SMESH_MeshAlgos.cxx
1 // Copyright (C) 2007-2016  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 // This file holds 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 "SMDS_FaceOfNodes.hxx"
32 #include "SMDS_LinearEdge.hxx"
33 #include "SMDS_Mesh.hxx"
34 #include "SMDS_PolygonalFaceOfNodes.hxx"
35 #include "SMDS_VolumeTool.hxx"
36 #include "SMESH_OctreeNode.hxx"
37
38 #include <Utils_SALOME_Exception.hxx>
39
40 #include <GC_MakeSegment.hxx>
41 #include <GeomAPI_ExtremaCurveCurve.hxx>
42 #include <Geom_Line.hxx>
43 #include <IntAna_IntConicQuad.hxx>
44 #include <IntAna_Quadric.hxx>
45 #include <gp_Lin.hxx>
46 #include <gp_Pln.hxx>
47
48 #include <limits>
49 #include <numeric>
50
51 #include <boost/container/flat_set.hpp>
52
53 //=======================================================================
54 /*!
55  * \brief Implementation of search for the node closest to point
56  */
57 //=======================================================================
58
59 struct SMESH_NodeSearcherImpl: public SMESH_NodeSearcher
60 {
61   //---------------------------------------------------------------------
62   /*!
63    * \brief Constructor
64    */
65   SMESH_NodeSearcherImpl( const SMDS_Mesh*     theMesh   = 0,
66                           SMDS_ElemIteratorPtr theElemIt = SMDS_ElemIteratorPtr() )
67   {
68     myMesh = ( SMDS_Mesh* ) theMesh;
69
70     TIDSortedNodeSet nodes;
71     if ( theMesh ) {
72       SMDS_NodeIteratorPtr nIt = theMesh->nodesIterator(/*idInceasingOrder=*/true);
73       while ( nIt->more() )
74         nodes.insert( nodes.end(), nIt->next() );
75     }
76     else if ( theElemIt )
77     {
78       while ( theElemIt->more() )
79       {
80         const SMDS_MeshElement* e = theElemIt->next();
81         nodes.insert( e->begin_nodes(), e->end_nodes() );
82       }
83     }
84     myOctreeNode = new SMESH_OctreeNode(nodes) ;
85
86     // get max size of a leaf box
87     SMESH_OctreeNode* tree = myOctreeNode;
88     while ( !tree->isLeaf() )
89     {
90       SMESH_OctreeNodeIteratorPtr cIt = tree->GetChildrenIterator();
91       if ( cIt->more() )
92         tree = cIt->next();
93     }
94     myHalfLeafSize = tree->maxSize() / 2.;
95   }
96
97   //---------------------------------------------------------------------
98   /*!
99    * \brief Move node and update myOctreeNode accordingly
100    */
101   void MoveNode( const SMDS_MeshNode* node, const gp_Pnt& toPnt )
102   {
103     myOctreeNode->UpdateByMoveNode( node, toPnt );
104     myMesh->MoveNode( node, toPnt.X(), toPnt.Y(), toPnt.Z() );
105   }
106
107   //---------------------------------------------------------------------
108   /*!
109    * \brief Do it's job
110    */
111   const SMDS_MeshNode* FindClosestTo( const gp_Pnt& thePnt )
112   {
113     std::map<double, const SMDS_MeshNode*> dist2Nodes;
114     myOctreeNode->NodesAround( thePnt.Coord(), dist2Nodes, myHalfLeafSize );
115     if ( !dist2Nodes.empty() )
116       return dist2Nodes.begin()->second;
117
118     std::vector<const SMDS_MeshNode*> nodes;
119     //myOctreeNode->NodesAround( &tgtNode, &nodes, myHalfLeafSize );
120
121     double minSqDist = DBL_MAX;
122     if ( nodes.empty() )  // get all nodes of OctreeNode's closest to thePnt
123     {
124       // sort leafs by their distance from thePnt
125       typedef std::multimap< double, SMESH_OctreeNode* > TDistTreeMap;
126       TDistTreeMap treeMap;
127       std::list< SMESH_OctreeNode* > treeList;
128       std::list< SMESH_OctreeNode* >::iterator trIt;
129       treeList.push_back( myOctreeNode );
130
131       gp_XYZ pointNode( thePnt.X(), thePnt.Y(), thePnt.Z() );
132       bool pointInside = myOctreeNode->isInside( pointNode, myHalfLeafSize );
133       for ( trIt = treeList.begin(); trIt != treeList.end(); ++trIt)
134       {
135         SMESH_OctreeNode* tree = *trIt;
136         if ( !tree->isLeaf() ) // put children to the queue
137         {
138           if ( pointInside && !tree->isInside( pointNode, myHalfLeafSize )) continue;
139           SMESH_OctreeNodeIteratorPtr cIt = tree->GetChildrenIterator();
140           while ( cIt->more() )
141             treeList.push_back( cIt->next() );
142         }
143         else if ( tree->NbNodes() ) // put a tree to the treeMap
144         {
145           const Bnd_B3d& box = *tree->getBox();
146           double sqDist = thePnt.SquareDistance( 0.5 * ( box.CornerMin() + box.CornerMax() ));
147           treeMap.insert( std::make_pair( sqDist, tree ));
148         }
149       }
150       // find distance after which there is no sense to check tree's
151       double sqLimit = DBL_MAX;
152       TDistTreeMap::iterator sqDist_tree = treeMap.begin();
153       if ( treeMap.size() > 5 ) {
154         SMESH_OctreeNode* closestTree = sqDist_tree->second;
155         const Bnd_B3d& box = *closestTree->getBox();
156         double limit = sqrt( sqDist_tree->first ) + sqrt ( box.SquareExtent() );
157         sqLimit = limit * limit;
158       }
159       // get all nodes from trees
160       for ( ; sqDist_tree != treeMap.end(); ++sqDist_tree) {
161         if ( sqDist_tree->first > sqLimit )
162           break;
163         SMESH_OctreeNode* tree = sqDist_tree->second;
164         tree->AllNodesAround( tree->GetNodeIterator()->next(), &nodes );
165       }
166     }
167     // find closest among nodes
168     minSqDist = DBL_MAX;
169     const SMDS_MeshNode* closestNode = 0;
170     for ( size_t i = 0; i < nodes.size(); ++i )
171     {
172       double sqDist = thePnt.SquareDistance( SMESH_NodeXYZ( nodes[ i ]));
173       if ( minSqDist > sqDist ) {
174         closestNode = nodes[ i ];
175         minSqDist = sqDist;
176       }
177     }
178     return closestNode;
179   }
180
181   //---------------------------------------------------------------------
182   /*!
183    * \brief Finds nodes located within a tolerance near a point
184    */
185   int FindNearPoint(const gp_Pnt&                        point,
186                     const double                         tolerance,
187                     std::vector< const SMDS_MeshNode* >& foundNodes)
188   {
189     myOctreeNode->NodesAround( point.Coord(), foundNodes, tolerance );
190     return foundNodes.size();
191   }
192
193   //---------------------------------------------------------------------
194   /*!
195    * \brief Destructor
196    */
197   ~SMESH_NodeSearcherImpl() { delete myOctreeNode; }
198
199   //---------------------------------------------------------------------
200   /*!
201    * \brief Return the node tree
202    */
203   const SMESH_OctreeNode* getTree() const { return myOctreeNode; }
204
205 private:
206   SMESH_OctreeNode* myOctreeNode;
207   SMDS_Mesh*        myMesh;
208   double            myHalfLeafSize; // max size of a leaf box
209 };
210
211 // ========================================================================
212 namespace // Utils used in SMESH_ElementSearcherImpl::FindElementsByPoint()
213 {
214   const int MaxNbElemsInLeaf = 10; // maximal number of elements in a leaf of tree
215   const int MaxLevel         = 7;  // maximal tree height -> nb terminal boxes: 8^7 = 2097152
216   const double NodeRadius = 1e-9;  // to enlarge bnd box of element
217
218   //=======================================================================
219   /*!
220    * \brief Octal tree of bounding boxes of elements
221    */
222   //=======================================================================
223
224   class ElementBndBoxTree : public SMESH_Octree
225   {
226   public:
227
228     typedef boost::container::flat_set< const SMDS_MeshElement*, TIDCompare > TElemSeq;
229
230     ElementBndBoxTree(const SMDS_Mesh&     mesh,
231                       SMDSAbs_ElementType  elemType,
232                       SMDS_ElemIteratorPtr theElemIt = SMDS_ElemIteratorPtr(),
233                       double               tolerance = NodeRadius );
234     void getElementsNearPoint( const gp_Pnt& point, TElemSeq& foundElems );
235     void getElementsNearLine ( const gp_Ax1& line,  TElemSeq& foundElems );
236     void getElementsInBox    ( const Bnd_B3d& box,  TElemSeq& foundElems );
237     void getElementsInSphere ( const gp_XYZ& center, const double radius, TElemSeq& foundElems );
238     ElementBndBoxTree* getLeafAtPoint( const gp_XYZ& point );
239
240   protected:
241     ElementBndBoxTree() {}
242     SMESH_Octree* newChild() const { return new ElementBndBoxTree; }
243     void          buildChildrenData();
244     Bnd_B3d*      buildRootBox();
245   private:
246     //!< Bounding box of element
247     struct ElementBox : public Bnd_B3d
248     {
249       const SMDS_MeshElement* _element;
250       void init(const SMDS_MeshElement* elem, double tolerance);
251     };
252     std::vector< ElementBox* > _elements;
253
254     typedef ObjectPool< ElementBox > TElementBoxPool;
255
256     //!< allocator of ElementBox's and SMESH_TreeLimit
257     struct LimitAndPool : public SMESH_TreeLimit
258     {
259       TElementBoxPool _elBoPool;
260       LimitAndPool():SMESH_TreeLimit( MaxLevel, /*minSize=*/0. ) {}
261     };
262     LimitAndPool* getLimitAndPool() const
263     {
264       SMESH_TreeLimit* limitAndPool = const_cast< SMESH_TreeLimit* >( myLimit );
265       return static_cast< LimitAndPool* >( limitAndPool );
266     }
267   };
268
269   //================================================================================
270   /*!
271    * \brief ElementBndBoxTree creation
272    */
273   //================================================================================
274
275   ElementBndBoxTree::ElementBndBoxTree(const SMDS_Mesh&     mesh,
276                                        SMDSAbs_ElementType  elemType,
277                                        SMDS_ElemIteratorPtr theElemIt,
278                                        double               tolerance)
279     :SMESH_Octree( new LimitAndPool() )
280   {
281     int nbElems = mesh.GetMeshInfo().NbElements( elemType );
282     _elements.reserve( nbElems );
283
284     TElementBoxPool& elBoPool = getLimitAndPool()->_elBoPool;
285
286     SMDS_ElemIteratorPtr elemIt = theElemIt ? theElemIt : mesh.elementsIterator( elemType );
287     while ( elemIt->more() )
288     {
289       ElementBox* eb = elBoPool.getNew();
290       eb->init( elemIt->next(), tolerance );
291       _elements.push_back( eb );
292     }
293     compute();
294   }
295
296   //================================================================================
297   /*!
298    * \brief Return the maximal box
299    */
300   //================================================================================
301
302   Bnd_B3d* ElementBndBoxTree::buildRootBox()
303   {
304     Bnd_B3d* box = new Bnd_B3d;
305     for ( size_t i = 0; i < _elements.size(); ++i )
306       box->Add( *_elements[i] );
307     return box;
308   }
309
310   //================================================================================
311   /*!
312    * \brief Redistrubute element boxes among children
313    */
314   //================================================================================
315
316   void ElementBndBoxTree::buildChildrenData()
317   {
318     for ( size_t i = 0; i < _elements.size(); ++i )
319     {
320       for (int j = 0; j < 8; j++)
321       {
322         if ( !_elements[i]->IsOut( *myChildren[j]->getBox() ))
323           ((ElementBndBoxTree*)myChildren[j])->_elements.push_back( _elements[i]);
324       }
325     }
326     //_size = _elements.size();
327     SMESHUtils::FreeVector( _elements ); // = _elements.clear() + free memory
328
329     for (int j = 0; j < 8; j++)
330     {
331       ElementBndBoxTree* child = static_cast<ElementBndBoxTree*>( myChildren[j]);
332       if ((int) child->_elements.size() <= MaxNbElemsInLeaf )
333         child->myIsLeaf = true;
334
335       if ( child->isLeaf() && child->_elements.capacity() > child->_elements.size() )
336         SMESHUtils::CompactVector( child->_elements );
337     }
338   }
339
340   //================================================================================
341   /*!
342    * \brief Return elements which can include the point
343    */
344   //================================================================================
345
346   void ElementBndBoxTree::getElementsNearPoint( const gp_Pnt& point, TElemSeq& foundElems)
347   {
348     if ( getBox()->IsOut( point.XYZ() ))
349       return;
350
351     if ( isLeaf() )
352     {
353       for ( size_t i = 0; i < _elements.size(); ++i )
354         if ( !_elements[i]->IsOut( point.XYZ() ))
355           foundElems.insert( _elements[i]->_element );
356     }
357     else
358     {
359       for (int i = 0; i < 8; i++)
360         ((ElementBndBoxTree*) myChildren[i])->getElementsNearPoint( point, foundElems );
361     }
362   }
363
364   //================================================================================
365   /*!
366    * \brief Return elements which can be intersected by the line
367    */
368   //================================================================================
369
370   void ElementBndBoxTree::getElementsNearLine( const gp_Ax1& line, TElemSeq& foundElems )
371   {
372     if ( getBox()->IsOut( line ))
373       return;
374
375     if ( isLeaf() )
376     {
377       for ( size_t i = 0; i < _elements.size(); ++i )
378         if ( !_elements[i]->IsOut( line ) )
379           foundElems.insert( _elements[i]->_element );
380     }
381     else
382     {
383       for (int i = 0; i < 8; i++)
384         ((ElementBndBoxTree*) myChildren[i])->getElementsNearLine( line, foundElems );
385     }
386   }
387
388   //================================================================================
389   /*!
390    * \brief Return elements from leaves intersecting the sphere
391    */
392   //================================================================================
393
394   void ElementBndBoxTree::getElementsInSphere ( const gp_XYZ& center,
395                                                 const double  radius,
396                                                 TElemSeq&     foundElems)
397   {
398     if ( getBox()->IsOut( center, radius ))
399       return;
400
401     if ( isLeaf() )
402     {
403       for ( size_t i = 0; i < _elements.size(); ++i )
404         if ( !_elements[i]->IsOut( center, radius ))
405           foundElems.insert( _elements[i]->_element );
406     }
407     else
408     {
409       for (int i = 0; i < 8; i++)
410         ((ElementBndBoxTree*) myChildren[i])->getElementsInSphere( center, radius, foundElems );
411     }
412   }
413
414   //================================================================================
415   /*!
416    * \brief Return elements from leaves intersecting the box
417    */
418   //================================================================================
419
420   void ElementBndBoxTree::getElementsInBox( const Bnd_B3d& box,  TElemSeq& foundElems )
421   {
422     if ( getBox()->IsOut( box ))
423       return;
424
425     if ( isLeaf() )
426     {
427       for ( size_t i = 0; i < _elements.size(); ++i )
428         if ( !_elements[i]->IsOut( box ))
429           foundElems.insert( _elements[i]->_element );
430     }
431     else
432     {
433       for (int i = 0; i < 8; i++)
434         ((ElementBndBoxTree*) myChildren[i])->getElementsInBox( box, foundElems );
435     }
436   }
437
438   //================================================================================
439   /*!
440    * \brief Return a leaf including a point
441    */
442   //================================================================================
443
444   ElementBndBoxTree* ElementBndBoxTree::getLeafAtPoint( const gp_XYZ& point )
445   {
446     if ( getBox()->IsOut( point ))
447       return 0;
448
449     if ( isLeaf() )
450     {
451       return this;
452     }
453     else
454     {
455       for (int i = 0; i < 8; i++)
456         if ( ElementBndBoxTree* l = ((ElementBndBoxTree*) myChildren[i])->getLeafAtPoint( point ))
457           return l;
458     }
459     return 0;
460   }
461
462   //================================================================================
463   /*!
464    * \brief Construct the element box
465    */
466   //================================================================================
467
468   void ElementBndBoxTree::ElementBox::init(const SMDS_MeshElement* elem, double tolerance)
469   {
470     _element  = elem;
471     SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
472     while ( nIt->more() )
473       Add( SMESH_NodeXYZ( nIt->next() ));
474     Enlarge( tolerance );
475   }
476
477 } // namespace
478
479 //=======================================================================
480 /*!
481  * \brief Implementation of search for the elements by point and
482  *        of classification of point in 2D mesh
483  */
484 //=======================================================================
485
486 SMESH_ElementSearcher::~SMESH_ElementSearcher()
487 {
488 }
489
490 struct SMESH_ElementSearcherImpl: public SMESH_ElementSearcher
491 {
492   SMDS_Mesh*                        _mesh;
493   SMDS_ElemIteratorPtr              _meshPartIt;
494   ElementBndBoxTree*                _ebbTree      [SMDSAbs_NbElementTypes];
495   int                               _ebbTreeHeight[SMDSAbs_NbElementTypes];
496   SMESH_NodeSearcherImpl*           _nodeSearcher;
497   SMDSAbs_ElementType               _elementType;
498   double                            _tolerance;
499   bool                              _outerFacesFound;
500   std::set<const SMDS_MeshElement*> _outerFaces; // empty means "no internal faces at all"
501
502   SMESH_ElementSearcherImpl( SMDS_Mesh&           mesh,
503                              double               tol=-1,
504                              SMDS_ElemIteratorPtr elemIt=SMDS_ElemIteratorPtr())
505     : _mesh(&mesh),_meshPartIt(elemIt),_nodeSearcher(0),_tolerance(tol),_outerFacesFound(false)
506   {
507     for ( int i = 0; i < SMDSAbs_NbElementTypes; ++i )
508     {
509       _ebbTree[i] = NULL;
510       _ebbTreeHeight[i] = -1;
511     }
512     _elementType = SMDSAbs_All;
513   }
514   virtual ~SMESH_ElementSearcherImpl()
515   {
516     for ( int i = 0; i < SMDSAbs_NbElementTypes; ++i )
517     {
518       delete _ebbTree[i]; _ebbTree[i] = NULL;
519     }
520     if ( _nodeSearcher ) delete _nodeSearcher; _nodeSearcher = 0;
521   }
522   virtual int FindElementsByPoint(const gp_Pnt&                           point,
523                                   SMDSAbs_ElementType                     type,
524                                   std::vector< const SMDS_MeshElement* >& foundElements);
525   virtual TopAbs_State GetPointState(const gp_Pnt& point);
526   virtual const SMDS_MeshElement* FindClosestTo( const gp_Pnt&       point,
527                                                  SMDSAbs_ElementType type );
528
529   virtual void GetElementsNearLine( const gp_Ax1&                           line,
530                                     SMDSAbs_ElementType                     type,
531                                     std::vector< const SMDS_MeshElement* >& foundElems);
532   virtual void GetElementsInSphere( const gp_XYZ&                           center,
533                                     const double                            radius,
534                                     SMDSAbs_ElementType                     type,
535                                     std::vector< const SMDS_MeshElement* >& foundElems);
536   virtual void GetElementsInBox( const Bnd_B3d&                          box,
537                                  SMDSAbs_ElementType                     type,
538                                  std::vector< const SMDS_MeshElement* >& foundElems);
539   virtual gp_XYZ Project(const gp_Pnt&            point,
540                          SMDSAbs_ElementType      type,
541                          const SMDS_MeshElement** closestElem);
542   double getTolerance();
543   bool getIntersParamOnLine(const gp_Lin& line, const SMDS_MeshElement* face,
544                             const double tolerance, double & param);
545   void findOuterBoundary(const SMDS_MeshElement* anyOuterFace);
546   bool isOuterBoundary(const SMDS_MeshElement* face) const
547   {
548     return _outerFaces.empty() || _outerFaces.count(face);
549   }
550   int getTreeHeight()
551   {
552     if ( _ebbTreeHeight[ _elementType ] < 0 )
553       _ebbTreeHeight[ _elementType ] = _ebbTree[ _elementType ]->getHeight();
554     return _ebbTreeHeight[ _elementType ];
555   }
556
557   struct TInters //!< data of intersection of the line and the mesh face (used in GetPointState())
558   {
559     const SMDS_MeshElement* _face;
560     gp_Vec                  _faceNorm;
561     bool                    _coincides; //!< the line lays in face plane
562     TInters(const SMDS_MeshElement* face, const gp_Vec& faceNorm, bool coinc=false)
563       : _face(face), _faceNorm( faceNorm ), _coincides( coinc ) {}
564   };
565   struct TFaceLink //!< link and faces sharing it (used in findOuterBoundary())
566   {
567     SMESH_TLink      _link;
568     TIDSortedElemSet _faces;
569     TFaceLink( const SMDS_MeshNode* n1, const SMDS_MeshNode* n2, const SMDS_MeshElement* face)
570       : _link( n1, n2 ), _faces( &face, &face + 1) {}
571   };
572 };
573
574 ostream& operator<< (ostream& out, const SMESH_ElementSearcherImpl::TInters& i)
575 {
576   return out << "TInters(face=" << ( i._face ? i._face->GetID() : 0)
577              << ", _coincides="<<i._coincides << ")";
578 }
579
580 //=======================================================================
581 /*!
582  * \brief define tolerance for search
583  */
584 //=======================================================================
585
586 double SMESH_ElementSearcherImpl::getTolerance()
587 {
588   if ( _tolerance < 0 )
589   {
590     const SMDS_MeshInfo& meshInfo = _mesh->GetMeshInfo();
591
592     _tolerance = 0;
593     if ( _nodeSearcher && meshInfo.NbNodes() > 1 )
594     {
595       double boxSize = _nodeSearcher->getTree()->maxSize();
596       _tolerance = 1e-8 * boxSize/* / meshInfo.NbNodes()*/;
597     }
598     else if ( _ebbTree[_elementType] && meshInfo.NbElements() > 0 )
599     {
600       double boxSize = _ebbTree[_elementType]->maxSize();
601       _tolerance = 1e-8 * boxSize/* / meshInfo.NbElements()*/;
602     }
603     if ( _tolerance == 0 )
604     {
605       // define tolerance by size of a most complex element
606       int complexType = SMDSAbs_Volume;
607       while ( complexType > SMDSAbs_All &&
608               meshInfo.NbElements( SMDSAbs_ElementType( complexType )) < 1 )
609         --complexType;
610       if ( complexType == SMDSAbs_All ) return 0; // empty mesh
611       double elemSize;
612       if ( complexType == int( SMDSAbs_Node ))
613       {
614         SMDS_NodeIteratorPtr nodeIt = _mesh->nodesIterator();
615         elemSize = 1;
616         if ( meshInfo.NbNodes() > 2 )
617           elemSize = SMESH_TNodeXYZ( nodeIt->next() ).Distance( nodeIt->next() );
618       }
619       else
620       {
621         SMDS_ElemIteratorPtr  elemIt = _mesh->elementsIterator( SMDSAbs_ElementType( complexType ));
622         const SMDS_MeshElement* elem = elemIt->next();
623         SMDS_ElemIteratorPtr  nodeIt = elem->nodesIterator();
624         SMESH_TNodeXYZ n1( nodeIt->next() );
625         elemSize = 0;
626         while ( nodeIt->more() )
627         {
628           double dist = n1.Distance( static_cast<const SMDS_MeshNode*>( nodeIt->next() ));
629           elemSize = std::max( dist, elemSize );
630         }
631       }
632       _tolerance = 1e-4 * elemSize;
633     }
634   }
635   return _tolerance;
636 }
637
638 //================================================================================
639 /*!
640  * \brief Find intersection of the line and an edge of face and return parameter on line
641  */
642 //================================================================================
643
644 bool SMESH_ElementSearcherImpl::getIntersParamOnLine(const gp_Lin&           line,
645                                                      const SMDS_MeshElement* face,
646                                                      const double            tol,
647                                                      double &                param)
648 {
649   int nbInts = 0;
650   param = 0;
651
652   GeomAPI_ExtremaCurveCurve anExtCC;
653   Handle(Geom_Curve) lineCurve = new Geom_Line( line );
654
655   int nbNodes = face->IsQuadratic() ? face->NbNodes()/2 : face->NbNodes();
656   for ( int i = 0; i < nbNodes && nbInts < 2; ++i )
657   {
658     GC_MakeSegment edge( SMESH_TNodeXYZ( face->GetNode( i )),
659                          SMESH_TNodeXYZ( face->GetNode( (i+1)%nbNodes) ));
660     anExtCC.Init( lineCurve, edge.Value() );
661     if ( anExtCC.NbExtrema() > 0 && anExtCC.LowerDistance() <= tol)
662     {
663       Standard_Real pl, pe;
664       anExtCC.LowerDistanceParameters( pl, pe );
665       param += pl;
666       if ( ++nbInts == 2 )
667         break;
668     }
669   }
670   if ( nbInts > 0 ) param /= nbInts;
671   return nbInts > 0;
672 }
673 //================================================================================
674 /*!
675  * \brief Find all faces belonging to the outer boundary of mesh
676  */
677 //================================================================================
678
679 void SMESH_ElementSearcherImpl::findOuterBoundary(const SMDS_MeshElement* outerFace)
680 {
681   if ( _outerFacesFound ) return;
682
683   // Collect all outer faces by passing from one outer face to another via their links
684   // and BTW find out if there are internal faces at all.
685
686   // checked links and links where outer boundary meets internal one
687   std::set< SMESH_TLink > visitedLinks, seamLinks;
688
689   // links to treat with already visited faces sharing them
690   std::list < TFaceLink > startLinks;
691
692   // load startLinks with the first outerFace
693   startLinks.push_back( TFaceLink( outerFace->GetNode(0), outerFace->GetNode(1), outerFace));
694   _outerFaces.insert( outerFace );
695
696   TIDSortedElemSet emptySet;
697   while ( !startLinks.empty() )
698   {
699     const SMESH_TLink& link  = startLinks.front()._link;
700     TIDSortedElemSet&  faces = startLinks.front()._faces;
701
702     outerFace = *faces.begin();
703     // find other faces sharing the link
704     const SMDS_MeshElement* f;
705     while (( f = SMESH_MeshAlgos::FindFaceInSet(link.node1(), link.node2(), emptySet, faces )))
706       faces.insert( f );
707
708     // select another outer face among the found
709     const SMDS_MeshElement* outerFace2 = 0;
710     if ( faces.size() == 2 )
711     {
712       outerFace2 = (outerFace == *faces.begin() ? *faces.rbegin() : *faces.begin());
713     }
714     else if ( faces.size() > 2 )
715     {
716       seamLinks.insert( link );
717
718       // link direction within the outerFace
719       gp_Vec n1n2( SMESH_TNodeXYZ( link.node1()),
720                    SMESH_TNodeXYZ( link.node2()));
721       int i1 = outerFace->GetNodeIndex( link.node1() );
722       int i2 = outerFace->GetNodeIndex( link.node2() );
723       bool rev = ( abs(i2-i1) == 1 ? i1 > i2 : i2 > i1 );
724       if ( rev ) n1n2.Reverse();
725       // outerFace normal
726       gp_XYZ ofNorm, fNorm;
727       if ( SMESH_MeshAlgos::FaceNormal( outerFace, ofNorm, /*normalized=*/false ))
728       {
729         // direction from the link inside outerFace
730         gp_Vec dirInOF = gp_Vec( ofNorm ) ^ n1n2;
731         // sort all other faces by angle with the dirInOF
732         std::map< double, const SMDS_MeshElement* > angle2Face;
733         std::set< const SMDS_MeshElement*, TIDCompare >::const_iterator face = faces.begin();
734         for ( ; face != faces.end(); ++face )
735         {
736           if ( *face == outerFace ) continue;
737           if ( !SMESH_MeshAlgos::FaceNormal( *face, fNorm, /*normalized=*/false ))
738             continue;
739           gp_Vec dirInF = gp_Vec( fNorm ) ^ n1n2;
740           double angle = dirInOF.AngleWithRef( dirInF, n1n2 );
741           if ( angle < 0 ) angle += 2. * M_PI;
742           angle2Face.insert( std::make_pair( angle, *face ));
743         }
744         if ( !angle2Face.empty() )
745           outerFace2 = angle2Face.begin()->second;
746       }
747     }
748     // store the found outer face and add its links to continue searching from
749     if ( outerFace2 )
750     {
751       _outerFaces.insert( outerFace2 );
752       int nbNodes = outerFace2->NbCornerNodes();
753       for ( int i = 0; i < nbNodes; ++i )
754       {
755         SMESH_TLink link2( outerFace2->GetNode(i), outerFace2->GetNode((i+1)%nbNodes));
756         if ( visitedLinks.insert( link2 ).second )
757           startLinks.push_back( TFaceLink( link2.node1(), link2.node2(), outerFace2 ));
758       }
759     }
760     startLinks.pop_front();
761   }
762   _outerFacesFound = true;
763
764   if ( !seamLinks.empty() )
765   {
766     // There are internal boundaries touching the outher one,
767     // find all faces of internal boundaries in order to find
768     // faces of boundaries of holes, if any.
769
770   }
771   else
772   {
773     _outerFaces.clear();
774   }
775 }
776
777 //=======================================================================
778 /*!
779  * \brief Find elements of given type where the given point is IN or ON.
780  *        Returns nb of found elements and elements them-selves.
781  *
782  * 'ALL' type means elements of any type excluding nodes, balls and 0D elements
783  */
784 //=======================================================================
785
786 int SMESH_ElementSearcherImpl::
787 FindElementsByPoint(const gp_Pnt&                           point,
788                     SMDSAbs_ElementType                     type,
789                     std::vector< const SMDS_MeshElement* >& foundElements)
790 {
791   foundElements.clear();
792   _elementType = type;
793
794   double tolerance = getTolerance();
795
796   // =================================================================================
797   if ( type == SMDSAbs_Node || type == SMDSAbs_0DElement || type == SMDSAbs_Ball)
798   {
799     if ( !_nodeSearcher )
800     {
801       if ( _meshPartIt )
802         _nodeSearcher = new SMESH_NodeSearcherImpl( 0, _meshPartIt );
803       else
804         _nodeSearcher = new SMESH_NodeSearcherImpl( _mesh );
805     }
806     std::vector< const SMDS_MeshNode* > foundNodes;
807     _nodeSearcher->FindNearPoint( point, tolerance, foundNodes );
808
809     if ( type == SMDSAbs_Node )
810     {
811       foundElements.assign( foundNodes.begin(), foundNodes.end() );
812     }
813     else
814     {
815       for ( size_t i = 0; i < foundNodes.size(); ++i )
816       {
817         SMDS_ElemIteratorPtr elemIt = foundNodes[i]->GetInverseElementIterator( type );
818         while ( elemIt->more() )
819           foundElements.push_back( elemIt->next() );
820       }
821     }
822   }
823   // =================================================================================
824   else // elements more complex than 0D
825   {
826     if ( !_ebbTree[type] )
827     {
828       _ebbTree[_elementType] = new ElementBndBoxTree( *_mesh, type, _meshPartIt, tolerance );
829     }
830     ElementBndBoxTree::TElemSeq suspectElems;
831     _ebbTree[ type ]->getElementsNearPoint( point, suspectElems );
832     ElementBndBoxTree::TElemSeq::iterator elem = suspectElems.begin();
833     for ( ; elem != suspectElems.end(); ++elem )
834       if ( !SMESH_MeshAlgos::IsOut( *elem, point, tolerance ))
835         foundElements.push_back( *elem );
836   }
837   return foundElements.size();
838 }
839
840 //=======================================================================
841 /*!
842  * \brief Find an element of given type most close to the given point
843  *
844  * WARNING: Only face search is implemeneted so far
845  */
846 //=======================================================================
847
848 const SMDS_MeshElement*
849 SMESH_ElementSearcherImpl::FindClosestTo( const gp_Pnt&       point,
850                                           SMDSAbs_ElementType type )
851 {
852   const SMDS_MeshElement* closestElem = 0;
853   _elementType = type;
854
855   if ( type == SMDSAbs_Face ||
856        type == SMDSAbs_Volume ||
857        type == SMDSAbs_Edge )
858   {
859     ElementBndBoxTree*& ebbTree = _ebbTree[ type ];
860     if ( !ebbTree )
861       ebbTree = new ElementBndBoxTree( *_mesh, type, _meshPartIt );
862
863     ElementBndBoxTree::TElemSeq suspectElems;
864     ebbTree->getElementsNearPoint( point, suspectElems );
865
866     if ( suspectElems.empty() && ebbTree->maxSize() > 0 )
867     {
868       gp_Pnt boxCenter = 0.5 * ( ebbTree->getBox()->CornerMin() +
869                                  ebbTree->getBox()->CornerMax() );
870       double radius = -1;
871       if ( ebbTree->getBox()->IsOut( point.XYZ() ))
872         radius = point.Distance( boxCenter ) - 0.5 * ebbTree->maxSize();
873       if ( radius < 0 )
874         radius = ebbTree->maxSize() / pow( 2., getTreeHeight()) / 2;
875       while ( suspectElems.empty() )
876       {
877         ebbTree->getElementsInSphere( point.XYZ(), radius, suspectElems );
878         radius *= 1.1;
879       }
880     }
881     double minDist = std::numeric_limits<double>::max();
882     std::multimap< double, const SMDS_MeshElement* > dist2face;
883     ElementBndBoxTree::TElemSeq::iterator elem = suspectElems.begin();
884     for ( ; elem != suspectElems.end(); ++elem )
885     {
886       double dist = SMESH_MeshAlgos::GetDistance( *elem, point );
887       if ( dist < minDist + 1e-10)
888       {
889         minDist = dist;
890         dist2face.insert( dist2face.begin(), std::make_pair( dist, *elem ));
891       }
892     }
893     if ( !dist2face.empty() )
894     {
895       std::multimap< double, const SMDS_MeshElement* >::iterator d2f = dist2face.begin();
896       closestElem = d2f->second;
897       // if there are several elements at the same distance, select one
898       // with GC closest to the point
899       typedef SMDS_StdIterator< SMESH_TNodeXYZ, SMDS_ElemIteratorPtr > TXyzIterator;
900       double minDistToGC = 0;
901       for ( ++d2f; d2f != dist2face.end() && fabs( d2f->first - minDist ) < 1e-10; ++d2f )
902       {
903         if ( minDistToGC == 0 )
904         {
905           gp_XYZ gc(0,0,0);
906           gc = accumulate( TXyzIterator(closestElem->nodesIterator()),
907                            TXyzIterator(), gc ) / closestElem->NbNodes();
908           minDistToGC = point.SquareDistance( gc );
909         }
910         gp_XYZ gc(0,0,0);
911         gc = accumulate( TXyzIterator( d2f->second->nodesIterator()),
912                          TXyzIterator(), gc ) / d2f->second->NbNodes();
913         double d = point.SquareDistance( gc );
914         if ( d < minDistToGC )
915         {
916           minDistToGC = d;
917           closestElem = d2f->second;
918         }
919       }
920       // cout << "FindClosestTo( " <<point.X()<<", "<<point.Y()<<", "<<point.Z()<<" ) FACE "
921       //      <<closestElem->GetID() << " DIST " << minDist << endl;
922     }
923   }
924   else
925   {
926     // NOT IMPLEMENTED SO FAR
927   }
928   return closestElem;
929 }
930
931
932 //================================================================================
933 /*!
934  * \brief Classify the given point in the closed 2D mesh
935  */
936 //================================================================================
937
938 TopAbs_State SMESH_ElementSearcherImpl::GetPointState(const gp_Pnt& point)
939 {
940   _elementType = SMDSAbs_Face;
941
942   double tolerance = getTolerance();
943
944   ElementBndBoxTree*& ebbTree = _ebbTree[ SMDSAbs_Face ];
945   if ( !ebbTree )
946     ebbTree = new ElementBndBoxTree( *_mesh, _elementType, _meshPartIt );
947
948   // Algo: analyse transition of a line starting at the point through mesh boundary;
949   // try three lines parallel to axis of the coordinate system and perform rough
950   // analysis. If solution is not clear perform thorough analysis.
951
952   const int nbAxes = 3;
953   gp_Dir axisDir[ nbAxes ] = { gp::DX(), gp::DY(), gp::DZ() };
954   std::map< double, TInters >   paramOnLine2TInters[ nbAxes ];
955   std::list< TInters > tangentInters[ nbAxes ]; // of faces whose plane includes the line
956   std::multimap< int, int > nbInt2Axis; // to find the simplest case
957   for ( int axis = 0; axis < nbAxes; ++axis )
958   {
959     gp_Ax1 lineAxis( point, axisDir[axis]);
960     gp_Lin line    ( lineAxis );
961
962     ElementBndBoxTree::TElemSeq suspectFaces; // faces possibly intersecting the line
963     ebbTree->getElementsNearLine( lineAxis, suspectFaces );
964
965     // Intersect faces with the line
966
967     std::map< double, TInters > & u2inters = paramOnLine2TInters[ axis ];
968     ElementBndBoxTree::TElemSeq::iterator face = suspectFaces.begin();
969     for ( ; face != suspectFaces.end(); ++face )
970     {
971       // get face plane
972       gp_XYZ fNorm;
973       if ( !SMESH_MeshAlgos::FaceNormal( *face, fNorm, /*normalized=*/false)) continue;
974       gp_Pln facePlane( SMESH_TNodeXYZ( (*face)->GetNode(0)), fNorm );
975
976       // perform intersection
977       IntAna_IntConicQuad intersection( line, IntAna_Quadric( facePlane ));
978       if ( !intersection.IsDone() )
979         continue;
980       if ( intersection.IsInQuadric() )
981       {
982         tangentInters[ axis ].push_back( TInters( *face, fNorm, true ));
983       }
984       else if ( ! intersection.IsParallel() && intersection.NbPoints() > 0 )
985       {
986         double tol = 1e-4 * Sqrt( fNorm.Modulus() );
987         gp_Pnt intersectionPoint = intersection.Point(1);
988         if ( !SMESH_MeshAlgos::IsOut( *face, intersectionPoint, tol ))
989           u2inters.insert( std::make_pair( intersection.ParamOnConic(1), TInters( *face, fNorm )));
990       }
991     }
992     // Analyse intersections roughly
993
994     int nbInter = u2inters.size();
995     if ( nbInter == 0 )
996       return TopAbs_OUT;
997
998     double f = u2inters.begin()->first, l = u2inters.rbegin()->first;
999     if ( nbInter == 1 ) // not closed mesh
1000       return fabs( f ) < tolerance ? TopAbs_ON : TopAbs_UNKNOWN;
1001
1002     if ( fabs( f ) < tolerance || fabs( l ) < tolerance )
1003       return TopAbs_ON;
1004
1005     if ( (f<0) == (l<0) )
1006       return TopAbs_OUT;
1007
1008     int nbIntBeforePoint = std::distance( u2inters.begin(), u2inters.lower_bound(0));
1009     int nbIntAfterPoint  = nbInter - nbIntBeforePoint;
1010     if ( nbIntBeforePoint == 1 || nbIntAfterPoint == 1 )
1011       return TopAbs_IN;
1012
1013     nbInt2Axis.insert( std::make_pair( std::min( nbIntBeforePoint, nbIntAfterPoint ), axis ));
1014
1015     if ( _outerFacesFound ) break; // pass to thorough analysis
1016
1017   } // three attempts - loop on CS axes
1018
1019   // Analyse intersections thoroughly.
1020   // We make two loops maximum, on the first one we only exclude touching intersections,
1021   // on the second, if situation is still unclear, we gather and use information on
1022   // position of faces (internal or outer). If faces position is already gathered,
1023   // we make the second loop right away.
1024
1025   for ( int hasPositionInfo = _outerFacesFound; hasPositionInfo < 2; ++hasPositionInfo )
1026   {
1027     std::multimap< int, int >::const_iterator nb_axis = nbInt2Axis.begin();
1028     for ( ; nb_axis != nbInt2Axis.end(); ++nb_axis )
1029     {
1030       int axis = nb_axis->second;
1031       std::map< double, TInters > & u2inters = paramOnLine2TInters[ axis ];
1032
1033       gp_Ax1 lineAxis( point, axisDir[axis]);
1034       gp_Lin line    ( lineAxis );
1035
1036       // add tangent intersections to u2inters
1037       double param;
1038       std::list< TInters >::const_iterator tgtInt = tangentInters[ axis ].begin();
1039       for ( ; tgtInt != tangentInters[ axis ].end(); ++tgtInt )
1040         if ( getIntersParamOnLine( line, tgtInt->_face, tolerance, param ))
1041           u2inters.insert( std::make_pair( param, *tgtInt ));
1042       tangentInters[ axis ].clear();
1043
1044       // Count intersections before and after the point excluding touching ones.
1045       // If hasPositionInfo we count intersections of outer boundary only
1046
1047       int nbIntBeforePoint = 0, nbIntAfterPoint = 0;
1048       double f = std::numeric_limits<double>::max(), l = -std::numeric_limits<double>::max();
1049       std::map< double, TInters >::iterator u_int1 = u2inters.begin(), u_int2 = u_int1;
1050       bool ok = ! u_int1->second._coincides;
1051       while ( ok && u_int1 != u2inters.end() )
1052       {
1053         double u = u_int1->first;
1054         bool touchingInt = false;
1055         if ( ++u_int2 != u2inters.end() )
1056         {
1057           // skip intersections at the same point (if the line passes through edge or node)
1058           int nbSamePnt = 0;
1059           while ( u_int2 != u2inters.end() && fabs( u_int2->first - u ) < tolerance )
1060           {
1061             ++nbSamePnt;
1062             ++u_int2;
1063           }
1064
1065           // skip tangent intersections
1066           int nbTgt = 0;
1067           if ( u_int2 != u2inters.end() )
1068           {
1069             const SMDS_MeshElement* prevFace = u_int1->second._face;
1070             while ( ok && u_int2->second._coincides )
1071             {
1072               if ( SMESH_MeshAlgos::GetCommonNodes(prevFace , u_int2->second._face).empty() )
1073                 ok = false;
1074               else
1075               {
1076                 nbTgt++;
1077                 u_int2++;
1078                 ok = ( u_int2 != u2inters.end() );
1079               }
1080             }
1081           }
1082           if ( !ok ) break;
1083
1084           // skip intersections at the same point after tangent intersections
1085           if ( nbTgt > 0 )
1086           {
1087             double u2 = u_int2->first;
1088             ++u_int2;
1089             while ( u_int2 != u2inters.end() && fabs( u_int2->first - u2 ) < tolerance )
1090             {
1091               ++nbSamePnt;
1092               ++u_int2;
1093             }
1094           }
1095           // decide if we skipped a touching intersection
1096           if ( nbSamePnt + nbTgt > 0 )
1097           {
1098             double minDot = std::numeric_limits<double>::max(), maxDot = -minDot;
1099             std::map< double, TInters >::iterator u_int = u_int1;
1100             for ( ; u_int != u_int2; ++u_int )
1101             {
1102               if ( u_int->second._coincides ) continue;
1103               double dot = u_int->second._faceNorm * line.Direction();
1104               if ( dot > maxDot ) maxDot = dot;
1105               if ( dot < minDot ) minDot = dot;
1106             }
1107             touchingInt = ( minDot*maxDot < 0 );
1108           }
1109         }
1110         if ( !touchingInt )
1111         {
1112           if ( !hasPositionInfo || isOuterBoundary( u_int1->second._face ))
1113           {
1114             if ( u < 0 )
1115               ++nbIntBeforePoint;
1116             else
1117               ++nbIntAfterPoint;
1118           }
1119           if ( u < f ) f = u;
1120           if ( u > l ) l = u;
1121         }
1122
1123         u_int1 = u_int2; // to next intersection
1124
1125       } // loop on intersections with one line
1126
1127       if ( ok )
1128       {
1129         if ( fabs( f ) < tolerance || fabs( l ) < tolerance )
1130           return TopAbs_ON;
1131
1132         if ( nbIntBeforePoint == 0  || nbIntAfterPoint == 0)
1133           return TopAbs_OUT;
1134
1135         if ( nbIntBeforePoint + nbIntAfterPoint == 1 ) // not closed mesh
1136           return fabs( f ) < tolerance ? TopAbs_ON : TopAbs_UNKNOWN;
1137
1138         if ( nbIntBeforePoint == 1 || nbIntAfterPoint == 1 )
1139           return TopAbs_IN;
1140
1141         if ( (f<0) == (l<0) )
1142           return TopAbs_OUT;
1143
1144         if ( hasPositionInfo )
1145           return nbIntBeforePoint % 2 ? TopAbs_IN : TopAbs_OUT;
1146       }
1147     } // loop on intersections of the tree lines - thorough analysis
1148
1149     if ( !hasPositionInfo )
1150     {
1151       // gather info on faces position - is face in the outer boundary or not
1152       std::map< double, TInters > & u2inters = paramOnLine2TInters[ 0 ];
1153       findOuterBoundary( u2inters.begin()->second._face );
1154     }
1155
1156   } // two attempts - with and w/o faces position info in the mesh
1157
1158   return TopAbs_UNKNOWN;
1159 }
1160
1161 //=======================================================================
1162 /*!
1163  * \brief Return elements possibly intersecting the line
1164  */
1165 //=======================================================================
1166
1167 void SMESH_ElementSearcherImpl::
1168 GetElementsNearLine( const gp_Ax1&                           line,
1169                      SMDSAbs_ElementType                     type,
1170                      std::vector< const SMDS_MeshElement* >& foundElems)
1171 {
1172   _elementType = type;
1173   ElementBndBoxTree*& ebbTree = _ebbTree[ type ];
1174   if ( !ebbTree )
1175     ebbTree = new ElementBndBoxTree( *_mesh, _elementType, _meshPartIt );
1176
1177   ElementBndBoxTree::TElemSeq elems;
1178   ebbTree->getElementsNearLine( line, elems );
1179
1180   foundElems.insert( foundElems.end(), elems.begin(), elems.end() );
1181 }
1182
1183 //=======================================================================
1184 /*
1185  * Return elements whose bounding box intersects a sphere
1186  */
1187 //=======================================================================
1188
1189 void SMESH_ElementSearcherImpl::
1190 GetElementsInSphere( const gp_XYZ&                           center,
1191                      const double                            radius,
1192                      SMDSAbs_ElementType                     type,
1193                      std::vector< const SMDS_MeshElement* >& foundElems)
1194 {
1195   _elementType = type;
1196   ElementBndBoxTree*& ebbTree = _ebbTree[ type ];
1197   if ( !ebbTree )
1198     ebbTree = new ElementBndBoxTree( *_mesh, _elementType, _meshPartIt );
1199
1200   ElementBndBoxTree::TElemSeq elems;
1201   ebbTree->getElementsInSphere( center, radius, elems );
1202
1203   foundElems.insert( foundElems.end(), elems.begin(), elems.end() );
1204 }
1205
1206 //=======================================================================
1207 /*
1208  * Return elements whose bounding box intersects a given bounding box
1209  */
1210 //=======================================================================
1211
1212 void SMESH_ElementSearcherImpl::
1213 GetElementsInBox( const Bnd_B3d&                          box,
1214                   SMDSAbs_ElementType                     type,
1215                   std::vector< const SMDS_MeshElement* >& foundElems)
1216 {
1217   _elementType = type;
1218   ElementBndBoxTree*& ebbTree = _ebbTree[ type ];
1219   if ( !ebbTree )
1220     ebbTree = new ElementBndBoxTree( *_mesh, _elementType, _meshPartIt, getTolerance() );
1221
1222   ElementBndBoxTree::TElemSeq elems;
1223   ebbTree->getElementsInBox( box, elems );
1224
1225   foundElems.insert( foundElems.end(), elems.begin(), elems.end() );
1226 }
1227
1228 //=======================================================================
1229 /*
1230  * \brief Return a projection of a given point to a mesh.
1231  *        Optionally return the closest element
1232  */
1233 //=======================================================================
1234
1235 gp_XYZ SMESH_ElementSearcherImpl::Project(const gp_Pnt&            point,
1236                                           SMDSAbs_ElementType      type,
1237                                           const SMDS_MeshElement** closestElem)
1238 {
1239   _elementType = type;
1240   if ( _mesh->GetMeshInfo().NbElements( _elementType ) == 0 )
1241     throw SALOME_Exception( LOCALIZED( "No elements of given type in the mesh" ));
1242
1243   ElementBndBoxTree*& ebbTree = _ebbTree[ _elementType ];
1244   if ( !ebbTree )
1245     ebbTree = new ElementBndBoxTree( *_mesh, _elementType );
1246
1247   gp_XYZ p = point.XYZ();
1248   ElementBndBoxTree* ebbLeaf = ebbTree->getLeafAtPoint( p );
1249   const Bnd_B3d* box = ebbLeaf->getBox();
1250   double radius = ( box->CornerMax() - box->CornerMin() ).Modulus();
1251
1252   ElementBndBoxTree::TElemSeq elems;
1253   ebbTree->getElementsInSphere( p, radius, elems );
1254   while ( elems.empty() )
1255   {
1256     radius *= 1.5;
1257     ebbTree->getElementsInSphere( p, radius, elems );
1258   }
1259   gp_XYZ proj, bestProj;
1260   const SMDS_MeshElement* elem = 0;
1261   double minDist = 2 * radius;
1262   ElementBndBoxTree::TElemSeq::iterator e = elems.begin();
1263   for ( ; e != elems.end(); ++e )
1264   {
1265     double d = SMESH_MeshAlgos::GetDistance( *e, p, &proj );
1266     if ( d < minDist )
1267     {
1268       bestProj = proj;
1269       elem = *e;
1270       minDist = d;
1271     }
1272   }
1273   if ( closestElem ) *closestElem = elem;
1274
1275   return bestProj;
1276 }
1277
1278 //=======================================================================
1279 /*!
1280  * \brief Return true if the point is IN or ON of the element
1281  */
1282 //=======================================================================
1283
1284 bool SMESH_MeshAlgos::IsOut( const SMDS_MeshElement* element, const gp_Pnt& point, double tol )
1285 {
1286   if ( element->GetType() == SMDSAbs_Volume)
1287   {
1288     return SMDS_VolumeTool( element ).IsOut( point.X(), point.Y(), point.Z(), tol );
1289   }
1290
1291   // get ordered nodes
1292
1293   std::vector< SMESH_TNodeXYZ > xyz; xyz.reserve( element->NbNodes()+1 );
1294
1295   SMDS_ElemIteratorPtr nodeIt = element->interlacedNodesElemIterator();
1296   for ( int i = 0; nodeIt->more(); ++i )
1297     xyz.push_back( SMESH_TNodeXYZ( nodeIt->next() ));
1298
1299   int i, nbNodes = (int) xyz.size(); // central node of biquadratic is missing
1300
1301   if ( element->GetType() == SMDSAbs_Face ) // --------------------------------------------------
1302   {
1303     // compute face normal
1304     gp_Vec faceNorm(0,0,0);
1305     xyz.push_back( xyz.front() );
1306     for ( i = 0; i < nbNodes; ++i )
1307     {
1308       gp_Vec edge1( xyz[i+1], xyz[i]);
1309       gp_Vec edge2( xyz[i+1], xyz[(i+2)%nbNodes] );
1310       faceNorm += edge1 ^ edge2;
1311     }
1312     double fNormSize = faceNorm.Magnitude();
1313     if ( fNormSize <= tol )
1314     {
1315       // degenerated face: point is out if it is out of all face edges
1316       for ( i = 0; i < nbNodes; ++i )
1317       {
1318         SMDS_LinearEdge edge( xyz[i]._node, xyz[i+1]._node );
1319         if ( !IsOut( &edge, point, tol ))
1320           return false;
1321       }
1322       return true;
1323     }
1324     faceNorm /= fNormSize;
1325
1326     // check if the point lays on face plane
1327     gp_Vec n2p( xyz[0], point );
1328     double dot = n2p * faceNorm;
1329     if ( Abs( dot ) > tol ) // not on face plane
1330     {
1331       bool isOut = true;
1332       if ( nbNodes > 3 ) // maybe the face is not planar
1333       {
1334         double elemThick = 0;
1335         for ( i = 1; i < nbNodes; ++i )
1336         {
1337           gp_Vec n2n( xyz[0], xyz[i] );
1338           elemThick = Max( elemThick, Abs( n2n * faceNorm ));
1339         }
1340         isOut = Abs( dot ) > elemThick + tol;
1341       }
1342       if ( isOut )
1343         return isOut;
1344     }
1345
1346     // check if point is out of face boundary:
1347     // define it by closest transition of a ray point->infinity through face boundary
1348     // on the face plane.
1349     // First, find normal of a plane perpendicular to face plane, to be used as a cutting tool
1350     // to find intersections of the ray with the boundary.
1351     gp_Vec ray = n2p;
1352     gp_Vec plnNorm = ray ^ faceNorm;
1353     double n2pSize = plnNorm.Magnitude();
1354     if ( n2pSize <= tol ) return false; // point coincides with the first node
1355     if ( n2pSize * n2pSize > fNormSize * 100 ) return true; // point is very far
1356     plnNorm /= n2pSize;
1357     // for each node of the face, compute its signed distance to the cutting plane
1358     std::vector<double> dist( nbNodes + 1);
1359     for ( i = 0; i < nbNodes; ++i )
1360     {
1361       gp_Vec n2p( xyz[i], point );
1362       dist[i] = n2p * plnNorm;
1363     }
1364     dist.back() = dist.front();
1365     // find the closest intersection
1366     int    iClosest = -1;
1367     double rClosest = 0, distClosest = 1e100;
1368     gp_Pnt pClosest;
1369     for ( i = 0; i < nbNodes; ++i )
1370     {
1371       double r;
1372       if ( fabs( dist[i] ) < tol )
1373         r = 0.;
1374       else if ( fabs( dist[i+1]) < tol )
1375         r = 1.;
1376       else if ( dist[i] * dist[i+1] < 0 )
1377         r = dist[i] / ( dist[i] - dist[i+1] );
1378       else
1379         continue; // no intersection
1380       gp_Pnt pInt = xyz[i] * (1.-r) + xyz[i+1] * r;
1381       gp_Vec p2int( point, pInt);
1382       double intDist = p2int.SquareMagnitude();
1383       if ( intDist < distClosest )
1384       {
1385         iClosest = i;
1386         rClosest = r;
1387         pClosest = pInt;
1388         distClosest = intDist;
1389       }
1390     }
1391     if ( iClosest < 0 )
1392       return true; // no intesections - out
1393
1394     // analyse transition
1395     gp_Vec edge( xyz[iClosest], xyz[iClosest+1] );
1396     gp_Vec edgeNorm = -( edge ^ faceNorm ); // normal to intersected edge pointing out of face
1397     gp_Vec p2int ( point, pClosest );
1398     bool out = (edgeNorm * p2int) < -tol;
1399     if ( rClosest > 0. && rClosest < 1. ) // not node intersection
1400       return out;
1401
1402     // the ray passes through a face node; analyze transition through an adjacent edge
1403     gp_Pnt p1 = xyz[ (rClosest == 0.) ? ((iClosest+nbNodes-1) % nbNodes) : (iClosest+1) ];
1404     gp_Pnt p2 = xyz[ (rClosest == 0.) ? iClosest : ((iClosest+2) % nbNodes) ];
1405     gp_Vec edgeAdjacent( p1, p2 );
1406     gp_Vec edgeNorm2 = -( edgeAdjacent ^ faceNorm );
1407     bool out2 = (edgeNorm2 * p2int) < -tol;
1408
1409     bool covexCorner = ( edgeNorm * edgeAdjacent * (rClosest==1. ? 1. : -1.)) < 0;
1410     return covexCorner ? (out || out2) : (out && out2);
1411   }
1412
1413   if ( element->GetType() == SMDSAbs_Edge ) // --------------------------------------------------
1414   {
1415     // point is out of edge if it is NOT ON any straight part of edge
1416     // (we consider quadratic edge as being composed of two straight parts)
1417     for ( i = 1; i < nbNodes; ++i )
1418     {
1419       gp_Vec edge( xyz[i-1], xyz[i] );
1420       gp_Vec n1p ( xyz[i-1], point  );
1421       double u = ( edge * n1p ) / edge.SquareMagnitude(); // param [0,1] on the edge
1422       if ( u <= 0. ) {
1423         if ( n1p.SquareMagnitude() < tol * tol )
1424           return false;
1425         continue;
1426       }
1427       if ( u >= 1. ) {
1428         if ( point.SquareDistance( xyz[i] ) < tol * tol )
1429           return false;
1430         continue;
1431       }
1432       gp_XYZ proj = ( 1. - u ) * xyz[i-1] + u * xyz[i]; // projection of the point on the edge
1433       double dist2 = point.SquareDistance( proj );
1434       if ( dist2 > tol * tol )
1435         continue;
1436       return false; // point is ON this part
1437     }
1438     return true;
1439   }
1440
1441   // Node or 0D element -------------------------------------------------------------------------
1442   {
1443     gp_Vec n2p ( xyz[0], point );
1444     return n2p.SquareMagnitude() > tol * tol;
1445   }
1446   return true;
1447 }
1448
1449 //=======================================================================
1450 namespace
1451 {
1452   // Position of a point relative to a segment
1453   //            .           .
1454   //            .  LEFT     .
1455   //            .           .
1456   //  VERTEX 1  o----ON----->  VERTEX 2
1457   //            .           .
1458   //            .  RIGHT    .
1459   //            .           .
1460   enum PositionName { POS_LEFT = 1, POS_VERTEX = 2, POS_RIGHT = 4, //POS_ON = 8,
1461                       POS_ALL = POS_LEFT | POS_RIGHT | POS_VERTEX };
1462   struct PointPos
1463   {
1464     PositionName _name;
1465     int          _index; // index of vertex or segment
1466
1467     PointPos( PositionName n, int i=-1 ): _name(n), _index(i) {}
1468     bool operator < (const PointPos& other ) const
1469     {
1470       if ( _name == other._name )
1471         return  ( _index < 0 || other._index < 0 ) ? false : _index < other._index;
1472       return _name < other._name;
1473     }
1474   };
1475
1476   //================================================================================
1477   /*!
1478    * \brief Return of a point relative to a segment
1479    *  \param point2D      - the point to analyze position of
1480    *  \param xyVec        - end points of segments
1481    *  \param index0       - 0-based index of the first point of segment
1482    *  \param posToFindOut - flags of positions to detect
1483    *  \retval PointPos - point position
1484    */
1485   //================================================================================
1486
1487   PointPos getPointPosition( const gp_XY& point2D,
1488                              const gp_XY* segEnds,
1489                              const int    index0 = 0,
1490                              const int    posToFindOut = POS_ALL)
1491   {
1492     const gp_XY& p1 = segEnds[ index0   ];
1493     const gp_XY& p2 = segEnds[ index0+1 ];
1494     const gp_XY grad = p2 - p1;
1495
1496     if ( posToFindOut & POS_VERTEX )
1497     {
1498       // check if the point2D is at "vertex 1" zone
1499       gp_XY pp1[2] = { p1, gp_XY( p1.X() - grad.Y(),
1500                                   p1.Y() + grad.X() ) };
1501       if ( getPointPosition( point2D, pp1, 0, POS_LEFT|POS_RIGHT )._name == POS_LEFT )
1502         return PointPos( POS_VERTEX, index0 );
1503
1504       // check if the point2D is at "vertex 2" zone
1505       gp_XY pp2[2] = { p2, gp_XY( p2.X() - grad.Y(),
1506                                   p2.Y() + grad.X() ) };
1507       if ( getPointPosition( point2D, pp2, 0, POS_LEFT|POS_RIGHT )._name == POS_RIGHT )
1508         return PointPos( POS_VERTEX, index0 + 1);
1509     }
1510     double edgeEquation =
1511       ( point2D.X() - p1.X() ) * grad.Y() - ( point2D.Y() - p1.Y() ) * grad.X();
1512     return PointPos( edgeEquation < 0 ? POS_LEFT : POS_RIGHT, index0 );
1513   }
1514 }
1515
1516 //=======================================================================
1517 /*!
1518  * \brief Return minimal distance from a point to an element
1519  *
1520  * Currently we ignore non-planarity and 2nd order of face
1521  */
1522 //=======================================================================
1523
1524 double SMESH_MeshAlgos::GetDistance( const SMDS_MeshElement* elem,
1525                                      const gp_Pnt&           point,
1526                                      gp_XYZ*                 closestPnt )
1527 {
1528   switch ( elem->GetType() )
1529   {
1530   case SMDSAbs_Volume:
1531     return GetDistance( dynamic_cast<const SMDS_MeshVolume*>( elem ), point, closestPnt );
1532   case SMDSAbs_Face:
1533     return GetDistance( dynamic_cast<const SMDS_MeshFace*>( elem ), point, closestPnt );
1534   case SMDSAbs_Edge:
1535     return GetDistance( dynamic_cast<const SMDS_MeshEdge*>( elem ), point, closestPnt );
1536   case SMDSAbs_Node:
1537     if ( closestPnt ) *closestPnt = SMESH_TNodeXYZ( elem );
1538     return point.Distance( SMESH_TNodeXYZ( elem ));
1539   default:;
1540   }
1541   return -1;
1542 }
1543
1544 //=======================================================================
1545 /*!
1546  * \brief Return minimal distance from a point to a face
1547  *
1548  * Currently we ignore non-planarity and 2nd order of face
1549  */
1550 //=======================================================================
1551
1552 double SMESH_MeshAlgos::GetDistance( const SMDS_MeshFace* face,
1553                                      const gp_Pnt&        point,
1554                                      gp_XYZ*              closestPnt )
1555 {
1556   const double badDistance = -1;
1557   if ( !face ) return badDistance;
1558
1559   // coordinates of nodes (medium nodes, if any, ignored)
1560   typedef SMDS_StdIterator< SMESH_TNodeXYZ, SMDS_ElemIteratorPtr > TXyzIterator;
1561   std::vector<gp_XYZ> xyz( TXyzIterator( face->nodesIterator()), TXyzIterator() );
1562   xyz.resize( face->NbCornerNodes()+1 );
1563
1564   // transformation to get xyz[0] lies on the origin, xyz[1] lies on the Z axis,
1565   // and xyz[2] lies in the XZ plane. This is to pass to 2D space on XZ plane.
1566   gp_Trsf trsf;
1567   gp_Vec OZ ( xyz[0], xyz[1] );
1568   gp_Vec OX ( xyz[0], xyz[2] );
1569   if ( OZ.Magnitude() < std::numeric_limits<double>::min() )
1570   {
1571     if ( xyz.size() < 4 ) return badDistance;
1572     OZ = gp_Vec ( xyz[0], xyz[2] );
1573     OX = gp_Vec ( xyz[0], xyz[3] );
1574   }
1575   gp_Ax3 tgtCS;
1576   try {
1577     tgtCS = gp_Ax3( xyz[0], OZ, OX );
1578   }
1579   catch ( Standard_Failure ) {
1580     return badDistance;
1581   }
1582   trsf.SetTransformation( tgtCS );
1583
1584   // move all the nodes to 2D
1585   std::vector<gp_XY> xy( xyz.size() );
1586   for ( size_t i = 0;i < xyz.size()-1; ++i )
1587   {
1588     gp_XYZ p3d = xyz[i];
1589     trsf.Transforms( p3d );
1590     xy[i].SetCoord( p3d.X(), p3d.Z() );
1591   }
1592   xyz.back() = xyz.front();
1593   xy.back() = xy.front();
1594
1595   // // move the point in 2D
1596   gp_XYZ tmpPnt = point.XYZ();
1597   trsf.Transforms( tmpPnt );
1598   gp_XY point2D( tmpPnt.X(), tmpPnt.Z() );
1599
1600   // loop on edges of the face to analyze point position ralative to the face
1601   std::set< PointPos > pntPosSet;
1602   for ( size_t i = 1; i < xy.size(); ++i )
1603   {
1604     PointPos pos = getPointPosition( point2D, &xy[0], i-1 );
1605     pntPosSet.insert( pos );
1606   }
1607
1608   // compute distance
1609   PointPos pos = *pntPosSet.begin();
1610   switch ( pos._name )
1611   {
1612   case POS_LEFT:
1613   {
1614     // point is most close to an edge
1615     gp_Vec edge( xyz[ pos._index ], xyz[ pos._index+1 ]);
1616     gp_Vec n1p ( xyz[ pos._index ], point  );
1617     double u = ( edge * n1p ) / edge.SquareMagnitude(); // param [0,1] on the edge
1618     // projection of the point on the edge
1619     gp_XYZ proj = xyz[ pos._index ] + u * edge.XYZ();
1620     if ( closestPnt ) *closestPnt = proj;
1621     return point.Distance( proj );
1622   }
1623   case POS_RIGHT:
1624   {
1625     // point is inside the face
1626     double distToFacePlane = Abs( tmpPnt.Y() );
1627     if ( closestPnt )
1628     {
1629       if ( distToFacePlane < std::numeric_limits<double>::min() ) {
1630         *closestPnt = point.XYZ();
1631       }
1632       else {
1633         tmpPnt.SetY( 0 );
1634         trsf.Inverted().Transforms( tmpPnt );
1635         *closestPnt = tmpPnt;
1636       }
1637     }
1638     return distToFacePlane;
1639   }
1640   case POS_VERTEX:
1641   {
1642     // point is most close to a node
1643     gp_Vec distVec( point, xyz[ pos._index ]);
1644     return distVec.Magnitude();
1645   }
1646   default:;
1647   }
1648   return badDistance;
1649 }
1650
1651 //=======================================================================
1652 /*!
1653  * \brief Return minimal distance from a point to an edge
1654  */
1655 //=======================================================================
1656
1657 double SMESH_MeshAlgos::GetDistance( const SMDS_MeshEdge* seg,
1658                                      const gp_Pnt&        point,
1659                                      gp_XYZ*              closestPnt )
1660 {
1661   double dist = Precision::Infinite();
1662   if ( !seg ) return dist;
1663
1664   int i = 0, nbNodes = seg->NbNodes();
1665
1666   std::vector< SMESH_TNodeXYZ > xyz( nbNodes );
1667   SMDS_ElemIteratorPtr nodeIt = seg->interlacedNodesElemIterator();
1668   while ( nodeIt->more() )
1669     xyz[ i++ ].Set( nodeIt->next() );
1670
1671   for ( i = 1; i < nbNodes; ++i )
1672   {
1673     gp_Vec edge( xyz[i-1], xyz[i] );
1674     gp_Vec n1p ( xyz[i-1], point  );
1675     double d, u = ( edge * n1p ) / edge.SquareMagnitude(); // param [0,1] on the edge
1676     if ( u <= 0. ) {
1677       if (( d = n1p.SquareMagnitude() ) < dist ) {
1678         dist = d;
1679         if ( closestPnt ) *closestPnt = xyz[i-1];
1680       }
1681     }
1682     else if ( u >= 1. ) {
1683       if (( d = point.SquareDistance( xyz[i] )) < dist ) {
1684         dist = d;
1685         if ( closestPnt ) *closestPnt = xyz[i];
1686       }
1687     }
1688     else {
1689       gp_XYZ proj = xyz[i-1] + u * edge.XYZ(); // projection of the point on the edge
1690       if (( d = point.SquareDistance( proj )) < dist ) {
1691         dist = d;
1692         if ( closestPnt ) *closestPnt = proj;
1693       }
1694     }
1695   }
1696   return Sqrt( dist );
1697 }
1698
1699 //=======================================================================
1700 /*!
1701  * \brief Return minimal distance from a point to a volume
1702  *
1703  * Currently we ignore non-planarity and 2nd order
1704  */
1705 //=======================================================================
1706
1707 double SMESH_MeshAlgos::GetDistance( const SMDS_MeshVolume* volume,
1708                                      const gp_Pnt&          point,
1709                                      gp_XYZ*                closestPnt )
1710 {
1711   SMDS_VolumeTool vTool( volume );
1712   vTool.SetExternalNormal();
1713   const int iQ = volume->IsQuadratic() ? 2 : 1;
1714
1715   double n[3], bc[3];
1716   double minDist = 1e100, dist;
1717   gp_XYZ closeP = point.XYZ();
1718   bool isOut = false;
1719   for ( int iF = 0; iF < vTool.NbFaces(); ++iF )
1720   {
1721     // skip a facet with normal not "looking at" the point
1722     if ( !vTool.GetFaceNormal( iF, n[0], n[1], n[2] ) ||
1723          !vTool.GetFaceBaryCenter( iF, bc[0], bc[1], bc[2] ))
1724       continue;
1725     gp_XYZ bcp = point.XYZ() - gp_XYZ( bc[0], bc[1], bc[2] );
1726     if ( gp_XYZ( n[0], n[1], n[2] ) * bcp < 1e-6 )
1727       continue;
1728
1729     // find distance to a facet
1730     const SMDS_MeshNode** nodes = vTool.GetFaceNodes( iF );
1731     switch ( vTool.NbFaceNodes( iF ) / iQ ) {
1732     case 3:
1733     {
1734       SMDS_FaceOfNodes tmpFace( nodes[0], nodes[ 1*iQ ], nodes[ 2*iQ ] );
1735       dist = GetDistance( &tmpFace, point, closestPnt );
1736       break;
1737     }
1738     case 4:
1739     {
1740       SMDS_FaceOfNodes tmpFace( nodes[0], nodes[ 1*iQ ], nodes[ 2*iQ ], nodes[ 3*iQ ]);
1741       dist = GetDistance( &tmpFace, point, closestPnt );
1742       break;
1743     }
1744     default:
1745       std::vector<const SMDS_MeshNode *> nvec( nodes, nodes + vTool.NbFaceNodes( iF ));
1746       SMDS_PolygonalFaceOfNodes tmpFace( nvec );
1747       dist = GetDistance( &tmpFace, point, closestPnt );
1748     }
1749     if ( dist < minDist )
1750     {
1751       minDist = dist;
1752       isOut = true;
1753       if ( closestPnt ) closeP = *closestPnt;
1754     }
1755   }
1756   if ( isOut )
1757   {
1758     if ( closestPnt ) *closestPnt = closeP;
1759     return minDist;
1760   }
1761
1762   return 0; // point is inside the volume
1763 }
1764
1765 //================================================================================
1766 /*!
1767  * \brief Returns barycentric coordinates of a point within a triangle.
1768  *        A not returned bc2 = 1. - bc0 - bc1.
1769  *        The point lies within the triangle if ( bc0 >= 0 && bc1 >= 0 && bc0+bc1 <= 1 )
1770  */
1771 //================================================================================
1772
1773 void SMESH_MeshAlgos::GetBarycentricCoords( const gp_XY& p,
1774                                             const gp_XY& t0,
1775                                             const gp_XY& t1,
1776                                             const gp_XY& t2,
1777                                             double &     bc0,
1778                                             double &     bc1)
1779 {
1780   const double // matrix 2x2
1781     T11 = t0.X()-t2.X(), T12 = t1.X()-t2.X(),
1782     T21 = t0.Y()-t2.Y(), T22 = t1.Y()-t2.Y();
1783   const double Tdet = T11*T22 - T12*T21; // matrix determinant
1784   if ( Abs( Tdet ) < std::numeric_limits<double>::min() )
1785   {
1786     bc0 = bc1 = 2.;
1787     return;
1788   }
1789   // matrix inverse
1790   const double t11 = T22, t12 = -T12, t21 = -T21, t22 = T11;
1791   // vector
1792   const double r11 = p.X()-t2.X(), r12 = p.Y()-t2.Y();
1793   // barycentric coordinates: mutiply matrix by vector
1794   bc0 = (t11 * r11 + t12 * r12)/Tdet;
1795   bc1 = (t21 * r11 + t22 * r12)/Tdet;
1796 }
1797
1798 //=======================================================================
1799 //function : FindFaceInSet
1800 //purpose  : Return a face having linked nodes n1 and n2 and which is
1801 //           - not in avoidSet,
1802 //           - in elemSet provided that !elemSet.empty()
1803 //           i1 and i2 optionally returns indices of n1 and n2
1804 //=======================================================================
1805
1806 const SMDS_MeshElement*
1807 SMESH_MeshAlgos::FindFaceInSet(const SMDS_MeshNode*    n1,
1808                                const SMDS_MeshNode*    n2,
1809                                const TIDSortedElemSet& elemSet,
1810                                const TIDSortedElemSet& avoidSet,
1811                                int*                    n1ind,
1812                                int*                    n2ind)
1813
1814 {
1815   int i1 = 0, i2 = 0;
1816   const SMDS_MeshElement* face = 0;
1817
1818   SMDS_ElemIteratorPtr invElemIt = n1->GetInverseElementIterator(SMDSAbs_Face);
1819   while ( invElemIt->more() && !face ) // loop on inverse faces of n1
1820   {
1821     const SMDS_MeshElement* elem = invElemIt->next();
1822     if (avoidSet.count( elem ))
1823       continue;
1824     if ( !elemSet.empty() && !elemSet.count( elem ))
1825       continue;
1826     // index of n1
1827     i1 = elem->GetNodeIndex( n1 );
1828     // find a n2 linked to n1
1829     int nbN = elem->IsQuadratic() ? elem->NbNodes()/2 : elem->NbNodes();
1830     for ( int di = -1; di < 2 && !face; di += 2 )
1831     {
1832       i2 = (i1+di+nbN) % nbN;
1833       if ( elem->GetNode( i2 ) == n2 )
1834         face = elem;
1835     }
1836     if ( !face && elem->IsQuadratic())
1837     {
1838       // analysis for quadratic elements using all nodes
1839       SMDS_ElemIteratorPtr anIter = elem->interlacedNodesElemIterator();
1840       const SMDS_MeshNode* prevN = static_cast<const SMDS_MeshNode*>( anIter->next() );
1841       for ( i1 = -1, i2 = 0; anIter->more() && !face; i1++, i2++ )
1842       {
1843         const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( anIter->next() );
1844         if ( n1 == prevN && n2 == n )
1845         {
1846           face = elem;
1847         }
1848         else if ( n2 == prevN && n1 == n )
1849         {
1850           face = elem; std::swap( i1, i2 );
1851         }
1852         prevN = n;
1853       }
1854     }
1855   }
1856   if ( n1ind ) *n1ind = i1;
1857   if ( n2ind ) *n2ind = i2;
1858   return face;
1859 }
1860
1861 //================================================================================
1862 /*!
1863  * \brief Calculate normal of a mesh face
1864  */
1865 //================================================================================
1866
1867 bool SMESH_MeshAlgos::FaceNormal(const SMDS_MeshElement* F, gp_XYZ& normal, bool normalized)
1868 {
1869   if ( !F || F->GetType() != SMDSAbs_Face )
1870     return false;
1871
1872   normal.SetCoord(0,0,0);
1873   int nbNodes = F->NbCornerNodes();
1874   for ( int i = 0; i < nbNodes-2; ++i )
1875   {
1876     gp_XYZ p[3];
1877     for ( int n = 0; n < 3; ++n )
1878     {
1879       const SMDS_MeshNode* node = F->GetNode( i + n );
1880       p[n].SetCoord( node->X(), node->Y(), node->Z() );
1881     }
1882     normal += ( p[2] - p[1] ) ^ ( p[0] - p[1] );
1883   }
1884   double size2 = normal.SquareModulus();
1885   bool ok = ( size2 > std::numeric_limits<double>::min() * std::numeric_limits<double>::min());
1886   if ( normalized && ok )
1887     normal /= sqrt( size2 );
1888
1889   return ok;
1890 }
1891
1892 //=======================================================================
1893 //function : GetCommonNodes
1894 //purpose  : Return nodes common to two elements
1895 //=======================================================================
1896
1897 std::vector< const SMDS_MeshNode*> SMESH_MeshAlgos::GetCommonNodes(const SMDS_MeshElement* e1,
1898                                                                    const SMDS_MeshElement* e2)
1899 {
1900   std::vector< const SMDS_MeshNode*> common;
1901   for ( int i = 0 ; i < e1->NbNodes(); ++i )
1902     if ( e2->GetNodeIndex( e1->GetNode( i )) >= 0 )
1903       common.push_back( e1->GetNode( i ));
1904   return common;
1905 }
1906 //================================================================================
1907 /*!
1908  * \brief Return true if node1 encounters first in the face and node2, after
1909  */
1910 //================================================================================
1911
1912 bool SMESH_MeshAlgos::IsRightOrder( const SMDS_MeshElement* face,
1913                                     const SMDS_MeshNode*    node0,
1914                                     const SMDS_MeshNode*    node1 )
1915 {
1916   int i0 = face->GetNodeIndex( node0 );
1917   int i1 = face->GetNodeIndex( node1 );
1918   if ( face->IsQuadratic() )
1919   {
1920     if ( face->IsMediumNode( node0 ))
1921     {
1922       i0 -= ( face->NbNodes()/2 - 1 );
1923       i1 *= 2;
1924     }
1925     else
1926     {
1927       i1 -= ( face->NbNodes()/2 - 1 );
1928       i0 *= 2;
1929     }
1930   }
1931   int diff = i1 - i0;
1932   return ( diff == 1 ) || ( diff == -face->NbNodes()+1 );
1933 }
1934
1935 //=======================================================================
1936 /*!
1937  * \brief Return SMESH_NodeSearcher
1938  */
1939 //=======================================================================
1940
1941 SMESH_NodeSearcher* SMESH_MeshAlgos::GetNodeSearcher(SMDS_Mesh& mesh)
1942 {
1943   return new SMESH_NodeSearcherImpl( &mesh );
1944 }
1945
1946 //=======================================================================
1947 /*!
1948  * \brief Return SMESH_NodeSearcher
1949  */
1950 //=======================================================================
1951
1952 SMESH_NodeSearcher* SMESH_MeshAlgos::GetNodeSearcher(SMDS_ElemIteratorPtr elemIt)
1953 {
1954   return new SMESH_NodeSearcherImpl( 0, elemIt );
1955 }
1956
1957 //=======================================================================
1958 /*!
1959  * \brief Return SMESH_ElementSearcher
1960  */
1961 //=======================================================================
1962
1963 SMESH_ElementSearcher* SMESH_MeshAlgos::GetElementSearcher(SMDS_Mesh& mesh,
1964                                                            double     tolerance)
1965 {
1966   return new SMESH_ElementSearcherImpl( mesh, tolerance );
1967 }
1968
1969 //=======================================================================
1970 /*!
1971  * \brief Return SMESH_ElementSearcher acting on a sub-set of elements
1972  */
1973 //=======================================================================
1974
1975 SMESH_ElementSearcher* SMESH_MeshAlgos::GetElementSearcher(SMDS_Mesh&           mesh,
1976                                                            SMDS_ElemIteratorPtr elemIt,
1977                                                            double               tolerance)
1978 {
1979   return new SMESH_ElementSearcherImpl( mesh, tolerance, elemIt );
1980 }