Salome HOME
0022098: EDF 2036 SMESH: Create groups from none conected parts of a mesh
[modules/smesh.git] / src / SMESHUtils / SMESH_MeshAlgos.cxx
1 // Copyright (C) 2007-2013  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License.
10 //
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 // Lesser General Public License for more details.
15 //
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22 // File      : SMESH_MeshAlgos.hxx
23 // Created   : Tue Apr 30 18:00:36 2013
24 // Author    : Edward AGAPOV (eap)
25
26 // This file holds some low level algorithms extracted from SMESH_MeshEditor
27 // to make them accessible from Controls package
28
29 #include "SMESH_MeshAlgos.hxx"
30
31 #include "SMDS_LinearEdge.hxx"
32 #include "SMDS_VolumeTool.hxx"
33 #include "SMDS_Mesh.hxx"
34 #include "SMESH_OctreeNode.hxx"
35
36 #include <GC_MakeSegment.hxx>
37 #include <GeomAPI_ExtremaCurveCurve.hxx>
38 #include <Geom_Line.hxx>
39 #include <IntAna_IntConicQuad.hxx>
40 #include <IntAna_Quadric.hxx>
41 #include <gp_Lin.hxx>
42 #include <gp_Pln.hxx>
43
44 #include <limits>
45 #include <numeric>
46
47 using namespace std;
48
49 //=======================================================================
50 /*!
51  * \brief Implementation of search for the node closest to point
52  */
53 //=======================================================================
54
55 struct SMESH_NodeSearcherImpl: public SMESH_NodeSearcher
56 {
57   //---------------------------------------------------------------------
58   /*!
59    * \brief Constructor
60    */
61   SMESH_NodeSearcherImpl( const SMDS_Mesh* theMesh )
62   {
63     myMesh = ( SMDS_Mesh* ) theMesh;
64
65     TIDSortedNodeSet nodes;
66     if ( theMesh ) {
67       SMDS_NodeIteratorPtr nIt = theMesh->nodesIterator(/*idInceasingOrder=*/true);
68       while ( nIt->more() )
69         nodes.insert( nodes.end(), nIt->next() );
70     }
71     myOctreeNode = new SMESH_OctreeNode(nodes) ;
72
73     // get max size of a leaf box
74     SMESH_OctreeNode* tree = myOctreeNode;
75     while ( !tree->isLeaf() )
76     {
77       SMESH_OctreeNodeIteratorPtr cIt = tree->GetChildrenIterator();
78       if ( cIt->more() )
79         tree = cIt->next();
80     }
81     myHalfLeafSize = tree->maxSize() / 2.;
82   }
83
84   //---------------------------------------------------------------------
85   /*!
86    * \brief Move node and update myOctreeNode accordingly
87    */
88   void MoveNode( const SMDS_MeshNode* node, const gp_Pnt& toPnt )
89   {
90     myOctreeNode->UpdateByMoveNode( node, toPnt );
91     myMesh->MoveNode( node, toPnt.X(), toPnt.Y(), toPnt.Z() );
92   }
93
94   //---------------------------------------------------------------------
95   /*!
96    * \brief Do it's job
97    */
98   const SMDS_MeshNode* FindClosestTo( const gp_Pnt& thePnt )
99   {
100     map<double, const SMDS_MeshNode*> dist2Nodes;
101     myOctreeNode->NodesAround( thePnt.Coord(), dist2Nodes, myHalfLeafSize );
102     if ( !dist2Nodes.empty() )
103       return dist2Nodes.begin()->second;
104     list<const SMDS_MeshNode*> nodes;
105     //myOctreeNode->NodesAround( &tgtNode, &nodes, myHalfLeafSize );
106
107     double minSqDist = DBL_MAX;
108     if ( nodes.empty() )  // get all nodes of OctreeNode's closest to thePnt
109     {
110       // sort leafs by their distance from thePnt
111       typedef map< double, SMESH_OctreeNode* > TDistTreeMap;
112       TDistTreeMap treeMap;
113       list< SMESH_OctreeNode* > treeList;
114       list< SMESH_OctreeNode* >::iterator trIt;
115       treeList.push_back( myOctreeNode );
116
117       gp_XYZ pointNode( thePnt.X(), thePnt.Y(), thePnt.Z() );
118       bool pointInside = myOctreeNode->isInside( pointNode, myHalfLeafSize );
119       for ( trIt = treeList.begin(); trIt != treeList.end(); ++trIt)
120       {
121         SMESH_OctreeNode* tree = *trIt;
122         if ( !tree->isLeaf() ) // put children to the queue
123         {
124           if ( pointInside && !tree->isInside( pointNode, myHalfLeafSize )) continue;
125           SMESH_OctreeNodeIteratorPtr cIt = tree->GetChildrenIterator();
126           while ( cIt->more() )
127             treeList.push_back( cIt->next() );
128         }
129         else if ( tree->NbNodes() ) // put a tree to the treeMap
130         {
131           const Bnd_B3d& box = *tree->getBox();
132           double sqDist = thePnt.SquareDistance( 0.5 * ( box.CornerMin() + box.CornerMax() ));
133           pair<TDistTreeMap::iterator,bool> it_in = treeMap.insert( make_pair( sqDist, tree ));
134           if ( !it_in.second ) // not unique distance to box center
135             treeMap.insert( it_in.first, make_pair( sqDist + 1e-13*treeMap.size(), tree ));
136         }
137       }
138       // find distance after which there is no sense to check tree's
139       double sqLimit = DBL_MAX;
140       TDistTreeMap::iterator sqDist_tree = treeMap.begin();
141       if ( treeMap.size() > 5 ) {
142         SMESH_OctreeNode* closestTree = sqDist_tree->second;
143         const Bnd_B3d& box = *closestTree->getBox();
144         double limit = sqrt( sqDist_tree->first ) + sqrt ( box.SquareExtent() );
145         sqLimit = limit * limit;
146       }
147       // get all nodes from trees
148       for ( ; sqDist_tree != treeMap.end(); ++sqDist_tree) {
149         if ( sqDist_tree->first > sqLimit )
150           break;
151         SMESH_OctreeNode* tree = sqDist_tree->second;
152         tree->NodesAround( tree->GetNodeIterator()->next(), &nodes );
153       }
154     }
155     // find closest among nodes
156     minSqDist = DBL_MAX;
157     const SMDS_MeshNode* closestNode = 0;
158     list<const SMDS_MeshNode*>::iterator nIt = nodes.begin();
159     for ( ; nIt != nodes.end(); ++nIt ) {
160       double sqDist = thePnt.SquareDistance( SMESH_TNodeXYZ( *nIt ) );
161       if ( minSqDist > sqDist ) {
162         closestNode = *nIt;
163         minSqDist = sqDist;
164       }
165     }
166     return closestNode;
167   }
168
169   //---------------------------------------------------------------------
170   /*!
171    * \brief Destructor
172    */
173   ~SMESH_NodeSearcherImpl() { delete myOctreeNode; }
174
175   //---------------------------------------------------------------------
176   /*!
177    * \brief Return the node tree
178    */
179   const SMESH_OctreeNode* getTree() const { return myOctreeNode; }
180
181 private:
182   SMESH_OctreeNode* myOctreeNode;
183   SMDS_Mesh*        myMesh;
184   double            myHalfLeafSize; // max size of a leaf box
185 };
186
187 // ========================================================================
188 namespace // Utils used in SMESH_ElementSearcherImpl::FindElementsByPoint()
189 {
190   const int MaxNbElemsInLeaf = 10; // maximal number of elements in a leaf of tree
191   const int MaxLevel         = 7;  // maximal tree height -> nb terminal boxes: 8^7 = 2097152
192   const double NodeRadius = 1e-9;  // to enlarge bnd box of element
193
194   //=======================================================================
195   /*!
196    * \brief Octal tree of bounding boxes of elements
197    */
198   //=======================================================================
199
200   class ElementBndBoxTree : public SMESH_Octree
201   {
202   public:
203
204     ElementBndBoxTree(const SMDS_Mesh&     mesh,
205                       SMDSAbs_ElementType  elemType,
206                       SMDS_ElemIteratorPtr theElemIt = SMDS_ElemIteratorPtr(),
207                       double               tolerance = NodeRadius );
208     void getElementsNearPoint( const gp_Pnt& point, TIDSortedElemSet& foundElems );
209     void getElementsNearLine ( const gp_Ax1& line, TIDSortedElemSet& foundElems);
210     void getElementsInSphere ( const gp_XYZ& center,
211                                const double  radius, TIDSortedElemSet& foundElems);
212     size_t getSize() { return std::max( _size, _elements.size() ); }
213     ~ElementBndBoxTree();
214
215   protected:
216     ElementBndBoxTree():_size(0) {}
217     SMESH_Octree* newChild() const { return new ElementBndBoxTree; }
218     void          buildChildrenData();
219     Bnd_B3d*      buildRootBox();
220   private:
221     //!< Bounding box of element
222     struct ElementBox : public Bnd_B3d
223     {
224       const SMDS_MeshElement* _element;
225       int                     _refCount; // an ElementBox can be included in several tree branches
226       ElementBox(const SMDS_MeshElement* elem, double tolerance);
227     };
228     vector< ElementBox* > _elements;
229     size_t                _size;
230   };
231
232   //================================================================================
233   /*!
234    * \brief ElementBndBoxTree creation
235    */
236   //================================================================================
237
238   ElementBndBoxTree::ElementBndBoxTree(const SMDS_Mesh& mesh, SMDSAbs_ElementType elemType, SMDS_ElemIteratorPtr theElemIt, double tolerance)
239     :SMESH_Octree( new SMESH_TreeLimit( MaxLevel, /*minSize=*/0. ))
240   {
241     int nbElems = mesh.GetMeshInfo().NbElements( elemType );
242     _elements.reserve( nbElems );
243
244     SMDS_ElemIteratorPtr elemIt = theElemIt ? theElemIt : mesh.elementsIterator( elemType );
245     while ( elemIt->more() )
246       _elements.push_back( new ElementBox( elemIt->next(),tolerance  ));
247
248     compute();
249   }
250
251   //================================================================================
252   /*!
253    * \brief Destructor
254    */
255   //================================================================================
256
257   ElementBndBoxTree::~ElementBndBoxTree()
258   {
259     for ( int i = 0; i < _elements.size(); ++i )
260       if ( --_elements[i]->_refCount <= 0 )
261         delete _elements[i];
262   }
263
264   //================================================================================
265   /*!
266    * \brief Return the maximal box
267    */
268   //================================================================================
269
270   Bnd_B3d* ElementBndBoxTree::buildRootBox()
271   {
272     Bnd_B3d* box = new Bnd_B3d;
273     for ( int i = 0; i < _elements.size(); ++i )
274       box->Add( *_elements[i] );
275     return box;
276   }
277
278   //================================================================================
279   /*!
280    * \brief Redistrubute element boxes among children
281    */
282   //================================================================================
283
284   void ElementBndBoxTree::buildChildrenData()
285   {
286     for ( int i = 0; i < _elements.size(); ++i )
287     {
288       for (int j = 0; j < 8; j++)
289       {
290         if ( !_elements[i]->IsOut( *myChildren[j]->getBox() ))
291         {
292           _elements[i]->_refCount++;
293           ((ElementBndBoxTree*)myChildren[j])->_elements.push_back( _elements[i]);
294         }
295       }
296       _elements[i]->_refCount--;
297     }
298     _size = _elements.size();
299     SMESHUtils::FreeVector( _elements ); // = _elements.clear() + free memory
300
301     for (int j = 0; j < 8; j++)
302     {
303       ElementBndBoxTree* child = static_cast<ElementBndBoxTree*>( myChildren[j]);
304       if ( child->_elements.size() <= MaxNbElemsInLeaf )
305         child->myIsLeaf = true;
306
307       if ( child->_elements.capacity() - child->_elements.size() > 1000 )
308         SMESHUtils::CompactVector( child->_elements );
309     }
310   }
311
312   //================================================================================
313   /*!
314    * \brief Return elements which can include the point
315    */
316   //================================================================================
317
318   void ElementBndBoxTree::getElementsNearPoint( const gp_Pnt&     point,
319                                                 TIDSortedElemSet& foundElems)
320   {
321     if ( getBox()->IsOut( point.XYZ() ))
322       return;
323
324     if ( isLeaf() )
325     {
326       for ( int i = 0; i < _elements.size(); ++i )
327         if ( !_elements[i]->IsOut( point.XYZ() ))
328           foundElems.insert( _elements[i]->_element );
329     }
330     else
331     {
332       for (int i = 0; i < 8; i++)
333         ((ElementBndBoxTree*) myChildren[i])->getElementsNearPoint( point, foundElems );
334     }
335   }
336
337   //================================================================================
338   /*!
339    * \brief Return elements which can be intersected by the line
340    */
341   //================================================================================
342
343   void ElementBndBoxTree::getElementsNearLine( const gp_Ax1&     line,
344                                                TIDSortedElemSet& foundElems)
345   {
346     if ( getBox()->IsOut( line ))
347       return;
348
349     if ( isLeaf() )
350     {
351       for ( int i = 0; i < _elements.size(); ++i )
352         if ( !_elements[i]->IsOut( line ))
353           foundElems.insert( _elements[i]->_element );
354     }
355     else
356     {
357       for (int i = 0; i < 8; i++)
358         ((ElementBndBoxTree*) myChildren[i])->getElementsNearLine( line, foundElems );
359     }
360   }
361
362   //================================================================================
363   /*!
364    * \brief Return elements from leaves intersecting the sphere
365    */
366   //================================================================================
367
368   void ElementBndBoxTree::getElementsInSphere ( const gp_XYZ&     center,
369                                                 const double      radius,
370                                                 TIDSortedElemSet& foundElems)
371   {
372     if ( getBox()->IsOut( center, radius ))
373       return;
374
375     if ( isLeaf() )
376     {
377       for ( int i = 0; i < _elements.size(); ++i )
378         if ( !_elements[i]->IsOut( center, radius ))
379           foundElems.insert( _elements[i]->_element );
380     }
381     else
382     {
383       for (int i = 0; i < 8; i++)
384         ((ElementBndBoxTree*) myChildren[i])->getElementsInSphere( center, radius, foundElems );
385     }
386   }
387
388   //================================================================================
389   /*!
390    * \brief Construct the element box
391    */
392   //================================================================================
393
394   ElementBndBoxTree::ElementBox::ElementBox(const SMDS_MeshElement* elem, double tolerance)
395   {
396     _element  = elem;
397     _refCount = 1;
398     SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
399     while ( nIt->more() )
400       Add( SMESH_TNodeXYZ( nIt->next() ));
401     Enlarge( tolerance );
402   }
403
404 } // namespace
405
406 //=======================================================================
407 /*!
408  * \brief Implementation of search for the elements by point and
409  *        of classification of point in 2D mesh
410  */
411 //=======================================================================
412
413 struct SMESH_ElementSearcherImpl: public SMESH_ElementSearcher
414 {
415   SMDS_Mesh*                   _mesh;
416   SMDS_ElemIteratorPtr         _meshPartIt;
417   ElementBndBoxTree*           _ebbTree;
418   SMESH_NodeSearcherImpl*      _nodeSearcher;
419   SMDSAbs_ElementType          _elementType;
420   double                       _tolerance;
421   bool                         _outerFacesFound;
422   set<const SMDS_MeshElement*> _outerFaces; // empty means "no internal faces at all"
423
424   SMESH_ElementSearcherImpl( SMDS_Mesh& mesh, SMDS_ElemIteratorPtr elemIt=SMDS_ElemIteratorPtr())
425     : _mesh(&mesh),_meshPartIt(elemIt),_ebbTree(0),_nodeSearcher(0),_tolerance(-1),_outerFacesFound(false) {}
426   ~SMESH_ElementSearcherImpl()
427   {
428     if ( _ebbTree )      delete _ebbTree;      _ebbTree      = 0;
429     if ( _nodeSearcher ) delete _nodeSearcher; _nodeSearcher = 0;
430   }
431   virtual int FindElementsByPoint(const gp_Pnt&                      point,
432                                   SMDSAbs_ElementType                type,
433                                   vector< const SMDS_MeshElement* >& foundElements);
434   virtual TopAbs_State GetPointState(const gp_Pnt& point);
435   virtual const SMDS_MeshElement* FindClosestTo( const gp_Pnt&       point,
436                                                  SMDSAbs_ElementType type );
437
438   void GetElementsNearLine( const gp_Ax1&                      line,
439                             SMDSAbs_ElementType                type,
440                             vector< const SMDS_MeshElement* >& foundElems);
441   double getTolerance();
442   bool getIntersParamOnLine(const gp_Lin& line, const SMDS_MeshElement* face,
443                             const double tolerance, double & param);
444   void findOuterBoundary(const SMDS_MeshElement* anyOuterFace);
445   bool isOuterBoundary(const SMDS_MeshElement* face) const
446   {
447     return _outerFaces.empty() || _outerFaces.count(face);
448   }
449   struct TInters //!< data of intersection of the line and the mesh face (used in GetPointState())
450   {
451     const SMDS_MeshElement* _face;
452     gp_Vec                  _faceNorm;
453     bool                    _coincides; //!< the line lays in face plane
454     TInters(const SMDS_MeshElement* face, const gp_Vec& faceNorm, bool coinc=false)
455       : _face(face), _faceNorm( faceNorm ), _coincides( coinc ) {}
456   };
457   struct TFaceLink //!< link and faces sharing it (used in findOuterBoundary())
458   {
459     SMESH_TLink      _link;
460     TIDSortedElemSet _faces;
461     TFaceLink( const SMDS_MeshNode* n1, const SMDS_MeshNode* n2, const SMDS_MeshElement* face)
462       : _link( n1, n2 ), _faces( &face, &face + 1) {}
463   };
464 };
465
466 ostream& operator<< (ostream& out, const SMESH_ElementSearcherImpl::TInters& i)
467 {
468   return out << "TInters(face=" << ( i._face ? i._face->GetID() : 0)
469              << ", _coincides="<<i._coincides << ")";
470 }
471
472 //=======================================================================
473 /*!
474  * \brief define tolerance for search
475  */
476 //=======================================================================
477
478 double SMESH_ElementSearcherImpl::getTolerance()
479 {
480   if ( _tolerance < 0 )
481   {
482     const SMDS_MeshInfo& meshInfo = _mesh->GetMeshInfo();
483
484     _tolerance = 0;
485     if ( _nodeSearcher && meshInfo.NbNodes() > 1 )
486     {
487       double boxSize = _nodeSearcher->getTree()->maxSize();
488       _tolerance = 1e-8 * boxSize/* / meshInfo.NbNodes()*/;
489     }
490     else if ( _ebbTree && meshInfo.NbElements() > 0 )
491     {
492       double boxSize = _ebbTree->maxSize();
493       _tolerance = 1e-8 * boxSize/* / meshInfo.NbElements()*/;
494     }
495     if ( _tolerance == 0 )
496     {
497       // define tolerance by size of a most complex element
498       int complexType = SMDSAbs_Volume;
499       while ( complexType > SMDSAbs_All &&
500               meshInfo.NbElements( SMDSAbs_ElementType( complexType )) < 1 )
501         --complexType;
502       if ( complexType == SMDSAbs_All ) return 0; // empty mesh
503       double elemSize;
504       if ( complexType == int( SMDSAbs_Node ))
505       {
506         SMDS_NodeIteratorPtr nodeIt = _mesh->nodesIterator();
507         elemSize = 1;
508         if ( meshInfo.NbNodes() > 2 )
509           elemSize = SMESH_TNodeXYZ( nodeIt->next() ).Distance( nodeIt->next() );
510       }
511       else
512       {
513         SMDS_ElemIteratorPtr elemIt =
514             _mesh->elementsIterator( SMDSAbs_ElementType( complexType ));
515         const SMDS_MeshElement* elem = elemIt->next();
516         SMDS_ElemIteratorPtr nodeIt = elem->nodesIterator();
517         SMESH_TNodeXYZ n1( nodeIt->next() );
518         elemSize = 0;
519         while ( nodeIt->more() )
520         {
521           double dist = n1.Distance( static_cast<const SMDS_MeshNode*>( nodeIt->next() ));
522           elemSize = max( dist, elemSize );
523         }
524       }
525       _tolerance = 1e-4 * elemSize;
526     }
527   }
528   return _tolerance;
529 }
530
531 //================================================================================
532 /*!
533  * \brief Find intersection of the line and an edge of face and return parameter on line
534  */
535 //================================================================================
536
537 bool SMESH_ElementSearcherImpl::getIntersParamOnLine(const gp_Lin&           line,
538                                                      const SMDS_MeshElement* face,
539                                                      const double            tol,
540                                                      double &                param)
541 {
542   int nbInts = 0;
543   param = 0;
544
545   GeomAPI_ExtremaCurveCurve anExtCC;
546   Handle(Geom_Curve) lineCurve = new Geom_Line( line );
547
548   int nbNodes = face->IsQuadratic() ? face->NbNodes()/2 : face->NbNodes();
549   for ( int i = 0; i < nbNodes && nbInts < 2; ++i )
550   {
551     GC_MakeSegment edge( SMESH_TNodeXYZ( face->GetNode( i )),
552                          SMESH_TNodeXYZ( face->GetNode( (i+1)%nbNodes) ));
553     anExtCC.Init( lineCurve, edge);
554     if ( anExtCC.NbExtrema() > 0 && anExtCC.LowerDistance() <= tol)
555     {
556       Quantity_Parameter pl, pe;
557       anExtCC.LowerDistanceParameters( pl, pe );
558       param += pl;
559       if ( ++nbInts == 2 )
560         break;
561     }
562   }
563   if ( nbInts > 0 ) param /= nbInts;
564   return nbInts > 0;
565 }
566 //================================================================================
567 /*!
568  * \brief Find all faces belonging to the outer boundary of mesh
569  */
570 //================================================================================
571
572 void SMESH_ElementSearcherImpl::findOuterBoundary(const SMDS_MeshElement* outerFace)
573 {
574   if ( _outerFacesFound ) return;
575
576   // Collect all outer faces by passing from one outer face to another via their links
577   // and BTW find out if there are internal faces at all.
578
579   // checked links and links where outer boundary meets internal one
580   set< SMESH_TLink > visitedLinks, seamLinks;
581
582   // links to treat with already visited faces sharing them
583   list < TFaceLink > startLinks;
584
585   // load startLinks with the first outerFace
586   startLinks.push_back( TFaceLink( outerFace->GetNode(0), outerFace->GetNode(1), outerFace));
587   _outerFaces.insert( outerFace );
588
589   TIDSortedElemSet emptySet;
590   while ( !startLinks.empty() )
591   {
592     const SMESH_TLink& link  = startLinks.front()._link;
593     TIDSortedElemSet&  faces = startLinks.front()._faces;
594
595     outerFace = *faces.begin();
596     // find other faces sharing the link
597     const SMDS_MeshElement* f;
598     while (( f = SMESH_MeshAlgos::FindFaceInSet(link.node1(), link.node2(), emptySet, faces )))
599       faces.insert( f );
600
601     // select another outer face among the found
602     const SMDS_MeshElement* outerFace2 = 0;
603     if ( faces.size() == 2 )
604     {
605       outerFace2 = (outerFace == *faces.begin() ? *faces.rbegin() : *faces.begin());
606     }
607     else if ( faces.size() > 2 )
608     {
609       seamLinks.insert( link );
610
611       // link direction within the outerFace
612       gp_Vec n1n2( SMESH_TNodeXYZ( link.node1()),
613                    SMESH_TNodeXYZ( link.node2()));
614       int i1 = outerFace->GetNodeIndex( link.node1() );
615       int i2 = outerFace->GetNodeIndex( link.node2() );
616       bool rev = ( abs(i2-i1) == 1 ? i1 > i2 : i2 > i1 );
617       if ( rev ) n1n2.Reverse();
618       // outerFace normal
619       gp_XYZ ofNorm, fNorm;
620       if ( SMESH_MeshAlgos::FaceNormal( outerFace, ofNorm, /*normalized=*/false ))
621       {
622         // direction from the link inside outerFace
623         gp_Vec dirInOF = gp_Vec( ofNorm ) ^ n1n2;
624         // sort all other faces by angle with the dirInOF
625         map< double, const SMDS_MeshElement* > angle2Face;
626         set< const SMDS_MeshElement*, TIDCompare >::const_iterator face = faces.begin();
627         for ( ; face != faces.end(); ++face )
628         {
629           if ( !SMESH_MeshAlgos::FaceNormal( *face, fNorm, /*normalized=*/false ))
630             continue;
631           gp_Vec dirInF = gp_Vec( fNorm ) ^ n1n2;
632           double angle = dirInOF.AngleWithRef( dirInF, n1n2 );
633           if ( angle < 0 ) angle += 2. * M_PI;
634           angle2Face.insert( make_pair( angle, *face ));
635         }
636         if ( !angle2Face.empty() )
637           outerFace2 = angle2Face.begin()->second;
638       }
639     }
640     // store the found outer face and add its links to continue seaching from
641     if ( outerFace2 )
642     {
643       _outerFaces.insert( outerFace );
644       int nbNodes = outerFace2->NbNodes()/( outerFace2->IsQuadratic() ? 2 : 1 );
645       for ( int i = 0; i < nbNodes; ++i )
646       {
647         SMESH_TLink link2( outerFace2->GetNode(i), outerFace2->GetNode((i+1)%nbNodes));
648         if ( visitedLinks.insert( link2 ).second )
649           startLinks.push_back( TFaceLink( link2.node1(), link2.node2(), outerFace2 ));
650       }
651     }
652     startLinks.pop_front();
653   }
654   _outerFacesFound = true;
655
656   if ( !seamLinks.empty() )
657   {
658     // There are internal boundaries touching the outher one,
659     // find all faces of internal boundaries in order to find
660     // faces of boundaries of holes, if any.
661
662   }
663   else
664   {
665     _outerFaces.clear();
666   }
667 }
668
669 //=======================================================================
670 /*!
671  * \brief Find elements of given type where the given point is IN or ON.
672  *        Returns nb of found elements and elements them-selves.
673  *
674  * 'ALL' type means elements of any type excluding nodes, balls and 0D elements
675  */
676 //=======================================================================
677
678 int SMESH_ElementSearcherImpl::
679 FindElementsByPoint(const gp_Pnt&                      point,
680                     SMDSAbs_ElementType                type,
681                     vector< const SMDS_MeshElement* >& foundElements)
682 {
683   foundElements.clear();
684
685   double tolerance = getTolerance();
686
687   // =================================================================================
688   if ( type == SMDSAbs_Node || type == SMDSAbs_0DElement || type == SMDSAbs_Ball)
689   {
690     if ( !_nodeSearcher )
691       _nodeSearcher = new SMESH_NodeSearcherImpl( _mesh );
692
693     const SMDS_MeshNode* closeNode = _nodeSearcher->FindClosestTo( point );
694     if ( !closeNode ) return foundElements.size();
695
696     if ( point.Distance( SMESH_TNodeXYZ( closeNode )) > tolerance )
697       return foundElements.size(); // to far from any node
698
699     if ( type == SMDSAbs_Node )
700     {
701       foundElements.push_back( closeNode );
702     }
703     else
704     {
705       SMDS_ElemIteratorPtr elemIt = closeNode->GetInverseElementIterator( type );
706       while ( elemIt->more() )
707         foundElements.push_back( elemIt->next() );
708     }
709   }
710   // =================================================================================
711   else // elements more complex than 0D
712   {
713     if ( !_ebbTree || _elementType != type )
714     {
715       if ( _ebbTree ) delete _ebbTree;
716       _ebbTree = new ElementBndBoxTree( *_mesh, _elementType = type, _meshPartIt, tolerance );
717     }
718     TIDSortedElemSet suspectElems;
719     _ebbTree->getElementsNearPoint( point, suspectElems );
720     TIDSortedElemSet::iterator elem = suspectElems.begin();
721     for ( ; elem != suspectElems.end(); ++elem )
722       if ( !SMESH_MeshAlgos::IsOut( *elem, point, tolerance ))
723         foundElements.push_back( *elem );
724   }
725   return foundElements.size();
726 }
727
728 //=======================================================================
729 /*!
730  * \brief Find an element of given type most close to the given point
731  *
732  * WARNING: Only face search is implemeneted so far
733  */
734 //=======================================================================
735
736 const SMDS_MeshElement*
737 SMESH_ElementSearcherImpl::FindClosestTo( const gp_Pnt&       point,
738                                           SMDSAbs_ElementType type )
739 {
740   const SMDS_MeshElement* closestElem = 0;
741
742   if ( type == SMDSAbs_Face )
743   {
744     if ( !_ebbTree || _elementType != type )
745     {
746       if ( _ebbTree ) delete _ebbTree;
747       _ebbTree = new ElementBndBoxTree( *_mesh, _elementType = type, _meshPartIt );
748     }
749     TIDSortedElemSet suspectElems;
750     _ebbTree->getElementsNearPoint( point, suspectElems );
751
752     if ( suspectElems.empty() && _ebbTree->maxSize() > 0 )
753     {
754       gp_Pnt boxCenter = 0.5 * ( _ebbTree->getBox()->CornerMin() +
755                                  _ebbTree->getBox()->CornerMax() );
756       double radius;
757       if ( _ebbTree->getBox()->IsOut( point.XYZ() ))
758         radius = point.Distance( boxCenter ) - 0.5 * _ebbTree->maxSize();
759       else
760         radius = _ebbTree->maxSize() / pow( 2., _ebbTree->getHeight()) / 2;
761       while ( suspectElems.empty() )
762       {
763         _ebbTree->getElementsInSphere( point.XYZ(), radius, suspectElems );
764         radius *= 1.1;
765       }
766     }
767     double minDist = std::numeric_limits<double>::max();
768     multimap< double, const SMDS_MeshElement* > dist2face;
769     TIDSortedElemSet::iterator elem = suspectElems.begin();
770     for ( ; elem != suspectElems.end(); ++elem )
771     {
772       double dist = SMESH_MeshAlgos::GetDistance( dynamic_cast<const SMDS_MeshFace*>(*elem),
773                                                    point );
774       if ( dist < minDist + 1e-10)
775       {
776         minDist = dist;
777         dist2face.insert( dist2face.begin(), make_pair( dist, *elem ));
778       }
779     }
780     if ( !dist2face.empty() )
781     {
782       multimap< double, const SMDS_MeshElement* >::iterator d2f = dist2face.begin();
783       closestElem = d2f->second;
784       // if there are several elements at the same distance, select one
785       // with GC closest to the point
786       typedef SMDS_StdIterator< SMESH_TNodeXYZ, SMDS_ElemIteratorPtr > TXyzIterator;
787       double minDistToGC = 0;
788       for ( ++d2f; d2f != dist2face.end() && fabs( d2f->first - minDist ) < 1e-10; ++d2f )
789       {
790         if ( minDistToGC == 0 )
791         {
792           gp_XYZ gc(0,0,0);
793           gc = accumulate( TXyzIterator(closestElem->nodesIterator()),
794                            TXyzIterator(), gc ) / closestElem->NbNodes();
795           minDistToGC = point.SquareDistance( gc );
796         }
797         gp_XYZ gc(0,0,0);
798         gc = accumulate( TXyzIterator( d2f->second->nodesIterator()),
799                          TXyzIterator(), gc ) / d2f->second->NbNodes();
800         double d = point.SquareDistance( gc );
801         if ( d < minDistToGC )
802         {
803           minDistToGC = d;
804           closestElem = d2f->second;
805         }
806       }
807       // cout << "FindClosestTo( " <<point.X()<<", "<<point.Y()<<", "<<point.Z()<<" ) FACE "
808       //      <<closestElem->GetID() << " DIST " << minDist << endl;
809     }
810   }
811   else
812   {
813     // NOT IMPLEMENTED SO FAR
814   }
815   return closestElem;
816 }
817
818
819 //================================================================================
820 /*!
821  * \brief Classify the given point in the closed 2D mesh
822  */
823 //================================================================================
824
825 TopAbs_State SMESH_ElementSearcherImpl::GetPointState(const gp_Pnt& point)
826 {
827   double tolerance = getTolerance();
828   if ( !_ebbTree || _elementType != SMDSAbs_Face )
829   {
830     if ( _ebbTree ) delete _ebbTree;
831     _ebbTree = new ElementBndBoxTree( *_mesh, _elementType = SMDSAbs_Face, _meshPartIt );
832   }
833   // Algo: analyse transition of a line starting at the point through mesh boundary;
834   // try three lines parallel to axis of the coordinate system and perform rough
835   // analysis. If solution is not clear perform thorough analysis.
836
837   const int nbAxes = 3;
838   gp_Dir axisDir[ nbAxes ] = { gp::DX(), gp::DY(), gp::DZ() };
839   map< double, TInters >   paramOnLine2TInters[ nbAxes ];
840   list< TInters > tangentInters[ nbAxes ]; // of faces whose plane includes the line
841   multimap< int, int > nbInt2Axis; // to find the simplest case
842   for ( int axis = 0; axis < nbAxes; ++axis )
843   {
844     gp_Ax1 lineAxis( point, axisDir[axis]);
845     gp_Lin line    ( lineAxis );
846
847     TIDSortedElemSet suspectFaces; // faces possibly intersecting the line
848     _ebbTree->getElementsNearLine( lineAxis, suspectFaces );
849
850     // Intersect faces with the line
851
852     map< double, TInters > & u2inters = paramOnLine2TInters[ axis ];
853     TIDSortedElemSet::iterator face = suspectFaces.begin();
854     for ( ; face != suspectFaces.end(); ++face )
855     {
856       // get face plane
857       gp_XYZ fNorm;
858       if ( !SMESH_MeshAlgos::FaceNormal( *face, fNorm, /*normalized=*/false)) continue;
859       gp_Pln facePlane( SMESH_TNodeXYZ( (*face)->GetNode(0)), fNorm );
860
861       // perform intersection
862       IntAna_IntConicQuad intersection( line, IntAna_Quadric( facePlane ));
863       if ( !intersection.IsDone() )
864         continue;
865       if ( intersection.IsInQuadric() )
866       {
867         tangentInters[ axis ].push_back( TInters( *face, fNorm, true ));
868       }
869       else if ( ! intersection.IsParallel() && intersection.NbPoints() > 0 )
870       {
871         gp_Pnt intersectionPoint = intersection.Point(1);
872         if ( !SMESH_MeshAlgos::IsOut( *face, intersectionPoint, tolerance ))
873           u2inters.insert(make_pair( intersection.ParamOnConic(1), TInters( *face, fNorm )));
874       }
875     }
876     // Analyse intersections roughly
877
878     int nbInter = u2inters.size();
879     if ( nbInter == 0 )
880       return TopAbs_OUT;
881
882     double f = u2inters.begin()->first, l = u2inters.rbegin()->first;
883     if ( nbInter == 1 ) // not closed mesh
884       return fabs( f ) < tolerance ? TopAbs_ON : TopAbs_UNKNOWN;
885
886     if ( fabs( f ) < tolerance || fabs( l ) < tolerance )
887       return TopAbs_ON;
888
889     if ( (f<0) == (l<0) )
890       return TopAbs_OUT;
891
892     int nbIntBeforePoint = std::distance( u2inters.begin(), u2inters.lower_bound(0));
893     int nbIntAfterPoint  = nbInter - nbIntBeforePoint;
894     if ( nbIntBeforePoint == 1 || nbIntAfterPoint == 1 )
895       return TopAbs_IN;
896
897     nbInt2Axis.insert( make_pair( min( nbIntBeforePoint, nbIntAfterPoint ), axis ));
898
899     if ( _outerFacesFound ) break; // pass to thorough analysis
900
901   } // three attempts - loop on CS axes
902
903   // Analyse intersections thoroughly.
904   // We make two loops maximum, on the first one we only exclude touching intersections,
905   // on the second, if situation is still unclear, we gather and use information on
906   // position of faces (internal or outer). If faces position is already gathered,
907   // we make the second loop right away.
908
909   for ( int hasPositionInfo = _outerFacesFound; hasPositionInfo < 2; ++hasPositionInfo )
910   {
911     multimap< int, int >::const_iterator nb_axis = nbInt2Axis.begin();
912     for ( ; nb_axis != nbInt2Axis.end(); ++nb_axis )
913     {
914       int axis = nb_axis->second;
915       map< double, TInters > & u2inters = paramOnLine2TInters[ axis ];
916
917       gp_Ax1 lineAxis( point, axisDir[axis]);
918       gp_Lin line    ( lineAxis );
919
920       // add tangent intersections to u2inters
921       double param;
922       list< TInters >::const_iterator tgtInt = tangentInters[ axis ].begin();
923       for ( ; tgtInt != tangentInters[ axis ].end(); ++tgtInt )
924         if ( getIntersParamOnLine( line, tgtInt->_face, tolerance, param ))
925           u2inters.insert(make_pair( param, *tgtInt ));
926       tangentInters[ axis ].clear();
927
928       // Count intersections before and after the point excluding touching ones.
929       // If hasPositionInfo we count intersections of outer boundary only
930
931       int nbIntBeforePoint = 0, nbIntAfterPoint = 0;
932       double f = numeric_limits<double>::max(), l = -numeric_limits<double>::max();
933       map< double, TInters >::iterator u_int1 = u2inters.begin(), u_int2 = u_int1;
934       bool ok = ! u_int1->second._coincides;
935       while ( ok && u_int1 != u2inters.end() )
936       {
937         double u = u_int1->first;
938         bool touchingInt = false;
939         if ( ++u_int2 != u2inters.end() )
940         {
941           // skip intersections at the same point (if the line passes through edge or node)
942           int nbSamePnt = 0;
943           while ( u_int2 != u2inters.end() && fabs( u_int2->first - u ) < tolerance )
944           {
945             ++nbSamePnt;
946             ++u_int2;
947           }
948
949           // skip tangent intersections
950           int nbTgt = 0;
951           const SMDS_MeshElement* prevFace = u_int1->second._face;
952           while ( ok && u_int2->second._coincides )
953           {
954             if ( SMESH_MeshAlgos::GetCommonNodes(prevFace , u_int2->second._face).empty() )
955               ok = false;
956             else
957             {
958               nbTgt++;
959               u_int2++;
960               ok = ( u_int2 != u2inters.end() );
961             }
962           }
963           if ( !ok ) break;
964
965           // skip intersections at the same point after tangent intersections
966           if ( nbTgt > 0 )
967           {
968             double u2 = u_int2->first;
969             ++u_int2;
970             while ( u_int2 != u2inters.end() && fabs( u_int2->first - u2 ) < tolerance )
971             {
972               ++nbSamePnt;
973               ++u_int2;
974             }
975           }
976           // decide if we skipped a touching intersection
977           if ( nbSamePnt + nbTgt > 0 )
978           {
979             double minDot = numeric_limits<double>::max(), maxDot = -numeric_limits<double>::max();
980             map< double, TInters >::iterator u_int = u_int1;
981             for ( ; u_int != u_int2; ++u_int )
982             {
983               if ( u_int->second._coincides ) continue;
984               double dot = u_int->second._faceNorm * line.Direction();
985               if ( dot > maxDot ) maxDot = dot;
986               if ( dot < minDot ) minDot = dot;
987             }
988             touchingInt = ( minDot*maxDot < 0 );
989           }
990         }
991         if ( !touchingInt )
992         {
993           if ( !hasPositionInfo || isOuterBoundary( u_int1->second._face ))
994           {
995             if ( u < 0 )
996               ++nbIntBeforePoint;
997             else
998               ++nbIntAfterPoint;
999           }
1000           if ( u < f ) f = u;
1001           if ( u > l ) l = u;
1002         }
1003
1004         u_int1 = u_int2; // to next intersection
1005
1006       } // loop on intersections with one line
1007
1008       if ( ok )
1009       {
1010         if ( fabs( f ) < tolerance || fabs( l ) < tolerance )
1011           return TopAbs_ON;
1012
1013         if ( nbIntBeforePoint == 0  || nbIntAfterPoint == 0)
1014           return TopAbs_OUT;
1015
1016         if ( nbIntBeforePoint + nbIntAfterPoint == 1 ) // not closed mesh
1017           return fabs( f ) < tolerance ? TopAbs_ON : TopAbs_UNKNOWN;
1018
1019         if ( nbIntBeforePoint == 1 || nbIntAfterPoint == 1 )
1020           return TopAbs_IN;
1021
1022         if ( (f<0) == (l<0) )
1023           return TopAbs_OUT;
1024
1025         if ( hasPositionInfo )
1026           return nbIntBeforePoint % 2 ? TopAbs_IN : TopAbs_OUT;
1027       }
1028     } // loop on intersections of the tree lines - thorough analysis
1029
1030     if ( !hasPositionInfo )
1031     {
1032       // gather info on faces position - is face in the outer boundary or not
1033       map< double, TInters > & u2inters = paramOnLine2TInters[ 0 ];
1034       findOuterBoundary( u2inters.begin()->second._face );
1035     }
1036
1037   } // two attempts - with and w/o faces position info in the mesh
1038
1039   return TopAbs_UNKNOWN;
1040 }
1041
1042 //=======================================================================
1043 /*!
1044  * \brief Return elements possibly intersecting the line
1045  */
1046 //=======================================================================
1047
1048 void SMESH_ElementSearcherImpl::GetElementsNearLine( const gp_Ax1&                      line,
1049                                                      SMDSAbs_ElementType                type,
1050                                                      vector< const SMDS_MeshElement* >& foundElems)
1051 {
1052   if ( !_ebbTree || _elementType != type )
1053   {
1054     if ( _ebbTree ) delete _ebbTree;
1055     _ebbTree = new ElementBndBoxTree( *_mesh, _elementType = type, _meshPartIt );
1056   }
1057   TIDSortedElemSet suspectFaces; // elements possibly intersecting the line
1058   _ebbTree->getElementsNearLine( line, suspectFaces );
1059   foundElems.assign( suspectFaces.begin(), suspectFaces.end());
1060 }
1061
1062 //=======================================================================
1063 /*!
1064  * \brief Return true if the point is IN or ON of the element
1065  */
1066 //=======================================================================
1067
1068 bool SMESH_MeshAlgos::IsOut( const SMDS_MeshElement* element, const gp_Pnt& point, double tol )
1069 {
1070   if ( element->GetType() == SMDSAbs_Volume)
1071   {
1072     return SMDS_VolumeTool( element ).IsOut( point.X(), point.Y(), point.Z(), tol );
1073   }
1074
1075   // get ordered nodes
1076
1077   vector< gp_XYZ > xyz;
1078   vector<const SMDS_MeshNode*> nodeList;
1079
1080   SMDS_ElemIteratorPtr nodeIt = element->nodesIterator();
1081   if ( element->IsQuadratic() ) {
1082     nodeIt = element->interlacedNodesElemIterator();
1083     // if (const SMDS_VtkFace* f=dynamic_cast<const SMDS_VtkFace*>(element))
1084     //   nodeIt = f->interlacedNodesElemIterator();
1085     // else if (const SMDS_VtkEdge*  e =dynamic_cast<const SMDS_VtkEdge*>(element))
1086     //   nodeIt = e->interlacedNodesElemIterator();
1087   }
1088   while ( nodeIt->more() )
1089   {
1090     SMESH_TNodeXYZ node = nodeIt->next();
1091     xyz.push_back( node );
1092     nodeList.push_back(node._node);
1093   }
1094
1095   int i, nbNodes = (int) nodeList.size(); // central node of biquadratic is missing
1096
1097   if ( element->GetType() == SMDSAbs_Face ) // --------------------------------------------------
1098   {
1099     // compute face normal
1100     gp_Vec faceNorm(0,0,0);
1101     xyz.push_back( xyz.front() );
1102     nodeList.push_back( nodeList.front() );
1103     for ( i = 0; i < nbNodes; ++i )
1104     {
1105       gp_Vec edge1( xyz[i+1], xyz[i]);
1106       gp_Vec edge2( xyz[i+1], xyz[(i+2)%nbNodes] );
1107       faceNorm += edge1 ^ edge2;
1108     }
1109     double normSize = faceNorm.Magnitude();
1110     if ( normSize <= tol )
1111     {
1112       // degenerated face: point is out if it is out of all face edges
1113       for ( i = 0; i < nbNodes; ++i )
1114       {
1115         SMDS_LinearEdge edge( nodeList[i], nodeList[i+1] );
1116         if ( !IsOut( &edge, point, tol ))
1117           return false;
1118       }
1119       return true;
1120     }
1121     faceNorm /= normSize;
1122
1123     // check if the point lays on face plane
1124     gp_Vec n2p( xyz[0], point );
1125     if ( fabs( n2p * faceNorm ) > tol )
1126       return true; // not on face plane
1127
1128     // check if point is out of face boundary:
1129     // define it by closest transition of a ray point->infinity through face boundary
1130     // on the face plane.
1131     // First, find normal of a plane perpendicular to face plane, to be used as a cutting tool
1132     // to find intersections of the ray with the boundary.
1133     gp_Vec ray = n2p;
1134     gp_Vec plnNorm = ray ^ faceNorm;
1135     normSize = plnNorm.Magnitude();
1136     if ( normSize <= tol ) return false; // point coincides with the first node
1137     plnNorm /= normSize;
1138     // for each node of the face, compute its signed distance to the plane
1139     vector<double> dist( nbNodes + 1);
1140     for ( i = 0; i < nbNodes; ++i )
1141     {
1142       gp_Vec n2p( xyz[i], point );
1143       dist[i] = n2p * plnNorm;
1144     }
1145     dist.back() = dist.front();
1146     // find the closest intersection
1147     int    iClosest = -1;
1148     double rClosest, distClosest = 1e100;;
1149     gp_Pnt pClosest;
1150     for ( i = 0; i < nbNodes; ++i )
1151     {
1152       double r;
1153       if ( fabs( dist[i]) < tol )
1154         r = 0.;
1155       else if ( fabs( dist[i+1]) < tol )
1156         r = 1.;
1157       else if ( dist[i] * dist[i+1] < 0 )
1158         r = dist[i] / ( dist[i] - dist[i+1] );
1159       else
1160         continue; // no intersection
1161       gp_Pnt pInt = xyz[i] * (1.-r) + xyz[i+1] * r;
1162       gp_Vec p2int ( point, pInt);
1163       if ( p2int * ray > -tol ) // right half-space
1164       {
1165         double intDist = p2int.SquareMagnitude();
1166         if ( intDist < distClosest )
1167         {
1168           iClosest = i;
1169           rClosest = r;
1170           pClosest = pInt;
1171           distClosest = intDist;
1172         }
1173       }
1174     }
1175     if ( iClosest < 0 )
1176       return true; // no intesections - out
1177
1178     // analyse transition
1179     gp_Vec edge( xyz[iClosest], xyz[iClosest+1] );
1180     gp_Vec edgeNorm = -( edge ^ faceNorm ); // normal to intersected edge pointing out of face
1181     gp_Vec p2int ( point, pClosest );
1182     bool out = (edgeNorm * p2int) < -tol;
1183     if ( rClosest > 0. && rClosest < 1. ) // not node intersection
1184       return out;
1185
1186     // ray pass through a face node; analyze transition through an adjacent edge
1187     gp_Pnt p1 = xyz[ (rClosest == 0.) ? ((iClosest+nbNodes-1) % nbNodes) : (iClosest+1) ];
1188     gp_Pnt p2 = xyz[ (rClosest == 0.) ? iClosest : ((iClosest+2) % nbNodes) ];
1189     gp_Vec edgeAdjacent( p1, p2 );
1190     gp_Vec edgeNorm2 = -( edgeAdjacent ^ faceNorm );
1191     bool out2 = (edgeNorm2 * p2int) < -tol;
1192
1193     bool covexCorner = ( edgeNorm * edgeAdjacent * (rClosest==1. ? 1. : -1.)) < 0;
1194     return covexCorner ? (out || out2) : (out && out2);
1195   }
1196   if ( element->GetType() == SMDSAbs_Edge ) // --------------------------------------------------
1197   {
1198     // point is out of edge if it is NOT ON any straight part of edge
1199     // (we consider quadratic edge as being composed of two straight parts)
1200     for ( i = 1; i < nbNodes; ++i )
1201     {
1202       gp_Vec edge( xyz[i-1], xyz[i]);
1203       gp_Vec n1p ( xyz[i-1], point);
1204       double dist = ( edge ^ n1p ).Magnitude() / edge.Magnitude();
1205       if ( dist > tol )
1206         continue;
1207       gp_Vec n2p( xyz[i], point );
1208       if ( fabs( edge.Magnitude() - n1p.Magnitude() - n2p.Magnitude()) > tol )
1209         continue;
1210       return false; // point is ON this part
1211     }
1212     return true;
1213   }
1214   // Node or 0D element -------------------------------------------------------------------------
1215   {
1216     gp_Vec n2p ( xyz[0], point );
1217     return n2p.Magnitude() <= tol;
1218   }
1219   return true;
1220 }
1221
1222 //=======================================================================
1223 namespace
1224 {
1225   // Position of a point relative to a segment
1226   //            .           .
1227   //            .  LEFT     .
1228   //            .           .
1229   //  VERTEX 1  o----ON----->  VERTEX 2
1230   //            .           .
1231   //            .  RIGHT    .
1232   //            .           .
1233   enum PositionName { POS_LEFT = 1, POS_VERTEX = 2, POS_RIGHT = 4, //POS_ON = 8,
1234                       POS_ALL = POS_LEFT | POS_RIGHT | POS_VERTEX };
1235   struct PointPos
1236   {
1237     PositionName _name;
1238     int          _index; // index of vertex or segment
1239
1240     PointPos( PositionName n, int i=-1 ): _name(n), _index(i) {}
1241     bool operator < (const PointPos& other ) const
1242     {
1243       if ( _name == other._name )
1244         return  ( _index < 0 || other._index < 0 ) ? false : _index < other._index;
1245       return _name < other._name;
1246     }
1247   };
1248
1249   //================================================================================
1250   /*!
1251    * \brief Return of a point relative to a segment
1252    *  \param point2D      - the point to analyze position of
1253    *  \param xyVec        - end points of segments
1254    *  \param index0       - 0-based index of the first point of segment
1255    *  \param posToFindOut - flags of positions to detect
1256    *  \retval PointPos - point position
1257    */
1258   //================================================================================
1259
1260   PointPos getPointPosition( const gp_XY& point2D,
1261                              const gp_XY* segEnds,
1262                              const int    index0 = 0,
1263                              const int    posToFindOut = POS_ALL)
1264   {
1265     const gp_XY& p1 = segEnds[ index0   ];
1266     const gp_XY& p2 = segEnds[ index0+1 ];
1267     const gp_XY grad = p2 - p1;
1268
1269     if ( posToFindOut & POS_VERTEX )
1270     {
1271       // check if the point2D is at "vertex 1" zone
1272       gp_XY pp1[2] = { p1, gp_XY( p1.X() - grad.Y(),
1273                                   p1.Y() + grad.X() ) };
1274       if ( getPointPosition( point2D, pp1, 0, POS_LEFT|POS_RIGHT )._name == POS_LEFT )
1275         return PointPos( POS_VERTEX, index0 );
1276
1277       // check if the point2D is at "vertex 2" zone
1278       gp_XY pp2[2] = { p2, gp_XY( p2.X() - grad.Y(),
1279                                   p2.Y() + grad.X() ) };
1280       if ( getPointPosition( point2D, pp2, 0, POS_LEFT|POS_RIGHT )._name == POS_RIGHT )
1281         return PointPos( POS_VERTEX, index0 + 1);
1282     }
1283     double edgeEquation =
1284       ( point2D.X() - p1.X() ) * grad.Y() - ( point2D.Y() - p1.Y() ) * grad.X();
1285     return PointPos( edgeEquation < 0 ? POS_LEFT : POS_RIGHT, index0 );
1286   }
1287 }
1288
1289 //=======================================================================
1290 /*!
1291  * \brief Return minimal distance from a point to a face
1292  *
1293  * Currently we ignore non-planarity and 2nd order of face
1294  */
1295 //=======================================================================
1296
1297 double SMESH_MeshAlgos::GetDistance( const SMDS_MeshFace* face,
1298                                      const gp_Pnt&        point )
1299 {
1300   double badDistance = -1;
1301   if ( !face ) return badDistance;
1302
1303   // coordinates of nodes (medium nodes, if any, ignored)
1304   typedef SMDS_StdIterator< SMESH_TNodeXYZ, SMDS_ElemIteratorPtr > TXyzIterator;
1305   vector<gp_XYZ> xyz( TXyzIterator( face->nodesIterator()), TXyzIterator() );
1306   xyz.resize( face->NbCornerNodes()+1 );
1307
1308   // transformation to get xyz[0] lies on the origin, xyz[1] lies on the Z axis,
1309   // and xyz[2] lies in the XZ plane. This is to pass to 2D space on XZ plane.
1310   gp_Trsf trsf;
1311   gp_Vec OZ ( xyz[0], xyz[1] );
1312   gp_Vec OX ( xyz[0], xyz[2] );
1313   if ( OZ.Magnitude() < std::numeric_limits<double>::min() )
1314   {
1315     if ( xyz.size() < 4 ) return badDistance;
1316     OZ = gp_Vec ( xyz[0], xyz[2] );
1317     OX = gp_Vec ( xyz[0], xyz[3] );
1318   }
1319   gp_Ax3 tgtCS;
1320   try {
1321     tgtCS = gp_Ax3( xyz[0], OZ, OX );
1322   }
1323   catch ( Standard_Failure ) {
1324     return badDistance;
1325   }
1326   trsf.SetTransformation( tgtCS );
1327
1328   // move all the nodes to 2D
1329   vector<gp_XY> xy( xyz.size() );
1330   for ( size_t i = 0;i < xyz.size()-1; ++i )
1331   {
1332     gp_XYZ p3d = xyz[i];
1333     trsf.Transforms( p3d );
1334     xy[i].SetCoord( p3d.X(), p3d.Z() );
1335   }
1336   xyz.back() = xyz.front();
1337   xy.back() = xy.front();
1338
1339   // // move the point in 2D
1340   gp_XYZ tmpPnt = point.XYZ();
1341   trsf.Transforms( tmpPnt );
1342   gp_XY point2D( tmpPnt.X(), tmpPnt.Z() );
1343
1344   // loop on segments of the face to analyze point position ralative to the face
1345   set< PointPos > pntPosSet;
1346   for ( size_t i = 1; i < xy.size(); ++i )
1347   {
1348     PointPos pos = getPointPosition( point2D, &xy[0], i-1 );
1349     pntPosSet.insert( pos );
1350   }
1351
1352   // compute distance
1353   PointPos pos = *pntPosSet.begin();
1354   // cout << "Face " << face->GetID() << " DIST: ";
1355   switch ( pos._name )
1356   {
1357   case POS_LEFT: {
1358     // point is most close to a segment
1359     gp_Vec p0p1( point, xyz[ pos._index ] );
1360     gp_Vec p1p2( xyz[ pos._index ], xyz[ pos._index+1 ]); // segment vector
1361     p1p2.Normalize();
1362     double projDist = p0p1 * p1p2; // distance projected to the segment
1363     gp_Vec projVec = p1p2 * projDist;
1364     gp_Vec distVec = p0p1 - projVec;
1365     // cout << distVec.Magnitude()  << ", SEG " << face->GetNode(pos._index)->GetID()
1366     //      << " - " << face->GetNodeWrap(pos._index+1)->GetID() << endl;
1367     return distVec.Magnitude();
1368   }
1369   case POS_RIGHT: {
1370     // point is inside the face
1371     double distToFacePlane = tmpPnt.Y();
1372     // cout << distToFacePlane << ", INSIDE " << endl;
1373     return Abs( distToFacePlane );
1374   }
1375   case POS_VERTEX: {
1376     // point is most close to a node
1377     gp_Vec distVec( point, xyz[ pos._index ]);
1378     // cout << distVec.Magnitude()  << " VERTEX " << face->GetNode(pos._index)->GetID() << endl;
1379     return distVec.Magnitude();
1380   }
1381   }
1382   return badDistance;
1383 }
1384
1385 //=======================================================================
1386 //function : FindFaceInSet
1387 //purpose  : Return a face having linked nodes n1 and n2 and which is
1388 //           - not in avoidSet,
1389 //           - in elemSet provided that !elemSet.empty()
1390 //           i1 and i2 optionally returns indices of n1 and n2
1391 //=======================================================================
1392
1393 const SMDS_MeshElement*
1394 SMESH_MeshAlgos::FindFaceInSet(const SMDS_MeshNode*    n1,
1395                                const SMDS_MeshNode*    n2,
1396                                const TIDSortedElemSet& elemSet,
1397                                const TIDSortedElemSet& avoidSet,
1398                                int*                    n1ind,
1399                                int*                    n2ind)
1400
1401 {
1402   int i1, i2;
1403   const SMDS_MeshElement* face = 0;
1404
1405   SMDS_ElemIteratorPtr invElemIt = n1->GetInverseElementIterator(SMDSAbs_Face);
1406   //MESSAGE("n1->GetInverseElementIterator(SMDSAbs_Face) " << invElemIt);
1407   while ( invElemIt->more() && !face ) // loop on inverse faces of n1
1408   {
1409     //MESSAGE("in while ( invElemIt->more() && !face )");
1410     const SMDS_MeshElement* elem = invElemIt->next();
1411     if (avoidSet.count( elem ))
1412       continue;
1413     if ( !elemSet.empty() && !elemSet.count( elem ))
1414       continue;
1415     // index of n1
1416     i1 = elem->GetNodeIndex( n1 );
1417     // find a n2 linked to n1
1418     int nbN = elem->IsQuadratic() ? elem->NbNodes()/2 : elem->NbNodes();
1419     for ( int di = -1; di < 2 && !face; di += 2 )
1420     {
1421       i2 = (i1+di+nbN) % nbN;
1422       if ( elem->GetNode( i2 ) == n2 )
1423         face = elem;
1424     }
1425     if ( !face && elem->IsQuadratic())
1426     {
1427       // analysis for quadratic elements using all nodes
1428       // const SMDS_VtkFace* F = dynamic_cast<const SMDS_VtkFace*>(elem);
1429       // if (!F) throw SALOME_Exception(LOCALIZED("not an SMDS_VtkFace"));
1430       // use special nodes iterator
1431       SMDS_ElemIteratorPtr anIter = elem->interlacedNodesElemIterator();
1432       const SMDS_MeshNode* prevN = static_cast<const SMDS_MeshNode*>( anIter->next() );
1433       for ( i1 = -1, i2 = 0; anIter->more() && !face; i1++, i2++ )
1434       {
1435         const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( anIter->next() );
1436         if ( n1 == prevN && n2 == n )
1437         {
1438           face = elem;
1439         }
1440         else if ( n2 == prevN && n1 == n )
1441         {
1442           face = elem; swap( i1, i2 );
1443         }
1444         prevN = n;
1445       }
1446     }
1447   }
1448   if ( n1ind ) *n1ind = i1;
1449   if ( n2ind ) *n2ind = i2;
1450   return face;
1451 }
1452
1453 //================================================================================
1454 /*!
1455  * \brief Calculate normal of a mesh face
1456  */
1457 //================================================================================
1458
1459 bool SMESH_MeshAlgos::FaceNormal(const SMDS_MeshElement* F, gp_XYZ& normal, bool normalized)
1460 {
1461   if ( !F || F->GetType() != SMDSAbs_Face )
1462     return false;
1463
1464   normal.SetCoord(0,0,0);
1465   int nbNodes = F->IsQuadratic() ? F->NbNodes()/2 : F->NbNodes();
1466   for ( int i = 0; i < nbNodes-2; ++i )
1467   {
1468     gp_XYZ p[3];
1469     for ( int n = 0; n < 3; ++n )
1470     {
1471       const SMDS_MeshNode* node = F->GetNode( i + n );
1472       p[n].SetCoord( node->X(), node->Y(), node->Z() );
1473     }
1474     normal += ( p[2] - p[1] ) ^ ( p[0] - p[1] );
1475   }
1476   double size2 = normal.SquareModulus();
1477   bool ok = ( size2 > numeric_limits<double>::min() * numeric_limits<double>::min());
1478   if ( normalized && ok )
1479     normal /= sqrt( size2 );
1480
1481   return ok;
1482 }
1483
1484 //=======================================================================
1485 //function : GetCommonNodes
1486 //purpose  : Return nodes common to two elements
1487 //=======================================================================
1488
1489 vector< const SMDS_MeshNode*> SMESH_MeshAlgos::GetCommonNodes(const SMDS_MeshElement* e1,
1490                                                               const SMDS_MeshElement* e2)
1491 {
1492   vector< const SMDS_MeshNode*> common;
1493   for ( int i = 0 ; i < e1->NbNodes(); ++i )
1494     if ( e2->GetNodeIndex( e1->GetNode( i )) >= 0 )
1495       common.push_back( e1->GetNode( i ));
1496   return common;
1497 }
1498
1499 //=======================================================================
1500 /*!
1501  * \brief Return SMESH_NodeSearcher
1502  */
1503 //=======================================================================
1504
1505 SMESH_NodeSearcher* SMESH_MeshAlgos::GetNodeSearcher(SMDS_Mesh& mesh)
1506 {
1507   return new SMESH_NodeSearcherImpl( &mesh );
1508 }
1509
1510 //=======================================================================
1511 /*!
1512  * \brief Return SMESH_ElementSearcher
1513  */
1514 //=======================================================================
1515
1516 SMESH_ElementSearcher* SMESH_MeshAlgos::GetElementSearcher(SMDS_Mesh& mesh)
1517 {
1518   return new SMESH_ElementSearcherImpl( mesh );
1519 }
1520
1521 //=======================================================================
1522 /*!
1523  * \brief Return SMESH_ElementSearcher acting on a sub-set of elements
1524  */
1525 //=======================================================================
1526
1527 SMESH_ElementSearcher* SMESH_MeshAlgos::GetElementSearcher(SMDS_Mesh&           mesh,
1528                                                            SMDS_ElemIteratorPtr elemIt)
1529 {
1530   return new SMESH_ElementSearcherImpl( mesh, elemIt );
1531 }