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