Salome HOME
2ecd29a9044f5b483c2645a8b13e7be1a4b700cf
[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     virtual ~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 SMESH_ElementSearcher::~SMESH_ElementSearcher()
414 {
415 }
416
417 struct SMESH_ElementSearcherImpl: public SMESH_ElementSearcher
418 {
419   SMDS_Mesh*                   _mesh;
420   SMDS_ElemIteratorPtr         _meshPartIt;
421   ElementBndBoxTree*           _ebbTree;
422   SMESH_NodeSearcherImpl*      _nodeSearcher;
423   SMDSAbs_ElementType          _elementType;
424   double                       _tolerance;
425   bool                         _outerFacesFound;
426   set<const SMDS_MeshElement*> _outerFaces; // empty means "no internal faces at all"
427
428   SMESH_ElementSearcherImpl( SMDS_Mesh& mesh, SMDS_ElemIteratorPtr elemIt=SMDS_ElemIteratorPtr())
429     : _mesh(&mesh),_meshPartIt(elemIt),_ebbTree(0),_nodeSearcher(0),_tolerance(-1),_outerFacesFound(false) {}
430   virtual ~SMESH_ElementSearcherImpl()
431   {
432     if ( _ebbTree )      delete _ebbTree;      _ebbTree      = 0;
433     if ( _nodeSearcher ) delete _nodeSearcher; _nodeSearcher = 0;
434   }
435   virtual int FindElementsByPoint(const gp_Pnt&                      point,
436                                   SMDSAbs_ElementType                type,
437                                   vector< const SMDS_MeshElement* >& foundElements);
438   virtual TopAbs_State GetPointState(const gp_Pnt& point);
439   virtual const SMDS_MeshElement* FindClosestTo( const gp_Pnt&       point,
440                                                  SMDSAbs_ElementType type );
441
442   void GetElementsNearLine( const gp_Ax1&                      line,
443                             SMDSAbs_ElementType                type,
444                             vector< const SMDS_MeshElement* >& foundElems);
445   double getTolerance();
446   bool getIntersParamOnLine(const gp_Lin& line, const SMDS_MeshElement* face,
447                             const double tolerance, double & param);
448   void findOuterBoundary(const SMDS_MeshElement* anyOuterFace);
449   bool isOuterBoundary(const SMDS_MeshElement* face) const
450   {
451     return _outerFaces.empty() || _outerFaces.count(face);
452   }
453   struct TInters //!< data of intersection of the line and the mesh face (used in GetPointState())
454   {
455     const SMDS_MeshElement* _face;
456     gp_Vec                  _faceNorm;
457     bool                    _coincides; //!< the line lays in face plane
458     TInters(const SMDS_MeshElement* face, const gp_Vec& faceNorm, bool coinc=false)
459       : _face(face), _faceNorm( faceNorm ), _coincides( coinc ) {}
460   };
461   struct TFaceLink //!< link and faces sharing it (used in findOuterBoundary())
462   {
463     SMESH_TLink      _link;
464     TIDSortedElemSet _faces;
465     TFaceLink( const SMDS_MeshNode* n1, const SMDS_MeshNode* n2, const SMDS_MeshElement* face)
466       : _link( n1, n2 ), _faces( &face, &face + 1) {}
467   };
468 };
469
470 ostream& operator<< (ostream& out, const SMESH_ElementSearcherImpl::TInters& i)
471 {
472   return out << "TInters(face=" << ( i._face ? i._face->GetID() : 0)
473              << ", _coincides="<<i._coincides << ")";
474 }
475
476 //=======================================================================
477 /*!
478  * \brief define tolerance for search
479  */
480 //=======================================================================
481
482 double SMESH_ElementSearcherImpl::getTolerance()
483 {
484   if ( _tolerance < 0 )
485   {
486     const SMDS_MeshInfo& meshInfo = _mesh->GetMeshInfo();
487
488     _tolerance = 0;
489     if ( _nodeSearcher && meshInfo.NbNodes() > 1 )
490     {
491       double boxSize = _nodeSearcher->getTree()->maxSize();
492       _tolerance = 1e-8 * boxSize/* / meshInfo.NbNodes()*/;
493     }
494     else if ( _ebbTree && meshInfo.NbElements() > 0 )
495     {
496       double boxSize = _ebbTree->maxSize();
497       _tolerance = 1e-8 * boxSize/* / meshInfo.NbElements()*/;
498     }
499     if ( _tolerance == 0 )
500     {
501       // define tolerance by size of a most complex element
502       int complexType = SMDSAbs_Volume;
503       while ( complexType > SMDSAbs_All &&
504               meshInfo.NbElements( SMDSAbs_ElementType( complexType )) < 1 )
505         --complexType;
506       if ( complexType == SMDSAbs_All ) return 0; // empty mesh
507       double elemSize;
508       if ( complexType == int( SMDSAbs_Node ))
509       {
510         SMDS_NodeIteratorPtr nodeIt = _mesh->nodesIterator();
511         elemSize = 1;
512         if ( meshInfo.NbNodes() > 2 )
513           elemSize = SMESH_TNodeXYZ( nodeIt->next() ).Distance( nodeIt->next() );
514       }
515       else
516       {
517         SMDS_ElemIteratorPtr elemIt =
518             _mesh->elementsIterator( SMDSAbs_ElementType( complexType ));
519         const SMDS_MeshElement* elem = elemIt->next();
520         SMDS_ElemIteratorPtr nodeIt = elem->nodesIterator();
521         SMESH_TNodeXYZ n1( nodeIt->next() );
522         elemSize = 0;
523         while ( nodeIt->more() )
524         {
525           double dist = n1.Distance( static_cast<const SMDS_MeshNode*>( nodeIt->next() ));
526           elemSize = max( dist, elemSize );
527         }
528       }
529       _tolerance = 1e-4 * elemSize;
530     }
531   }
532   return _tolerance;
533 }
534
535 //================================================================================
536 /*!
537  * \brief Find intersection of the line and an edge of face and return parameter on line
538  */
539 //================================================================================
540
541 bool SMESH_ElementSearcherImpl::getIntersParamOnLine(const gp_Lin&           line,
542                                                      const SMDS_MeshElement* face,
543                                                      const double            tol,
544                                                      double &                param)
545 {
546   int nbInts = 0;
547   param = 0;
548
549   GeomAPI_ExtremaCurveCurve anExtCC;
550   Handle(Geom_Curve) lineCurve = new Geom_Line( line );
551
552   int nbNodes = face->IsQuadratic() ? face->NbNodes()/2 : face->NbNodes();
553   for ( int i = 0; i < nbNodes && nbInts < 2; ++i )
554   {
555     GC_MakeSegment edge( SMESH_TNodeXYZ( face->GetNode( i )),
556                          SMESH_TNodeXYZ( face->GetNode( (i+1)%nbNodes) ));
557     anExtCC.Init( lineCurve, edge);
558     if ( anExtCC.NbExtrema() > 0 && anExtCC.LowerDistance() <= tol)
559     {
560       Quantity_Parameter pl, pe;
561       anExtCC.LowerDistanceParameters( pl, pe );
562       param += pl;
563       if ( ++nbInts == 2 )
564         break;
565     }
566   }
567   if ( nbInts > 0 ) param /= nbInts;
568   return nbInts > 0;
569 }
570 //================================================================================
571 /*!
572  * \brief Find all faces belonging to the outer boundary of mesh
573  */
574 //================================================================================
575
576 void SMESH_ElementSearcherImpl::findOuterBoundary(const SMDS_MeshElement* outerFace)
577 {
578   if ( _outerFacesFound ) return;
579
580   // Collect all outer faces by passing from one outer face to another via their links
581   // and BTW find out if there are internal faces at all.
582
583   // checked links and links where outer boundary meets internal one
584   set< SMESH_TLink > visitedLinks, seamLinks;
585
586   // links to treat with already visited faces sharing them
587   list < TFaceLink > startLinks;
588
589   // load startLinks with the first outerFace
590   startLinks.push_back( TFaceLink( outerFace->GetNode(0), outerFace->GetNode(1), outerFace));
591   _outerFaces.insert( outerFace );
592
593   TIDSortedElemSet emptySet;
594   while ( !startLinks.empty() )
595   {
596     const SMESH_TLink& link  = startLinks.front()._link;
597     TIDSortedElemSet&  faces = startLinks.front()._faces;
598
599     outerFace = *faces.begin();
600     // find other faces sharing the link
601     const SMDS_MeshElement* f;
602     while (( f = SMESH_MeshAlgos::FindFaceInSet(link.node1(), link.node2(), emptySet, faces )))
603       faces.insert( f );
604
605     // select another outer face among the found
606     const SMDS_MeshElement* outerFace2 = 0;
607     if ( faces.size() == 2 )
608     {
609       outerFace2 = (outerFace == *faces.begin() ? *faces.rbegin() : *faces.begin());
610     }
611     else if ( faces.size() > 2 )
612     {
613       seamLinks.insert( link );
614
615       // link direction within the outerFace
616       gp_Vec n1n2( SMESH_TNodeXYZ( link.node1()),
617                    SMESH_TNodeXYZ( link.node2()));
618       int i1 = outerFace->GetNodeIndex( link.node1() );
619       int i2 = outerFace->GetNodeIndex( link.node2() );
620       bool rev = ( abs(i2-i1) == 1 ? i1 > i2 : i2 > i1 );
621       if ( rev ) n1n2.Reverse();
622       // outerFace normal
623       gp_XYZ ofNorm, fNorm;
624       if ( SMESH_MeshAlgos::FaceNormal( outerFace, ofNorm, /*normalized=*/false ))
625       {
626         // direction from the link inside outerFace
627         gp_Vec dirInOF = gp_Vec( ofNorm ) ^ n1n2;
628         // sort all other faces by angle with the dirInOF
629         map< double, const SMDS_MeshElement* > angle2Face;
630         set< const SMDS_MeshElement*, TIDCompare >::const_iterator face = faces.begin();
631         for ( ; face != faces.end(); ++face )
632         {
633           if ( !SMESH_MeshAlgos::FaceNormal( *face, fNorm, /*normalized=*/false ))
634             continue;
635           gp_Vec dirInF = gp_Vec( fNorm ) ^ n1n2;
636           double angle = dirInOF.AngleWithRef( dirInF, n1n2 );
637           if ( angle < 0 ) angle += 2. * M_PI;
638           angle2Face.insert( make_pair( angle, *face ));
639         }
640         if ( !angle2Face.empty() )
641           outerFace2 = angle2Face.begin()->second;
642       }
643     }
644     // store the found outer face and add its links to continue seaching from
645     if ( outerFace2 )
646     {
647       _outerFaces.insert( outerFace );
648       int nbNodes = outerFace2->NbNodes()/( outerFace2->IsQuadratic() ? 2 : 1 );
649       for ( int i = 0; i < nbNodes; ++i )
650       {
651         SMESH_TLink link2( outerFace2->GetNode(i), outerFace2->GetNode((i+1)%nbNodes));
652         if ( visitedLinks.insert( link2 ).second )
653           startLinks.push_back( TFaceLink( link2.node1(), link2.node2(), outerFace2 ));
654       }
655     }
656     startLinks.pop_front();
657   }
658   _outerFacesFound = true;
659
660   if ( !seamLinks.empty() )
661   {
662     // There are internal boundaries touching the outher one,
663     // find all faces of internal boundaries in order to find
664     // faces of boundaries of holes, if any.
665
666   }
667   else
668   {
669     _outerFaces.clear();
670   }
671 }
672
673 //=======================================================================
674 /*!
675  * \brief Find elements of given type where the given point is IN or ON.
676  *        Returns nb of found elements and elements them-selves.
677  *
678  * 'ALL' type means elements of any type excluding nodes, balls and 0D elements
679  */
680 //=======================================================================
681
682 int SMESH_ElementSearcherImpl::
683 FindElementsByPoint(const gp_Pnt&                      point,
684                     SMDSAbs_ElementType                type,
685                     vector< const SMDS_MeshElement* >& foundElements)
686 {
687   foundElements.clear();
688
689   double tolerance = getTolerance();
690
691   // =================================================================================
692   if ( type == SMDSAbs_Node || type == SMDSAbs_0DElement || type == SMDSAbs_Ball)
693   {
694     if ( !_nodeSearcher )
695       _nodeSearcher = new SMESH_NodeSearcherImpl( _mesh );
696
697     const SMDS_MeshNode* closeNode = _nodeSearcher->FindClosestTo( point );
698     if ( !closeNode ) return foundElements.size();
699
700     if ( point.Distance( SMESH_TNodeXYZ( closeNode )) > tolerance )
701       return foundElements.size(); // to far from any node
702
703     if ( type == SMDSAbs_Node )
704     {
705       foundElements.push_back( closeNode );
706     }
707     else
708     {
709       SMDS_ElemIteratorPtr elemIt = closeNode->GetInverseElementIterator( type );
710       while ( elemIt->more() )
711         foundElements.push_back( elemIt->next() );
712     }
713   }
714   // =================================================================================
715   else // elements more complex than 0D
716   {
717     if ( !_ebbTree || _elementType != type )
718     {
719       if ( _ebbTree ) delete _ebbTree;
720       _ebbTree = new ElementBndBoxTree( *_mesh, _elementType = type, _meshPartIt, tolerance );
721     }
722     TIDSortedElemSet suspectElems;
723     _ebbTree->getElementsNearPoint( point, suspectElems );
724     TIDSortedElemSet::iterator elem = suspectElems.begin();
725     for ( ; elem != suspectElems.end(); ++elem )
726       if ( !SMESH_MeshAlgos::IsOut( *elem, point, tolerance ))
727         foundElements.push_back( *elem );
728   }
729   return foundElements.size();
730 }
731
732 //=======================================================================
733 /*!
734  * \brief Find an element of given type most close to the given point
735  *
736  * WARNING: Only face search is implemeneted so far
737  */
738 //=======================================================================
739
740 const SMDS_MeshElement*
741 SMESH_ElementSearcherImpl::FindClosestTo( const gp_Pnt&       point,
742                                           SMDSAbs_ElementType type )
743 {
744   const SMDS_MeshElement* closestElem = 0;
745
746   if ( type == SMDSAbs_Face )
747   {
748     if ( !_ebbTree || _elementType != type )
749     {
750       if ( _ebbTree ) delete _ebbTree;
751       _ebbTree = new ElementBndBoxTree( *_mesh, _elementType = type, _meshPartIt );
752     }
753     TIDSortedElemSet suspectElems;
754     _ebbTree->getElementsNearPoint( point, suspectElems );
755
756     if ( suspectElems.empty() && _ebbTree->maxSize() > 0 )
757     {
758       gp_Pnt boxCenter = 0.5 * ( _ebbTree->getBox()->CornerMin() +
759                                  _ebbTree->getBox()->CornerMax() );
760       double radius;
761       if ( _ebbTree->getBox()->IsOut( point.XYZ() ))
762         radius = point.Distance( boxCenter ) - 0.5 * _ebbTree->maxSize();
763       else
764         radius = _ebbTree->maxSize() / pow( 2., _ebbTree->getHeight()) / 2;
765       while ( suspectElems.empty() )
766       {
767         _ebbTree->getElementsInSphere( point.XYZ(), radius, suspectElems );
768         radius *= 1.1;
769       }
770     }
771     double minDist = std::numeric_limits<double>::max();
772     multimap< double, const SMDS_MeshElement* > dist2face;
773     TIDSortedElemSet::iterator elem = suspectElems.begin();
774     for ( ; elem != suspectElems.end(); ++elem )
775     {
776       double dist = SMESH_MeshAlgos::GetDistance( dynamic_cast<const SMDS_MeshFace*>(*elem),
777                                                    point );
778       if ( dist < minDist + 1e-10)
779       {
780         minDist = dist;
781         dist2face.insert( dist2face.begin(), make_pair( dist, *elem ));
782       }
783     }
784     if ( !dist2face.empty() )
785     {
786       multimap< double, const SMDS_MeshElement* >::iterator d2f = dist2face.begin();
787       closestElem = d2f->second;
788       // if there are several elements at the same distance, select one
789       // with GC closest to the point
790       typedef SMDS_StdIterator< SMESH_TNodeXYZ, SMDS_ElemIteratorPtr > TXyzIterator;
791       double minDistToGC = 0;
792       for ( ++d2f; d2f != dist2face.end() && fabs( d2f->first - minDist ) < 1e-10; ++d2f )
793       {
794         if ( minDistToGC == 0 )
795         {
796           gp_XYZ gc(0,0,0);
797           gc = accumulate( TXyzIterator(closestElem->nodesIterator()),
798                            TXyzIterator(), gc ) / closestElem->NbNodes();
799           minDistToGC = point.SquareDistance( gc );
800         }
801         gp_XYZ gc(0,0,0);
802         gc = accumulate( TXyzIterator( d2f->second->nodesIterator()),
803                          TXyzIterator(), gc ) / d2f->second->NbNodes();
804         double d = point.SquareDistance( gc );
805         if ( d < minDistToGC )
806         {
807           minDistToGC = d;
808           closestElem = d2f->second;
809         }
810       }
811       // cout << "FindClosestTo( " <<point.X()<<", "<<point.Y()<<", "<<point.Z()<<" ) FACE "
812       //      <<closestElem->GetID() << " DIST " << minDist << endl;
813     }
814   }
815   else
816   {
817     // NOT IMPLEMENTED SO FAR
818   }
819   return closestElem;
820 }
821
822
823 //================================================================================
824 /*!
825  * \brief Classify the given point in the closed 2D mesh
826  */
827 //================================================================================
828
829 TopAbs_State SMESH_ElementSearcherImpl::GetPointState(const gp_Pnt& point)
830 {
831   double tolerance = getTolerance();
832   if ( !_ebbTree || _elementType != SMDSAbs_Face )
833   {
834     if ( _ebbTree ) delete _ebbTree;
835     _ebbTree = new ElementBndBoxTree( *_mesh, _elementType = SMDSAbs_Face, _meshPartIt );
836   }
837   // Algo: analyse transition of a line starting at the point through mesh boundary;
838   // try three lines parallel to axis of the coordinate system and perform rough
839   // analysis. If solution is not clear perform thorough analysis.
840
841   const int nbAxes = 3;
842   gp_Dir axisDir[ nbAxes ] = { gp::DX(), gp::DY(), gp::DZ() };
843   map< double, TInters >   paramOnLine2TInters[ nbAxes ];
844   list< TInters > tangentInters[ nbAxes ]; // of faces whose plane includes the line
845   multimap< int, int > nbInt2Axis; // to find the simplest case
846   for ( int axis = 0; axis < nbAxes; ++axis )
847   {
848     gp_Ax1 lineAxis( point, axisDir[axis]);
849     gp_Lin line    ( lineAxis );
850
851     TIDSortedElemSet suspectFaces; // faces possibly intersecting the line
852     _ebbTree->getElementsNearLine( lineAxis, suspectFaces );
853
854     // Intersect faces with the line
855
856     map< double, TInters > & u2inters = paramOnLine2TInters[ axis ];
857     TIDSortedElemSet::iterator face = suspectFaces.begin();
858     for ( ; face != suspectFaces.end(); ++face )
859     {
860       // get face plane
861       gp_XYZ fNorm;
862       if ( !SMESH_MeshAlgos::FaceNormal( *face, fNorm, /*normalized=*/false)) continue;
863       gp_Pln facePlane( SMESH_TNodeXYZ( (*face)->GetNode(0)), fNorm );
864
865       // perform intersection
866       IntAna_IntConicQuad intersection( line, IntAna_Quadric( facePlane ));
867       if ( !intersection.IsDone() )
868         continue;
869       if ( intersection.IsInQuadric() )
870       {
871         tangentInters[ axis ].push_back( TInters( *face, fNorm, true ));
872       }
873       else if ( ! intersection.IsParallel() && intersection.NbPoints() > 0 )
874       {
875         gp_Pnt intersectionPoint = intersection.Point(1);
876         if ( !SMESH_MeshAlgos::IsOut( *face, intersectionPoint, tolerance ))
877           u2inters.insert(make_pair( intersection.ParamOnConic(1), TInters( *face, fNorm )));
878       }
879     }
880     // Analyse intersections roughly
881
882     int nbInter = u2inters.size();
883     if ( nbInter == 0 )
884       return TopAbs_OUT;
885
886     double f = u2inters.begin()->first, l = u2inters.rbegin()->first;
887     if ( nbInter == 1 ) // not closed mesh
888       return fabs( f ) < tolerance ? TopAbs_ON : TopAbs_UNKNOWN;
889
890     if ( fabs( f ) < tolerance || fabs( l ) < tolerance )
891       return TopAbs_ON;
892
893     if ( (f<0) == (l<0) )
894       return TopAbs_OUT;
895
896     int nbIntBeforePoint = std::distance( u2inters.begin(), u2inters.lower_bound(0));
897     int nbIntAfterPoint  = nbInter - nbIntBeforePoint;
898     if ( nbIntBeforePoint == 1 || nbIntAfterPoint == 1 )
899       return TopAbs_IN;
900
901     nbInt2Axis.insert( make_pair( min( nbIntBeforePoint, nbIntAfterPoint ), axis ));
902
903     if ( _outerFacesFound ) break; // pass to thorough analysis
904
905   } // three attempts - loop on CS axes
906
907   // Analyse intersections thoroughly.
908   // We make two loops maximum, on the first one we only exclude touching intersections,
909   // on the second, if situation is still unclear, we gather and use information on
910   // position of faces (internal or outer). If faces position is already gathered,
911   // we make the second loop right away.
912
913   for ( int hasPositionInfo = _outerFacesFound; hasPositionInfo < 2; ++hasPositionInfo )
914   {
915     multimap< int, int >::const_iterator nb_axis = nbInt2Axis.begin();
916     for ( ; nb_axis != nbInt2Axis.end(); ++nb_axis )
917     {
918       int axis = nb_axis->second;
919       map< double, TInters > & u2inters = paramOnLine2TInters[ axis ];
920
921       gp_Ax1 lineAxis( point, axisDir[axis]);
922       gp_Lin line    ( lineAxis );
923
924       // add tangent intersections to u2inters
925       double param;
926       list< TInters >::const_iterator tgtInt = tangentInters[ axis ].begin();
927       for ( ; tgtInt != tangentInters[ axis ].end(); ++tgtInt )
928         if ( getIntersParamOnLine( line, tgtInt->_face, tolerance, param ))
929           u2inters.insert(make_pair( param, *tgtInt ));
930       tangentInters[ axis ].clear();
931
932       // Count intersections before and after the point excluding touching ones.
933       // If hasPositionInfo we count intersections of outer boundary only
934
935       int nbIntBeforePoint = 0, nbIntAfterPoint = 0;
936       double f = numeric_limits<double>::max(), l = -numeric_limits<double>::max();
937       map< double, TInters >::iterator u_int1 = u2inters.begin(), u_int2 = u_int1;
938       bool ok = ! u_int1->second._coincides;
939       while ( ok && u_int1 != u2inters.end() )
940       {
941         double u = u_int1->first;
942         bool touchingInt = false;
943         if ( ++u_int2 != u2inters.end() )
944         {
945           // skip intersections at the same point (if the line passes through edge or node)
946           int nbSamePnt = 0;
947           while ( u_int2 != u2inters.end() && fabs( u_int2->first - u ) < tolerance )
948           {
949             ++nbSamePnt;
950             ++u_int2;
951           }
952
953           // skip tangent intersections
954           int nbTgt = 0;
955           const SMDS_MeshElement* prevFace = u_int1->second._face;
956           while ( ok && u_int2->second._coincides )
957           {
958             if ( SMESH_MeshAlgos::GetCommonNodes(prevFace , u_int2->second._face).empty() )
959               ok = false;
960             else
961             {
962               nbTgt++;
963               u_int2++;
964               ok = ( u_int2 != u2inters.end() );
965             }
966           }
967           if ( !ok ) break;
968
969           // skip intersections at the same point after tangent intersections
970           if ( nbTgt > 0 )
971           {
972             double u2 = u_int2->first;
973             ++u_int2;
974             while ( u_int2 != u2inters.end() && fabs( u_int2->first - u2 ) < tolerance )
975             {
976               ++nbSamePnt;
977               ++u_int2;
978             }
979           }
980           // decide if we skipped a touching intersection
981           if ( nbSamePnt + nbTgt > 0 )
982           {
983             double minDot = numeric_limits<double>::max(), maxDot = -numeric_limits<double>::max();
984             map< double, TInters >::iterator u_int = u_int1;
985             for ( ; u_int != u_int2; ++u_int )
986             {
987               if ( u_int->second._coincides ) continue;
988               double dot = u_int->second._faceNorm * line.Direction();
989               if ( dot > maxDot ) maxDot = dot;
990               if ( dot < minDot ) minDot = dot;
991             }
992             touchingInt = ( minDot*maxDot < 0 );
993           }
994         }
995         if ( !touchingInt )
996         {
997           if ( !hasPositionInfo || isOuterBoundary( u_int1->second._face ))
998           {
999             if ( u < 0 )
1000               ++nbIntBeforePoint;
1001             else
1002               ++nbIntAfterPoint;
1003           }
1004           if ( u < f ) f = u;
1005           if ( u > l ) l = u;
1006         }
1007
1008         u_int1 = u_int2; // to next intersection
1009
1010       } // loop on intersections with one line
1011
1012       if ( ok )
1013       {
1014         if ( fabs( f ) < tolerance || fabs( l ) < tolerance )
1015           return TopAbs_ON;
1016
1017         if ( nbIntBeforePoint == 0  || nbIntAfterPoint == 0)
1018           return TopAbs_OUT;
1019
1020         if ( nbIntBeforePoint + nbIntAfterPoint == 1 ) // not closed mesh
1021           return fabs( f ) < tolerance ? TopAbs_ON : TopAbs_UNKNOWN;
1022
1023         if ( nbIntBeforePoint == 1 || nbIntAfterPoint == 1 )
1024           return TopAbs_IN;
1025
1026         if ( (f<0) == (l<0) )
1027           return TopAbs_OUT;
1028
1029         if ( hasPositionInfo )
1030           return nbIntBeforePoint % 2 ? TopAbs_IN : TopAbs_OUT;
1031       }
1032     } // loop on intersections of the tree lines - thorough analysis
1033
1034     if ( !hasPositionInfo )
1035     {
1036       // gather info on faces position - is face in the outer boundary or not
1037       map< double, TInters > & u2inters = paramOnLine2TInters[ 0 ];
1038       findOuterBoundary( u2inters.begin()->second._face );
1039     }
1040
1041   } // two attempts - with and w/o faces position info in the mesh
1042
1043   return TopAbs_UNKNOWN;
1044 }
1045
1046 //=======================================================================
1047 /*!
1048  * \brief Return elements possibly intersecting the line
1049  */
1050 //=======================================================================
1051
1052 void SMESH_ElementSearcherImpl::GetElementsNearLine( const gp_Ax1&                      line,
1053                                                      SMDSAbs_ElementType                type,
1054                                                      vector< const SMDS_MeshElement* >& foundElems)
1055 {
1056   if ( !_ebbTree || _elementType != type )
1057   {
1058     if ( _ebbTree ) delete _ebbTree;
1059     _ebbTree = new ElementBndBoxTree( *_mesh, _elementType = type, _meshPartIt );
1060   }
1061   TIDSortedElemSet suspectFaces; // elements possibly intersecting the line
1062   _ebbTree->getElementsNearLine( line, suspectFaces );
1063   foundElems.assign( suspectFaces.begin(), suspectFaces.end());
1064 }
1065
1066 //=======================================================================
1067 /*!
1068  * \brief Return true if the point is IN or ON of the element
1069  */
1070 //=======================================================================
1071
1072 bool SMESH_MeshAlgos::IsOut( const SMDS_MeshElement* element, const gp_Pnt& point, double tol )
1073 {
1074   if ( element->GetType() == SMDSAbs_Volume)
1075   {
1076     return SMDS_VolumeTool( element ).IsOut( point.X(), point.Y(), point.Z(), tol );
1077   }
1078
1079   // get ordered nodes
1080
1081   vector< gp_XYZ > xyz;
1082   vector<const SMDS_MeshNode*> nodeList;
1083
1084   SMDS_ElemIteratorPtr nodeIt = element->nodesIterator();
1085   if ( element->IsQuadratic() ) {
1086     nodeIt = element->interlacedNodesElemIterator();
1087     // if (const SMDS_VtkFace* f=dynamic_cast<const SMDS_VtkFace*>(element))
1088     //   nodeIt = f->interlacedNodesElemIterator();
1089     // else if (const SMDS_VtkEdge*  e =dynamic_cast<const SMDS_VtkEdge*>(element))
1090     //   nodeIt = e->interlacedNodesElemIterator();
1091   }
1092   while ( nodeIt->more() )
1093   {
1094     SMESH_TNodeXYZ node = nodeIt->next();
1095     xyz.push_back( node );
1096     nodeList.push_back(node._node);
1097   }
1098
1099   int i, nbNodes = (int) nodeList.size(); // central node of biquadratic is missing
1100
1101   if ( element->GetType() == SMDSAbs_Face ) // --------------------------------------------------
1102   {
1103     // compute face normal
1104     gp_Vec faceNorm(0,0,0);
1105     xyz.push_back( xyz.front() );
1106     nodeList.push_back( nodeList.front() );
1107     for ( i = 0; i < nbNodes; ++i )
1108     {
1109       gp_Vec edge1( xyz[i+1], xyz[i]);
1110       gp_Vec edge2( xyz[i+1], xyz[(i+2)%nbNodes] );
1111       faceNorm += edge1 ^ edge2;
1112     }
1113     double normSize = faceNorm.Magnitude();
1114     if ( normSize <= tol )
1115     {
1116       // degenerated face: point is out if it is out of all face edges
1117       for ( i = 0; i < nbNodes; ++i )
1118       {
1119         SMDS_LinearEdge edge( nodeList[i], nodeList[i+1] );
1120         if ( !IsOut( &edge, point, tol ))
1121           return false;
1122       }
1123       return true;
1124     }
1125     faceNorm /= normSize;
1126
1127     // check if the point lays on face plane
1128     gp_Vec n2p( xyz[0], point );
1129     if ( fabs( n2p * faceNorm ) > tol )
1130       return true; // not on face plane
1131
1132     // check if point is out of face boundary:
1133     // define it by closest transition of a ray point->infinity through face boundary
1134     // on the face plane.
1135     // First, find normal of a plane perpendicular to face plane, to be used as a cutting tool
1136     // to find intersections of the ray with the boundary.
1137     gp_Vec ray = n2p;
1138     gp_Vec plnNorm = ray ^ faceNorm;
1139     normSize = plnNorm.Magnitude();
1140     if ( normSize <= tol ) return false; // point coincides with the first node
1141     plnNorm /= normSize;
1142     // for each node of the face, compute its signed distance to the plane
1143     vector<double> dist( nbNodes + 1);
1144     for ( i = 0; i < nbNodes; ++i )
1145     {
1146       gp_Vec n2p( xyz[i], point );
1147       dist[i] = n2p * plnNorm;
1148     }
1149     dist.back() = dist.front();
1150     // find the closest intersection
1151     int    iClosest = -1;
1152     double rClosest, distClosest = 1e100;;
1153     gp_Pnt pClosest;
1154     for ( i = 0; i < nbNodes; ++i )
1155     {
1156       double r;
1157       if ( fabs( dist[i]) < tol )
1158         r = 0.;
1159       else if ( fabs( dist[i+1]) < tol )
1160         r = 1.;
1161       else if ( dist[i] * dist[i+1] < 0 )
1162         r = dist[i] / ( dist[i] - dist[i+1] );
1163       else
1164         continue; // no intersection
1165       gp_Pnt pInt = xyz[i] * (1.-r) + xyz[i+1] * r;
1166       gp_Vec p2int ( point, pInt);
1167       if ( p2int * ray > -tol ) // right half-space
1168       {
1169         double intDist = p2int.SquareMagnitude();
1170         if ( intDist < distClosest )
1171         {
1172           iClosest = i;
1173           rClosest = r;
1174           pClosest = pInt;
1175           distClosest = intDist;
1176         }
1177       }
1178     }
1179     if ( iClosest < 0 )
1180       return true; // no intesections - out
1181
1182     // analyse transition
1183     gp_Vec edge( xyz[iClosest], xyz[iClosest+1] );
1184     gp_Vec edgeNorm = -( edge ^ faceNorm ); // normal to intersected edge pointing out of face
1185     gp_Vec p2int ( point, pClosest );
1186     bool out = (edgeNorm * p2int) < -tol;
1187     if ( rClosest > 0. && rClosest < 1. ) // not node intersection
1188       return out;
1189
1190     // ray pass through a face node; analyze transition through an adjacent edge
1191     gp_Pnt p1 = xyz[ (rClosest == 0.) ? ((iClosest+nbNodes-1) % nbNodes) : (iClosest+1) ];
1192     gp_Pnt p2 = xyz[ (rClosest == 0.) ? iClosest : ((iClosest+2) % nbNodes) ];
1193     gp_Vec edgeAdjacent( p1, p2 );
1194     gp_Vec edgeNorm2 = -( edgeAdjacent ^ faceNorm );
1195     bool out2 = (edgeNorm2 * p2int) < -tol;
1196
1197     bool covexCorner = ( edgeNorm * edgeAdjacent * (rClosest==1. ? 1. : -1.)) < 0;
1198     return covexCorner ? (out || out2) : (out && out2);
1199   }
1200   if ( element->GetType() == SMDSAbs_Edge ) // --------------------------------------------------
1201   {
1202     // point is out of edge if it is NOT ON any straight part of edge
1203     // (we consider quadratic edge as being composed of two straight parts)
1204     for ( i = 1; i < nbNodes; ++i )
1205     {
1206       gp_Vec edge( xyz[i-1], xyz[i]);
1207       gp_Vec n1p ( xyz[i-1], point);
1208       double dist = ( edge ^ n1p ).Magnitude() / edge.Magnitude();
1209       if ( dist > tol )
1210         continue;
1211       gp_Vec n2p( xyz[i], point );
1212       if ( fabs( edge.Magnitude() - n1p.Magnitude() - n2p.Magnitude()) > tol )
1213         continue;
1214       return false; // point is ON this part
1215     }
1216     return true;
1217   }
1218   // Node or 0D element -------------------------------------------------------------------------
1219   {
1220     gp_Vec n2p ( xyz[0], point );
1221     return n2p.Magnitude() <= tol;
1222   }
1223   return true;
1224 }
1225
1226 //=======================================================================
1227 namespace
1228 {
1229   // Position of a point relative to a segment
1230   //            .           .
1231   //            .  LEFT     .
1232   //            .           .
1233   //  VERTEX 1  o----ON----->  VERTEX 2
1234   //            .           .
1235   //            .  RIGHT    .
1236   //            .           .
1237   enum PositionName { POS_LEFT = 1, POS_VERTEX = 2, POS_RIGHT = 4, //POS_ON = 8,
1238                       POS_ALL = POS_LEFT | POS_RIGHT | POS_VERTEX };
1239   struct PointPos
1240   {
1241     PositionName _name;
1242     int          _index; // index of vertex or segment
1243
1244     PointPos( PositionName n, int i=-1 ): _name(n), _index(i) {}
1245     bool operator < (const PointPos& other ) const
1246     {
1247       if ( _name == other._name )
1248         return  ( _index < 0 || other._index < 0 ) ? false : _index < other._index;
1249       return _name < other._name;
1250     }
1251   };
1252
1253   //================================================================================
1254   /*!
1255    * \brief Return of a point relative to a segment
1256    *  \param point2D      - the point to analyze position of
1257    *  \param xyVec        - end points of segments
1258    *  \param index0       - 0-based index of the first point of segment
1259    *  \param posToFindOut - flags of positions to detect
1260    *  \retval PointPos - point position
1261    */
1262   //================================================================================
1263
1264   PointPos getPointPosition( const gp_XY& point2D,
1265                              const gp_XY* segEnds,
1266                              const int    index0 = 0,
1267                              const int    posToFindOut = POS_ALL)
1268   {
1269     const gp_XY& p1 = segEnds[ index0   ];
1270     const gp_XY& p2 = segEnds[ index0+1 ];
1271     const gp_XY grad = p2 - p1;
1272
1273     if ( posToFindOut & POS_VERTEX )
1274     {
1275       // check if the point2D is at "vertex 1" zone
1276       gp_XY pp1[2] = { p1, gp_XY( p1.X() - grad.Y(),
1277                                   p1.Y() + grad.X() ) };
1278       if ( getPointPosition( point2D, pp1, 0, POS_LEFT|POS_RIGHT )._name == POS_LEFT )
1279         return PointPos( POS_VERTEX, index0 );
1280
1281       // check if the point2D is at "vertex 2" zone
1282       gp_XY pp2[2] = { p2, gp_XY( p2.X() - grad.Y(),
1283                                   p2.Y() + grad.X() ) };
1284       if ( getPointPosition( point2D, pp2, 0, POS_LEFT|POS_RIGHT )._name == POS_RIGHT )
1285         return PointPos( POS_VERTEX, index0 + 1);
1286     }
1287     double edgeEquation =
1288       ( point2D.X() - p1.X() ) * grad.Y() - ( point2D.Y() - p1.Y() ) * grad.X();
1289     return PointPos( edgeEquation < 0 ? POS_LEFT : POS_RIGHT, index0 );
1290   }
1291 }
1292
1293 //=======================================================================
1294 /*!
1295  * \brief Return minimal distance from a point to a face
1296  *
1297  * Currently we ignore non-planarity and 2nd order of face
1298  */
1299 //=======================================================================
1300
1301 double SMESH_MeshAlgos::GetDistance( const SMDS_MeshFace* face,
1302                                      const gp_Pnt&        point )
1303 {
1304   double badDistance = -1;
1305   if ( !face ) return badDistance;
1306
1307   // coordinates of nodes (medium nodes, if any, ignored)
1308   typedef SMDS_StdIterator< SMESH_TNodeXYZ, SMDS_ElemIteratorPtr > TXyzIterator;
1309   vector<gp_XYZ> xyz( TXyzIterator( face->nodesIterator()), TXyzIterator() );
1310   xyz.resize( face->NbCornerNodes()+1 );
1311
1312   // transformation to get xyz[0] lies on the origin, xyz[1] lies on the Z axis,
1313   // and xyz[2] lies in the XZ plane. This is to pass to 2D space on XZ plane.
1314   gp_Trsf trsf;
1315   gp_Vec OZ ( xyz[0], xyz[1] );
1316   gp_Vec OX ( xyz[0], xyz[2] );
1317   if ( OZ.Magnitude() < std::numeric_limits<double>::min() )
1318   {
1319     if ( xyz.size() < 4 ) return badDistance;
1320     OZ = gp_Vec ( xyz[0], xyz[2] );
1321     OX = gp_Vec ( xyz[0], xyz[3] );
1322   }
1323   gp_Ax3 tgtCS;
1324   try {
1325     tgtCS = gp_Ax3( xyz[0], OZ, OX );
1326   }
1327   catch ( Standard_Failure ) {
1328     return badDistance;
1329   }
1330   trsf.SetTransformation( tgtCS );
1331
1332   // move all the nodes to 2D
1333   vector<gp_XY> xy( xyz.size() );
1334   for ( size_t i = 0;i < xyz.size()-1; ++i )
1335   {
1336     gp_XYZ p3d = xyz[i];
1337     trsf.Transforms( p3d );
1338     xy[i].SetCoord( p3d.X(), p3d.Z() );
1339   }
1340   xyz.back() = xyz.front();
1341   xy.back() = xy.front();
1342
1343   // // move the point in 2D
1344   gp_XYZ tmpPnt = point.XYZ();
1345   trsf.Transforms( tmpPnt );
1346   gp_XY point2D( tmpPnt.X(), tmpPnt.Z() );
1347
1348   // loop on segments of the face to analyze point position ralative to the face
1349   set< PointPos > pntPosSet;
1350   for ( size_t i = 1; i < xy.size(); ++i )
1351   {
1352     PointPos pos = getPointPosition( point2D, &xy[0], i-1 );
1353     pntPosSet.insert( pos );
1354   }
1355
1356   // compute distance
1357   PointPos pos = *pntPosSet.begin();
1358   // cout << "Face " << face->GetID() << " DIST: ";
1359   switch ( pos._name )
1360   {
1361   case POS_LEFT: {
1362     // point is most close to a segment
1363     gp_Vec p0p1( point, xyz[ pos._index ] );
1364     gp_Vec p1p2( xyz[ pos._index ], xyz[ pos._index+1 ]); // segment vector
1365     p1p2.Normalize();
1366     double projDist = p0p1 * p1p2; // distance projected to the segment
1367     gp_Vec projVec = p1p2 * projDist;
1368     gp_Vec distVec = p0p1 - projVec;
1369     // cout << distVec.Magnitude()  << ", SEG " << face->GetNode(pos._index)->GetID()
1370     //      << " - " << face->GetNodeWrap(pos._index+1)->GetID() << endl;
1371     return distVec.Magnitude();
1372   }
1373   case POS_RIGHT: {
1374     // point is inside the face
1375     double distToFacePlane = tmpPnt.Y();
1376     // cout << distToFacePlane << ", INSIDE " << endl;
1377     return Abs( distToFacePlane );
1378   }
1379   case POS_VERTEX: {
1380     // point is most close to a node
1381     gp_Vec distVec( point, xyz[ pos._index ]);
1382     // cout << distVec.Magnitude()  << " VERTEX " << face->GetNode(pos._index)->GetID() << endl;
1383     return distVec.Magnitude();
1384   }
1385   }
1386   return badDistance;
1387 }
1388
1389 //================================================================================
1390 /*!
1391  * \brief Returns barycentric coordinates of a point within a triangle.
1392  *        A not returned bc2 = 1. - bc0 - bc1.
1393  *        The point lies within the triangle if ( bc0 >= 0 && bc1 >= 0 && bc0+bc1 <= 1 )
1394  */
1395 //================================================================================
1396
1397 void SMESH_MeshAlgos::GetBarycentricCoords( const gp_XY& p,
1398                                             const gp_XY& t0,
1399                                             const gp_XY& t1,
1400                                             const gp_XY& t2,
1401                                             double &     bc0,
1402                                             double &     bc1)
1403 {
1404   const double // matrix 2x2
1405     T11 = t0.X()-t2.X(), T12 = t1.X()-t2.X(),
1406     T21 = t0.Y()-t2.Y(), T22 = t1.Y()-t2.Y();
1407   const double Tdet = T11*T22 - T12*T21; // matrix determinant
1408   if ( Abs( Tdet ) < std::numeric_limits<double>::min() )
1409   {
1410     bc0 = bc1 = 2.;
1411     return;
1412   }
1413   // matrix inverse
1414   const double t11 = T22, t12 = -T12, t21 = -T21, t22 = T11;
1415   // vector
1416   const double r11 = p.X()-t2.X(), r12 = p.Y()-t2.Y();
1417   // barycentric coordinates: mutiply matrix by vector
1418   bc0 = (t11 * r11 + t12 * r12)/Tdet;
1419   bc1 = (t21 * r11 + t22 * r12)/Tdet;
1420 }
1421
1422 //=======================================================================
1423 //function : FindFaceInSet
1424 //purpose  : Return a face having linked nodes n1 and n2 and which is
1425 //           - not in avoidSet,
1426 //           - in elemSet provided that !elemSet.empty()
1427 //           i1 and i2 optionally returns indices of n1 and n2
1428 //=======================================================================
1429
1430 const SMDS_MeshElement*
1431 SMESH_MeshAlgos::FindFaceInSet(const SMDS_MeshNode*    n1,
1432                                const SMDS_MeshNode*    n2,
1433                                const TIDSortedElemSet& elemSet,
1434                                const TIDSortedElemSet& avoidSet,
1435                                int*                    n1ind,
1436                                int*                    n2ind)
1437
1438 {
1439   int i1, i2;
1440   const SMDS_MeshElement* face = 0;
1441
1442   SMDS_ElemIteratorPtr invElemIt = n1->GetInverseElementIterator(SMDSAbs_Face);
1443   //MESSAGE("n1->GetInverseElementIterator(SMDSAbs_Face) " << invElemIt);
1444   while ( invElemIt->more() && !face ) // loop on inverse faces of n1
1445   {
1446     //MESSAGE("in while ( invElemIt->more() && !face )");
1447     const SMDS_MeshElement* elem = invElemIt->next();
1448     if (avoidSet.count( elem ))
1449       continue;
1450     if ( !elemSet.empty() && !elemSet.count( elem ))
1451       continue;
1452     // index of n1
1453     i1 = elem->GetNodeIndex( n1 );
1454     // find a n2 linked to n1
1455     int nbN = elem->IsQuadratic() ? elem->NbNodes()/2 : elem->NbNodes();
1456     for ( int di = -1; di < 2 && !face; di += 2 )
1457     {
1458       i2 = (i1+di+nbN) % nbN;
1459       if ( elem->GetNode( i2 ) == n2 )
1460         face = elem;
1461     }
1462     if ( !face && elem->IsQuadratic())
1463     {
1464       // analysis for quadratic elements using all nodes
1465       // const SMDS_VtkFace* F = dynamic_cast<const SMDS_VtkFace*>(elem);
1466       // if (!F) throw SALOME_Exception(LOCALIZED("not an SMDS_VtkFace"));
1467       // use special nodes iterator
1468       SMDS_ElemIteratorPtr anIter = elem->interlacedNodesElemIterator();
1469       const SMDS_MeshNode* prevN = static_cast<const SMDS_MeshNode*>( anIter->next() );
1470       for ( i1 = -1, i2 = 0; anIter->more() && !face; i1++, i2++ )
1471       {
1472         const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( anIter->next() );
1473         if ( n1 == prevN && n2 == n )
1474         {
1475           face = elem;
1476         }
1477         else if ( n2 == prevN && n1 == n )
1478         {
1479           face = elem; swap( i1, i2 );
1480         }
1481         prevN = n;
1482       }
1483     }
1484   }
1485   if ( n1ind ) *n1ind = i1;
1486   if ( n2ind ) *n2ind = i2;
1487   return face;
1488 }
1489
1490 //================================================================================
1491 /*!
1492  * \brief Calculate normal of a mesh face
1493  */
1494 //================================================================================
1495
1496 bool SMESH_MeshAlgos::FaceNormal(const SMDS_MeshElement* F, gp_XYZ& normal, bool normalized)
1497 {
1498   if ( !F || F->GetType() != SMDSAbs_Face )
1499     return false;
1500
1501   normal.SetCoord(0,0,0);
1502   int nbNodes = F->IsQuadratic() ? F->NbNodes()/2 : F->NbNodes();
1503   for ( int i = 0; i < nbNodes-2; ++i )
1504   {
1505     gp_XYZ p[3];
1506     for ( int n = 0; n < 3; ++n )
1507     {
1508       const SMDS_MeshNode* node = F->GetNode( i + n );
1509       p[n].SetCoord( node->X(), node->Y(), node->Z() );
1510     }
1511     normal += ( p[2] - p[1] ) ^ ( p[0] - p[1] );
1512   }
1513   double size2 = normal.SquareModulus();
1514   bool ok = ( size2 > numeric_limits<double>::min() * numeric_limits<double>::min());
1515   if ( normalized && ok )
1516     normal /= sqrt( size2 );
1517
1518   return ok;
1519 }
1520
1521 //=======================================================================
1522 //function : GetCommonNodes
1523 //purpose  : Return nodes common to two elements
1524 //=======================================================================
1525
1526 vector< const SMDS_MeshNode*> SMESH_MeshAlgos::GetCommonNodes(const SMDS_MeshElement* e1,
1527                                                               const SMDS_MeshElement* e2)
1528 {
1529   vector< const SMDS_MeshNode*> common;
1530   for ( int i = 0 ; i < e1->NbNodes(); ++i )
1531     if ( e2->GetNodeIndex( e1->GetNode( i )) >= 0 )
1532       common.push_back( e1->GetNode( i ));
1533   return common;
1534 }
1535
1536 //=======================================================================
1537 /*!
1538  * \brief Return SMESH_NodeSearcher
1539  */
1540 //=======================================================================
1541
1542 SMESH_NodeSearcher* SMESH_MeshAlgos::GetNodeSearcher(SMDS_Mesh& mesh)
1543 {
1544   return new SMESH_NodeSearcherImpl( &mesh );
1545 }
1546
1547 //=======================================================================
1548 /*!
1549  * \brief Return SMESH_ElementSearcher
1550  */
1551 //=======================================================================
1552
1553 SMESH_ElementSearcher* SMESH_MeshAlgos::GetElementSearcher(SMDS_Mesh& mesh)
1554 {
1555   return new SMESH_ElementSearcherImpl( mesh );
1556 }
1557
1558 //=======================================================================
1559 /*!
1560  * \brief Return SMESH_ElementSearcher acting on a sub-set of elements
1561  */
1562 //=======================================================================
1563
1564 SMESH_ElementSearcher* SMESH_MeshAlgos::GetElementSearcher(SMDS_Mesh&           mesh,
1565                                                            SMDS_ElemIteratorPtr elemIt)
1566 {
1567   return new SMESH_ElementSearcherImpl( mesh, elemIt );
1568 }