Salome HOME
7e444be893672c8d92438e4a8bc527f2f06ccf0d
[modules/smesh.git] / src / StdMeshers / StdMeshers_Cartesian_3D.cxx
1 // Copyright (C) 2007-2020  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 #include "StdMeshers_CartesianParameters3D.hxx"
27
28 #include "ObjectPool.hxx"
29 #include "SMDS_MeshNode.hxx"
30 #include "SMDS_VolumeTool.hxx"
31 #include "SMESHDS_Mesh.hxx"
32 #include "SMESH_Block.hxx"
33 #include "SMESH_Comment.hxx"
34 #include "SMESH_ControlsDef.hxx"
35 #include "SMESH_Mesh.hxx"
36 #include "SMESH_MeshAlgos.hxx"
37 #include "SMESH_MeshEditor.hxx"
38 #include "SMESH_MesherHelper.hxx"
39 #include "SMESH_subMesh.hxx"
40 #include "SMESH_subMeshEventListener.hxx"
41 #include "StdMeshers_FaceSide.hxx"
42
43 #include <utilities.h>
44 #include <Utils_ExceptHandlers.hxx>
45
46 #include <GEOMUtils.hxx>
47
48 #include <BRepAdaptor_Curve.hxx>
49 #include <BRepAdaptor_Surface.hxx>
50 #include <BRepBndLib.hxx>
51 #include <BRepBuilderAPI_Copy.hxx>
52 #include <BRepBuilderAPI_MakeFace.hxx>
53 #include <BRepTools.hxx>
54 #include <BRepTopAdaptor_FClass2d.hxx>
55 #include <BRep_Builder.hxx>
56 #include <BRep_Tool.hxx>
57 #include <Bnd_B3d.hxx>
58 #include <Bnd_Box.hxx>
59 #include <ElSLib.hxx>
60 #include <GCPnts_UniformDeflection.hxx>
61 #include <Geom2d_BSplineCurve.hxx>
62 #include <Geom2d_BezierCurve.hxx>
63 #include <Geom2d_TrimmedCurve.hxx>
64 #include <GeomAPI_ProjectPointOnSurf.hxx>
65 #include <GeomLib.hxx>
66 #include <Geom_BSplineCurve.hxx>
67 #include <Geom_BSplineSurface.hxx>
68 #include <Geom_BezierCurve.hxx>
69 #include <Geom_BezierSurface.hxx>
70 #include <Geom_RectangularTrimmedSurface.hxx>
71 #include <Geom_TrimmedCurve.hxx>
72 #include <IntAna_IntConicQuad.hxx>
73 #include <IntAna_IntLinTorus.hxx>
74 #include <IntAna_Quadric.hxx>
75 #include <IntCurveSurface_TransitionOnCurve.hxx>
76 #include <IntCurvesFace_Intersector.hxx>
77 #include <Poly_Triangulation.hxx>
78 #include <Precision.hxx>
79 #include <TopExp.hxx>
80 #include <TopExp_Explorer.hxx>
81 #include <TopLoc_Location.hxx>
82 #include <TopTools_IndexedMapOfShape.hxx>
83 #include <TopTools_MapOfShape.hxx>
84 #include <TopoDS.hxx>
85 #include <TopoDS_Compound.hxx>
86 #include <TopoDS_Face.hxx>
87 #include <TopoDS_TShape.hxx>
88 #include <gp_Cone.hxx>
89 #include <gp_Cylinder.hxx>
90 #include <gp_Lin.hxx>
91 #include <gp_Pln.hxx>
92 #include <gp_Pnt2d.hxx>
93 #include <gp_Sphere.hxx>
94 #include <gp_Torus.hxx>
95
96 #include <limits>
97
98 #include <boost/container/flat_map.hpp>
99
100 //#undef WITH_TBB
101 #ifdef WITH_TBB
102
103 #ifdef WIN32
104 // See https://docs.microsoft.com/en-gb/cpp/porting/modifying-winver-and-win32-winnt?view=vs-2019
105 // Windows 10 = 0x0A00  
106 #define WINVER 0x0A00
107 #define _WIN32_WINNT 0x0A00
108 #endif
109
110 #include <tbb/parallel_for.h>
111 //#include <tbb/enumerable_thread_specific.h>
112 #endif
113
114 using namespace std;
115 using namespace SMESH;
116
117 #ifdef _DEBUG_
118 //#define _MY_DEBUG_
119 #endif
120
121 //=============================================================================
122 /*!
123  * Constructor
124  */
125 //=============================================================================
126
127 StdMeshers_Cartesian_3D::StdMeshers_Cartesian_3D(int hypId, SMESH_Gen * gen)
128   :SMESH_3D_Algo(hypId, gen)
129 {
130   _name = "Cartesian_3D";
131   _shapeType = (1 << TopAbs_SOLID);       // 1 bit /shape type
132   _compatibleHypothesis.push_back("CartesianParameters3D");
133
134   _onlyUnaryInput = false;          // to mesh all SOLIDs at once
135   _requireDiscreteBoundary = false; // 2D mesh not needed
136   _supportSubmeshes = false;        // do not use any existing mesh
137 }
138
139 //=============================================================================
140 /*!
141  * Check presence of a hypothesis
142  */
143 //=============================================================================
144
145 bool StdMeshers_Cartesian_3D::CheckHypothesis (SMESH_Mesh&          aMesh,
146                                                const TopoDS_Shape&  aShape,
147                                                Hypothesis_Status&   aStatus)
148 {
149   aStatus = SMESH_Hypothesis::HYP_MISSING;
150
151   const list<const SMESHDS_Hypothesis*>& hyps = GetUsedHypothesis(aMesh, aShape);
152   list <const SMESHDS_Hypothesis* >::const_iterator h = hyps.begin();
153   if ( h == hyps.end())
154   {
155     return false;
156   }
157
158   for ( ; h != hyps.end(); ++h )
159   {
160     if (( _hyp = dynamic_cast<const StdMeshers_CartesianParameters3D*>( *h )))
161     {
162       aStatus = _hyp->IsDefined() ? HYP_OK : HYP_BAD_PARAMETER;
163       break;
164     }
165   }
166
167   return aStatus == HYP_OK;
168 }
169
170 namespace
171 {
172   typedef int TGeomID; // IDs of sub-shapes
173
174   //=============================================================================
175   // Definitions of internal utils
176   // --------------------------------------------------------------------------
177   enum Transition {
178     Trans_TANGENT = IntCurveSurface_Tangent,
179     Trans_IN      = IntCurveSurface_In,
180     Trans_OUT     = IntCurveSurface_Out,
181     Trans_APEX,
182     Trans_INTERNAL // for INTERNAL FACE
183   };
184   // --------------------------------------------------------------------------
185   /*!
186    * \brief Container of IDs of SOLID sub-shapes
187    */
188   class Solid // sole SOLID contains all sub-shapes
189   {
190     TGeomID _id; // SOLID id
191     bool    _hasInternalFaces;
192   public:
193     virtual ~Solid() {}
194     virtual bool Contains( TGeomID subID ) const { return true; }
195     virtual bool ContainsAny( const vector< TGeomID>& subIDs ) const { return true; }
196     virtual TopAbs_Orientation Orientation( const TopoDS_Shape& s ) const { return s.Orientation(); }
197     virtual bool IsOutsideOriented( TGeomID faceID ) const { return true; }
198     void SetID( TGeomID id ) { _id = id; }
199     TGeomID ID() const { return _id; }
200     void SetHasInternalFaces( bool has ) { _hasInternalFaces = has; }
201     bool HasInternalFaces() const { return _hasInternalFaces; }
202   };
203   // --------------------------------------------------------------------------
204   class OneOfSolids : public Solid
205   {
206     TColStd_MapOfInteger _subIDs;
207     TopTools_MapOfShape  _faces; // keep FACE orientation
208     TColStd_MapOfInteger _outFaceIDs; // FACEs of shape_to_mesh oriented outside the SOLID
209   public:
210     void Init( const TopoDS_Shape& solid,
211                TopAbs_ShapeEnum    subType,
212                const SMESHDS_Mesh* mesh );
213     virtual bool Contains( TGeomID i ) const { return i == ID() || _subIDs.Contains( i ); }
214     virtual bool ContainsAny( const vector< TGeomID>& subIDs ) const
215     {
216       for ( size_t i = 0; i < subIDs.size(); ++i ) if ( Contains( subIDs[ i ])) return true;
217       return false;
218     }
219     virtual TopAbs_Orientation Orientation( const TopoDS_Shape& face ) const
220     {
221       const TopoDS_Shape& sInMap = const_cast< OneOfSolids* >(this)->_faces.Added( face );
222       return sInMap.Orientation();
223     }
224     virtual bool IsOutsideOriented( TGeomID faceID ) const
225     {
226       return faceID == 0 || _outFaceIDs.Contains( faceID );
227     }
228   };
229   // --------------------------------------------------------------------------
230   /*!
231    * \brief Geom data
232    */
233   struct Geometry
234   {
235     TopoDS_Shape                _mainShape;
236     vector< vector< TGeomID > > _solidIDsByShapeID;// V/E/F ID -> SOLID IDs
237     Solid                       _soleSolid;
238     map< TGeomID, OneOfSolids > _solidByID;
239     TColStd_MapOfInteger        _boundaryFaces; // FACEs on boundary of mesh->ShapeToMesh()
240     TColStd_MapOfInteger        _strangeEdges; // EDGEs shared by strange FACEs
241     TGeomID                     _extIntFaceID; // pseudo FACE - extension of INTERNAL FACE
242
243     Controls::ElementsOnShape _edgeClassifier;
244     Controls::ElementsOnShape _vertexClassifier;
245
246     bool IsOneSolid() const { return _solidByID.size() < 2; }
247   };
248   // --------------------------------------------------------------------------
249   /*!
250    * \brief Common data of any intersection between a Grid and a shape
251    */
252   struct B_IntersectPoint
253   {
254     mutable const SMDS_MeshNode* _node;
255     mutable vector< TGeomID >    _faceIDs;
256
257     B_IntersectPoint(): _node(NULL) {}
258     void Add( const vector< TGeomID >& fIDs, const SMDS_MeshNode* n=0 ) const;
259     int HasCommonFace( const B_IntersectPoint * other, int avoidFace=-1 ) const;
260     bool IsOnFace( int faceID ) const;
261     virtual ~B_IntersectPoint() {}
262   };
263   // --------------------------------------------------------------------------
264   /*!
265    * \brief Data of intersection between a GridLine and a TopoDS_Face
266    */
267   struct F_IntersectPoint : public B_IntersectPoint
268   {
269     double             _paramOnLine;
270     double             _u, _v;
271     mutable Transition _transition;
272     mutable size_t     _indexOnLine;
273
274     bool operator< ( const F_IntersectPoint& o ) const { return _paramOnLine < o._paramOnLine; }
275   };
276   // --------------------------------------------------------------------------
277   /*!
278    * \brief Data of intersection between GridPlanes and a TopoDS_EDGE
279    */
280   struct E_IntersectPoint : public B_IntersectPoint
281   {
282     gp_Pnt  _point;
283     double  _uvw[3];
284     TGeomID _shapeID; // ID of EDGE or VERTEX
285   };
286   // --------------------------------------------------------------------------
287   /*!
288    * \brief A line of the grid and its intersections with 2D geometry
289    */
290   struct GridLine
291   {
292     gp_Lin _line;
293     double _length; // line length
294     multiset< F_IntersectPoint > _intPoints;
295
296     void RemoveExcessIntPoints( const double tol );
297     TGeomID GetSolidIDBefore( multiset< F_IntersectPoint >::iterator ip,
298                               const TGeomID                          prevID,
299                               const Geometry&                        geom);
300   };
301   // --------------------------------------------------------------------------
302   /*!
303    * \brief Planes of the grid used to find intersections of an EDGE with a hexahedron
304    */
305   struct GridPlanes
306   {
307     gp_XYZ           _zNorm;
308     vector< gp_XYZ > _origins; // origin points of all planes in one direction
309     vector< double > _zProjs;  // projections of origins to _zNorm
310   };
311   // --------------------------------------------------------------------------
312   /*!
313    * \brief Iterator on the parallel grid lines of one direction
314    */
315   struct LineIndexer
316   {
317     size_t _size  [3];
318     size_t _curInd[3];
319     size_t _iVar1, _iVar2, _iConst;
320     string _name1, _name2, _nameConst;
321     LineIndexer() {}
322     LineIndexer( size_t sz1, size_t sz2, size_t sz3,
323                  size_t iv1, size_t iv2, size_t iConst,
324                  const string& nv1, const string& nv2, const string& nConst )
325     {
326       _size[0] = sz1; _size[1] = sz2; _size[2] = sz3;
327       _curInd[0] = _curInd[1] = _curInd[2] = 0;
328       _iVar1 = iv1; _iVar2 = iv2; _iConst = iConst;
329       _name1 = nv1; _name2 = nv2; _nameConst = nConst;
330     }
331
332     size_t I() const { return _curInd[0]; }
333     size_t J() const { return _curInd[1]; }
334     size_t K() const { return _curInd[2]; }
335     void SetIJK( size_t i, size_t j, size_t k )
336     {
337       _curInd[0] = i; _curInd[1] = j; _curInd[2] = k;
338     }
339     void operator++()
340     {
341       if ( ++_curInd[_iVar1] == _size[_iVar1] )
342         _curInd[_iVar1] = 0, ++_curInd[_iVar2];
343     }
344     bool More() const { return _curInd[_iVar2] < _size[_iVar2]; }
345     size_t LineIndex   () const { return _curInd[_iVar1] + _curInd[_iVar2]* _size[_iVar1]; }
346     size_t LineIndex10 () const { return (_curInd[_iVar1] + 1 ) + _curInd[_iVar2]* _size[_iVar1]; }
347     size_t LineIndex01 () const { return _curInd[_iVar1] + (_curInd[_iVar2] + 1 )* _size[_iVar1]; }
348     size_t LineIndex11 () const { return (_curInd[_iVar1] + 1 ) + (_curInd[_iVar2] + 1 )* _size[_iVar1]; }
349     void SetIndexOnLine (size_t i)  { _curInd[ _iConst ] = i; }
350     size_t NbLines() const { return _size[_iVar1] * _size[_iVar2]; }
351   };
352   // --------------------------------------------------------------------------
353   /*!
354    * \brief Container of GridLine's
355    */
356   struct Grid
357   {
358     vector< double >   _coords[3]; // coordinates of grid nodes
359     gp_XYZ             _axes  [3]; // axis directions
360     vector< GridLine > _lines [3]; //    in 3 directions
361     double             _tol, _minCellSize;
362     gp_XYZ             _origin;
363     gp_Mat             _invB; // inverted basis of _axes
364
365     // index shift within _nodes of nodes of a cell from the 1st node
366     int                _nodeShift[8];
367
368     vector< const SMDS_MeshNode* >    _nodes; // mesh nodes at grid nodes
369     vector< const F_IntersectPoint* > _gridIntP; // grid node intersection with geometry
370     ObjectPool< E_IntersectPoint >    _edgeIntPool; // intersections with EDGEs
371     ObjectPool< F_IntersectPoint >    _extIntPool; // intersections with extended INTERNAL FACEs
372     //list< E_IntersectPoint >          _edgeIntP; // intersections with EDGEs
373
374     Geometry                          _geometry;
375     bool                              _toAddEdges;
376     bool                              _toCreateFaces;
377     bool                              _toConsiderInternalFaces;
378     bool                              _toUseThresholdForInternalFaces;
379     double                            _sizeThreshold;
380
381     SMESH_MesherHelper*               _helper;
382
383     size_t CellIndex( size_t i, size_t j, size_t k ) const
384     {
385       return i + j*(_coords[0].size()-1) + k*(_coords[0].size()-1)*(_coords[1].size()-1);
386     }
387     size_t NodeIndex( size_t i, size_t j, size_t k ) const
388     {
389       return i + j*_coords[0].size() + k*_coords[0].size()*_coords[1].size();
390     }
391     size_t NodeIndexDX() const { return 1; }
392     size_t NodeIndexDY() const { return _coords[0].size(); }
393     size_t NodeIndexDZ() const { return _coords[0].size() * _coords[1].size(); }
394
395     LineIndexer GetLineIndexer(size_t iDir) const;
396
397     E_IntersectPoint* Add( const E_IntersectPoint& ip )
398     {
399       E_IntersectPoint* eip = _edgeIntPool.getNew();
400       *eip = ip;
401       return eip;
402     }
403     void Remove( E_IntersectPoint* eip ) { _edgeIntPool.destroy( eip ); }
404
405     TGeomID ShapeID( const TopoDS_Shape& s ) const;
406     const TopoDS_Shape& Shape( TGeomID id ) const;
407     TopAbs_ShapeEnum ShapeType( TGeomID id ) const { return Shape(id).ShapeType(); }
408     void InitGeometry( const TopoDS_Shape& theShape );
409     void InitClassifier( const TopoDS_Shape&        mainShape,
410                          TopAbs_ShapeEnum           shapeType,
411                          Controls::ElementsOnShape& classifier );
412     void GetEdgesToImplement( map< TGeomID, vector< TGeomID > > & edge2faceMap,
413                               const TopoDS_Shape&                 shape,
414                               const vector< TopoDS_Shape >&       faces );
415     void SetSolidFather( const TopoDS_Shape& s, const TopoDS_Shape& theShapeToMesh );
416     bool IsShared( TGeomID faceID ) const;
417     bool IsAnyShared( const std::vector< TGeomID >& faceIDs ) const;
418     bool IsInternal( TGeomID faceID ) const {
419       return ( faceID == PseudoIntExtFaceID() ||
420                Shape( faceID ).Orientation() == TopAbs_INTERNAL ); }
421     bool IsSolid( TGeomID shapeID ) const {
422       if ( _geometry.IsOneSolid() ) return _geometry._soleSolid.ID() == shapeID;
423       else                          return _geometry._solidByID.count( shapeID ); }
424     bool IsStrangeEdge( TGeomID id ) const { return _geometry._strangeEdges.Contains( id ); }
425     TGeomID PseudoIntExtFaceID() const { return _geometry._extIntFaceID; }
426     Solid* GetSolid( TGeomID solidID = 0 );
427     Solid* GetOneOfSolids( TGeomID solidID );
428     const vector< TGeomID > & GetSolidIDs( TGeomID subShapeID ) const;
429     bool IsCorrectTransition( TGeomID faceID, const Solid* solid );
430     bool IsBoundaryFace( TGeomID face ) const { return _geometry._boundaryFaces.Contains( face ); }
431     void SetOnShape( const SMDS_MeshNode* n, const F_IntersectPoint& ip, bool unset=false );
432     bool IsToCheckNodePos() const { return !_toAddEdges && _toCreateFaces; }
433     bool IsToRemoveExcessEntities() const { return !_toAddEdges; }
434
435     void SetCoordinates(const vector<double>& xCoords,
436                         const vector<double>& yCoords,
437                         const vector<double>& zCoords,
438                         const double*         axesDirs,
439                         const Bnd_Box&        bndBox );
440     void ComputeUVW(const gp_XYZ& p, double uvw[3]);
441     void ComputeNodes(SMESH_MesherHelper& helper);
442   };
443   // --------------------------------------------------------------------------
444   /*!
445    * \brief Return cells sharing a link
446    */
447   struct CellsAroundLink
448   {
449     int    _iDir;
450     int    _dInd[4][3];
451     size_t _nbCells[3];
452     int    _i,_j,_k;
453     Grid*  _grid;
454
455     CellsAroundLink( Grid* grid, int iDir ):
456       _iDir( iDir ),
457       _dInd{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} },
458       _nbCells{ grid->_coords[0].size() - 1,
459           grid->_coords[1].size() - 1,
460           grid->_coords[2].size() - 1 },
461       _grid( grid )
462     {
463       const int iDirOther[3][2] = {{ 1,2 },{ 0,2 },{ 0,1 }};
464       _dInd[1][ iDirOther[iDir][0] ] = -1;
465       _dInd[2][ iDirOther[iDir][1] ] = -1;
466       _dInd[3][ iDirOther[iDir][0] ] = -1; _dInd[3][ iDirOther[iDir][1] ] = -1;
467     }
468     void Init( int i, int j, int k, int link12 = 0 )
469     {
470       int iL = link12 % 4;
471       _i = i - _dInd[iL][0];
472       _j = j - _dInd[iL][1];
473       _k = k - _dInd[iL][2];
474     }
475     bool GetCell( int iL, int& i, int& j, int& k, int& cellIndex, int& linkIndex )
476     {
477       i =  _i + _dInd[iL][0];
478       j =  _j + _dInd[iL][1];
479       k =  _k + _dInd[iL][2];
480       if ( i < 0 || i >= (int)_nbCells[0] ||
481            j < 0 || j >= (int)_nbCells[1] ||
482            k < 0 || k >= (int)_nbCells[2] )
483         return false;
484       cellIndex = _grid->CellIndex( i,j,k );
485       linkIndex = iL + _iDir * 4;
486       return true;
487     }
488   };
489   // --------------------------------------------------------------------------
490   /*!
491    * \brief Intersector of TopoDS_Face with all GridLine's
492    */
493   struct FaceGridIntersector
494   {
495     TopoDS_Face _face;
496     TGeomID     _faceID;
497     Grid*       _grid;
498     Bnd_Box     _bndBox;
499     IntCurvesFace_Intersector* _surfaceInt;
500     vector< std::pair< GridLine*, F_IntersectPoint > > _intersections;
501
502     FaceGridIntersector(): _grid(0), _surfaceInt(0) {}
503     void Intersect();
504
505     void StoreIntersections()
506     {
507       for ( size_t i = 0; i < _intersections.size(); ++i )
508       {
509         multiset< F_IntersectPoint >::iterator ip =
510           _intersections[i].first->_intPoints.insert( _intersections[i].second );
511         ip->_faceIDs.reserve( 1 );
512         ip->_faceIDs.push_back( _faceID );
513       }
514     }
515     const Bnd_Box& GetFaceBndBox()
516     {
517       GetCurveFaceIntersector();
518       return _bndBox;
519     }
520     IntCurvesFace_Intersector* GetCurveFaceIntersector()
521     {
522       if ( !_surfaceInt )
523       {
524         _surfaceInt = new IntCurvesFace_Intersector( _face, Precision::PConfusion() );
525         _bndBox     = _surfaceInt->Bounding();
526         if ( _bndBox.IsVoid() )
527           BRepBndLib::Add (_face, _bndBox);
528       }
529       return _surfaceInt;
530     }
531     bool IsThreadSafe(set< const Standard_Transient* >& noSafeTShapes) const;
532   };
533   // --------------------------------------------------------------------------
534   /*!
535    * \brief Intersector of a surface with a GridLine
536    */
537   struct FaceLineIntersector
538   {
539     double      _tol;
540     double      _u, _v, _w; // params on the face and the line
541     Transition  _transition; // transition at intersection (see IntCurveSurface.cdl)
542     Transition  _transIn, _transOut; // IN and OUT transitions depending of face orientation
543
544     gp_Pln      _plane;
545     gp_Cylinder _cylinder;
546     gp_Cone     _cone;
547     gp_Sphere   _sphere;
548     gp_Torus    _torus;
549     IntCurvesFace_Intersector* _surfaceInt;
550
551     vector< F_IntersectPoint > _intPoints;
552
553     void IntersectWithPlane   (const GridLine& gridLine);
554     void IntersectWithCylinder(const GridLine& gridLine);
555     void IntersectWithCone    (const GridLine& gridLine);
556     void IntersectWithSphere  (const GridLine& gridLine);
557     void IntersectWithTorus   (const GridLine& gridLine);
558     void IntersectWithSurface (const GridLine& gridLine);
559
560     bool UVIsOnFace() const;
561     void addIntPoint(const bool toClassify=true);
562     bool isParamOnLineOK( const double linLength )
563     {
564       return -_tol < _w && _w < linLength + _tol;
565     }
566     FaceLineIntersector():_surfaceInt(0) {}
567     ~FaceLineIntersector() { if (_surfaceInt ) delete _surfaceInt; _surfaceInt = 0; }
568   };
569   // --------------------------------------------------------------------------
570   /*!
571    * \brief Class representing topology of the hexahedron and creating a mesh
572    *        volume basing on analysis of hexahedron intersection with geometry
573    */
574   class Hexahedron
575   {
576     // --------------------------------------------------------------------------------
577     struct _Face;
578     struct _Link;
579     enum IsInternalFlag { IS_NOT_INTERNAL, IS_INTERNAL, IS_CUT_BY_INTERNAL_FACE };
580     // --------------------------------------------------------------------------------
581     struct _Node //!< node either at a hexahedron corner or at intersection
582     {
583       const SMDS_MeshNode*    _node; // mesh node at hexahedron corner
584       const B_IntersectPoint* _intPoint;
585       const _Face*            _usedInFace;
586       char                    _isInternalFlags;
587
588       _Node(const SMDS_MeshNode* n=0, const B_IntersectPoint* ip=0)
589         :_node(n), _intPoint(ip), _usedInFace(0), _isInternalFlags(0) {} 
590       const SMDS_MeshNode*    Node() const
591       { return ( _intPoint && _intPoint->_node ) ? _intPoint->_node : _node; }
592       const E_IntersectPoint* EdgeIntPnt() const
593       { return static_cast< const E_IntersectPoint* >( _intPoint ); }
594       const F_IntersectPoint* FaceIntPnt() const
595       { return static_cast< const F_IntersectPoint* >( _intPoint ); }
596       const vector< TGeomID >& faces() const { return _intPoint->_faceIDs; }
597       TGeomID face(size_t i) const { return _intPoint->_faceIDs[ i ]; }
598       void SetInternal( IsInternalFlag intFlag ) { _isInternalFlags |= intFlag; }
599       bool IsCutByInternal() const { return _isInternalFlags & IS_CUT_BY_INTERNAL_FACE; }
600       bool IsUsedInFace( const _Face* polygon = 0 )
601       {
602         return polygon ? ( _usedInFace == polygon ) : bool( _usedInFace );
603       }
604       TGeomID IsLinked( const B_IntersectPoint* other,
605                         TGeomID                 avoidFace=-1 ) const // returns id of a common face
606       {
607         return _intPoint ? _intPoint->HasCommonFace( other, avoidFace ) : 0;
608       }
609       bool IsOnFace( TGeomID faceID ) const // returns true if faceID is found
610       {
611         return _intPoint ? _intPoint->IsOnFace( faceID ) : false;
612       }
613       gp_Pnt Point() const
614       {
615         if ( const SMDS_MeshNode* n = Node() )
616           return SMESH_NodeXYZ( n );
617         if ( const E_IntersectPoint* eip =
618              dynamic_cast< const E_IntersectPoint* >( _intPoint ))
619           return eip->_point;
620         return gp_Pnt( 1e100, 0, 0 );
621       }
622       TGeomID ShapeID() const
623       {
624         if ( const E_IntersectPoint* eip = dynamic_cast< const E_IntersectPoint* >( _intPoint ))
625           return eip->_shapeID;
626         return 0;
627       }
628       void Add( const E_IntersectPoint* ip )
629       {
630         // Possible cases before Add(ip):
631         ///  1) _node != 0 --> _Node at hex corner ( _intPoint == 0 || _intPoint._node == 0 )
632         ///  2) _node == 0 && _intPoint._node != 0  -->  link intersected by FACE
633         ///  3) _node == 0 && _intPoint._node == 0  -->  _Node at EDGE intersection
634         //
635         // If ip is added in cases 1) and 2) _node position must be changed to ip._shapeID
636         //   at creation of elements
637         // To recognize this case, set _intPoint._node = Node()
638         const SMDS_MeshNode* node = Node();
639         if ( !_intPoint ) {
640           _intPoint = ip;
641         }
642         else {
643           ip->Add( _intPoint->_faceIDs );
644           _intPoint = ip;
645         }
646         if ( node )
647           _node = _intPoint->_node = node;
648       }
649     };
650     // --------------------------------------------------------------------------------
651     struct _Link // link connecting two _Node's
652     {
653       _Node* _nodes[2];
654       _Face* _faces[2]; // polygons sharing a link
655       vector< const F_IntersectPoint* > _fIntPoints; // GridLine intersections with FACEs
656       vector< _Node* >                  _fIntNodes;   // _Node's at _fIntPoints
657       vector< _Link >                   _splits;
658       _Link(): _faces{ 0, 0 } {}
659     };
660     // --------------------------------------------------------------------------------
661     struct _OrientedLink
662     {
663       _Link* _link;
664       bool   _reverse;
665       _OrientedLink( _Link* link=0, bool reverse=false ): _link(link), _reverse(reverse) {}
666       void Reverse() { _reverse = !_reverse; }
667       int NbResultLinks() const { return _link->_splits.size(); }
668       _OrientedLink ResultLink(int i) const
669       {
670         return _OrientedLink(&_link->_splits[_reverse ? NbResultLinks()-i-1 : i],_reverse);
671       }
672       _Node* FirstNode() const { return _link->_nodes[ _reverse ]; }
673       _Node* LastNode()  const { return _link->_nodes[ !_reverse ]; }
674       operator bool() const { return _link; }
675       vector< TGeomID > GetNotUsedFace(const set<TGeomID>& usedIDs ) const // returns supporting FACEs
676       {
677         vector< TGeomID > faces;
678         const B_IntersectPoint *ip0, *ip1;
679         if (( ip0 = _link->_nodes[0]->_intPoint ) &&
680             ( ip1 = _link->_nodes[1]->_intPoint ))
681         {
682           for ( size_t i = 0; i < ip0->_faceIDs.size(); ++i )
683             if ( ip1->IsOnFace ( ip0->_faceIDs[i] ) &&
684                  !usedIDs.count( ip0->_faceIDs[i] ) )
685               faces.push_back( ip0->_faceIDs[i] );
686         }
687         return faces;
688       }
689       bool HasEdgeNodes() const
690       {
691         return ( dynamic_cast< const E_IntersectPoint* >( _link->_nodes[0]->_intPoint ) ||
692                  dynamic_cast< const E_IntersectPoint* >( _link->_nodes[1]->_intPoint ));
693       }
694       int NbFaces() const
695       {
696         return !_link->_faces[0] ? 0 : 1 + bool( _link->_faces[1] );
697       }
698       void AddFace( _Face* f )
699       {
700         if ( _link->_faces[0] )
701         {
702           _link->_faces[1] = f;
703         }
704         else
705         {
706           _link->_faces[0] = f;
707           _link->_faces[1] = 0;
708         }
709       }
710       void RemoveFace( _Face* f )
711       {
712         if ( !_link->_faces[0] ) return;
713
714         if ( _link->_faces[1] == f )
715         {
716           _link->_faces[1] = 0;
717         }
718         else if ( _link->_faces[0] == f )
719         {
720           _link->_faces[0] = 0;
721           if ( _link->_faces[1] )
722           {
723             _link->_faces[0] = _link->_faces[1];
724             _link->_faces[1] = 0;
725           }
726         }
727       }
728     };
729     // --------------------------------------------------------------------------------
730     struct _SplitIterator //! set to _hexLinks splits on one side of INTERNAL FACEs
731     {
732       struct _Split // data of a link split
733       {
734         int    _linkID;      // hex link ID
735         _Node* _nodes[2];
736         int    _iCheckIteration; // iteration where split is tried as Hexahedron split
737         _Link* _checkedSplit;    // split set to hex links
738         bool   _isUsed;    // used in a volume
739
740         _Split( _Link & split, int iLink ):
741           _linkID( iLink ), _nodes{ split._nodes[0], split._nodes[1] },
742           _iCheckIteration( 0 ), _isUsed( false )
743         {}
744         bool IsCheckedOrUsed( bool used ) const { return used ? _isUsed : _iCheckIteration > 0; }
745       };
746       _Link*                _hexLinks;
747       std::vector< _Split > _splits;
748       int                   _iterationNb;
749       size_t                _nbChecked;
750       size_t                _nbUsed;
751       std::vector< _Node* > _freeNodes; // nodes reached while composing a split set
752
753       _SplitIterator( _Link* hexLinks ):
754         _hexLinks( hexLinks ), _iterationNb(0), _nbChecked(0), _nbUsed(0)
755       {
756         _freeNodes.reserve( 12 );
757         _splits.reserve( 24 );
758         for ( int iL = 0; iL < 12; ++iL )
759           for ( size_t iS = 0; iS < _hexLinks[ iL ]._splits.size(); ++iS )
760             _splits.emplace_back( _hexLinks[ iL ]._splits[ iS ], iL );
761         Next();
762       }
763       bool More() const { return _nbUsed < _splits.size(); }
764       bool Next();
765     };
766     // --------------------------------------------------------------------------------
767     struct _Face
768     {
769       SMESH_Block::TShapeID   _name;
770       vector< _OrientedLink > _links;       // links on GridLine's
771       vector< _Link >         _polyLinks;   // links added to close a polygonal face
772       vector< _Node* >        _eIntNodes;   // nodes at intersection with EDGEs
773
774       _Face():_name( SMESH_Block::ID_NONE )
775       {}
776       bool IsPolyLink( const _OrientedLink& ol )
777       {
778         return _polyLinks.empty() ? false :
779           ( &_polyLinks[0] <= ol._link &&  ol._link <= &_polyLinks.back() );
780       }
781       void AddPolyLink(_Node* n0, _Node* n1, _Face* faceToFindEqual=0)
782       {
783         if ( faceToFindEqual && faceToFindEqual != this ) {
784           for ( size_t iL = 0; iL < faceToFindEqual->_polyLinks.size(); ++iL )
785             if ( faceToFindEqual->_polyLinks[iL]._nodes[0] == n1 &&
786                  faceToFindEqual->_polyLinks[iL]._nodes[1] == n0 )
787             {
788               _links.push_back
789                 ( _OrientedLink( & faceToFindEqual->_polyLinks[iL], /*reverse=*/true ));
790               return;
791             }
792         }
793         _Link l;
794         l._nodes[0] = n0;
795         l._nodes[1] = n1;
796         _polyLinks.push_back( l );
797         _links.push_back( _OrientedLink( &_polyLinks.back() ));
798       }
799     };
800     // --------------------------------------------------------------------------------
801     struct _volumeDef // holder of nodes of a volume mesh element
802     {
803       typedef void* _ptr;
804
805       struct _nodeDef
806       {
807         const SMDS_MeshNode*    _node; // mesh node at hexahedron corner
808         const B_IntersectPoint* _intPoint;
809
810         _nodeDef(): _node(0), _intPoint(0) {}
811         _nodeDef( _Node* n ): _node( n->_node), _intPoint( n->_intPoint ) {}
812         const SMDS_MeshNode*    Node() const
813         { return ( _intPoint && _intPoint->_node ) ? _intPoint->_node : _node; }
814         const E_IntersectPoint* EdgeIntPnt() const
815         { return static_cast< const E_IntersectPoint* >( _intPoint ); }
816         _ptr Ptr() const { return Node() ? (_ptr) Node() : (_ptr) EdgeIntPnt(); }
817         bool operator==(const _nodeDef& other ) const { return Ptr() == other.Ptr(); }
818       };
819
820       vector< _nodeDef >      _nodes;
821       vector< int >           _quantities;
822       _volumeDef*             _next; // to store several _volumeDefs in a chain
823       TGeomID                 _solidID;
824       const SMDS_MeshElement* _volume; // new volume
825
826       vector< SMESH_Block::TShapeID > _names; // name of side a polygon originates from
827
828       _volumeDef(): _next(0), _solidID(0), _volume(0) {}
829       ~_volumeDef() { delete _next; }
830       _volumeDef( _volumeDef& other ):
831         _next(0), _solidID( other._solidID ), _volume( other._volume )
832       { _nodes.swap( other._nodes ); _quantities.swap( other._quantities ); other._volume = 0;
833         _names.swap( other._names ); }
834
835       size_t size() const { return 1 + ( _next ? _next->size() : 0 ); }
836       _volumeDef* at(int index)
837       { return index == 0 ? this : ( _next ? _next->at(index-1) : _next ); }
838
839       void Set( _Node** nodes, int nb )
840       { _nodes.assign( nodes, nodes + nb ); }
841
842       void SetNext( _volumeDef* vd )
843       { if ( _next ) { _next->SetNext( vd ); } else { _next = vd; }}
844
845       bool IsEmpty() const { return (( _nodes.empty() ) &&
846                                      ( !_next || _next->IsEmpty() )); }
847       bool IsPolyhedron() const { return ( !_quantities.empty() ||
848                                            ( _next && !_next->_quantities.empty() )); }
849
850
851       struct _linkDef: public std::pair<_ptr,_ptr> // to join polygons in removeExcessSideDivision()
852       {
853         _nodeDef _node1;//, _node2;
854         mutable /*const */_linkDef *_prev, *_next;
855         size_t _loopIndex;
856
857         _linkDef():_prev(0), _next(0) {}
858
859         void init( const _nodeDef& n1, const _nodeDef& n2, size_t iLoop )
860         {
861           _node1     = n1; //_node2 = n2;
862           _loopIndex = iLoop;
863           first      = n1.Ptr();
864           second     = n2.Ptr();
865           if ( first > second ) std::swap( first, second );
866         }
867         void setNext( _linkDef* next )
868         {
869           _next = next;
870           next->_prev = this;
871         }
872       };
873     };
874
875     // topology of a hexahedron
876     _Node _hexNodes [8];
877     _Link _hexLinks [12];
878     _Face _hexQuads [6];
879
880     // faces resulted from hexahedron intersection
881     vector< _Face > _polygons;
882
883     // intresections with EDGEs
884     vector< const E_IntersectPoint* > _eIntPoints;
885
886     // additional nodes created at intersection points
887     vector< _Node > _intNodes;
888
889     // nodes inside the hexahedron (at VERTEXes) refer to _intNodes
890     vector< _Node* > _vIntNodes;
891
892     // computed volume elements
893     _volumeDef _volumeDefs;
894
895     Grid*       _grid;
896     double      _sideLength[3];
897     int         _nbCornerNodes, _nbFaceIntNodes, _nbBndNodes;
898     int         _origNodeInd; // index of _hexNodes[0] node within the _grid
899     size_t      _i,_j,_k;
900     bool        _hasTooSmall;
901
902 #ifdef _DEBUG_
903     int         _cellID;
904 #endif
905
906   public:
907     Hexahedron(Grid* grid);
908     int MakeElements(SMESH_MesherHelper&                      helper,
909                      const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap);
910     void computeElements( const Solid* solid = 0, int solidIndex = -1 );
911
912   private:
913     Hexahedron(const Hexahedron& other, size_t i, size_t j, size_t k, int cellID );
914     void init( size_t i, size_t j, size_t k, const Solid* solid=0 );
915     void init( size_t i );
916     void setIJK( size_t i );
917     bool compute( const Solid* solid, const IsInternalFlag intFlag );
918     size_t getSolids( TGeomID ids[] );
919     bool isCutByInternalFace( IsInternalFlag & maxFlag );
920     void addEdges(SMESH_MesherHelper&                      helper,
921                   vector< Hexahedron* >&                   intersectedHex,
922                   const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap);
923     gp_Pnt findIntPoint( double u1, double proj1, double u2, double proj2,
924                          double proj, BRepAdaptor_Curve& curve,
925                          const gp_XYZ& axis, const gp_XYZ& origin );
926     int  getEntity( const E_IntersectPoint* ip, int* facets, int& sub );
927     bool addIntersection( const E_IntersectPoint* ip,
928                           vector< Hexahedron* >&  hexes,
929                           int ijk[], int dIJK[] );
930     bool findChain( _Node* n1, _Node* n2, _Face& quad, vector<_Node*>& chainNodes );
931     bool closePolygon( _Face* polygon, vector<_Node*>& chainNodes ) const;
932     bool findChainOnEdge( const vector< _OrientedLink >& splits,
933                           const _OrientedLink&           prevSplit,
934                           const _OrientedLink&           avoidSplit,
935                           size_t &                       iS,
936                           _Face&                         quad,
937                           vector<_Node*>&                chn);
938     int  addVolumes(SMESH_MesherHelper& helper );
939     void addFaces( SMESH_MesherHelper&                       helper,
940                    const vector< const SMDS_MeshElement* > & boundaryVolumes );
941     void addSegments( SMESH_MesherHelper&                      helper,
942                       const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap );
943     void getVolumes( vector< const SMDS_MeshElement* > & volumes );
944     void getBoundaryElems( vector< const SMDS_MeshElement* > & boundaryVolumes );
945     void removeExcessSideDivision(const vector< Hexahedron* >& allHexa);
946     void removeExcessNodes(vector< Hexahedron* >& allHexa);
947     TGeomID getAnyFace() const;
948     void cutByExtendedInternal( std::vector< Hexahedron* >& hexes,
949                                 const TColStd_MapOfInteger& intEdgeIDs );
950     gp_Pnt mostDistantInternalPnt( int hexIndex, const gp_Pnt& p1, const gp_Pnt& p2 );
951     bool isOutPoint( _Link& link, int iP, SMESH_MesherHelper& helper, const Solid* solid ) const;
952     void sortVertexNodes(vector<_Node*>& nodes, _Node* curNode, TGeomID face);
953     bool isInHole() const;
954     bool hasStrangeEdge() const;
955     bool checkPolyhedronSize( bool isCutByInternalFace ) const;
956     bool addHexa ();
957     bool addTetra();
958     bool addPenta();
959     bool addPyra ();
960     bool debugDumpLink( _Link* link );
961     _Node* findEqualNode( vector< _Node* >&       nodes,
962                           const E_IntersectPoint* ip,
963                           const double            tol2 )
964     {
965       for ( size_t i = 0; i < nodes.size(); ++i )
966         if ( nodes[i]->EdgeIntPnt() == ip ||
967              nodes[i]->Point().SquareDistance( ip->_point ) <= tol2 )
968           return nodes[i];
969       return 0;
970     }
971     bool isImplementEdges() const { return _grid->_edgeIntPool.nbElements(); }
972     bool isOutParam(const double uvw[3]) const;
973
974     typedef boost::container::flat_map< TGeomID, size_t > TID2Nb;
975     static void insertAndIncrement( TGeomID id, TID2Nb& id2nbMap )
976     {
977       TID2Nb::value_type s0( id, 0 );
978       TID2Nb::iterator id2nb = id2nbMap.insert( s0 ).first;
979       id2nb->second++;
980     }
981   }; // class Hexahedron
982
983 #ifdef WITH_TBB
984   // --------------------------------------------------------------------------
985   /*!
986    * \brief Hexahedron computing volumes in one thread
987    */
988   struct ParallelHexahedron
989   {
990     vector< Hexahedron* >& _hexVec;
991     ParallelHexahedron( vector< Hexahedron* >& hv ): _hexVec(hv) {}
992     void operator() ( const tbb::blocked_range<size_t>& r ) const
993     {
994       for ( size_t i = r.begin(); i != r.end(); ++i )
995         if ( Hexahedron* hex = _hexVec[ i ] )
996           hex->computeElements();
997     }
998   };
999   // --------------------------------------------------------------------------
1000   /*!
1001    * \brief Structure intersecting certain nb of faces with GridLine's in one thread
1002    */
1003   struct ParallelIntersector
1004   {
1005     vector< FaceGridIntersector >& _faceVec;
1006     ParallelIntersector( vector< FaceGridIntersector >& faceVec): _faceVec(faceVec){}
1007     void operator() ( const tbb::blocked_range<size_t>& r ) const
1008     {
1009       for ( size_t i = r.begin(); i != r.end(); ++i )
1010         _faceVec[i].Intersect();
1011     }
1012   };
1013 #endif
1014
1015   //=============================================================================
1016   // Implementation of internal utils
1017   //=============================================================================
1018   /*!
1019    * \brief adjust \a i to have \a val between values[i] and values[i+1]
1020    */
1021   inline void locateValue( int & i, double val, const vector<double>& values,
1022                            int& di, double tol )
1023   {
1024     //val += values[0]; // input \a val is measured from 0.
1025     if ( i > (int) values.size()-2 )
1026       i = values.size()-2;
1027     else
1028       while ( i+2 < (int) values.size() && val > values[ i+1 ])
1029         ++i;
1030     while ( i > 0 && val < values[ i ])
1031       --i;
1032
1033     if ( i > 0 && val - values[ i ] < tol )
1034       di = -1;
1035     else if ( i+2 < (int) values.size() && values[ i+1 ] - val < tol )
1036       di = 1;
1037     else
1038       di = 0;
1039   }
1040   //=============================================================================
1041   /*
1042    * Remove coincident intersection points
1043    */
1044   void GridLine::RemoveExcessIntPoints( const double tol )
1045   {
1046     if ( _intPoints.size() < 2 ) return;
1047
1048     set< Transition > tranSet;
1049     multiset< F_IntersectPoint >::iterator ip1, ip2 = _intPoints.begin();
1050     while ( ip2 != _intPoints.end() )
1051     {
1052       tranSet.clear();
1053       ip1 = ip2++;
1054       while ( ip2 != _intPoints.end() && ip2->_paramOnLine - ip1->_paramOnLine <= tol )
1055       {
1056         tranSet.insert( ip1->_transition );
1057         tranSet.insert( ip2->_transition );
1058         ip2->Add( ip1->_faceIDs );
1059         _intPoints.erase( ip1 );
1060         ip1 = ip2++;
1061       }
1062       if ( tranSet.size() > 1 ) // points with different transition coincide
1063       {
1064         bool isIN  = tranSet.count( Trans_IN );
1065         bool isOUT = tranSet.count( Trans_OUT );
1066         if ( isIN && isOUT )
1067           (*ip1)._transition = Trans_TANGENT;
1068         else
1069           (*ip1)._transition = isIN ? Trans_IN : Trans_OUT;
1070       }
1071     }
1072   }
1073   //================================================================================
1074   /*
1075    * Return ID of SOLID for nodes before the given intersection point
1076    */
1077   TGeomID GridLine::GetSolidIDBefore( multiset< F_IntersectPoint >::iterator ip,
1078                                       const TGeomID                          prevID,
1079                                       const Geometry&                        geom )
1080   {
1081     if ( ip == _intPoints.begin() )
1082       return 0;
1083
1084     if ( geom.IsOneSolid() )
1085     {
1086       bool isOut = true;
1087       switch ( ip->_transition ) {
1088       case Trans_IN:      isOut = true;            break;
1089       case Trans_OUT:     isOut = false;           break;
1090       case Trans_TANGENT: isOut = ( prevID != 0 ); break;
1091       case Trans_APEX:
1092       {
1093         // singularity point (apex of a cone)
1094         multiset< F_IntersectPoint >::iterator ipBef = ip, ipAft = ++ip;
1095         if ( ipAft == _intPoints.end() )
1096           isOut = false;
1097         else
1098         {
1099           --ipBef;
1100           if ( ipBef->_transition != ipAft->_transition )
1101             isOut = ( ipBef->_transition == Trans_OUT );
1102           else
1103             isOut = ( ipBef->_transition != Trans_OUT );
1104         }
1105         break;
1106       }
1107       case Trans_INTERNAL: isOut = false;
1108       default:;
1109       }
1110       return isOut ? 0 : geom._soleSolid.ID();
1111     }
1112
1113     const vector< TGeomID >& solids = geom._solidIDsByShapeID[ ip->_faceIDs[ 0 ]];
1114
1115     --ip;
1116     if ( ip->_transition == Trans_INTERNAL )
1117       return prevID;
1118
1119     const vector< TGeomID >& solidsBef = geom._solidIDsByShapeID[ ip->_faceIDs[ 0 ]];
1120
1121     if ( ip->_transition == Trans_IN ||
1122          ip->_transition == Trans_OUT )
1123     {
1124       if ( solidsBef.size() == 1 )
1125         return ( solidsBef[0] == prevID ) ? 0 : solidsBef[0];
1126
1127       return solidsBef[ solidsBef[0] == prevID ];
1128     }
1129
1130     if ( solidsBef.size() == 1 )
1131       return solidsBef[0];
1132
1133     for ( size_t i = 0; i < solids.size(); ++i )
1134     {
1135       vector< TGeomID >::const_iterator it =
1136         std::find( solidsBef.begin(), solidsBef.end(), solids[i] );
1137       if ( it != solidsBef.end() )
1138         return solids[i];
1139     }
1140     return 0;
1141   }
1142   //================================================================================
1143   /*
1144    * Adds face IDs
1145    */
1146   void B_IntersectPoint::Add( const vector< TGeomID >& fIDs,
1147                               const SMDS_MeshNode*     n) const
1148   {
1149     if ( _faceIDs.empty() )
1150       _faceIDs = fIDs;
1151     else
1152       for ( size_t i = 0; i < fIDs.size(); ++i )
1153       {
1154         vector< TGeomID >::iterator it =
1155           std::find( _faceIDs.begin(), _faceIDs.end(), fIDs[i] );
1156         if ( it == _faceIDs.end() )
1157           _faceIDs.push_back( fIDs[i] );
1158       }
1159     if ( !_node )
1160       _node = n;
1161   }
1162   //================================================================================
1163   /*
1164    * Returns index of a common face if any, else zero
1165    */
1166   int B_IntersectPoint::HasCommonFace( const B_IntersectPoint * other, int avoidFace ) const
1167   {
1168     if ( other )
1169       for ( size_t i = 0; i < other->_faceIDs.size(); ++i )
1170         if ( avoidFace != other->_faceIDs[i] &&
1171              IsOnFace   ( other->_faceIDs[i] ))
1172           return other->_faceIDs[i];
1173     return 0;
1174   }
1175   //================================================================================
1176   /*
1177    * Returns \c true if \a faceID in in this->_faceIDs
1178    */
1179   bool B_IntersectPoint::IsOnFace( int faceID ) const // returns true if faceID is found
1180   {
1181     vector< TGeomID >::const_iterator it =
1182       std::find( _faceIDs.begin(), _faceIDs.end(), faceID );
1183     return ( it != _faceIDs.end() );
1184   }
1185   //================================================================================
1186   /*
1187    * OneOfSolids initialization
1188    */
1189   void OneOfSolids::Init( const TopoDS_Shape& solid,
1190                           TopAbs_ShapeEnum    subType,
1191                           const SMESHDS_Mesh* mesh )
1192   {
1193     SetID( mesh->ShapeToIndex( solid ));
1194
1195     if ( subType == TopAbs_FACE )
1196       SetHasInternalFaces( false );
1197
1198     for ( TopExp_Explorer sub( solid, subType ); sub.More(); sub.Next() )
1199     {
1200       _subIDs.Add( mesh->ShapeToIndex( sub.Current() ));
1201       if ( subType == TopAbs_FACE )
1202       {
1203         _faces.Add( sub.Current() );
1204         if ( sub.Current().Orientation() == TopAbs_INTERNAL )
1205           SetHasInternalFaces( true );
1206
1207         TGeomID faceID = mesh->ShapeToIndex( sub.Current() );
1208         if ( sub.Current().Orientation() == TopAbs_INTERNAL ||
1209              sub.Current().Orientation() == mesh->IndexToShape( faceID ).Orientation() )
1210           _outFaceIDs.Add( faceID );
1211       }
1212     }
1213   }
1214   //================================================================================
1215   /*
1216    * Return an iterator on GridLine's in a given direction
1217    */
1218   LineIndexer Grid::GetLineIndexer(size_t iDir) const
1219   {
1220     const size_t indices[] = { 1,2,0, 0,2,1, 0,1,2 };
1221     const string s      [] = { "X", "Y", "Z" };
1222     LineIndexer li( _coords[0].size(),  _coords[1].size(),    _coords[2].size(),
1223                     indices[iDir*3],    indices[iDir*3+1],    indices[iDir*3+2],
1224                     s[indices[iDir*3]], s[indices[iDir*3+1]], s[indices[iDir*3+2]]);
1225     return li;
1226   }
1227   //=============================================================================
1228   /*
1229    * Creates GridLine's of the grid
1230    */
1231   void Grid::SetCoordinates(const vector<double>& xCoords,
1232                             const vector<double>& yCoords,
1233                             const vector<double>& zCoords,
1234                             const double*         axesDirs,
1235                             const Bnd_Box&        shapeBox)
1236   {
1237     _coords[0] = xCoords;
1238     _coords[1] = yCoords;
1239     _coords[2] = zCoords;
1240
1241     _axes[0].SetCoord( axesDirs[0],
1242                        axesDirs[1],
1243                        axesDirs[2]);
1244     _axes[1].SetCoord( axesDirs[3],
1245                        axesDirs[4],
1246                        axesDirs[5]);
1247     _axes[2].SetCoord( axesDirs[6],
1248                        axesDirs[7],
1249                        axesDirs[8]);
1250     _axes[0].Normalize();
1251     _axes[1].Normalize();
1252     _axes[2].Normalize();
1253
1254     _invB.SetCols( _axes[0], _axes[1], _axes[2] );
1255     _invB.Invert();
1256
1257     // compute tolerance
1258     _minCellSize = Precision::Infinite();
1259     for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
1260     {
1261       for ( size_t i = 1; i < _coords[ iDir ].size(); ++i )
1262       {
1263         double cellLen = _coords[ iDir ][ i ] - _coords[ iDir ][ i-1 ];
1264         if ( cellLen < _minCellSize )
1265           _minCellSize = cellLen;
1266       }
1267     }
1268     if ( _minCellSize < Precision::Confusion() )
1269       throw SMESH_ComputeError (COMPERR_ALGO_FAILED,
1270                                 SMESH_Comment("Too small cell size: ") << _minCellSize );
1271     _tol = _minCellSize / 1000.;
1272
1273     // attune grid extremities to shape bounding box
1274
1275     double sP[6]; // aXmin, aYmin, aZmin, aXmax, aYmax, aZmax
1276     shapeBox.Get(sP[0],sP[1],sP[2],sP[3],sP[4],sP[5]);
1277     double* cP[6] = { &_coords[0].front(), &_coords[1].front(), &_coords[2].front(),
1278                       &_coords[0].back(),  &_coords[1].back(),  &_coords[2].back() };
1279     for ( int i = 0; i < 6; ++i )
1280       if ( fabs( sP[i] - *cP[i] ) < _tol )
1281         *cP[i] = sP[i];// + _tol/1000. * ( i < 3 ? +1 : -1 );
1282
1283     for ( int iDir = 0; iDir < 3; ++iDir )
1284     {
1285       if ( _coords[iDir][0] - sP[iDir] > _tol )
1286       {
1287         _minCellSize = Min( _minCellSize, _coords[iDir][0] - sP[iDir] );
1288         _coords[iDir].insert( _coords[iDir].begin(), sP[iDir] + _tol/1000.);
1289       }
1290       if ( sP[iDir+3] - _coords[iDir].back() > _tol  )
1291       {
1292         _minCellSize = Min( _minCellSize, sP[iDir+3] - _coords[iDir].back() );
1293         _coords[iDir].push_back( sP[iDir+3] - _tol/1000.);
1294       }
1295     }
1296     _tol = _minCellSize / 1000.;
1297
1298     _origin = ( _coords[0][0] * _axes[0] +
1299                 _coords[1][0] * _axes[1] +
1300                 _coords[2][0] * _axes[2] );
1301
1302     // create lines
1303     for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
1304     {
1305       LineIndexer li = GetLineIndexer( iDir );
1306       _lines[iDir].resize( li.NbLines() );
1307       double len = _coords[ iDir ].back() - _coords[iDir].front();
1308       for ( ; li.More(); ++li )
1309       {
1310         GridLine& gl = _lines[iDir][ li.LineIndex() ];
1311         gl._line.SetLocation( _coords[0][li.I()] * _axes[0] +
1312                               _coords[1][li.J()] * _axes[1] +
1313                               _coords[2][li.K()] * _axes[2] );
1314         gl._line.SetDirection( _axes[ iDir ]);
1315         gl._length = len;
1316       }
1317     }
1318   }
1319   //================================================================================
1320   /*
1321    * Return local ID of shape
1322    */
1323   TGeomID Grid::ShapeID( const TopoDS_Shape& s ) const
1324   {
1325     return _helper->GetMeshDS()->ShapeToIndex( s );
1326   }
1327   //================================================================================
1328   /*
1329    * Return a shape by its local ID
1330    */
1331   const TopoDS_Shape& Grid::Shape( TGeomID id ) const
1332   {
1333     return _helper->GetMeshDS()->IndexToShape( id );
1334   }
1335   //================================================================================
1336   /*
1337    * Initialize _geometry
1338    */
1339   void Grid::InitGeometry( const TopoDS_Shape& theShapeToMesh )
1340   {
1341     SMESH_Mesh* mesh = _helper->GetMesh();
1342
1343     _geometry._mainShape = theShapeToMesh;
1344     _geometry._extIntFaceID = mesh->GetMeshDS()->MaxShapeIndex() * 100;
1345     _geometry._soleSolid.SetID( 0 );
1346     _geometry._soleSolid.SetHasInternalFaces( false );
1347
1348     InitClassifier( theShapeToMesh, TopAbs_VERTEX, _geometry._vertexClassifier );
1349     InitClassifier( theShapeToMesh, TopAbs_EDGE  , _geometry._edgeClassifier );
1350
1351     TopExp_Explorer solidExp( theShapeToMesh, TopAbs_SOLID );
1352
1353     bool isSeveralSolids = false;
1354     if ( _toConsiderInternalFaces ) // check nb SOLIDs
1355     {
1356       solidExp.Next();
1357       isSeveralSolids = solidExp.More();
1358       _toConsiderInternalFaces = isSeveralSolids;
1359       solidExp.ReInit();
1360
1361       if ( !isSeveralSolids ) // look for an internal FACE
1362       {
1363         TopExp_Explorer fExp( theShapeToMesh, TopAbs_FACE );
1364         for ( ; fExp.More() &&  !_toConsiderInternalFaces; fExp.Next() )
1365           _toConsiderInternalFaces = ( fExp.Current().Orientation() == TopAbs_INTERNAL );
1366
1367         _geometry._soleSolid.SetHasInternalFaces( _toConsiderInternalFaces );
1368         _geometry._soleSolid.SetID( ShapeID( solidExp.Current() ));
1369       }
1370       else // fill Geometry::_solidByID
1371       {
1372         for ( ; solidExp.More(); solidExp.Next() )
1373         {
1374           OneOfSolids & solid = _geometry._solidByID[ ShapeID( solidExp.Current() )];
1375           solid.Init( solidExp.Current(), TopAbs_FACE,   mesh->GetMeshDS() );
1376           solid.Init( solidExp.Current(), TopAbs_EDGE,   mesh->GetMeshDS() );
1377           solid.Init( solidExp.Current(), TopAbs_VERTEX, mesh->GetMeshDS() );
1378         }
1379       }
1380     }
1381     else
1382     {
1383       _geometry._soleSolid.SetID( ShapeID( solidExp.Current() ));
1384     }
1385
1386     if ( !_toCreateFaces )
1387     {
1388       int nbSolidsGlobal = _helper->Count( mesh->GetShapeToMesh(), TopAbs_SOLID, false );
1389       int nbSolidsLocal  = _helper->Count( theShapeToMesh,         TopAbs_SOLID, false );
1390       _toCreateFaces = ( nbSolidsLocal < nbSolidsGlobal );
1391     }
1392
1393     TopTools_IndexedMapOfShape faces;
1394     if ( _toCreateFaces || isSeveralSolids )
1395       TopExp::MapShapes( theShapeToMesh, TopAbs_FACE, faces );
1396
1397     // find boundary FACEs on boundary of mesh->ShapeToMesh()
1398     if ( _toCreateFaces )
1399       for ( int i = 1; i <= faces.Size(); ++i )
1400         if ( faces(i).Orientation() != TopAbs_INTERNAL &&
1401              _helper->NbAncestors( faces(i), *mesh, TopAbs_SOLID ) == 1 )
1402         {
1403           _geometry._boundaryFaces.Add( ShapeID( faces(i) ));
1404         }
1405
1406     if ( isSeveralSolids )
1407       for ( int i = 1; i <= faces.Size(); ++i )
1408       {
1409         SetSolidFather( faces(i), theShapeToMesh );
1410         for ( TopExp_Explorer eExp( faces(i), TopAbs_EDGE ); eExp.More(); eExp.Next() )
1411         {
1412           const TopoDS_Edge& edge = TopoDS::Edge( eExp.Current() );
1413           SetSolidFather( edge, theShapeToMesh );
1414           SetSolidFather( _helper->IthVertex( 0, edge ), theShapeToMesh );
1415           SetSolidFather( _helper->IthVertex( 1, edge ), theShapeToMesh );
1416         }
1417       }
1418     return;
1419   }
1420   //================================================================================
1421   /*
1422    * Store ID of SOLID as father of its child shape ID
1423    */
1424   void Grid::SetSolidFather( const TopoDS_Shape& s, const TopoDS_Shape& theShapeToMesh )
1425   {
1426     if ( _geometry._solidIDsByShapeID.empty() )
1427       _geometry._solidIDsByShapeID.resize( _helper->GetMeshDS()->MaxShapeIndex() + 1 );
1428
1429     vector< TGeomID > & solidIDs = _geometry._solidIDsByShapeID[ ShapeID( s )];
1430     if ( !solidIDs.empty() )
1431       return;
1432     solidIDs.reserve(2);
1433     PShapeIteratorPtr solidIt = _helper->GetAncestors( s,
1434                                                        *_helper->GetMesh(),
1435                                                        TopAbs_SOLID,
1436                                                        & theShapeToMesh );
1437     while ( const TopoDS_Shape* solid = solidIt->next() )
1438       solidIDs.push_back( ShapeID( *solid ));
1439   }
1440   //================================================================================
1441   /*
1442    * Return IDs of solids given sub-shape belongs to
1443    */
1444   const vector< TGeomID > & Grid::GetSolidIDs( TGeomID subShapeID ) const
1445   {
1446     return _geometry._solidIDsByShapeID[ subShapeID ];
1447   }
1448   //================================================================================
1449   /*
1450    * Check if a sub-shape belongs to several SOLIDs
1451    */
1452   bool Grid::IsShared( TGeomID shapeID ) const
1453   {
1454     return !_geometry.IsOneSolid() && ( _geometry._solidIDsByShapeID[ shapeID ].size() > 1 );
1455   }
1456   //================================================================================
1457   /*
1458    * Check if any of FACEs belongs to several SOLIDs
1459    */
1460   bool Grid::IsAnyShared( const std::vector< TGeomID >& faceIDs ) const
1461   {
1462     for ( size_t i = 0; i < faceIDs.size(); ++i )
1463       if ( IsShared( faceIDs[ i ]))
1464         return true;
1465     return false;
1466   }
1467   //================================================================================
1468   /*
1469    * Return Solid by ID
1470    */
1471   Solid* Grid::GetSolid( TGeomID solidID )
1472   {
1473     if ( !solidID || _geometry.IsOneSolid() || _geometry._solidByID.empty() )
1474       return & _geometry._soleSolid;
1475
1476     return & _geometry._solidByID[ solidID ];
1477   }
1478   //================================================================================
1479   /*
1480    * Return OneOfSolids by ID
1481    */
1482   Solid* Grid::GetOneOfSolids( TGeomID solidID )
1483   {
1484     map< TGeomID, OneOfSolids >::iterator is2s = _geometry._solidByID.find( solidID );
1485     if ( is2s != _geometry._solidByID.end() )
1486       return & is2s->second;
1487
1488     return & _geometry._soleSolid;
1489   }
1490   //================================================================================
1491   /*
1492    * Check if transition on given FACE is correct for a given SOLID
1493    */
1494   bool Grid::IsCorrectTransition( TGeomID faceID, const Solid* solid )
1495   {
1496     if ( _geometry.IsOneSolid() )
1497       return true;
1498
1499     const vector< TGeomID >& solidIDs = _geometry._solidIDsByShapeID[ faceID ];
1500     return solidIDs[0] == solid->ID();
1501   }
1502
1503   //================================================================================
1504   /*
1505    * Assign to geometry a node at FACE intersection
1506    */
1507   void Grid::SetOnShape( const SMDS_MeshNode* n, const F_IntersectPoint& ip, bool unset )
1508   {
1509     TopoDS_Shape s;
1510     SMESHDS_Mesh* mesh = _helper->GetMeshDS();
1511     if ( ip._faceIDs.size() == 1 )
1512     {
1513       mesh->SetNodeOnFace( n, ip._faceIDs[0], ip._u, ip._v );
1514     }
1515     else if ( _geometry._vertexClassifier.IsSatisfy( n, &s ))
1516     {
1517       if ( unset ) mesh->UnSetNodeOnShape( n );
1518       mesh->SetNodeOnVertex( n, TopoDS::Vertex( s ));
1519     }
1520     else if ( _geometry._edgeClassifier.IsSatisfy( n, &s ))
1521     {
1522       if ( unset ) mesh->UnSetNodeOnShape( n );
1523       mesh->SetNodeOnEdge( n, TopoDS::Edge( s ));
1524     }
1525     else if ( ip._faceIDs.size() > 0 )
1526     {
1527       mesh->SetNodeOnFace( n, ip._faceIDs[0], ip._u, ip._v );
1528     }
1529     else if ( !unset && _geometry.IsOneSolid() )
1530     {
1531       mesh->SetNodeInVolume( n, _geometry._soleSolid.ID() );
1532     }
1533   }
1534   //================================================================================
1535   /*
1536    * Initialize a classifier
1537    */
1538   void Grid::InitClassifier( const TopoDS_Shape&        mainShape,
1539                              TopAbs_ShapeEnum           shapeType,
1540                              Controls::ElementsOnShape& classifier )
1541   {
1542     TopTools_IndexedMapOfShape shapes;
1543     TopExp::MapShapes( mainShape, shapeType, shapes );
1544
1545     TopoDS_Compound compound; BRep_Builder builder;
1546     builder.MakeCompound( compound );
1547     for ( int i = 1; i <= shapes.Size(); ++i )
1548       builder.Add( compound, shapes(i) );
1549
1550     classifier.SetMesh( _helper->GetMeshDS() );
1551     //classifier.SetTolerance( _tol ); // _tol is not initialised
1552     classifier.SetShape( compound, SMDSAbs_Node );
1553   }
1554
1555   //================================================================================
1556   /*
1557    * Return EDGEs with FACEs to implement into the mesh
1558    */
1559   void Grid::GetEdgesToImplement( map< TGeomID, vector< TGeomID > > & edge2faceIDsMap,
1560                                   const TopoDS_Shape&                 shape,
1561                                   const vector< TopoDS_Shape >&       faces )
1562   {
1563     // check if there are strange EDGEs
1564     TopTools_IndexedMapOfShape faceMap;
1565     TopExp::MapShapes( _helper->GetMesh()->GetShapeToMesh(), TopAbs_FACE, faceMap );
1566     int nbFacesGlobal = faceMap.Size();
1567     faceMap.Clear( false );
1568     TopExp::MapShapes( shape, TopAbs_FACE, faceMap );
1569     int nbFacesLocal  = faceMap.Size();
1570     bool hasStrangeEdges = ( nbFacesGlobal > nbFacesLocal );
1571     if ( !_toAddEdges && !hasStrangeEdges )
1572       return; // no FACEs in contact with those meshed by other algo
1573
1574     for ( size_t i = 0; i < faces.size(); ++i )
1575     {
1576       _helper->SetSubShape( faces[i] );
1577       for ( TopExp_Explorer eExp( faces[i], TopAbs_EDGE ); eExp.More(); eExp.Next() )
1578       {
1579         const TopoDS_Edge& edge = TopoDS::Edge( eExp.Current() );
1580         if ( hasStrangeEdges )
1581         {
1582           bool hasStrangeFace = false;
1583           PShapeIteratorPtr faceIt = _helper->GetAncestors( edge, *_helper->GetMesh(), TopAbs_FACE);
1584           while ( const TopoDS_Shape* face = faceIt->next() )
1585             if (( hasStrangeFace = !faceMap.Contains( *face )))
1586               break;
1587           if ( !hasStrangeFace && !_toAddEdges )
1588             continue;
1589           _geometry._strangeEdges.Add( ShapeID( edge ));
1590           _geometry._strangeEdges.Add( ShapeID( _helper->IthVertex( 0, edge )));
1591           _geometry._strangeEdges.Add( ShapeID( _helper->IthVertex( 1, edge )));
1592         }
1593         if ( !SMESH_Algo::isDegenerated( edge ) &&
1594              !_helper->IsRealSeam( edge ))
1595         {
1596           edge2faceIDsMap[ ShapeID( edge )].push_back( ShapeID( faces[i] ));
1597         }
1598       }
1599     }
1600     return;
1601   }
1602
1603   //================================================================================
1604   /*
1605    * Computes coordinates of a point in the grid CS
1606    */
1607   void Grid::ComputeUVW(const gp_XYZ& P, double UVW[3])
1608   {
1609     gp_XYZ p = P * _invB;
1610     p.Coord( UVW[0], UVW[1], UVW[2] );
1611   }
1612   //================================================================================
1613   /*
1614    * Creates all nodes
1615    */
1616   void Grid::ComputeNodes(SMESH_MesherHelper& helper)
1617   {
1618     // state of each node of the grid relative to the geometry
1619     const size_t nbGridNodes = _coords[0].size() * _coords[1].size() * _coords[2].size();
1620     const TGeomID undefID = 1e+9;
1621     vector< TGeomID > shapeIDVec( nbGridNodes, undefID );
1622     _nodes.resize( nbGridNodes, 0 );
1623     _gridIntP.resize( nbGridNodes, NULL );
1624
1625     SMESHDS_Mesh* mesh = helper.GetMeshDS();
1626
1627     for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
1628     {
1629       LineIndexer li = GetLineIndexer( iDir );
1630
1631       // find out a shift of node index while walking along a GridLine in this direction
1632       li.SetIndexOnLine( 0 );
1633       size_t nIndex0 = NodeIndex( li.I(), li.J(), li.K() );
1634       li.SetIndexOnLine( 1 );
1635       const size_t nShift = NodeIndex( li.I(), li.J(), li.K() ) - nIndex0;
1636       
1637       const vector<double> & coords = _coords[ iDir ];
1638       for ( ; li.More(); ++li ) // loop on lines in iDir
1639       {
1640         li.SetIndexOnLine( 0 );
1641         nIndex0 = NodeIndex( li.I(), li.J(), li.K() );
1642
1643         GridLine& line = _lines[ iDir ][ li.LineIndex() ];
1644         const gp_XYZ lineLoc = line._line.Location().XYZ();
1645         const gp_XYZ lineDir = line._line.Direction().XYZ();
1646
1647         line.RemoveExcessIntPoints( _tol );
1648         multiset< F_IntersectPoint >&     intPnts = line._intPoints;
1649         multiset< F_IntersectPoint >::iterator ip = intPnts.begin();
1650
1651         // Create mesh nodes at intersections with geometry
1652         // and set OUT state of nodes between intersections
1653
1654         TGeomID solidID = 0;
1655         const double* nodeCoord = & coords[0];
1656         const double* coord0    = nodeCoord;
1657         const double* coordEnd  = coord0 + coords.size();
1658         double nodeParam = 0;
1659         for ( ; ip != intPnts.end(); ++ip )
1660         {
1661           solidID = line.GetSolidIDBefore( ip, solidID, _geometry );
1662
1663           // set OUT state or just skip IN nodes before ip
1664           if ( nodeParam < ip->_paramOnLine - _tol )
1665           {
1666             while ( nodeParam < ip->_paramOnLine - _tol )
1667             {
1668               TGeomID & nodeShapeID = shapeIDVec[ nIndex0 + nShift * ( nodeCoord-coord0 ) ];
1669               nodeShapeID = Min( solidID, nodeShapeID );
1670               if ( ++nodeCoord <  coordEnd )
1671                 nodeParam = *nodeCoord - *coord0;
1672               else
1673                 break;
1674             }
1675             if ( nodeCoord == coordEnd ) break;
1676           }
1677           // create a mesh node on a GridLine at ip if it does not coincide with a grid node
1678           if ( nodeParam > ip->_paramOnLine + _tol )
1679           {
1680             gp_XYZ xyz = lineLoc + ip->_paramOnLine * lineDir;
1681             ip->_node = mesh->AddNode( xyz.X(), xyz.Y(), xyz.Z() );
1682             ip->_indexOnLine = nodeCoord-coord0-1;
1683             SetOnShape( ip->_node, *ip );
1684           }
1685           // create a mesh node at ip coincident with a grid node
1686           else
1687           {
1688             int nodeIndex = nIndex0 + nShift * ( nodeCoord-coord0 );
1689             if ( !_nodes[ nodeIndex ] )
1690             {
1691               gp_XYZ xyz = lineLoc + nodeParam * lineDir;
1692               _nodes   [ nodeIndex ] = mesh->AddNode( xyz.X(), xyz.Y(), xyz.Z() );
1693               //_gridIntP[ nodeIndex ] = & * ip;
1694               //SetOnShape( _nodes[ nodeIndex ], *ip );
1695             }
1696             if ( _gridIntP[ nodeIndex ] )
1697               _gridIntP[ nodeIndex ]->Add( ip->_faceIDs );
1698             else
1699               _gridIntP[ nodeIndex ] = & * ip;
1700             // ip->_node        = _nodes[ nodeIndex ]; -- to differ from ip on links
1701             ip->_indexOnLine = nodeCoord-coord0;
1702             if ( ++nodeCoord < coordEnd )
1703               nodeParam = *nodeCoord - *coord0;
1704           }
1705         }
1706         // set OUT state to nodes after the last ip
1707         for ( ; nodeCoord < coordEnd; ++nodeCoord )
1708           shapeIDVec[ nIndex0 + nShift * ( nodeCoord-coord0 ) ] = 0;
1709       }
1710     }
1711
1712     // Create mesh nodes at !OUT nodes of the grid
1713
1714     for ( size_t z = 0; z < _coords[2].size(); ++z )
1715       for ( size_t y = 0; y < _coords[1].size(); ++y )
1716         for ( size_t x = 0; x < _coords[0].size(); ++x )
1717         {
1718           size_t nodeIndex = NodeIndex( x, y, z );
1719           if ( !_nodes[ nodeIndex ] &&
1720                0 < shapeIDVec[ nodeIndex ] && shapeIDVec[ nodeIndex ] < undefID )
1721           {
1722             gp_XYZ xyz = ( _coords[0][x] * _axes[0] +
1723                            _coords[1][y] * _axes[1] +
1724                            _coords[2][z] * _axes[2] );
1725             _nodes[ nodeIndex ] = mesh->AddNode( xyz.X(), xyz.Y(), xyz.Z() );
1726             mesh->SetNodeInVolume( _nodes[ nodeIndex ], shapeIDVec[ nodeIndex ]);
1727           }
1728           else if ( _nodes[ nodeIndex ] && _gridIntP[ nodeIndex ] /*&&
1729                     !_nodes[ nodeIndex]->GetShapeID()*/ )
1730           {
1731             SetOnShape( _nodes[ nodeIndex ], *_gridIntP[ nodeIndex ]);
1732           }
1733         }
1734
1735 #ifdef _MY_DEBUG_
1736     // check validity of transitions
1737     const char* trName[] = { "TANGENT", "IN", "OUT", "APEX" };
1738     for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
1739     {
1740       LineIndexer li = GetLineIndexer( iDir );
1741       for ( ; li.More(); ++li )
1742       {
1743         multiset< F_IntersectPoint >& intPnts = _lines[ iDir ][ li.LineIndex() ]._intPoints;
1744         if ( intPnts.empty() ) continue;
1745         if ( intPnts.size() == 1 )
1746         {
1747           if ( intPnts.begin()->_transition != Trans_TANGENT &&
1748                intPnts.begin()->_transition != Trans_APEX )
1749           throw SMESH_ComputeError (COMPERR_ALGO_FAILED,
1750                                     SMESH_Comment("Wrong SOLE transition of GridLine (")
1751                                     << li._curInd[li._iVar1] << ", " << li._curInd[li._iVar2]
1752                                     << ") along " << li._nameConst
1753                                     << ": " << trName[ intPnts.begin()->_transition] );
1754         }
1755         else
1756         {
1757           if ( intPnts.begin()->_transition == Trans_OUT )
1758             throw SMESH_ComputeError (COMPERR_ALGO_FAILED,
1759                                       SMESH_Comment("Wrong START transition of GridLine (")
1760                                       << li._curInd[li._iVar1] << ", " << li._curInd[li._iVar2]
1761                                       << ") along " << li._nameConst
1762                                       << ": " << trName[ intPnts.begin()->_transition ]);
1763           if ( intPnts.rbegin()->_transition == Trans_IN )
1764             throw SMESH_ComputeError (COMPERR_ALGO_FAILED,
1765                                       SMESH_Comment("Wrong END transition of GridLine (")
1766                                       << li._curInd[li._iVar1] << ", " << li._curInd[li._iVar2]
1767                                       << ") along " << li._nameConst
1768                                     << ": " << trName[ intPnts.rbegin()->_transition ]);
1769         }
1770       }
1771     }
1772 #endif
1773   }
1774
1775   //=============================================================================
1776   /*
1777    * Intersects TopoDS_Face with all GridLine's
1778    */
1779   void FaceGridIntersector::Intersect()
1780   {
1781     FaceLineIntersector intersector;
1782     intersector._surfaceInt = GetCurveFaceIntersector();
1783     intersector._tol        = _grid->_tol;
1784     intersector._transOut   = _face.Orientation() == TopAbs_REVERSED ? Trans_IN : Trans_OUT;
1785     intersector._transIn    = _face.Orientation() == TopAbs_REVERSED ? Trans_OUT : Trans_IN;
1786
1787     typedef void (FaceLineIntersector::* PIntFun )(const GridLine& gridLine);
1788     PIntFun interFunction;
1789
1790     bool isDirect = true;
1791     BRepAdaptor_Surface surf( _face );
1792     switch ( surf.GetType() ) {
1793     case GeomAbs_Plane:
1794       intersector._plane = surf.Plane();
1795       interFunction = &FaceLineIntersector::IntersectWithPlane;
1796       isDirect = intersector._plane.Direct();
1797       break;
1798     case GeomAbs_Cylinder:
1799       intersector._cylinder = surf.Cylinder();
1800       interFunction = &FaceLineIntersector::IntersectWithCylinder;
1801       isDirect = intersector._cylinder.Direct();
1802       break;
1803     case GeomAbs_Cone:
1804       intersector._cone = surf.Cone();
1805       interFunction = &FaceLineIntersector::IntersectWithCone;
1806       //isDirect = intersector._cone.Direct();
1807       break;
1808     case GeomAbs_Sphere:
1809       intersector._sphere = surf.Sphere();
1810       interFunction = &FaceLineIntersector::IntersectWithSphere;
1811       isDirect = intersector._sphere.Direct();
1812       break;
1813     case GeomAbs_Torus:
1814       intersector._torus = surf.Torus();
1815       interFunction = &FaceLineIntersector::IntersectWithTorus;
1816       //isDirect = intersector._torus.Direct();
1817       break;
1818     default:
1819       interFunction = &FaceLineIntersector::IntersectWithSurface;
1820     }
1821     if ( !isDirect )
1822       std::swap( intersector._transOut, intersector._transIn );
1823
1824     _intersections.clear();
1825     for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
1826     {
1827       if ( surf.GetType() == GeomAbs_Plane )
1828       {
1829         // check if all lines in this direction are parallel to a plane
1830         if ( intersector._plane.Axis().IsNormal( _grid->_lines[iDir][0]._line.Position(),
1831                                                  Precision::Angular()))
1832           continue;
1833         // find out a transition, that is the same for all lines of a direction
1834         gp_Dir plnNorm = intersector._plane.Axis().Direction();
1835         gp_Dir lineDir = _grid->_lines[iDir][0]._line.Direction();
1836         intersector._transition =
1837           ( plnNorm * lineDir < 0 ) ? intersector._transIn : intersector._transOut;
1838       }
1839       if ( surf.GetType() == GeomAbs_Cylinder )
1840       {
1841         // check if all lines in this direction are parallel to a cylinder
1842         if ( intersector._cylinder.Axis().IsParallel( _grid->_lines[iDir][0]._line.Position(),
1843                                                       Precision::Angular()))
1844           continue;
1845       }
1846
1847       // intersect the grid lines with the face
1848       for ( size_t iL = 0; iL < _grid->_lines[iDir].size(); ++iL )
1849       {
1850         GridLine& gridLine = _grid->_lines[iDir][iL];
1851         if ( _bndBox.IsOut( gridLine._line )) continue;
1852
1853         intersector._intPoints.clear();
1854         (intersector.*interFunction)( gridLine ); // <- intersection with gridLine
1855         for ( size_t i = 0; i < intersector._intPoints.size(); ++i )
1856           _intersections.push_back( make_pair( &gridLine, intersector._intPoints[i] ));
1857       }
1858     }
1859
1860     if ( _face.Orientation() == TopAbs_INTERNAL )
1861     {
1862       for ( size_t i = 0; i < _intersections.size(); ++i )
1863         if ( _intersections[i].second._transition == Trans_IN ||
1864              _intersections[i].second._transition == Trans_OUT )
1865         {
1866           _intersections[i].second._transition = Trans_INTERNAL;
1867         }
1868     }
1869     return;
1870   }
1871   //================================================================================
1872   /*
1873    * Return true if (_u,_v) is on the face
1874    */
1875   bool FaceLineIntersector::UVIsOnFace() const
1876   {
1877     TopAbs_State state = _surfaceInt->ClassifyUVPoint(gp_Pnt2d( _u,_v ));
1878     return ( state == TopAbs_IN || state == TopAbs_ON );
1879   }
1880   //================================================================================
1881   /*
1882    * Store an intersection if it is IN or ON the face
1883    */
1884   void FaceLineIntersector::addIntPoint(const bool toClassify)
1885   {
1886     if ( !toClassify || UVIsOnFace() )
1887     {
1888       F_IntersectPoint p;
1889       p._paramOnLine = _w;
1890       p._u           = _u;
1891       p._v           = _v;
1892       p._transition  = _transition;
1893       _intPoints.push_back( p );
1894     }
1895   }
1896   //================================================================================
1897   /*
1898    * Intersect a line with a plane
1899    */
1900   void FaceLineIntersector::IntersectWithPlane(const GridLine& gridLine)
1901   {
1902     IntAna_IntConicQuad linPlane( gridLine._line, _plane, Precision::Angular());
1903     _w = linPlane.ParamOnConic(1);
1904     if ( isParamOnLineOK( gridLine._length ))
1905     {
1906       ElSLib::Parameters(_plane, linPlane.Point(1) ,_u,_v);
1907       addIntPoint();
1908     }
1909   }
1910   //================================================================================
1911   /*
1912    * Intersect a line with a cylinder
1913    */
1914   void FaceLineIntersector::IntersectWithCylinder(const GridLine& gridLine)
1915   {
1916     IntAna_IntConicQuad linCylinder( gridLine._line, _cylinder );
1917     if ( linCylinder.IsDone() && linCylinder.NbPoints() > 0 )
1918     {
1919       _w = linCylinder.ParamOnConic(1);
1920       if ( linCylinder.NbPoints() == 1 )
1921         _transition = Trans_TANGENT;
1922       else
1923         _transition = _w < linCylinder.ParamOnConic(2) ? _transIn : _transOut;
1924       if ( isParamOnLineOK( gridLine._length ))
1925       {
1926         ElSLib::Parameters(_cylinder, linCylinder.Point(1) ,_u,_v);
1927         addIntPoint();
1928       }
1929       if ( linCylinder.NbPoints() > 1 )
1930       {
1931         _w = linCylinder.ParamOnConic(2);
1932         if ( isParamOnLineOK( gridLine._length ))
1933         {
1934           ElSLib::Parameters(_cylinder, linCylinder.Point(2) ,_u,_v);
1935           _transition = ( _transition == Trans_OUT ) ? Trans_IN : Trans_OUT;
1936           addIntPoint();
1937         }
1938       }
1939     }
1940   }
1941   //================================================================================
1942   /*
1943    * Intersect a line with a cone
1944    */
1945   void FaceLineIntersector::IntersectWithCone (const GridLine& gridLine)
1946   {
1947     IntAna_IntConicQuad linCone(gridLine._line,_cone);
1948     if ( !linCone.IsDone() ) return;
1949     gp_Pnt P;
1950     gp_Vec du, dv, norm;
1951     for ( int i = 1; i <= linCone.NbPoints(); ++i )
1952     {
1953       _w = linCone.ParamOnConic( i );
1954       if ( !isParamOnLineOK( gridLine._length )) continue;
1955       ElSLib::Parameters(_cone, linCone.Point(i) ,_u,_v);
1956       if ( UVIsOnFace() )
1957       {
1958         ElSLib::D1( _u, _v, _cone, P, du, dv );
1959         norm = du ^ dv;
1960         double normSize2 = norm.SquareMagnitude();
1961         if ( normSize2 > Precision::Angular() * Precision::Angular() )
1962         {
1963           double cos = norm.XYZ() * gridLine._line.Direction().XYZ();
1964           cos /= sqrt( normSize2 );
1965           if ( cos < -Precision::Angular() )
1966             _transition = _transIn;
1967           else if ( cos > Precision::Angular() )
1968             _transition = _transOut;
1969           else
1970             _transition = Trans_TANGENT;
1971         }
1972         else
1973         {
1974           _transition = Trans_APEX;
1975         }
1976         addIntPoint( /*toClassify=*/false);
1977       }
1978     }
1979   }
1980   //================================================================================
1981   /*
1982    * Intersect a line with a sphere
1983    */
1984   void FaceLineIntersector::IntersectWithSphere  (const GridLine& gridLine)
1985   {
1986     IntAna_IntConicQuad linSphere(gridLine._line,_sphere);
1987     if ( linSphere.IsDone() && linSphere.NbPoints() > 0 )
1988     {
1989       _w = linSphere.ParamOnConic(1);
1990       if ( linSphere.NbPoints() == 1 )
1991         _transition = Trans_TANGENT;
1992       else
1993         _transition = _w < linSphere.ParamOnConic(2) ? _transIn : _transOut;
1994       if ( isParamOnLineOK( gridLine._length ))
1995       {
1996         ElSLib::Parameters(_sphere, linSphere.Point(1) ,_u,_v);
1997         addIntPoint();
1998       }
1999       if ( linSphere.NbPoints() > 1 )
2000       {
2001         _w = linSphere.ParamOnConic(2);
2002         if ( isParamOnLineOK( gridLine._length ))
2003         {
2004           ElSLib::Parameters(_sphere, linSphere.Point(2) ,_u,_v);
2005           _transition = ( _transition == Trans_OUT ) ? Trans_IN : Trans_OUT;
2006           addIntPoint();
2007         }
2008       }
2009     }
2010   }
2011   //================================================================================
2012   /*
2013    * Intersect a line with a torus
2014    */
2015   void FaceLineIntersector::IntersectWithTorus   (const GridLine& gridLine)
2016   {
2017     IntAna_IntLinTorus linTorus(gridLine._line,_torus);
2018     if ( !linTorus.IsDone()) return;
2019     gp_Pnt P;
2020     gp_Vec du, dv, norm;
2021     for ( int i = 1; i <= linTorus.NbPoints(); ++i )
2022     {
2023       _w = linTorus.ParamOnLine( i );
2024       if ( !isParamOnLineOK( gridLine._length )) continue;
2025       linTorus.ParamOnTorus( i, _u,_v );
2026       if ( UVIsOnFace() )
2027       {
2028         ElSLib::D1( _u, _v, _torus, P, du, dv );
2029         norm = du ^ dv;
2030         double normSize = norm.Magnitude();
2031         double cos = norm.XYZ() * gridLine._line.Direction().XYZ();
2032         cos /= normSize;
2033         if ( cos < -Precision::Angular() )
2034           _transition = _transIn;
2035         else if ( cos > Precision::Angular() )
2036           _transition = _transOut;
2037         else
2038           _transition = Trans_TANGENT;
2039         addIntPoint( /*toClassify=*/false);
2040       }
2041     }
2042   }
2043   //================================================================================
2044   /*
2045    * Intersect a line with a non-analytical surface
2046    */
2047   void FaceLineIntersector::IntersectWithSurface (const GridLine& gridLine)
2048   {
2049     _surfaceInt->Perform( gridLine._line, 0.0, gridLine._length );
2050     if ( !_surfaceInt->IsDone() ) return;
2051     for ( int i = 1; i <= _surfaceInt->NbPnt(); ++i )
2052     {
2053       _transition = Transition( _surfaceInt->Transition( i ) );
2054       _w = _surfaceInt->WParameter( i );
2055       addIntPoint(/*toClassify=*/false);
2056     }
2057   }
2058   //================================================================================
2059   /*
2060    * check if its face can be safely intersected in a thread
2061    */
2062   bool FaceGridIntersector::IsThreadSafe(set< const Standard_Transient* >& noSafeTShapes) const
2063   {
2064     bool isSafe = true;
2065
2066     // check surface
2067     TopLoc_Location loc;
2068     Handle(Geom_Surface) surf = BRep_Tool::Surface( _face, loc );
2069     Handle(Geom_RectangularTrimmedSurface) ts =
2070       Handle(Geom_RectangularTrimmedSurface)::DownCast( surf );
2071     while( !ts.IsNull() ) {
2072       surf = ts->BasisSurface();
2073       ts = Handle(Geom_RectangularTrimmedSurface)::DownCast(surf);
2074     }
2075     if ( surf->IsKind( STANDARD_TYPE(Geom_BSplineSurface )) ||
2076          surf->IsKind( STANDARD_TYPE(Geom_BezierSurface )))
2077       if ( !noSafeTShapes.insert( _face.TShape().get() ).second )
2078         isSafe = false;
2079
2080     double f, l;
2081     TopExp_Explorer exp( _face, TopAbs_EDGE );
2082     for ( ; exp.More(); exp.Next() )
2083     {
2084       bool edgeIsSafe = true;
2085       const TopoDS_Edge& e = TopoDS::Edge( exp.Current() );
2086       // check 3d curve
2087       {
2088         Handle(Geom_Curve) c = BRep_Tool::Curve( e, loc, f, l);
2089         if ( !c.IsNull() )
2090         {
2091           Handle(Geom_TrimmedCurve) tc = Handle(Geom_TrimmedCurve)::DownCast(c);
2092           while( !tc.IsNull() ) {
2093             c = tc->BasisCurve();
2094             tc = Handle(Geom_TrimmedCurve)::DownCast(c);
2095           }
2096           if ( c->IsKind( STANDARD_TYPE(Geom_BSplineCurve )) ||
2097                c->IsKind( STANDARD_TYPE(Geom_BezierCurve )))
2098             edgeIsSafe = false;
2099         }
2100       }
2101       // check 2d curve
2102       if ( edgeIsSafe )
2103       {
2104         Handle(Geom2d_Curve) c2 = BRep_Tool::CurveOnSurface( e, surf, loc, f, l);
2105         if ( !c2.IsNull() )
2106         {
2107           Handle(Geom2d_TrimmedCurve) tc = Handle(Geom2d_TrimmedCurve)::DownCast(c2);
2108           while( !tc.IsNull() ) {
2109             c2 = tc->BasisCurve();
2110             tc = Handle(Geom2d_TrimmedCurve)::DownCast(c2);
2111           }
2112           if ( c2->IsKind( STANDARD_TYPE(Geom2d_BSplineCurve )) ||
2113                c2->IsKind( STANDARD_TYPE(Geom2d_BezierCurve )))
2114             edgeIsSafe = false;
2115         }
2116       }
2117       if ( !edgeIsSafe && !noSafeTShapes.insert( e.TShape().get() ).second )
2118         isSafe = false;
2119     }
2120     return isSafe;
2121   }
2122   //================================================================================
2123   /*!
2124    * \brief Creates topology of the hexahedron
2125    */
2126   Hexahedron::Hexahedron(Grid* grid)
2127     : _grid( grid ), _nbFaceIntNodes(0), _hasTooSmall( false )
2128   {
2129     _polygons.reserve(100); // to avoid reallocation;
2130
2131     //set nodes shift within grid->_nodes from the node 000 
2132     size_t dx = _grid->NodeIndexDX();
2133     size_t dy = _grid->NodeIndexDY();
2134     size_t dz = _grid->NodeIndexDZ();
2135     size_t i000 = 0;
2136     size_t i100 = i000 + dx;
2137     size_t i010 = i000 + dy;
2138     size_t i110 = i010 + dx;
2139     size_t i001 = i000 + dz;
2140     size_t i101 = i100 + dz;
2141     size_t i011 = i010 + dz;
2142     size_t i111 = i110 + dz;
2143     grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V000 )] = i000;
2144     grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V100 )] = i100;
2145     grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V010 )] = i010;
2146     grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V110 )] = i110;
2147     grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V001 )] = i001;
2148     grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V101 )] = i101;
2149     grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V011 )] = i011;
2150     grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V111 )] = i111;
2151
2152     vector< int > idVec;
2153     // set nodes to links
2154     for ( int linkID = SMESH_Block::ID_Ex00; linkID <= SMESH_Block::ID_E11z; ++linkID )
2155     {
2156       SMESH_Block::GetEdgeVertexIDs( linkID, idVec );
2157       _Link& link = _hexLinks[ SMESH_Block::ShapeIndex( linkID )];
2158       link._nodes[0] = &_hexNodes[ SMESH_Block::ShapeIndex( idVec[0] )];
2159       link._nodes[1] = &_hexNodes[ SMESH_Block::ShapeIndex( idVec[1] )];
2160     }
2161
2162     // set links to faces
2163     int interlace[4] = { 0, 3, 1, 2 }; // to walk by links around a face: { u0, 1v, u1, 0v }
2164     for ( int faceID = SMESH_Block::ID_Fxy0; faceID <= SMESH_Block::ID_F1yz; ++faceID )
2165     {
2166       _Face& quad = _hexQuads[ SMESH_Block::ShapeIndex( faceID )];
2167       quad._name = (SMESH_Block::TShapeID) faceID;
2168
2169       SMESH_Block::GetFaceEdgesIDs( faceID, idVec );
2170       bool revFace = ( faceID == SMESH_Block::ID_Fxy0 ||
2171                        faceID == SMESH_Block::ID_Fx1z ||
2172                        faceID == SMESH_Block::ID_F0yz );
2173       quad._links.resize(4);
2174       vector<_OrientedLink>::iterator         frwLinkIt = quad._links.begin();
2175       vector<_OrientedLink>::reverse_iterator revLinkIt = quad._links.rbegin();
2176       for ( int i = 0; i < 4; ++i )
2177       {
2178         bool revLink = revFace;
2179         if ( i > 1 ) // reverse links u1 and v0
2180           revLink = !revLink;
2181         _OrientedLink& link = revFace ? *revLinkIt++ : *frwLinkIt++;
2182         link = _OrientedLink( & _hexLinks[ SMESH_Block::ShapeIndex( idVec[interlace[i]] )],
2183                               revLink );
2184       }
2185     }
2186   }
2187   //================================================================================
2188   /*!
2189    * \brief Copy constructor
2190    */
2191   Hexahedron::Hexahedron( const Hexahedron& other, size_t i, size_t j, size_t k, int cellID )
2192     :_grid( other._grid ), _nbFaceIntNodes(0), _i( i ), _j( j ), _k( k ), _hasTooSmall( false )
2193   {
2194     _polygons.reserve(100); // to avoid reallocation;
2195
2196     // copy topology
2197     for ( int i = 0; i < 12; ++i )
2198     {
2199       const _Link& srcLink = other._hexLinks[ i ];
2200       _Link&       tgtLink = this->_hexLinks[ i ];
2201       tgtLink._nodes[0] = _hexNodes + ( srcLink._nodes[0] - other._hexNodes );
2202       tgtLink._nodes[1] = _hexNodes + ( srcLink._nodes[1] - other._hexNodes );
2203     }
2204
2205     for ( int i = 0; i < 6; ++i )
2206     {
2207       const _Face& srcQuad = other._hexQuads[ i ];
2208       _Face&       tgtQuad = this->_hexQuads[ i ];
2209       tgtQuad._name = srcQuad._name;
2210       tgtQuad._links.resize(4);
2211       for ( int j = 0; j < 4; ++j )
2212       {
2213         const _OrientedLink& srcLink = srcQuad._links[ j ];
2214         _OrientedLink&       tgtLink = tgtQuad._links[ j ];
2215         tgtLink._reverse = srcLink._reverse;
2216         tgtLink._link    = _hexLinks + ( srcLink._link - other._hexLinks );
2217       }
2218     }
2219 #ifdef _DEBUG_
2220     _cellID = cellID;
2221 #endif
2222   }
2223
2224   //================================================================================
2225   /*!
2226    * \brief Return IDs of SOLIDs interfering with this Hexahedron
2227    */
2228   size_t Hexahedron::getSolids( TGeomID ids[] )
2229   {
2230     if ( _grid->_geometry.IsOneSolid() )
2231     {
2232       ids[0] = _grid->GetSolid()->ID();
2233       return 1;
2234     }
2235     // count intersection points belonging to each SOLID
2236     TID2Nb id2NbPoints;
2237     id2NbPoints.reserve( 3 );
2238
2239     _origNodeInd = _grid->NodeIndex( _i,_j,_k );
2240     for ( int iN = 0; iN < 8; ++iN )
2241     {
2242       _hexNodes[iN]._node     = _grid->_nodes   [ _origNodeInd + _grid->_nodeShift[iN] ];
2243       _hexNodes[iN]._intPoint = _grid->_gridIntP[ _origNodeInd + _grid->_nodeShift[iN] ];
2244
2245       if ( _hexNodes[iN]._intPoint ) // intersection with a FACE
2246       {
2247         for ( size_t iF = 0; iF < _hexNodes[iN]._intPoint->_faceIDs.size(); ++iF )
2248         {
2249           const vector< TGeomID > & solidIDs =
2250             _grid->GetSolidIDs( _hexNodes[iN]._intPoint->_faceIDs[iF] );
2251           for ( size_t i = 0; i < solidIDs.size(); ++i )
2252             insertAndIncrement( solidIDs[i], id2NbPoints );
2253         }
2254       }
2255       else if ( _hexNodes[iN]._node ) // node inside a SOLID
2256       {
2257         insertAndIncrement( _hexNodes[iN]._node->GetShapeID(), id2NbPoints );
2258       }
2259     }
2260
2261     for ( int iL = 0; iL < 12; ++iL )
2262     {
2263       const _Link& link = _hexLinks[ iL ];
2264       for ( size_t iP = 0; iP < link._fIntPoints.size(); ++iP )
2265       {
2266         for ( size_t iF = 0; iF < link._fIntPoints[iP]->_faceIDs.size(); ++iF )
2267         {
2268           const vector< TGeomID > & solidIDs =
2269             _grid->GetSolidIDs( link._fIntPoints[iP]->_faceIDs[iF] );
2270           for ( size_t i = 0; i < solidIDs.size(); ++i )
2271             insertAndIncrement( solidIDs[i], id2NbPoints );
2272         }
2273       }
2274     }
2275
2276     for ( size_t iP = 0; iP < _eIntPoints.size(); ++iP )
2277     {
2278       const vector< TGeomID > & solidIDs = _grid->GetSolidIDs( _eIntPoints[iP]->_shapeID );
2279       for ( size_t i = 0; i < solidIDs.size(); ++i )
2280         insertAndIncrement( solidIDs[i], id2NbPoints );
2281     }
2282
2283     size_t nbSolids = 0;
2284     for ( TID2Nb::iterator id2nb = id2NbPoints.begin(); id2nb != id2NbPoints.end(); ++id2nb )
2285       if ( id2nb->second >= 3 )
2286         ids[ nbSolids++ ] = id2nb->first;
2287
2288     return nbSolids;
2289   }
2290
2291   //================================================================================
2292   /*!
2293    * \brief Count cuts by INTERNAL FACEs and set _Node::_isInternalFlags
2294    */
2295   bool Hexahedron::isCutByInternalFace( IsInternalFlag & maxFlag )
2296   {
2297     TID2Nb id2NbPoints;
2298     id2NbPoints.reserve( 3 );
2299
2300     for ( size_t iN = 0; iN < _intNodes.size(); ++iN )
2301       for ( size_t iF = 0; iF < _intNodes[iN]._intPoint->_faceIDs.size(); ++iF )
2302       {
2303         if ( _grid->IsInternal( _intNodes[iN]._intPoint->_faceIDs[iF]))
2304           insertAndIncrement( _intNodes[iN]._intPoint->_faceIDs[iF], id2NbPoints );
2305       }
2306     for ( size_t iN = 0; iN < 8; ++iN )
2307       if ( _hexNodes[iN]._intPoint )
2308         for ( size_t iF = 0; iF < _hexNodes[iN]._intPoint->_faceIDs.size(); ++iF )
2309         {
2310           if ( _grid->IsInternal( _hexNodes[iN]._intPoint->_faceIDs[iF]))
2311             insertAndIncrement( _hexNodes[iN]._intPoint->_faceIDs[iF], id2NbPoints );
2312         }
2313
2314     maxFlag = IS_NOT_INTERNAL;
2315     for ( TID2Nb::iterator id2nb = id2NbPoints.begin(); id2nb != id2NbPoints.end(); ++id2nb )
2316     {
2317       TGeomID        intFace = id2nb->first;
2318       IsInternalFlag intFlag = ( id2nb->second >= 3 ? IS_CUT_BY_INTERNAL_FACE : IS_INTERNAL );
2319       if ( intFlag > maxFlag )
2320         maxFlag = intFlag;
2321
2322       for ( size_t iN = 0; iN < _intNodes.size(); ++iN )
2323         if ( _intNodes[iN].IsOnFace( intFace ))
2324           _intNodes[iN].SetInternal( intFlag );
2325
2326       for ( size_t iN = 0; iN < 8; ++iN )
2327         if ( _hexNodes[iN].IsOnFace( intFace ))
2328           _hexNodes[iN].SetInternal( intFlag );
2329     }
2330
2331     return maxFlag;
2332   }
2333
2334   //================================================================================
2335   /*!
2336    * \brief Return any FACE interfering with this Hexahedron
2337    */
2338   TGeomID Hexahedron::getAnyFace() const
2339   {
2340     TID2Nb id2NbPoints;
2341     id2NbPoints.reserve( 3 );
2342
2343     for ( size_t iN = 0; iN < _intNodes.size(); ++iN )
2344       for ( size_t iF = 0; iF < _intNodes[iN]._intPoint->_faceIDs.size(); ++iF )
2345         insertAndIncrement( _intNodes[iN]._intPoint->_faceIDs[iF], id2NbPoints );
2346
2347     for ( size_t iN = 0; iN < 8; ++iN )
2348       if ( _hexNodes[iN]._intPoint )
2349         for ( size_t iF = 0; iF < _hexNodes[iN]._intPoint->_faceIDs.size(); ++iF )
2350           insertAndIncrement( _hexNodes[iN]._intPoint->_faceIDs[iF], id2NbPoints );
2351
2352     for ( unsigned int minNb = 3; minNb > 0; --minNb )
2353       for ( TID2Nb::iterator id2nb = id2NbPoints.begin(); id2nb != id2NbPoints.end(); ++id2nb )
2354         if ( id2nb->second >= minNb )
2355           return id2nb->first;
2356
2357     return 0;
2358   }
2359
2360   //================================================================================
2361   /*!
2362    * \brief Initializes IJK by Hexahedron index
2363    */
2364   void Hexahedron::setIJK( size_t iCell )
2365   {
2366     size_t iNbCell = _grid->_coords[0].size() - 1;
2367     size_t jNbCell = _grid->_coords[1].size() - 1;
2368     _i = iCell % iNbCell;
2369     _j = ( iCell % ( iNbCell * jNbCell )) / iNbCell;
2370     _k = iCell / iNbCell / jNbCell;
2371   }
2372
2373   //================================================================================
2374   /*!
2375    * \brief Initializes its data by given grid cell (countered from zero)
2376    */
2377   void Hexahedron::init( size_t iCell )
2378   {
2379     setIJK( iCell );
2380     init( _i, _j, _k );
2381   }
2382
2383   //================================================================================
2384   /*!
2385    * \brief Initializes its data by given grid cell nodes and intersections
2386    */
2387   void Hexahedron::init( size_t i, size_t j, size_t k, const Solid* solid )
2388   {
2389     _i = i; _j = j; _k = k;
2390
2391     if ( !solid )
2392       solid = _grid->GetSolid();
2393
2394     // set nodes of grid to nodes of the hexahedron and
2395     // count nodes at hexahedron corners located IN and ON geometry
2396     _nbCornerNodes = _nbBndNodes = 0;
2397     _origNodeInd   = _grid->NodeIndex( i,j,k );
2398     for ( int iN = 0; iN < 8; ++iN )
2399     {
2400       _hexNodes[iN]._isInternalFlags = 0;
2401
2402       _hexNodes[iN]._node     = _grid->_nodes   [ _origNodeInd + _grid->_nodeShift[iN] ];
2403       _hexNodes[iN]._intPoint = _grid->_gridIntP[ _origNodeInd + _grid->_nodeShift[iN] ];
2404
2405       if ( _hexNodes[iN]._node && !solid->Contains( _hexNodes[iN]._node->GetShapeID() ))
2406         _hexNodes[iN]._node = 0;
2407       if ( _hexNodes[iN]._intPoint && !solid->ContainsAny( _hexNodes[iN]._intPoint->_faceIDs ))
2408         _hexNodes[iN]._intPoint = 0;
2409
2410       _nbCornerNodes += bool( _hexNodes[iN]._node );
2411       _nbBndNodes    += bool( _hexNodes[iN]._intPoint );
2412     }
2413     _sideLength[0] = _grid->_coords[0][i+1] - _grid->_coords[0][i];
2414     _sideLength[1] = _grid->_coords[1][j+1] - _grid->_coords[1][j];
2415     _sideLength[2] = _grid->_coords[2][k+1] - _grid->_coords[2][k];
2416
2417     _intNodes.clear();
2418     _vIntNodes.clear();
2419
2420     if ( _nbFaceIntNodes + _eIntPoints.size()                  > 0 &&
2421          _nbFaceIntNodes + _eIntPoints.size() + _nbCornerNodes > 3)
2422     {
2423       _intNodes.reserve( 3 * _nbBndNodes + _nbFaceIntNodes + _eIntPoints.size() );
2424
2425       // this method can be called in parallel, so use own helper
2426       SMESH_MesherHelper helper( *_grid->_helper->GetMesh() );
2427
2428       // Create sub-links (_Link::_splits) by splitting links with _Link::_fIntPoints
2429       // ---------------------------------------------------------------
2430       _Link split;
2431       for ( int iLink = 0; iLink < 12; ++iLink )
2432       {
2433         _Link& link = _hexLinks[ iLink ];
2434         link._fIntNodes.clear();
2435         link._fIntNodes.reserve( link._fIntPoints.size() );
2436         for ( size_t i = 0; i < link._fIntPoints.size(); ++i )
2437           if ( solid->ContainsAny( link._fIntPoints[i]->_faceIDs ))
2438           {
2439             _intNodes.push_back( _Node( 0, link._fIntPoints[i] ));
2440             link._fIntNodes.push_back( & _intNodes.back() );
2441           }
2442
2443         link._splits.clear();
2444         split._nodes[ 0 ] = link._nodes[0];
2445         bool isOut = ( ! link._nodes[0]->Node() );
2446         bool checkTransition;
2447         for ( size_t i = 0; i < link._fIntNodes.size(); ++i )
2448         {
2449           const bool isGridNode = ( ! link._fIntNodes[i]->Node() );
2450           if ( !isGridNode ) // intersection non-coincident with a grid node
2451           {
2452             if ( split._nodes[ 0 ]->Node() && !isOut )
2453             {
2454               split._nodes[ 1 ] = link._fIntNodes[i];
2455               link._splits.push_back( split );
2456             }
2457             split._nodes[ 0 ] = link._fIntNodes[i];
2458             checkTransition = true;
2459           }
2460           else // FACE intersection coincident with a grid node (at link ends)
2461           {
2462             checkTransition = ( i == 0 && link._nodes[0]->Node() );
2463           }
2464           if ( checkTransition )
2465           {
2466             const vector< TGeomID >& faceIDs = link._fIntNodes[i]->_intPoint->_faceIDs;
2467             if ( _grid->IsInternal( faceIDs.back() ))
2468               isOut = false;
2469             else if ( faceIDs.size() > 1 || _eIntPoints.size() > 0 )
2470               isOut = isOutPoint( link, i, helper, solid );
2471             else
2472             {
2473               bool okTransi = _grid->IsCorrectTransition( faceIDs[0], solid );
2474               switch ( link._fIntNodes[i]->FaceIntPnt()->_transition ) {
2475               case Trans_OUT: isOut = okTransi;  break;
2476               case Trans_IN : isOut = !okTransi; break;
2477               default:
2478                 isOut = isOutPoint( link, i, helper, solid );
2479               }
2480             }
2481           }
2482         }
2483         if ( link._nodes[ 1 ]->Node() && split._nodes[ 0 ]->Node() && !isOut )
2484         {
2485           split._nodes[ 1 ] = link._nodes[1];
2486           link._splits.push_back( split );
2487         }
2488       }
2489
2490       // Create _Node's at intersections with EDGEs.
2491       // --------------------------------------------
2492       // 1) add this->_eIntPoints to _Face::_eIntNodes
2493       // 2) fill _intNodes and _vIntNodes
2494       //
2495       const double tol2 = _grid->_tol * _grid->_tol;
2496       int facets[3], nbFacets, subEntity;
2497
2498       for ( int iF = 0; iF < 6; ++iF )
2499         _hexQuads[ iF ]._eIntNodes.clear();
2500
2501       for ( size_t iP = 0; iP < _eIntPoints.size(); ++iP )
2502       {
2503         if ( !solid->ContainsAny( _eIntPoints[iP]->_faceIDs ))
2504           continue;
2505         nbFacets = getEntity( _eIntPoints[iP], facets, subEntity );
2506         _Node* equalNode = 0;
2507         switch( nbFacets ) {
2508         case 1: // in a _Face
2509         {
2510           _Face& quad = _hexQuads[ facets[0] - SMESH_Block::ID_FirstF ];
2511           equalNode = findEqualNode( quad._eIntNodes, _eIntPoints[ iP ], tol2 );
2512           if ( equalNode ) {
2513             equalNode->Add( _eIntPoints[ iP ] );
2514           }
2515           else {
2516             _intNodes.push_back( _Node( 0, _eIntPoints[ iP ]));
2517             quad._eIntNodes.push_back( & _intNodes.back() );
2518           }
2519           break;
2520         }
2521         case 2: // on a _Link
2522         {
2523           _Link& link = _hexLinks[ subEntity - SMESH_Block::ID_FirstE ];
2524           if ( link._splits.size() > 0 )
2525           {
2526             equalNode = findEqualNode( link._fIntNodes, _eIntPoints[ iP ], tol2 );
2527             if ( equalNode )
2528               equalNode->Add( _eIntPoints[ iP ] );
2529             else if ( link._splits.size() == 1 &&
2530                       link._splits[0]._nodes[0] &&
2531                       link._splits[0]._nodes[1] )
2532               link._splits.clear(); // hex edge is divided by _eIntPoints[iP]
2533           }
2534           //else
2535           if ( !equalNode )
2536           {
2537             _intNodes.push_back( _Node( 0, _eIntPoints[ iP ]));
2538             bool newNodeUsed = false;
2539             for ( int iF = 0; iF < 2; ++iF )
2540             {
2541               _Face& quad = _hexQuads[ facets[iF] - SMESH_Block::ID_FirstF ];
2542               equalNode = findEqualNode( quad._eIntNodes, _eIntPoints[ iP ], tol2 );
2543               if ( equalNode ) {
2544                 equalNode->Add( _eIntPoints[ iP ] );
2545               }
2546               else {
2547                 quad._eIntNodes.push_back( & _intNodes.back() );
2548                 newNodeUsed = true;
2549               }
2550             }
2551             if ( !newNodeUsed )
2552               _intNodes.pop_back();
2553           }
2554           break;
2555         }
2556         case 3: // at a corner
2557         {
2558           _Node& node = _hexNodes[ subEntity - SMESH_Block::ID_FirstV ];
2559           if ( node.Node() > 0 )
2560           {
2561             if ( node._intPoint )
2562               node._intPoint->Add( _eIntPoints[ iP ]->_faceIDs, _eIntPoints[ iP ]->_node );
2563           }
2564           else
2565           {
2566             _intNodes.push_back( _Node( 0, _eIntPoints[ iP ]));
2567             for ( int iF = 0; iF < 3; ++iF )
2568             {
2569               _Face& quad = _hexQuads[ facets[iF] - SMESH_Block::ID_FirstF ];
2570               equalNode = findEqualNode( quad._eIntNodes, _eIntPoints[ iP ], tol2 );
2571               if ( equalNode ) {
2572                 equalNode->Add( _eIntPoints[ iP ] );
2573               }
2574               else {
2575                 quad._eIntNodes.push_back( & _intNodes.back() );
2576               }
2577             }
2578           }
2579           break;
2580         }
2581         } // switch( nbFacets )
2582
2583         if ( nbFacets == 0 ||
2584              _grid->ShapeType( _eIntPoints[ iP ]->_shapeID ) == TopAbs_VERTEX )
2585         {
2586           equalNode = findEqualNode( _vIntNodes, _eIntPoints[ iP ], tol2 );
2587           if ( equalNode ) {
2588             equalNode->Add( _eIntPoints[ iP ] );
2589           }
2590           else if ( nbFacets == 0 ) {
2591             if ( _intNodes.empty() || _intNodes.back().EdgeIntPnt() != _eIntPoints[ iP ])
2592               _intNodes.push_back( _Node( 0, _eIntPoints[ iP ]));
2593             _vIntNodes.push_back( & _intNodes.back() );
2594           }
2595         }
2596       } // loop on _eIntPoints
2597     }
2598
2599     else if ( 3 < _nbCornerNodes && _nbCornerNodes < 8 ) // _nbFaceIntNodes == 0
2600     {
2601       _Link split;
2602       // create sub-links (_splits) of whole links
2603       for ( int iLink = 0; iLink < 12; ++iLink )
2604       {
2605         _Link& link = _hexLinks[ iLink ];
2606         link._splits.clear();
2607         if ( link._nodes[ 0 ]->Node() && link._nodes[ 1 ]->Node() )
2608         {
2609           split._nodes[ 0 ] = link._nodes[0];
2610           split._nodes[ 1 ] = link._nodes[1];
2611           link._splits.push_back( split );
2612         }
2613       }
2614     }
2615     return;
2616
2617   } // init( _i, _j, _k )
2618
2619   //================================================================================
2620   /*!
2621    * \brief Compute mesh volumes resulted from intersection of the Hexahedron
2622    */
2623   void Hexahedron::computeElements( const Solid* solid, int solidIndex )
2624   {
2625     if ( !solid )
2626     {
2627       solid = _grid->GetSolid();
2628       if ( !_grid->_geometry.IsOneSolid() )
2629       {
2630         TGeomID solidIDs[20];
2631         size_t nbSolids = getSolids( solidIDs );
2632         if ( nbSolids > 1 )
2633         {
2634           for ( size_t i = 0; i < nbSolids; ++i )
2635           {
2636             solid = _grid->GetSolid( solidIDs[i] );
2637             computeElements( solid, i );
2638             if ( !_volumeDefs._nodes.empty() && i < nbSolids - 1 )
2639               _volumeDefs.SetNext( new _volumeDef( _volumeDefs ));
2640           }
2641           return;
2642         }
2643         solid = _grid->GetSolid( solidIDs[0] );
2644       }
2645     }
2646
2647     init( _i, _j, _k, solid ); // get nodes and intersections from grid nodes and split links
2648
2649     int nbIntersections = _nbFaceIntNodes + _eIntPoints.size();
2650     if ( _nbCornerNodes + nbIntersections < 4 )
2651       return;
2652
2653     if ( _nbBndNodes == _nbCornerNodes && nbIntersections == 0 && isInHole() )
2654       return; // cell is in a hole
2655
2656     IsInternalFlag intFlag = IS_NOT_INTERNAL;
2657     if ( solid->HasInternalFaces() && this->isCutByInternalFace( intFlag ))
2658     {
2659       for ( _SplitIterator it( _hexLinks ); it.More(); it.Next() )
2660       {
2661         if ( compute( solid, intFlag ))
2662           _volumeDefs.SetNext( new _volumeDef( _volumeDefs ));
2663       }
2664     }
2665     else
2666     {
2667       if ( solidIndex >= 0 )
2668         intFlag = IS_CUT_BY_INTERNAL_FACE;
2669
2670       compute( solid, intFlag );
2671     }
2672   }
2673
2674   //================================================================================
2675   /*!
2676    * \brief Compute mesh volumes resulted from intersection of the Hexahedron
2677    */
2678   bool Hexahedron::compute( const Solid* solid, const IsInternalFlag intFlag )
2679   {
2680     _polygons.clear();
2681     _polygons.reserve( 20 );
2682
2683     for ( int iN = 0; iN < 8; ++iN )
2684       _hexNodes[iN]._usedInFace = 0;
2685
2686     // Create polygons from quadrangles
2687     // --------------------------------
2688
2689     vector< _OrientedLink > splits;
2690     vector<_Node*>          chainNodes;
2691     _Face*                  coplanarPolyg;
2692
2693     bool hasEdgeIntersections = !_eIntPoints.empty();
2694
2695     for ( int iF = 0; iF < 6; ++iF ) // loop on 6 sides of a hexahedron
2696     {
2697       _Face& quad = _hexQuads[ iF ] ;
2698
2699       _polygons.resize( _polygons.size() + 1 );
2700       _Face* polygon = &_polygons.back();
2701       polygon->_polyLinks.reserve( 20 );
2702       polygon->_name = quad._name;
2703
2704       splits.clear();
2705       for ( int iE = 0; iE < 4; ++iE ) // loop on 4 sides of a quadrangle
2706         for ( int iS = 0; iS < quad._links[ iE ].NbResultLinks(); ++iS )
2707           splits.push_back( quad._links[ iE ].ResultLink( iS ));
2708
2709       // add splits of links to a polygon and add _polyLinks to make
2710       // polygon's boundary closed
2711
2712       int nbSplits = splits.size();
2713       if (( nbSplits == 1 ) &&
2714           ( quad._eIntNodes.empty() ||
2715             splits[0].FirstNode()->IsLinked( splits[0].LastNode()->_intPoint )))
2716         //( quad._eIntNodes.empty() || _nbCornerNodes + nbIntersections > 6 ))
2717         nbSplits = 0;
2718
2719       for ( size_t iP = 0; iP < quad._eIntNodes.size(); ++iP )
2720         if ( quad._eIntNodes[ iP ]->IsUsedInFace( polygon ))
2721           quad._eIntNodes[ iP ]->_usedInFace = 0;
2722
2723       size_t nbUsedEdgeNodes = 0;
2724       _Face* prevPolyg = 0; // polygon previously created from this quad
2725
2726       while ( nbSplits > 0 )
2727       {
2728         size_t iS = 0;
2729         while ( !splits[ iS ] )
2730           ++iS;
2731
2732         if ( !polygon->_links.empty() )
2733         {
2734           _polygons.resize( _polygons.size() + 1 );
2735           polygon = &_polygons.back();
2736           polygon->_polyLinks.reserve( 20 );
2737           polygon->_name = quad._name;
2738         }
2739         polygon->_links.push_back( splits[ iS ] );
2740         splits[ iS++ ]._link = 0;
2741         --nbSplits;
2742
2743         _Node* nFirst = polygon->_links.back().FirstNode();
2744         _Node *n1,*n2 = polygon->_links.back().LastNode();
2745         for ( ; nFirst != n2 && iS < splits.size(); ++iS )
2746         {
2747           _OrientedLink& split = splits[ iS ];
2748           if ( !split ) continue;
2749
2750           n1 = split.FirstNode();
2751           if ( n1 == n2 &&
2752                n1->_intPoint &&
2753                (( n1->_intPoint->_faceIDs.size() > 1 && isImplementEdges() ) ||
2754                 ( n1->_isInternalFlags )))
2755           {
2756             // n1 is at intersection with EDGE
2757             if ( findChainOnEdge( splits, polygon->_links.back(), split, iS, quad, chainNodes ))
2758             {
2759               for ( size_t i = 1; i < chainNodes.size(); ++i )
2760                 polygon->AddPolyLink( chainNodes[i-1], chainNodes[i], prevPolyg );
2761               if ( chainNodes.back() != n1 ) // not a partial cut by INTERNAL FACE
2762               {
2763                 prevPolyg = polygon;
2764                 n2 = chainNodes.back();
2765                 continue;
2766               }
2767             }
2768           }
2769           else if ( n1 != n2 )
2770           {
2771             // try to connect to intersections with EDGEs
2772             if ( quad._eIntNodes.size() > nbUsedEdgeNodes  &&
2773                  findChain( n2, n1, quad, chainNodes ))
2774             {
2775               for ( size_t i = 1; i < chainNodes.size(); ++i )
2776               {
2777                 polygon->AddPolyLink( chainNodes[i-1], chainNodes[i] );
2778                 nbUsedEdgeNodes += ( chainNodes[i]->IsUsedInFace( polygon ));
2779               }
2780               if ( chainNodes.back() != n1 )
2781               {
2782                 n2 = chainNodes.back();
2783                 --iS;
2784                 continue;
2785               }
2786             }
2787             // try to connect to a split ending on the same FACE
2788             else
2789             {
2790               _OrientedLink foundSplit;
2791               for ( size_t i = iS; i < splits.size() && !foundSplit; ++i )
2792                 if (( foundSplit = splits[ i ]) &&
2793                     ( n2->IsLinked( foundSplit.FirstNode()->_intPoint )))
2794                 {
2795                   iS = i - 1;
2796                 }
2797                 else
2798                 {
2799                   foundSplit._link = 0;
2800                 }
2801               if ( foundSplit )
2802               {
2803                 if ( n2 != foundSplit.FirstNode() )
2804                 {
2805                   polygon->AddPolyLink( n2, foundSplit.FirstNode() );
2806                   n2 = foundSplit.FirstNode();
2807                 }
2808                 continue;
2809               }
2810               else
2811               {
2812                 if ( n2->IsLinked( nFirst->_intPoint ))
2813                   break;
2814                 polygon->AddPolyLink( n2, n1, prevPolyg );
2815               }
2816             }
2817           } // if ( n1 != n2 )
2818
2819           polygon->_links.push_back( split );
2820           split._link = 0;
2821           --nbSplits;
2822           n2 = polygon->_links.back().LastNode();
2823
2824         } // loop on splits
2825
2826         if ( nFirst != n2 ) // close a polygon
2827         {
2828           if ( !findChain( n2, nFirst, quad, chainNodes ))
2829           {
2830             if ( !closePolygon( polygon, chainNodes ))
2831               if ( !isImplementEdges() )
2832                 chainNodes.push_back( nFirst );
2833           }
2834           for ( size_t i = 1; i < chainNodes.size(); ++i )
2835           {
2836             polygon->AddPolyLink( chainNodes[i-1], chainNodes[i], prevPolyg );
2837             nbUsedEdgeNodes += bool( chainNodes[i]->IsUsedInFace( polygon ));
2838           }
2839         }
2840
2841         if ( polygon->_links.size() < 3 && nbSplits > 0 )
2842         {
2843           polygon->_polyLinks.clear();
2844           polygon->_links.clear();
2845         }
2846       } // while ( nbSplits > 0 )
2847
2848       if ( polygon->_links.size() < 3 )
2849       {
2850         _polygons.pop_back();
2851       }
2852     }  // loop on 6 hexahedron sides
2853
2854     // Create polygons closing holes in a polyhedron
2855     // ----------------------------------------------
2856
2857     // clear _usedInFace
2858     for ( size_t iN = 0; iN < _intNodes.size(); ++iN )
2859       _intNodes[ iN ]._usedInFace = 0;
2860
2861     // add polygons to their links and mark used nodes
2862     for ( size_t iP = 0; iP < _polygons.size(); ++iP )
2863     {
2864       _Face& polygon = _polygons[ iP ];
2865       for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
2866       {
2867         polygon._links[ iL ].AddFace( &polygon );
2868         polygon._links[ iL ].FirstNode()->_usedInFace = &polygon;
2869       }
2870     }
2871     // find free links
2872     vector< _OrientedLink* > freeLinks;
2873     freeLinks.reserve(20);
2874     for ( size_t iP = 0; iP < _polygons.size(); ++iP )
2875     {
2876       _Face& polygon = _polygons[ iP ];
2877       for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
2878         if ( polygon._links[ iL ].NbFaces() < 2 )
2879           freeLinks.push_back( & polygon._links[ iL ]);
2880     }
2881     int nbFreeLinks = freeLinks.size();
2882     if ( nbFreeLinks == 1 ) return false;
2883
2884     // put not used intersection nodes to _vIntNodes
2885     int nbVertexNodes = 0; // nb not used vertex nodes
2886     {
2887       for ( size_t iN = 0; iN < _vIntNodes.size(); ++iN )
2888         nbVertexNodes += ( !_vIntNodes[ iN ]->IsUsedInFace() );
2889
2890       const double tol = 1e-3 * Min( Min( _sideLength[0], _sideLength[1] ), _sideLength[0] );
2891       for ( size_t iN = _nbFaceIntNodes; iN < _intNodes.size(); ++iN )
2892       {
2893         if ( _intNodes[ iN ].IsUsedInFace() ) continue;
2894         if ( dynamic_cast< const F_IntersectPoint* >( _intNodes[ iN ]._intPoint )) continue;
2895         _Node* equalNode =
2896           findEqualNode( _vIntNodes, _intNodes[ iN ].EdgeIntPnt(), tol*tol );
2897         if ( !equalNode )
2898         {
2899           _vIntNodes.push_back( &_intNodes[ iN ]);
2900           ++nbVertexNodes;
2901         }
2902       }
2903     }
2904
2905     set<TGeomID> usedFaceIDs;
2906     vector< TGeomID > faces;
2907     TGeomID curFace = 0;
2908     const size_t nbQuadPolygons = _polygons.size();
2909     E_IntersectPoint ipTmp;
2910
2911     // create polygons by making closed chains of free links
2912     size_t iPolygon = _polygons.size();
2913     while ( nbFreeLinks > 0 )
2914     {
2915       if ( iPolygon == _polygons.size() )
2916       {
2917         _polygons.resize( _polygons.size() + 1 );
2918         _polygons[ iPolygon ]._polyLinks.reserve( 20 );
2919         _polygons[ iPolygon ]._links.reserve( 20 );
2920       }
2921       _Face& polygon = _polygons[ iPolygon ];
2922
2923       _OrientedLink* curLink = 0;
2924       _Node*         curNode;
2925       if (( !hasEdgeIntersections ) ||
2926           ( nbFreeLinks < 4 && nbVertexNodes == 0 ))
2927       {
2928         // get a remaining link to start from
2929         for ( size_t iL = 0; iL < freeLinks.size() && !curLink; ++iL )
2930           if (( curLink = freeLinks[ iL ] ))
2931             freeLinks[ iL ] = 0;
2932         polygon._links.push_back( *curLink );
2933         --nbFreeLinks;
2934         do
2935         {
2936           // find all links connected to curLink
2937           curNode = curLink->FirstNode();
2938           curLink = 0;
2939           for ( size_t iL = 0; iL < freeLinks.size() && !curLink; ++iL )
2940             if ( freeLinks[ iL ] && freeLinks[ iL ]->LastNode() == curNode )
2941             {
2942               curLink = freeLinks[ iL ];
2943               freeLinks[ iL ] = 0;
2944               --nbFreeLinks;
2945               polygon._links.push_back( *curLink );
2946             }
2947         } while ( curLink );
2948       }
2949       else // there are intersections with EDGEs
2950       {
2951         // get a remaining link to start from, one lying on minimal nb of FACEs
2952         {
2953           typedef pair< TGeomID, int > TFaceOfLink;
2954           TFaceOfLink faceOfLink( -1, -1 );
2955           TFaceOfLink facesOfLink[3] = { faceOfLink, faceOfLink, faceOfLink };
2956           for ( size_t iL = 0; iL < freeLinks.size(); ++iL )
2957             if ( freeLinks[ iL ] )
2958             {
2959               faces = freeLinks[ iL ]->GetNotUsedFace( usedFaceIDs );
2960               if ( faces.size() == 1 )
2961               {
2962                 faceOfLink = TFaceOfLink( faces[0], iL );
2963                 if ( !freeLinks[ iL ]->HasEdgeNodes() )
2964                   break;
2965                 facesOfLink[0] = faceOfLink;
2966               }
2967               else if ( facesOfLink[0].first < 0 )
2968               {
2969                 faceOfLink = TFaceOfLink(( faces.empty() ? -1 : faces[0]), iL );
2970                 facesOfLink[ 1 + faces.empty() ] = faceOfLink;
2971               }
2972             }
2973           for ( int i = 0; faceOfLink.first < 0 && i < 3; ++i )
2974             faceOfLink = facesOfLink[i];
2975
2976           if ( faceOfLink.first < 0 ) // all faces used
2977           {
2978             for ( size_t iL = 0; iL < freeLinks.size() && faceOfLink.first < 1; ++iL )
2979               if (( curLink = freeLinks[ iL ]))
2980               {
2981                 faceOfLink.first = 
2982                   curLink->FirstNode()->IsLinked( curLink->LastNode()->_intPoint );
2983                 faceOfLink.second = iL;
2984               }
2985             usedFaceIDs.clear();
2986           }
2987           curFace = faceOfLink.first;
2988           curLink = freeLinks[ faceOfLink.second ];
2989           freeLinks[ faceOfLink.second ] = 0;
2990         }
2991         usedFaceIDs.insert( curFace );
2992         polygon._links.push_back( *curLink );
2993         --nbFreeLinks;
2994
2995         // find all links lying on a curFace
2996         do
2997         {
2998           // go forward from curLink
2999           curNode = curLink->LastNode();
3000           curLink = 0;
3001           for ( size_t iL = 0; iL < freeLinks.size() && !curLink; ++iL )
3002             if ( freeLinks[ iL ] &&
3003                  freeLinks[ iL ]->FirstNode() == curNode &&
3004                  freeLinks[ iL ]->LastNode()->IsOnFace( curFace ))
3005             {
3006               curLink = freeLinks[ iL ];
3007               freeLinks[ iL ] = 0;
3008               polygon._links.push_back( *curLink );
3009               --nbFreeLinks;
3010             }
3011         } while ( curLink );
3012
3013         std::reverse( polygon._links.begin(), polygon._links.end() );
3014
3015         curLink = & polygon._links.back();
3016         do
3017         {
3018           // go backward from curLink
3019           curNode = curLink->FirstNode();
3020           curLink = 0;
3021           for ( size_t iL = 0; iL < freeLinks.size() && !curLink; ++iL )
3022             if ( freeLinks[ iL ] &&
3023                  freeLinks[ iL ]->LastNode() == curNode &&
3024                  freeLinks[ iL ]->FirstNode()->IsOnFace( curFace ))
3025             {
3026               curLink = freeLinks[ iL ];
3027               freeLinks[ iL ] = 0;
3028               polygon._links.push_back( *curLink );
3029               --nbFreeLinks;
3030             }
3031         } while ( curLink );
3032
3033         curNode = polygon._links.back().FirstNode();
3034
3035         if ( polygon._links[0].LastNode() != curNode )
3036         {
3037           if ( nbVertexNodes > 0 )
3038           {
3039             // add links with _vIntNodes if not already used
3040             chainNodes.clear();
3041             for ( size_t iN = 0; iN < _vIntNodes.size(); ++iN )
3042               if ( !_vIntNodes[ iN ]->IsUsedInFace() &&
3043                    _vIntNodes[ iN ]->IsOnFace( curFace ))
3044               {
3045                 _vIntNodes[ iN ]->_usedInFace = &polygon;
3046                 chainNodes.push_back( _vIntNodes[ iN ] );
3047               }
3048             if ( chainNodes.size() > 1 &&
3049                  curFace != _grid->PseudoIntExtFaceID() ) /////// TODO
3050             {
3051               sortVertexNodes( chainNodes, curNode, curFace );
3052             }
3053             for ( size_t i = 0; i < chainNodes.size(); ++i )
3054             {
3055               polygon.AddPolyLink( chainNodes[ i ], curNode );
3056               curNode = chainNodes[ i ];
3057               freeLinks.push_back( &polygon._links.back() );
3058               ++nbFreeLinks;
3059             }
3060             nbVertexNodes -= chainNodes.size();
3061           }
3062           // if ( polygon._links.size() > 1 )
3063           {
3064             polygon.AddPolyLink( polygon._links[0].LastNode(), curNode );
3065             freeLinks.push_back( &polygon._links.back() );
3066             ++nbFreeLinks;
3067           }
3068         }
3069       } // if there are intersections with EDGEs
3070
3071       if ( polygon._links.size() < 2 ||
3072            polygon._links[0].LastNode() != polygon._links.back().FirstNode() )
3073         return false; // closed polygon not found -> invalid polyhedron
3074
3075       if ( polygon._links.size() == 2 )
3076       {
3077         if ( freeLinks.back() == &polygon._links.back() )
3078         {
3079           freeLinks.pop_back();
3080           --nbFreeLinks;
3081         }
3082         if ( polygon._links.front().NbFaces() > 0 )
3083           polygon._links.back().AddFace( polygon._links.front()._link->_faces[0] );
3084         if ( polygon._links.back().NbFaces() > 0 )
3085           polygon._links.front().AddFace( polygon._links.back()._link->_faces[0] );
3086
3087         if ( iPolygon == _polygons.size()-1 )
3088           _polygons.pop_back();
3089       }
3090       else // polygon._links.size() >= 2
3091       {
3092         // add polygon to its links
3093         for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
3094         {
3095           polygon._links[ iL ].AddFace( &polygon );
3096           polygon._links[ iL ].Reverse();
3097         }
3098         if ( /*hasEdgeIntersections &&*/ iPolygon == _polygons.size() - 1 )
3099         {
3100           // check that a polygon does not lie on a hexa side
3101           coplanarPolyg = 0;
3102           for ( size_t iL = 0; iL < polygon._links.size() && !coplanarPolyg; ++iL )
3103           {
3104             if ( polygon._links[ iL ].NbFaces() < 2 )
3105               continue; // it's a just added free link
3106             // look for a polygon made on a hexa side and sharing
3107             // two or more haxa links
3108             size_t iL2;
3109             coplanarPolyg = polygon._links[ iL ]._link->_faces[0];
3110             for ( iL2 = iL + 1; iL2 < polygon._links.size(); ++iL2 )
3111               if ( polygon._links[ iL2 ]._link->_faces[0] == coplanarPolyg &&
3112                    !coplanarPolyg->IsPolyLink( polygon._links[ iL  ]) &&
3113                    !coplanarPolyg->IsPolyLink( polygon._links[ iL2 ]) &&
3114                    coplanarPolyg < & _polygons[ nbQuadPolygons ])
3115                 break;
3116             if ( iL2 == polygon._links.size() )
3117               coplanarPolyg = 0;
3118           }
3119           if ( coplanarPolyg ) // coplanar polygon found
3120           {
3121             freeLinks.resize( freeLinks.size() - polygon._polyLinks.size() );
3122             nbFreeLinks -= polygon._polyLinks.size();
3123
3124             // an E_IntersectPoint used to mark nodes of coplanarPolyg
3125             // as lying on curFace while they are not at intersection with geometry
3126             ipTmp._faceIDs.resize(1);
3127             ipTmp._faceIDs[0] = curFace;
3128
3129             // fill freeLinks with links not shared by coplanarPolyg and polygon
3130             for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
3131               if ( polygon._links[ iL ]._link->_faces[1] &&
3132                    polygon._links[ iL ]._link->_faces[0] != coplanarPolyg )
3133               {
3134                 _Face* p = polygon._links[ iL ]._link->_faces[0];
3135                 for ( size_t iL2 = 0; iL2 < p->_links.size(); ++iL2 )
3136                   if ( p->_links[ iL2 ]._link == polygon._links[ iL ]._link )
3137                   {
3138                     freeLinks.push_back( & p->_links[ iL2 ] );
3139                     ++nbFreeLinks;
3140                     freeLinks.back()->RemoveFace( &polygon );
3141                     break;
3142                   }
3143               }
3144             for ( size_t iL = 0; iL < coplanarPolyg->_links.size(); ++iL )
3145               if ( coplanarPolyg->_links[ iL ]._link->_faces[1] &&
3146                    coplanarPolyg->_links[ iL ]._link->_faces[1] != &polygon )
3147               {
3148                 _Face* p = coplanarPolyg->_links[ iL ]._link->_faces[0];
3149                 if ( p == coplanarPolyg )
3150                   p = coplanarPolyg->_links[ iL ]._link->_faces[1];
3151                 for ( size_t iL2 = 0; iL2 < p->_links.size(); ++iL2 )
3152                   if ( p->_links[ iL2 ]._link == coplanarPolyg->_links[ iL ]._link )
3153                   {
3154                     // set links of coplanarPolyg in place of used freeLinks
3155                     // to re-create coplanarPolyg next
3156                     size_t iL3 = 0;
3157                     for ( ; iL3 < freeLinks.size() && freeLinks[ iL3 ]; ++iL3 );
3158                     if ( iL3 < freeLinks.size() )
3159                       freeLinks[ iL3 ] = ( & p->_links[ iL2 ] );
3160                     else
3161                       freeLinks.push_back( & p->_links[ iL2 ] );
3162                     ++nbFreeLinks;
3163                     freeLinks[ iL3 ]->RemoveFace( coplanarPolyg );
3164                     //  mark nodes of coplanarPolyg as lying on curFace
3165                     for ( int iN = 0; iN < 2; ++iN )
3166                     {
3167                       _Node* n = freeLinks[ iL3 ]->_link->_nodes[ iN ];
3168                       if ( n->_intPoint ) n->_intPoint->Add( ipTmp._faceIDs );
3169                       else                n->_intPoint = &ipTmp;
3170                     }
3171                     break;
3172                   }
3173               }
3174             // set coplanarPolyg to be re-created next
3175             for ( size_t iP = 0; iP < _polygons.size(); ++iP )
3176               if ( coplanarPolyg == & _polygons[ iP ] )
3177               {
3178                 iPolygon = iP;
3179                 _polygons[ iPolygon ]._links.clear();
3180                 _polygons[ iPolygon ]._polyLinks.clear();
3181                 break;
3182               }
3183             _polygons.pop_back();
3184             usedFaceIDs.erase( curFace );
3185             continue;
3186           } // if ( coplanarPolyg )
3187         } // if ( hasEdgeIntersections ) - search for coplanarPolyg
3188
3189         iPolygon = _polygons.size();
3190
3191       } // end of case ( polygon._links.size() > 2 )
3192     } // while ( nbFreeLinks > 0 )
3193
3194     // check volume size
3195     _hasTooSmall = ! checkPolyhedronSize( intFlag & IS_CUT_BY_INTERNAL_FACE );
3196
3197     for ( size_t i = 0; i < 8; ++i )
3198       if ( _hexNodes[ i ]._intPoint == &ipTmp )
3199         _hexNodes[ i ]._intPoint = 0;
3200
3201     if ( _hasTooSmall )
3202       return false; // too small volume
3203
3204
3205     // Try to find out names of no-name polygons (issue # 19887)
3206     if ( _grid->IsToRemoveExcessEntities() && _polygons.back()._name == SMESH_Block::ID_NONE )
3207     {
3208       gp_XYZ uvwCenter =
3209         0.5 * ( _grid->_coords[0][_i] + _grid->_coords[0][_i+1] ) * _grid->_axes[0] +
3210         0.5 * ( _grid->_coords[1][_j] + _grid->_coords[1][_j+1] ) * _grid->_axes[1] +
3211         0.5 * ( _grid->_coords[2][_k] + _grid->_coords[2][_k+1] ) * _grid->_axes[2];
3212       for ( size_t i = _polygons.size() - 1; _polygons[i]._name == SMESH_Block::ID_NONE; --i )
3213       {
3214         _Face& face = _polygons[ i ];
3215         Bnd_Box bb;
3216         gp_Pnt uvw;
3217         for ( size_t iL = 0; iL < face._links.size(); ++iL )
3218         {
3219           _Node* n = face._links[ iL ].FirstNode();
3220           gp_XYZ p = SMESH_NodeXYZ( n->Node() );
3221           _grid->ComputeUVW( p, uvw.ChangeCoord().ChangeData() );
3222           bb.Add( uvw );
3223         }
3224         gp_Pnt pMin = bb.CornerMin();
3225         if ( bb.IsXThin( _grid->_tol ))
3226           face._name = pMin.X() < uvwCenter.X() ? SMESH_Block::ID_F0yz : SMESH_Block::ID_F1yz;
3227         else if ( bb.IsYThin( _grid->_tol ))
3228           face._name = pMin.Y() < uvwCenter.Y() ? SMESH_Block::ID_Fx0z : SMESH_Block::ID_Fx1z;
3229         else if ( bb.IsZThin( _grid->_tol ))
3230           face._name = pMin.Z() < uvwCenter.Z() ? SMESH_Block::ID_Fxy0 : SMESH_Block::ID_Fxy1;
3231       }
3232     }
3233
3234     _volumeDefs._nodes.clear();
3235     _volumeDefs._quantities.clear();
3236     _volumeDefs._names.clear();
3237
3238     // create a classic cell if possible
3239
3240     int nbPolygons = 0;
3241     for ( size_t iF = 0; iF < _polygons.size(); ++iF )
3242       nbPolygons += (_polygons[ iF ]._links.size() > 0 );
3243
3244     //const int nbNodes = _nbCornerNodes + nbIntersections;
3245     int nbNodes = 0;
3246     for ( size_t i = 0; i < 8; ++i )
3247       nbNodes += _hexNodes[ i ].IsUsedInFace();
3248     for ( size_t i = 0; i < _intNodes.size(); ++i )
3249       nbNodes += _intNodes[ i ].IsUsedInFace();
3250
3251     bool isClassicElem = false;
3252     if (      nbNodes == 8 && nbPolygons == 6 ) isClassicElem = addHexa();
3253     else if ( nbNodes == 4 && nbPolygons == 4 ) isClassicElem = addTetra();
3254     else if ( nbNodes == 6 && nbPolygons == 5 ) isClassicElem = addPenta();
3255     else if ( nbNodes == 5 && nbPolygons == 5 ) isClassicElem = addPyra ();
3256     if ( !isClassicElem )
3257     {
3258       for ( size_t iF = 0; iF < _polygons.size(); ++iF )
3259       {
3260         const size_t nbLinks = _polygons[ iF ]._links.size();
3261         if ( nbLinks == 0 ) continue;
3262         _volumeDefs._quantities.push_back( nbLinks );
3263         _volumeDefs._names.push_back( _polygons[ iF ]._name );
3264         for ( size_t iL = 0; iL < nbLinks; ++iL )
3265           _volumeDefs._nodes.push_back( _polygons[ iF ]._links[ iL ].FirstNode() );
3266       }
3267     }
3268     _volumeDefs._solidID = solid->ID();
3269
3270     return !_volumeDefs._nodes.empty();
3271   }
3272   //================================================================================
3273   /*!
3274    * \brief Create elements in the mesh
3275    */
3276   int Hexahedron::MakeElements(SMESH_MesherHelper&                      helper,
3277                                const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap)
3278   {
3279     SMESHDS_Mesh* mesh = helper.GetMeshDS();
3280
3281     CellsAroundLink c( _grid, 0 );
3282     const size_t nbGridCells = c._nbCells[0] * c._nbCells[1] * c._nbCells[2];
3283     vector< Hexahedron* > allHexa( nbGridCells, 0 );
3284     int nbIntHex = 0;
3285
3286     // set intersection nodes from GridLine's to links of allHexa
3287     int i,j,k, cellIndex, iLink;
3288     for ( int iDir = 0; iDir < 3; ++iDir )
3289     {
3290       // loop on GridLine's parallel to iDir
3291       LineIndexer lineInd = _grid->GetLineIndexer( iDir );
3292       CellsAroundLink fourCells( _grid, iDir );
3293       for ( ; lineInd.More(); ++lineInd )
3294       {
3295         GridLine& line = _grid->_lines[ iDir ][ lineInd.LineIndex() ];
3296         multiset< F_IntersectPoint >::const_iterator ip = line._intPoints.begin();
3297         for ( ; ip != line._intPoints.end(); ++ip )
3298         {
3299           // if ( !ip->_node ) continue; // intersection at a grid node
3300           lineInd.SetIndexOnLine( ip->_indexOnLine );
3301           fourCells.Init( lineInd.I(), lineInd.J(), lineInd.K() );
3302           for ( int iL = 0; iL < 4; ++iL ) // loop on 4 cells sharing a link
3303           {
3304             if ( !fourCells.GetCell( iL, i,j,k, cellIndex, iLink ))
3305               continue;
3306             Hexahedron *& hex = allHexa[ cellIndex ];
3307             if ( !hex)
3308             {
3309               hex = new Hexahedron( *this, i, j, k, cellIndex );
3310               ++nbIntHex;
3311             }
3312             hex->_hexLinks[iLink]._fIntPoints.push_back( &(*ip) );
3313             hex->_nbFaceIntNodes += bool( ip->_node );
3314           }
3315         }
3316       }
3317     }
3318
3319     // implement geom edges into the mesh
3320     addEdges( helper, allHexa, edge2faceIDsMap );
3321
3322     // add not split hexahedra to the mesh
3323     int nbAdded = 0;
3324     TGeomID solidIDs[20];
3325     vector< Hexahedron* > intHexa; intHexa.reserve( nbIntHex );
3326     vector< const SMDS_MeshElement* > boundaryVolumes; boundaryVolumes.reserve( nbIntHex * 1.1 );
3327     for ( size_t i = 0; i < allHexa.size(); ++i )
3328     {
3329       // initialize this by not cut allHexa[ i ]
3330       Hexahedron * & hex = allHexa[ i ];
3331       if ( hex ) // split hexahedron
3332       {
3333         intHexa.push_back( hex );
3334         if ( hex->_nbFaceIntNodes > 0 || hex->_eIntPoints.size() > 0 )
3335           continue; // treat intersected hex later in parallel
3336         this->init( hex->_i, hex->_j, hex->_k );
3337       }
3338       else
3339       {
3340         this->init( i ); // == init(i,j,k)
3341       }
3342       if (( _nbCornerNodes == 8 ) &&
3343           ( _nbBndNodes < _nbCornerNodes || !isInHole() ))
3344       {
3345         // order of _hexNodes is defined by enum SMESH_Block::TShapeID
3346         SMDS_MeshElement* el =
3347           mesh->AddVolume( _hexNodes[0].Node(), _hexNodes[2].Node(),
3348                            _hexNodes[3].Node(), _hexNodes[1].Node(),
3349                            _hexNodes[4].Node(), _hexNodes[6].Node(),
3350                            _hexNodes[7].Node(), _hexNodes[5].Node() );
3351         TGeomID solidID = 0;
3352         if ( _nbBndNodes < _nbCornerNodes )
3353         {
3354           for ( int iN = 0; iN < 8 &&  !solidID; ++iN )
3355             if ( !_hexNodes[iN]._intPoint ) // no intersection
3356               solidID = _hexNodes[iN].Node()->GetShapeID();
3357         }
3358         else
3359         {
3360           getSolids( solidIDs );
3361           solidID = solidIDs[0];
3362         }
3363         mesh->SetMeshElementOnShape( el, solidID );
3364         ++nbAdded;
3365         if ( hex )
3366           intHexa.pop_back();
3367         if ( _grid->_toCreateFaces && _nbBndNodes >= 3 )
3368         {
3369           boundaryVolumes.push_back( el );
3370           el->setIsMarked( true );
3371         }
3372       }
3373       else if ( _nbCornerNodes > 3 && !hex )
3374       {
3375         // all intersection of hex with geometry are at grid nodes
3376         hex = new Hexahedron( *this, _i, _j, _k, i );
3377         intHexa.push_back( hex );
3378       }
3379     }
3380
3381     // compute definitions of volumes resulted from hexadron intersection
3382 #ifdef WITH_TBB
3383     tbb::parallel_for ( tbb::blocked_range<size_t>( 0, intHexa.size() ),
3384                         ParallelHexahedron( intHexa ),
3385                         tbb::simple_partitioner()); // computeElements() is called here
3386 #else
3387     for ( size_t i = 0; i < intHexa.size(); ++i )
3388       if ( Hexahedron * hex = intHexa[ i ] )
3389         hex->computeElements();
3390 #endif
3391
3392     // simplify polyhedrons
3393     if ( _grid->IsToRemoveExcessEntities() )
3394     {
3395       for ( size_t i = 0; i < intHexa.size(); ++i )
3396         if ( Hexahedron * hex = intHexa[ i ] )
3397           hex->removeExcessSideDivision( allHexa );
3398
3399       for ( size_t i = 0; i < intHexa.size(); ++i )
3400         if ( Hexahedron * hex = intHexa[ i ] )
3401           hex->removeExcessNodes( allHexa );
3402     }
3403
3404     // add volumes
3405     for ( size_t i = 0; i < intHexa.size(); ++i )
3406       if ( Hexahedron * hex = intHexa[ i ] )
3407         nbAdded += hex->addVolumes( helper );
3408
3409     // fill boundaryVolumes with volumes neighboring too small skipped volumes
3410     if ( _grid->_toCreateFaces )
3411     {
3412       for ( size_t i = 0; i < intHexa.size(); ++i )
3413         if ( Hexahedron * hex = intHexa[ i ] )
3414           hex->getBoundaryElems( boundaryVolumes );
3415     }
3416
3417     // create boundary mesh faces
3418     addFaces( helper, boundaryVolumes );
3419
3420     // create mesh edges
3421     addSegments( helper, edge2faceIDsMap );
3422
3423     for ( size_t i = 0; i < allHexa.size(); ++i )
3424       if ( allHexa[ i ] )
3425         delete allHexa[ i ];
3426
3427     return nbAdded;
3428   }
3429
3430   //================================================================================
3431   /*!
3432    * \brief Implements geom edges into the mesh
3433    */
3434   void Hexahedron::addEdges(SMESH_MesherHelper&                      helper,
3435                             vector< Hexahedron* >&                   hexes,
3436                             const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap)
3437   {
3438     if ( edge2faceIDsMap.empty() ) return;
3439
3440     // Prepare planes for intersecting with EDGEs
3441     GridPlanes pln[3];
3442     {
3443       for ( int iDirZ = 0; iDirZ < 3; ++iDirZ ) // iDirZ gives normal direction to planes
3444       {
3445         GridPlanes& planes = pln[ iDirZ ];
3446         int iDirX = ( iDirZ + 1 ) % 3;
3447         int iDirY = ( iDirZ + 2 ) % 3;
3448         planes._zNorm  = ( _grid->_axes[ iDirX ] ^ _grid->_axes[ iDirY ] ).Normalized();
3449         planes._zProjs.resize ( _grid->_coords[ iDirZ ].size() );
3450         planes._zProjs [0] = 0;
3451         const double       zFactor = _grid->_axes[ iDirZ ] * planes._zNorm;
3452         const vector< double > & u = _grid->_coords[ iDirZ ];
3453         for ( size_t i = 1; i < planes._zProjs.size(); ++i )
3454         {
3455           planes._zProjs [i] = zFactor * ( u[i] - u[0] );
3456         }
3457       }
3458     }
3459     const double deflection = _grid->_minCellSize / 20.;
3460     const double tol        = _grid->_tol;
3461     E_IntersectPoint ip;
3462
3463     TColStd_MapOfInteger intEdgeIDs; // IDs of not shared INTERNAL EDGES
3464
3465     // Intersect EDGEs with the planes
3466     map< TGeomID, vector< TGeomID > >::const_iterator e2fIt = edge2faceIDsMap.begin();
3467     for ( ; e2fIt != edge2faceIDsMap.end(); ++e2fIt )
3468     {
3469       const TGeomID  edgeID = e2fIt->first;
3470       const TopoDS_Edge & E = TopoDS::Edge( _grid->Shape( edgeID ));
3471       BRepAdaptor_Curve curve( E );
3472       TopoDS_Vertex v1 = helper.IthVertex( 0, E, false );
3473       TopoDS_Vertex v2 = helper.IthVertex( 1, E, false );
3474
3475       ip._faceIDs = e2fIt->second;
3476       ip._shapeID = edgeID;
3477
3478       bool isInternal = ( ip._faceIDs.size() == 1 && _grid->IsInternal( edgeID ));
3479       if ( isInternal )
3480       {
3481         intEdgeIDs.Add( edgeID );
3482         intEdgeIDs.Add( _grid->ShapeID( v1 ));
3483         intEdgeIDs.Add( _grid->ShapeID( v2 ));
3484       }
3485
3486       // discretize the EDGE
3487       GCPnts_UniformDeflection discret( curve, deflection, true );
3488       if ( !discret.IsDone() || discret.NbPoints() < 2 )
3489         continue;
3490
3491       // perform intersection
3492       E_IntersectPoint* eip, *vip;
3493       for ( int iDirZ = 0; iDirZ < 3; ++iDirZ )
3494       {
3495         GridPlanes& planes = pln[ iDirZ ];
3496         int      iDirX = ( iDirZ + 1 ) % 3;
3497         int      iDirY = ( iDirZ + 2 ) % 3;
3498         double    xLen = _grid->_coords[ iDirX ].back() - _grid->_coords[ iDirX ][0];
3499         double    yLen = _grid->_coords[ iDirY ].back() - _grid->_coords[ iDirY ][0];
3500         double    zLen = _grid->_coords[ iDirZ ].back() - _grid->_coords[ iDirZ ][0];
3501         int dIJK[3], d000[3] = { 0,0,0 };
3502         double o[3] = { _grid->_coords[0][0],
3503                         _grid->_coords[1][0],
3504                         _grid->_coords[2][0] };
3505
3506         // locate the 1st point of a segment within the grid
3507         gp_XYZ p1     = discret.Value( 1 ).XYZ();
3508         double u1     = discret.Parameter( 1 );
3509         double zProj1 = planes._zNorm * ( p1 - _grid->_origin );
3510
3511         _grid->ComputeUVW( p1, ip._uvw );
3512         int iX1 = int(( ip._uvw[iDirX] - o[iDirX]) / xLen * (_grid->_coords[ iDirX ].size() - 1));
3513         int iY1 = int(( ip._uvw[iDirY] - o[iDirY]) / yLen * (_grid->_coords[ iDirY ].size() - 1));
3514         int iZ1 = int(( ip._uvw[iDirZ] - o[iDirZ]) / zLen * (_grid->_coords[ iDirZ ].size() - 1));
3515         locateValue( iX1, ip._uvw[iDirX], _grid->_coords[ iDirX ], dIJK[ iDirX ], tol );
3516         locateValue( iY1, ip._uvw[iDirY], _grid->_coords[ iDirY ], dIJK[ iDirY ], tol );
3517         locateValue( iZ1, ip._uvw[iDirZ], _grid->_coords[ iDirZ ], dIJK[ iDirZ ], tol );
3518
3519         int ijk[3]; // grid index where a segment intersects a plane
3520         ijk[ iDirX ] = iX1;
3521         ijk[ iDirY ] = iY1;
3522         ijk[ iDirZ ] = iZ1;
3523
3524         // add the 1st vertex point to a hexahedron
3525         if ( iDirZ == 0 )
3526         {
3527           ip._point   = p1;
3528           ip._shapeID = _grid->ShapeID( v1 );
3529           vip = _grid->Add( ip );
3530           if ( isInternal )
3531             vip->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
3532           if ( !addIntersection( vip, hexes, ijk, d000 ))
3533             _grid->Remove( vip );
3534           ip._shapeID = edgeID;
3535         }
3536         for ( int iP = 2; iP <= discret.NbPoints(); ++iP )
3537         {
3538           // locate the 2nd point of a segment within the grid
3539           gp_XYZ p2     = discret.Value( iP ).XYZ();
3540           double u2     = discret.Parameter( iP );
3541           double zProj2 = planes._zNorm * ( p2 - _grid->_origin );
3542           int    iZ2    = iZ1;
3543           if ( Abs( zProj2 - zProj1 ) > std::numeric_limits<double>::min() )
3544           {
3545             locateValue( iZ2, zProj2, planes._zProjs, dIJK[ iDirZ ], tol );
3546
3547             // treat intersections with planes between 2 end points of a segment
3548             int dZ = ( iZ1 <= iZ2 ) ? +1 : -1;
3549             int iZ = iZ1 + ( iZ1 < iZ2 );
3550             for ( int i = 0, nb = Abs( iZ1 - iZ2 ); i < nb; ++i, iZ += dZ )
3551             {
3552               ip._point = findIntPoint( u1, zProj1, u2, zProj2,
3553                                         planes._zProjs[ iZ ],
3554                                         curve, planes._zNorm, _grid->_origin );
3555               _grid->ComputeUVW( ip._point.XYZ(), ip._uvw );
3556               locateValue( ijk[iDirX], ip._uvw[iDirX], _grid->_coords[iDirX], dIJK[iDirX], tol );
3557               locateValue( ijk[iDirY], ip._uvw[iDirY], _grid->_coords[iDirY], dIJK[iDirY], tol );
3558               ijk[ iDirZ ] = iZ;
3559
3560               // add ip to hex "above" the plane
3561               eip = _grid->Add( ip );
3562               if ( isInternal )
3563                 eip->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
3564               dIJK[ iDirZ ] = 0;
3565               bool added = addIntersection( eip, hexes, ijk, dIJK);
3566
3567               // add ip to hex "below" the plane
3568               ijk[ iDirZ ] = iZ-1;
3569               if ( !addIntersection( eip, hexes, ijk, dIJK ) &&
3570                    !added )
3571                 _grid->Remove( eip );
3572             }
3573           }
3574           iZ1    = iZ2;
3575           p1     = p2;
3576           u1     = u2;
3577           zProj1 = zProj2;
3578         }
3579         // add the 2nd vertex point to a hexahedron
3580         if ( iDirZ == 0 )
3581         {
3582           ip._point   = p1;
3583           ip._shapeID = _grid->ShapeID( v2 );
3584           _grid->ComputeUVW( p1, ip._uvw );
3585           locateValue( ijk[iDirX], ip._uvw[iDirX], _grid->_coords[iDirX], dIJK[iDirX], tol );
3586           locateValue( ijk[iDirY], ip._uvw[iDirY], _grid->_coords[iDirY], dIJK[iDirY], tol );
3587           ijk[ iDirZ ] = iZ1;
3588           bool sameV = ( v1.IsSame( v2 ));
3589           if ( !sameV )
3590             vip = _grid->Add( ip );
3591           if ( isInternal && !sameV )
3592             vip->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
3593           if ( !addIntersection( vip, hexes, ijk, d000 ) && !sameV )
3594             _grid->Remove( vip );
3595           ip._shapeID = edgeID;
3596         }
3597       } // loop on 3 grid directions
3598     } // loop on EDGEs
3599
3600
3601     if ( intEdgeIDs.Size() > 0 )
3602       cutByExtendedInternal( hexes, intEdgeIDs );
3603
3604     return;
3605   }
3606
3607   //================================================================================
3608   /*!
3609    * \brief Fully cut hexes that are partially cut by INTERNAL FACE.
3610    *        Cut them by extended INTERNAL FACE.
3611    */
3612   void Hexahedron::cutByExtendedInternal( std::vector< Hexahedron* >& hexes,
3613                                           const TColStd_MapOfInteger& intEdgeIDs )
3614   {
3615     IntAna_IntConicQuad intersection;
3616     SMESHDS_Mesh* meshDS = _grid->_helper->GetMeshDS();
3617     const double tol2 = _grid->_tol * _grid->_tol;
3618
3619     for ( size_t iH = 0; iH < hexes.size(); ++iH )
3620     {
3621       Hexahedron* hex = hexes[ iH ];
3622       if ( !hex || hex->_eIntPoints.size() < 2 )
3623         continue;
3624       if ( !intEdgeIDs.Contains( hex->_eIntPoints.back()->_shapeID ))
3625         continue;
3626
3627       // get 3 points on INTERNAL FACE to construct a cutting plane
3628       gp_Pnt p1 = hex->_eIntPoints[0]->_point;
3629       gp_Pnt p2 = hex->_eIntPoints[1]->_point;
3630       gp_Pnt p3 = hex->mostDistantInternalPnt( iH, p1, p2 );
3631
3632       gp_Vec norm = gp_Vec( p1, p2 ) ^ gp_Vec( p1, p3 );
3633       gp_Pln pln;
3634       try {
3635         pln = gp_Pln( p1, norm );
3636       }
3637       catch(...)
3638       {
3639         continue;
3640       }
3641
3642       TGeomID intFaceID = hex->_eIntPoints.back()->_faceIDs.front(); // FACE being "extended"
3643       TGeomID   solidID = _grid->GetSolid( intFaceID )->ID();
3644
3645       // cut links by the plane
3646       //bool isCut = false;
3647       for ( int iLink = 0; iLink < 12; ++iLink )
3648       {
3649         _Link& link = hex->_hexLinks[ iLink ];
3650         if ( !link._fIntPoints.empty() )
3651         {
3652           // if ( link._fIntPoints[0]->_faceIDs.back() == _grid->PseudoIntExtFaceID() )
3653           //   isCut = true;
3654           continue; // already cut link
3655         }
3656         if ( !link._nodes[0]->Node() ||
3657              !link._nodes[1]->Node() )
3658           continue; // outside link
3659
3660         if ( link._nodes[0]->IsOnFace( intFaceID ))
3661         {
3662           if ( link._nodes[0]->_intPoint->_faceIDs.back() != _grid->PseudoIntExtFaceID() )
3663             if ( p1.SquareDistance( link._nodes[0]->Point() ) < tol2  ||
3664                  p2.SquareDistance( link._nodes[0]->Point() ) < tol2 )
3665               link._nodes[0]->_intPoint->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
3666           continue; // link is cut by FACE being "extended"
3667         }
3668         if ( link._nodes[1]->IsOnFace( intFaceID ))
3669         {
3670           if ( link._nodes[1]->_intPoint->_faceIDs.back() != _grid->PseudoIntExtFaceID() )
3671             if ( p1.SquareDistance( link._nodes[1]->Point() ) < tol2  ||
3672                  p2.SquareDistance( link._nodes[1]->Point() ) < tol2 )
3673               link._nodes[1]->_intPoint->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
3674           continue; // link is cut by FACE being "extended"
3675         }
3676         gp_Pnt p4 = link._nodes[0]->Point();
3677         gp_Pnt p5 = link._nodes[1]->Point();
3678         gp_Lin line( p4, gp_Vec( p4, p5 ));
3679
3680         intersection.Perform( line, pln );
3681         if ( !intersection.IsDone() ||
3682              intersection.IsInQuadric() ||
3683              intersection.IsParallel() ||
3684              intersection.NbPoints() < 1 )
3685           continue;
3686
3687         double u = intersection.ParamOnConic(1);
3688         if ( u + _grid->_tol < 0 )
3689           continue;
3690         int       iDir = iLink / 4;
3691         int      index = (&hex->_i)[iDir];
3692         double linkLen = _grid->_coords[iDir][index+1] - _grid->_coords[iDir][index];
3693         if ( u - _grid->_tol > linkLen )
3694           continue;
3695
3696         if ( u < _grid->_tol ||
3697              u > linkLen - _grid->_tol ) // intersection at grid node
3698         {
3699           int  i = ! ( u < _grid->_tol ); // [0,1]
3700           int iN = link._nodes[ i ] - hex->_hexNodes; // [0-7]
3701
3702           const F_IntersectPoint * & ip = _grid->_gridIntP[ hex->_origNodeInd +
3703                                                             _grid->_nodeShift[iN] ];
3704           if ( !ip )
3705           {
3706             ip = _grid->_extIntPool.getNew();
3707             ip->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
3708             //ip->_transition = Trans_INTERNAL;
3709           }
3710           else if ( ip->_faceIDs.back() != _grid->PseudoIntExtFaceID() )
3711           {
3712             ip->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
3713           }
3714           hex->_nbFaceIntNodes++;
3715           //isCut = true;
3716         }
3717         else
3718         {
3719           const gp_Pnt&      p = intersection.Point( 1 );
3720           F_IntersectPoint* ip = _grid->_extIntPool.getNew();
3721           ip->_node = meshDS->AddNode( p.X(), p.Y(), p.Z() );
3722           ip->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
3723           ip->_transition = Trans_INTERNAL;
3724           meshDS->SetNodeInVolume( ip->_node, solidID );
3725
3726           CellsAroundLink fourCells( _grid, iDir );
3727           fourCells.Init( hex->_i, hex->_j, hex->_k, iLink );
3728           int i,j,k, cellIndex;
3729           for ( int iC = 0; iC < 4; ++iC ) // loop on 4 cells sharing the link
3730           {
3731             if ( !fourCells.GetCell( iC, i,j,k, cellIndex, iLink ))
3732               continue;
3733             Hexahedron * h = hexes[ cellIndex ];
3734             if ( !h )
3735               h = hexes[ cellIndex ] = new Hexahedron( *this, i, j, k, cellIndex );
3736             h->_hexLinks[iLink]._fIntPoints.push_back( ip );
3737             h->_nbFaceIntNodes++;
3738             //isCut = true;
3739           }
3740         }
3741       }
3742
3743       // if ( isCut )
3744       //   for ( size_t i = 0; i < hex->_eIntPoints.size(); ++i )
3745       //   {
3746       //     if ( _grid->IsInternal( hex->_eIntPoints[i]->_shapeID ) &&
3747       //          ! hex->_eIntPoints[i]->IsOnFace( _grid->PseudoIntExtFaceID() ))
3748       //       hex->_eIntPoints[i]->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
3749       //   }
3750       continue;
3751
3752     } // loop on all hexes
3753     return;
3754   }
3755
3756   //================================================================================
3757   /*!
3758    * \brief Return intersection point on INTERNAL FACE most distant from given ones
3759    */
3760   gp_Pnt Hexahedron::mostDistantInternalPnt( int hexIndex, const gp_Pnt& p1, const gp_Pnt& p2 )
3761   {
3762     gp_Pnt resultPnt = p1;
3763
3764     double maxDist2 = 0;
3765     for ( int iLink = 0; iLink < 12; ++iLink ) // check links
3766     {
3767       _Link& link = _hexLinks[ iLink ];
3768       for ( size_t i = 0; i < link._fIntPoints.size(); ++i )
3769         if ( _grid->PseudoIntExtFaceID() != link._fIntPoints[i]->_faceIDs[0] &&
3770              _grid->IsInternal( link._fIntPoints[i]->_faceIDs[0] ) &&
3771              link._fIntPoints[i]->_node )
3772         {
3773           gp_Pnt p = SMESH_NodeXYZ( link._fIntPoints[i]->_node );
3774           double d = p1.SquareDistance( p );
3775           if ( d > maxDist2 )
3776           {
3777             resultPnt = p;
3778             maxDist2  = d;
3779           }
3780           else
3781           {
3782             d = p2.SquareDistance( p );
3783             if ( d > maxDist2 )
3784             {
3785               resultPnt = p;
3786               maxDist2  = d;
3787             }
3788           }
3789         }
3790     }
3791     setIJK( hexIndex );
3792     _origNodeInd = _grid->NodeIndex( _i,_j,_k );
3793
3794     for ( size_t iN = 0; iN < 8; ++iN ) // check corners
3795     {
3796       _hexNodes[iN]._node     = _grid->_nodes   [ _origNodeInd + _grid->_nodeShift[iN] ];
3797       _hexNodes[iN]._intPoint = _grid->_gridIntP[ _origNodeInd + _grid->_nodeShift[iN] ];
3798       if ( _hexNodes[iN]._intPoint )
3799         for ( size_t iF = 0; iF < _hexNodes[iN]._intPoint->_faceIDs.size(); ++iF )
3800         {
3801           if ( _grid->IsInternal( _hexNodes[iN]._intPoint->_faceIDs[iF]))
3802           {
3803             gp_Pnt p = SMESH_NodeXYZ( _hexNodes[iN]._node );
3804             double d = p1.SquareDistance( p );
3805             if ( d > maxDist2 )
3806             {
3807               resultPnt = p;
3808               maxDist2  = d;
3809             }
3810             else
3811             {
3812               d = p2.SquareDistance( p );
3813               if ( d > maxDist2 )
3814               {
3815                 resultPnt = p;
3816                 maxDist2  = d;
3817               }
3818             }
3819           }
3820         }
3821     }
3822     if ( maxDist2 < _grid->_tol * _grid->_tol )
3823       return p1;
3824
3825     return resultPnt;
3826   }
3827
3828   //================================================================================
3829   /*!
3830    * \brief Finds intersection of a curve with a plane
3831    *  \param [in] u1 - parameter of one curve point
3832    *  \param [in] proj1 - projection of the curve point to the plane normal
3833    *  \param [in] u2 - parameter of another curve point
3834    *  \param [in] proj2 - projection of the other curve point to the plane normal
3835    *  \param [in] proj - projection of a point where the curve intersects the plane
3836    *  \param [in] curve - the curve
3837    *  \param [in] axis - the plane normal
3838    *  \param [in] origin - the plane origin
3839    *  \return gp_Pnt - the found intersection point
3840    */
3841   gp_Pnt Hexahedron::findIntPoint( double u1, double proj1,
3842                                    double u2, double proj2,
3843                                    double proj,
3844                                    BRepAdaptor_Curve& curve,
3845                                    const gp_XYZ& axis,
3846                                    const gp_XYZ& origin)
3847   {
3848     double r = (( proj - proj1 ) / ( proj2 - proj1 ));
3849     double u = u1 * ( 1 - r ) + u2 * r;
3850     gp_Pnt p = curve.Value( u );
3851     double newProj =  axis * ( p.XYZ() - origin );
3852     if ( Abs( proj - newProj ) > _grid->_tol / 10. )
3853     {
3854       if ( r > 0.5 )
3855         return findIntPoint( u2, proj2, u, newProj, proj, curve, axis, origin );
3856       else
3857         return findIntPoint( u1, proj2, u, newProj, proj, curve, axis, origin );
3858     }
3859     return p;
3860   }
3861
3862   //================================================================================
3863   /*!
3864    * \brief Returns indices of a hexahedron sub-entities holding a point
3865    *  \param [in] ip - intersection point
3866    *  \param [out] facets - 0-3 facets holding a point
3867    *  \param [out] sub - index of a vertex or an edge holding a point
3868    *  \return int - number of facets holding a point
3869    */
3870   int Hexahedron::getEntity( const E_IntersectPoint* ip, int* facets, int& sub )
3871   {
3872     enum { X = 1, Y = 2, Z = 4 }; // == 001, 010, 100
3873     int nbFacets = 0;
3874     int vertex = 0, edgeMask = 0;
3875
3876     if ( Abs( _grid->_coords[0][ _i   ] - ip->_uvw[0] ) < _grid->_tol ) {
3877       facets[ nbFacets++ ] = SMESH_Block::ID_F0yz;
3878       edgeMask |= X;
3879     }
3880     else if ( Abs( _grid->_coords[0][ _i+1 ] - ip->_uvw[0] ) < _grid->_tol ) {
3881       facets[ nbFacets++ ] = SMESH_Block::ID_F1yz;
3882       vertex   |= X;
3883       edgeMask |= X;
3884     }
3885     if ( Abs( _grid->_coords[1][ _j   ] - ip->_uvw[1] ) < _grid->_tol ) {
3886       facets[ nbFacets++ ] = SMESH_Block::ID_Fx0z;
3887       edgeMask |= Y;
3888     }
3889     else if ( Abs( _grid->_coords[1][ _j+1 ] - ip->_uvw[1] ) < _grid->_tol ) {
3890       facets[ nbFacets++ ] = SMESH_Block::ID_Fx1z;
3891       vertex   |= Y;
3892       edgeMask |= Y;
3893     }
3894     if ( Abs( _grid->_coords[2][ _k   ] - ip->_uvw[2] ) < _grid->_tol ) {
3895       facets[ nbFacets++ ] = SMESH_Block::ID_Fxy0;
3896       edgeMask |= Z;
3897     }
3898     else if ( Abs( _grid->_coords[2][ _k+1 ] - ip->_uvw[2] ) < _grid->_tol ) {
3899       facets[ nbFacets++ ] = SMESH_Block::ID_Fxy1;
3900       vertex   |= Z;
3901       edgeMask |= Z;
3902     }
3903
3904     switch ( nbFacets )
3905     {
3906     case 0: sub = 0;         break;
3907     case 1: sub = facets[0]; break;
3908     case 2: {
3909       const int edge [3][8] = {
3910         { SMESH_Block::ID_E00z, SMESH_Block::ID_E10z,
3911           SMESH_Block::ID_E01z, SMESH_Block::ID_E11z },
3912         { SMESH_Block::ID_E0y0, SMESH_Block::ID_E1y0, 0, 0,
3913           SMESH_Block::ID_E0y1, SMESH_Block::ID_E1y1 },
3914         { SMESH_Block::ID_Ex00, 0, SMESH_Block::ID_Ex10, 0,
3915           SMESH_Block::ID_Ex01, 0, SMESH_Block::ID_Ex11 }
3916       };
3917       switch ( edgeMask ) {
3918       case X | Y: sub = edge[ 0 ][ vertex ]; break;
3919       case X | Z: sub = edge[ 1 ][ vertex ]; break;
3920       default:    sub = edge[ 2 ][ vertex ];
3921       }
3922       break;
3923     }
3924     //case 3:
3925     default:
3926       sub = vertex + SMESH_Block::ID_FirstV;
3927     }
3928
3929     return nbFacets;
3930   }
3931   //================================================================================
3932   /*!
3933    * \brief Adds intersection with an EDGE
3934    */
3935   bool Hexahedron::addIntersection( const E_IntersectPoint* ip,
3936                                     vector< Hexahedron* >&  hexes,
3937                                     int ijk[], int dIJK[] )
3938   {
3939     bool added = false;
3940
3941     size_t hexIndex[4] = {
3942       _grid->CellIndex( ijk[0], ijk[1], ijk[2] ),
3943       dIJK[0] ? _grid->CellIndex( ijk[0]+dIJK[0], ijk[1], ijk[2] ) : -1,
3944       dIJK[1] ? _grid->CellIndex( ijk[0], ijk[1]+dIJK[1], ijk[2] ) : -1,
3945       dIJK[2] ? _grid->CellIndex( ijk[0], ijk[1], ijk[2]+dIJK[2] ) : -1
3946     };
3947     for ( int i = 0; i < 4; ++i )
3948     {
3949       if ( hexIndex[i] < hexes.size() && hexes[ hexIndex[i] ] )
3950       {
3951         Hexahedron* h = hexes[ hexIndex[i] ];
3952         h->_eIntPoints.reserve(2);
3953         h->_eIntPoints.push_back( ip );
3954         added = true;
3955 #ifdef _DEBUG_
3956         // check if ip is really inside the hex
3957         if ( h->isOutParam( ip->_uvw ))
3958           throw SALOME_Exception("ip outside a hex");
3959 #endif
3960       }
3961     }
3962     return added;
3963   }
3964   //================================================================================
3965   /*!
3966    * \brief Finds nodes at a path from one node to another via intersections with EDGEs
3967    */
3968   bool Hexahedron::findChain( _Node*          n1,
3969                               _Node*          n2,
3970                               _Face&          quad,
3971                               vector<_Node*>& chn )
3972   {
3973     chn.clear();
3974     chn.push_back( n1 );
3975     for ( size_t iP = 0; iP < quad._eIntNodes.size(); ++iP )
3976       if ( !quad._eIntNodes[ iP ]->IsUsedInFace( &quad ) &&
3977            n1->IsLinked( quad._eIntNodes[ iP ]->_intPoint ) &&
3978            n2->IsLinked( quad._eIntNodes[ iP ]->_intPoint ))
3979       {
3980         chn.push_back( quad._eIntNodes[ iP ]);
3981         chn.push_back( n2 );
3982         quad._eIntNodes[ iP ]->_usedInFace = &quad;
3983         return true;
3984       }
3985     bool found;
3986     do
3987     {
3988       found = false;
3989       for ( size_t iP = 0; iP < quad._eIntNodes.size(); ++iP )
3990         if ( !quad._eIntNodes[ iP ]->IsUsedInFace( &quad ) &&
3991              chn.back()->IsLinked( quad._eIntNodes[ iP ]->_intPoint ))
3992         {
3993           chn.push_back( quad._eIntNodes[ iP ]);
3994           found = ( quad._eIntNodes[ iP ]->_usedInFace = &quad );
3995           break;
3996         }
3997     } while ( found && ! chn.back()->IsLinked( n2->_intPoint ) );
3998
3999     if ( chn.back() != n2 && chn.back()->IsLinked( n2->_intPoint ))
4000       chn.push_back( n2 );
4001
4002     return chn.size() > 1;
4003   }
4004   //================================================================================
4005   /*!
4006    * \brief Try to heal a polygon whose ends are not connected
4007    */
4008   bool Hexahedron::closePolygon( _Face* polygon, vector<_Node*>& chainNodes ) const
4009   {
4010     int i = -1, nbLinks = polygon->_links.size();
4011     if ( nbLinks < 3 )
4012       return false;
4013     vector< _OrientedLink > newLinks;
4014     // find a node lying on the same FACE as the last one
4015     _Node*   node = polygon->_links.back().LastNode();
4016     int avoidFace = node->IsLinked( polygon->_links.back().FirstNode()->_intPoint );
4017     for ( i = nbLinks - 2; i >= 0; --i )
4018       if ( node->IsLinked( polygon->_links[i].FirstNode()->_intPoint, avoidFace ))
4019         break;
4020     if ( i >= 0 )
4021     {
4022       for ( ; i < nbLinks; ++i )
4023         newLinks.push_back( polygon->_links[i] );
4024     }
4025     else
4026     {
4027       // find a node lying on the same FACE as the first one
4028       node      = polygon->_links[0].FirstNode();
4029       avoidFace = node->IsLinked( polygon->_links[0].LastNode()->_intPoint );
4030       for ( i = 1; i < nbLinks; ++i )
4031         if ( node->IsLinked( polygon->_links[i].LastNode()->_intPoint, avoidFace ))
4032           break;
4033       if ( i < nbLinks )
4034         for ( nbLinks = i + 1, i = 0; i < nbLinks; ++i )
4035           newLinks.push_back( polygon->_links[i] );
4036     }
4037     if ( newLinks.size() > 1 )
4038     {
4039       polygon->_links.swap( newLinks );
4040       chainNodes.clear();
4041       chainNodes.push_back( polygon->_links.back().LastNode() );
4042       chainNodes.push_back( polygon->_links[0].FirstNode() );
4043       return true;
4044     }
4045     return false;
4046   }
4047   //================================================================================
4048   /*!
4049    * \brief Finds nodes on the same EDGE as the first node of avoidSplit.
4050    *
4051    * This function is for
4052    * 1) a case where an EDGE lies on a quad which lies on a FACE
4053    *    so that a part of quad in ON and another part is IN
4054    * 2) INTERNAL FACE passes through the 1st node of avoidSplit
4055    */
4056   bool Hexahedron::findChainOnEdge( const vector< _OrientedLink >& splits,
4057                                     const _OrientedLink&           prevSplit,
4058                                     const _OrientedLink&           avoidSplit,
4059                                     size_t &                       iS,
4060                                     _Face&                         quad,
4061                                     vector<_Node*>&                chn )
4062   {
4063     _Node* pn1 = prevSplit.FirstNode();
4064     _Node* pn2 = prevSplit.LastNode();
4065     int avoidFace = pn1->IsLinked( pn2->_intPoint ); // FACE under the quad
4066     if ( avoidFace < 1 && pn1->_intPoint )
4067       return false;
4068
4069     _Node* n = 0, *stopNode = avoidSplit.LastNode();
4070
4071     chn.clear();
4072     if ( !quad._eIntNodes.empty() ) // connect pn2 with EDGE intersections
4073     {
4074       chn.push_back( pn2 );
4075       bool found;
4076       do
4077       {
4078         found = false;
4079         for ( size_t iP = 0; iP < quad._eIntNodes.size(); ++iP )
4080           if (( !quad._eIntNodes[ iP ]->IsUsedInFace( &quad )) &&
4081               ( chn.back()->IsLinked( quad._eIntNodes[ iP ]->_intPoint, avoidFace )) &&
4082               ( !avoidFace || quad._eIntNodes[ iP ]->IsOnFace( avoidFace )))
4083           {
4084             chn.push_back( quad._eIntNodes[ iP ]);
4085             found = ( quad._eIntNodes[ iP ]->_usedInFace = &quad );
4086             break;
4087           }
4088       } while ( found );
4089       pn2 = chn.back();
4090     }
4091
4092     int i;
4093     for ( i = splits.size()-1; i >= 0; --i ) // connect new pn2 (at _eIntNodes) with a split
4094     {
4095       if ( !splits[i] )
4096         continue;
4097
4098       n = splits[i].LastNode();
4099       if ( n == stopNode )
4100         break;
4101       if (( n != pn1 ) &&
4102           ( n->IsLinked( pn2->_intPoint, avoidFace )) &&
4103           ( !avoidFace || n->IsOnFace( avoidFace )))
4104         break;
4105
4106       n = splits[i].FirstNode();
4107       if ( n == stopNode )
4108         break;
4109       if (( n->IsLinked( pn2->_intPoint, avoidFace )) &&
4110           ( !avoidFace || n->IsOnFace( avoidFace )))
4111         break;
4112       n = 0;
4113     }
4114     if ( n && n != stopNode )
4115     {
4116       if ( chn.empty() )
4117         chn.push_back( pn2 );
4118       chn.push_back( n );
4119       iS = i-1;
4120       return true;
4121     }
4122     else if ( !chn.empty() && chn.back()->_isInternalFlags )
4123     {
4124       // INTERNAL FACE partially cuts the quad
4125       for ( int i = chn.size() - 2; i >= 0; --i )
4126         chn.push_back( chn[ i ]);
4127       return true;
4128     }
4129     return false;
4130   }
4131   //================================================================================
4132   /*!
4133    * \brief Checks transition at the ginen intersection node of a link
4134    */
4135   bool Hexahedron::isOutPoint( _Link& link, int iP,
4136                                SMESH_MesherHelper& helper, const Solid* solid ) const
4137   {
4138     bool isOut = false;
4139
4140     if ( link._fIntNodes[iP]->faces().size() == 1 &&
4141          _grid->IsInternal( link._fIntNodes[iP]->face(0) ))
4142       return false;
4143
4144     const bool moreIntPoints = ( iP+1 < (int) link._fIntNodes.size() );
4145
4146     // get 2 _Node's
4147     _Node* n1 = link._fIntNodes[ iP ];
4148     if ( !n1->Node() )
4149       n1 = link._nodes[0];
4150     _Node* n2 = moreIntPoints ? link._fIntNodes[ iP+1 ] : 0;
4151     if ( !n2 || !n2->Node() )
4152       n2 = link._nodes[1];
4153     if ( !n2->Node() )
4154       return true;
4155
4156     // get all FACEs under n1 and n2
4157     set< TGeomID > faceIDs;
4158     if ( moreIntPoints ) faceIDs.insert( link._fIntNodes[iP+1]->faces().begin(),
4159                                          link._fIntNodes[iP+1]->faces().end() );
4160     if ( n2->_intPoint ) faceIDs.insert( n2->_intPoint->_faceIDs.begin(),
4161                                          n2->_intPoint->_faceIDs.end() );
4162     if ( faceIDs.empty() )
4163       return false; // n2 is inside
4164     if ( n1->_intPoint ) faceIDs.insert( n1->_intPoint->_faceIDs.begin(),
4165                                          n1->_intPoint->_faceIDs.end() );
4166     faceIDs.insert( link._fIntNodes[iP]->faces().begin(),
4167                     link._fIntNodes[iP]->faces().end() );
4168
4169     // get a point between 2 nodes
4170     gp_Pnt p1      = n1->Point();
4171     gp_Pnt p2      = n2->Point();
4172     gp_Pnt pOnLink = 0.8 * p1.XYZ() + 0.2 * p2.XYZ();
4173
4174     TopLoc_Location loc;
4175
4176     set< TGeomID >::iterator faceID = faceIDs.begin();
4177     for ( ; faceID != faceIDs.end(); ++faceID )
4178     {
4179       // project pOnLink on a FACE
4180       if ( *faceID < 1 || !solid->Contains( *faceID )) continue;
4181       const TopoDS_Face& face = TopoDS::Face( _grid->Shape( *faceID ));
4182       GeomAPI_ProjectPointOnSurf& proj = helper.GetProjector( face, loc, 0.1*_grid->_tol );
4183       gp_Pnt testPnt = pOnLink.Transformed( loc.Transformation().Inverted() );
4184       proj.Perform( testPnt );
4185       if ( proj.IsDone() && proj.NbPoints() > 0 )       
4186       {
4187         Standard_Real u,v;
4188         proj.LowerDistanceParameters( u,v );
4189
4190         if ( proj.LowerDistance() <= 0.1 * _grid->_tol )
4191         {
4192           isOut = false;
4193         }
4194         else
4195         {
4196           // find isOut by normals
4197           gp_Dir normal;
4198           if ( GeomLib::NormEstim( BRep_Tool::Surface( face, loc ),
4199                                    gp_Pnt2d( u,v ),
4200                                    0.1*_grid->_tol,
4201                                    normal ) < 3 )
4202           {
4203             if ( solid->Orientation( face ) == TopAbs_REVERSED )
4204               normal.Reverse();
4205             gp_Vec v( proj.NearestPoint(), testPnt );
4206             isOut = ( v * normal > 0 );
4207           }
4208         }
4209         if ( !isOut )
4210         {
4211           // classify a projection
4212           if ( !n1->IsOnFace( *faceID ) || !n2->IsOnFace( *faceID ))
4213           {
4214             BRepTopAdaptor_FClass2d cls( face, Precision::Confusion() );
4215             TopAbs_State state = cls.Perform( gp_Pnt2d( u,v ));
4216             if ( state == TopAbs_OUT )
4217             {
4218               isOut = true;
4219               continue;
4220             }
4221           }
4222           return false;
4223         }
4224       }
4225     }
4226     return isOut;
4227   }
4228   //================================================================================
4229   /*!
4230    * \brief Sort nodes on a FACE
4231    */
4232   void Hexahedron::sortVertexNodes(vector<_Node*>& nodes, _Node* curNode, TGeomID faceID)
4233   {
4234     if ( nodes.size() > 20 ) return;
4235
4236     // get shapes under nodes
4237     TGeomID nShapeIds[20], *nShapeIdsEnd = &nShapeIds[0] + nodes.size();
4238     for ( size_t i = 0; i < nodes.size(); ++i )
4239       if ( !( nShapeIds[i] = nodes[i]->ShapeID() ))
4240         return;
4241
4242     // get shapes of the FACE
4243     const TopoDS_Face&  face = TopoDS::Face( _grid->Shape( faceID ));
4244     list< TopoDS_Edge > edges;
4245     list< int >         nbEdges;
4246     int nbW = SMESH_Block::GetOrderedEdges (face, edges, nbEdges);
4247     if ( nbW > 1 ) {
4248       // select a WIRE - remove EDGEs of irrelevant WIREs from edges
4249       list< TopoDS_Edge >::iterator e = edges.begin(), eEnd = e;
4250       list< int >::iterator nE = nbEdges.begin();
4251       for ( ; nbW > 0; ++nE, --nbW )
4252       {
4253         std::advance( eEnd, *nE );
4254         for ( ; e != eEnd; ++e )
4255           for ( int i = 0; i < 2; ++i )
4256           {
4257             TGeomID id = i==0 ?
4258               _grid->ShapeID( *e ) :
4259               _grid->ShapeID( SMESH_MesherHelper::IthVertex( 0, *e ));
4260             if (( id > 0 ) &&
4261                 ( std::find( &nShapeIds[0], nShapeIdsEnd, id ) != nShapeIdsEnd ))
4262             {
4263               edges.erase( eEnd, edges.end() ); // remove rest wires
4264               e = eEnd = edges.end();
4265               --e;
4266               nbW = 0;
4267               break;
4268             }
4269           }
4270         if ( nbW > 0 )
4271           edges.erase( edges.begin(), eEnd ); // remove a current irrelevant wire
4272       }
4273     }
4274     // rotate edges to have the first one at least partially out of the hexa
4275     list< TopoDS_Edge >::iterator e = edges.begin(), eMidOut = edges.end();
4276     for ( ; e != edges.end(); ++e )
4277     {
4278       if ( !_grid->ShapeID( *e ))
4279         continue;
4280       bool isOut = false;
4281       gp_Pnt p;
4282       double uvw[3], f,l;
4283       for ( int i = 0; i < 2 && !isOut; ++i )
4284       {
4285         if ( i == 0 )
4286         {
4287           TopoDS_Vertex v = SMESH_MesherHelper::IthVertex( 0, *e );
4288           p = BRep_Tool::Pnt( v );
4289         }
4290         else if ( eMidOut == edges.end() )
4291         {
4292           TopLoc_Location loc;
4293           Handle(Geom_Curve) c = BRep_Tool::Curve( *e, loc, f, l);
4294           if ( c.IsNull() ) break;
4295           p = c->Value( 0.5 * ( f + l )).Transformed( loc );
4296         }
4297         else
4298         {
4299           continue;
4300         }
4301
4302         _grid->ComputeUVW( p.XYZ(), uvw );
4303         if ( isOutParam( uvw ))
4304         {
4305           if ( i == 0 )
4306             isOut = true;
4307           else
4308             eMidOut = e;
4309         }
4310       }
4311       if ( isOut )
4312         break;
4313     }
4314     if ( e != edges.end() )
4315       edges.splice( edges.end(), edges, edges.begin(), e );
4316     else if ( eMidOut != edges.end() )
4317       edges.splice( edges.end(), edges, edges.begin(), eMidOut );
4318
4319     // sort nodes according to the order of edges
4320     _Node*  orderNodes   [20];
4321     //TGeomID orderShapeIDs[20];
4322     size_t nbN = 0;
4323     TGeomID id, *pID = 0;
4324     for ( e = edges.begin(); e != edges.end(); ++e )
4325     {
4326       if (( id = _grid->ShapeID( SMESH_MesherHelper::IthVertex( 0, *e ))) &&
4327           (( pID = std::find( &nShapeIds[0], nShapeIdsEnd, id )) != nShapeIdsEnd ))
4328       {
4329         //orderShapeIDs[ nbN ] = id;
4330         orderNodes   [ nbN++ ] = nodes[ pID - &nShapeIds[0] ];
4331         *pID = -1;
4332       }
4333       if (( id = _grid->ShapeID( *e )) &&
4334           (( pID = std::find( &nShapeIds[0], nShapeIdsEnd, id )) != nShapeIdsEnd ))
4335       {
4336         //orderShapeIDs[ nbN ] = id;
4337         orderNodes   [ nbN++ ] = nodes[ pID - &nShapeIds[0] ];
4338         *pID = -1;
4339       }
4340     }
4341     if ( nbN != nodes.size() )
4342       return;
4343
4344     bool reverse = ( orderNodes[0    ]->Point().SquareDistance( curNode->Point() ) >
4345                      orderNodes[nbN-1]->Point().SquareDistance( curNode->Point() ));
4346
4347     for ( size_t i = 0; i < nodes.size(); ++i )
4348       nodes[ i ] = orderNodes[ reverse ? nbN-1-i : i ];
4349   }
4350
4351   //================================================================================
4352   /*!
4353    * \brief Adds computed elements to the mesh
4354    */
4355   int Hexahedron::addVolumes( SMESH_MesherHelper& helper )
4356   {
4357     F_IntersectPoint noIntPnt;
4358     const bool toCheckNodePos = _grid->IsToCheckNodePos();
4359
4360     int nbAdded = 0;
4361     // add elements resulted from hexahedron intersection
4362     for ( _volumeDef* volDef = &_volumeDefs; volDef; volDef = volDef->_next )
4363     {
4364       vector< const SMDS_MeshNode* > nodes( volDef->_nodes.size() );
4365       for ( size_t iN = 0; iN < nodes.size(); ++iN )
4366       {
4367         if ( !( nodes[iN] = volDef->_nodes[iN].Node() ))
4368         {
4369           if ( const E_IntersectPoint* eip = volDef->_nodes[iN].EdgeIntPnt() )
4370           {
4371             nodes[iN] = volDef->_nodes[iN]._intPoint->_node =
4372               helper.AddNode( eip->_point.X(),
4373                               eip->_point.Y(),
4374                               eip->_point.Z() );
4375             if ( _grid->ShapeType( eip->_shapeID ) == TopAbs_VERTEX )
4376               helper.GetMeshDS()->SetNodeOnVertex( nodes[iN], eip->_shapeID );
4377             else
4378               helper.GetMeshDS()->SetNodeOnEdge( nodes[iN], eip->_shapeID );
4379           }
4380           else
4381             throw SALOME_Exception("Bug: no node at intersection point");
4382         }
4383         else if ( volDef->_nodes[iN]._intPoint &&
4384                   volDef->_nodes[iN]._intPoint->_node == volDef->_nodes[iN]._node )
4385         {
4386           // Update position of node at EDGE intersection;
4387           // see comment to _Node::Add( E_IntersectPoint )
4388           SMESHDS_Mesh* mesh = helper.GetMeshDS();
4389           TGeomID    shapeID = volDef->_nodes[iN].EdgeIntPnt()->_shapeID;
4390           mesh->UnSetNodeOnShape( nodes[iN] );
4391           if ( _grid->ShapeType( shapeID ) == TopAbs_VERTEX )
4392             mesh->SetNodeOnVertex( nodes[iN], shapeID );
4393           else
4394             mesh->SetNodeOnEdge( nodes[iN], shapeID );
4395         }
4396         else if ( toCheckNodePos &&
4397                   !nodes[iN]->isMarked() && 
4398                   _grid->ShapeType( nodes[iN]->GetShapeID() ) == TopAbs_FACE )
4399         {
4400           _grid->SetOnShape( nodes[iN], noIntPnt, /*unset=*/true );
4401           nodes[iN]->setIsMarked( true );
4402         }
4403       }
4404
4405       const SMDS_MeshElement* v = 0;
4406       if ( !volDef->_quantities.empty() )
4407       {
4408         v = helper.AddPolyhedralVolume( nodes, volDef->_quantities );
4409       }
4410       else
4411       {
4412         switch ( nodes.size() )
4413         {
4414         case 8: v = helper.AddVolume( nodes[0],nodes[1],nodes[2],nodes[3],
4415                                       nodes[4],nodes[5],nodes[6],nodes[7] );
4416           break;
4417         case 4: v = helper.AddVolume( nodes[0],nodes[1],nodes[2],nodes[3] );
4418           break;
4419         case 6: v = helper.AddVolume( nodes[0],nodes[1],nodes[2],nodes[3],nodes[4],nodes[5] );
4420           break;
4421         case 5: v = helper.AddVolume( nodes[0],nodes[1],nodes[2],nodes[3],nodes[4] );
4422           break;
4423         }
4424       }
4425       if (( volDef->_volume = v ))
4426       {
4427         helper.GetMeshDS()->SetMeshElementOnShape( v, volDef->_solidID );
4428         ++nbAdded;
4429       }
4430     }
4431
4432     return nbAdded;
4433   }
4434   //================================================================================
4435   /*!
4436    * \brief Return true if the element is in a hole
4437    */
4438   bool Hexahedron::isInHole() const
4439   {
4440     if ( !_vIntNodes.empty() )
4441       return false;
4442
4443     const size_t ijk[3] = { _i, _j, _k };
4444     F_IntersectPoint curIntPnt;
4445
4446     // consider a cell to be in a hole if all links in any direction
4447     // comes OUT of geometry
4448     for ( int iDir = 0; iDir < 3; ++iDir )
4449     {
4450       const vector<double>& coords = _grid->_coords[ iDir ];
4451       LineIndexer               li = _grid->GetLineIndexer( iDir );
4452       li.SetIJK( _i,_j,_k );
4453       size_t lineIndex[4] = { li.LineIndex  (),
4454                               li.LineIndex10(),
4455                               li.LineIndex01(),
4456                               li.LineIndex11() };
4457       bool allLinksOut = true, hasLinks = false;
4458       for ( int iL = 0; iL < 4 && allLinksOut; ++iL ) // loop on 4 links parallel to iDir
4459       {
4460         const _Link& link = _hexLinks[ iL + 4*iDir ];
4461         // check transition of the first node of a link
4462         const F_IntersectPoint* firstIntPnt = 0;
4463         if ( link._nodes[0]->Node() ) // 1st node is a hexa corner
4464         {
4465           curIntPnt._paramOnLine = coords[ ijk[ iDir ]] - coords[0] + _grid->_tol;
4466           const GridLine& line = _grid->_lines[ iDir ][ lineIndex[ iL ]];
4467           multiset< F_IntersectPoint >::const_iterator ip =
4468             line._intPoints.upper_bound( curIntPnt );
4469           --ip;
4470           firstIntPnt = &(*ip);
4471         }
4472         else if ( !link._fIntPoints.empty() )
4473         {
4474           firstIntPnt = link._fIntPoints[0];
4475         }
4476
4477         if ( firstIntPnt )
4478         {
4479           hasLinks = true;
4480           allLinksOut = ( firstIntPnt->_transition == Trans_OUT &&
4481                           !_grid->IsShared( firstIntPnt->_faceIDs[0] ));
4482         }
4483       }
4484       if ( hasLinks && allLinksOut )
4485         return true;
4486     }
4487     return false;
4488   }
4489
4490   //================================================================================
4491   /*!
4492    * \brief Check if a polyherdon has an edge lying on EDGE shared by strange FACE
4493    *        that will be meshed by other algo
4494    */
4495   bool Hexahedron::hasStrangeEdge() const
4496   {
4497     if ( _eIntPoints.size() < 2 )
4498       return false;
4499
4500     TopTools_MapOfShape edges;
4501     for ( size_t i = 0; i < _eIntPoints.size(); ++i )
4502     {
4503       if ( !_grid->IsStrangeEdge( _eIntPoints[i]->_shapeID ))
4504         continue;
4505       const TopoDS_Shape& s = _grid->Shape( _eIntPoints[i]->_shapeID );
4506       if ( s.ShapeType() == TopAbs_EDGE )
4507       {
4508         if ( ! edges.Add( s ))
4509           return true; // an EDGE encounters twice
4510       }
4511       else
4512       {
4513         PShapeIteratorPtr edgeIt = _grid->_helper->GetAncestors( s,
4514                                                                  *_grid->_helper->GetMesh(),
4515                                                                  TopAbs_EDGE );
4516         while ( const TopoDS_Shape* edge = edgeIt->next() )
4517           if ( ! edges.Add( *edge ))
4518             return true; // an EDGE encounters twice
4519       }
4520     }
4521     return false;
4522   }
4523
4524   //================================================================================
4525   /*!
4526    * \brief Return true if a polyhedron passes _sizeThreshold criterion
4527    */
4528   bool Hexahedron::checkPolyhedronSize( bool cutByInternalFace ) const
4529   {
4530     if ( cutByInternalFace && !_grid->_toUseThresholdForInternalFaces )
4531     {
4532       // check if any polygon fully lies on shared/internal FACEs
4533       for ( size_t iP = 0; iP < _polygons.size(); ++iP )
4534       {
4535         const _Face& polygon = _polygons[iP];
4536         if ( polygon._links.empty() )
4537           continue;
4538         bool allNodesInternal = true;
4539         for ( size_t iL = 0; iL < polygon._links.size() &&  allNodesInternal; ++iL )
4540         {
4541           _Node* n = polygon._links[ iL ].FirstNode();
4542           allNodesInternal = (( n->IsCutByInternal() ) ||
4543                               ( n->_intPoint && _grid->IsAnyShared( n->_intPoint->_faceIDs )));
4544         }
4545         if ( allNodesInternal )
4546           return true;
4547       }
4548     }
4549     if ( this->hasStrangeEdge() )
4550       return true;
4551
4552     double volume = 0;
4553     for ( size_t iP = 0; iP < _polygons.size(); ++iP )
4554     {
4555       const _Face& polygon = _polygons[iP];
4556       if ( polygon._links.empty() )
4557         continue;
4558       gp_XYZ area (0,0,0);
4559       gp_XYZ p1 = polygon._links[ 0 ].FirstNode()->Point().XYZ();
4560       for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
4561       {
4562         gp_XYZ p2 = polygon._links[ iL ].LastNode()->Point().XYZ();
4563         area += p1 ^ p2;
4564         p1 = p2;
4565       }
4566       volume += p1 * area;
4567     }
4568     volume /= 6;
4569
4570     double initVolume = _sideLength[0] * _sideLength[1] * _sideLength[2];
4571
4572     return volume > initVolume / _grid->_sizeThreshold;
4573   }
4574   //================================================================================
4575   /*!
4576    * \brief Tries to create a hexahedron
4577    */
4578   bool Hexahedron::addHexa()
4579   {
4580     int nbQuad = 0, iQuad = -1;
4581     for ( size_t i = 0; i < _polygons.size(); ++i )
4582     {
4583       if ( _polygons[i]._links.empty() )
4584         continue;
4585       if ( _polygons[i]._links.size() != 4 )
4586         return false;
4587       ++nbQuad;
4588       if ( iQuad < 0 )
4589         iQuad = i;
4590     }
4591     if ( nbQuad != 6 )
4592       return false;
4593
4594     _Node* nodes[8];
4595     int nbN = 0;
4596     for ( int iL = 0; iL < 4; ++iL )
4597     {
4598       // a base node
4599       nodes[iL] = _polygons[iQuad]._links[iL].FirstNode();
4600       ++nbN;
4601
4602       // find a top node above the base node
4603       _Link* link = _polygons[iQuad]._links[iL]._link;
4604       if ( !link->_faces[0] || !link->_faces[1] )
4605         return debugDumpLink( link );
4606       // a quadrangle sharing <link> with _polygons[iQuad]
4607       _Face* quad = link->_faces[ bool( link->_faces[0] == & _polygons[iQuad] )];
4608       for ( int i = 0; i < 4; ++i )
4609         if ( quad->_links[i]._link == link )
4610         {
4611           // 1st node of a link opposite to <link> in <quad>
4612           nodes[iL+4] = quad->_links[(i+2)%4].FirstNode();
4613           ++nbN;
4614           break;
4615         }
4616     }
4617     if ( nbN == 8 )
4618       _volumeDefs.Set( &nodes[0], 8 );
4619
4620     return nbN == 8;
4621   }
4622   //================================================================================
4623   /*!
4624    * \brief Tries to create a tetrahedron
4625    */
4626   bool Hexahedron::addTetra()
4627   {
4628     int iTria = -1;
4629     for ( size_t i = 0; i < _polygons.size() && iTria < 0; ++i )
4630       if ( _polygons[i]._links.size() == 3 )
4631         iTria = i;
4632     if ( iTria < 0 )
4633       return false;
4634
4635     _Node* nodes[4];
4636     nodes[0] = _polygons[iTria]._links[0].FirstNode();
4637     nodes[1] = _polygons[iTria]._links[1].FirstNode();
4638     nodes[2] = _polygons[iTria]._links[2].FirstNode();
4639
4640     _Link* link = _polygons[iTria]._links[0]._link;
4641     if ( !link->_faces[0] || !link->_faces[1] )
4642       return debugDumpLink( link );
4643
4644     // a triangle sharing <link> with _polygons[0]
4645     _Face* tria = link->_faces[ bool( link->_faces[0] == & _polygons[iTria] )];
4646     for ( int i = 0; i < 3; ++i )
4647       if ( tria->_links[i]._link == link )
4648       {
4649         nodes[3] = tria->_links[(i+1)%3].LastNode();
4650         _volumeDefs.Set( &nodes[0], 4 );
4651         return true;
4652       }
4653
4654     return false;
4655   }
4656   //================================================================================
4657   /*!
4658    * \brief Tries to create a pentahedron
4659    */
4660   bool Hexahedron::addPenta()
4661   {
4662     // find a base triangular face
4663     int iTri = -1;
4664     for ( int iF = 0; iF < 5 && iTri < 0; ++iF )
4665       if ( _polygons[ iF ]._links.size() == 3 )
4666         iTri = iF;
4667     if ( iTri < 0 ) return false;
4668
4669     // find nodes
4670     _Node* nodes[6];
4671     int nbN = 0;
4672     for ( int iL = 0; iL < 3; ++iL )
4673     {
4674       // a base node
4675       nodes[iL] = _polygons[ iTri ]._links[iL].FirstNode();
4676       ++nbN;
4677
4678       // find a top node above the base node
4679       _Link* link = _polygons[ iTri ]._links[iL]._link;
4680       if ( !link->_faces[0] || !link->_faces[1] )
4681         return debugDumpLink( link );
4682       // a quadrangle sharing <link> with a base triangle
4683       _Face* quad = link->_faces[ bool( link->_faces[0] == & _polygons[ iTri ] )];
4684       if ( quad->_links.size() != 4 ) return false;
4685       for ( int i = 0; i < 4; ++i )
4686         if ( quad->_links[i]._link == link )
4687         {
4688           // 1st node of a link opposite to <link> in <quad>
4689           nodes[iL+3] = quad->_links[(i+2)%4].FirstNode();
4690           ++nbN;
4691           break;
4692         }
4693     }
4694     if ( nbN == 6 )
4695       _volumeDefs.Set( &nodes[0], 6 );
4696
4697     return ( nbN == 6 );
4698   }
4699   //================================================================================
4700   /*!
4701    * \brief Tries to create a pyramid
4702    */
4703   bool Hexahedron::addPyra()
4704   {
4705     // find a base quadrangle
4706     int iQuad = -1;
4707     for ( int iF = 0; iF < 5 && iQuad < 0; ++iF )
4708       if ( _polygons[ iF ]._links.size() == 4 )
4709         iQuad = iF;
4710     if ( iQuad < 0 ) return false;
4711
4712     // find nodes
4713     _Node* nodes[5];
4714     nodes[0] = _polygons[iQuad]._links[0].FirstNode();
4715     nodes[1] = _polygons[iQuad]._links[1].FirstNode();
4716     nodes[2] = _polygons[iQuad]._links[2].FirstNode();
4717     nodes[3] = _polygons[iQuad]._links[3].FirstNode();
4718
4719     _Link* link = _polygons[iQuad]._links[0]._link;
4720     if ( !link->_faces[0] || !link->_faces[1] )
4721       return debugDumpLink( link );
4722
4723     // a triangle sharing <link> with a base quadrangle
4724     _Face* tria = link->_faces[ bool( link->_faces[0] == & _polygons[ iQuad ] )];
4725     if ( tria->_links.size() != 3 ) return false;
4726     for ( int i = 0; i < 3; ++i )
4727       if ( tria->_links[i]._link == link )
4728       {
4729         nodes[4] = tria->_links[(i+1)%3].LastNode();
4730         _volumeDefs.Set( &nodes[0], 5 );
4731         return true;
4732       }
4733
4734     return false;
4735   }
4736   //================================================================================
4737   /*!
4738    * \brief Dump a link and return \c false
4739    */
4740   bool Hexahedron::debugDumpLink( Hexahedron::_Link* link )
4741   {
4742 #ifdef _DEBUG_
4743     gp_Pnt p1 = link->_nodes[0]->Point(), p2 = link->_nodes[1]->Point();
4744     cout << "BUG: not shared link. IKJ = ( "<< _i << " " << _j << " " << _k << " )" << endl
4745          << "n1 (" << p1.X() << ", "<< p1.Y() << ", "<< p1.Z() << " )" << endl
4746          << "n2 (" << p2.X() << ", "<< p2.Y() << ", "<< p2.Z() << " )" << endl;
4747 #endif
4748     return false;
4749   }
4750   //================================================================================
4751   /*!
4752    * \brief Classify a point by grid parameters
4753    */
4754   bool Hexahedron::isOutParam(const double uvw[3]) const
4755   {
4756     return (( _grid->_coords[0][ _i   ] - _grid->_tol > uvw[0] ) ||
4757             ( _grid->_coords[0][ _i+1 ] + _grid->_tol < uvw[0] ) ||
4758             ( _grid->_coords[1][ _j   ] - _grid->_tol > uvw[1] ) ||
4759             ( _grid->_coords[1][ _j+1 ] + _grid->_tol < uvw[1] ) ||
4760             ( _grid->_coords[2][ _k   ] - _grid->_tol > uvw[2] ) ||
4761             ( _grid->_coords[2][ _k+1 ] + _grid->_tol < uvw[2] ));
4762   }
4763   //================================================================================
4764   /*!
4765    * \brief Divide a polygon into triangles and modify accordingly an adjacent polyhedron
4766    */
4767   void splitPolygon( const SMDS_MeshElement*         polygon,
4768                      SMDS_VolumeTool &               volume,
4769                      const int                       facetIndex,
4770                      const TGeomID                   faceID,
4771                      const TGeomID                   solidID,
4772                      SMESH_MeshEditor::ElemFeatures& face,
4773                      SMESH_MeshEditor&               editor,
4774                      const bool                      reinitVolume)
4775   {
4776     SMESH_MeshAlgos::Triangulate divider(/*optimize=*/false);
4777     int nbTrias = divider.GetTriangles( polygon, face.myNodes );
4778     face.myNodes.resize( nbTrias * 3 );
4779
4780     SMESH_MeshEditor::ElemFeatures newVolumeDef;
4781     newVolumeDef.Init( volume.Element() );
4782     newVolumeDef.SetID( volume.Element()->GetID() );
4783
4784     newVolumeDef.myPolyhedQuantities.reserve( volume.NbFaces() + nbTrias );
4785     newVolumeDef.myNodes.reserve( volume.NbNodes() + nbTrias * 3 );
4786
4787     SMESHDS_Mesh* meshDS = editor.GetMeshDS();
4788     SMDS_MeshElement* newTriangle;
4789     for ( int iF = 0, nF = volume.NbFaces(); iF < nF; iF++ )
4790     {
4791       if ( iF == facetIndex )
4792       {
4793         newVolumeDef.myPolyhedQuantities.push_back( 3 );
4794         newVolumeDef.myNodes.insert( newVolumeDef.myNodes.end(),
4795                                      face.myNodes.begin(),
4796                                      face.myNodes.begin() + 3 );
4797         meshDS->RemoveFreeElement( polygon, 0, false );
4798         newTriangle = meshDS->AddFace( face.myNodes[0], face.myNodes[1], face.myNodes[2] );
4799         meshDS->SetMeshElementOnShape( newTriangle, faceID );
4800       }
4801       else
4802       {
4803         const SMDS_MeshNode** nn = volume.GetFaceNodes( iF );
4804         const size_t nbFaceNodes = volume.NbFaceNodes ( iF );
4805         newVolumeDef.myPolyhedQuantities.push_back( nbFaceNodes );
4806         newVolumeDef.myNodes.insert( newVolumeDef.myNodes.end(), nn, nn + nbFaceNodes );
4807       }
4808     }
4809
4810     for ( size_t iN = 3; iN < face.myNodes.size(); iN += 3 )
4811     {
4812       newVolumeDef.myPolyhedQuantities.push_back( 3 );
4813       newVolumeDef.myNodes.insert( newVolumeDef.myNodes.end(),
4814                                    face.myNodes.begin() + iN,
4815                                    face.myNodes.begin() + iN + 3 );
4816       newTriangle = meshDS->AddFace( face.myNodes[iN], face.myNodes[iN+1], face.myNodes[iN+2] );
4817       meshDS->SetMeshElementOnShape( newTriangle, faceID );
4818     }
4819
4820     meshDS->RemoveFreeElement( volume.Element(), 0, false );
4821     SMDS_MeshElement* newVolume = editor.AddElement( newVolumeDef.myNodes, newVolumeDef );
4822     meshDS->SetMeshElementOnShape( newVolume, solidID );
4823
4824     if ( reinitVolume )
4825     {
4826       volume.Set( 0 );
4827       volume.Set( newVolume );
4828     }
4829     return;
4830   }
4831   //================================================================================
4832   /*!
4833    * \brief Create mesh faces at free facets
4834    */
4835   void Hexahedron::addFaces( SMESH_MesherHelper&                       helper,
4836                              const vector< const SMDS_MeshElement* > & boundaryVolumes )
4837   {
4838     if ( !_grid->_toCreateFaces )
4839       return;
4840
4841     SMDS_VolumeTool vTool;
4842     vector<int> bndFacets;
4843     SMESH_MeshEditor editor( helper.GetMesh() );
4844     SMESH_MeshEditor::ElemFeatures face( SMDSAbs_Face );
4845     SMESHDS_Mesh* meshDS = helper.GetMeshDS();
4846
4847     // check if there are internal or shared FACEs
4848     bool hasInternal = ( !_grid->_geometry.IsOneSolid() ||
4849                          _grid->_geometry._soleSolid.HasInternalFaces() );
4850
4851     for ( size_t iV = 0; iV < boundaryVolumes.size(); ++iV )
4852     {
4853       if ( !vTool.Set( boundaryVolumes[ iV ]))
4854         continue;
4855
4856       TGeomID solidID = vTool.Element()->GetShapeID();
4857       Solid *   solid = _grid->GetOneOfSolids( solidID );
4858
4859       // find boundary facets
4860
4861       bndFacets.clear();
4862       for ( int iF = 0, n = vTool.NbFaces(); iF < n; iF++ )
4863       {
4864         bool isBoundary = vTool.IsFreeFace( iF );
4865         if ( isBoundary )
4866         {
4867           bndFacets.push_back( iF );
4868         }
4869         else if ( hasInternal )
4870         {
4871           // check if all nodes are on internal/shared FACEs
4872           isBoundary = true;
4873           const SMDS_MeshNode** nn = vTool.GetFaceNodes( iF );
4874           const size_t nbFaceNodes = vTool.NbFaceNodes ( iF );
4875           for ( size_t iN = 0; iN < nbFaceNodes &&  isBoundary; ++iN )
4876             isBoundary = ( nn[ iN ]->GetShapeID() != solidID );
4877           if ( isBoundary )
4878             bndFacets.push_back( -( iF+1 )); // !!! minus ==> to check the FACE
4879         }
4880       }
4881       if ( bndFacets.empty() )
4882         continue;
4883
4884       // create faces
4885
4886       if ( !vTool.IsPoly() )
4887         vTool.SetExternalNormal();
4888       for ( size_t i = 0; i < bndFacets.size(); ++i ) // loop on boundary facets
4889       {
4890         const bool    isBoundary = ( bndFacets[i] >= 0 );
4891         const int         iFacet = isBoundary ? bndFacets[i] : -bndFacets[i]-1;
4892         const SMDS_MeshNode** nn = vTool.GetFaceNodes( iFacet );
4893         const size_t nbFaceNodes = vTool.NbFaceNodes ( iFacet );
4894         face.myNodes.assign( nn, nn + nbFaceNodes );
4895
4896         TGeomID faceID = 0;
4897         const SMDS_MeshElement* existFace = 0, *newFace = 0;
4898
4899         if (( existFace = meshDS->FindElement( face.myNodes, SMDSAbs_Face )))
4900         {
4901           if ( existFace->isMarked() )
4902             continue; // created by this method
4903           faceID = existFace->GetShapeID();
4904         }
4905         else
4906         {
4907           // look for a supporting FACE
4908           for ( size_t iN = 0; iN < nbFaceNodes &&  !faceID; ++iN ) // look for a node on FACE
4909           {
4910             if ( nn[ iN ]->GetPosition()->GetDim() == 2 )
4911               faceID = nn[ iN ]->GetShapeID();
4912           }
4913           for ( size_t iN = 0; iN < nbFaceNodes &&  !faceID; ++iN )
4914           {
4915             // look for a father FACE of EDGEs and VERTEXes
4916             const TopoDS_Shape& s1 = _grid->Shape( nn[ iN   ]->GetShapeID() );
4917             const TopoDS_Shape& s2 = _grid->Shape( nn[ iN+1 ]->GetShapeID() );
4918             if ( s1 != s2 && s1.ShapeType() == TopAbs_EDGE && s2.ShapeType() == TopAbs_EDGE )
4919             {
4920               TopoDS_Shape f = helper.GetCommonAncestor( s1, s2, *helper.GetMesh(), TopAbs_FACE );
4921               if ( !f.IsNull() )
4922                 faceID = _grid->ShapeID( f );
4923             }
4924           }
4925
4926           bool toCheckFace = faceID && (( !isBoundary ) ||
4927                                         ( hasInternal && _grid->_toUseThresholdForInternalFaces ));
4928           if ( toCheckFace ) // check if all nodes are on the found FACE
4929           {
4930             SMESH_subMesh* faceSM = helper.GetMesh()->GetSubMeshContaining( faceID );
4931             for ( size_t iN = 0; iN < nbFaceNodes &&  faceID; ++iN )
4932             {
4933               TGeomID subID = nn[ iN ]->GetShapeID();
4934               if ( subID != faceID && !faceSM->DependsOn( subID ))
4935                 faceID = 0;
4936             }
4937             if ( !faceID && !isBoundary )
4938               continue;
4939           }
4940         }
4941         // orient a new face according to supporting FACE orientation in shape_to_mesh
4942         if ( !solid->IsOutsideOriented( faceID ))
4943         {
4944           if ( existFace )
4945             editor.Reorient( existFace );
4946           else
4947             std::reverse( face.myNodes.begin(), face.myNodes.end() );
4948         }
4949
4950         if ( ! ( newFace = existFace ))
4951         {
4952           face.SetPoly( nbFaceNodes > 4 );
4953           newFace = editor.AddElement( face.myNodes, face );
4954           if ( !newFace )
4955             continue;
4956           newFace->setIsMarked( true ); // to distinguish from face created in getBoundaryElems()
4957         }
4958
4959         if ( faceID && _grid->IsBoundaryFace( faceID )) // face is not shared
4960         {
4961           // set newFace to the found FACE provided that it fully lies on the FACE
4962           for ( size_t iN = 0; iN < nbFaceNodes &&  faceID; ++iN )
4963             if ( nn[iN]->GetShapeID() == solidID )
4964             {
4965               if ( existFace )
4966                 meshDS->UnSetMeshElementOnShape( existFace, _grid->Shape( faceID ));
4967               faceID = 0;
4968             }
4969         }
4970
4971         // split a polygon that will be used by other 3D algorithm
4972         if ( faceID && nbFaceNodes > 4 &&
4973              !_grid->IsInternal( faceID ) &&
4974              !_grid->IsShared( faceID ) &&
4975              !_grid->IsBoundaryFace( faceID ))
4976         {
4977           splitPolygon( newFace, vTool, iFacet, faceID, solidID,
4978                         face, editor, i+1 < bndFacets.size() );
4979         }
4980         else
4981         {
4982           if ( faceID )
4983             meshDS->SetMeshElementOnShape( newFace, faceID );
4984           else
4985             meshDS->SetMeshElementOnShape( newFace, solidID );
4986         }
4987       } // loop on bndFacets
4988     } // loop on boundaryVolumes
4989
4990
4991     // Orient coherently mesh faces on INTERNAL FACEs
4992
4993     if ( hasInternal )
4994     {
4995       TopExp_Explorer faceExp( _grid->_geometry._mainShape, TopAbs_FACE );
4996       for ( ; faceExp.More(); faceExp.Next() )
4997       {
4998         if ( faceExp.Current().Orientation() != TopAbs_INTERNAL )
4999           continue;
5000
5001         SMESHDS_SubMesh* sm = meshDS->MeshElements( faceExp.Current() );
5002         if ( !sm ) continue;
5003
5004         TIDSortedElemSet facesToOrient;
5005         for ( SMDS_ElemIteratorPtr fIt = sm->GetElements(); fIt->more(); )
5006           facesToOrient.insert( facesToOrient.end(), fIt->next() );
5007         if ( facesToOrient.size() < 2 )
5008           continue;
5009
5010         gp_Dir direction(1,0,0);
5011         const SMDS_MeshElement* anyFace = *facesToOrient.begin();
5012         editor.Reorient2D( facesToOrient, direction, anyFace );
5013       }
5014     }
5015     return;
5016   }
5017
5018   //================================================================================
5019   /*!
5020    * \brief Create mesh segments.
5021    */
5022   void Hexahedron::addSegments( SMESH_MesherHelper&                      helper,
5023                                 const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap )
5024   {
5025     SMESHDS_Mesh* mesh = helper.GetMeshDS();
5026
5027     std::vector<const SMDS_MeshNode*> nodes;
5028     std::vector<const SMDS_MeshElement *> elems;
5029     map< TGeomID, vector< TGeomID > >::const_iterator e2ff = edge2faceIDsMap.begin();
5030     for ( ; e2ff != edge2faceIDsMap.end(); ++e2ff )
5031     {
5032       const TopoDS_Edge& edge = TopoDS::Edge( _grid->Shape( e2ff->first ));
5033       const TopoDS_Face& face = TopoDS::Face( _grid->Shape( e2ff->second[0] ));
5034       StdMeshers_FaceSide side( face, edge, helper.GetMesh(), /*isFwd=*/true, /*skipMed=*/true );
5035       nodes = side.GetOrderedNodes();
5036
5037       elems.clear();
5038       if ( nodes.size() == 2 )
5039         // check that there is an element connecting two nodes
5040         if ( !mesh->GetElementsByNodes( nodes, elems ))
5041           continue;
5042
5043       for ( size_t i = 1; i < nodes.size(); i++ )
5044       {
5045         SMDS_MeshElement* segment = mesh->AddEdge( nodes[i-1], nodes[i] );
5046         mesh->SetMeshElementOnShape( segment, e2ff->first );
5047       }
5048     }
5049     return;
5050   }
5051
5052   //================================================================================
5053   /*!
5054    * \brief Return created volumes and volumes that can have free facet because of
5055    *        skipped small volume. Also create mesh faces on free facets
5056    *        of adjacent not-cut volumes if the result volume is too small.
5057    */
5058   void Hexahedron::getBoundaryElems( vector< const SMDS_MeshElement* > & boundaryElems )
5059   {
5060     if ( _hasTooSmall /*|| _volumeDefs.IsEmpty()*/ )
5061     {
5062       // create faces around a missing small volume
5063       TGeomID faceID = 0;
5064       SMESH_MeshEditor editor( _grid->_helper->GetMesh() );
5065       SMESH_MeshEditor::ElemFeatures polygon( SMDSAbs_Face );
5066       SMESHDS_Mesh* meshDS = _grid->_helper->GetMeshDS();
5067       std::vector<const SMDS_MeshElement *> adjVolumes(2);
5068       for ( size_t iF = 0; iF < _polygons.size(); ++iF )
5069       {
5070         const size_t nbLinks = _polygons[ iF ]._links.size();
5071         if ( nbLinks != 4 ) continue;
5072         polygon.myNodes.resize( nbLinks );
5073         polygon.myNodes.back() = 0;
5074         for ( size_t iL = 0, iN = nbLinks - 1; iL < nbLinks; ++iL, --iN )
5075           if ( ! ( polygon.myNodes[iN] = _polygons[ iF ]._links[ iL ].FirstNode()->Node() ))
5076             break;
5077         if ( !polygon.myNodes.back() )
5078           continue;
5079
5080         meshDS->GetElementsByNodes( polygon.myNodes, adjVolumes, SMDSAbs_Volume );
5081         if ( adjVolumes.size() != 1 )
5082           continue;
5083         if ( !adjVolumes[0]->isMarked() )
5084         {
5085           boundaryElems.push_back( adjVolumes[0] );
5086           adjVolumes[0]->setIsMarked( true );
5087         }
5088
5089         bool sameShape = true;
5090         TGeomID shapeID = polygon.myNodes[0]->GetShapeID();
5091         for ( size_t i = 1; i < polygon.myNodes.size() && sameShape; ++i )
5092           sameShape = ( shapeID == polygon.myNodes[i]->GetShapeID() );
5093
5094         if ( !sameShape || !_grid->IsSolid( shapeID ))
5095           continue; // some of shapes must be FACE
5096
5097         if ( !faceID )
5098         {
5099           faceID = getAnyFace();
5100           if ( !faceID )
5101             break;
5102           if ( _grid->IsInternal( faceID ) ||
5103                _grid->IsShared( faceID ) //||
5104                //_grid->IsBoundaryFace( faceID ) -- commented for #19887
5105                ) 
5106             break; // create only if a new face will be used by other 3D algo
5107         }
5108
5109         Solid * solid = _grid->GetOneOfSolids( adjVolumes[0]->GetShapeID() );
5110         if ( !solid->IsOutsideOriented( faceID ))
5111           std::reverse( polygon.myNodes.begin(), polygon.myNodes.end() );
5112
5113         //polygon.SetPoly( polygon.myNodes.size() > 4 );
5114         const SMDS_MeshElement* newFace = editor.AddElement( polygon.myNodes, polygon );
5115         meshDS->SetMeshElementOnShape( newFace, faceID );
5116       }
5117     }
5118
5119     // return created volumes
5120     for ( _volumeDef* volDef = &_volumeDefs; volDef; volDef = volDef->_next )
5121     {
5122       if ( volDef->_volume && !volDef->_volume->isMarked() )
5123       {
5124         volDef->_volume->setIsMarked( true );
5125         boundaryElems.push_back( volDef->_volume );
5126
5127         if ( _grid->IsToCheckNodePos() ) // un-mark nodes marked in addVolumes()
5128           for ( size_t iN = 0; iN < volDef->_nodes.size(); ++iN )
5129             volDef->_nodes[iN].Node()->setIsMarked( false );
5130       }
5131     }
5132   }
5133
5134   //================================================================================
5135   /*!
5136    * \brief Remove edges and nodes dividing a hexa side in the case if an adjacent
5137    *        volume also sharing the dividing edge is missing due to its small side.
5138    *        Issue #19887.
5139    */
5140   //================================================================================
5141
5142   void Hexahedron::removeExcessSideDivision(const vector< Hexahedron* >& allHexa)
5143   {
5144     if ( ! _volumeDefs.IsPolyhedron() )
5145       return; // not a polyhedron
5146       
5147     // look for a divided side adjacent to a small hexahedron
5148
5149     int di[6] = { 0, 0, 0, 0,-1, 1 };
5150     int dj[6] = { 0, 0,-1, 1, 0, 0 };
5151     int dk[6] = {-1, 1, 0, 0, 0, 0 };
5152
5153     for ( int iF = 0; iF < 6; ++iF ) // loop on 6 sides of a hexahedron
5154     {
5155       size_t neighborIndex = _grid->CellIndex( _i + di[iF],
5156                                                _j + dj[iF],
5157                                                _k + dk[iF] );
5158       if ( neighborIndex >= allHexa.size() ||
5159            !allHexa[ neighborIndex ]       ||
5160            !allHexa[ neighborIndex ]->_hasTooSmall )
5161         continue;
5162
5163       // check if a side is divided into several polygons
5164       for ( _volumeDef* volDef = &_volumeDefs; volDef; volDef = volDef->_next )
5165       {
5166         int nbPolygons = 0, nbNodes = 0;
5167         for ( size_t i = 0; i < volDef->_names.size(); ++i )
5168           if ( volDef->_names[ i ] == _hexQuads[ iF ]._name )
5169           {
5170             ++nbPolygons;
5171             nbNodes += volDef->_quantities[ i ];
5172           }
5173         if ( nbPolygons < 2 )
5174           continue;
5175
5176         // construct loops from polygons
5177         typedef _volumeDef::_linkDef TLinkDef;
5178         std::vector< TLinkDef* > loops;
5179         std::vector< TLinkDef > links( nbNodes );
5180         for ( size_t i = 0, iN = 0, iLoop = 0; iLoop < volDef->_quantities.size(); ++iLoop )
5181         {
5182           size_t nbLinks = volDef->_quantities[ iLoop ];
5183           if ( volDef->_names[ iLoop ] != _hexQuads[ iF ]._name )
5184           {
5185             iN += nbLinks;
5186             continue;
5187           }
5188           loops.push_back( & links[i] );
5189           for ( size_t n = 0; n < nbLinks-1; ++n, ++i, ++iN )
5190           {
5191             links[i].init( volDef->_nodes[iN], volDef->_nodes[iN+1], iLoop );
5192             links[i].setNext( &links[i+1] );
5193           }
5194           links[i].init( volDef->_nodes[iN], volDef->_nodes[iN-nbLinks+1], iLoop );
5195           links[i].setNext( &links[i-nbLinks+1] );
5196           ++i; ++iN;
5197         }
5198
5199         // look for equal links in different loops and join such loops
5200         bool loopsJoined = false;
5201         std::set< TLinkDef > linkSet;
5202         for ( size_t iLoop = 0; iLoop < loops.size(); ++iLoop )
5203         {
5204           TLinkDef* beg = 0;
5205           for ( TLinkDef* l = loops[ iLoop ]; l != beg; l = l->_next ) // walk around the iLoop
5206           {
5207             std::pair< std::set< TLinkDef >::iterator, bool > it2new = linkSet.insert( *l );
5208             if ( !it2new.second ) // equal found, join loops
5209             {
5210               const TLinkDef* equal = &(*it2new.first);
5211               if ( equal->_loopIndex == l->_loopIndex )
5212                 continue; // error?
5213
5214               loopsJoined = true;
5215
5216               for ( size_t i = iLoop - 1; i < loops.size(); --i )
5217                 if ( loops[ i ] && loops[ i ]->_loopIndex == equal->_loopIndex )
5218                   loops[ i ] = 0;
5219
5220               // exclude l and equal and join two loops
5221               if ( l->_prev != equal )
5222                 l->_prev->setNext( equal->_next );
5223               if ( equal->_prev != l )
5224                 equal->_prev->setNext( l->_next );
5225
5226               if ( volDef->_quantities[ l->_loopIndex ] > 0 )
5227                 volDef->_quantities[ l->_loopIndex     ] *= -1;
5228               if ( volDef->_quantities[ equal->_loopIndex ] > 0 )
5229                 volDef->_quantities[ equal->_loopIndex ] *= -1;
5230
5231               if ( loops[ iLoop ] == l )
5232                 loops[ iLoop ] = l->_prev->_next;
5233             }
5234             beg = loops[ iLoop ];
5235           }
5236         }
5237         // update volDef
5238         if ( loopsJoined )
5239         {
5240           // set unchanged polygons
5241           std::vector< int >                  newQuantities;
5242           std::vector< _volumeDef::_nodeDef > newNodes;
5243           vector< SMESH_Block::TShapeID >     newNames;
5244           newQuantities.reserve( volDef->_quantities.size() );
5245           newNodes.reserve     ( volDef->_nodes.size() );
5246           newNames.reserve     ( volDef->_names.size() );
5247           for ( size_t i = 0, iLoop = 0; iLoop < volDef->_quantities.size(); ++iLoop )
5248           {
5249             if ( volDef->_quantities[ iLoop ] < 0 )
5250             {
5251               i -= volDef->_quantities[ iLoop ];
5252               continue;
5253             }
5254             newQuantities.push_back( volDef->_quantities[ iLoop ]);
5255             newNodes.insert( newNodes.end(),
5256                              volDef->_nodes.begin() + i,
5257                              volDef->_nodes.begin() + i + newQuantities.back() );
5258             newNames.push_back( volDef->_names[ iLoop ]);
5259             i += volDef->_quantities[ iLoop ];
5260           }
5261
5262           // set joined loops
5263           for ( size_t iLoop = 0; iLoop < loops.size(); ++iLoop )
5264           {
5265             if ( !loops[ iLoop ] )
5266               continue;
5267             newQuantities.push_back( 0 );
5268             TLinkDef* beg = 0;
5269             for ( TLinkDef* l = loops[ iLoop ]; l != beg; l = l->_next, ++newQuantities.back() )
5270             {
5271               newNodes.push_back( l->_node1 );
5272               beg = loops[ iLoop ];
5273             }
5274             newNames.push_back( _hexQuads[ iF ]._name );
5275           }
5276           volDef->_quantities.swap( newQuantities );
5277           volDef->_nodes.swap( newNodes );
5278           volDef->_names.swap( newNames );
5279         }
5280       } // loop on volDef's
5281     } // loop on hex sides
5282
5283     return;
5284   } // removeExcessSideDivision()
5285
5286
5287   //================================================================================
5288   /*!
5289    * \brief Remove nodes splitting Cartesian cell edges in the case if a node
5290    *        is used in every cells only by two polygons sharing the edge
5291    *        Issue #19887.
5292    */
5293   //================================================================================
5294
5295   void Hexahedron::removeExcessNodes(vector< Hexahedron* >& allHexa)
5296   {
5297     if ( ! _volumeDefs.IsPolyhedron() )
5298       return; // not a polyhedron
5299
5300     typedef vector< _volumeDef::_nodeDef >::iterator TNodeIt;
5301     vector< int > nodesInPoly[ 4 ]; // node index in _volumeDefs._nodes
5302     vector< int > volDefInd  [ 4 ]; // index of a _volumeDefs
5303     Hexahedron*   hexa       [ 4 ];
5304     int i,j,k, cellIndex, iLink = 0, iCellLink;
5305     for ( int iDir = 0; iDir < 3; ++iDir )
5306     {
5307       CellsAroundLink fourCells( _grid, iDir );
5308       for ( int iL = 0; iL < 4; ++iL, ++iLink ) // 4 links in a direction
5309       {
5310         _Link& link = _hexLinks[ iLink ];
5311         fourCells.Init( _i, _j, _k, iLink );
5312
5313         for ( size_t iP = 0; iP < link._fIntPoints.size(); ++iP ) // loop on nodes on the link
5314         {
5315           bool nodeRemoved = true;
5316           _volumeDef::_nodeDef node; node._intPoint = link._fIntPoints[iP];
5317
5318           for ( size_t i = 0, nb = _volumeDefs.size(); i < nb &&  nodeRemoved; ++i )
5319             if ( _volumeDef* vol = _volumeDefs.at( i ))
5320               nodeRemoved =
5321                 ( std::find( vol->_nodes.begin(), vol->_nodes.end(), node ) == vol->_nodes.end() );
5322           if ( nodeRemoved )
5323             continue; // node already removed
5324
5325           // check if a node encounters zero or two times in 4 cells sharing iLink
5326           // if so, the node can be removed from the cells
5327           bool       nodeIsOnEdge = true;
5328           int nbPolyhedraWithNode = 0;
5329           for ( int iC = 0; iC < 4; ++iC ) // loop on 4 cells sharing a link
5330           {
5331             nodesInPoly[ iC ].clear();
5332             volDefInd  [ iC ].clear();
5333             hexa       [ iC ] = 0;
5334             if ( !fourCells.GetCell( iC, i,j,k, cellIndex, iCellLink ))
5335               continue;
5336             hexa[ iC ] = allHexa[ cellIndex ];
5337             if ( !hexa[ iC ])
5338               continue;
5339             for ( size_t i = 0, nb = hexa[ iC ]->_volumeDefs.size(); i < nb; ++i )
5340               if ( _volumeDef* vol = hexa[ iC ]->_volumeDefs.at( i ))
5341               {
5342                 for ( TNodeIt nIt = vol->_nodes.begin(); nIt != vol->_nodes.end(); ++nIt )
5343                 {
5344                   nIt = std::find( nIt, vol->_nodes.end(), node );
5345                   if ( nIt != vol->_nodes.end() )
5346                   {
5347                     nodesInPoly[ iC ].push_back( std::distance( vol->_nodes.begin(), nIt ));
5348                     volDefInd  [ iC ].push_back( i );
5349                   }
5350                   else
5351                     break;
5352                 }
5353                 nbPolyhedraWithNode += ( !nodesInPoly[ iC ].empty() );
5354               }
5355             if ( nodesInPoly[ iC ].size() != 0 &&
5356                  nodesInPoly[ iC ].size() != 2 )
5357             {
5358               nodeIsOnEdge = false;
5359               break;
5360             }
5361           } // loop  on 4 cells
5362
5363           // remove nodes from polyhedra
5364           if ( nbPolyhedraWithNode > 0 && nodeIsOnEdge )
5365           {
5366             for ( int iC = 0; iC < 4; ++iC ) // loop on 4 cells sharing the link
5367             {
5368               if ( nodesInPoly[ iC ].empty() )
5369                 continue;
5370               for ( int i = volDefInd[ iC ].size() - 1; i >= 0; --i )
5371               {
5372                 _volumeDef* vol = hexa[ iC ]->_volumeDefs.at( volDefInd[ iC ][ i ]);
5373                 int nIndex = nodesInPoly[ iC ][ i ];
5374                 // decrement _quantities
5375                 for ( size_t iQ = 0; iQ < vol->_quantities.size(); ++iQ )
5376                   if ( nIndex < vol->_quantities[ iQ ])
5377                   {
5378                     vol->_quantities[ iQ ]--;
5379                     break;
5380                   }
5381                   else
5382                   {
5383                     nIndex -= vol->_quantities[ iQ ];
5384                   }
5385                 vol->_nodes.erase( vol->_nodes.begin() + nodesInPoly[ iC ][ i ]);
5386
5387                 if ( i == 0 &&
5388                      vol->_nodes.size() == 6 * 4 &&
5389                      vol->_quantities.size() == 6 ) // polyhedron becomes hexahedron?
5390                 {
5391                   bool allQuads = true;
5392                   for ( size_t iQ = 0; iQ < vol->_quantities.size() &&  allQuads; ++iQ )
5393                     allQuads = ( vol->_quantities[ iQ ] == 4 );
5394                   if ( allQuads )
5395                   {
5396                     // set side nodes as this: bottom, top, top, ...
5397                     int iTop, iBot; // side indices
5398                     for ( int iS = 0; iS < 6; ++iS )
5399                     {
5400                       if ( vol->_names[ iS ] == SMESH_Block::ID_Fxy0 )
5401                         iBot = iS;
5402                       if ( vol->_names[ iS ] == SMESH_Block::ID_Fxy1 )
5403                         iTop = iS;
5404                     }
5405                     if ( iBot != 0 )
5406                     {
5407                       if ( iTop == 0 )
5408                       {
5409                         std::copy( vol->_nodes.begin(),
5410                                    vol->_nodes.begin() + 4,
5411                                    vol->_nodes.begin() + 4 );
5412                         iTop = 1;
5413                       }
5414                       std::copy( vol->_nodes.begin() + 4 * iBot,
5415                                  vol->_nodes.begin() + 4 * ( iBot + 1),
5416                                  vol->_nodes.begin() );
5417                     }
5418                     if ( iTop != 1 )
5419                       std::copy( vol->_nodes.begin() + 4 * iTop,
5420                                  vol->_nodes.begin() + 4 * ( iTop + 1),
5421                                  vol->_nodes.begin() + 4 );
5422
5423                     std::copy( vol->_nodes.begin() + 4,
5424                                vol->_nodes.begin() + 8,
5425                                vol->_nodes.begin() + 8 );
5426                     // set up top facet nodes by comparing their uvw with bottom nodes
5427                     E_IntersectPoint ip[8];
5428                     for ( int iN = 0; iN < 8; ++iN )
5429                     {
5430                       SMESH_NodeXYZ p = vol->_nodes[ iN ].Node();
5431                       _grid->ComputeUVW( p, ip[ iN ]._uvw );
5432                     }
5433                     const double tol2 = _grid->_tol * _grid->_tol;
5434                     for ( int iN = 0; iN < 4; ++iN )
5435                     {
5436                       gp_Pnt2d pBot( ip[ iN ]._uvw[0], ip[ iN ]._uvw[1] );
5437                       for ( int iT = 4; iT < 8; ++iT )
5438                       {
5439                         gp_Pnt2d pTop( ip[ iT ]._uvw[0], ip[ iT ]._uvw[1] );
5440                         if ( pBot.SquareDistance( pTop ) < tol2 )
5441                         {
5442                           // vol->_nodes[ iN + 4 ]._node = ip[ iT ]._node;
5443                           // vol->_nodes[ iN + 4 ]._intPoint = 0;
5444                           vol->_nodes[ iN + 4 ] = vol->_nodes[ iT + 4 ];
5445                           break;
5446                         }
5447                       }
5448                     }
5449                     vol->_nodes.resize( 8 );
5450                     vol->_quantities.clear();
5451                     //vol->_names.clear();
5452                   }
5453                 }
5454               } // loop on _volumeDefs
5455             } // loop on 4 cell abound a link
5456           } // if ( nodeIsOnEdge )
5457         } // loop on intersection points of a link
5458       } // loop on 4 links of a direction
5459     } // loop on 3 directions
5460
5461     return;
5462
5463   } // removeExcessNodes()
5464
5465   //================================================================================
5466   /*!
5467    * \brief Set to _hexLinks a next portion of splits located on one side of INTERNAL FACEs
5468    */
5469   bool Hexahedron::_SplitIterator::Next()
5470   {
5471     if ( _iterationNb > 0 )
5472       // count used splits
5473       for ( size_t i = 0; i < _splits.size(); ++i )
5474       {
5475         if ( _splits[i]._iCheckIteration == _iterationNb )
5476         {
5477           _splits[i]._isUsed = _splits[i]._checkedSplit->_faces[1];
5478           _nbUsed += _splits[i]._isUsed;
5479         }
5480         if ( !More() )
5481           return false;
5482       }
5483
5484     ++_iterationNb;
5485
5486     bool toTestUsed = ( _nbChecked >= _splits.size() );
5487     if ( toTestUsed )
5488     {
5489       // all splits are checked; find all not used splits
5490       for ( size_t i = 0; i < _splits.size(); ++i )
5491         if ( !_splits[i].IsCheckedOrUsed( toTestUsed ))
5492           _splits[i]._iCheckIteration = _iterationNb;
5493
5494       _nbUsed = _splits.size(); // to stop iteration
5495     }
5496     else
5497     {
5498       // get any not used/checked split to start from
5499       _freeNodes.clear();
5500       for ( size_t i = 0; i < _splits.size(); ++i )
5501       {
5502         if ( !_splits[i].IsCheckedOrUsed( toTestUsed ))
5503         {
5504           _freeNodes.push_back( _splits[i]._nodes[0] );
5505           _freeNodes.push_back( _splits[i]._nodes[1] );
5506           _splits[i]._iCheckIteration = _iterationNb;
5507           break;
5508         }
5509       }
5510       // find splits connected to the start one via _freeNodes
5511       for ( size_t iN = 0; iN < _freeNodes.size(); ++iN )
5512       {
5513         for ( size_t iS = 0; iS < _splits.size(); ++iS )
5514         {
5515           if ( _splits[iS].IsCheckedOrUsed( toTestUsed ))
5516             continue;
5517           int iN2 = -1;
5518           if (      _freeNodes[iN] == _splits[iS]._nodes[0] )
5519             iN2 = 1;
5520           else if ( _freeNodes[iN] == _splits[iS]._nodes[1] )
5521             iN2 = 0;
5522           else
5523             continue;
5524           if ( _freeNodes[iN]->_isInternalFlags > 0 )
5525           {
5526             if ( _splits[iS]._nodes[ iN2 ]->_isInternalFlags == 0 )
5527               continue;
5528             if ( !_splits[iS]._nodes[ iN2 ]->IsLinked( _freeNodes[iN]->_intPoint ))
5529               continue;
5530           }
5531           _splits[iS]._iCheckIteration = _iterationNb;
5532           _freeNodes.push_back( _splits[iS]._nodes[ iN2 ]);
5533         }
5534       }
5535     }
5536     // set splits to hex links
5537
5538     for ( int iL = 0; iL < 12; ++iL )
5539       _hexLinks[ iL ]._splits.clear();
5540
5541     _Link split;
5542     for ( size_t i = 0; i < _splits.size(); ++i )
5543     {
5544       if ( _splits[i]._iCheckIteration == _iterationNb )
5545       {
5546         split._nodes[0] = _splits[i]._nodes[0];
5547         split._nodes[1] = _splits[i]._nodes[1];
5548         _Link & hexLink = _hexLinks[ _splits[i]._linkID ];
5549         hexLink._splits.push_back( split );
5550         _splits[i]._checkedSplit = & hexLink._splits.back();
5551         ++_nbChecked;
5552       }
5553     }
5554     return More();
5555   }
5556
5557   //================================================================================
5558   /*!
5559    * \brief computes exact bounding box with axes parallel to given ones
5560    */
5561   //================================================================================
5562
5563   void getExactBndBox( const vector< TopoDS_Shape >& faceVec,
5564                        const double*                 axesDirs,
5565                        Bnd_Box&                      shapeBox )
5566   {
5567     BRep_Builder b;
5568     TopoDS_Compound allFacesComp;
5569     b.MakeCompound( allFacesComp );
5570     for ( size_t iF = 0; iF < faceVec.size(); ++iF )
5571       b.Add( allFacesComp, faceVec[ iF ] );
5572
5573     double sP[6]; // aXmin, aYmin, aZmin, aXmax, aYmax, aZmax
5574     shapeBox.Get(sP[0],sP[1],sP[2],sP[3],sP[4],sP[5]);
5575     double farDist = 0;
5576     for ( int i = 0; i < 6; ++i )
5577       farDist = Max( farDist, 10 * sP[i] );
5578
5579     gp_XYZ axis[3] = { gp_XYZ( axesDirs[0], axesDirs[1], axesDirs[2] ),
5580                        gp_XYZ( axesDirs[3], axesDirs[4], axesDirs[5] ),
5581                        gp_XYZ( axesDirs[6], axesDirs[7], axesDirs[8] ) };
5582     axis[0].Normalize();
5583     axis[1].Normalize();
5584     axis[2].Normalize();
5585
5586     gp_Mat basis( axis[0], axis[1], axis[2] );
5587     gp_Mat bi = basis.Inverted();
5588
5589     gp_Pnt pMin, pMax;
5590     for ( int iDir = 0; iDir < 3; ++iDir )
5591     {
5592       gp_XYZ axis0 = axis[ iDir ];
5593       gp_XYZ axis1 = axis[ ( iDir + 1 ) % 3 ];
5594       gp_XYZ axis2 = axis[ ( iDir + 2 ) % 3 ];
5595       for ( int isMax = 0; isMax < 2; ++isMax )
5596       {
5597         double shift = isMax ? farDist : -farDist;
5598         gp_XYZ orig = shift * axis0;
5599         gp_XYZ norm = axis1 ^ axis2;
5600         gp_Pln pln( orig, norm );
5601         norm = pln.Axis().Direction().XYZ();
5602         BRepBuilderAPI_MakeFace plane( pln, -farDist, farDist, -farDist, farDist );
5603
5604         gp_Pnt& pAxis = isMax ? pMax : pMin;
5605         gp_Pnt pPlane, pFaces;
5606         double dist = GEOMUtils::GetMinDistance( plane, allFacesComp, pPlane, pFaces );
5607         if ( dist < 0 )
5608         {
5609           Bnd_B3d bb;
5610           gp_XYZ corner;
5611           for ( int i = 0; i < 2; ++i ) {
5612             corner.SetCoord( 1, sP[ i*3 ]);
5613             for ( int j = 0; j < 2; ++j ) {
5614               corner.SetCoord( 2, sP[ i*3 + 1 ]);
5615               for ( int k = 0; k < 2; ++k )
5616               {
5617                 corner.SetCoord( 3, sP[ i*3 + 2 ]);
5618                 corner *= bi;
5619                 bb.Add( corner );
5620               }
5621             }
5622           }
5623           corner = isMax ? bb.CornerMax() : bb.CornerMin();
5624           pAxis.SetCoord( iDir+1, corner.Coord( iDir+1 ));
5625         }
5626         else
5627         {
5628           gp_XYZ pf = pFaces.XYZ() * bi;
5629           pAxis.SetCoord( iDir+1, pf.Coord( iDir+1 ) );
5630         }
5631       }
5632     } // loop on 3 axes
5633
5634     shapeBox.SetVoid();
5635     shapeBox.Add( pMin );
5636     shapeBox.Add( pMax );
5637
5638     return;
5639   }
5640
5641 } // namespace
5642
5643 //=============================================================================
5644 /*!
5645  * \brief Generates 3D structured Cartesian mesh in the internal part of
5646  * solid shapes and polyhedral volumes near the shape boundary.
5647  *  \param theMesh - mesh to fill in
5648  *  \param theShape - a compound of all SOLIDs to mesh
5649  *  \retval bool - true in case of success
5650  */
5651 //=============================================================================
5652
5653 bool StdMeshers_Cartesian_3D::Compute(SMESH_Mesh &         theMesh,
5654                                       const TopoDS_Shape & theShape)
5655 {
5656   // The algorithm generates the mesh in following steps:
5657
5658   // 1) Intersection of grid lines with the geometry boundary.
5659   // This step allows to find out if a given node of the initial grid is
5660   // inside or outside the geometry.
5661
5662   // 2) For each cell of the grid, check how many of it's nodes are outside
5663   // of the geometry boundary. Depending on a result of this check
5664   // - skip a cell, if all it's nodes are outside
5665   // - skip a cell, if it is too small according to the size threshold
5666   // - add a hexahedron in the mesh, if all nodes are inside
5667   // - add a polyhedron in the mesh, if some nodes are inside and some outside
5668
5669   _computeCanceled = false;
5670
5671   SMESH_MesherHelper helper( theMesh );
5672   SMESHDS_Mesh* meshDS = theMesh.GetMeshDS();
5673
5674   try
5675   {
5676     Grid grid;
5677     grid._helper                         = &helper;
5678     grid._toAddEdges                     = _hyp->GetToAddEdges();
5679     grid._toCreateFaces                  = _hyp->GetToCreateFaces();
5680     grid._toConsiderInternalFaces        = _hyp->GetToConsiderInternalFaces();
5681     grid._toUseThresholdForInternalFaces = _hyp->GetToUseThresholdForInternalFaces();
5682     grid._sizeThreshold                  = _hyp->GetSizeThreshold();
5683     grid.InitGeometry( theShape );
5684
5685     vector< TopoDS_Shape > faceVec;
5686     {
5687       TopTools_MapOfShape faceMap;
5688       TopExp_Explorer fExp;
5689       for ( fExp.Init( theShape, TopAbs_FACE ); fExp.More(); fExp.Next() )
5690       {
5691         bool isNewFace = faceMap.Add( fExp.Current() );
5692         if ( !grid._toConsiderInternalFaces )
5693           if ( !isNewFace || fExp.Current().Orientation() == TopAbs_INTERNAL )
5694             // remove an internal face
5695             faceMap.Remove( fExp.Current() );
5696       }
5697       faceVec.reserve( faceMap.Extent() );
5698       faceVec.assign( faceMap.cbegin(), faceMap.cend() );
5699     }
5700     vector<FaceGridIntersector> facesItersectors( faceVec.size() );
5701     Bnd_Box shapeBox;
5702     for ( size_t i = 0; i < faceVec.size(); ++i )
5703     {
5704       facesItersectors[i]._face   = TopoDS::Face( faceVec[i] );
5705       facesItersectors[i]._faceID = grid.ShapeID( faceVec[i] );
5706       facesItersectors[i]._grid   = &grid;
5707       shapeBox.Add( facesItersectors[i].GetFaceBndBox() );
5708     }
5709     getExactBndBox( faceVec, _hyp->GetAxisDirs(), shapeBox );
5710
5711
5712     vector<double> xCoords, yCoords, zCoords;
5713     _hyp->GetCoordinates( xCoords, yCoords, zCoords, shapeBox );
5714
5715     grid.SetCoordinates( xCoords, yCoords, zCoords, _hyp->GetAxisDirs(), shapeBox );
5716
5717     if ( _computeCanceled ) return false;
5718
5719 #ifdef WITH_TBB
5720     { // copy partner faces and curves of not thread-safe types
5721       set< const Standard_Transient* > tshapes;
5722       BRepBuilderAPI_Copy copier;
5723       for ( size_t i = 0; i < facesItersectors.size(); ++i )
5724       {
5725         if ( !facesItersectors[i].IsThreadSafe( tshapes ))
5726         {
5727           copier.Perform( facesItersectors[i]._face );
5728           facesItersectors[i]._face = TopoDS::Face( copier );
5729         }
5730       }
5731     }
5732     // Intersection of grid lines with the geometry boundary.
5733     tbb::parallel_for ( tbb::blocked_range<size_t>( 0, facesItersectors.size() ),
5734                         ParallelIntersector( facesItersectors ),
5735                         tbb::simple_partitioner());
5736 #else
5737     for ( size_t i = 0; i < facesItersectors.size(); ++i )
5738       facesItersectors[i].Intersect();
5739 #endif
5740
5741     // put intersection points onto the GridLine's; this is done after intersection
5742     // to avoid contention of facesItersectors for writing into the same GridLine
5743     // in case of parallel work of facesItersectors
5744     for ( size_t i = 0; i < facesItersectors.size(); ++i )
5745       facesItersectors[i].StoreIntersections();
5746
5747     if ( _computeCanceled ) return false;
5748
5749     // create nodes on the geometry
5750     grid.ComputeNodes( helper );
5751
5752     if ( _computeCanceled ) return false;
5753
5754     // get EDGEs to take into account
5755     map< TGeomID, vector< TGeomID > > edge2faceIDsMap;
5756     grid.GetEdgesToImplement( edge2faceIDsMap, theShape, faceVec );
5757
5758     // create volume elements
5759     Hexahedron hex( &grid );
5760     int nbAdded = hex.MakeElements( helper, edge2faceIDsMap );
5761
5762     if ( nbAdded > 0 )
5763     {
5764       if ( !grid._toConsiderInternalFaces )
5765       {
5766         // make all SOLIDs computed
5767         TopExp_Explorer solidExp( theShape, TopAbs_SOLID );
5768         if ( SMESHDS_SubMesh* sm1 = meshDS->MeshElements( solidExp.Current()) )
5769         {
5770           SMDS_ElemIteratorPtr volIt = sm1->GetElements();
5771           for ( ; solidExp.More() && volIt->more(); solidExp.Next() )
5772           {
5773             const SMDS_MeshElement* vol = volIt->next();
5774             sm1->RemoveElement( vol );
5775             meshDS->SetMeshElementOnShape( vol, solidExp.Current() );
5776           }
5777         }
5778       }
5779       // make other sub-shapes computed
5780       setSubmeshesComputed( theMesh, theShape );
5781     }
5782
5783     // remove free nodes
5784     //if ( SMESHDS_SubMesh * smDS = meshDS->MeshElements( helper.GetSubShapeID() ))
5785     {
5786       std::vector< const SMDS_MeshNode* > nodesToRemove;
5787       // get intersection nodes
5788       for ( int iDir = 0; iDir < 3; ++iDir )
5789       {
5790         vector< GridLine >& lines = grid._lines[ iDir ];
5791         for ( size_t i = 0; i < lines.size(); ++i )
5792         {
5793           multiset< F_IntersectPoint >::iterator ip = lines[i]._intPoints.begin();
5794           for ( ; ip != lines[i]._intPoints.end(); ++ip )
5795             if ( ip->_node && ip->_node->NbInverseElements() == 0 && !ip->_node->isMarked() )
5796             {
5797               nodesToRemove.push_back( ip->_node );
5798               ip->_node->setIsMarked( true );
5799             }
5800         }
5801       }
5802       // get grid nodes
5803       for ( size_t i = 0; i < grid._nodes.size(); ++i )
5804         if ( grid._nodes[i] && grid._nodes[i]->NbInverseElements() == 0 &&
5805              !grid._nodes[i]->isMarked() )
5806         {
5807           nodesToRemove.push_back( grid._nodes[i] );
5808           grid._nodes[i]->setIsMarked( true );
5809         }
5810
5811       // do remove
5812       for ( size_t i = 0; i < nodesToRemove.size(); ++i )
5813         meshDS->RemoveFreeNode( nodesToRemove[i], /*smD=*/0, /*fromGroups=*/false );
5814     }
5815
5816     return nbAdded;
5817
5818   }
5819   // SMESH_ComputeError is not caught at SMESH_submesh level for an unknown reason
5820   catch ( SMESH_ComputeError& e)
5821   {
5822     return error( SMESH_ComputeErrorPtr( new SMESH_ComputeError( e )));
5823   }
5824   return false;
5825 }
5826
5827 //=============================================================================
5828 /*!
5829  *  Evaluate
5830  */
5831 //=============================================================================
5832
5833 bool StdMeshers_Cartesian_3D::Evaluate(SMESH_Mesh &         theMesh,
5834                                        const TopoDS_Shape & theShape,
5835                                        MapShapeNbElems&     theResMap)
5836 {
5837   // TODO
5838 //   std::vector<int> aResVec(SMDSEntity_Last);
5839 //   for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aResVec[i] = 0;
5840 //   if(IsQuadratic) {
5841 //     aResVec[SMDSEntity_Quad_Cartesian] = nb2d_face0 * ( nb2d/nb1d );
5842 //     int nb1d_face0_int = ( nb2d_face0*4 - nb1d ) / 2;
5843 //     aResVec[SMDSEntity_Node] = nb0d_face0 * ( 2*nb2d/nb1d - 1 ) - nb1d_face0_int * nb2d/nb1d;
5844 //   }
5845 //   else {
5846 //     aResVec[SMDSEntity_Node] = nb0d_face0 * ( nb2d/nb1d - 1 );
5847 //     aResVec[SMDSEntity_Cartesian] = nb2d_face0 * ( nb2d/nb1d );
5848 //   }
5849 //   SMESH_subMesh * sm = aMesh.GetSubMesh(aShape);
5850 //   aResMap.insert(std::make_pair(sm,aResVec));
5851
5852   return true;
5853 }
5854
5855 //=============================================================================
5856 namespace
5857 {
5858   /*!
5859    * \brief Event listener setting/unsetting _alwaysComputed flag to
5860    *        submeshes of inferior levels to prevent their computing
5861    */
5862   struct _EventListener : public SMESH_subMeshEventListener
5863   {
5864     string _algoName;
5865
5866     _EventListener(const string& algoName):
5867       SMESH_subMeshEventListener(/*isDeletable=*/true,"StdMeshers_Cartesian_3D::_EventListener"),
5868       _algoName(algoName)
5869     {}
5870     // --------------------------------------------------------------------------------
5871     // setting/unsetting _alwaysComputed flag to submeshes of inferior levels
5872     //
5873     static void setAlwaysComputed( const bool     isComputed,
5874                                    SMESH_subMesh* subMeshOfSolid)
5875     {
5876       SMESH_subMeshIteratorPtr smIt =
5877         subMeshOfSolid->getDependsOnIterator(/*includeSelf=*/false, /*complexShapeFirst=*/false);
5878       while ( smIt->more() )
5879       {
5880         SMESH_subMesh* sm = smIt->next();
5881         sm->SetIsAlwaysComputed( isComputed );
5882       }
5883       subMeshOfSolid->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
5884     }
5885
5886     // --------------------------------------------------------------------------------
5887     // unsetting _alwaysComputed flag if "Cartesian_3D" was removed
5888     //
5889     virtual void ProcessEvent(const int          event,
5890                               const int          eventType,
5891                               SMESH_subMesh*     subMeshOfSolid,
5892                               SMESH_subMeshEventListenerData* data,
5893                               const SMESH_Hypothesis*         hyp = 0)
5894     {
5895       if ( eventType == SMESH_subMesh::COMPUTE_EVENT )
5896       {
5897         setAlwaysComputed( subMeshOfSolid->GetComputeState() == SMESH_subMesh::COMPUTE_OK,
5898                            subMeshOfSolid );
5899       }
5900       else
5901       {
5902         SMESH_Algo* algo3D = subMeshOfSolid->GetAlgo();
5903         if ( !algo3D || _algoName != algo3D->GetName() )
5904           setAlwaysComputed( false, subMeshOfSolid );
5905       }
5906     }
5907
5908     // --------------------------------------------------------------------------------
5909     // set the event listener
5910     //
5911     static void SetOn( SMESH_subMesh* subMeshOfSolid, const string& algoName )
5912     {
5913       subMeshOfSolid->SetEventListener( new _EventListener( algoName ),
5914                                         /*data=*/0,
5915                                         subMeshOfSolid );
5916     }
5917
5918   }; // struct _EventListener
5919
5920 } // namespace
5921
5922 //================================================================================
5923 /*!
5924  * \brief Sets event listener to submeshes if necessary
5925  *  \param subMesh - submesh where algo is set
5926  * This method is called when a submesh gets HYP_OK algo_state.
5927  * After being set, event listener is notified on each event of a submesh.
5928  */
5929 //================================================================================
5930
5931 void StdMeshers_Cartesian_3D::SetEventListener(SMESH_subMesh* subMesh)
5932 {
5933   _EventListener::SetOn( subMesh, GetName() );
5934 }
5935
5936 //================================================================================
5937 /*!
5938  * \brief Set _alwaysComputed flag to submeshes of inferior levels to avoid their computing
5939  */
5940 //================================================================================
5941
5942 void StdMeshers_Cartesian_3D::setSubmeshesComputed(SMESH_Mesh&         theMesh,
5943                                                    const TopoDS_Shape& theShape)
5944 {
5945   for ( TopExp_Explorer soExp( theShape, TopAbs_SOLID ); soExp.More(); soExp.Next() )
5946     _EventListener::setAlwaysComputed( true, theMesh.GetSubMesh( soExp.Current() ));
5947 }