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