Salome HOME
8b40fe2d9510cb79979d8e80f8a5a0dde77d80e5
[modules/smesh.git] / src / StdMeshers / StdMeshers_Cartesian_3D.cxx
1 // Copyright (C) 2007-2014  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   : StdMeshers_Cartesian_3D.cxx
23 //  Module : SMESH
24 //
25 #include "StdMeshers_Cartesian_3D.hxx"
26
27 #include "SMDS_MeshNode.hxx"
28 #include "SMESH_Block.hxx"
29 #include "SMESH_Comment.hxx"
30 #include "SMESH_Mesh.hxx"
31 #include "SMESH_MesherHelper.hxx"
32 #include "SMESH_subMesh.hxx"
33 #include "SMESH_subMeshEventListener.hxx"
34 #include "StdMeshers_CartesianParameters3D.hxx"
35
36 #include <utilities.h>
37 #include <Utils_ExceptHandlers.hxx>
38 #include <Basics_OCCTVersion.hxx>
39
40 #include <GEOMUtils.hxx>
41
42 #include <BRepAdaptor_Curve.hxx>
43 #include <BRepAdaptor_Surface.hxx>
44 #include <BRepBndLib.hxx>
45 #include <BRepBuilderAPI_Copy.hxx>
46 #include <BRepBuilderAPI_MakeFace.hxx>
47 #include <BRepTools.hxx>
48 #include <BRepTopAdaptor_FClass2d.hxx>
49 #include <BRep_Builder.hxx>
50 #include <BRep_Tool.hxx>
51 #include <Bnd_B3d.hxx>
52 #include <Bnd_Box.hxx>
53 #include <ElSLib.hxx>
54 #include <GCPnts_UniformDeflection.hxx>
55 #include <Geom2d_BSplineCurve.hxx>
56 #include <Geom2d_BezierCurve.hxx>
57 #include <Geom2d_TrimmedCurve.hxx>
58 #include <GeomAPI_ProjectPointOnSurf.hxx>
59 #include <GeomLib.hxx>
60 #include <Geom_BSplineCurve.hxx>
61 #include <Geom_BSplineSurface.hxx>
62 #include <Geom_BezierCurve.hxx>
63 #include <Geom_BezierSurface.hxx>
64 #include <Geom_RectangularTrimmedSurface.hxx>
65 #include <Geom_TrimmedCurve.hxx>
66 #include <IntAna_IntConicQuad.hxx>
67 #include <IntAna_IntLinTorus.hxx>
68 #include <IntAna_Quadric.hxx>
69 #include <IntCurveSurface_TransitionOnCurve.hxx>
70 #include <IntCurvesFace_Intersector.hxx>
71 #include <Poly_Triangulation.hxx>
72 #include <Precision.hxx>
73 #include <TopExp.hxx>
74 #include <TopExp_Explorer.hxx>
75 #include <TopLoc_Location.hxx>
76 #include <TopTools_MapOfShape.hxx>
77 #include <TopoDS.hxx>
78 #include <TopoDS_Compound.hxx>
79 #include <TopoDS_Face.hxx>
80 #include <TopoDS_TShape.hxx>
81 #include <gp_Cone.hxx>
82 #include <gp_Cylinder.hxx>
83 #include <gp_Lin.hxx>
84 #include <gp_Pln.hxx>
85 #include <gp_Pnt2d.hxx>
86 #include <gp_Sphere.hxx>
87 #include <gp_Torus.hxx>
88
89 #include <limits>
90
91 //#undef WITH_TBB
92 #ifdef WITH_TBB
93 #include <tbb/parallel_for.h>
94 //#include <tbb/enumerable_thread_specific.h>
95 #endif
96
97 using namespace std;
98
99 #ifdef _DEBUG_
100 //#define _MY_DEBUG_
101 #endif
102
103 #if OCC_VERSION_LARGE <= 0x06050300
104 // workaround is required only for OCCT6.5.3 and older (see OCC22809)
105 #define ELLIPSOLID_WORKAROUND
106 #endif
107
108 #ifdef ELLIPSOLID_WORKAROUND
109 #include <BRepIntCurveSurface_Inter.hxx>
110 #include <BRepTopAdaptor_TopolTool.hxx>
111 #include <BRepAdaptor_HSurface.hxx>
112 #endif
113
114 //=============================================================================
115 /*!
116  * Constructor
117  */
118 //=============================================================================
119
120 StdMeshers_Cartesian_3D::StdMeshers_Cartesian_3D(int hypId, int studyId, SMESH_Gen * gen)
121   :SMESH_3D_Algo(hypId, studyId, gen)
122 {
123   _name = "Cartesian_3D";
124   _shapeType = (1 << TopAbs_SOLID);       // 1 bit /shape type
125   _compatibleHypothesis.push_back("CartesianParameters3D");
126
127   _onlyUnaryInput = false;          // to mesh all SOLIDs at once
128   _requireDiscreteBoundary = false; // 2D mesh not needed
129   _supportSubmeshes = false;        // do not use any existing mesh
130 }
131
132 //=============================================================================
133 /*!
134  * Check presence of a hypothesis
135  */
136 //=============================================================================
137
138 bool StdMeshers_Cartesian_3D::CheckHypothesis (SMESH_Mesh&          aMesh,
139                                                const TopoDS_Shape&  aShape,
140                                                Hypothesis_Status&   aStatus)
141 {
142   aStatus = SMESH_Hypothesis::HYP_MISSING;
143
144   const list<const SMESHDS_Hypothesis*>& hyps = GetUsedHypothesis(aMesh, aShape);
145   list <const SMESHDS_Hypothesis* >::const_iterator h = hyps.begin();
146   if ( h == hyps.end())
147   {
148     return false;
149   }
150
151   for ( ; h != hyps.end(); ++h )
152   {
153     if (( _hyp = dynamic_cast<const StdMeshers_CartesianParameters3D*>( *h )))
154     {
155       aStatus = _hyp->IsDefined() ? HYP_OK : HYP_BAD_PARAMETER;
156       break;
157     }
158   }
159
160   return aStatus == HYP_OK;
161 }
162
163 namespace
164 {
165   typedef int TGeomID;
166
167   //=============================================================================
168   // Definitions of internal utils
169   // --------------------------------------------------------------------------
170   enum Transition {
171     Trans_TANGENT = IntCurveSurface_Tangent,
172     Trans_IN      = IntCurveSurface_In,
173     Trans_OUT     = IntCurveSurface_Out,
174     Trans_APEX
175   };
176   // --------------------------------------------------------------------------
177   /*!
178    * \brief Common data of any intersection between a Grid and a shape
179    */
180   struct B_IntersectPoint
181   {
182     mutable const SMDS_MeshNode* _node;
183     mutable vector< TGeomID >    _faceIDs;
184
185     B_IntersectPoint(): _node(NULL) {}
186     void Add( const vector< TGeomID >& fIDs, const SMDS_MeshNode* n=0 ) const;
187     int HasCommonFace( const B_IntersectPoint * other, int avoidFace=-1 ) const;
188     bool IsOnFace( int faceID ) const;
189     virtual ~B_IntersectPoint() {}
190   };
191   // --------------------------------------------------------------------------
192   /*!
193    * \brief Data of intersection between a GridLine and a TopoDS_Face
194    */
195   struct F_IntersectPoint : public B_IntersectPoint
196   {
197     double             _paramOnLine;
198     mutable Transition _transition;
199     mutable size_t     _indexOnLine;
200
201     bool operator< ( const F_IntersectPoint& o ) const { return _paramOnLine < o._paramOnLine; }
202   };
203   // --------------------------------------------------------------------------
204   /*!
205    * \brief Data of intersection between GridPlanes and a TopoDS_EDGE
206    */
207   struct E_IntersectPoint : public B_IntersectPoint
208   {
209     gp_Pnt  _point;
210     double  _uvw[3];
211     TGeomID _shapeID;
212   };
213   // --------------------------------------------------------------------------
214   /*!
215    * \brief A line of the grid and its intersections with 2D geometry
216    */
217   struct GridLine
218   {
219     gp_Lin _line;
220     double _length; // line length
221     multiset< F_IntersectPoint > _intPoints;
222
223     void RemoveExcessIntPoints( const double tol );
224     bool GetIsOutBefore( multiset< F_IntersectPoint >::iterator ip, bool prevIsOut );
225   };
226   // --------------------------------------------------------------------------
227   /*!
228    * \brief Planes of the grid used to find intersections of an EDGE with a hexahedron
229    */
230   struct GridPlanes
231   {
232     gp_XYZ           _zNorm;
233     vector< gp_XYZ > _origins; // origin points of all planes in one direction
234     vector< double > _zProjs;  // projections of origins to _zNorm
235   };
236   // --------------------------------------------------------------------------
237   /*!
238    * \brief Iterator on the parallel grid lines of one direction
239    */
240   struct LineIndexer
241   {
242     size_t _size  [3];
243     size_t _curInd[3];
244     size_t _iVar1, _iVar2, _iConst;
245     string _name1, _name2, _nameConst;
246     LineIndexer() {}
247     LineIndexer( size_t sz1, size_t sz2, size_t sz3,
248                  size_t iv1, size_t iv2, size_t iConst,
249                  const string& nv1, const string& nv2, const string& nConst )
250     {
251       _size[0] = sz1; _size[1] = sz2; _size[2] = sz3;
252       _curInd[0] = _curInd[1] = _curInd[2] = 0;
253       _iVar1 = iv1; _iVar2 = iv2; _iConst = iConst; 
254       _name1 = nv1; _name2 = nv2; _nameConst = nConst;
255     }
256
257     size_t I() const { return _curInd[0]; }
258     size_t J() const { return _curInd[1]; }
259     size_t K() const { return _curInd[2]; }
260     void SetIJK( size_t i, size_t j, size_t k )
261     {
262       _curInd[0] = i; _curInd[1] = j; _curInd[2] = k;
263     }
264     void operator++()
265     {
266       if ( ++_curInd[_iVar1] == _size[_iVar1] )
267         _curInd[_iVar1] = 0, ++_curInd[_iVar2];
268     }
269     bool More() const { return _curInd[_iVar2] < _size[_iVar2]; }
270     size_t LineIndex   () const { return _curInd[_iVar1] + _curInd[_iVar2]* _size[_iVar1]; }
271     size_t LineIndex10 () const { return (_curInd[_iVar1] + 1 ) + _curInd[_iVar2]* _size[_iVar1]; }
272     size_t LineIndex01 () const { return _curInd[_iVar1] + (_curInd[_iVar2] + 1 )* _size[_iVar1]; }
273     size_t LineIndex11 () const { return (_curInd[_iVar1] + 1 ) + (_curInd[_iVar2] + 1 )* _size[_iVar1]; }
274     void SetIndexOnLine (size_t i)  { _curInd[ _iConst ] = i; }
275     size_t NbLines() const { return _size[_iVar1] * _size[_iVar2]; }
276   };
277   // --------------------------------------------------------------------------
278   /*!
279    * \brief Container of GridLine's
280    */
281   struct Grid
282   {
283     vector< double >   _coords[3]; // coordinates of grid nodes
284     gp_XYZ             _axes  [3]; // axis directions
285     vector< GridLine > _lines [3]; //    in 3 directions
286     double             _tol, _minCellSize;
287     gp_XYZ             _origin;
288     gp_Mat             _invB; // inverted basis of _axes
289
290     vector< const SMDS_MeshNode* >    _nodes; // mesh nodes at grid nodes
291     vector< const F_IntersectPoint* > _gridIntP; // grid node intersection with geometry
292
293     list< E_IntersectPoint >          _edgeIntP; // intersections with EDGEs
294     TopTools_IndexedMapOfShape        _shapes;
295
296     SMESH_MesherHelper*               _helper;
297
298     size_t CellIndex( size_t i, size_t j, size_t k ) const
299     {
300       return i + j*(_coords[0].size()-1) + k*(_coords[0].size()-1)*(_coords[1].size()-1);
301     }
302     size_t NodeIndex( size_t i, size_t j, size_t k ) const
303     {
304       return i + j*_coords[0].size() + k*_coords[0].size()*_coords[1].size();
305     }
306     size_t NodeIndexDX() const { return 1; }
307     size_t NodeIndexDY() const { return _coords[0].size(); }
308     size_t NodeIndexDZ() const { return _coords[0].size() * _coords[1].size(); }
309
310     LineIndexer GetLineIndexer(size_t iDir) const;
311
312     void SetCoordinates(const vector<double>& xCoords,
313                         const vector<double>& yCoords,
314                         const vector<double>& zCoords,
315                         const double*         axesDirs,
316                         const Bnd_Box&        bndBox );
317     void ComputeUVW(const gp_XYZ& p, double uvw[3]);
318     void ComputeNodes(SMESH_MesherHelper& helper);
319   };
320 #ifdef ELLIPSOLID_WORKAROUND
321   // --------------------------------------------------------------------------
322   /*!
323    * \brief struct temporary replacing IntCurvesFace_Intersector until
324    *        OCCT bug 0022809 is fixed
325    *        http://tracker.dev.opencascade.org/view.php?id=22809
326    */
327   struct TMP_IntCurvesFace_Intersector
328   {
329     BRepAdaptor_Surface                       _surf;
330     double                                    _tol;
331     BRepIntCurveSurface_Inter                 _intcs;
332     vector<IntCurveSurface_IntersectionPoint> _points;
333     BRepTopAdaptor_TopolTool                  _clsf;
334
335     TMP_IntCurvesFace_Intersector(const TopoDS_Face& face, const double tol)
336       :_surf( face ), _tol( tol ), _clsf( new BRepAdaptor_HSurface(_surf) ) {}
337     Bnd_Box Bounding() const { Bnd_Box b; BRepBndLib::Add (_surf.Face(), b); return b; }
338     void Perform( const gp_Lin& line, const double w0, const double w1 )
339     {
340       _points.clear();
341       for ( _intcs.Init( _surf.Face(), line, _tol ); _intcs.More(); _intcs.Next() )
342         if ( w0 <= _intcs.W() && _intcs.W() <= w1 )
343           _points.push_back( _intcs.Point() );
344     }
345     bool IsDone() const { return true; }
346     int  NbPnt()  const { return _points.size(); }
347     IntCurveSurface_TransitionOnCurve Transition( const int i ) const { return _points[ i-1 ].Transition(); }
348     double       WParameter( const int i ) const { return _points[ i-1 ].W(); }
349     TopAbs_State ClassifyUVPoint(const gp_Pnt2d& p) { return _clsf.Classify( p, _tol ); }
350   };
351 #define __IntCurvesFace_Intersector TMP_IntCurvesFace_Intersector
352 #else
353 #define __IntCurvesFace_Intersector IntCurvesFace_Intersector
354 #endif
355   // --------------------------------------------------------------------------
356   /*!
357    * \brief Intersector of TopoDS_Face with all GridLine's
358    */
359   struct FaceGridIntersector
360   {
361     TopoDS_Face _face;
362     TGeomID     _faceID;
363     Grid*       _grid;
364     Bnd_Box     _bndBox;
365     __IntCurvesFace_Intersector* _surfaceInt;
366     vector< std::pair< GridLine*, F_IntersectPoint > > _intersections;
367
368     FaceGridIntersector(): _grid(0), _surfaceInt(0) {}
369     void Intersect();
370
371     void StoreIntersections()
372     {
373       for ( size_t i = 0; i < _intersections.size(); ++i )
374       {
375         multiset< F_IntersectPoint >::iterator ip = 
376           _intersections[i].first->_intPoints.insert( _intersections[i].second );
377         ip->_faceIDs.reserve( 1 );
378         ip->_faceIDs.push_back( _faceID );
379       }
380     }
381     const Bnd_Box& GetFaceBndBox()
382     {
383       GetCurveFaceIntersector();
384       return _bndBox;
385     }
386     __IntCurvesFace_Intersector* GetCurveFaceIntersector()
387     {
388       if ( !_surfaceInt )
389       {
390         _surfaceInt = new __IntCurvesFace_Intersector( _face, Precision::PConfusion() );
391         _bndBox     = _surfaceInt->Bounding();
392         if ( _bndBox.IsVoid() )
393           BRepBndLib::Add (_face, _bndBox);
394       }
395       return _surfaceInt;
396     }
397     bool IsThreadSafe(set< const Standard_Transient* >& noSafeTShapes) const;
398   };
399   // --------------------------------------------------------------------------
400   /*!
401    * \brief Intersector of a surface with a GridLine
402    */
403   struct FaceLineIntersector
404   {
405     double      _tol;
406     double      _u, _v, _w; // params on the face and the line
407     Transition  _transition; // transition of at intersection (see IntCurveSurface.cdl)
408     Transition  _transIn, _transOut; // IN and OUT transitions depending of face orientation
409
410     gp_Pln      _plane;
411     gp_Cylinder _cylinder;
412     gp_Cone     _cone;
413     gp_Sphere   _sphere;
414     gp_Torus    _torus;
415     __IntCurvesFace_Intersector* _surfaceInt;
416
417     vector< F_IntersectPoint > _intPoints;
418
419     void IntersectWithPlane   (const GridLine& gridLine);
420     void IntersectWithCylinder(const GridLine& gridLine);
421     void IntersectWithCone    (const GridLine& gridLine);
422     void IntersectWithSphere  (const GridLine& gridLine);
423     void IntersectWithTorus   (const GridLine& gridLine);
424     void IntersectWithSurface (const GridLine& gridLine);
425
426     bool UVIsOnFace() const;
427     void addIntPoint(const bool toClassify=true);
428     bool isParamOnLineOK( const double linLength )
429     {
430       return -_tol < _w && _w < linLength + _tol;
431     }
432     FaceLineIntersector():_surfaceInt(0) {}
433     ~FaceLineIntersector() { if (_surfaceInt ) delete _surfaceInt; _surfaceInt = 0; }
434   };
435   // --------------------------------------------------------------------------
436   /*!
437    * \brief Class representing topology of the hexahedron and creating a mesh
438    *        volume basing on analysis of hexahedron intersection with geometry
439    */
440   class Hexahedron
441   {
442     // --------------------------------------------------------------------------------
443     struct _Face;
444     struct _Link;
445     // --------------------------------------------------------------------------------
446     struct _Node //!< node either at a hexahedron corner or at intersection
447     {
448       const SMDS_MeshNode*    _node; // mesh node at hexahedron corner
449       const B_IntersectPoint* _intPoint;
450       const _Face*            _usedInFace;
451
452       _Node(const SMDS_MeshNode* n=0, const B_IntersectPoint* ip=0)
453         :_node(n), _intPoint(ip), _usedInFace(0) {} 
454       const SMDS_MeshNode*    Node() const
455       { return ( _intPoint && _intPoint->_node ) ? _intPoint->_node : _node; }
456       const E_IntersectPoint* EdgeIntPnt() const
457       { return static_cast< const E_IntersectPoint* >( _intPoint ); }
458       bool IsUsedInFace( const _Face* polygon = 0 )
459       {
460         return polygon ? ( _usedInFace == polygon ) : bool( _usedInFace );
461       }
462       void Add( const E_IntersectPoint* ip )
463       {
464         if ( !_intPoint ) {
465           _intPoint = ip;
466         }
467         else if ( !_intPoint->_node ) {
468           ip->Add( _intPoint->_faceIDs );
469           _intPoint = ip;
470         }
471         else  {
472           _intPoint->Add( ip->_faceIDs );
473         }
474       }
475       TGeomID IsLinked( const B_IntersectPoint* other,
476                         TGeomID                 avoidFace=-1 ) const // returns id of a common face
477       {
478         return _intPoint ? _intPoint->HasCommonFace( other, avoidFace ) : 0;
479       }
480       bool IsOnFace( TGeomID faceID ) const // returns true if faceID is found
481       {
482         return _intPoint ? _intPoint->IsOnFace( faceID ) : false;
483       }
484       gp_Pnt Point() const
485       {
486         if ( const SMDS_MeshNode* n = Node() )
487           return SMESH_TNodeXYZ( n );
488         if ( const E_IntersectPoint* eip =
489              dynamic_cast< const E_IntersectPoint* >( _intPoint ))
490           return eip->_point;
491         return gp_Pnt( 1e100, 0, 0 );
492       }
493       TGeomID ShapeID() const
494       {
495         if ( const E_IntersectPoint* eip = dynamic_cast< const E_IntersectPoint* >( _intPoint ))
496           return eip->_shapeID;
497         return 0;
498       }
499     };
500     // --------------------------------------------------------------------------------
501     struct _Link // link connecting two _Node's
502     {
503       _Node* _nodes[2];
504       _Face* _faces[2]; // polygons sharing a link
505       vector< const F_IntersectPoint* > _fIntPoints; // GridLine intersections with FACEs
506       vector< _Node* >                  _fIntNodes;   // _Node's at _fIntPoints
507       vector< _Link >                   _splits;
508       _Link() { _faces[0] = 0; }
509     };
510     // --------------------------------------------------------------------------------
511     struct _OrientedLink
512     {
513       _Link* _link;
514       bool   _reverse;
515       _OrientedLink( _Link* link=0, bool reverse=false ): _link(link), _reverse(reverse) {}
516       void Reverse() { _reverse = !_reverse; }
517       int NbResultLinks() const { return _link->_splits.size(); }
518       _OrientedLink ResultLink(int i) const
519       {
520         return _OrientedLink(&_link->_splits[_reverse ? NbResultLinks()-i-1 : i],_reverse);
521       }
522       _Node* FirstNode() const { return _link->_nodes[ _reverse ]; }
523       _Node* LastNode()  const { return _link->_nodes[ !_reverse ]; }
524       operator bool() const { return _link; }
525       vector< TGeomID > GetNotUsedFace(const set<TGeomID>& usedIDs ) const // returns supporting FACEs
526       {
527         vector< TGeomID > faces;
528         const B_IntersectPoint *ip0, *ip1;
529         if (( ip0 = _link->_nodes[0]->_intPoint ) &&
530             ( ip1 = _link->_nodes[1]->_intPoint ))
531         {
532           for ( size_t i = 0; i < ip0->_faceIDs.size(); ++i )
533             if ( ip1->IsOnFace ( ip0->_faceIDs[i] ) &&
534                  !usedIDs.count( ip0->_faceIDs[i] ) )
535               faces.push_back( ip0->_faceIDs[i] );
536         }
537         return faces;
538       }
539       bool HasEdgeNodes() const
540       {
541         return ( dynamic_cast< const E_IntersectPoint* >( _link->_nodes[0]->_intPoint ) ||
542                  dynamic_cast< const E_IntersectPoint* >( _link->_nodes[1]->_intPoint ));
543       }
544       int NbFaces() const
545       {
546         return !_link->_faces[0] ? 0 : 1 + bool( _link->_faces[1] );
547       }
548       void AddFace( _Face* f )
549       {
550         if ( _link->_faces[0] )
551         {
552           _link->_faces[1] = f;
553         }
554         else
555         {
556           _link->_faces[0] = f;
557           _link->_faces[1] = 0;
558         }
559       }
560       void RemoveFace( _Face* f )
561       {
562         if ( !_link->_faces[0] ) return;
563
564         if ( _link->_faces[1] == f )
565         {
566           _link->_faces[1] = 0;
567         }
568         else if ( _link->_faces[0] == f )
569         {
570           _link->_faces[0] = 0;
571           if ( _link->_faces[1] )
572           {
573             _link->_faces[0] = _link->_faces[1];
574             _link->_faces[1] = 0;
575           }
576         }
577       }
578     };
579     // --------------------------------------------------------------------------------
580     struct _Face
581     {
582       vector< _OrientedLink > _links;       // links on GridLine's
583       vector< _Link >         _polyLinks;   // links added to close a polygonal face
584       vector< _Node* >        _eIntNodes;   // nodes at intersection with EDGEs
585       bool IsPolyLink( const _OrientedLink& ol )
586       {
587         return _polyLinks.empty() ? false :
588           ( &_polyLinks[0] <= ol._link &&  ol._link <= &_polyLinks.back() );
589       }
590       void AddPolyLink(_Node* n0, _Node* n1, _Face* faceToFindEqual=0)
591       {
592         if ( faceToFindEqual && faceToFindEqual != this ) {
593           for ( size_t iL = 0; iL < faceToFindEqual->_polyLinks.size(); ++iL )
594             if ( faceToFindEqual->_polyLinks[iL]._nodes[0] == n1 &&
595                  faceToFindEqual->_polyLinks[iL]._nodes[1] == n0 )
596             {
597               _links.push_back
598                 ( _OrientedLink( & faceToFindEqual->_polyLinks[iL], /*reverse=*/true ));
599               return;
600             }
601         }
602         _Link l;
603         l._nodes[0] = n0;
604         l._nodes[1] = n1;
605         _polyLinks.push_back( l );
606         _links.push_back( _OrientedLink( &_polyLinks.back() ));
607       }
608     };
609     // --------------------------------------------------------------------------------
610     struct _volumeDef // holder of nodes of a volume mesh element
611     {
612       vector< _Node* > _nodes;
613       vector< int >    _quantities;
614       typedef boost::shared_ptr<_volumeDef> Ptr;
615       void set( const vector< _Node* >& nodes,
616                 const vector< int >&    quant = vector< int >() )
617       { _nodes = nodes; _quantities = quant; }
618       void set( _Node** nodes, int nb )
619       { _nodes.assign( nodes, nodes + nb ); }
620     };
621
622     // topology of a hexahedron
623     int   _nodeShift[8];
624     _Node _hexNodes [8];
625     _Link _hexLinks [12];
626     _Face _hexQuads [6];
627
628     // faces resulted from hexahedron intersection
629     vector< _Face > _polygons;
630
631     // intresections with EDGEs
632     vector< const E_IntersectPoint* > _eIntPoints;
633
634     // additional nodes created at intersection points
635     vector< _Node > _intNodes;
636
637     // nodes inside the hexahedron (at VERTEXes)
638     vector< _Node* > _vIntNodes;
639
640     // computed volume elements
641     //vector< _volumeDef::Ptr > _volumeDefs;
642     _volumeDef _volumeDefs;
643
644     Grid*       _grid;
645     double      _sizeThreshold, _sideLength[3];
646     int         _nbCornerNodes, _nbFaceIntNodes, _nbBndNodes;
647     int         _origNodeInd; // index of _hexNodes[0] node within the _grid
648     size_t      _i,_j,_k;
649
650   public:
651     Hexahedron(const double sizeThreshold, Grid* grid);
652     int MakeElements(SMESH_MesherHelper&                      helper,
653                      const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap);
654     void ComputeElements();
655     void Init() { init( _i, _j, _k ); }
656
657   private:
658     Hexahedron(const Hexahedron& other );
659     void init( size_t i, size_t j, size_t k );
660     void init( size_t i );
661     void addEdges(SMESH_MesherHelper&                      helper,
662                   vector< Hexahedron* >&                   intersectedHex,
663                   const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap);
664     gp_Pnt findIntPoint( double u1, double proj1, double u2, double proj2,
665                          double proj, BRepAdaptor_Curve& curve,
666                          const gp_XYZ& axis, const gp_XYZ& origin );
667     int  getEntity( const E_IntersectPoint* ip, int* facets, int& sub );
668     bool addIntersection( const E_IntersectPoint& ip,
669                           vector< Hexahedron* >&  hexes,
670                           int ijk[], int dIJK[] );
671     bool findChain( _Node* n1, _Node* n2, _Face& quad, vector<_Node*>& chainNodes );
672     bool closePolygon( _Face* polygon, vector<_Node*>& chainNodes ) const;
673     bool findChainOnEdge( const vector< _OrientedLink >& splits,
674                           const _OrientedLink&           prevSplit,
675                           const _OrientedLink&           avoidSplit,
676                           size_t &                       iS,
677                           _Face&                         quad,
678                           vector<_Node*>&                chn);
679     int  addElements(SMESH_MesherHelper& helper);
680     bool isOutPoint( _Link& link, int iP, SMESH_MesherHelper& helper ) const;
681     void sortVertexNodes(vector<_Node*>& nodes, _Node* curNode, TGeomID face);
682     bool isInHole() const;
683     bool checkPolyhedronSize() const;
684     bool addHexa ();
685     bool addTetra();
686     bool addPenta();
687     bool addPyra ();
688     bool debugDumpLink( _Link* link );
689     _Node* findEqualNode( vector< _Node* >&       nodes,
690                           const E_IntersectPoint* ip,
691                           const double            tol2 )
692     {
693       for ( size_t i = 0; i < nodes.size(); ++i )
694         if ( nodes[i]->EdgeIntPnt() == ip ||
695              nodes[i]->Point().SquareDistance( ip->_point ) <= tol2 )
696           return nodes[i];
697       return 0;
698     }
699     bool isImplementEdges() const { return !_grid->_edgeIntP.empty(); }
700     bool isOutParam(const double uvw[3]) const;
701   };
702
703 #ifdef WITH_TBB
704   // --------------------------------------------------------------------------
705   /*!
706    * \brief Hexahedron computing volumes in one thread
707    */
708   struct ParallelHexahedron
709   {
710     vector< Hexahedron* >& _hexVec;
711     ParallelHexahedron( vector< Hexahedron* >& hv ): _hexVec(hv) {}
712     void operator() ( const tbb::blocked_range<size_t>& r ) const
713     {
714       for ( size_t i = r.begin(); i != r.end(); ++i )
715         if ( Hexahedron* hex = _hexVec[ i ] )
716           hex->ComputeElements();
717     }
718   };
719   // --------------------------------------------------------------------------
720   /*!
721    * \brief Structure intersecting certain nb of faces with GridLine's in one thread
722    */
723   struct ParallelIntersector
724   {
725     vector< FaceGridIntersector >& _faceVec;
726     ParallelIntersector( vector< FaceGridIntersector >& faceVec): _faceVec(faceVec){}
727     void operator() ( const tbb::blocked_range<size_t>& r ) const
728     {
729       for ( size_t i = r.begin(); i != r.end(); ++i )
730         _faceVec[i].Intersect();
731     }
732   };
733 #endif
734
735   //=============================================================================
736   // Implementation of internal utils
737   //=============================================================================
738   /*!
739    * \brief adjust \a i to have \a val between values[i] and values[i+1]
740    */
741   inline void locateValue( int & i, double val, const vector<double>& values,
742                            int& di, double tol )
743   {
744     //val += values[0]; // input \a val is measured from 0.
745     if ( i > values.size()-2 )
746       i = values.size()-2;
747     else
748       while ( i+2 < values.size() && val > values[ i+1 ])
749         ++i;
750     while ( i > 0 && val < values[ i ])
751       --i;
752
753     if ( i > 0 && val - values[ i ] < tol )
754       di = -1;
755     else if ( i+2 < values.size() && values[ i+1 ] - val < tol )
756       di = 1;
757     else
758       di = 0;
759   }
760   //=============================================================================
761   /*
762    * Remove coincident intersection points
763    */
764   void GridLine::RemoveExcessIntPoints( const double tol )
765   {
766     if ( _intPoints.size() < 2 ) return;
767
768     set< Transition > tranSet;
769     multiset< F_IntersectPoint >::iterator ip1, ip2 = _intPoints.begin();
770     while ( ip2 != _intPoints.end() )
771     {
772       tranSet.clear();
773       ip1 = ip2++;
774       while ( ip2 != _intPoints.end() && ip2->_paramOnLine - ip1->_paramOnLine <= tol )
775       {
776         tranSet.insert( ip1->_transition );
777         tranSet.insert( ip2->_transition );
778         ip2->Add( ip1->_faceIDs );
779         _intPoints.erase( ip1 );
780         ip1 = ip2++;
781       }
782       if ( tranSet.size() > 1 ) // points with different transition coincide
783       {
784         bool isIN  = tranSet.count( Trans_IN );
785         bool isOUT = tranSet.count( Trans_OUT );
786         if ( isIN && isOUT )
787           (*ip1)._transition = Trans_TANGENT;
788         else
789           (*ip1)._transition = isIN ? Trans_IN : Trans_OUT;
790       }
791     }
792   }
793   //================================================================================
794   /*
795    * Return "is OUT" state for nodes before the given intersection point
796    */
797   bool GridLine::GetIsOutBefore( multiset< F_IntersectPoint >::iterator ip, bool prevIsOut )
798   {
799     if ( ip->_transition == Trans_IN )
800       return true;
801     if ( ip->_transition == Trans_OUT )
802       return false;
803     if ( ip->_transition == Trans_APEX )
804     {
805       // singularity point (apex of a cone)
806       if ( _intPoints.size() == 1 || ip == _intPoints.begin() )
807         return true;
808       multiset< F_IntersectPoint >::iterator ipBef = ip, ipAft = ++ip;
809       if ( ipAft == _intPoints.end() )
810         return false;
811       --ipBef;
812       if ( ipBef->_transition != ipAft->_transition )
813         return ( ipBef->_transition == Trans_OUT );
814       return ( ipBef->_transition != Trans_OUT );
815     }
816     // _transition == Trans_TANGENT
817     return !prevIsOut;
818   }
819   //================================================================================
820   /*
821    * Adds face IDs
822    */
823   void B_IntersectPoint::Add( const vector< TGeomID >& fIDs,
824                               const SMDS_MeshNode*     n) const
825   {
826     if ( _faceIDs.empty() )
827       _faceIDs = fIDs;
828     else
829       for ( size_t i = 0; i < fIDs.size(); ++i )
830       {
831         vector< TGeomID >::iterator it =
832           std::find( _faceIDs.begin(), _faceIDs.end(), fIDs[i] );
833         if ( it == _faceIDs.end() )
834           _faceIDs.push_back( fIDs[i] );
835       }
836     if ( !_node )
837       _node = n;
838   }
839   //================================================================================
840   /*
841    * Returns index of a common face if any, else zero
842    */
843   int B_IntersectPoint::HasCommonFace( const B_IntersectPoint * other, int avoidFace ) const
844   {
845     if ( other )
846       for ( size_t i = 0; i < other->_faceIDs.size(); ++i )
847         if ( avoidFace != other->_faceIDs[i] &&
848              IsOnFace   ( other->_faceIDs[i] ))
849           return other->_faceIDs[i];
850     return 0;
851   }
852   //================================================================================
853   /*
854    * Returns \c true if \a faceID in in this->_faceIDs
855    */
856   bool B_IntersectPoint::IsOnFace( int faceID ) const // returns true if faceID is found
857   {
858     vector< TGeomID >::const_iterator it =
859       std::find( _faceIDs.begin(), _faceIDs.end(), faceID );
860     return ( it != _faceIDs.end() );
861   }
862   //================================================================================
863   /*
864    * Return an iterator on GridLine's in a given direction
865    */
866   LineIndexer Grid::GetLineIndexer(size_t iDir) const
867   {
868     const size_t indices[] = { 1,2,0, 0,2,1, 0,1,2 };
869     const string s      [] = { "X", "Y", "Z" };
870     LineIndexer li( _coords[0].size(),  _coords[1].size(),    _coords[2].size(),
871                     indices[iDir*3],    indices[iDir*3+1],    indices[iDir*3+2],
872                     s[indices[iDir*3]], s[indices[iDir*3+1]], s[indices[iDir*3+2]]);
873     return li;
874   }
875   //=============================================================================
876   /*
877    * Creates GridLine's of the grid
878    */
879   void Grid::SetCoordinates(const vector<double>& xCoords,
880                             const vector<double>& yCoords,
881                             const vector<double>& zCoords,
882                             const double*         axesDirs,
883                             const Bnd_Box&        shapeBox)
884   {
885     _coords[0] = xCoords;
886     _coords[1] = yCoords;
887     _coords[2] = zCoords;
888
889     _axes[0].SetCoord( axesDirs[0],
890                        axesDirs[1],
891                        axesDirs[2]);
892     _axes[1].SetCoord( axesDirs[3],
893                        axesDirs[4],
894                        axesDirs[5]);
895     _axes[2].SetCoord( axesDirs[6],
896                        axesDirs[7],
897                        axesDirs[8]);
898     _axes[0].Normalize();
899     _axes[1].Normalize();
900     _axes[2].Normalize();
901
902     _invB.SetCols( _axes[0], _axes[1], _axes[2] );
903     _invB.Invert();
904
905     // compute tolerance
906     _minCellSize = Precision::Infinite();
907     for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
908     {
909       for ( size_t i = 1; i < _coords[ iDir ].size(); ++i )
910       {
911         double cellLen = _coords[ iDir ][ i ] - _coords[ iDir ][ i-1 ];
912         if ( cellLen < _minCellSize )
913           _minCellSize = cellLen;
914       }
915     }
916     if ( _minCellSize < Precision::Confusion() )
917       throw SMESH_ComputeError (COMPERR_ALGO_FAILED,
918                                 SMESH_Comment("Too small cell size: ") << _minCellSize );
919     _tol = _minCellSize / 1000.;
920
921     // attune grid extremities to shape bounding box
922
923     double sP[6]; // aXmin, aYmin, aZmin, aXmax, aYmax, aZmax
924     shapeBox.Get(sP[0],sP[1],sP[2],sP[3],sP[4],sP[5]);
925     double* cP[6] = { &_coords[0].front(), &_coords[1].front(), &_coords[2].front(),
926                       &_coords[0].back(),  &_coords[1].back(),  &_coords[2].back() };
927     for ( int i = 0; i < 6; ++i )
928       if ( fabs( sP[i] - *cP[i] ) < _tol )
929         *cP[i] = sP[i];// + _tol/1000. * ( i < 3 ? +1 : -1 );
930
931     for ( int iDir = 0; iDir < 3; ++iDir )
932     {
933       if ( _coords[iDir][0] - sP[iDir] > _tol )
934       {
935         _minCellSize = Min( _minCellSize, _coords[iDir][0] - sP[iDir] );
936         _coords[iDir].insert( _coords[iDir].begin(), sP[iDir] + _tol/1000.);
937       }
938       if ( sP[iDir+3] - _coords[iDir].back() > _tol  )
939       {
940         _minCellSize = Min( _minCellSize, sP[iDir+3] - _coords[iDir].back() );
941         _coords[iDir].push_back( sP[iDir+3] - _tol/1000.);
942       }
943     }
944     _tol = _minCellSize / 1000.;
945
946     _origin = ( _coords[0][0] * _axes[0] +
947                 _coords[1][0] * _axes[1] +
948                 _coords[2][0] * _axes[2] );
949
950     // create lines
951     for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
952     {
953       LineIndexer li = GetLineIndexer( iDir );
954       _lines[iDir].resize( li.NbLines() );
955       double len = _coords[ iDir ].back() - _coords[iDir].front();
956       for ( ; li.More(); ++li )
957       {
958         GridLine& gl = _lines[iDir][ li.LineIndex() ];
959         gl._line.SetLocation( _coords[0][li.I()] * _axes[0] +
960                               _coords[1][li.J()] * _axes[1] +
961                               _coords[2][li.K()] * _axes[2] );
962         gl._line.SetDirection( _axes[ iDir ]);
963         gl._length = len;
964       }
965     }
966   }
967   //================================================================================
968   /*
969    * Computes coordinates of a point in the grid CS
970    */
971   void Grid::ComputeUVW(const gp_XYZ& P, double UVW[3])
972   {
973     gp_XYZ p = P * _invB;
974     p.Coord( UVW[0], UVW[1], UVW[2] );
975   }
976   //================================================================================
977   /*
978    * Creates all nodes
979    */
980   void Grid::ComputeNodes(SMESH_MesherHelper& helper)
981   {
982     // state of each node of the grid relative to the geometry
983     const size_t nbGridNodes = _coords[0].size() * _coords[1].size() * _coords[2].size();
984     vector< bool > isNodeOut( nbGridNodes, false );
985     _nodes.resize( nbGridNodes, 0 );
986     _gridIntP.resize( nbGridNodes, NULL );
987
988     for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
989     {
990       LineIndexer li = GetLineIndexer( iDir );
991
992       // find out a shift of node index while walking along a GridLine in this direction
993       li.SetIndexOnLine( 0 );
994       size_t nIndex0 = NodeIndex( li.I(), li.J(), li.K() );
995       li.SetIndexOnLine( 1 );
996       const size_t nShift = NodeIndex( li.I(), li.J(), li.K() ) - nIndex0;
997       
998       const vector<double> & coords = _coords[ iDir ];
999       for ( ; li.More(); ++li ) // loop on lines in iDir
1000       {
1001         li.SetIndexOnLine( 0 );
1002         nIndex0 = NodeIndex( li.I(), li.J(), li.K() );
1003
1004         GridLine& line = _lines[ iDir ][ li.LineIndex() ];
1005         const gp_XYZ lineLoc = line._line.Location().XYZ();
1006         const gp_XYZ lineDir = line._line.Direction().XYZ();
1007         line.RemoveExcessIntPoints( _tol );
1008         multiset< F_IntersectPoint >& intPnts = line._intPoints;
1009         multiset< F_IntersectPoint >::iterator ip = intPnts.begin();
1010
1011         bool isOut = true;
1012         const double* nodeCoord = & coords[0];
1013         const double* coord0    = nodeCoord;
1014         const double* coordEnd  = coord0 + coords.size();
1015         double nodeParam = 0;
1016         for ( ; ip != intPnts.end(); ++ip )
1017         {
1018           // set OUT state or just skip IN nodes before ip
1019           if ( nodeParam < ip->_paramOnLine - _tol )
1020           {
1021             isOut = line.GetIsOutBefore( ip, isOut );
1022
1023             while ( nodeParam < ip->_paramOnLine - _tol )
1024             {
1025               if ( isOut )
1026                 isNodeOut[ nIndex0 + nShift * ( nodeCoord-coord0 ) ] = isOut;
1027               if ( ++nodeCoord <  coordEnd )
1028                 nodeParam = *nodeCoord - *coord0;
1029               else
1030                 break;
1031             }
1032             if ( nodeCoord == coordEnd ) break;
1033           }
1034           // create a mesh node on a GridLine at ip if it does not coincide with a grid node
1035           if ( nodeParam > ip->_paramOnLine + _tol )
1036           {
1037             // li.SetIndexOnLine( 0 );
1038             // double xyz[3] = { _coords[0][ li.I() ], _coords[1][ li.J() ], _coords[2][ li.K() ]};
1039             // xyz[ li._iConst ] += ip->_paramOnLine;
1040             gp_XYZ xyz = lineLoc + ip->_paramOnLine * lineDir;
1041             ip->_node = helper.AddNode( xyz.X(), xyz.Y(), xyz.Z() );
1042             ip->_indexOnLine = nodeCoord-coord0-1;
1043           }
1044           // create a mesh node at ip concident with a grid node
1045           else
1046           {
1047             int nodeIndex = nIndex0 + nShift * ( nodeCoord-coord0 );
1048             if ( !_nodes[ nodeIndex ] )
1049             {
1050               //li.SetIndexOnLine( nodeCoord-coord0 );
1051               //double xyz[3] = { _coords[0][ li.I() ], _coords[1][ li.J() ], _coords[2][ li.K() ]};
1052               gp_XYZ xyz = lineLoc + nodeParam * lineDir;
1053               _nodes   [ nodeIndex ] = helper.AddNode( xyz.X(), xyz.Y(), xyz.Z() );
1054               _gridIntP[ nodeIndex ] = & * ip;
1055             }
1056             if ( _gridIntP[ nodeIndex ] )
1057               _gridIntP[ nodeIndex ]->Add( ip->_faceIDs );
1058             else
1059               _gridIntP[ nodeIndex ] = & * ip;
1060             // ip->_node        = _nodes[ nodeIndex ]; -- to differ from ip on links
1061             ip->_indexOnLine = nodeCoord-coord0;
1062             if ( ++nodeCoord < coordEnd )
1063               nodeParam = *nodeCoord - *coord0;
1064           }
1065         }
1066         // set OUT state to nodes after the last ip
1067         for ( ; nodeCoord < coordEnd; ++nodeCoord )
1068           isNodeOut[ nIndex0 + nShift * ( nodeCoord-coord0 ) ] = true;
1069       }
1070     }
1071
1072     // Create mesh nodes at !OUT nodes of the grid
1073
1074     for ( size_t z = 0; z < _coords[2].size(); ++z )
1075       for ( size_t y = 0; y < _coords[1].size(); ++y )
1076         for ( size_t x = 0; x < _coords[0].size(); ++x )
1077         {
1078           size_t nodeIndex = NodeIndex( x, y, z );
1079           if ( !isNodeOut[ nodeIndex ] && !_nodes[ nodeIndex] )
1080           {
1081             //_nodes[ nodeIndex ] = helper.AddNode( _coords[0][x], _coords[1][y], _coords[2][z] );
1082             gp_XYZ xyz = ( _coords[0][x] * _axes[0] +
1083                            _coords[1][y] * _axes[1] +
1084                            _coords[2][z] * _axes[2] );
1085             _nodes[ nodeIndex ] = helper.AddNode( xyz.X(), xyz.Y(), xyz.Z() );
1086           }
1087         }
1088
1089 #ifdef _MY_DEBUG_
1090     // check validity of transitions
1091     const char* trName[] = { "TANGENT", "IN", "OUT", "APEX" };
1092     for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
1093     {
1094       LineIndexer li = GetLineIndexer( iDir );
1095       for ( ; li.More(); ++li )
1096       {
1097         multiset< F_IntersectPoint >& intPnts = _lines[ iDir ][ li.LineIndex() ]._intPoints;
1098         if ( intPnts.empty() ) continue;
1099         if ( intPnts.size() == 1 )
1100         {
1101           if ( intPnts.begin()->_transition != Trans_TANGENT &&
1102                intPnts.begin()->_transition != Trans_APEX )
1103           throw SMESH_ComputeError (COMPERR_ALGO_FAILED,
1104                                     SMESH_Comment("Wrong SOLE transition of GridLine (")
1105                                     << li._curInd[li._iVar1] << ", " << li._curInd[li._iVar2]
1106                                     << ") along " << li._nameConst
1107                                     << ": " << trName[ intPnts.begin()->_transition] );
1108         }
1109         else
1110         {
1111           if ( intPnts.begin()->_transition == Trans_OUT )
1112             throw SMESH_ComputeError (COMPERR_ALGO_FAILED,
1113                                       SMESH_Comment("Wrong START transition of GridLine (")
1114                                       << li._curInd[li._iVar1] << ", " << li._curInd[li._iVar2]
1115                                       << ") along " << li._nameConst
1116                                       << ": " << trName[ intPnts.begin()->_transition ]);
1117           if ( intPnts.rbegin()->_transition == Trans_IN )
1118             throw SMESH_ComputeError (COMPERR_ALGO_FAILED,
1119                                       SMESH_Comment("Wrong END transition of GridLine (")
1120                                       << li._curInd[li._iVar1] << ", " << li._curInd[li._iVar2]
1121                                       << ") along " << li._nameConst
1122                                     << ": " << trName[ intPnts.rbegin()->_transition ]);
1123         }
1124       }
1125     }
1126 #endif
1127   }
1128
1129   //=============================================================================
1130   /*
1131    * Intersects TopoDS_Face with all GridLine's
1132    */
1133   void FaceGridIntersector::Intersect()
1134   {
1135     FaceLineIntersector intersector;
1136     intersector._surfaceInt = GetCurveFaceIntersector();
1137     intersector._tol        = _grid->_tol;
1138     intersector._transOut   = _face.Orientation() == TopAbs_REVERSED ? Trans_IN : Trans_OUT;
1139     intersector._transIn    = _face.Orientation() == TopAbs_REVERSED ? Trans_OUT : Trans_IN;
1140
1141     typedef void (FaceLineIntersector::* PIntFun )(const GridLine& gridLine);
1142     PIntFun interFunction;
1143
1144     bool isDirect = true;
1145     BRepAdaptor_Surface surf( _face );
1146     switch ( surf.GetType() ) {
1147     case GeomAbs_Plane:
1148       intersector._plane = surf.Plane();
1149       interFunction = &FaceLineIntersector::IntersectWithPlane;
1150       isDirect = intersector._plane.Direct();
1151       break;
1152     case GeomAbs_Cylinder:
1153       intersector._cylinder = surf.Cylinder();
1154       interFunction = &FaceLineIntersector::IntersectWithCylinder;
1155       isDirect = intersector._cylinder.Direct();
1156       break;
1157     case GeomAbs_Cone:
1158       intersector._cone = surf.Cone();
1159       interFunction = &FaceLineIntersector::IntersectWithCone;
1160       //isDirect = intersector._cone.Direct();
1161       break;
1162     case GeomAbs_Sphere:
1163       intersector._sphere = surf.Sphere();
1164       interFunction = &FaceLineIntersector::IntersectWithSphere;
1165       isDirect = intersector._sphere.Direct();
1166       break;
1167     case GeomAbs_Torus:
1168       intersector._torus = surf.Torus();
1169       interFunction = &FaceLineIntersector::IntersectWithTorus;
1170       //isDirect = intersector._torus.Direct();
1171       break;
1172     default:
1173       interFunction = &FaceLineIntersector::IntersectWithSurface;
1174     }
1175     if ( !isDirect )
1176       std::swap( intersector._transOut, intersector._transIn );
1177
1178     _intersections.clear();
1179     for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
1180     {
1181       if ( surf.GetType() == GeomAbs_Plane )
1182       {
1183         // check if all lines in this direction are parallel to a plane
1184         if ( intersector._plane.Axis().IsNormal( _grid->_lines[iDir][0]._line.Position(),
1185                                                  Precision::Angular()))
1186           continue;
1187         // find out a transition, that is the same for all lines of a direction
1188         gp_Dir plnNorm = intersector._plane.Axis().Direction();
1189         gp_Dir lineDir = _grid->_lines[iDir][0]._line.Direction();
1190         intersector._transition =
1191           ( plnNorm * lineDir < 0 ) ? intersector._transIn : intersector._transOut;
1192       }
1193       if ( surf.GetType() == GeomAbs_Cylinder )
1194       {
1195         // check if all lines in this direction are parallel to a cylinder
1196         if ( intersector._cylinder.Axis().IsParallel( _grid->_lines[iDir][0]._line.Position(),
1197                                                       Precision::Angular()))
1198           continue;
1199       }
1200
1201       // intersect the grid lines with the face
1202       for ( size_t iL = 0; iL < _grid->_lines[iDir].size(); ++iL )
1203       {
1204         GridLine& gridLine = _grid->_lines[iDir][iL];
1205         if ( _bndBox.IsOut( gridLine._line )) continue;
1206
1207         intersector._intPoints.clear();
1208         (intersector.*interFunction)( gridLine ); // <- intersection with gridLine
1209         for ( size_t i = 0; i < intersector._intPoints.size(); ++i )
1210           _intersections.push_back( make_pair( &gridLine, intersector._intPoints[i] ));
1211       }
1212     }
1213   }
1214   //================================================================================
1215   /*
1216    * Return true if (_u,_v) is on the face
1217    */
1218   bool FaceLineIntersector::UVIsOnFace() const
1219   {
1220     TopAbs_State state = _surfaceInt->ClassifyUVPoint(gp_Pnt2d( _u,_v ));
1221     return ( state == TopAbs_IN || state == TopAbs_ON );
1222   }
1223   //================================================================================
1224   /*
1225    * Store an intersection if it is IN or ON the face
1226    */
1227   void FaceLineIntersector::addIntPoint(const bool toClassify)
1228   {
1229     if ( !toClassify || UVIsOnFace() )
1230     {
1231       F_IntersectPoint p;
1232       p._paramOnLine = _w;
1233       p._transition  = _transition;
1234       _intPoints.push_back( p );
1235     }
1236   }
1237   //================================================================================
1238   /*
1239    * Intersect a line with a plane
1240    */
1241   void FaceLineIntersector::IntersectWithPlane(const GridLine& gridLine)
1242   {
1243     IntAna_IntConicQuad linPlane( gridLine._line, _plane, Precision::Angular());
1244     _w = linPlane.ParamOnConic(1);
1245     if ( isParamOnLineOK( gridLine._length ))
1246     {
1247       ElSLib::Parameters(_plane, linPlane.Point(1) ,_u,_v);
1248       addIntPoint();
1249     }
1250   }
1251   //================================================================================
1252   /*
1253    * Intersect a line with a cylinder
1254    */
1255   void FaceLineIntersector::IntersectWithCylinder(const GridLine& gridLine)
1256   {
1257     IntAna_IntConicQuad linCylinder( gridLine._line, _cylinder );
1258     if ( linCylinder.IsDone() && linCylinder.NbPoints() > 0 )
1259     {
1260       _w = linCylinder.ParamOnConic(1);
1261       if ( linCylinder.NbPoints() == 1 )
1262         _transition = Trans_TANGENT;
1263       else
1264         _transition = _w < linCylinder.ParamOnConic(2) ? _transIn : _transOut;
1265       if ( isParamOnLineOK( gridLine._length ))
1266       {
1267         ElSLib::Parameters(_cylinder, linCylinder.Point(1) ,_u,_v);
1268         addIntPoint();
1269       }
1270       if ( linCylinder.NbPoints() > 1 )
1271       {
1272         _w = linCylinder.ParamOnConic(2);
1273         if ( isParamOnLineOK( gridLine._length ))
1274         {
1275           ElSLib::Parameters(_cylinder, linCylinder.Point(2) ,_u,_v);
1276           _transition = ( _transition == Trans_OUT ) ? Trans_IN : Trans_OUT;
1277           addIntPoint();
1278         }
1279       }
1280     }
1281   }
1282   //================================================================================
1283   /*
1284    * Intersect a line with a cone
1285    */
1286   void FaceLineIntersector::IntersectWithCone (const GridLine& gridLine)
1287   {
1288     IntAna_IntConicQuad linCone(gridLine._line,_cone);
1289     if ( !linCone.IsDone() ) return;
1290     gp_Pnt P;
1291     gp_Vec du, dv, norm;
1292     for ( int i = 1; i <= linCone.NbPoints(); ++i )
1293     {
1294       _w = linCone.ParamOnConic( i );
1295       if ( !isParamOnLineOK( gridLine._length )) continue;
1296       ElSLib::Parameters(_cone, linCone.Point(i) ,_u,_v);
1297       if ( UVIsOnFace() )
1298       {
1299         ElSLib::D1( _u, _v, _cone, P, du, dv );
1300         norm = du ^ dv;
1301         double normSize2 = norm.SquareMagnitude();
1302         if ( normSize2 > Precision::Angular() * Precision::Angular() )
1303         {
1304           double cos = norm.XYZ() * gridLine._line.Direction().XYZ();
1305           cos /= sqrt( normSize2 );
1306           if ( cos < -Precision::Angular() )
1307             _transition = _transIn;
1308           else if ( cos > Precision::Angular() )
1309             _transition = _transOut;
1310           else
1311             _transition = Trans_TANGENT;
1312         }
1313         else
1314         {
1315           _transition = Trans_APEX;
1316         }
1317         addIntPoint( /*toClassify=*/false);
1318       }
1319     }
1320   }
1321   //================================================================================
1322   /*
1323    * Intersect a line with a sphere
1324    */
1325   void FaceLineIntersector::IntersectWithSphere  (const GridLine& gridLine)
1326   {
1327     IntAna_IntConicQuad linSphere(gridLine._line,_sphere);
1328     if ( linSphere.IsDone() && linSphere.NbPoints() > 0 )
1329     {
1330       _w = linSphere.ParamOnConic(1);
1331       if ( linSphere.NbPoints() == 1 )
1332         _transition = Trans_TANGENT;
1333       else
1334         _transition = _w < linSphere.ParamOnConic(2) ? _transIn : _transOut;
1335       if ( isParamOnLineOK( gridLine._length ))
1336       {
1337         ElSLib::Parameters(_sphere, linSphere.Point(1) ,_u,_v);
1338         addIntPoint();
1339       }
1340       if ( linSphere.NbPoints() > 1 )
1341       {
1342         _w = linSphere.ParamOnConic(2);
1343         if ( isParamOnLineOK( gridLine._length ))
1344         {
1345           ElSLib::Parameters(_sphere, linSphere.Point(2) ,_u,_v);
1346           _transition = ( _transition == Trans_OUT ) ? Trans_IN : Trans_OUT;
1347           addIntPoint();
1348         }
1349       }
1350     }
1351   }
1352   //================================================================================
1353   /*
1354    * Intersect a line with a torus
1355    */
1356   void FaceLineIntersector::IntersectWithTorus   (const GridLine& gridLine)
1357   {
1358     IntAna_IntLinTorus linTorus(gridLine._line,_torus);
1359     if ( !linTorus.IsDone()) return;
1360     gp_Pnt P;
1361     gp_Vec du, dv, norm;
1362     for ( int i = 1; i <= linTorus.NbPoints(); ++i )
1363     {
1364       _w = linTorus.ParamOnLine( i );
1365       if ( !isParamOnLineOK( gridLine._length )) continue;
1366       linTorus.ParamOnTorus( i, _u,_v );
1367       if ( UVIsOnFace() )
1368       {
1369         ElSLib::D1( _u, _v, _torus, P, du, dv );
1370         norm = du ^ dv;
1371         double normSize = norm.Magnitude();
1372         double cos = norm.XYZ() * gridLine._line.Direction().XYZ();
1373         cos /= normSize;
1374         if ( cos < -Precision::Angular() )
1375           _transition = _transIn;
1376         else if ( cos > Precision::Angular() )
1377           _transition = _transOut;
1378         else
1379           _transition = Trans_TANGENT;
1380         addIntPoint( /*toClassify=*/false);
1381       }
1382     }
1383   }
1384   //================================================================================
1385   /*
1386    * Intersect a line with a non-analytical surface
1387    */
1388   void FaceLineIntersector::IntersectWithSurface (const GridLine& gridLine)
1389   {
1390     _surfaceInt->Perform( gridLine._line, 0.0, gridLine._length );
1391     if ( !_surfaceInt->IsDone() ) return;
1392     for ( int i = 1; i <= _surfaceInt->NbPnt(); ++i )
1393     {
1394       _transition = Transition( _surfaceInt->Transition( i ) );
1395       _w = _surfaceInt->WParameter( i );
1396       addIntPoint(/*toClassify=*/false);
1397     }
1398   }
1399   //================================================================================
1400   /*
1401    * check if its face can be safely intersected in a thread
1402    */
1403   bool FaceGridIntersector::IsThreadSafe(set< const Standard_Transient* >& noSafeTShapes) const
1404   {
1405     bool isSafe = true;
1406
1407     // check surface
1408     TopLoc_Location loc;
1409     Handle(Geom_Surface) surf = BRep_Tool::Surface( _face, loc );
1410     Handle(Geom_RectangularTrimmedSurface) ts =
1411       Handle(Geom_RectangularTrimmedSurface)::DownCast( surf );
1412     while( !ts.IsNull() ) {
1413       surf = ts->BasisSurface();
1414       ts = Handle(Geom_RectangularTrimmedSurface)::DownCast(surf);
1415     }
1416     if ( surf->IsKind( STANDARD_TYPE(Geom_BSplineSurface )) ||
1417          surf->IsKind( STANDARD_TYPE(Geom_BezierSurface )))
1418       if ( !noSafeTShapes.insert((const Standard_Transient*) _face.TShape() ).second )
1419         isSafe = false;
1420
1421     double f, l;
1422     TopExp_Explorer exp( _face, TopAbs_EDGE );
1423     for ( ; exp.More(); exp.Next() )
1424     {
1425       bool edgeIsSafe = true;
1426       const TopoDS_Edge& e = TopoDS::Edge( exp.Current() );
1427       // check 3d curve
1428       {
1429         Handle(Geom_Curve) c = BRep_Tool::Curve( e, loc, f, l);
1430         if ( !c.IsNull() )
1431         {
1432           Handle(Geom_TrimmedCurve) tc = Handle(Geom_TrimmedCurve)::DownCast(c);
1433           while( !tc.IsNull() ) {
1434             c = tc->BasisCurve();
1435             tc = Handle(Geom_TrimmedCurve)::DownCast(c);
1436           }
1437           if ( c->IsKind( STANDARD_TYPE(Geom_BSplineCurve )) ||
1438                c->IsKind( STANDARD_TYPE(Geom_BezierCurve )))
1439             edgeIsSafe = false;
1440         }
1441       }
1442       // check 2d curve
1443       if ( edgeIsSafe )
1444       {
1445         Handle(Geom2d_Curve) c2 = BRep_Tool::CurveOnSurface( e, surf, loc, f, l);
1446         if ( !c2.IsNull() )
1447         {
1448           Handle(Geom2d_TrimmedCurve) tc = Handle(Geom2d_TrimmedCurve)::DownCast(c2);
1449           while( !tc.IsNull() ) {
1450             c2 = tc->BasisCurve();
1451             tc = Handle(Geom2d_TrimmedCurve)::DownCast(c2);
1452           }
1453           if ( c2->IsKind( STANDARD_TYPE(Geom2d_BSplineCurve )) ||
1454                c2->IsKind( STANDARD_TYPE(Geom2d_BezierCurve )))
1455             edgeIsSafe = false;
1456         }
1457       }
1458       if ( !edgeIsSafe && !noSafeTShapes.insert((const Standard_Transient*) e.TShape() ).second )
1459         isSafe = false;
1460     }
1461     return isSafe;
1462   }
1463   //================================================================================
1464   /*!
1465    * \brief Creates topology of the hexahedron
1466    */
1467   Hexahedron::Hexahedron(const double sizeThreshold, Grid* grid)
1468     : _grid( grid ), _sizeThreshold( sizeThreshold ), _nbFaceIntNodes(0)
1469   {
1470     _polygons.reserve(100); // to avoid reallocation;
1471
1472     //set nodes shift within grid->_nodes from the node 000 
1473     size_t dx = _grid->NodeIndexDX();
1474     size_t dy = _grid->NodeIndexDY();
1475     size_t dz = _grid->NodeIndexDZ();
1476     size_t i000 = 0;
1477     size_t i100 = i000 + dx;
1478     size_t i010 = i000 + dy;
1479     size_t i110 = i010 + dx;
1480     size_t i001 = i000 + dz;
1481     size_t i101 = i100 + dz;
1482     size_t i011 = i010 + dz;
1483     size_t i111 = i110 + dz;
1484     _nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V000 )] = i000;
1485     _nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V100 )] = i100;
1486     _nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V010 )] = i010;
1487     _nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V110 )] = i110;
1488     _nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V001 )] = i001;
1489     _nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V101 )] = i101;
1490     _nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V011 )] = i011;
1491     _nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V111 )] = i111;
1492
1493     vector< int > idVec;
1494     // set nodes to links
1495     for ( int linkID = SMESH_Block::ID_Ex00; linkID <= SMESH_Block::ID_E11z; ++linkID )
1496     {
1497       SMESH_Block::GetEdgeVertexIDs( linkID, idVec );
1498       _Link& link = _hexLinks[ SMESH_Block::ShapeIndex( linkID )];
1499       link._nodes[0] = &_hexNodes[ SMESH_Block::ShapeIndex( idVec[0] )];
1500       link._nodes[1] = &_hexNodes[ SMESH_Block::ShapeIndex( idVec[1] )];
1501     }
1502
1503     // set links to faces
1504     int interlace[4] = { 0, 3, 1, 2 }; // to walk by links around a face: { u0, 1v, u1, 0v }
1505     for ( int faceID = SMESH_Block::ID_Fxy0; faceID <= SMESH_Block::ID_F1yz; ++faceID )
1506     {
1507       SMESH_Block::GetFaceEdgesIDs( faceID, idVec );
1508       _Face& quad = _hexQuads[ SMESH_Block::ShapeIndex( faceID )];
1509       bool revFace = ( faceID == SMESH_Block::ID_Fxy0 ||
1510                        faceID == SMESH_Block::ID_Fx1z ||
1511                        faceID == SMESH_Block::ID_F0yz );
1512       quad._links.resize(4);
1513       vector<_OrientedLink>::iterator         frwLinkIt = quad._links.begin();
1514       vector<_OrientedLink>::reverse_iterator revLinkIt = quad._links.rbegin();
1515       for ( int i = 0; i < 4; ++i )
1516       {
1517         bool revLink = revFace;
1518         if ( i > 1 ) // reverse links u1 and v0
1519           revLink = !revLink;
1520         _OrientedLink& link = revFace ? *revLinkIt++ : *frwLinkIt++;
1521         link = _OrientedLink( & _hexLinks[ SMESH_Block::ShapeIndex( idVec[interlace[i]] )],
1522                               revLink );
1523       }
1524     }
1525   }
1526   //================================================================================
1527   /*!
1528    * \brief Copy constructor
1529    */
1530   Hexahedron::Hexahedron( const Hexahedron& other )
1531     :_grid( other._grid ), _sizeThreshold( other._sizeThreshold ), _nbFaceIntNodes(0)
1532   {
1533     _polygons.reserve(100); // to avoid reallocation;
1534
1535     for ( int i = 0; i < 8; ++i )
1536       _nodeShift[i] = other._nodeShift[i];
1537
1538     for ( int i = 0; i < 12; ++i )
1539     {
1540       const _Link& srcLink = other._hexLinks[ i ];
1541       _Link&       tgtLink = this->_hexLinks[ i ];
1542       tgtLink._nodes[0] = _hexNodes + ( srcLink._nodes[0] - other._hexNodes );
1543       tgtLink._nodes[1] = _hexNodes + ( srcLink._nodes[1] - other._hexNodes );
1544     }
1545
1546     for ( int i = 0; i < 6; ++i )
1547     {
1548       const _Face& srcQuad = other._hexQuads[ i ];
1549       _Face&       tgtQuad = this->_hexQuads[ i ];
1550       tgtQuad._links.resize(4);
1551       for ( int j = 0; j < 4; ++j )
1552       {
1553         const _OrientedLink& srcLink = srcQuad._links[ j ];
1554         _OrientedLink&       tgtLink = tgtQuad._links[ j ];
1555         tgtLink._reverse = srcLink._reverse;
1556         tgtLink._link    = _hexLinks + ( srcLink._link - other._hexLinks );
1557       }
1558     }
1559   }
1560
1561   //================================================================================
1562   /*!
1563    * \brief Initializes its data by given grid cell
1564    */
1565   void Hexahedron::init( size_t i, size_t j, size_t k )
1566   {
1567     _i = i; _j = j; _k = k;
1568     // set nodes of grid to nodes of the hexahedron and
1569     // count nodes at hexahedron corners located IN and ON geometry
1570     _nbCornerNodes = _nbBndNodes = 0;
1571     _origNodeInd   = _grid->NodeIndex( i,j,k );
1572     for ( int iN = 0; iN < 8; ++iN )
1573     {
1574       _hexNodes[iN]._node     = _grid->_nodes   [ _origNodeInd + _nodeShift[iN] ];
1575       _hexNodes[iN]._intPoint = _grid->_gridIntP[ _origNodeInd + _nodeShift[iN] ];
1576       _nbCornerNodes += bool( _hexNodes[iN]._node );
1577       _nbBndNodes    += bool( _hexNodes[iN]._intPoint );
1578     }
1579     _sideLength[0] = _grid->_coords[0][i+1] - _grid->_coords[0][i];
1580     _sideLength[1] = _grid->_coords[1][j+1] - _grid->_coords[1][j];
1581     _sideLength[2] = _grid->_coords[2][k+1] - _grid->_coords[2][k];
1582
1583     _intNodes.clear();
1584     _vIntNodes.clear();
1585
1586     if ( _nbFaceIntNodes + _eIntPoints.size() > 0 &&
1587          _nbFaceIntNodes + _nbCornerNodes + _eIntPoints.size() > 3)
1588     {
1589       _intNodes.reserve( 3 * _nbBndNodes + _nbFaceIntNodes + _eIntPoints.size() );
1590
1591       // this method can be called in parallel, so use own helper
1592       SMESH_MesherHelper helper( *_grid->_helper->GetMesh() );
1593
1594       // create sub-links (_splits) by splitting links with _fIntPoints
1595       _Link split;
1596       for ( int iLink = 0; iLink < 12; ++iLink )
1597       {
1598         _Link& link = _hexLinks[ iLink ];
1599         link._fIntNodes.resize( link._fIntPoints.size() );
1600         for ( size_t i = 0; i < link._fIntPoints.size(); ++i )
1601         {
1602           _intNodes.push_back( _Node( 0, link._fIntPoints[i] ));
1603           link._fIntNodes[ i ] = & _intNodes.back();
1604         }
1605
1606         link._splits.clear();
1607         split._nodes[ 0 ] = link._nodes[0];
1608         bool isOut = ( ! link._nodes[0]->Node() );
1609         bool checkTransition;
1610         for ( size_t i = 0; i < link._fIntNodes.size(); ++i )
1611         {
1612           const bool isGridNode = ( ! link._fIntNodes[i]->Node() );
1613           if ( !isGridNode ) // intersection non-coincident with a grid node
1614           {
1615             if ( split._nodes[ 0 ]->Node() && !isOut )
1616             {
1617               split._nodes[ 1 ] = link._fIntNodes[i];
1618               link._splits.push_back( split );
1619             }
1620             split._nodes[ 0 ] = link._fIntNodes[i];
1621             checkTransition = true;
1622           }
1623           else // FACE intersection coincident with a grid node (at link ends)
1624           {
1625             checkTransition = ( i == 0 && link._nodes[0]->Node() );
1626           }
1627           if ( checkTransition )
1628           {
1629             if ( link._fIntPoints[i]->_faceIDs.size() > 1 || _eIntPoints.size() > 0 )
1630               isOut = isOutPoint( link, i, helper );
1631             else
1632               switch ( link._fIntPoints[i]->_transition ) {
1633               case Trans_OUT: isOut = true;  break;
1634               case Trans_IN : isOut = false; break;
1635               default:
1636                 isOut = isOutPoint( link, i, helper );
1637               }
1638           }
1639         }
1640         if ( link._nodes[ 1 ]->Node() && split._nodes[ 0 ]->Node() && !isOut )
1641         {
1642           split._nodes[ 1 ] = link._nodes[1];
1643           link._splits.push_back( split );
1644         }
1645       }
1646
1647       // Create _Node's at intersections with EDGEs.
1648
1649       const double tol2 = _grid->_tol * _grid->_tol;
1650       int facets[3], nbFacets, subEntity;
1651
1652       for ( size_t iP = 0; iP < _eIntPoints.size(); ++iP )
1653       {
1654         nbFacets = getEntity( _eIntPoints[iP], facets, subEntity );
1655         _Node* equalNode = 0;
1656         switch( nbFacets ) {
1657         case 1: // in a _Face
1658         {
1659           _Face& quad = _hexQuads[ facets[0] - SMESH_Block::ID_FirstF ];
1660           equalNode = findEqualNode( quad._eIntNodes, _eIntPoints[ iP ], tol2 );
1661           if ( equalNode ) {
1662             equalNode->Add( _eIntPoints[ iP ] );
1663           }
1664           else {
1665             _intNodes.push_back( _Node( 0, _eIntPoints[ iP ]));
1666             quad._eIntNodes.push_back( & _intNodes.back() );
1667           }
1668           break;
1669         }
1670         case 2: // on a _Link
1671         {
1672           _Link& link = _hexLinks[ subEntity - SMESH_Block::ID_FirstE ];
1673           if ( link._splits.size() > 0 )
1674           {
1675             equalNode = findEqualNode( link._fIntNodes, _eIntPoints[ iP ], tol2 );
1676             if ( equalNode )
1677               equalNode->Add( _eIntPoints[ iP ] );
1678           }
1679           else
1680           {
1681             _intNodes.push_back( _Node( 0, _eIntPoints[ iP ]));
1682             for ( int iF = 0; iF < 2; ++iF )
1683             {
1684               _Face& quad = _hexQuads[ facets[iF] - SMESH_Block::ID_FirstF ];
1685               equalNode = findEqualNode( quad._eIntNodes, _eIntPoints[ iP ], tol2 );
1686               if ( equalNode ) {
1687                 equalNode->Add( _eIntPoints[ iP ] );
1688               }
1689               else {
1690                 quad._eIntNodes.push_back( & _intNodes.back() );
1691               }
1692             }
1693           }
1694           break;
1695         }
1696         case 3: // at a corner
1697         {
1698           _Node& node = _hexNodes[ subEntity - SMESH_Block::ID_FirstV ];
1699           if ( node.Node() > 0 )
1700           {
1701             if ( node._intPoint )
1702               node._intPoint->Add( _eIntPoints[ iP ]->_faceIDs, _eIntPoints[ iP ]->_node );
1703           }
1704           else
1705           {
1706             _intNodes.push_back( _Node( 0, _eIntPoints[ iP ]));
1707             for ( int iF = 0; iF < 3; ++iF )
1708             {
1709               _Face& quad = _hexQuads[ facets[iF] - SMESH_Block::ID_FirstF ];
1710               equalNode = findEqualNode( quad._eIntNodes, _eIntPoints[ iP ], tol2 );
1711               if ( equalNode ) {
1712                 equalNode->Add( _eIntPoints[ iP ] );
1713               }
1714               else {
1715                 quad._eIntNodes.push_back( & _intNodes.back() );
1716               }
1717             }
1718           }
1719           break;
1720         }
1721         } // switch( nbFacets )
1722
1723         if ( nbFacets == 0 ||
1724              _grid->_shapes( _eIntPoints[ iP ]->_shapeID ).ShapeType() == TopAbs_VERTEX )
1725         {
1726           equalNode = findEqualNode( _vIntNodes, _eIntPoints[ iP ], tol2 );
1727           if ( equalNode ) {
1728             equalNode->Add( _eIntPoints[ iP ] );
1729           }
1730           else if ( nbFacets == 0 ) {
1731             if ( _intNodes.empty() || _intNodes.back().EdgeIntPnt() != _eIntPoints[ iP ])
1732               _intNodes.push_back( _Node( 0, _eIntPoints[ iP ]));
1733             _vIntNodes.push_back( & _intNodes.back() );
1734           }
1735         }
1736       } // loop on _eIntPoints
1737     }
1738     else if ( 3 < _nbCornerNodes && _nbCornerNodes < 8 ) // _nbFaceIntNodes == 0
1739     {
1740       _Link split;
1741       // create sub-links (_splits) of whole links
1742       for ( int iLink = 0; iLink < 12; ++iLink )
1743       {
1744         _Link& link = _hexLinks[ iLink ];
1745         link._splits.clear();
1746         if ( link._nodes[ 0 ]->Node() && link._nodes[ 1 ]->Node() )
1747         {
1748           split._nodes[ 0 ] = link._nodes[0];
1749           split._nodes[ 1 ] = link._nodes[1];
1750           link._splits.push_back( split );
1751         }
1752       }
1753     }
1754
1755   }
1756   //================================================================================
1757   /*!
1758    * \brief Initializes its data by given grid cell (countered from zero)
1759    */
1760   void Hexahedron::init( size_t iCell )
1761   {
1762     size_t iNbCell = _grid->_coords[0].size() - 1;
1763     size_t jNbCell = _grid->_coords[1].size() - 1;
1764     _i = iCell % iNbCell;
1765     _j = ( iCell % ( iNbCell * jNbCell )) / iNbCell;
1766     _k = iCell / iNbCell / jNbCell;
1767     init( _i, _j, _k );
1768   }
1769
1770   //================================================================================
1771   /*!
1772    * \brief Compute mesh volumes resulted from intersection of the Hexahedron
1773    */
1774   void Hexahedron::ComputeElements()
1775   {
1776     Init();
1777
1778     int nbIntersections = _nbFaceIntNodes + _eIntPoints.size();
1779     if ( _nbCornerNodes + nbIntersections < 4 )
1780       return;
1781
1782     if ( _nbBndNodes == _nbCornerNodes && nbIntersections == 0 && isInHole() )
1783       return;
1784
1785     _polygons.clear();
1786     _polygons.reserve( 20 );
1787
1788     // Create polygons from quadrangles
1789     // --------------------------------
1790
1791     vector< _OrientedLink > splits;
1792     vector<_Node*>          chainNodes;
1793     _Face*                  coplanarPolyg;
1794
1795     bool hasEdgeIntersections = !_eIntPoints.empty();
1796
1797     for ( int iF = 0; iF < 6; ++iF ) // loop on 6 sides of a hexahedron
1798     {
1799       _Face& quad = _hexQuads[ iF ] ;
1800
1801       _polygons.resize( _polygons.size() + 1 );
1802       _Face* polygon = &_polygons.back();
1803       polygon->_polyLinks.reserve( 20 );
1804
1805       splits.clear();
1806       for ( int iE = 0; iE < 4; ++iE ) // loop on 4 sides of a quadrangle
1807         for ( int iS = 0; iS < quad._links[ iE ].NbResultLinks(); ++iS )
1808           splits.push_back( quad._links[ iE ].ResultLink( iS ));
1809
1810       // add splits of links to a polygon and add _polyLinks to make
1811       // polygon's boundary closed
1812
1813       int nbSplits = splits.size();
1814       if (( nbSplits == 1 ) &&
1815           ( quad._eIntNodes.empty() ||
1816             splits[0].FirstNode()->IsLinked( splits[0].LastNode()->_intPoint )))
1817           //( quad._eIntNodes.empty() || _nbCornerNodes + nbIntersections > 6 ))
1818         nbSplits = 0;
1819
1820 #ifdef _DEBUG_
1821       for ( size_t iP = 0; iP < quad._eIntNodes.size(); ++iP )
1822         if ( quad._eIntNodes[ iP ]->IsUsedInFace( polygon ))
1823           quad._eIntNodes[ iP ]->_usedInFace = 0;
1824 #endif
1825       int nbUsedEdgeNodes = 0;
1826       _Face* prevPolyg = 0; // polygon previously created from this quad
1827
1828       while ( nbSplits > 0 )
1829       {
1830         size_t iS = 0;
1831         while ( !splits[ iS ] )
1832           ++iS;
1833
1834         if ( !polygon->_links.empty() )
1835         {
1836           _polygons.resize( _polygons.size() + 1 );
1837           polygon = &_polygons.back();
1838           polygon->_polyLinks.reserve( 20 );
1839         }
1840         polygon->_links.push_back( splits[ iS ] );
1841         splits[ iS++ ]._link = 0;
1842         --nbSplits;
1843
1844         _Node* nFirst = polygon->_links.back().FirstNode();
1845         _Node *n1,*n2 = polygon->_links.back().LastNode();
1846         for ( ; nFirst != n2 && iS < splits.size(); ++iS )
1847         {
1848           _OrientedLink& split = splits[ iS ];
1849           if ( !split ) continue;
1850
1851           n1 = split.FirstNode();
1852           if ( n1 == n2 &&
1853                n1->_intPoint &&
1854                n1->_intPoint->_faceIDs.size() > 1 )
1855           {
1856             // n1 is at intersection with EDGE
1857             if ( findChainOnEdge( splits, polygon->_links.back(), split, iS, quad, chainNodes ))
1858             {
1859               for ( size_t i = 1; i < chainNodes.size(); ++i )
1860                 polygon->AddPolyLink( chainNodes[i-1], chainNodes[i], prevPolyg );
1861               prevPolyg = polygon;
1862               n2 = chainNodes.back();
1863               continue;
1864             }
1865           }
1866           else if ( n1 != n2 )
1867           {
1868             // try to connect to intersections with EDGEs
1869             if ( quad._eIntNodes.size() > nbUsedEdgeNodes  &&
1870                  findChain( n2, n1, quad, chainNodes ))
1871             {
1872               for ( size_t i = 1; i < chainNodes.size(); ++i )
1873               {
1874                 polygon->AddPolyLink( chainNodes[i-1], chainNodes[i] );
1875                 nbUsedEdgeNodes += ( chainNodes[i]->IsUsedInFace( polygon ));
1876               }
1877               if ( chainNodes.back() != n1 )
1878               {
1879                 n2 = chainNodes.back();
1880                 --iS;
1881                 continue;
1882               }
1883             }
1884             // try to connect to a split ending on the same FACE
1885             else
1886             {
1887               _OrientedLink foundSplit;
1888               for ( int i = iS; i < splits.size() && !foundSplit; ++i )
1889                 if (( foundSplit = splits[ i ]) &&
1890                     ( n2->IsLinked( foundSplit.FirstNode()->_intPoint )))
1891                 {
1892                   iS = i - 1;
1893                 }
1894                 else
1895                 {
1896                   foundSplit._link = 0;
1897                 }
1898               if ( foundSplit )
1899               {
1900                 if ( n2 != foundSplit.FirstNode() )
1901                 {
1902                   polygon->AddPolyLink( n2, foundSplit.FirstNode() );
1903                   n2 = foundSplit.FirstNode();
1904                 }
1905                 continue;
1906               }
1907               else
1908               {
1909                 if ( n2->IsLinked( nFirst->_intPoint ))
1910                   break;
1911                 polygon->AddPolyLink( n2, n1, prevPolyg );
1912               }
1913             }
1914           } // if ( n1 != n2 )
1915
1916           polygon->_links.push_back( split );
1917           split._link = 0;
1918           --nbSplits;
1919           n2 = polygon->_links.back().LastNode();
1920
1921         } // loop on splits
1922
1923         if ( nFirst != n2 ) // close a polygon
1924         {
1925           if ( !findChain( n2, nFirst, quad, chainNodes ))
1926           {
1927             if ( !closePolygon( polygon, chainNodes ))
1928               if ( !isImplementEdges() )
1929                 chainNodes.push_back( nFirst );
1930           }
1931           for ( size_t i = 1; i < chainNodes.size(); ++i )
1932           {
1933             polygon->AddPolyLink( chainNodes[i-1], chainNodes[i], prevPolyg );
1934             nbUsedEdgeNodes += bool( chainNodes[i]->IsUsedInFace( polygon ));
1935           }
1936         }
1937
1938         if ( polygon->_links.size() < 3 && nbSplits > 0 )
1939         {
1940           polygon->_polyLinks.clear();
1941           polygon->_links.clear();
1942         }
1943       } // while ( nbSplits > 0 )
1944
1945       if ( polygon->_links.size() < 3 )
1946       {
1947         _polygons.pop_back();
1948       }
1949     }  // loop on 6 hexahedron sides
1950
1951     // Create polygons closing holes in a polyhedron
1952     // ----------------------------------------------
1953
1954     // clear _usedInFace
1955     for ( size_t iN = 0; iN < _intNodes.size(); ++iN )
1956       _intNodes[ iN ]._usedInFace = 0;
1957
1958     // add polygons to their links and mark used nodes
1959     for ( size_t iP = 0; iP < _polygons.size(); ++iP )
1960     {
1961       _Face& polygon = _polygons[ iP ];
1962       for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
1963       {
1964         polygon._links[ iL ].AddFace( &polygon );
1965         polygon._links[ iL ].FirstNode()->_usedInFace = &polygon;
1966       }
1967     }
1968     // find free links
1969     vector< _OrientedLink* > freeLinks;
1970     freeLinks.reserve(20);
1971     for ( size_t iP = 0; iP < _polygons.size(); ++iP )
1972     {
1973       _Face& polygon = _polygons[ iP ];
1974       for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
1975         if ( polygon._links[ iL ].NbFaces() < 2 )
1976           freeLinks.push_back( & polygon._links[ iL ]);
1977     }
1978     int nbFreeLinks = freeLinks.size();
1979     if ( nbFreeLinks == 1 ) return;
1980
1981     // put not used intersection nodes to _vIntNodes
1982     int nbVertexNodes = 0; // nb not used vertex nodes
1983     {
1984       for ( size_t iN = 0; iN < _vIntNodes.size(); ++iN )
1985         nbVertexNodes += ( !_vIntNodes[ iN ]->IsUsedInFace() );
1986
1987       const double tol = 1e-3 * Min( Min( _sideLength[0], _sideLength[1] ), _sideLength[0] );
1988       for ( size_t iN = _nbFaceIntNodes; iN < _intNodes.size(); ++iN )
1989       {
1990         if ( _intNodes[ iN ].IsUsedInFace() ) continue;
1991         if ( dynamic_cast< const F_IntersectPoint* >( _intNodes[ iN ]._intPoint )) continue;
1992         _Node* equalNode =
1993           findEqualNode( _vIntNodes, _intNodes[ iN ].EdgeIntPnt(), tol*tol );
1994         if ( !equalNode )
1995         {
1996           _vIntNodes.push_back( &_intNodes[ iN ]);
1997           ++nbVertexNodes;
1998         }
1999       }
2000     }
2001
2002     set<TGeomID> usedFaceIDs;
2003     vector< TGeomID > faces;
2004     TGeomID curFace = 0;
2005     const size_t nbQuadPolygons = _polygons.size();
2006     E_IntersectPoint ipTmp;
2007
2008     // create polygons by making closed chains of free links
2009     size_t iPolygon = _polygons.size();
2010     while ( nbFreeLinks > 0 )
2011     {
2012       if ( iPolygon == _polygons.size() )
2013       {
2014         _polygons.resize( _polygons.size() + 1 );
2015         _polygons[ iPolygon ]._polyLinks.reserve( 20 );
2016         _polygons[ iPolygon ]._links.reserve( 20 );
2017       }
2018       _Face& polygon = _polygons[ iPolygon ];
2019
2020       _OrientedLink* curLink = 0;
2021       _Node*         curNode;
2022       if (( !hasEdgeIntersections ) ||
2023           ( nbFreeLinks < 4 && nbVertexNodes == 0 ))
2024       {
2025         // get a remaining link to start from
2026         for ( size_t iL = 0; iL < freeLinks.size() && !curLink; ++iL )
2027           if (( curLink = freeLinks[ iL ] ))
2028             freeLinks[ iL ] = 0;
2029         polygon._links.push_back( *curLink );
2030         --nbFreeLinks;
2031         do
2032         {
2033           // find all links connected to curLink
2034           curNode = curLink->FirstNode();
2035           curLink = 0;
2036           for ( size_t iL = 0; iL < freeLinks.size() && !curLink; ++iL )
2037             if ( freeLinks[ iL ] && freeLinks[ iL ]->LastNode() == curNode )
2038             {
2039               curLink = freeLinks[ iL ];
2040               freeLinks[ iL ] = 0;
2041               --nbFreeLinks;
2042               polygon._links.push_back( *curLink );
2043             }
2044         } while ( curLink );
2045       }
2046       else // there are intersections with EDGEs
2047       {
2048         // get a remaining link to start from, one lying on minimal nb of FACEs
2049         {
2050           typedef pair< TGeomID, int > TFaceOfLink;
2051           TFaceOfLink faceOfLink( -1, -1 );
2052           TFaceOfLink facesOfLink[3] = { faceOfLink, faceOfLink, faceOfLink };
2053           for ( size_t iL = 0; iL < freeLinks.size(); ++iL )
2054             if ( freeLinks[ iL ] )
2055             {
2056               faces = freeLinks[ iL ]->GetNotUsedFace( usedFaceIDs );
2057               if ( faces.size() == 1 )
2058               {
2059                 faceOfLink = TFaceOfLink( faces[0], iL );
2060                 if ( !freeLinks[ iL ]->HasEdgeNodes() )
2061                   break;
2062                 facesOfLink[0] = faceOfLink;
2063               }
2064               else if ( facesOfLink[0].first < 0 )
2065               {
2066                 faceOfLink = TFaceOfLink(( faces.empty() ? -1 : faces[0]), iL );
2067                 facesOfLink[ 1 + faces.empty() ] = faceOfLink;
2068               }
2069             }
2070           for ( int i = 0; faceOfLink.first < 0 && i < 3; ++i )
2071             faceOfLink = facesOfLink[i];
2072
2073           if ( faceOfLink.first < 0 ) // all faces used
2074           {
2075             for ( size_t iL = 0; iL < freeLinks.size() && faceOfLink.first < 1; ++iL )
2076               if (( curLink = freeLinks[ iL ]))
2077               {
2078                 faceOfLink.first = 
2079                   curLink->FirstNode()->IsLinked( curLink->LastNode()->_intPoint );
2080                 faceOfLink.second = iL;
2081               }
2082             usedFaceIDs.clear();
2083           }
2084           curFace = faceOfLink.first;
2085           curLink = freeLinks[ faceOfLink.second ];
2086           freeLinks[ faceOfLink.second ] = 0;
2087         }
2088         usedFaceIDs.insert( curFace );
2089         polygon._links.push_back( *curLink );
2090         --nbFreeLinks;
2091
2092         // find all links lying on a curFace
2093         do
2094         {
2095           // go forward from curLink
2096           curNode = curLink->LastNode();
2097           curLink = 0;
2098           for ( size_t iL = 0; iL < freeLinks.size() && !curLink; ++iL )
2099             if ( freeLinks[ iL ] &&
2100                  freeLinks[ iL ]->FirstNode() == curNode &&
2101                  freeLinks[ iL ]->LastNode()->IsOnFace( curFace ))
2102             {
2103               curLink = freeLinks[ iL ];
2104               freeLinks[ iL ] = 0;
2105               polygon._links.push_back( *curLink );
2106               --nbFreeLinks;
2107             }
2108         } while ( curLink );
2109
2110         std::reverse( polygon._links.begin(), polygon._links.end() );
2111
2112         curLink = & polygon._links.back();
2113         do
2114         {
2115           // go backward from curLink
2116           curNode = curLink->FirstNode();
2117           curLink = 0;
2118           for ( size_t iL = 0; iL < freeLinks.size() && !curLink; ++iL )
2119             if ( freeLinks[ iL ] &&
2120                  freeLinks[ iL ]->LastNode() == curNode &&
2121                  freeLinks[ iL ]->FirstNode()->IsOnFace( curFace ))
2122             {
2123               curLink = freeLinks[ iL ];
2124               freeLinks[ iL ] = 0;
2125               polygon._links.push_back( *curLink );
2126               --nbFreeLinks;
2127             }
2128         } while ( curLink );
2129
2130         curNode = polygon._links.back().FirstNode();
2131
2132         if ( polygon._links[0].LastNode() != curNode )
2133         {
2134           if ( nbVertexNodes > 0 )
2135           {
2136             // add links with _vIntNodes if not already used
2137             chainNodes.clear();
2138             for ( size_t iN = 0; iN < _vIntNodes.size(); ++iN )
2139               if ( !_vIntNodes[ iN ]->IsUsedInFace() &&
2140                    _vIntNodes[ iN ]->IsOnFace( curFace ))
2141               {
2142                 _vIntNodes[ iN ]->_usedInFace = &polygon;
2143                 chainNodes.push_back( _vIntNodes[ iN ] );
2144               }
2145             if ( chainNodes.size() > 1 )
2146             {
2147               sortVertexNodes( chainNodes, curNode, curFace );
2148             }
2149             for ( int i = 0; i < chainNodes.size(); ++i )
2150             {
2151               polygon.AddPolyLink( chainNodes[ i ], curNode );
2152               curNode = chainNodes[ i ];
2153               freeLinks.push_back( &polygon._links.back() );
2154               ++nbFreeLinks;
2155             }
2156             nbVertexNodes -= chainNodes.size();
2157           }
2158           // if ( polygon._links.size() > 1 )
2159           {
2160             polygon.AddPolyLink( polygon._links[0].LastNode(), curNode );
2161             freeLinks.push_back( &polygon._links.back() );
2162             ++nbFreeLinks;
2163           }
2164         }
2165       } // if there are intersections with EDGEs
2166
2167       if ( polygon._links.size() < 2 ||
2168            polygon._links[0].LastNode() != polygon._links.back().FirstNode() )
2169         return; // closed polygon not found -> invalid polyhedron
2170
2171       if ( polygon._links.size() == 2 )
2172       {
2173         if ( freeLinks.back() == &polygon._links.back() )
2174         {
2175           freeLinks.pop_back();
2176           --nbFreeLinks;
2177         }
2178         if ( polygon._links.front().NbFaces() > 0 )
2179           polygon._links.back().AddFace( polygon._links.front()._link->_faces[0] );
2180         if ( polygon._links.back().NbFaces() > 0 )
2181           polygon._links.front().AddFace( polygon._links.back()._link->_faces[0] );
2182
2183         if ( iPolygon == _polygons.size()-1 )
2184           _polygons.pop_back();
2185       }
2186       else // polygon._links.size() >= 2
2187       {
2188         // add polygon to its links
2189         for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
2190         {
2191           polygon._links[ iL ].AddFace( &polygon );
2192           polygon._links[ iL ].Reverse();
2193         }
2194         if ( /*hasEdgeIntersections &&*/ iPolygon == _polygons.size() - 1 )
2195         {
2196           // check that a polygon does not lie on a hexa side
2197           coplanarPolyg = 0;
2198           for ( size_t iL = 0; iL < polygon._links.size() && !coplanarPolyg; ++iL )
2199           {
2200             if ( polygon._links[ iL ].NbFaces() < 2 )
2201               continue; // it's a just added free link
2202             // look for a polygon made on a hexa side and sharing
2203             // two or more haxa links
2204             size_t iL2;
2205             coplanarPolyg = polygon._links[ iL ]._link->_faces[0];
2206             for ( iL2 = iL + 1; iL2 < polygon._links.size(); ++iL2 )
2207               if ( polygon._links[ iL2 ]._link->_faces[0] == coplanarPolyg &&
2208                    !coplanarPolyg->IsPolyLink( polygon._links[ iL  ]) &&
2209                    !coplanarPolyg->IsPolyLink( polygon._links[ iL2 ]) &&
2210                    coplanarPolyg < & _polygons[ nbQuadPolygons ])
2211                 break;
2212             if ( iL2 == polygon._links.size() )
2213               coplanarPolyg = 0;
2214           }
2215           if ( coplanarPolyg ) // coplanar polygon found
2216           {
2217             freeLinks.resize( freeLinks.size() - polygon._polyLinks.size() );
2218             nbFreeLinks -= polygon._polyLinks.size();
2219
2220             // an E_IntersectPoint used to mark nodes of coplanarPolyg
2221             // as lying on curFace while they are not at intersection with geometry
2222             ipTmp._faceIDs.resize(1);
2223             ipTmp._faceIDs[0] = curFace;
2224
2225             // fill freeLinks with links not shared by coplanarPolyg and polygon
2226             for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
2227               if ( polygon._links[ iL ]._link->_faces[1] &&
2228                    polygon._links[ iL ]._link->_faces[0] != coplanarPolyg )
2229               {
2230                 _Face* p = polygon._links[ iL ]._link->_faces[0];
2231                 for ( size_t iL2 = 0; iL2 < p->_links.size(); ++iL2 )
2232                   if ( p->_links[ iL2 ]._link == polygon._links[ iL ]._link )
2233                   {
2234                     freeLinks.push_back( & p->_links[ iL2 ] );
2235                     ++nbFreeLinks;
2236                     freeLinks.back()->RemoveFace( &polygon );
2237                     break;
2238                   }
2239               }
2240             for ( size_t iL = 0; iL < coplanarPolyg->_links.size(); ++iL )
2241               if ( coplanarPolyg->_links[ iL ]._link->_faces[1] &&
2242                    coplanarPolyg->_links[ iL ]._link->_faces[1] != &polygon )
2243               {
2244                 _Face* p = coplanarPolyg->_links[ iL ]._link->_faces[0];
2245                 if ( p == coplanarPolyg )
2246                   p = coplanarPolyg->_links[ iL ]._link->_faces[1];
2247                 for ( size_t iL2 = 0; iL2 < p->_links.size(); ++iL2 )
2248                   if ( p->_links[ iL2 ]._link == coplanarPolyg->_links[ iL ]._link )
2249                   {
2250                     // set links of coplanarPolyg in place of used freeLinks
2251                     // to re-create coplanarPolyg next
2252                     size_t iL3 = 0;
2253                     for ( ; iL3 < freeLinks.size() && freeLinks[ iL3 ]; ++iL3 );
2254                     if ( iL3 < freeLinks.size() )
2255                       freeLinks[ iL3 ] = ( & p->_links[ iL2 ] );
2256                     else
2257                       freeLinks.push_back( & p->_links[ iL2 ] );
2258                     ++nbFreeLinks;
2259                     freeLinks[ iL3 ]->RemoveFace( coplanarPolyg );
2260                     //  mark nodes of coplanarPolyg as lying on curFace
2261                     for ( int iN = 0; iN < 2; ++iN )
2262                     {
2263                       _Node* n = freeLinks[ iL3 ]->_link->_nodes[ iN ];
2264                       if ( n->_intPoint ) n->_intPoint->Add( ipTmp._faceIDs );
2265                       else                n->_intPoint = &ipTmp;
2266                     }
2267                     break;
2268                   }
2269               }
2270             // set coplanarPolyg to be re-created next
2271             for ( size_t iP = 0; iP < _polygons.size(); ++iP )
2272               if ( coplanarPolyg == & _polygons[ iP ] )
2273               {
2274                 iPolygon = iP;
2275                 _polygons[ iPolygon ]._links.clear();
2276                 _polygons[ iPolygon ]._polyLinks.clear();
2277                 break;
2278               }
2279             _polygons.pop_back();
2280             usedFaceIDs.erase( curFace );
2281             continue;
2282           } // if ( coplanarPolyg )
2283         } // if ( hasEdgeIntersections ) - search for coplanarPolyg
2284
2285         iPolygon = _polygons.size();
2286
2287       } // end of case ( polygon._links.size() > 2 )
2288     } // while ( nbFreeLinks > 0 )
2289
2290     if ( ! checkPolyhedronSize() )
2291     {
2292       return;
2293     }
2294
2295     for ( size_t i = 0; i < 8; ++i )
2296       if ( _hexNodes[ i ]._intPoint == &ipTmp )
2297         _hexNodes[ i ]._intPoint = 0;
2298
2299     // create a classic cell if possible
2300
2301     int nbPolygons = 0;
2302     for ( size_t iF = 0; iF < _polygons.size(); ++iF )
2303       nbPolygons += (_polygons[ iF ]._links.size() > 0 );
2304
2305     //const int nbNodes = _nbCornerNodes + nbIntersections;
2306     int nbNodes = 0;
2307     for ( size_t i = 0; i < 8; ++i )
2308       nbNodes += _hexNodes[ i ].IsUsedInFace();
2309     for ( size_t i = 0; i < _intNodes.size(); ++i )
2310       nbNodes += _intNodes[ i ].IsUsedInFace();
2311
2312     bool isClassicElem = false;
2313     if (      nbNodes == 8 && nbPolygons == 6 ) isClassicElem = addHexa();
2314     else if ( nbNodes == 4 && nbPolygons == 4 ) isClassicElem = addTetra();
2315     else if ( nbNodes == 6 && nbPolygons == 5 ) isClassicElem = addPenta();
2316     else if ( nbNodes == 5 && nbPolygons == 5 ) isClassicElem = addPyra ();
2317     if ( !isClassicElem )
2318     {
2319       _volumeDefs._nodes.clear();
2320       _volumeDefs._quantities.clear();
2321
2322       for ( size_t iF = 0; iF < _polygons.size(); ++iF )
2323       {
2324         const size_t nbLinks = _polygons[ iF ]._links.size();
2325         if ( nbLinks == 0 ) continue;
2326         _volumeDefs._quantities.push_back( nbLinks );
2327         for ( size_t iL = 0; iL < nbLinks; ++iL )
2328           _volumeDefs._nodes.push_back( _polygons[ iF ]._links[ iL ].FirstNode() );
2329       }
2330     }
2331   }
2332   //================================================================================
2333   /*!
2334    * \brief Create elements in the mesh
2335    */
2336   int Hexahedron::MakeElements(SMESH_MesherHelper&                      helper,
2337                                const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap)
2338   {
2339     SMESHDS_Mesh* mesh = helper.GetMeshDS();
2340
2341     size_t nbCells[3] = { _grid->_coords[0].size() - 1,
2342                           _grid->_coords[1].size() - 1,
2343                           _grid->_coords[2].size() - 1 };
2344     const size_t nbGridCells = nbCells[0] * nbCells[1] * nbCells[2];
2345     vector< Hexahedron* > allHexa( nbGridCells, 0 );
2346     int nbIntHex = 0;
2347
2348     // set intersection nodes from GridLine's to links of allHexa
2349     int i,j,k, iDirOther[3][2] = {{ 1,2 },{ 0,2 },{ 0,1 }};
2350     for ( int iDir = 0; iDir < 3; ++iDir )
2351     {
2352       int dInd[4][3] = { {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} };
2353       dInd[1][ iDirOther[iDir][0] ] = -1;
2354       dInd[2][ iDirOther[iDir][1] ] = -1;
2355       dInd[3][ iDirOther[iDir][0] ] = -1; dInd[3][ iDirOther[iDir][1] ] = -1;
2356       // loop on GridLine's parallel to iDir
2357       LineIndexer lineInd = _grid->GetLineIndexer( iDir );
2358       for ( ; lineInd.More(); ++lineInd )
2359       {
2360         GridLine& line = _grid->_lines[ iDir ][ lineInd.LineIndex() ];
2361         multiset< F_IntersectPoint >::const_iterator ip = line._intPoints.begin();
2362         for ( ; ip != line._intPoints.end(); ++ip )
2363         {
2364           // if ( !ip->_node ) continue; // intersection at a grid node
2365           lineInd.SetIndexOnLine( ip->_indexOnLine );
2366           for ( int iL = 0; iL < 4; ++iL ) // loop on 4 cells sharing a link
2367           {
2368             i = int(lineInd.I()) + dInd[iL][0];
2369             j = int(lineInd.J()) + dInd[iL][1];
2370             k = int(lineInd.K()) + dInd[iL][2];
2371             if ( i < 0 || i >= nbCells[0] ||
2372                  j < 0 || j >= nbCells[1] ||
2373                  k < 0 || k >= nbCells[2] ) continue;
2374
2375             const size_t hexIndex = _grid->CellIndex( i,j,k );
2376             Hexahedron *& hex = allHexa[ hexIndex ];
2377             if ( !hex)
2378             {
2379               hex = new Hexahedron( *this );
2380               hex->_i = i;
2381               hex->_j = j;
2382               hex->_k = k;
2383               ++nbIntHex;
2384             }
2385             const int iLink = iL + iDir * 4;
2386             hex->_hexLinks[iLink]._fIntPoints.push_back( &(*ip) );
2387             hex->_nbFaceIntNodes += bool( ip->_node );
2388           }
2389         }
2390       }
2391     }
2392
2393     // implement geom edges into the mesh
2394     addEdges( helper, allHexa, edge2faceIDsMap );
2395
2396     // add not split hexadrons to the mesh
2397     int nbAdded = 0;
2398     vector< Hexahedron* > intHexa( nbIntHex, (Hexahedron*) NULL );
2399     for ( size_t i = 0; i < allHexa.size(); ++i )
2400     {
2401       Hexahedron * & hex = allHexa[ i ];
2402       if ( hex )
2403       {
2404         intHexa.push_back( hex );
2405         if ( hex->_nbFaceIntNodes > 0 || hex->_eIntPoints.size() > 0 )
2406           continue; // treat intersected hex later
2407         this->init( hex->_i, hex->_j, hex->_k );
2408       }
2409       else
2410       {    
2411         this->init( i );
2412       }
2413       if (( _nbCornerNodes == 8 ) &&
2414           ( _nbBndNodes < _nbCornerNodes || !isInHole() ))
2415       {
2416         // order of _hexNodes is defined by enum SMESH_Block::TShapeID
2417         SMDS_MeshElement* el =
2418           mesh->AddVolume( _hexNodes[0].Node(), _hexNodes[2].Node(),
2419                            _hexNodes[3].Node(), _hexNodes[1].Node(),
2420                            _hexNodes[4].Node(), _hexNodes[6].Node(),
2421                            _hexNodes[7].Node(), _hexNodes[5].Node() );
2422         mesh->SetMeshElementOnShape( el, helper.GetSubShapeID() );
2423         ++nbAdded;
2424         if ( hex )
2425           intHexa.pop_back();
2426       }
2427       else if ( _nbCornerNodes > 3  && !hex )
2428       {
2429         // all intersection of hex with geometry are at grid nodes
2430         hex = new Hexahedron( *this );
2431         hex->_i = _i;
2432         hex->_j = _j;
2433         hex->_k = _k;
2434         intHexa.push_back( hex );
2435       }
2436     }
2437
2438     // add elements resulted from hexadron intersection
2439 #ifdef WITH_TBB
2440     tbb::parallel_for ( tbb::blocked_range<size_t>( 0, intHexa.size() ),
2441                         ParallelHexahedron( intHexa ),
2442                         tbb::simple_partitioner()); // ComputeElements() is called here
2443     for ( size_t i = 0; i < intHexa.size(); ++i )
2444       if ( Hexahedron * hex = intHexa[ i ] )
2445         nbAdded += hex->addElements( helper );
2446 #else
2447     for ( size_t i = 0; i < intHexa.size(); ++i )
2448       if ( Hexahedron * hex = intHexa[ i ] )
2449       {
2450         hex->ComputeElements();
2451         nbAdded += hex->addElements( helper );
2452       }
2453 #endif
2454
2455     for ( size_t i = 0; i < allHexa.size(); ++i )
2456       if ( allHexa[ i ] )
2457         delete allHexa[ i ];
2458
2459     return nbAdded;
2460   }
2461
2462   //================================================================================
2463   /*!
2464    * \brief Implements geom edges into the mesh
2465    */
2466   void Hexahedron::addEdges(SMESH_MesherHelper&                      helper,
2467                             vector< Hexahedron* >&                   hexes,
2468                             const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap)
2469   {
2470     if ( edge2faceIDsMap.empty() ) return;
2471
2472     // Prepare planes for intersecting with EDGEs
2473     GridPlanes pln[3];
2474     {
2475       for ( int iDirZ = 0; iDirZ < 3; ++iDirZ ) // iDirZ gives normal direction to planes
2476       {
2477         GridPlanes& planes = pln[ iDirZ ];
2478         int iDirX = ( iDirZ + 1 ) % 3;
2479         int iDirY = ( iDirZ + 2 ) % 3;
2480         planes._zNorm  = ( _grid->_axes[ iDirX ] ^ _grid->_axes[ iDirY ] ).Normalized();
2481         planes._zProjs.resize ( _grid->_coords[ iDirZ ].size() );
2482         planes._zProjs [0] = 0;
2483         const double       zFactor = _grid->_axes[ iDirZ ] * planes._zNorm;
2484         const vector< double > & u = _grid->_coords[ iDirZ ];
2485         for ( int i = 1; i < planes._zProjs.size(); ++i )
2486         {
2487           planes._zProjs [i] = zFactor * ( u[i] - u[0] );
2488         }
2489       }
2490     }
2491     const double deflection = _grid->_minCellSize / 20.;
2492     const double tol        = _grid->_tol;
2493     E_IntersectPoint ip;
2494
2495     // Intersect EDGEs with the planes
2496     map< TGeomID, vector< TGeomID > >::const_iterator e2fIt = edge2faceIDsMap.begin();
2497     for ( ; e2fIt != edge2faceIDsMap.end(); ++e2fIt )
2498     {
2499       const TGeomID  edgeID = e2fIt->first;
2500       const TopoDS_Edge & E = TopoDS::Edge( _grid->_shapes( edgeID ));
2501       BRepAdaptor_Curve curve( E );
2502       TopoDS_Vertex v1 = helper.IthVertex( 0, E, false ); 
2503       TopoDS_Vertex v2 = helper.IthVertex( 1, E, false ); 
2504
2505       ip._faceIDs = e2fIt->second;
2506       ip._shapeID = edgeID;
2507
2508       // discretize the EGDE
2509       GCPnts_UniformDeflection discret( curve, deflection, true );
2510       if ( !discret.IsDone() || discret.NbPoints() < 2 )
2511         continue;
2512
2513       // perform intersection
2514       for ( int iDirZ = 0; iDirZ < 3; ++iDirZ )
2515       {
2516         GridPlanes& planes = pln[ iDirZ ];
2517         int      iDirX = ( iDirZ + 1 ) % 3;
2518         int      iDirY = ( iDirZ + 2 ) % 3;
2519         double    xLen = _grid->_coords[ iDirX ].back() - _grid->_coords[ iDirX ][0];
2520         double    yLen = _grid->_coords[ iDirY ].back() - _grid->_coords[ iDirY ][0];
2521         double    zLen = _grid->_coords[ iDirZ ].back() - _grid->_coords[ iDirZ ][0];
2522         int dIJK[3], d000[3] = { 0,0,0 };
2523         double o[3] = { _grid->_coords[0][0],
2524                         _grid->_coords[1][0],
2525                         _grid->_coords[2][0] };
2526
2527         // locate the 1st point of a segment within the grid
2528         gp_XYZ p1     = discret.Value( 1 ).XYZ();
2529         double u1     = discret.Parameter( 1 );
2530         double zProj1 = planes._zNorm * ( p1 - _grid->_origin );
2531
2532         _grid->ComputeUVW( p1, ip._uvw );
2533         int iX1 = int(( ip._uvw[iDirX] - o[iDirX]) / xLen * (_grid->_coords[ iDirX ].size() - 1));
2534         int iY1 = int(( ip._uvw[iDirY] - o[iDirY]) / yLen * (_grid->_coords[ iDirY ].size() - 1));
2535         int iZ1 = int(( ip._uvw[iDirZ] - o[iDirZ]) / zLen * (_grid->_coords[ iDirZ ].size() - 1));
2536         locateValue( iX1, ip._uvw[iDirX], _grid->_coords[ iDirX ], dIJK[ iDirX ], tol );
2537         locateValue( iY1, ip._uvw[iDirY], _grid->_coords[ iDirY ], dIJK[ iDirY ], tol );
2538         locateValue( iZ1, ip._uvw[iDirZ], _grid->_coords[ iDirZ ], dIJK[ iDirZ ], tol );
2539
2540         int ijk[3]; // grid index where a segment intersect a plane
2541         ijk[ iDirX ] = iX1;
2542         ijk[ iDirY ] = iY1;
2543         ijk[ iDirZ ] = iZ1;
2544
2545         // add the 1st vertex point to a hexahedron
2546         if ( iDirZ == 0 )
2547         {
2548           ip._point   = p1;
2549           ip._shapeID = _grid->_shapes.Add( v1 );
2550           _grid->_edgeIntP.push_back( ip );
2551           if ( !addIntersection( _grid->_edgeIntP.back(), hexes, ijk, d000 ))
2552             _grid->_edgeIntP.pop_back();
2553           ip._shapeID = edgeID;
2554         }
2555         for ( int iP = 2; iP <= discret.NbPoints(); ++iP )
2556         {
2557           // locate the 2nd point of a segment within the grid
2558           gp_XYZ p2     = discret.Value( iP ).XYZ();
2559           double u2     = discret.Parameter( iP );
2560           double zProj2 = planes._zNorm * ( p2 - _grid->_origin );
2561           int    iZ2    = iZ1;
2562           if ( Abs( zProj2 - zProj1 ) > std::numeric_limits<double>::min() )
2563           {
2564             locateValue( iZ2, zProj2, planes._zProjs, dIJK[ iDirZ ], tol );
2565
2566             // treat intersections with planes between 2 end points of a segment
2567             int dZ = ( iZ1 <= iZ2 ) ? +1 : -1;
2568             int iZ = iZ1 + ( iZ1 < iZ2 );
2569             for ( int i = 0, nb = Abs( iZ1 - iZ2 ); i < nb; ++i, iZ += dZ )
2570             {
2571               ip._point = findIntPoint( u1, zProj1, u2, zProj2,
2572                                         planes._zProjs[ iZ ],
2573                                         curve, planes._zNorm, _grid->_origin );
2574               _grid->ComputeUVW( ip._point.XYZ(), ip._uvw );
2575               locateValue( ijk[iDirX], ip._uvw[iDirX], _grid->_coords[iDirX], dIJK[iDirX], tol );
2576               locateValue( ijk[iDirY], ip._uvw[iDirY], _grid->_coords[iDirY], dIJK[iDirY], tol );
2577               ijk[ iDirZ ] = iZ;
2578
2579               // add ip to hex "above" the plane
2580               _grid->_edgeIntP.push_back( ip );
2581               dIJK[ iDirZ ] = 0;
2582               bool added = addIntersection(_grid->_edgeIntP.back(), hexes, ijk, dIJK);
2583
2584               // add ip to hex "below" the plane
2585               ijk[ iDirZ ] = iZ-1;
2586               if ( !addIntersection( _grid->_edgeIntP.back(), hexes, ijk, dIJK ) &&
2587                    !added)
2588                 _grid->_edgeIntP.pop_back();
2589             }
2590           }
2591           iZ1    = iZ2;
2592           p1     = p2;
2593           u1     = u2;
2594           zProj1 = zProj2;
2595         }
2596         // add the 2nd vertex point to a hexahedron
2597         if ( iDirZ == 0 )
2598         {
2599           ip._shapeID = _grid->_shapes.Add( v2 );
2600           ip._point = p1;
2601           _grid->ComputeUVW( p1, ip._uvw );
2602           locateValue( ijk[iDirX], ip._uvw[iDirX], _grid->_coords[iDirX], dIJK[iDirX], tol );
2603           locateValue( ijk[iDirY], ip._uvw[iDirY], _grid->_coords[iDirY], dIJK[iDirY], tol );
2604           ijk[ iDirZ ] = iZ1;
2605           _grid->_edgeIntP.push_back( ip );
2606           if ( !addIntersection( _grid->_edgeIntP.back(), hexes, ijk, d000 ))
2607             _grid->_edgeIntP.pop_back();
2608           ip._shapeID = edgeID;
2609         }
2610       } // loop on 3 grid directions
2611     } // loop on EDGEs
2612
2613   }
2614
2615   //================================================================================
2616   /*!
2617    * \brief Finds intersection of a curve with a plane
2618    *  \param [in] u1 - parameter of one curve point
2619    *  \param [in] proj1 - projection of the curve point to the plane normal
2620    *  \param [in] u2 - parameter of another curve point
2621    *  \param [in] proj2 - projection of the other curve point to the plane normal
2622    *  \param [in] proj - projection of a point where the curve intersects the plane
2623    *  \param [in] curve - the curve
2624    *  \param [in] axis - the plane normal
2625    *  \param [in] origin - the plane origin
2626    *  \return gp_Pnt - the found intersection point
2627    */
2628   gp_Pnt Hexahedron::findIntPoint( double u1, double proj1,
2629                                    double u2, double proj2,
2630                                    double proj,
2631                                    BRepAdaptor_Curve& curve,
2632                                    const gp_XYZ& axis,
2633                                    const gp_XYZ& origin)
2634   {
2635     double r = (( proj - proj1 ) / ( proj2 - proj1 ));
2636     double u = u1 * ( 1 - r ) + u2 * r;
2637     gp_Pnt p = curve.Value( u );
2638     double newProj =  axis * ( p.XYZ() - origin );
2639     if ( Abs( proj - newProj ) > _grid->_tol / 10. )
2640     {
2641       if ( r > 0.5 )
2642         return findIntPoint( u2, proj2, u, newProj, proj, curve, axis, origin );
2643       else
2644         return findIntPoint( u1, proj2, u, newProj, proj, curve, axis, origin );
2645     }
2646     return p;
2647   }
2648
2649   //================================================================================
2650   /*!
2651    * \brief Returns indices of a hexahedron sub-entities holding a point
2652    *  \param [in] ip - intersection point
2653    *  \param [out] facets - 0-3 facets holding a point
2654    *  \param [out] sub - index of a vertex or an edge holding a point
2655    *  \return int - number of facets holding a point
2656    */
2657   int Hexahedron::getEntity( const E_IntersectPoint* ip, int* facets, int& sub )
2658   {
2659     enum { X = 1, Y = 2, Z = 4 }; // == 001, 010, 100
2660     int nbFacets = 0;
2661     int vertex = 0, egdeMask = 0;
2662
2663     if ( Abs( _grid->_coords[0][ _i   ] - ip->_uvw[0] ) < _grid->_tol ) {
2664       facets[ nbFacets++ ] = SMESH_Block::ID_F0yz;
2665       egdeMask |= X;
2666     }
2667     else if ( Abs( _grid->_coords[0][ _i+1 ] - ip->_uvw[0] ) < _grid->_tol ) {
2668       facets[ nbFacets++ ] = SMESH_Block::ID_F1yz;
2669       vertex   |= X;
2670       egdeMask |= X;
2671     }
2672     if ( Abs( _grid->_coords[1][ _j   ] - ip->_uvw[1] ) < _grid->_tol ) {
2673       facets[ nbFacets++ ] = SMESH_Block::ID_Fx0z;
2674       egdeMask |= Y;
2675     }
2676     else if ( Abs( _grid->_coords[1][ _j+1 ] - ip->_uvw[1] ) < _grid->_tol ) {
2677       facets[ nbFacets++ ] = SMESH_Block::ID_Fx1z;
2678       vertex   |= Y;
2679       egdeMask |= Y;
2680     }
2681     if ( Abs( _grid->_coords[2][ _k   ] - ip->_uvw[2] ) < _grid->_tol ) {
2682       facets[ nbFacets++ ] = SMESH_Block::ID_Fxy0;
2683       egdeMask |= Z;
2684     }
2685     else if ( Abs( _grid->_coords[2][ _k+1 ] - ip->_uvw[2] ) < _grid->_tol ) {
2686       facets[ nbFacets++ ] = SMESH_Block::ID_Fxy1;
2687       vertex   |= Z;
2688       egdeMask |= Z;
2689     }
2690
2691     switch ( nbFacets )
2692     {
2693     case 0: sub = 0;         break;
2694     case 1: sub = facets[0]; break;
2695     case 2: {
2696       const int edge [3][8] = {
2697         { SMESH_Block::ID_E00z, SMESH_Block::ID_E10z,
2698           SMESH_Block::ID_E01z, SMESH_Block::ID_E11z },
2699         { SMESH_Block::ID_E0y0, SMESH_Block::ID_E1y0, 0, 0,
2700           SMESH_Block::ID_E0y1, SMESH_Block::ID_E1y1 },
2701         { SMESH_Block::ID_Ex00, 0, SMESH_Block::ID_Ex10, 0,
2702           SMESH_Block::ID_Ex01, 0, SMESH_Block::ID_Ex11 }
2703       };
2704       switch ( egdeMask ) {
2705       case X | Y: sub = edge[ 0 ][ vertex ]; break;
2706       case X | Z: sub = edge[ 1 ][ vertex ]; break;
2707       default:    sub = edge[ 2 ][ vertex ];
2708       }
2709       break;
2710     }
2711     //case 3:
2712     default:
2713       sub = vertex + SMESH_Block::ID_FirstV;
2714     }
2715
2716     return nbFacets;
2717   }
2718   //================================================================================
2719   /*!
2720    * \brief Adds intersection with an EDGE
2721    */
2722   bool Hexahedron::addIntersection( const E_IntersectPoint& ip,
2723                                     vector< Hexahedron* >&  hexes,
2724                                     int ijk[], int dIJK[] )
2725   {
2726     bool added = false;
2727
2728     size_t hexIndex[4] = {
2729       _grid->CellIndex( ijk[0], ijk[1], ijk[2] ),
2730       dIJK[0] ? _grid->CellIndex( ijk[0]+dIJK[0], ijk[1], ijk[2] ) : -1,
2731       dIJK[1] ? _grid->CellIndex( ijk[0], ijk[1]+dIJK[1], ijk[2] ) : -1,
2732       dIJK[2] ? _grid->CellIndex( ijk[0], ijk[1], ijk[2]+dIJK[2] ) : -1
2733     };
2734     for ( int i = 0; i < 4; ++i )
2735     {
2736       if ( /*0 <= hexIndex[i] &&*/ hexIndex[i] < hexes.size() && hexes[ hexIndex[i] ] )
2737       {
2738         Hexahedron* h = hexes[ hexIndex[i] ];
2739         // check if ip is really inside the hex
2740 #ifdef _DEBUG_
2741         if ( h->isOutParam( ip._uvw ))
2742           throw SALOME_Exception("ip outside a hex");
2743 #endif
2744         h->_eIntPoints.push_back( & ip );
2745         added = true;
2746       }
2747     }
2748     return added;
2749   }
2750   //================================================================================
2751   /*!
2752    * \brief Finds nodes at a path from one node to another via intersections with EDGEs
2753    */
2754   bool Hexahedron::findChain( _Node*          n1,
2755                               _Node*          n2,
2756                               _Face&          quad,
2757                               vector<_Node*>& chn )
2758   {
2759     chn.clear();
2760     chn.push_back( n1 );
2761     for ( size_t iP = 0; iP < quad._eIntNodes.size(); ++iP )
2762       if ( !quad._eIntNodes[ iP ]->IsUsedInFace( &quad ) &&
2763            n1->IsLinked( quad._eIntNodes[ iP ]->_intPoint ) &&
2764            n2->IsLinked( quad._eIntNodes[ iP ]->_intPoint ))
2765       {
2766         chn.push_back( quad._eIntNodes[ iP ]);
2767         chn.push_back( n2 );
2768         quad._eIntNodes[ iP ]->_usedInFace = &quad;
2769         return true;
2770       }
2771     bool found;
2772     do
2773     {
2774       found = false;
2775       for ( size_t iP = 0; iP < quad._eIntNodes.size(); ++iP )
2776         if ( !quad._eIntNodes[ iP ]->IsUsedInFace( &quad ) &&
2777              chn.back()->IsLinked( quad._eIntNodes[ iP ]->_intPoint ))
2778         {
2779           chn.push_back( quad._eIntNodes[ iP ]);
2780           found = quad._eIntNodes[ iP ]->_usedInFace = &quad;
2781           break;
2782         }
2783     } while ( found && ! chn.back()->IsLinked( n2->_intPoint ) );
2784
2785     if ( chn.back() != n2 && chn.back()->IsLinked( n2->_intPoint ))
2786       chn.push_back( n2 );
2787
2788     return chn.size() > 1;
2789   }
2790   //================================================================================
2791   /*!
2792    * \brief Try to heal a polygon whose ends are not connected
2793    */
2794   bool Hexahedron::closePolygon( _Face* polygon, vector<_Node*>& chainNodes ) const
2795   {
2796     int i = -1, nbLinks = polygon->_links.size();
2797     if ( nbLinks < 3 )
2798       return false;
2799     vector< _OrientedLink > newLinks;
2800     // find a node lying on the same FACE as the last one
2801     _Node*   node = polygon->_links.back().LastNode();
2802     int avoidFace = node->IsLinked( polygon->_links.back().FirstNode()->_intPoint );
2803     for ( i = nbLinks - 2; i >= 0; --i )
2804       if ( node->IsLinked( polygon->_links[i].FirstNode()->_intPoint, avoidFace ))
2805         break;
2806     if ( i >= 0 )
2807     {
2808       for ( ; i < nbLinks; ++i )
2809         newLinks.push_back( polygon->_links[i] );
2810     }
2811     else
2812     {
2813       // find a node lying on the same FACE as the first one
2814       node      = polygon->_links[0].FirstNode();
2815       avoidFace = node->IsLinked( polygon->_links[0].LastNode()->_intPoint );
2816       for ( i = 1; i < nbLinks; ++i )
2817         if ( node->IsLinked( polygon->_links[i].LastNode()->_intPoint, avoidFace ))
2818           break;
2819       if ( i < nbLinks )
2820         for ( nbLinks = i + 1, i = 0; i < nbLinks; ++i )
2821           newLinks.push_back( polygon->_links[i] );
2822     }
2823     if ( newLinks.size() > 1 )
2824     {
2825       polygon->_links.swap( newLinks );
2826       chainNodes.clear();
2827       chainNodes.push_back( polygon->_links.back().LastNode() );
2828       chainNodes.push_back( polygon->_links[0].FirstNode() );
2829       return true;
2830     }
2831     return false;
2832   }
2833   //================================================================================
2834   /*!
2835    * \brief Finds nodes on the same EDGE as the first node of avoidSplit.
2836    *
2837    * This function is for a case where an EDGE lies on a quad which lies on a FACE
2838    * so that a part of quad in ON and another part in IN
2839    */
2840   bool Hexahedron::findChainOnEdge( const vector< _OrientedLink >& splits,
2841                                     const _OrientedLink&           prevSplit,
2842                                     const _OrientedLink&           avoidSplit,
2843                                     size_t &                       iS,
2844                                     _Face&                         quad,
2845                                     vector<_Node*>&                chn )
2846   {
2847     if ( !isImplementEdges() )
2848       return false;
2849
2850     _Node* pn1 = prevSplit.FirstNode();
2851     _Node* pn2 = prevSplit.LastNode();
2852     int avoidFace = pn1->IsLinked( pn2->_intPoint ); // FACE under the quad
2853     if ( avoidFace < 1 && pn1->_intPoint )
2854       return false;
2855
2856     _Node* n, *stopNode = avoidSplit.LastNode();
2857
2858     chn.clear();
2859     if ( !quad._eIntNodes.empty() )
2860     {
2861       chn.push_back( pn2 );
2862       bool found;
2863       do
2864       {
2865         found = false;
2866         for ( size_t iP = 0; iP < quad._eIntNodes.size(); ++iP )
2867           if (( !quad._eIntNodes[ iP ]->IsUsedInFace( &quad )) &&
2868               ( chn.back()->IsLinked( quad._eIntNodes[ iP ]->_intPoint, avoidFace )) &&
2869               ( !avoidFace || quad._eIntNodes[ iP ]->IsOnFace( avoidFace )))
2870           {
2871             chn.push_back( quad._eIntNodes[ iP ]);
2872             found = quad._eIntNodes[ iP ]->_usedInFace = &quad;
2873             break;
2874           }
2875       } while ( found );
2876       pn2 = chn.back();
2877     }
2878
2879     int i;
2880     for ( i = splits.size()-1; i >= 0; --i )
2881     {
2882       if ( !splits[i] )
2883         continue;
2884
2885       n = splits[i].LastNode();
2886       if ( n == stopNode )
2887         break;
2888       if (( n != pn1 ) &&
2889           ( n->IsLinked( pn2->_intPoint, avoidFace )) &&
2890           ( !avoidFace || n->IsOnFace( avoidFace )))
2891         break;
2892
2893       n = splits[i].FirstNode();
2894       if ( n == stopNode )
2895         break;
2896       if (( n->IsLinked( pn2->_intPoint, avoidFace )) &&
2897           ( !avoidFace || n->IsOnFace( avoidFace )))
2898         break;
2899       n = 0;
2900     }
2901     if ( n && n != stopNode)
2902     {
2903       if ( chn.empty() )
2904         chn.push_back( pn2 );
2905       chn.push_back( n );
2906       iS = i-1;
2907       return true;
2908     }
2909     return false;
2910   }
2911   //================================================================================
2912   /*!
2913    * \brief Checks transition at the ginen intersection node of a link
2914    */
2915   bool Hexahedron::isOutPoint( _Link& link, int iP, SMESH_MesherHelper& helper ) const
2916   {
2917     bool isOut = false;
2918
2919     const bool moreIntPoints = ( iP+1 < link._fIntPoints.size() );
2920
2921     // get 2 _Node's
2922     _Node* n1 = link._fIntNodes[ iP ];
2923     if ( !n1->Node() )
2924       n1 = link._nodes[0];
2925     _Node* n2 = moreIntPoints ? link._fIntNodes[ iP+1 ] : 0;
2926     if ( !n2 || !n2->Node() )
2927       n2 = link._nodes[1];
2928     if ( !n2->Node() )
2929       return true;
2930
2931     // get all FACEs under n1 and n2
2932     set< TGeomID > faceIDs;
2933     if ( moreIntPoints ) faceIDs.insert( link._fIntPoints[iP+1]->_faceIDs.begin(),
2934                                          link._fIntPoints[iP+1]->_faceIDs.end() );
2935     if ( n2->_intPoint ) faceIDs.insert( n2->_intPoint->_faceIDs.begin(),
2936                                          n2->_intPoint->_faceIDs.end() );
2937     if ( faceIDs.empty() )
2938       return false; // n2 is inside
2939     if ( n1->_intPoint ) faceIDs.insert( n1->_intPoint->_faceIDs.begin(),
2940                                          n1->_intPoint->_faceIDs.end() );
2941     faceIDs.insert( link._fIntPoints[iP]->_faceIDs.begin(),
2942                     link._fIntPoints[iP]->_faceIDs.end() );
2943
2944     // get a point between 2 nodes
2945     gp_Pnt p1      = n1->Point();
2946     gp_Pnt p2      = n2->Point();
2947     gp_Pnt pOnLink = 0.8 * p1.XYZ() + 0.2 * p2.XYZ();
2948
2949     TopLoc_Location loc;
2950
2951     set< TGeomID >::iterator faceID = faceIDs.begin();
2952     for ( ; faceID != faceIDs.end(); ++faceID )
2953     {
2954       // project pOnLink on a FACE
2955       if ( *faceID < 1 ) continue;
2956       const TopoDS_Face& face = TopoDS::Face( _grid->_shapes( *faceID ));
2957       GeomAPI_ProjectPointOnSurf& proj =
2958         helper.GetProjector( face, loc, 0.1*_grid->_tol );
2959       gp_Pnt testPnt = pOnLink.Transformed( loc.Transformation().Inverted() );
2960       proj.Perform( testPnt );
2961       if ( proj.IsDone() && proj.NbPoints() > 0 )       
2962       {
2963         Quantity_Parameter u,v;
2964         proj.LowerDistanceParameters( u,v );
2965
2966         if ( proj.LowerDistance() <= 0.1 * _grid->_tol )
2967         {
2968           isOut = false;
2969         }
2970         else
2971         {
2972           // find isOut by normals
2973           gp_Dir normal;
2974           if ( GeomLib::NormEstim( BRep_Tool::Surface( face, loc ),
2975                                    gp_Pnt2d( u,v ),
2976                                    0.1*_grid->_tol,
2977                                    normal ) < 3 )
2978           {
2979             if ( face.Orientation() == TopAbs_REVERSED )
2980               normal.Reverse();
2981             gp_Vec v( proj.NearestPoint(), testPnt );
2982             isOut = ( v * normal > 0 );
2983           }
2984         }
2985         if ( !isOut )
2986         {
2987           // classify a projection
2988           if ( !n1->IsOnFace( *faceID ) || !n2->IsOnFace( *faceID ))
2989           {
2990             BRepTopAdaptor_FClass2d cls( face, Precision::Confusion() );
2991             TopAbs_State state = cls.Perform( gp_Pnt2d( u,v ));
2992             if ( state == TopAbs_OUT )
2993             {
2994               isOut = true;
2995               continue;
2996             }
2997           }
2998           return false;
2999         }
3000       }
3001     }
3002     return isOut;
3003   }
3004   //================================================================================
3005   /*!
3006    * \brief Sort nodes on a FACE
3007    */
3008   void Hexahedron::sortVertexNodes(vector<_Node*>& nodes, _Node* curNode, TGeomID faceID)
3009   {
3010     if ( nodes.size() > 20 ) return;
3011
3012     // get shapes under nodes
3013     TGeomID nShapeIds[20], *nShapeIdsEnd = &nShapeIds[0] + nodes.size();
3014     for ( size_t i = 0; i < nodes.size(); ++i )
3015       if ( !( nShapeIds[i] = nodes[i]->ShapeID() ))
3016         return;
3017
3018     // get shapes of the FACE
3019     const TopoDS_Face&  face = TopoDS::Face( _grid->_shapes( faceID ));
3020     list< TopoDS_Edge > edges;
3021     list< int >         nbEdges;
3022     int nbW = SMESH_Block::GetOrderedEdges (face, edges, nbEdges);
3023     if ( nbW > 1 ) {
3024       // select a WIRE
3025       list< TopoDS_Edge >::iterator e = edges.begin(), eEnd = e;
3026       list< int >::iterator nE = nbEdges.begin();
3027       for ( ; nbW ; ++nE, --nbW )
3028       {
3029         std::advance( eEnd, *nE );
3030         for ( ; e != eEnd; ++e )
3031           for ( int i = 0; i < 2; ++i )
3032           {
3033             TGeomID id = i==0 ?
3034               _grid->_shapes.FindIndex( *e ) :
3035               _grid->_shapes.FindIndex( SMESH_MesherHelper::IthVertex( 0, *e ));
3036             if (( id > 0 ) &&
3037                 ( std::find( &nShapeIds[0], nShapeIdsEnd, id ) != nShapeIdsEnd ))
3038             {
3039               edges.erase( eEnd, edges.end() ); // remove rest wires
3040               e = eEnd;
3041               nbW = 0;
3042               break;
3043             }
3044           }
3045         if ( nbW > 0 )
3046           edges.erase( edges.begin(), eEnd ); // remove a current wire
3047       }
3048     }
3049     // rotate edges to have the first one at least partially out of the hexa
3050     list< TopoDS_Edge >::iterator e = edges.begin(), eMidOut = edges.end();
3051     for ( ; e != edges.end(); ++e )
3052     {
3053       if ( !_grid->_shapes.FindIndex( *e ))
3054         continue;
3055       bool isOut = false;
3056       gp_Pnt p;
3057       double uvw[3], f,l;
3058       for ( int i = 0; i < 2 && !isOut; ++i )
3059       {
3060         if ( i == 0 )
3061         {
3062           TopoDS_Vertex v = SMESH_MesherHelper::IthVertex( 0, *e );
3063           p = BRep_Tool::Pnt( v );
3064         }
3065         else if ( eMidOut == edges.end() )
3066         {
3067           TopLoc_Location loc;
3068           Handle(Geom_Curve) c = BRep_Tool::Curve( *e, loc, f, l);
3069           if ( c.IsNull() ) break;
3070           p = c->Value( 0.5 * ( f + l )).Transformed( loc );
3071         }
3072         else
3073         {
3074           continue;
3075         }
3076
3077         _grid->ComputeUVW( p.XYZ(), uvw );
3078         if ( isOutParam( uvw ))
3079         {
3080           if ( i == 0 )
3081             isOut = true;
3082           else
3083             eMidOut = e;
3084         }
3085       }
3086       if ( isOut )
3087         break;
3088     }
3089     if ( e != edges.end() )
3090       edges.splice( edges.end(), edges, edges.begin(), e );
3091     else if ( eMidOut != edges.end() )
3092       edges.splice( edges.end(), edges, edges.begin(), eMidOut );
3093
3094     // sort nodes accoring to the order of edges
3095     _Node*  orderNodes   [20];
3096     TGeomID orderShapeIDs[20];
3097     int nbN = 0;
3098     TGeomID id, *pID;
3099     for ( e = edges.begin(); e != edges.end(); ++e )
3100     {
3101       if (( id = _grid->_shapes.FindIndex( SMESH_MesherHelper::IthVertex( 0, *e ))) &&
3102           (( pID = std::find( &nShapeIds[0], nShapeIdsEnd, id )) != nShapeIdsEnd ))
3103       {
3104         orderShapeIDs[ nbN ] = id;
3105         orderNodes   [ nbN++ ] = nodes[ pID - &nShapeIds[0] ];
3106         *pID = -1;
3107       }
3108       if (( id = _grid->_shapes.FindIndex( *e )) &&
3109           (( pID = std::find( &nShapeIds[0], nShapeIdsEnd, id )) != nShapeIdsEnd ))
3110       {
3111         orderShapeIDs[ nbN ] = id;
3112         orderNodes   [ nbN++ ] = nodes[ pID - &nShapeIds[0] ];
3113         *pID = -1;
3114       }
3115     }
3116     if ( nbN != nodes.size() )
3117       return;
3118
3119     bool reverse = ( orderNodes[0    ]->Point().SquareDistance( curNode->Point() ) >
3120                      orderNodes[nbN-1]->Point().SquareDistance( curNode->Point() ));
3121
3122     for ( size_t i = 0; i < nodes.size(); ++i )
3123       nodes[ i ] = orderNodes[ reverse ? nbN-1-i : i ];
3124   }
3125
3126   //================================================================================
3127   /*!
3128    * \brief Adds computed elements to the mesh
3129    */
3130   int Hexahedron::addElements(SMESH_MesherHelper& helper)
3131   {
3132     int nbAdded = 0;
3133     // add elements resulted from hexahedron intersection
3134     //for ( size_t i = 0; i < _volumeDefs.size(); ++i )
3135     {
3136       vector< const SMDS_MeshNode* > nodes( _volumeDefs._nodes.size() );
3137       for ( size_t iN = 0; iN < nodes.size(); ++iN )
3138         if ( !( nodes[iN] = _volumeDefs._nodes[iN]->Node() ))
3139         {
3140           if ( const E_IntersectPoint* eip = _volumeDefs._nodes[iN]->EdgeIntPnt() )
3141             nodes[iN] = _volumeDefs._nodes[iN]->_intPoint->_node =
3142               helper.AddNode( eip->_point.X(),
3143                               eip->_point.Y(),
3144                               eip->_point.Z() );
3145           else
3146             throw SALOME_Exception("Bug: no node at intersection point");
3147         }
3148
3149       if ( !_volumeDefs._quantities.empty() )
3150       {
3151         helper.AddPolyhedralVolume( nodes, _volumeDefs._quantities );
3152       }
3153       else
3154       {
3155         switch ( nodes.size() )
3156         {
3157         case 8: helper.AddVolume( nodes[0],nodes[1],nodes[2],nodes[3],
3158                                   nodes[4],nodes[5],nodes[6],nodes[7] );
3159           break;
3160         case 4: helper.AddVolume( nodes[0],nodes[1],nodes[2],nodes[3] );
3161           break;
3162         case 6: helper.AddVolume( nodes[0],nodes[1],nodes[2],nodes[3], nodes[4],nodes[5] );
3163           break;
3164         case 5:
3165           helper.AddVolume( nodes[0],nodes[1],nodes[2],nodes[3],nodes[4] );
3166           break;
3167         }
3168       }
3169       nbAdded += int ( _volumeDefs._nodes.size() > 0 );
3170     }
3171
3172     return nbAdded;
3173   }
3174   //================================================================================
3175   /*!
3176    * \brief Return true if the element is in a hole
3177    */
3178   bool Hexahedron::isInHole() const
3179   {
3180     if ( !_vIntNodes.empty() )
3181       return false;
3182
3183     const int ijk[3] = { _i, _j, _k };
3184     F_IntersectPoint curIntPnt;
3185
3186     // consider a cell to be in a hole if all links in any direction
3187     // comes OUT of geometry
3188     for ( int iDir = 0; iDir < 3; ++iDir )
3189     {
3190       const vector<double>& coords = _grid->_coords[ iDir ];
3191       LineIndexer               li = _grid->GetLineIndexer( iDir );
3192       li.SetIJK( _i,_j,_k );
3193       size_t lineIndex[4] = { li.LineIndex  (),
3194                               li.LineIndex10(),
3195                               li.LineIndex01(),
3196                               li.LineIndex11() };
3197       bool allLinksOut = true, hasLinks = false;
3198       for ( int iL = 0; iL < 4 && allLinksOut; ++iL ) // loop on 4 links parallel to iDir
3199       {
3200         const _Link& link = _hexLinks[ iL + 4*iDir ];
3201         // check transition of the first node of a link
3202         const F_IntersectPoint* firstIntPnt = 0;
3203         if ( link._nodes[0]->Node() ) // 1st node is a hexa corner
3204         {
3205           curIntPnt._paramOnLine = coords[ ijk[ iDir ]] - coords[0];
3206           const GridLine& line = _grid->_lines[ iDir ][ lineIndex[ iL ]];
3207           multiset< F_IntersectPoint >::const_iterator ip =
3208             line._intPoints.upper_bound( curIntPnt );
3209           --ip;
3210           firstIntPnt = &(*ip);
3211         }
3212         else if ( !link._fIntPoints.empty() )
3213         {
3214           firstIntPnt = link._fIntPoints[0];
3215         }
3216
3217         if ( firstIntPnt )
3218         {
3219           hasLinks = true;
3220           allLinksOut = ( firstIntPnt->_transition == Trans_OUT );
3221         }
3222       }
3223       if ( hasLinks && allLinksOut )
3224         return true;
3225     }
3226     return false;
3227   }
3228
3229   //================================================================================
3230   /*!
3231    * \brief Return true if a polyhedron passes _sizeThreshold criterion
3232    */
3233   bool Hexahedron::checkPolyhedronSize() const
3234   {
3235     double volume = 0;
3236     for ( size_t iP = 0; iP < _polygons.size(); ++iP )
3237     {
3238       const _Face& polygon = _polygons[iP];
3239       if ( polygon._links.empty() )
3240         continue;
3241       gp_XYZ area (0,0,0);
3242       gp_XYZ p1 = polygon._links[ 0 ].FirstNode()->Point().XYZ();
3243       for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
3244       {
3245         gp_XYZ p2 = polygon._links[ iL ].LastNode()->Point().XYZ();
3246         area += p1 ^ p2;
3247         p1 = p2;
3248       }
3249       volume += p1 * area;
3250     }
3251     volume /= 6;
3252
3253     double initVolume = _sideLength[0] * _sideLength[1] * _sideLength[2];
3254
3255     return volume > initVolume / _sizeThreshold;
3256   }
3257   //================================================================================
3258   /*!
3259    * \brief Tries to create a hexahedron
3260    */
3261   bool Hexahedron::addHexa()
3262   {
3263     int nbQuad = 0, iQuad = -1;
3264     for ( size_t i = 0; i < _polygons.size(); ++i )
3265     {
3266       if ( _polygons[i]._links.empty() )
3267         continue;
3268       if ( _polygons[i]._links.size() != 4 )
3269         return false;
3270       ++nbQuad;
3271       if ( iQuad < 0 )
3272         iQuad = i;
3273     }
3274     if ( nbQuad != 6 )
3275       return false;
3276
3277     _Node* nodes[8];
3278     int nbN = 0;
3279     for ( int iL = 0; iL < 4; ++iL )
3280     {
3281       // a base node
3282       nodes[iL] = _polygons[iQuad]._links[iL].FirstNode();
3283       ++nbN;
3284
3285       // find a top node above the base node
3286       _Link* link = _polygons[iQuad]._links[iL]._link;
3287       if ( !link->_faces[0] || !link->_faces[1] )
3288         return debugDumpLink( link );
3289       // a quadrangle sharing <link> with _polygons[iQuad]
3290       _Face* quad = link->_faces[ bool( link->_faces[0] == & _polygons[iQuad] )];
3291       for ( int i = 0; i < 4; ++i )
3292         if ( quad->_links[i]._link == link )
3293         {
3294           // 1st node of a link opposite to <link> in <quad>
3295           nodes[iL+4] = quad->_links[(i+2)%4].FirstNode();
3296           ++nbN;
3297           break;
3298         }
3299     }
3300     if ( nbN == 8 )
3301       _volumeDefs.set( &nodes[0], 8 );
3302
3303     return nbN == 8;
3304   }
3305   //================================================================================
3306   /*!
3307    * \brief Tries to create a tetrahedron
3308    */
3309   bool Hexahedron::addTetra()
3310   {
3311     int iTria = -1;
3312     for ( size_t i = 0; i < _polygons.size() && iTria < 0; ++i )
3313       if ( _polygons[i]._links.size() == 3 )
3314         iTria = i;
3315     if ( iTria < 0 )
3316       return false;
3317
3318     _Node* nodes[4];
3319     nodes[0] = _polygons[iTria]._links[0].FirstNode();
3320     nodes[1] = _polygons[iTria]._links[1].FirstNode();
3321     nodes[2] = _polygons[iTria]._links[2].FirstNode();
3322
3323     _Link* link = _polygons[iTria]._links[0]._link;
3324     if ( !link->_faces[0] || !link->_faces[1] )
3325       return debugDumpLink( link );
3326
3327     // a triangle sharing <link> with _polygons[0]
3328     _Face* tria = link->_faces[ bool( link->_faces[0] == & _polygons[iTria] )];
3329     for ( int i = 0; i < 3; ++i )
3330       if ( tria->_links[i]._link == link )
3331       {
3332         nodes[3] = tria->_links[(i+1)%3].LastNode();
3333         _volumeDefs.set( &nodes[0], 4 );
3334         return true;
3335       }
3336
3337     return false;
3338   }
3339   //================================================================================
3340   /*!
3341    * \brief Tries to create a pentahedron
3342    */
3343   bool Hexahedron::addPenta()
3344   {
3345     // find a base triangular face
3346     int iTri = -1;
3347     for ( int iF = 0; iF < 5 && iTri < 0; ++iF )
3348       if ( _polygons[ iF ]._links.size() == 3 )
3349         iTri = iF;
3350     if ( iTri < 0 ) return false;
3351
3352     // find nodes
3353     _Node* nodes[6];
3354     int nbN = 0;
3355     for ( int iL = 0; iL < 3; ++iL )
3356     {
3357       // a base node
3358       nodes[iL] = _polygons[ iTri ]._links[iL].FirstNode();
3359       ++nbN;
3360
3361       // find a top node above the base node
3362       _Link* link = _polygons[ iTri ]._links[iL]._link;
3363       if ( !link->_faces[0] || !link->_faces[1] )
3364         return debugDumpLink( link );
3365       // a quadrangle sharing <link> with a base triangle
3366       _Face* quad = link->_faces[ bool( link->_faces[0] == & _polygons[ iTri ] )];
3367       if ( quad->_links.size() != 4 ) return false;
3368       for ( int i = 0; i < 4; ++i )
3369         if ( quad->_links[i]._link == link )
3370         {
3371           // 1st node of a link opposite to <link> in <quad>
3372           nodes[iL+3] = quad->_links[(i+2)%4].FirstNode();
3373           ++nbN;
3374           break;
3375         }
3376     }
3377     if ( nbN == 6 )
3378       _volumeDefs.set( &nodes[0], 6 );
3379
3380     return ( nbN == 6 );
3381   }
3382   //================================================================================
3383   /*!
3384    * \brief Tries to create a pyramid
3385    */
3386   bool Hexahedron::addPyra()
3387   {
3388     // find a base quadrangle
3389     int iQuad = -1;
3390     for ( int iF = 0; iF < 5 && iQuad < 0; ++iF )
3391       if ( _polygons[ iF ]._links.size() == 4 )
3392         iQuad = iF;
3393     if ( iQuad < 0 ) return false;
3394
3395     // find nodes
3396     _Node* nodes[5];
3397     nodes[0] = _polygons[iQuad]._links[0].FirstNode();
3398     nodes[1] = _polygons[iQuad]._links[1].FirstNode();
3399     nodes[2] = _polygons[iQuad]._links[2].FirstNode();
3400     nodes[3] = _polygons[iQuad]._links[3].FirstNode();
3401
3402     _Link* link = _polygons[iQuad]._links[0]._link;
3403     if ( !link->_faces[0] || !link->_faces[1] )
3404       return debugDumpLink( link );
3405
3406     // a triangle sharing <link> with a base quadrangle
3407     _Face* tria = link->_faces[ bool( link->_faces[0] == & _polygons[ iQuad ] )];
3408     if ( tria->_links.size() != 3 ) return false;
3409     for ( int i = 0; i < 3; ++i )
3410       if ( tria->_links[i]._link == link )
3411       {
3412         nodes[4] = tria->_links[(i+1)%3].LastNode();
3413         _volumeDefs.set( &nodes[0], 5 );
3414         return true;
3415       }
3416
3417     return false;
3418   }
3419   //================================================================================
3420   /*!
3421    * \brief Dump a link and return \c false
3422    */
3423   bool Hexahedron::debugDumpLink( Hexahedron::_Link* link )
3424   {
3425 #ifdef _DEBUG_
3426     gp_Pnt p1 = link->_nodes[0]->Point(), p2 = link->_nodes[1]->Point();
3427     cout << "BUG: not shared link. IKJ = ( "<< _i << " " << _j << " " << _k << " )" << endl
3428          << "n1 (" << p1.X() << ", "<< p1.Y() << ", "<< p1.Z() << " )" << endl
3429          << "n2 (" << p2.X() << ", "<< p2.Y() << ", "<< p2.Z() << " )" << endl;
3430 #endif
3431     return false;
3432   }
3433   //================================================================================
3434   /*!
3435    * \brief Classify a point by grid paremeters
3436    */
3437   bool Hexahedron::isOutParam(const double uvw[3]) const
3438   {
3439     return (( _grid->_coords[0][ _i   ] - _grid->_tol > uvw[0] ) ||
3440             ( _grid->_coords[0][ _i+1 ] + _grid->_tol < uvw[0] ) ||
3441             ( _grid->_coords[1][ _j   ] - _grid->_tol > uvw[1] ) ||
3442             ( _grid->_coords[1][ _j+1 ] + _grid->_tol < uvw[1] ) ||
3443             ( _grid->_coords[2][ _k   ] - _grid->_tol > uvw[2] ) ||
3444             ( _grid->_coords[2][ _k+1 ] + _grid->_tol < uvw[2] ));
3445   }
3446
3447   //================================================================================
3448   /*!
3449    * \brief computes exact bounding box with axes parallel to given ones
3450    */
3451   //================================================================================
3452
3453   void getExactBndBox( const vector< TopoDS_Shape >& faceVec,
3454                        const double*                 axesDirs,
3455                        Bnd_Box&                      shapeBox )
3456   {
3457     BRep_Builder b;
3458     TopoDS_Compound allFacesComp;
3459     b.MakeCompound( allFacesComp );
3460     for ( size_t iF = 0; iF < faceVec.size(); ++iF )
3461       b.Add( allFacesComp, faceVec[ iF ] );
3462
3463     double sP[6]; // aXmin, aYmin, aZmin, aXmax, aYmax, aZmax
3464     shapeBox.Get(sP[0],sP[1],sP[2],sP[3],sP[4],sP[5]);
3465     double farDist = 0;
3466     for ( int i = 0; i < 6; ++i )
3467       farDist = Max( farDist, 10 * sP[i] );
3468
3469     gp_XYZ axis[3] = { gp_XYZ( axesDirs[0], axesDirs[1], axesDirs[2] ),
3470                        gp_XYZ( axesDirs[3], axesDirs[4], axesDirs[5] ),
3471                        gp_XYZ( axesDirs[6], axesDirs[7], axesDirs[8] ) };
3472     axis[0].Normalize();
3473     axis[1].Normalize();
3474     axis[2].Normalize();
3475
3476     gp_Mat basis( axis[0], axis[1], axis[2] );
3477     gp_Mat bi = basis.Inverted();
3478
3479     gp_Pnt pMin, pMax;
3480     for ( int iDir = 0; iDir < 3; ++iDir )
3481     {
3482       gp_XYZ axis0 = axis[ iDir ];
3483       gp_XYZ axis1 = axis[ ( iDir + 1 ) % 3 ];
3484       gp_XYZ axis2 = axis[ ( iDir + 2 ) % 3 ];
3485       for ( int isMax = 0; isMax < 2; ++isMax )
3486       {
3487         double shift = isMax ? farDist : -farDist;
3488         gp_XYZ orig = shift * axis0;
3489         gp_XYZ norm = axis1 ^ axis2;
3490         gp_Pln pln( orig, norm );
3491         norm = pln.Axis().Direction().XYZ();
3492         BRepBuilderAPI_MakeFace plane( pln, -farDist, farDist, -farDist, farDist );
3493
3494         gp_Pnt& pAxis = isMax ? pMax : pMin;
3495         gp_Pnt pPlane, pFaces;
3496         double dist = GEOMUtils::GetMinDistance( plane, allFacesComp, pPlane, pFaces );
3497         if ( dist < 0 )
3498         {
3499           Bnd_B3d bb;
3500           gp_XYZ corner;
3501           for ( int i = 0; i < 2; ++i ) {
3502             corner.SetCoord( 1, sP[ i*3 ]);
3503             for ( int j = 0; j < 2; ++j ) {
3504               corner.SetCoord( 2, sP[ i*3 + 1 ]);
3505               for ( int k = 0; k < 2; ++k )
3506               {
3507                 corner.SetCoord( 3, sP[ i*3 + 2 ]);
3508                 corner *= bi;
3509                 bb.Add( corner );
3510               }
3511             }
3512           }
3513           corner = isMax ? bb.CornerMax() : bb.CornerMin();
3514           pAxis.SetCoord( iDir+1, corner.Coord( iDir+1 ));
3515         }
3516         else
3517         {
3518           gp_XYZ pf = pFaces.XYZ() * bi;
3519           pAxis.SetCoord( iDir+1, pf.Coord( iDir+1 ) );
3520         }
3521       }
3522     } // loop on 3 axes
3523
3524     shapeBox.SetVoid();
3525     shapeBox.Add( pMin );
3526     shapeBox.Add( pMax );
3527
3528     return;
3529   }
3530
3531 } // namespace
3532
3533 //=============================================================================
3534 /*!
3535  * \brief Generates 3D structured Cartesian mesh in the internal part of
3536  * solid shapes and polyhedral volumes near the shape boundary.
3537  *  \param theMesh - mesh to fill in
3538  *  \param theShape - a compound of all SOLIDs to mesh
3539  *  \retval bool - true in case of success
3540  */
3541 //=============================================================================
3542
3543 bool StdMeshers_Cartesian_3D::Compute(SMESH_Mesh &         theMesh,
3544                                       const TopoDS_Shape & theShape)
3545 {
3546   // The algorithm generates the mesh in following steps:
3547
3548   // 1) Intersection of grid lines with the geometry boundary.
3549   // This step allows to find out if a given node of the initial grid is
3550   // inside or outside the geometry.
3551
3552   // 2) For each cell of the grid, check how many of it's nodes are outside
3553   // of the geometry boundary. Depending on a result of this check
3554   // - skip a cell, if all it's nodes are outside
3555   // - skip a cell, if it is too small according to the size threshold
3556   // - add a hexahedron in the mesh, if all nodes are inside
3557   // - add a polyhedron in the mesh, if some nodes are inside and some outside
3558
3559   _computeCanceled = false;
3560
3561   SMESH_MesherHelper helper( theMesh );
3562
3563   try
3564   {
3565     Grid grid;
3566     grid._helper = &helper;
3567
3568     vector< TopoDS_Shape > faceVec;
3569     {
3570       TopTools_MapOfShape faceMap;
3571       TopExp_Explorer fExp;
3572       for ( fExp.Init( theShape, TopAbs_FACE ); fExp.More(); fExp.Next() )
3573         if ( !faceMap.Add( fExp.Current() ))
3574           faceMap.Remove( fExp.Current() ); // remove a face shared by two solids
3575
3576       for ( fExp.ReInit(); fExp.More(); fExp.Next() )
3577         if ( faceMap.Contains( fExp.Current() ))
3578           faceVec.push_back( fExp.Current() );
3579     }
3580     vector<FaceGridIntersector> facesItersectors( faceVec.size() );
3581     map< TGeomID, vector< TGeomID > > edge2faceIDsMap;
3582     TopExp_Explorer eExp;
3583     Bnd_Box shapeBox;
3584     for ( int i = 0; i < faceVec.size(); ++i )
3585     {
3586       facesItersectors[i]._face   = TopoDS::Face    ( faceVec[i] );
3587       facesItersectors[i]._faceID = grid._shapes.Add( faceVec[i] );
3588       facesItersectors[i]._grid   = &grid;
3589       shapeBox.Add( facesItersectors[i].GetFaceBndBox() );
3590
3591       if ( _hyp->GetToAddEdges() )
3592       {
3593         helper.SetSubShape( faceVec[i] );
3594         for ( eExp.Init( faceVec[i], TopAbs_EDGE ); eExp.More(); eExp.Next() )
3595         {
3596           const TopoDS_Edge& edge = TopoDS::Edge( eExp.Current() );
3597           if ( !SMESH_Algo::isDegenerated( edge ) &&
3598                !helper.IsRealSeam( edge ))
3599             edge2faceIDsMap[ grid._shapes.Add( edge )].push_back( facesItersectors[i]._faceID );
3600         }
3601       }
3602     }
3603
3604     getExactBndBox( faceVec, _hyp->GetAxisDirs(), shapeBox );
3605
3606     vector<double> xCoords, yCoords, zCoords;
3607     _hyp->GetCoordinates( xCoords, yCoords, zCoords, shapeBox );
3608
3609     grid.SetCoordinates( xCoords, yCoords, zCoords, _hyp->GetAxisDirs(), shapeBox );
3610
3611     if ( _computeCanceled ) return false;
3612
3613 #ifdef WITH_TBB
3614     { // copy partner faces and curves of not thread-safe types
3615       set< const Standard_Transient* > tshapes;
3616       BRepBuilderAPI_Copy copier;
3617       for ( size_t i = 0; i < facesItersectors.size(); ++i )
3618       {
3619         if ( !facesItersectors[i].IsThreadSafe(tshapes) )
3620         {
3621           copier.Perform( facesItersectors[i]._face );
3622           facesItersectors[i]._face = TopoDS::Face( copier );
3623         }
3624       }
3625     }
3626     // Intersection of grid lines with the geometry boundary.
3627     tbb::parallel_for ( tbb::blocked_range<size_t>( 0, facesItersectors.size() ),
3628                         ParallelIntersector( facesItersectors ),
3629                         tbb::simple_partitioner());
3630 #else
3631     for ( size_t i = 0; i < facesItersectors.size(); ++i )
3632       facesItersectors[i].Intersect();
3633 #endif
3634
3635     // put interesection points onto the GridLine's; this is done after intersection
3636     // to avoid contention of facesItersectors for writing into the same GridLine
3637     // in case of parallel work of facesItersectors
3638     for ( size_t i = 0; i < facesItersectors.size(); ++i )
3639       facesItersectors[i].StoreIntersections();
3640
3641     TopExp_Explorer solidExp (theShape, TopAbs_SOLID);
3642     helper.SetSubShape( solidExp.Current() );
3643     helper.SetElementsOnShape( true );
3644
3645     if ( _computeCanceled ) return false;
3646
3647     // create nodes on the geometry
3648     grid.ComputeNodes(helper);
3649
3650     if ( _computeCanceled ) return false;
3651
3652     // create volume elements
3653     Hexahedron hex( _hyp->GetSizeThreshold(), &grid );
3654     int nbAdded = hex.MakeElements( helper, edge2faceIDsMap );
3655
3656     SMESHDS_Mesh* meshDS = theMesh.GetMeshDS();
3657     if ( nbAdded > 0 )
3658     {
3659       // make all SOLIDs computed
3660       if ( SMESHDS_SubMesh* sm1 = meshDS->MeshElements( solidExp.Current()) )
3661       {
3662         SMDS_ElemIteratorPtr volIt = sm1->GetElements();
3663         for ( ; solidExp.More() && volIt->more(); solidExp.Next() )
3664         {
3665           const SMDS_MeshElement* vol = volIt->next();
3666           sm1->RemoveElement( vol, /*isElemDeleted=*/false );
3667           meshDS->SetMeshElementOnShape( vol, solidExp.Current() );
3668         }
3669       }
3670       // make other sub-shapes computed
3671       setSubmeshesComputed( theMesh, theShape );
3672     }
3673
3674     // remove free nodes
3675     if ( SMESHDS_SubMesh * smDS = meshDS->MeshElements( helper.GetSubShapeID() ))
3676     {
3677       TIDSortedNodeSet nodesToRemove;
3678       // get intersection nodes
3679       for ( int iDir = 0; iDir < 3; ++iDir )
3680       {
3681         vector< GridLine >& lines = grid._lines[ iDir ];
3682         for ( size_t i = 0; i < lines.size(); ++i )
3683         {
3684           multiset< F_IntersectPoint >::iterator ip = lines[i]._intPoints.begin();
3685           for ( ; ip != lines[i]._intPoints.end(); ++ip )
3686             if ( ip->_node && ip->_node->NbInverseElements() == 0 )
3687               nodesToRemove.insert( nodesToRemove.end(), ip->_node );
3688         }
3689       }
3690       // get grid nodes
3691       for ( size_t i = 0; i < grid._nodes.size(); ++i )
3692         if ( grid._nodes[i] && grid._nodes[i]->NbInverseElements() == 0 )
3693           nodesToRemove.insert( nodesToRemove.end(), grid._nodes[i] );
3694
3695       // do remove
3696       TIDSortedNodeSet::iterator n = nodesToRemove.begin();
3697       for ( ; n != nodesToRemove.end(); ++n )
3698         meshDS->RemoveFreeNode( *n, smDS, /*fromGroups=*/false );
3699     }
3700
3701     return nbAdded;
3702
3703   }
3704   // SMESH_ComputeError is not caught at SMESH_submesh level for an unknown reason
3705   catch ( SMESH_ComputeError& e)
3706   {
3707     return error( SMESH_ComputeErrorPtr( new SMESH_ComputeError( e )));
3708   }
3709   return false;
3710 }
3711
3712 //=============================================================================
3713 /*!
3714  *  Evaluate
3715  */
3716 //=============================================================================
3717
3718 bool StdMeshers_Cartesian_3D::Evaluate(SMESH_Mesh &         theMesh,
3719                                        const TopoDS_Shape & theShape,
3720                                        MapShapeNbElems&     theResMap)
3721 {
3722   // TODO
3723 //   std::vector<int> aResVec(SMDSEntity_Last);
3724 //   for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aResVec[i] = 0;
3725 //   if(IsQuadratic) {
3726 //     aResVec[SMDSEntity_Quad_Cartesian] = nb2d_face0 * ( nb2d/nb1d );
3727 //     int nb1d_face0_int = ( nb2d_face0*4 - nb1d ) / 2;
3728 //     aResVec[SMDSEntity_Node] = nb0d_face0 * ( 2*nb2d/nb1d - 1 ) - nb1d_face0_int * nb2d/nb1d;
3729 //   }
3730 //   else {
3731 //     aResVec[SMDSEntity_Node] = nb0d_face0 * ( nb2d/nb1d - 1 );
3732 //     aResVec[SMDSEntity_Cartesian] = nb2d_face0 * ( nb2d/nb1d );
3733 //   }
3734 //   SMESH_subMesh * sm = aMesh.GetSubMesh(aShape);
3735 //   aResMap.insert(std::make_pair(sm,aResVec));
3736
3737   return true;
3738 }
3739
3740 //=============================================================================
3741 namespace
3742 {
3743   /*!
3744    * \brief Event listener setting/unsetting _alwaysComputed flag to
3745    *        submeshes of inferior levels to prevent their computing
3746    */
3747   struct _EventListener : public SMESH_subMeshEventListener
3748   {
3749     string _algoName;
3750
3751     _EventListener(const string& algoName):
3752       SMESH_subMeshEventListener(/*isDeletable=*/true,"StdMeshers_Cartesian_3D::_EventListener"),
3753       _algoName(algoName)
3754     {}
3755     // --------------------------------------------------------------------------------
3756     // setting/unsetting _alwaysComputed flag to submeshes of inferior levels
3757     //
3758     static void setAlwaysComputed( const bool     isComputed,
3759                                    SMESH_subMesh* subMeshOfSolid)
3760     {
3761       SMESH_subMeshIteratorPtr smIt =
3762         subMeshOfSolid->getDependsOnIterator(/*includeSelf=*/false, /*complexShapeFirst=*/false);
3763       while ( smIt->more() )
3764       {
3765         SMESH_subMesh* sm = smIt->next();
3766         sm->SetIsAlwaysComputed( isComputed );
3767       }
3768       subMeshOfSolid->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
3769     }
3770
3771     // --------------------------------------------------------------------------------
3772     // unsetting _alwaysComputed flag if "Cartesian_3D" was removed
3773     //
3774     virtual void ProcessEvent(const int          event,
3775                               const int          eventType,
3776                               SMESH_subMesh*     subMeshOfSolid,
3777                               SMESH_subMeshEventListenerData* data,
3778                               const SMESH_Hypothesis*         hyp = 0)
3779     {
3780       if ( eventType == SMESH_subMesh::COMPUTE_EVENT )
3781       {
3782         setAlwaysComputed( subMeshOfSolid->GetComputeState() == SMESH_subMesh::COMPUTE_OK,
3783                            subMeshOfSolid );
3784       }
3785       else
3786       {
3787         SMESH_Algo* algo3D = subMeshOfSolid->GetAlgo();
3788         if ( !algo3D || _algoName != algo3D->GetName() )
3789           setAlwaysComputed( false, subMeshOfSolid );
3790       }
3791     }
3792
3793     // --------------------------------------------------------------------------------
3794     // set the event listener
3795     //
3796     static void SetOn( SMESH_subMesh* subMeshOfSolid, const string& algoName )
3797     {
3798       subMeshOfSolid->SetEventListener( new _EventListener( algoName ),
3799                                         /*data=*/0,
3800                                         subMeshOfSolid );
3801     }
3802
3803   }; // struct _EventListener
3804
3805 } // namespace
3806
3807 //================================================================================
3808 /*!
3809  * \brief Sets event listener to submeshes if necessary
3810  *  \param subMesh - submesh where algo is set
3811  * This method is called when a submesh gets HYP_OK algo_state.
3812  * After being set, event listener is notified on each event of a submesh.
3813  */
3814 //================================================================================
3815
3816 void StdMeshers_Cartesian_3D::SetEventListener(SMESH_subMesh* subMesh)
3817 {
3818   _EventListener::SetOn( subMesh, GetName() );
3819 }
3820
3821 //================================================================================
3822 /*!
3823  * \brief Set _alwaysComputed flag to submeshes of inferior levels to avoid their computing
3824  */
3825 //================================================================================
3826
3827 void StdMeshers_Cartesian_3D::setSubmeshesComputed(SMESH_Mesh&         theMesh,
3828                                                    const TopoDS_Shape& theShape)
3829 {
3830   for ( TopExp_Explorer soExp( theShape, TopAbs_SOLID ); soExp.More(); soExp.Next() )
3831     _EventListener::setAlwaysComputed( true, theMesh.GetSubMesh( soExp.Current() ));
3832 }
3833