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