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