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