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