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