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