Salome HOME
4ed66607ada5ded28596be8065e4f7208ce025f0
[modules/smesh.git] / src / StdMeshers / StdMeshers_ViscousLayers.cxx
1 // Copyright (C) 2007-2021  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 // File      : StdMeshers_ViscousLayers.cxx
21 // Created   : Wed Dec  1 15:15:34 2010
22 // Author    : Edward AGAPOV (eap)
23
24 #include "StdMeshers_ViscousLayers.hxx"
25
26 #include "ObjectPool.hxx"
27 #include "SMDS_EdgePosition.hxx"
28 #include "SMDS_FaceOfNodes.hxx"
29 #include "SMDS_FacePosition.hxx"
30 #include "SMDS_MeshNode.hxx"
31 #include "SMDS_PolygonalFaceOfNodes.hxx"
32 #include "SMDS_SetIterator.hxx"
33 #include "SMESHDS_Group.hxx"
34 #include "SMESHDS_Hypothesis.hxx"
35 #include "SMESHDS_Mesh.hxx"
36 #include "SMESH_Algo.hxx"
37 #include "SMESH_Block.hxx"
38 #include "SMESH_ComputeError.hxx"
39 #include "SMESH_ControlsDef.hxx"
40 #include "SMESH_Gen.hxx"
41 #include "SMESH_Group.hxx"
42 #include "SMESH_HypoFilter.hxx"
43 #include "SMESH_Mesh.hxx"
44 #include "SMESH_MeshAlgos.hxx"
45 #include "SMESH_MeshEditor.hxx"
46 #include "SMESH_MesherHelper.hxx"
47 #include "SMESH_ProxyMesh.hxx"
48 #include "SMESH_subMesh.hxx"
49 #include "SMESH_subMeshEventListener.hxx"
50 #include "StdMeshers_FaceSide.hxx"
51 #include "StdMeshers_ProjectionUtils.hxx"
52 #include "StdMeshers_Quadrangle_2D.hxx"
53 #include "StdMeshers_ViscousLayers2D.hxx"
54
55 #include <Adaptor3d_HSurface.hxx>
56 #include <BRepAdaptor_Curve.hxx>
57 #include <BRepAdaptor_Curve2d.hxx>
58 #include <BRepAdaptor_Surface.hxx>
59 #include <BRepLProp_SLProps.hxx>
60 #include <BRepOffsetAPI_MakeOffsetShape.hxx>
61 #include <BRep_Tool.hxx>
62 #include <Bnd_B2d.hxx>
63 #include <Bnd_B3d.hxx>
64 #include <ElCLib.hxx>
65 #include <GCPnts_AbscissaPoint.hxx>
66 #include <GCPnts_TangentialDeflection.hxx>
67 #include <Geom2d_Circle.hxx>
68 #include <Geom2d_Line.hxx>
69 #include <Geom2d_TrimmedCurve.hxx>
70 #include <GeomAdaptor_Curve.hxx>
71 #include <GeomLib.hxx>
72 #include <Geom_Circle.hxx>
73 #include <Geom_Curve.hxx>
74 #include <Geom_Line.hxx>
75 #include <Geom_TrimmedCurve.hxx>
76 #include <Precision.hxx>
77 #include <Standard_ErrorHandler.hxx>
78 #include <Standard_Failure.hxx>
79 #include <TColStd_Array1OfReal.hxx>
80 #include <TopExp.hxx>
81 #include <TopExp_Explorer.hxx>
82 #include <TopTools_IndexedMapOfShape.hxx>
83 #include <TopTools_ListOfShape.hxx>
84 #include <TopTools_MapIteratorOfMapOfShape.hxx>
85 #include <TopTools_MapOfShape.hxx>
86 #include <TopoDS.hxx>
87 #include <TopoDS_Edge.hxx>
88 #include <TopoDS_Face.hxx>
89 #include <TopoDS_Vertex.hxx>
90 #include <gp_Ax1.hxx>
91 #include <gp_Cone.hxx>
92 #include <gp_Sphere.hxx>
93 #include <gp_Vec.hxx>
94 #include <gp_XY.hxx>
95
96 #include <cmath>
97 #include <limits>
98 #include <list>
99 #include <queue>
100 #include <string>
101 #include <unordered_map>
102
103 #ifdef _DEBUG_
104 #define __myDEBUG
105 //#define __NOT_INVALIDATE_BAD_SMOOTH
106 //#define __NODES_AT_POS
107 #endif
108
109 #define INCREMENTAL_SMOOTH // smooth only if min angle is too small
110 #define BLOCK_INFLATION // of individual _LayerEdge's
111 #define OLD_NEF_POLYGON
112
113 using namespace std;
114
115 //================================================================================
116 namespace VISCOUS_3D
117 {
118   typedef int TGeomID;
119
120   enum UIndex { U_TGT = 1, U_SRC, LEN_TGT };
121
122   const double theMinSmoothCosin = 0.1;
123   const double theSmoothThickToElemSizeRatio = 0.6;
124   const double theMinSmoothTriaAngle = 30;
125   const double theMinSmoothQuadAngle = 45;
126
127   // what part of thickness is allowed till intersection
128   // (defined by SALOME_TESTS/Grids/smesh/viscous_layers_00/A5)
129   const double theThickToIntersection = 1.5;
130
131   bool needSmoothing( double cosin, double tgtThick, double elemSize )
132   {
133     return cosin * tgtThick > theSmoothThickToElemSizeRatio * elemSize;
134   }
135   double getSmoothingThickness( double cosin, double elemSize )
136   {
137     return theSmoothThickToElemSizeRatio * elemSize / cosin;
138   }
139
140   /*!
141    * \brief SMESH_ProxyMesh computed by _ViscousBuilder for a SOLID.
142    * It is stored in a SMESH_subMesh of the SOLID as SMESH_subMeshEventListenerData
143    */
144   struct _MeshOfSolid : public SMESH_ProxyMesh,
145                         public SMESH_subMeshEventListenerData
146   {
147     bool                  _n2nMapComputed;
148     SMESH_ComputeErrorPtr _warning;
149
150     _MeshOfSolid( SMESH_Mesh* mesh)
151       :SMESH_subMeshEventListenerData( /*isDeletable=*/true),_n2nMapComputed(false)
152     {
153       SMESH_ProxyMesh::setMesh( *mesh );
154     }
155
156     // returns submesh for a geom face
157     SMESH_ProxyMesh::SubMesh* getFaceSubM(const TopoDS_Face& F, bool create=false)
158     {
159       TGeomID i = SMESH_ProxyMesh::shapeIndex(F);
160       return create ? SMESH_ProxyMesh::getProxySubMesh(i) : findProxySubMesh(i);
161     }
162     void setNode2Node(const SMDS_MeshNode*                 srcNode,
163                       const SMDS_MeshNode*                 proxyNode,
164                       const SMESH_ProxyMesh::SubMesh* subMesh)
165     {
166       SMESH_ProxyMesh::setNode2Node( srcNode,proxyNode,subMesh);
167     }
168   };
169   //--------------------------------------------------------------------------------
170   /*!
171    * \brief Listener of events of 3D sub-meshes computed with viscous layers.
172    * It is used to clear an inferior dim sub-meshes modified by viscous layers
173    */
174   class _ShrinkShapeListener : SMESH_subMeshEventListener
175   {
176     _ShrinkShapeListener()
177       : SMESH_subMeshEventListener(/*isDeletable=*/false,
178                                    "StdMeshers_ViscousLayers::_ShrinkShapeListener") {}
179   public:
180     static SMESH_subMeshEventListener* Get() { static _ShrinkShapeListener l; return &l; }
181     virtual void ProcessEvent(const int                       event,
182                               const int                       eventType,
183                               SMESH_subMesh*                  solidSM,
184                               SMESH_subMeshEventListenerData* data,
185                               const SMESH_Hypothesis*         hyp)
186     {
187       if ( SMESH_subMesh::COMPUTE_EVENT == eventType && solidSM->IsEmpty() && data )
188       {
189         SMESH_subMeshEventListener::ProcessEvent(event,eventType,solidSM,data,hyp);
190       }
191     }
192   };
193   //--------------------------------------------------------------------------------
194   /*!
195    * \brief Listener of events of 3D sub-meshes computed with viscous layers.
196    * It is used to store data computed by _ViscousBuilder for a sub-mesh and to
197    * delete the data as soon as it has been used
198    */
199   class _ViscousListener : SMESH_subMeshEventListener
200   {
201     _ViscousListener():
202       SMESH_subMeshEventListener(/*isDeletable=*/false,
203                                  "StdMeshers_ViscousLayers::_ViscousListener") {}
204     static SMESH_subMeshEventListener* Get() { static _ViscousListener l; return &l; }
205   public:
206     virtual void ProcessEvent(const int                       event,
207                               const int                       eventType,
208                               SMESH_subMesh*                  subMesh,
209                               SMESH_subMeshEventListenerData* /*data*/,
210                               const SMESH_Hypothesis*         /*hyp*/)
211     {
212       if (( SMESH_subMesh::COMPUTE_EVENT       == eventType ) &&
213           ( SMESH_subMesh::CHECK_COMPUTE_STATE != event &&
214             SMESH_subMesh::SUBMESH_COMPUTED    != event ))
215       {
216         // delete SMESH_ProxyMesh containing temporary faces
217         subMesh->DeleteEventListener( this );
218       }
219     }
220     // Finds or creates proxy mesh of the solid
221     static _MeshOfSolid* GetSolidMesh(SMESH_Mesh*         mesh,
222                                       const TopoDS_Shape& solid,
223                                       bool                toCreate=false)
224     {
225       if ( !mesh ) return 0;
226       SMESH_subMesh* sm = mesh->GetSubMesh(solid);
227       _MeshOfSolid* data = (_MeshOfSolid*) sm->GetEventListenerData( Get() );
228       if ( !data && toCreate )
229       {
230         data = new _MeshOfSolid(mesh);
231         data->mySubMeshes.push_back( sm ); // to find SOLID by _MeshOfSolid
232         sm->SetEventListener( Get(), data, sm );
233       }
234       return data;
235     }
236     // Removes proxy mesh of the solid
237     static void RemoveSolidMesh(SMESH_Mesh* mesh, const TopoDS_Shape& solid)
238     {
239       mesh->GetSubMesh(solid)->DeleteEventListener( _ViscousListener::Get() );
240     }
241   };
242   
243   //================================================================================
244   /*!
245    * \brief sets a sub-mesh event listener to clear sub-meshes of sub-shapes of
246    * the main shape when sub-mesh of the main shape is cleared,
247    * for example to clear sub-meshes of FACEs when sub-mesh of a SOLID
248    * is cleared
249    */
250   //================================================================================
251
252   void ToClearSubWithMain( SMESH_subMesh* sub, const TopoDS_Shape& main)
253   {
254     SMESH_subMesh* mainSM = sub->GetFather()->GetSubMesh( main );
255     SMESH_subMeshEventListenerData* data =
256       mainSM->GetEventListenerData( _ShrinkShapeListener::Get());
257     if ( data )
258     {
259       if ( find( data->mySubMeshes.begin(), data->mySubMeshes.end(), sub ) ==
260            data->mySubMeshes.end())
261         data->mySubMeshes.push_back( sub );
262     }
263     else
264     {
265       data = SMESH_subMeshEventListenerData::MakeData( /*dependent=*/sub );
266       sub->SetEventListener( _ShrinkShapeListener::Get(), data, /*whereToListenTo=*/mainSM );
267     }
268   }
269   struct _SolidData;
270   //--------------------------------------------------------------------------------
271   /*!
272    * \brief Simplex (triangle or tetrahedron) based on 1 (tria) or 2 (tet) nodes of
273    * _LayerEdge and 2 nodes of the mesh surface beening smoothed.
274    * The class is used to check validity of face or volumes around a smoothed node;
275    * it stores only 2 nodes as the other nodes are stored by _LayerEdge.
276    */
277   struct _Simplex
278   {
279     const SMDS_MeshNode *_nPrev, *_nNext; // nodes on a smoothed mesh surface
280     const SMDS_MeshNode *_nOpp; // in 2D case, a node opposite to a smoothed node in QUAD
281     _Simplex(const SMDS_MeshNode* nPrev=0,
282              const SMDS_MeshNode* nNext=0,
283              const SMDS_MeshNode* nOpp=0)
284       : _nPrev(nPrev), _nNext(nNext), _nOpp(nOpp) {}
285     bool IsForward(const gp_XYZ* pntSrc, const gp_XYZ* pntTgt, double& vol) const
286     {
287       const double M[3][3] =
288         {{ _nNext->X() - pntSrc->X(), _nNext->Y() - pntSrc->Y(), _nNext->Z() - pntSrc->Z() },
289          { pntTgt->X() - pntSrc->X(), pntTgt->Y() - pntSrc->Y(), pntTgt->Z() - pntSrc->Z() },
290          { _nPrev->X() - pntSrc->X(), _nPrev->Y() - pntSrc->Y(), _nPrev->Z() - pntSrc->Z() }};
291       vol = ( + M[0][0] * M[1][1] * M[2][2]
292               + M[0][1] * M[1][2] * M[2][0]
293               + M[0][2] * M[1][0] * M[2][1]
294               - M[0][0] * M[1][2] * M[2][1]
295               - M[0][1] * M[1][0] * M[2][2]
296               - M[0][2] * M[1][1] * M[2][0]);
297       return vol > 1e-100;
298     }
299     bool IsForward(const SMDS_MeshNode* nSrc, const gp_XYZ& pTgt, double& vol) const
300     {
301       SMESH_TNodeXYZ pSrc( nSrc );
302       return IsForward( &pSrc, &pTgt, vol );
303     }
304     bool IsForward(const gp_XY&         tgtUV,
305                    const SMDS_MeshNode* smoothedNode,
306                    const TopoDS_Face&   face,
307                    SMESH_MesherHelper&  helper,
308                    const double         refSign) const
309     {
310       gp_XY prevUV = helper.GetNodeUV( face, _nPrev, smoothedNode );
311       gp_XY nextUV = helper.GetNodeUV( face, _nNext, smoothedNode );
312       gp_Vec2d v1( tgtUV, prevUV ), v2( tgtUV, nextUV );
313       double d = v1 ^ v2;
314       return d*refSign > 1e-100;
315     }
316     bool IsMinAngleOK( const gp_XYZ& pTgt, double& minAngle ) const
317     {
318       SMESH_TNodeXYZ pPrev( _nPrev ), pNext( _nNext );
319       if ( !_nOpp ) // triangle
320       {
321         gp_Vec tp( pPrev - pTgt ), pn( pNext - pPrev ), nt( pTgt - pNext );
322         double tp2 = tp.SquareMagnitude();
323         double pn2 = pn.SquareMagnitude();
324         double nt2 = nt.SquareMagnitude();
325
326         if ( tp2 < pn2 && tp2 < nt2 )
327           minAngle = ( nt * -pn ) * ( nt * -pn ) / nt2 / pn2;
328         else if ( pn2 < nt2 )
329           minAngle = ( tp * -nt ) * ( tp * -nt ) / tp2 / nt2;
330         else
331           minAngle = ( pn * -tp ) * ( pn * -tp ) / pn2 / tp2;
332
333         static double theMaxCos2 = ( Cos( theMinSmoothTriaAngle * M_PI / 180. ) *
334                                      Cos( theMinSmoothTriaAngle * M_PI / 180. ));
335         return minAngle < theMaxCos2;
336       }
337       else // quadrangle
338       {
339         SMESH_TNodeXYZ pOpp( _nOpp );
340         gp_Vec tp( pPrev - pTgt ), po( pOpp - pPrev ), on( pNext - pOpp), nt( pTgt - pNext );
341         double tp2 = tp.SquareMagnitude();
342         double po2 = po.SquareMagnitude();
343         double on2 = on.SquareMagnitude();
344         double nt2 = nt.SquareMagnitude();
345         minAngle = Max( Max((( tp * -nt ) * ( tp * -nt ) / tp2 / nt2 ),
346                             (( po * -tp ) * ( po * -tp ) / po2 / tp2 )),
347                         Max((( on * -po ) * ( on * -po ) / on2 / po2 ),
348                             (( nt * -on ) * ( nt * -on ) / nt2 / on2 )));
349
350         static double theMaxCos2 = ( Cos( theMinSmoothQuadAngle * M_PI / 180. ) *
351                                      Cos( theMinSmoothQuadAngle * M_PI / 180. ));
352         return minAngle < theMaxCos2;
353       }
354     }
355     bool IsNeighbour(const _Simplex& other) const
356     {
357       return _nPrev == other._nNext || _nNext == other._nPrev;
358     }
359     bool Includes( const SMDS_MeshNode* node ) const { return _nPrev == node || _nNext == node; }
360     static void GetSimplices( const SMDS_MeshNode* node,
361                               vector<_Simplex>&   simplices,
362                               const set<TGeomID>& ingnoreShapes,
363                               const _SolidData*   dataToCheckOri = 0,
364                               const bool          toSort = false);
365     static void SortSimplices(vector<_Simplex>& simplices);
366   };
367   //--------------------------------------------------------------------------------
368   /*!
369    * Structure used to take into account surface curvature while smoothing
370    */
371   struct _Curvature
372   {
373     double   _r; // radius
374     double   _k; // factor to correct node smoothed position
375     double   _h2lenRatio; // avgNormProj / (2*avgDist)
376     gp_Pnt2d _uv; // UV used in putOnOffsetSurface()
377   public:
378     static _Curvature* New( double avgNormProj, double avgDist );
379     double lenDelta(double len) const { return _k * ( _r + len ); }
380     double lenDeltaByDist(double dist) const { return dist * _h2lenRatio; }
381   };
382   //--------------------------------------------------------------------------------
383
384   struct _2NearEdges;
385   struct _LayerEdge;
386   struct _EdgesOnShape;
387   struct _Smoother1D;
388   struct _Mapper2D;
389   typedef map< const SMDS_MeshNode*, _LayerEdge*, TIDCompare > TNode2Edge;
390
391   //--------------------------------------------------------------------------------
392   /*!
393    * \brief Edge normal to surface, connecting a node on solid surface (_nodes[0])
394    * and a node of the most internal layer (_nodes.back())
395    */
396   struct _LayerEdge
397   {
398     typedef gp_XYZ (_LayerEdge::*PSmooFun)();
399
400     vector< const SMDS_MeshNode*> _nodes;
401
402     gp_XYZ              _normal;    // to boundary of solid
403     vector<gp_XYZ>      _pos;       // points computed during inflation
404     double              _len;       // length achieved with the last inflation step
405     double              _maxLen;    // maximal possible length
406     double              _cosin;     // of angle (_normal ^ surface)
407     double              _minAngle;  // of _simplices
408     double              _lenFactor; // to compute _len taking _cosin into account
409     int                 _flags;
410
411     // simplices connected to the source node (_nodes[0]);
412     // used for smoothing and quality check of _LayerEdge's based on the FACE
413     vector<_Simplex>    _simplices;
414     vector<_LayerEdge*> _neibors; // all surrounding _LayerEdge's
415     PSmooFun            _smooFunction; // smoothing function
416     _Curvature*         _curvature;
417     // data for smoothing of _LayerEdge's based on the EDGE
418     _2NearEdges*        _2neibors;
419
420     enum EFlags { TO_SMOOTH       = 0x0000001,
421                   MOVED           = 0x0000002, // set by _neibors[i]->SetNewLength()
422                   SMOOTHED        = 0x0000004, // set by _LayerEdge::Smooth()
423                   DIFFICULT       = 0x0000008, // near concave VERTEX
424                   ON_CONCAVE_FACE = 0x0000010,
425                   BLOCKED         = 0x0000020, // not to inflate any more
426                   INTERSECTED     = 0x0000040, // close intersection with a face found
427                   NORMAL_UPDATED  = 0x0000080,
428                   UPD_NORMAL_CONV = 0x0000100, // to update normal on boundary of concave FACE
429                   MARKED          = 0x0000200, // local usage
430                   MULTI_NORMAL    = 0x0000400, // a normal is invisible by some of surrounding faces
431                   NEAR_BOUNDARY   = 0x0000800, // is near FACE boundary forcing smooth
432                   SMOOTHED_C1     = 0x0001000, // is on _eosC1
433                   DISTORTED       = 0x0002000, // was bad before smoothing
434                   RISKY_SWOL      = 0x0004000, // SWOL is parallel to a source FACE
435                   SHRUNK          = 0x0008000, // target node reached a tgt position while shrink()
436                   UNUSED_FLAG     = 0x0100000  // to add user flags after
437     };
438     bool Is   ( int flag ) const { return _flags & flag; }
439     void Set  ( int flag ) { _flags |= flag; }
440     void Unset( int flag ) { _flags &= ~flag; }
441     std::string DumpFlags() const; // debug
442
443     void SetNewLength( double len, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
444     bool SetNewLength2d( Handle(Geom_Surface)& surface,
445                          const TopoDS_Face&    F,
446                          _EdgesOnShape&        eos,
447                          SMESH_MesherHelper&   helper );
448     bool UpdatePositionOnSWOL( SMDS_MeshNode*      n,
449                                double              tol,
450                                _EdgesOnShape&      eos,
451                                SMESH_MesherHelper& helper );
452     void SetDataByNeighbors( const SMDS_MeshNode* n1,
453                              const SMDS_MeshNode* n2,
454                              const _EdgesOnShape& eos,
455                              SMESH_MesherHelper&  helper);
456     void Block( _SolidData& data );
457     void InvalidateStep( size_t curStep, const _EdgesOnShape& eos, bool restoreLength=false );
458     void ChooseSmooFunction(const set< TGeomID >& concaveVertices,
459                             const TNode2Edge&     n2eMap);
460     void SmoothPos( const vector< double >& segLen, const double tol );
461     int  GetSmoothedPos( const double tol );
462     int  Smooth(const int step, const bool isConcaveFace, bool findBest);
463     int  Smooth(const int step, bool findBest, vector< _LayerEdge* >& toSmooth );
464     int  CheckNeiborsOnBoundary(vector< _LayerEdge* >* badNeibors = 0, bool * needSmooth = 0 );
465     void SmoothWoCheck();
466     bool SmoothOnEdge(Handle(ShapeAnalysis_Surface)& surface,
467                       const TopoDS_Face&             F,
468                       SMESH_MesherHelper&            helper);
469     void MoveNearConcaVer( const _EdgesOnShape*    eov,
470                            const _EdgesOnShape*    eos,
471                            const int               step,
472                            vector< _LayerEdge* > & badSmooEdges);
473     bool FindIntersection( SMESH_ElementSearcher&   searcher,
474                            double &                 distance,
475                            const double&            epsilon,
476                            _EdgesOnShape&           eos,
477                            const SMDS_MeshElement** face = 0);
478     bool SegTriaInter( const gp_Ax1&        lastSegment,
479                        const gp_XYZ&        p0,
480                        const gp_XYZ&        p1,
481                        const gp_XYZ&        p2,
482                        double&              dist,
483                        const double&        epsilon) const;
484     bool SegTriaInter( const gp_Ax1&        lastSegment,
485                        const SMDS_MeshNode* n0,
486                        const SMDS_MeshNode* n1,
487                        const SMDS_MeshNode* n2,
488                        double&              dist,
489                        const double&        epsilon) const
490     { return SegTriaInter( lastSegment,
491                            SMESH_TNodeXYZ( n0 ), SMESH_TNodeXYZ( n1 ), SMESH_TNodeXYZ( n2 ),
492                            dist, epsilon );
493     }
494     const gp_XYZ& PrevPos() const { return _pos[ _pos.size() - 2 ]; }
495     gp_XYZ PrevCheckPos( _EdgesOnShape* eos=0 ) const;
496     gp_Ax1 LastSegment(double& segLen, _EdgesOnShape& eos) const;
497     gp_XY  LastUV( const TopoDS_Face& F, _EdgesOnShape& eos, int which=-1 ) const;
498     bool   IsOnEdge() const { return _2neibors; }
499     bool   IsOnFace() const { return ( _nodes[0]->GetPosition()->GetDim() == 2 ); }
500     int    BaseShapeDim() const { return _nodes[0]->GetPosition()->GetDim(); }
501     gp_XYZ Copy( _LayerEdge& other, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
502     double SetCosin( double cosin );
503     void   SetNormal( const gp_XYZ& n ) { _normal = n; }
504     void   SetMaxLen( double l ) { _maxLen = l; }
505     int    NbSteps() const { return _pos.size() - 1; } // nb inlation steps
506     bool   IsNeiborOnEdge( const _LayerEdge* edge ) const;
507     void   SetSmooLen( double len ) { // set _len at which smoothing is needed
508       _cosin = len; // as for _LayerEdge's on FACE _cosin is not used
509     }
510     double GetSmooLen() { return _cosin; } // for _LayerEdge's on FACE _cosin is not used
511
512     gp_XYZ smoothLaplacian();
513     gp_XYZ smoothAngular();
514     gp_XYZ smoothLengthWeighted();
515     gp_XYZ smoothCentroidal();
516     gp_XYZ smoothNefPolygon();
517
518     enum { FUN_LAPLACIAN, FUN_LENWEIGHTED, FUN_CENTROIDAL, FUN_NEFPOLY, FUN_ANGULAR, FUN_NB };
519     static const int theNbSmooFuns = FUN_NB;
520     static PSmooFun _funs[theNbSmooFuns];
521     static const char* _funNames[theNbSmooFuns+1];
522     int smooFunID( PSmooFun fun=0) const;
523   };
524   _LayerEdge::PSmooFun _LayerEdge::_funs[theNbSmooFuns] = { &_LayerEdge::smoothLaplacian,
525                                                             &_LayerEdge::smoothLengthWeighted,
526                                                             &_LayerEdge::smoothCentroidal,
527                                                             &_LayerEdge::smoothNefPolygon,
528                                                             &_LayerEdge::smoothAngular };
529   const char* _LayerEdge::_funNames[theNbSmooFuns+1] = { "Laplacian",
530                                                          "LengthWeighted",
531                                                          "Centroidal",
532                                                          "NefPolygon",
533                                                          "Angular",
534                                                          "None"};
535   struct _LayerEdgeCmp
536   {
537     bool operator () (const _LayerEdge* e1, const _LayerEdge* e2) const
538     {
539       const bool cmpNodes = ( e1 && e2 && e1->_nodes.size() && e2->_nodes.size() );
540       return cmpNodes ? ( e1->_nodes[0]->GetID() < e2->_nodes[0]->GetID()) : ( e1 < e2 );
541     }
542   };
543   //--------------------------------------------------------------------------------
544   /*!
545    * A 2D half plane used by _LayerEdge::smoothNefPolygon()
546    */
547   struct _halfPlane
548   {
549     gp_XY _pos, _dir, _inNorm;
550     bool IsOut( const gp_XY p, const double tol ) const
551     {
552       return _inNorm * ( p - _pos ) < -tol;
553     }
554     bool FindIntersection( const _halfPlane& hp, gp_XY & intPnt )
555     {
556       //const double eps = 1e-10;
557       double D = _dir.Crossed( hp._dir );
558       if ( fabs(D) < std::numeric_limits<double>::min())
559         return false;
560       gp_XY vec21 = _pos - hp._pos; 
561       double u = hp._dir.Crossed( vec21 ) / D; 
562       intPnt = _pos + _dir * u;
563       return true;
564     }
565   };
566   //--------------------------------------------------------------------------------
567   /*!
568    * Structure used to smooth a _LayerEdge based on an EDGE.
569    */
570   struct _2NearEdges
571   {
572     double               _wgt  [2]; // weights of _nodes
573     _LayerEdge*          _edges[2];
574
575      // normal to plane passing through _LayerEdge._normal and tangent of EDGE
576     gp_XYZ*              _plnNorm;
577
578     _2NearEdges() { _edges[0]=_edges[1]=0; _plnNorm = 0; }
579     ~_2NearEdges(){ delete _plnNorm; }
580     const SMDS_MeshNode* tgtNode(bool is2nd) {
581       return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0;
582     }
583     const SMDS_MeshNode* srcNode(bool is2nd) {
584       return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0;
585     }
586     void reverse() {
587       std::swap( _wgt  [0], _wgt  [1] );
588       std::swap( _edges[0], _edges[1] );
589     }
590     void set( _LayerEdge* e1, _LayerEdge* e2, double w1, double w2 ) {
591       _edges[0] = e1; _edges[1] = e2; _wgt[0] = w1; _wgt[1] = w2;
592     }
593     bool include( const _LayerEdge* e ) {
594       return ( _edges[0] == e || _edges[1] == e );
595     }
596   };
597
598
599   //--------------------------------------------------------------------------------
600   /*!
601    * \brief Layers parameters got by averaging several hypotheses
602    */
603   struct AverageHyp
604   {
605     AverageHyp( const StdMeshers_ViscousLayers* hyp = 0 )
606       :_nbLayers(0), _nbHyps(0), _method(0), _thickness(0), _stretchFactor(0)
607     {
608       Add( hyp );
609     }
610     void Add( const StdMeshers_ViscousLayers* hyp )
611     {
612       if ( hyp )
613       {
614         _nbHyps++;
615         _nbLayers       = hyp->GetNumberLayers();
616         //_thickness     += hyp->GetTotalThickness();
617         _thickness      = Max( _thickness, hyp->GetTotalThickness() );
618         _stretchFactor += hyp->GetStretchFactor();
619         _method         = hyp->GetMethod();
620         if ( _groupName.empty() )
621           _groupName = hyp->GetGroupName();
622       }
623     }
624     double GetTotalThickness() const { return _thickness; /*_nbHyps ? _thickness / _nbHyps : 0;*/ }
625     double GetStretchFactor()  const { return _nbHyps ? _stretchFactor / _nbHyps : 0; }
626     int    GetNumberLayers()   const { return _nbLayers; }
627     int    GetMethod()         const { return _method; }
628     bool   ToCreateGroup()     const { return !_groupName.empty(); }
629     const std::string& GetGroupName() const { return _groupName; }
630
631     double Get1stLayerThickness( double realThickness = 0.) const
632     {
633       const double T = ( realThickness > 0 ) ? realThickness : GetTotalThickness();
634       const double f = GetStretchFactor();
635       const int    N = GetNumberLayers();
636       const double fPowN = pow( f, N );
637       double h0;
638       if ( fPowN - 1 <= numeric_limits<double>::min() )
639         h0 = T / N;
640       else
641         h0 = T * ( f - 1 )/( fPowN - 1 );
642       return h0;
643     }
644
645     bool   UseSurfaceNormal()  const
646     { return _method == StdMeshers_ViscousLayers::SURF_OFFSET_SMOOTH; }
647     bool   ToSmooth()          const
648     { return _method == StdMeshers_ViscousLayers::SURF_OFFSET_SMOOTH; }
649     bool   IsOffsetMethod()    const
650     { return _method == StdMeshers_ViscousLayers::FACE_OFFSET; }
651
652     bool operator==( const AverageHyp& other ) const
653     {
654       return ( _nbLayers == other._nbLayers &&
655                _method   == other._method   &&
656                Equals( GetTotalThickness(), other.GetTotalThickness() ) &&
657                Equals( GetStretchFactor(), other.GetStretchFactor() ));
658     }
659     static bool Equals( double v1, double v2 ) { return Abs( v1 - v2 ) < 0.01 * ( v1 + v2 ); }
660
661   private:
662     int         _nbLayers, _nbHyps, _method;
663     double      _thickness, _stretchFactor;
664     std::string _groupName;
665   };
666
667   //--------------------------------------------------------------------------------
668   /*!
669    * \brief _LayerEdge's on a shape and other shape data
670    */
671   struct _EdgesOnShape
672   {
673     vector< _LayerEdge* > _edges;
674
675     TopoDS_Shape          _shape;
676     TGeomID               _shapeID;
677     SMESH_subMesh *       _subMesh;
678     // face or edge w/o layer along or near which _edges are inflated
679     TopoDS_Shape          _sWOL;
680     bool                  _isRegularSWOL; // w/o singularities
681     // averaged StdMeshers_ViscousLayers parameters
682     AverageHyp            _hyp;
683     bool                  _toSmooth;
684     _Smoother1D*          _edgeSmoother;
685     vector< _EdgesOnShape* > _eosConcaVer; // edges at concave VERTEXes of a FACE
686     vector< _EdgesOnShape* > _eosC1; // to smooth together several C1 continues shapes
687
688     typedef std::unordered_map< const SMDS_MeshElement*, gp_XYZ > TFace2NormMap;
689     TFace2NormMap            _faceNormals; // if _shape is FACE
690     vector< _EdgesOnShape* > _faceEOS; // to get _faceNormals of adjacent FACEs
691
692     Handle(ShapeAnalysis_Surface) _offsetSurf;
693     _LayerEdge*                   _edgeForOffset;
694     double                        _offsetValue;
695     _Mapper2D*                    _mapper2D;
696
697     _SolidData*            _data; // parent SOLID
698
699     _LayerEdge*      operator[](size_t i) const { return (_LayerEdge*) _edges[i]; }
700     size_t           size() const { return _edges.size(); }
701     TopAbs_ShapeEnum ShapeType() const
702     { return _shape.IsNull() ? TopAbs_SHAPE : _shape.ShapeType(); }
703     TopAbs_ShapeEnum SWOLType() const
704     { return _sWOL.IsNull() ? TopAbs_SHAPE : _sWOL.ShapeType(); }
705     bool             HasC1( const _EdgesOnShape* other ) const
706     { return std::find( _eosC1.begin(), _eosC1.end(), other ) != _eosC1.end(); }
707     bool             GetNormal( const SMDS_MeshElement* face, gp_Vec& norm );
708     _SolidData&      GetData() const { return *_data; }
709     char             ShapeTypeLetter() const
710     { switch ( ShapeType() ) { case TopAbs_FACE: return 'F'; case TopAbs_EDGE: return 'E';
711       case TopAbs_VERTEX: return 'V'; default: return 'S'; }}
712
713     _EdgesOnShape(): _shapeID(-1), _subMesh(0), _toSmooth(false), _edgeSmoother(0), _mapper2D(0) {}
714     ~_EdgesOnShape();
715   };
716
717   //--------------------------------------------------------------------------------
718   /*!
719    * \brief Convex FACE whose radius of curvature is less than the thickness of
720    *        layers. It is used to detect distortion of prisms based on a convex
721    *        FACE and to update normals to enable further increasing the thickness
722    */
723   struct _ConvexFace
724   {
725     TopoDS_Face                     _face;
726
727     // edges whose _simplices are used to detect prism distortion
728     vector< _LayerEdge* >           _simplexTestEdges;
729
730     // map a sub-shape to _SolidData::_edgesOnShape
731     map< TGeomID, _EdgesOnShape* >  _subIdToEOS;
732
733     bool                            _isTooCurved;
734     bool                            _normalsFixed;
735     bool                            _normalsFixedOnBorders; // used in putOnOffsetSurface()
736
737     double GetMaxCurvature( _SolidData&         data,
738                             _EdgesOnShape&      eof,
739                             BRepLProp_SLProps&  surfProp,
740                             SMESH_MesherHelper& helper);
741
742     bool GetCenterOfCurvature( _LayerEdge*         ledge,
743                                BRepLProp_SLProps&  surfProp,
744                                SMESH_MesherHelper& helper,
745                                gp_Pnt &            center ) const;
746     bool CheckPrisms() const;
747   };
748
749   //--------------------------------------------------------------------------------
750   /*!
751    * \brief Structure holding _LayerEdge's based on EDGEs that will collide
752    *        at inflation up to the full thickness. A detected collision
753    *        is fixed in updateNormals()
754    */
755   struct _CollisionEdges
756   {
757     _LayerEdge*           _edge;
758     vector< _LayerEdge* > _intEdges; // each pair forms an intersected quadrangle
759     const SMDS_MeshNode* nSrc(int i) const { return _intEdges[i]->_nodes[0]; }
760     const SMDS_MeshNode* nTgt(int i) const { return _intEdges[i]->_nodes.back(); }
761   };
762
763   //--------------------------------------------------------------------------------
764   /*!
765    * \brief Data of a SOLID
766    */
767   struct _SolidData
768   {
769     typedef const StdMeshers_ViscousLayers* THyp;
770     TopoDS_Shape                    _solid;
771     TopTools_MapOfShape             _before; // SOLIDs to be computed before _solid
772     TGeomID                         _index; // SOLID id
773     _MeshOfSolid*                   _proxyMesh;
774     bool                            _done;
775     list< THyp >                    _hyps;
776     list< TopoDS_Shape >            _hypShapes;
777     map< TGeomID, THyp >            _face2hyp; // filled if _hyps.size() > 1
778     set< TGeomID >                  _reversedFaceIds;
779     set< TGeomID >                  _ignoreFaceIds; // WOL FACEs and FACEs of other SOLIDs
780
781     double                          _stepSize, _stepSizeCoeff, _geomSize;
782     const SMDS_MeshNode*            _stepSizeNodes[2];
783
784     TNode2Edge                      _n2eMap; // nodes and _LayerEdge's based on them
785
786     // map to find _n2eMap of another _SolidData by a shrink shape shared by two _SolidData's
787     map< TGeomID, TNode2Edge* >     _s2neMap;
788     // _LayerEdge's with underlying shapes
789     vector< _EdgesOnShape >         _edgesOnShape;
790
791     // key:   an ID of shape (EDGE or VERTEX) shared by a FACE with
792     //        layers and a FACE w/o layers
793     // value: the shape (FACE or EDGE) to shrink mesh on.
794     //       _LayerEdge's basing on nodes on key shape are inflated along the value shape
795     map< TGeomID, TopoDS_Shape >     _shrinkShape2Shape;
796
797     // Convex FACEs whose radius of curvature is less than the thickness of layers
798     map< TGeomID, _ConvexFace >      _convexFaces;
799
800     // shapes (EDGEs and VERTEXes) shrink from which is forbidden due to collisions with
801     // the adjacent SOLID
802     set< TGeomID >                   _noShrinkShapes;
803
804     int                              _nbShapesToSmooth;
805
806     vector< _CollisionEdges >        _collisionEdges;
807     set< TGeomID >                   _concaveFaces;
808
809     double                           _maxThickness; // of all _hyps
810     double                           _minThickness; // of all _hyps
811
812     double                           _epsilon; // precision for SegTriaInter()
813
814     SMESH_MesherHelper*              _helper;
815
816     _SolidData(const TopoDS_Shape& s=TopoDS_Shape(),
817                _MeshOfSolid*       m=0)
818       :_solid(s), _proxyMesh(m), _done(false),_helper(0) {}
819     ~_SolidData() { delete _helper; _helper = 0; }
820
821     void SortOnEdge( const TopoDS_Edge& E, vector< _LayerEdge* >& edges);
822     void Sort2NeiborsOnEdge( vector< _LayerEdge* >& edges );
823
824     _ConvexFace* GetConvexFace( const TGeomID faceID ) {
825       map< TGeomID, _ConvexFace >::iterator id2face = _convexFaces.find( faceID );
826       return id2face == _convexFaces.end() ? 0 : & id2face->second;
827     }
828     _EdgesOnShape* GetShapeEdges(const TGeomID       shapeID );
829     _EdgesOnShape* GetShapeEdges(const TopoDS_Shape& shape );
830     _EdgesOnShape* GetShapeEdges(const _LayerEdge*   edge )
831     { return GetShapeEdges( edge->_nodes[0]->getshapeId() ); }
832
833     SMESH_MesherHelper& GetHelper() const { return *_helper; }
834
835     void UnmarkEdges( int flag = _LayerEdge::MARKED ) {
836       for ( size_t i = 0; i < _edgesOnShape.size(); ++i )
837         for ( size_t j = 0; j < _edgesOnShape[i]._edges.size(); ++j )
838           _edgesOnShape[i]._edges[j]->Unset( flag );
839     }
840     void AddShapesToSmooth( const set< _EdgesOnShape* >& shape,
841                             const set< _EdgesOnShape* >* edgesNoAnaSmooth=0 );
842
843     void PrepareEdgesToSmoothOnFace( _EdgesOnShape* eof, bool substituteSrcNodes );
844   };
845   //--------------------------------------------------------------------------------
846   /*!
847    * \brief Offset plane used in getNormalByOffset()
848    */
849   struct _OffsetPlane
850   {
851     gp_Pln _plane;
852     int    _faceIndex;
853     int    _faceIndexNext[2];
854     gp_Lin _lines[2]; // line of intersection with neighbor _OffsetPlane's
855     bool   _isLineOK[2];
856     _OffsetPlane() {
857       _isLineOK[0] = _isLineOK[1] = false; _faceIndexNext[0] = _faceIndexNext[1] = -1;
858     }
859     void   ComputeIntersectionLine( _OffsetPlane&        pln, 
860                                     const TopoDS_Edge&   E,
861                                     const TopoDS_Vertex& V );
862     gp_XYZ GetCommonPoint(bool& isFound, const TopoDS_Vertex& V) const;
863     int    NbLines() const { return _isLineOK[0] + _isLineOK[1]; }
864   };
865   //--------------------------------------------------------------------------------
866   /*!
867    * \brief Container of centers of curvature at nodes on an EDGE bounding _ConvexFace
868    */
869   struct _CentralCurveOnEdge
870   {
871     bool                  _isDegenerated;
872     vector< gp_Pnt >      _curvaCenters;
873     vector< _LayerEdge* > _ledges;
874     vector< gp_XYZ >      _normals; // new normal for each of _ledges
875     vector< double >      _segLength2;
876
877     TopoDS_Edge           _edge;
878     TopoDS_Face           _adjFace;
879     bool                  _adjFaceToSmooth;
880
881     void Append( const gp_Pnt& center, _LayerEdge* ledge )
882     {
883       if ( ledge->Is( _LayerEdge::MULTI_NORMAL ))
884         return;
885       if ( _curvaCenters.size() > 0 )
886         _segLength2.push_back( center.SquareDistance( _curvaCenters.back() ));
887       _curvaCenters.push_back( center );
888       _ledges.push_back( ledge );
889       _normals.push_back( ledge->_normal );
890     }
891     bool FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal );
892     void SetShapes( const TopoDS_Edge&  edge,
893                     const _ConvexFace&  convFace,
894                     _SolidData&         data,
895                     SMESH_MesherHelper& helper);
896   };
897   //--------------------------------------------------------------------------------
898   /*!
899    * \brief Data of node on a shrinked FACE
900    */
901   struct _SmoothNode
902   {
903     const SMDS_MeshNode*         _node;
904     vector<_Simplex>             _simplices; // for quality check
905
906     enum SmoothType { LAPLACIAN, CENTROIDAL, ANGULAR, TFI };
907
908     bool Smooth(int&                  badNb,
909                 Handle(Geom_Surface)& surface,
910                 SMESH_MesherHelper&   helper,
911                 const double          refSign,
912                 SmoothType            how,
913                 bool                  set3D);
914
915     gp_XY computeAngularPos(vector<gp_XY>& uv,
916                             const gp_XY&   uvToFix,
917                             const double   refSign );
918   };
919   struct PyDump;
920   struct Periodicity;
921   //--------------------------------------------------------------------------------
922   /*!
923    * \brief Builder of viscous layers
924    */
925   class _ViscousBuilder
926   {
927   public:
928     _ViscousBuilder();
929     // does it's job
930     SMESH_ComputeErrorPtr Compute(SMESH_Mesh&         mesh,
931                                   const TopoDS_Shape& shape);
932     // check validity of hypotheses
933     SMESH_ComputeErrorPtr CheckHypotheses( SMESH_Mesh&         mesh,
934                                            const TopoDS_Shape& shape );
935
936     // restore event listeners used to clear an inferior dim sub-mesh modified by viscous layers
937     void RestoreListeners();
938
939     // computes SMESH_ProxyMesh::SubMesh::_n2n;
940     bool MakeN2NMap( _MeshOfSolid* pm );
941
942   private:
943
944     bool findSolidsWithLayers(const bool checkFaceMesh=true);
945     bool setBefore( _SolidData& solidBefore, _SolidData& solidAfter );
946     bool findFacesWithLayers(const bool onlyWith=false);
947     void findPeriodicFaces();
948     void getIgnoreFaces(const TopoDS_Shape&             solid,
949                         const StdMeshers_ViscousLayers* hyp,
950                         const TopoDS_Shape&             hypShape,
951                         set<TGeomID>&                   ignoreFaces);
952     int makeEdgesOnShape();
953     bool makeLayer(_SolidData& data);
954     void setShapeData( _EdgesOnShape& eos, SMESH_subMesh* sm, _SolidData& data );
955     bool setEdgeData( _LayerEdge& edge, _EdgesOnShape& eos,
956                       SMESH_MesherHelper& helper, _SolidData& data);
957     gp_XYZ getFaceNormal(const SMDS_MeshNode* n,
958                          const TopoDS_Face&   face,
959                          SMESH_MesherHelper&  helper,
960                          bool&                isOK,
961                          bool                 shiftInside=false);
962     bool getFaceNormalAtSingularity(const gp_XY&        uv,
963                                     const TopoDS_Face&  face,
964                                     SMESH_MesherHelper& helper,
965                                     gp_Dir&             normal );
966     gp_XYZ getWeigthedNormal( const _LayerEdge*                edge );
967     gp_XYZ getNormalByOffset( _LayerEdge*                      edge,
968                               std::pair< TopoDS_Face, gp_XYZ > fId2Normal[],
969                               int                              nbFaces,
970                               bool                             lastNoOffset = false);
971     bool findNeiborsOnEdge(const _LayerEdge*     edge,
972                            const SMDS_MeshNode*& n1,
973                            const SMDS_MeshNode*& n2,
974                            _EdgesOnShape&        eos,
975                            _SolidData&           data);
976     void findSimplexTestEdges( _SolidData&                    data,
977                                vector< vector<_LayerEdge*> >& edgesByGeom);
978     void computeGeomSize( _SolidData& data );
979     bool findShapesToSmooth( _SolidData& data);
980     void limitStepSizeByCurvature( _SolidData&  data );
981     void limitStepSize( _SolidData&             data,
982                         const SMDS_MeshElement* face,
983                         const _LayerEdge*       maxCosinEdge );
984     void limitStepSize( _SolidData& data, const double minSize);
985     bool inflate(_SolidData& data);
986     bool smoothAndCheck(_SolidData& data, const int nbSteps, double & distToIntersection);
987     int  invalidateBadSmooth( _SolidData&               data,
988                               SMESH_MesherHelper&       helper,
989                               vector< _LayerEdge* >&    badSmooEdges,
990                               vector< _EdgesOnShape* >& eosC1,
991                               const int                 infStep );
992     void makeOffsetSurface( _EdgesOnShape& eos, SMESH_MesherHelper& );
993     void putOnOffsetSurface( _EdgesOnShape& eos, int infStep,
994                              vector< _EdgesOnShape* >& eosC1,
995                              int smooStep=0, int moveAll=false );
996     void findCollisionEdges( _SolidData& data, SMESH_MesherHelper& helper );
997     void findEdgesToUpdateNormalNearConvexFace( _ConvexFace &       convFace,
998                                                 _SolidData&         data,
999                                                 SMESH_MesherHelper& helper );
1000     void limitMaxLenByCurvature( _SolidData& data, SMESH_MesherHelper& helper );
1001     void limitMaxLenByCurvature( _LayerEdge* e1, _LayerEdge* e2,
1002                                  _EdgesOnShape& eos1, _EdgesOnShape& eos2,
1003                                  const bool isSmoothable );
1004     bool updateNormals( _SolidData& data, SMESH_MesherHelper& helper, int stepNb, double stepSize );
1005     bool updateNormalsOfConvexFaces( _SolidData&         data,
1006                                      SMESH_MesherHelper& helper,
1007                                      int                 stepNb );
1008     void updateNormalsOfC1Vertices( _SolidData& data );
1009     bool updateNormalsOfSmoothed( _SolidData&         data,
1010                                   SMESH_MesherHelper& helper,
1011                                   const int           nbSteps,
1012                                   const double        stepSize );
1013     bool isNewNormalOk( _SolidData&   data,
1014                         _LayerEdge&   edge,
1015                         const gp_XYZ& newNormal);
1016     bool refine(_SolidData& data);
1017     bool shrink(_SolidData& data);
1018     bool prepareEdgeToShrink( _LayerEdge& edge, _EdgesOnShape& eos,
1019                               SMESH_MesherHelper& helper,
1020                               const SMESHDS_SubMesh* faceSubMesh );
1021     void restoreNoShrink( _LayerEdge& edge ) const;
1022     void fixBadFaces(const TopoDS_Face&          F,
1023                      SMESH_MesherHelper&         helper,
1024                      const bool                  is2D,
1025                      const int                   step,
1026                      set<const SMDS_MeshNode*> * involvedNodes=NULL);
1027     bool addBoundaryElements(_SolidData& data);
1028
1029     bool error( const string& text, int solidID=-1 );
1030     SMESHDS_Mesh* getMeshDS() const { return _mesh->GetMeshDS(); }
1031
1032     // debug
1033     void makeGroupOfLE();
1034
1035     SMESH_Mesh*                  _mesh;
1036     SMESH_ComputeErrorPtr        _error;
1037
1038     vector<                      _SolidData >  _sdVec;
1039     TopTools_IndexedMapOfShape   _solids; // to find _SolidData by a solid
1040     TopTools_MapOfShape          _shrunkFaces;
1041     std::unique_ptr<Periodicity> _periodicity;
1042
1043     int                          _tmpFaceID;
1044     PyDump*                      _pyDump;
1045   };
1046   //--------------------------------------------------------------------------------
1047   /*!
1048    * \brief Shrinker of nodes on the EDGE
1049    */
1050   class _Shrinker1D
1051   {
1052     TopoDS_Edge                   _geomEdge;
1053     vector<double>                _initU;
1054     vector<double>                _normPar;
1055     vector<const SMDS_MeshNode*>  _nodes;
1056     const _LayerEdge*             _edges[2];
1057     bool                          _done;
1058   public:
1059     void AddEdge( const _LayerEdge* e, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
1060     void Compute(bool set3D, SMESH_MesherHelper& helper);
1061     void RestoreParams();
1062     void SwapSrcTgtNodes(SMESHDS_Mesh* mesh);
1063     const TopoDS_Edge& GeomEdge() const { return _geomEdge; }
1064     const SMDS_MeshNode* TgtNode( bool is2nd ) const
1065     { return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0; }
1066     const SMDS_MeshNode* SrcNode( bool is2nd ) const
1067     { return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0; }
1068   };
1069   //--------------------------------------------------------------------------------
1070   /*!
1071    * \brief Smoother of _LayerEdge's on EDGE.
1072    */
1073   struct _Smoother1D
1074   {
1075     struct OffPnt // point of the offsetted EDGE
1076     {
1077       gp_XYZ      _xyz;    // coord of a point inflated from EDGE w/o smooth
1078       double      _len;    // length reached at previous inflation step
1079       double      _param;  // on EDGE
1080       _2NearEdges _2edges; // 2 neighbor _LayerEdge's
1081       gp_XYZ      _edgeDir;// EDGE tangent at _param
1082       double Distance( const OffPnt& p ) const { return ( _xyz - p._xyz ).Modulus(); }
1083     };
1084     vector< OffPnt >   _offPoints;
1085     vector< double >   _leParams; // normalized param of _eos._edges on EDGE
1086     Handle(Geom_Curve) _anaCurve; // for analytic smooth
1087     _LayerEdge         _leOnV[2]; // _LayerEdge's holding normal to the EDGE at VERTEXes
1088     gp_XYZ             _edgeDir[2]; // tangent at VERTEXes
1089     size_t             _iSeg[2];  // index of segment where extreme tgt node is projected
1090     _EdgesOnShape&     _eos;
1091     double             _curveLen; // length of the EDGE
1092     std::pair<int,int> _eToSmooth[2]; // <from,to> indices of _LayerEdge's in _eos
1093
1094     static Handle(Geom_Curve) CurveForSmooth( const TopoDS_Edge&  E,
1095                                               _EdgesOnShape&      eos,
1096                                               SMESH_MesherHelper& helper);
1097
1098     _Smoother1D( Handle(Geom_Curve) curveForSmooth,
1099                  _EdgesOnShape&     eos )
1100       : _anaCurve( curveForSmooth ), _eos( eos )
1101     {
1102     }
1103     bool Perform(_SolidData&                    data,
1104                  Handle(ShapeAnalysis_Surface)& surface,
1105                  const TopoDS_Face&             F,
1106                  SMESH_MesherHelper&            helper );
1107
1108     void prepare(_SolidData& data );
1109
1110     void findEdgesToSmooth();
1111
1112     bool isToSmooth( int iE );
1113
1114     bool smoothAnalyticEdge( _SolidData&                    data,
1115                              Handle(ShapeAnalysis_Surface)& surface,
1116                              const TopoDS_Face&             F,
1117                              SMESH_MesherHelper&            helper);
1118     bool smoothComplexEdge( _SolidData&                     data,
1119                             Handle(ShapeAnalysis_Surface)& surface,
1120                             const TopoDS_Face&             F,
1121                             SMESH_MesherHelper&            helper);
1122     gp_XYZ getNormalNormal( const gp_XYZ & normal,
1123                             const gp_XYZ&  edgeDir);
1124     _LayerEdge* getLEdgeOnV( bool is2nd )
1125     {
1126       return _eos._edges[ is2nd ? _eos._edges.size()-1 : 0 ]->_2neibors->_edges[ is2nd ];
1127     }
1128     bool isAnalytic() const { return !_anaCurve.IsNull(); }
1129
1130     void offPointsToPython() const; // debug
1131   };
1132
1133   //--------------------------------------------------------------------------------
1134   /*!
1135    * \brief Compute positions of nodes of 2D structured mesh using TFI
1136    */
1137   class _Mapper2D
1138   {
1139     FaceQuadStruct _quadPoints;
1140
1141     UVPtStruct& uvPnt( size_t i, size_t j ) { return _quadPoints.UVPt( i, j ); }
1142
1143   public:
1144     _Mapper2D( const TParam2ColumnMap & param2ColumnMap, const TNode2Edge& n2eMap );
1145     bool ComputeNodePositions();
1146   };
1147
1148   //--------------------------------------------------------------------------------
1149   /*!
1150    * \brief Class of temporary mesh face.
1151    * We can't use SMDS_FaceOfNodes since it's impossible to set it's ID which is
1152    * needed because SMESH_ElementSearcher internally uses set of elements sorted by ID
1153    */
1154   struct _TmpMeshFace : public SMDS_PolygonalFaceOfNodes
1155   {
1156     const SMDS_MeshElement* _srcFace;
1157
1158     _TmpMeshFace( const vector<const SMDS_MeshNode*>& nodes,
1159                   int                                 ID,
1160                   int                                 faceID=-1,
1161                   const SMDS_MeshElement*             srcFace=0 ):
1162       SMDS_PolygonalFaceOfNodes(nodes), _srcFace( srcFace ) { setID( ID ); setShapeID( faceID ); }
1163     virtual SMDSAbs_EntityType  GetEntityType() const
1164     { return _srcFace ? _srcFace->GetEntityType() : SMDSEntity_Quadrangle; }
1165     virtual SMDSAbs_GeometryType GetGeomType()  const
1166     { return _srcFace ? _srcFace->GetGeomType() : SMDSGeom_QUADRANGLE; }
1167   };
1168   //--------------------------------------------------------------------------------
1169   /*!
1170    * \brief Class of temporary mesh quadrangle face storing _LayerEdge it's based on
1171    */
1172   struct _TmpMeshFaceOnEdge : public _TmpMeshFace
1173   {
1174     _LayerEdge *_le1, *_le2;
1175     _TmpMeshFaceOnEdge( _LayerEdge* le1, _LayerEdge* le2, int ID ):
1176       _TmpMeshFace( vector<const SMDS_MeshNode*>(4), ID ), _le1(le1), _le2(le2)
1177     {
1178       myNodes[0]=_le1->_nodes[0];
1179       myNodes[1]=_le1->_nodes.back();
1180       myNodes[2]=_le2->_nodes.back();
1181       myNodes[3]=_le2->_nodes[0];
1182     }
1183     const SMDS_MeshNode* n( size_t i ) const
1184     {
1185       return myNodes[ i ];
1186     }
1187     gp_XYZ GetDir() const // return average direction of _LayerEdge's, normal to EDGE
1188     {
1189       SMESH_TNodeXYZ p0s( myNodes[0] );
1190       SMESH_TNodeXYZ p0t( myNodes[1] );
1191       SMESH_TNodeXYZ p1t( myNodes[2] );
1192       SMESH_TNodeXYZ p1s( myNodes[3] );
1193       gp_XYZ  v0 = p0t - p0s;
1194       gp_XYZ  v1 = p1t - p1s;
1195       gp_XYZ v01 = p1s - p0s;
1196       gp_XYZ   n = ( v0 ^ v01 ) + ( v1 ^ v01 );
1197       gp_XYZ   d = v01 ^ n;
1198       d.Normalize();
1199       return d;
1200     }
1201     gp_XYZ GetDir(_LayerEdge* le1, _LayerEdge* le2) // return average direction of _LayerEdge's
1202     {
1203       myNodes[0]=le1->_nodes[0];
1204       myNodes[1]=le1->_nodes.back();
1205       myNodes[2]=le2->_nodes.back();
1206       myNodes[3]=le2->_nodes[0];
1207       return GetDir();
1208     }
1209   };
1210   //--------------------------------------------------------------------------------
1211   /*!
1212    * \brief Retriever of node coordinates either directly or from a surface by node UV.
1213    * \warning Location of a surface is ignored
1214    */
1215   struct _NodeCoordHelper
1216   {
1217     SMESH_MesherHelper&        _helper;
1218     const TopoDS_Face&         _face;
1219     Handle(Geom_Surface)       _surface;
1220     gp_XYZ (_NodeCoordHelper::* _fun)(const SMDS_MeshNode* n) const;
1221
1222     _NodeCoordHelper(const TopoDS_Face& F, SMESH_MesherHelper& helper, bool is2D)
1223       : _helper( helper ), _face( F )
1224     {
1225       if ( is2D )
1226       {
1227         TopLoc_Location loc;
1228         _surface = BRep_Tool::Surface( _face, loc );
1229       }
1230       if ( _surface.IsNull() )
1231         _fun = & _NodeCoordHelper::direct;
1232       else
1233         _fun = & _NodeCoordHelper::byUV;
1234     }
1235     gp_XYZ operator()(const SMDS_MeshNode* n) const { return (this->*_fun)( n ); }
1236
1237   private:
1238     gp_XYZ direct(const SMDS_MeshNode* n) const
1239     {
1240       return SMESH_TNodeXYZ( n );
1241     }
1242     gp_XYZ byUV  (const SMDS_MeshNode* n) const
1243     {
1244       gp_XY uv = _helper.GetNodeUV( _face, n );
1245       return _surface->Value( uv.X(), uv.Y() ).XYZ();
1246     }
1247   };
1248
1249   //================================================================================
1250   /*!
1251    * \brief Check angle between vectors 
1252    */
1253   //================================================================================
1254
1255   inline bool isLessAngle( const gp_Vec& v1, const gp_Vec& v2, const double cos )
1256   {
1257     double dot = v1 * v2; // cos * |v1| * |v2|
1258     double l1  = v1.SquareMagnitude();
1259     double l2  = v2.SquareMagnitude();
1260     return (( dot * cos >= 0 ) && 
1261             ( dot * dot ) / l1 / l2 >= ( cos * cos ));
1262   }
1263
1264   class _Factory
1265   {
1266     ObjectPool< _LayerEdge >  _edgePool;
1267     ObjectPool< _Curvature >  _curvaturePool;
1268     ObjectPool< _2NearEdges > _nearEdgesPool;
1269
1270     static _Factory* & me()
1271     {
1272       static _Factory* theFactory = 0;
1273       return theFactory;
1274     }
1275   public:
1276
1277     _Factory()  { me() = this; }
1278     ~_Factory() { me() = 0; }
1279
1280     static _LayerEdge*  NewLayerEdge() { return me()->_edgePool.getNew(); }
1281     static _Curvature * NewCurvature() { return me()->_curvaturePool.getNew(); }
1282     static _2NearEdges* NewNearEdges() { return me()->_nearEdgesPool.getNew(); }
1283   };
1284
1285 } // namespace VISCOUS_3D
1286
1287
1288
1289 //================================================================================
1290 // StdMeshers_ViscousLayers hypothesis
1291 //
1292 StdMeshers_ViscousLayers::StdMeshers_ViscousLayers(int hypId, SMESH_Gen* gen)
1293   :SMESH_Hypothesis(hypId, gen),
1294    _isToIgnoreShapes(1), _nbLayers(1), _thickness(1), _stretchFactor(1),
1295    _method( SURF_OFFSET_SMOOTH ),
1296    _groupName("")
1297 {
1298   _name = StdMeshers_ViscousLayers::GetHypType();
1299   _param_algo_dim = -3; // auxiliary hyp used by 3D algos
1300 } // --------------------------------------------------------------------------------
1301 void StdMeshers_ViscousLayers::SetBndShapes(const std::vector<int>& faceIds, bool toIgnore)
1302 {
1303   if ( faceIds != _shapeIds )
1304     _shapeIds = faceIds, NotifySubMeshesHypothesisModification();
1305   if ( _isToIgnoreShapes != toIgnore )
1306     _isToIgnoreShapes = toIgnore, NotifySubMeshesHypothesisModification();
1307 } // --------------------------------------------------------------------------------
1308 void StdMeshers_ViscousLayers::SetTotalThickness(double thickness)
1309 {
1310   if ( thickness != _thickness )
1311     _thickness = thickness, NotifySubMeshesHypothesisModification();
1312 } // --------------------------------------------------------------------------------
1313 void StdMeshers_ViscousLayers::SetNumberLayers(int nb)
1314 {
1315   if ( _nbLayers != nb )
1316     _nbLayers = nb, NotifySubMeshesHypothesisModification();
1317 } // --------------------------------------------------------------------------------
1318 void StdMeshers_ViscousLayers::SetStretchFactor(double factor)
1319 {
1320   if ( _stretchFactor != factor )
1321     _stretchFactor = factor, NotifySubMeshesHypothesisModification();
1322 } // --------------------------------------------------------------------------------
1323 void StdMeshers_ViscousLayers::SetMethod( ExtrusionMethod method )
1324 {
1325   if ( _method != method )
1326     _method = method, NotifySubMeshesHypothesisModification();
1327 } // --------------------------------------------------------------------------------
1328 void StdMeshers_ViscousLayers::SetGroupName(const std::string& name)
1329 {
1330   if ( _groupName != name )
1331   {
1332     _groupName = name;
1333     if ( !_groupName.empty() )
1334       NotifySubMeshesHypothesisModification();
1335   }
1336 } // --------------------------------------------------------------------------------
1337 SMESH_ProxyMesh::Ptr
1338 StdMeshers_ViscousLayers::Compute(SMESH_Mesh&         theMesh,
1339                                   const TopoDS_Shape& theShape,
1340                                   const bool          toMakeN2NMap) const
1341 {
1342   using namespace VISCOUS_3D;
1343   _ViscousBuilder builder;
1344   SMESH_ComputeErrorPtr err = builder.Compute( theMesh, theShape );
1345   if ( err && !err->IsOK() )
1346     return SMESH_ProxyMesh::Ptr();
1347
1348   vector<SMESH_ProxyMesh::Ptr> components;
1349   TopExp_Explorer exp( theShape, TopAbs_SOLID );
1350   for ( ; exp.More(); exp.Next() )
1351   {
1352     if ( _MeshOfSolid* pm =
1353          _ViscousListener::GetSolidMesh( &theMesh, exp.Current(), /*toCreate=*/false))
1354     {
1355       if ( toMakeN2NMap && !pm->_n2nMapComputed )
1356         if ( !builder.MakeN2NMap( pm ))
1357           return SMESH_ProxyMesh::Ptr();
1358       components.push_back( SMESH_ProxyMesh::Ptr( pm ));
1359       pm->myIsDeletable = false; // it will de deleted by boost::shared_ptr
1360
1361       if ( pm->_warning && !pm->_warning->IsOK() )
1362       {
1363         SMESH_subMesh* sm = theMesh.GetSubMesh( exp.Current() );
1364         SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1365         if ( !smError || smError->IsOK() )
1366           smError = pm->_warning;
1367       }
1368     }
1369     _ViscousListener::RemoveSolidMesh ( &theMesh, exp.Current() );
1370   }
1371   switch ( components.size() )
1372   {
1373   case 0: break;
1374
1375   case 1: return components[0];
1376
1377   default: return SMESH_ProxyMesh::Ptr( new SMESH_ProxyMesh( components ));
1378   }
1379   return SMESH_ProxyMesh::Ptr();
1380 } // --------------------------------------------------------------------------------
1381 std::ostream & StdMeshers_ViscousLayers::SaveTo(std::ostream & save)
1382 {
1383   save << " " << _nbLayers
1384        << " " << _thickness
1385        << " " << _stretchFactor
1386        << " " << _shapeIds.size();
1387   for ( size_t i = 0; i < _shapeIds.size(); ++i )
1388     save << " " << _shapeIds[i];
1389   save << " " << !_isToIgnoreShapes; // negate to keep the behavior in old studies.
1390   save << " " << _method;
1391   save << " " << _groupName.size();
1392   if ( !_groupName.empty() )
1393     save << " " << _groupName;
1394   return save;
1395 } // --------------------------------------------------------------------------------
1396 std::istream & StdMeshers_ViscousLayers::LoadFrom(std::istream & load)
1397 {
1398   int nbFaces, faceID, shapeToTreat, method;
1399   load >> _nbLayers >> _thickness >> _stretchFactor >> nbFaces;
1400   while ( (int) _shapeIds.size() < nbFaces && load >> faceID )
1401     _shapeIds.push_back( faceID );
1402   if ( load >> shapeToTreat ) {
1403     _isToIgnoreShapes = !shapeToTreat;
1404     if ( load >> method )
1405       _method = (ExtrusionMethod) method;
1406     int nameSize = 0;
1407     if ( load >> nameSize && nameSize > 0 )
1408     {
1409       _groupName.resize( nameSize );
1410       load.get( _groupName[0] ); // remove a white-space
1411       load.getline( &_groupName[0], nameSize + 1 );
1412     }
1413   }
1414   else {
1415     _isToIgnoreShapes = true; // old behavior
1416   }
1417   return load;
1418 } // --------------------------------------------------------------------------------
1419 bool StdMeshers_ViscousLayers::SetParametersByMesh(const SMESH_Mesh*   /*theMesh*/,
1420                                                    const TopoDS_Shape& /*theShape*/)
1421 {
1422   // TODO
1423   return false;
1424 } // --------------------------------------------------------------------------------
1425 SMESH_ComputeErrorPtr
1426 StdMeshers_ViscousLayers::CheckHypothesis(SMESH_Mesh&                          theMesh,
1427                                           const TopoDS_Shape&                  theShape,
1428                                           SMESH_Hypothesis::Hypothesis_Status& theStatus)
1429 {
1430   VISCOUS_3D::_ViscousBuilder builder;
1431   SMESH_ComputeErrorPtr err = builder.CheckHypotheses( theMesh, theShape );
1432   if ( err && !err->IsOK() )
1433     theStatus = SMESH_Hypothesis::HYP_INCOMPAT_HYPS;
1434   else
1435     theStatus = SMESH_Hypothesis::HYP_OK;
1436
1437   return err;
1438 }
1439 // --------------------------------------------------------------------------------
1440 bool StdMeshers_ViscousLayers::IsShapeWithLayers(int shapeIndex) const
1441 {
1442   bool isIn =
1443     ( std::find( _shapeIds.begin(), _shapeIds.end(), shapeIndex ) != _shapeIds.end() );
1444   return IsToIgnoreShapes() ? !isIn : isIn;
1445 }
1446
1447 // --------------------------------------------------------------------------------
1448 SMDS_MeshGroup* StdMeshers_ViscousLayers::CreateGroup( const std::string&  theName,
1449                                                        SMESH_Mesh&         theMesh,
1450                                                        SMDSAbs_ElementType theType)
1451 {
1452   SMESH_Group*      group = 0;
1453   SMDS_MeshGroup* groupDS = 0;
1454
1455   if ( theName.empty() )
1456     return groupDS;
1457        
1458   if ( SMESH_Mesh::GroupIteratorPtr grIt = theMesh.GetGroups() )
1459     while( grIt->more() && !group )
1460     {
1461       group = grIt->next();
1462       if ( !group ||
1463            group->GetGroupDS()->GetType() != theType ||
1464            group->GetName()               != theName ||
1465            !dynamic_cast< SMESHDS_Group* >( group->GetGroupDS() ))
1466         group = 0;
1467     }
1468   if ( !group )
1469     group = theMesh.AddGroup( theType, theName.c_str() );
1470
1471   groupDS = & dynamic_cast< SMESHDS_Group* >( group->GetGroupDS() )->SMDSGroup();
1472
1473   return groupDS;
1474 }
1475
1476 // END StdMeshers_ViscousLayers hypothesis
1477 //================================================================================
1478
1479 namespace VISCOUS_3D
1480 {
1481   gp_XYZ getEdgeDir( const TopoDS_Edge& E, const TopoDS_Vertex& fromV,
1482                      const double h0, bool* isRegularEdge = nullptr )
1483   {
1484     gp_Vec dir;
1485     double f,l;
1486     Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1487     if ( c.IsNull() ) return gp_XYZ( Precision::Infinite(), 1e100, 1e100 );
1488     gp_Pnt  p = BRep_Tool::Pnt( fromV );
1489     gp_Pnt pf = c->Value( f ), pl = c->Value( l );
1490     double distF = p.SquareDistance( pf );
1491     double distL = p.SquareDistance( pl );
1492     c->D1(( distF < distL ? f : l), p, dir );
1493     if ( distL < distF ) dir.Reverse();
1494     bool isDifficult = false;
1495     if ( dir.SquareMagnitude() < h0 * h0 ) // check dir orientation
1496     {
1497       gp_Pnt& pClose = distF < distL ? pf : pl;
1498       gp_Pnt&   pFar = distF < distL ? pl : pf;
1499       gp_Pnt    pMid = 0.9 * pClose.XYZ() + 0.1 * pFar.XYZ();
1500       gp_Vec vMid( p, pMid );
1501       double     dot = vMid * dir;
1502       double    cos2 = dot * dot / dir.SquareMagnitude() / vMid.SquareMagnitude();
1503       if ( cos2 < 0.7 * 0.7 || dot < 0 ) // large angle between dir and vMid
1504       {
1505         double uClose = distF < distL ? f : l;
1506         double   uFar = distF < distL ? l : f;
1507         double      r = h0 / SMESH_Algo::EdgeLength( E );
1508         double   uMid = ( 1 - r ) * uClose + r * uFar;
1509         pMid = c->Value( uMid );
1510         dir = gp_Vec( p, pMid );
1511         isDifficult = true;
1512       }
1513     }
1514     if ( isRegularEdge )
1515       *isRegularEdge = !isDifficult;
1516
1517     return dir.XYZ();
1518   }
1519   //--------------------------------------------------------------------------------
1520   gp_XYZ getEdgeDir( const TopoDS_Edge& E, const SMDS_MeshNode* atNode,
1521                      SMESH_MesherHelper& helper)
1522   {
1523     gp_Vec dir;
1524     double f,l; gp_Pnt p;
1525     Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1526     if ( c.IsNull() ) return gp_XYZ( Precision::Infinite(), 1e100, 1e100 );
1527     double u = helper.GetNodeU( E, atNode );
1528     c->D1( u, p, dir );
1529     return dir.XYZ();
1530   }
1531   //--------------------------------------------------------------------------------
1532   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1533                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok/*,
1534                      double* cosin=0*/);
1535   //--------------------------------------------------------------------------------
1536   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Edge& fromE,
1537                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok)
1538   {
1539     double f,l;
1540     Handle(Geom_Curve) c = BRep_Tool::Curve( fromE, f, l );
1541     if ( c.IsNull() )
1542     {
1543       TopoDS_Vertex v = helper.IthVertex( 0, fromE );
1544       return getFaceDir( F, v, node, helper, ok );
1545     }
1546     gp_XY uv = helper.GetNodeUV( F, node, 0, &ok );
1547     Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
1548     gp_Pnt p; gp_Vec du, dv, norm;
1549     surface->D1( uv.X(),uv.Y(), p, du,dv );
1550     norm = du ^ dv;
1551
1552     double u = helper.GetNodeU( fromE, node, 0, &ok );
1553     c->D1( u, p, du );
1554     TopAbs_Orientation o = helper.GetSubShapeOri( F.Oriented(TopAbs_FORWARD), fromE);
1555     if ( o == TopAbs_REVERSED )
1556       du.Reverse();
1557
1558     gp_Vec dir = norm ^ du;
1559
1560     if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX &&
1561          helper.IsClosedEdge( fromE ))
1562     {
1563       if ( fabs(u-f) < fabs(u-l)) c->D1( l, p, dv );
1564       else                        c->D1( f, p, dv );
1565       if ( o == TopAbs_REVERSED )
1566         dv.Reverse();
1567       gp_Vec dir2 = norm ^ dv;
1568       dir = dir.Normalized() + dir2.Normalized();
1569     }
1570     return dir.XYZ();
1571   }
1572   //--------------------------------------------------------------------------------
1573   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1574                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper,
1575                      bool& ok/*, double* cosin*/)
1576   {
1577     TopoDS_Face faceFrw = F;
1578     faceFrw.Orientation( TopAbs_FORWARD );
1579     //double f,l; TopLoc_Location loc;
1580     TopoDS_Edge edges[2]; // sharing a vertex
1581     size_t nbEdges = 0;
1582     {
1583       TopoDS_Vertex VV[2];
1584       TopExp_Explorer exp( faceFrw, TopAbs_EDGE );
1585       for ( ; exp.More() && nbEdges < 2; exp.Next() )
1586       {
1587         const TopoDS_Edge& e = TopoDS::Edge( exp.Current() );
1588         if ( SMESH_Algo::isDegenerated( e )) continue;
1589         TopExp::Vertices( e, VV[0], VV[1], /*CumOri=*/true );
1590         if ( VV[1].IsSame( fromV )) {
1591           nbEdges += edges[ 0 ].IsNull();
1592           edges[ 0 ] = e;
1593         }
1594         else if ( VV[0].IsSame( fromV )) {
1595           nbEdges += edges[ 1 ].IsNull();
1596           edges[ 1 ] = e;
1597         }
1598       }
1599     }
1600     gp_XYZ dir(0,0,0), edgeDir[2];
1601     if ( nbEdges == 2 )
1602     {
1603       // get dirs of edges going fromV
1604       ok = true;
1605       for ( size_t i = 0; i < nbEdges && ok; ++i )
1606       {
1607         edgeDir[i] = getEdgeDir( edges[i], fromV, 0.1 * SMESH_Algo::EdgeLength( edges[i] ));
1608         double size2 = edgeDir[i].SquareModulus();
1609         if (( ok = size2 > numeric_limits<double>::min() ))
1610           edgeDir[i] /= sqrt( size2 );
1611       }
1612       if ( !ok ) return dir;
1613
1614       // get angle between the 2 edges
1615       gp_Vec faceNormal;
1616       double angle = helper.GetAngle( edges[0], edges[1], faceFrw, fromV, &faceNormal );
1617       if ( Abs( angle ) < 5 * M_PI/180 )
1618       {
1619         dir = ( faceNormal.XYZ() ^ edgeDir[0].Reversed()) + ( faceNormal.XYZ() ^ edgeDir[1] );
1620       }
1621       else
1622       {
1623         dir = edgeDir[0] + edgeDir[1];
1624         if ( angle < 0 )
1625           dir.Reverse();
1626       }
1627       // if ( cosin ) {
1628       //   double angle = faceNormal.Angle( dir );
1629       //   *cosin = Cos( angle );
1630       // }
1631     }
1632     else if ( nbEdges == 1 )
1633     {
1634       dir = getFaceDir( faceFrw, edges[ edges[0].IsNull() ], node, helper, ok );
1635       //if ( cosin ) *cosin = 1.;
1636     }
1637     else
1638     {
1639       ok = false;
1640     }
1641
1642     return dir;
1643   }
1644
1645   //================================================================================
1646   /*!
1647    * \brief Finds concave VERTEXes of a FACE
1648    */
1649   //================================================================================
1650
1651   bool getConcaveVertices( const TopoDS_Face&  F,
1652                            SMESH_MesherHelper& helper,
1653                            set< TGeomID >*     vertices = 0)
1654   {
1655     // check angles at VERTEXes
1656     TError error;
1657     TSideVector wires = StdMeshers_FaceSide::GetFaceWires( F, *helper.GetMesh(), 0, error );
1658     for ( size_t iW = 0; iW < wires.size(); ++iW )
1659     {
1660       const int nbEdges = wires[iW]->NbEdges();
1661       if ( nbEdges < 2 && SMESH_Algo::isDegenerated( wires[iW]->Edge(0)))
1662         continue;
1663       for ( int iE1 = 0; iE1 < nbEdges; ++iE1 )
1664       {
1665         if ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE1 ))) continue;
1666         int iE2 = ( iE1 + 1 ) % nbEdges;
1667         while ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE2 )))
1668           iE2 = ( iE2 + 1 ) % nbEdges;
1669         TopoDS_Vertex V = wires[iW]->FirstVertex( iE2 );
1670         double angle = helper.GetAngle( wires[iW]->Edge( iE1 ),
1671                                         wires[iW]->Edge( iE2 ), F, V );
1672         if ( angle < -5. * M_PI / 180. )
1673         {
1674           if ( !vertices )
1675             return true;
1676           vertices->insert( helper.GetMeshDS()->ShapeToIndex( V ));
1677         }
1678       }
1679     }
1680     return vertices ? !vertices->empty() : false;
1681   }
1682
1683   //================================================================================
1684   /*!
1685    * \brief Returns true if a FACE is bound by a concave EDGE
1686    */
1687   //================================================================================
1688
1689   bool isConcave( const TopoDS_Face&  F,
1690                   SMESH_MesherHelper& helper,
1691                   set< TGeomID >*     vertices = 0 )
1692   {
1693     bool isConcv = false;
1694     // if ( helper.Count( F, TopAbs_WIRE, /*useMap=*/false) > 1 )
1695     //   return true;
1696     gp_Vec2d drv1, drv2;
1697     gp_Pnt2d p;
1698     TopExp_Explorer eExp( F.Oriented( TopAbs_FORWARD ), TopAbs_EDGE );
1699     for ( ; eExp.More(); eExp.Next() )
1700     {
1701       const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
1702       if ( SMESH_Algo::isDegenerated( E )) continue;
1703       // check if 2D curve is concave
1704       BRepAdaptor_Curve2d curve( E, F );
1705       const int nbIntervals = curve.NbIntervals( GeomAbs_C2 );
1706       TColStd_Array1OfReal intervals(1, nbIntervals + 1 );
1707       curve.Intervals( intervals, GeomAbs_C2 );
1708       bool isConvex = true;
1709       for ( int i = 1; i <= nbIntervals && isConvex; ++i )
1710       {
1711         double u1 = intervals( i );
1712         double u2 = intervals( i+1 );
1713         curve.D2( 0.5*( u1+u2 ), p, drv1, drv2 );
1714         double cross = drv1 ^ drv2;
1715         if ( E.Orientation() == TopAbs_REVERSED )
1716           cross = -cross;
1717         isConvex = ( cross > -1e-9 ); // 0.1 );
1718       }
1719       if ( !isConvex )
1720       {
1721         //cout << "Concave FACE " << helper.GetMeshDS()->ShapeToIndex( F ) << endl;
1722         isConcv = true;
1723         if ( vertices )
1724           break;
1725         else
1726           return true;
1727       }
1728     }
1729
1730     // check angles at VERTEXes
1731     if ( getConcaveVertices( F, helper, vertices ))
1732       isConcv = true;
1733
1734     return isConcv;
1735   }
1736
1737   //================================================================================
1738   /*!
1739    * \brief Computes minimal distance of face in-FACE nodes from an EDGE
1740    *  \param [in] face - the mesh face to treat
1741    *  \param [in] nodeOnEdge - a node on the EDGE
1742    *  \param [out] faceSize - the computed distance
1743    *  \return bool - true if faceSize computed
1744    */
1745   //================================================================================
1746
1747   bool getDistFromEdge( const SMDS_MeshElement* face,
1748                         const SMDS_MeshNode*    nodeOnEdge,
1749                         double &                faceSize )
1750   {
1751     faceSize = Precision::Infinite();
1752     bool done = false;
1753
1754     int nbN  = face->NbCornerNodes();
1755     int iOnE = face->GetNodeIndex( nodeOnEdge );
1756     int iNext[2] = { SMESH_MesherHelper::WrapIndex( iOnE+1, nbN ),
1757                      SMESH_MesherHelper::WrapIndex( iOnE-1, nbN ) };
1758     const SMDS_MeshNode* nNext[2] = { face->GetNode( iNext[0] ),
1759                                       face->GetNode( iNext[1] ) };
1760     gp_XYZ segVec, segEnd = SMESH_TNodeXYZ( nodeOnEdge ); // segment on EDGE
1761     double segLen = -1.;
1762     // look for two neighbor not in-FACE nodes of face
1763     for ( int i = 0; i < 2; ++i )
1764     {
1765       if (( nNext[i]->GetPosition()->GetDim() != 2 ) &&
1766           ( nodeOnEdge->GetPosition()->GetDim() == 0 || nNext[i]->GetID() < nodeOnEdge->GetID() ))
1767       {
1768         // look for an in-FACE node
1769         for ( int iN = 0; iN < nbN; ++iN )
1770         {
1771           if ( iN == iOnE || iN == iNext[i] )
1772             continue;
1773           SMESH_TNodeXYZ pInFace = face->GetNode( iN );
1774           gp_XYZ v = pInFace - segEnd;
1775           if ( segLen < 0 )
1776           {
1777             segVec = SMESH_TNodeXYZ( nNext[i] ) - segEnd;
1778             segLen = segVec.Modulus();
1779           }
1780           double distToSeg = v.Crossed( segVec ).Modulus() / segLen;
1781           faceSize = Min( faceSize, distToSeg );
1782           done = true;
1783         }
1784         segLen = -1;
1785       }
1786     }
1787     return done;
1788   }
1789   //================================================================================
1790   /*!
1791    * \brief Return direction of axis or revolution of a surface
1792    */
1793   //================================================================================
1794
1795   bool getRovolutionAxis( const Adaptor3d_Surface& surface,
1796                           gp_Dir &                 axis )
1797   {
1798     switch ( surface.GetType() ) {
1799     case GeomAbs_Cone:
1800     {
1801       gp_Cone cone = surface.Cone();
1802       axis = cone.Axis().Direction();
1803       break;
1804     }
1805     case GeomAbs_Sphere:
1806     {
1807       gp_Sphere sphere = surface.Sphere();
1808       axis = sphere.Position().Direction();
1809       break;
1810     }
1811     case GeomAbs_SurfaceOfRevolution:
1812     {
1813       axis = surface.AxeOfRevolution().Direction();
1814       break;
1815     }
1816     //case GeomAbs_SurfaceOfExtrusion:
1817     case GeomAbs_OffsetSurface:
1818     {
1819       Handle(Adaptor3d_HSurface) base = surface.BasisSurface();
1820       return getRovolutionAxis( base->Surface(), axis );
1821     }
1822     default: return false;
1823     }
1824     return true;
1825   }
1826
1827   //--------------------------------------------------------------------------------
1828   // DEBUG. Dump intermediate node positions into a python script
1829   // HOWTO use: run python commands written in a console and defined in /tmp/viscous.py
1830   // to see construction steps of viscous layers
1831 #ifdef __myDEBUG
1832   ostream* py;
1833   int      theNbPyFunc;
1834   struct PyDump
1835   {
1836     PyDump(SMESH_Mesh& m) {
1837       int tag = 3 + m.GetId();
1838       const char* fname = "/tmp/viscous.py";
1839       cout << "exec(open('"<<fname<<"','rb').read() )"<<endl;
1840       py = _pyStream = new ofstream(fname);
1841       *py << "import SMESH" << endl
1842           << "from salome.smesh import smeshBuilder" << endl
1843           << "smesh  = smeshBuilder.New()" << endl
1844           << "meshSO = salome.myStudy.FindObjectID('0:1:2:" << tag <<"')" << endl
1845           << "mesh   = smesh.Mesh( meshSO.GetObject() )"<<endl;
1846       theNbPyFunc = 0;
1847     }
1848     void Finish() {
1849       if (py) {
1850         *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Viscous Prisms',"
1851           "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_ElemGeomType,'=',SMESH.Geom_PENTA))"<<endl;
1852         *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Neg Volumes',"
1853           "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_Volume3D,'<',0))"<<endl;
1854       }
1855       delete py; py=0;
1856     }
1857     ~PyDump() { Finish(); cout << "NB FUNCTIONS: " << theNbPyFunc << endl; }
1858     struct MyStream : public ostream
1859     {
1860       template <class T> ostream & operator<<( const T &anything ) { return *this ; }
1861     };
1862     void Pause() { py = &_mystream; }
1863     void Resume() { py = _pyStream; }
1864     MyStream _mystream;
1865     ostream* _pyStream;
1866   };
1867 #define dumpFunction(f) { _dumpFunction(f, __LINE__);}
1868 #define dumpMove(n)     { _dumpMove(n, __LINE__);}
1869 #define dumpMoveComm(n,txt) { _dumpMove(n, __LINE__, txt);}
1870 #define dumpCmd(txt)    { _dumpCmd(txt, __LINE__);}
1871   void _dumpFunction(const string& fun, int ln)
1872   { if (py) *py<< "def "<<fun<<"(): # "<< ln <<endl; cout<<fun<<"()"<<endl; ++theNbPyFunc; }
1873   void _dumpMove(const SMDS_MeshNode* n, int ln, const char* txt="")
1874   { if (py) *py<< "  mesh.MoveNode( "<<n->GetID()<< ", "<< n->X()
1875                << ", "<<n->Y()<<", "<< n->Z()<< ")\t\t # "<< ln <<" "<< txt << endl; }
1876   void _dumpCmd(const string& txt, int ln)
1877   { if (py) *py<< "  "<<txt<<" # "<< ln <<endl; }
1878   void dumpFunctionEnd()
1879   { if (py) *py<< "  return"<< endl; }
1880   void dumpChangeNodes( const SMDS_MeshElement* f )
1881   { if (py) { *py<< "  mesh.ChangeElemNodes( " << f->GetID()<<", [";
1882       for ( int i=1; i < f->NbNodes(); ++i ) *py << f->GetNode(i-1)->GetID()<<", ";
1883       *py << f->GetNode( f->NbNodes()-1 )->GetID() << " ])"<< endl; }}
1884 #define debugMsg( txt ) { cout << "# "<< txt << " (line: " << __LINE__ << ")" << endl; }
1885
1886 #else
1887
1888   struct PyDump { PyDump(SMESH_Mesh&) {} void Finish() {} void Pause() {} void Resume() {} };
1889 #define dumpFunction(f) f
1890 #define dumpMove(n)
1891 #define dumpMoveComm(n,txt)
1892 #define dumpCmd(txt)
1893 #define dumpFunctionEnd()
1894 #define dumpChangeNodes(f) { if(f) {} } // prevent "unused variable 'f'" warning
1895 #define debugMsg( txt ) {}
1896
1897 #endif
1898 }
1899
1900 using namespace VISCOUS_3D;
1901
1902 //================================================================================
1903 /*!
1904  * \brief Constructor of _ViscousBuilder
1905  */
1906 //================================================================================
1907
1908 _ViscousBuilder::_ViscousBuilder()
1909 {
1910   _error = SMESH_ComputeError::New(COMPERR_OK);
1911   _tmpFaceID = 0;
1912 }
1913
1914 //================================================================================
1915 /*!
1916  * \brief Stores error description and returns false
1917  */
1918 //================================================================================
1919
1920 bool _ViscousBuilder::error(const string& text, int solidId )
1921 {
1922   const string prefix = string("Viscous layers builder: ");
1923   _error->myName    = COMPERR_ALGO_FAILED;
1924   _error->myComment = prefix + text;
1925   if ( _mesh )
1926   {
1927     SMESH_subMesh* sm = _mesh->GetSubMeshContaining( solidId );
1928     if ( !sm && !_sdVec.empty() )
1929       sm = _mesh->GetSubMeshContaining( solidId = _sdVec[0]._index );
1930     if ( sm && sm->GetSubShape().ShapeType() == TopAbs_SOLID )
1931     {
1932       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1933       if ( smError && smError->myAlgo )
1934         _error->myAlgo = smError->myAlgo;
1935       smError = _error;
1936       sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1937     }
1938     // set KO to all solids
1939     for ( size_t i = 0; i < _sdVec.size(); ++i )
1940     {
1941       if ( _sdVec[i]._index == solidId )
1942         continue;
1943       sm = _mesh->GetSubMesh( _sdVec[i]._solid );
1944       if ( !sm->IsEmpty() )
1945         continue;
1946       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1947       if ( !smError || smError->IsOK() )
1948       {
1949         smError = SMESH_ComputeError::New( COMPERR_ALGO_FAILED, prefix + "failed");
1950         sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1951       }
1952     }
1953   }
1954   makeGroupOfLE(); // debug
1955
1956   return false;
1957 }
1958
1959 //================================================================================
1960 /*!
1961  * \brief At study restoration, restore event listeners used to clear an inferior
1962  *  dim sub-mesh modified by viscous layers
1963  */
1964 //================================================================================
1965
1966 void _ViscousBuilder::RestoreListeners()
1967 {
1968   // TODO
1969 }
1970
1971 //================================================================================
1972 /*!
1973  * \brief computes SMESH_ProxyMesh::SubMesh::_n2n
1974  */
1975 //================================================================================
1976
1977 bool _ViscousBuilder::MakeN2NMap( _MeshOfSolid* pm )
1978 {
1979   SMESH_subMesh* solidSM = pm->mySubMeshes.front();
1980   TopExp_Explorer fExp( solidSM->GetSubShape(), TopAbs_FACE );
1981   for ( ; fExp.More(); fExp.Next() )
1982   {
1983     SMESHDS_SubMesh* srcSmDS = pm->GetMeshDS()->MeshElements( fExp.Current() );
1984     const SMESH_ProxyMesh::SubMesh* prxSmDS = pm->GetProxySubMesh( fExp.Current() );
1985
1986     if ( !srcSmDS || !prxSmDS || !srcSmDS->NbElements() || !prxSmDS->NbElements() )
1987       continue;
1988     if ( srcSmDS->GetElements()->next() == prxSmDS->GetElements()->next())
1989       continue;
1990
1991     if ( srcSmDS->NbElements() != prxSmDS->NbElements() )
1992       return error( "Different nb elements in a source and a proxy sub-mesh", solidSM->GetId());
1993
1994     SMDS_ElemIteratorPtr srcIt = srcSmDS->GetElements();
1995     SMDS_ElemIteratorPtr prxIt = prxSmDS->GetElements();
1996     while( prxIt->more() )
1997     {
1998       const SMDS_MeshElement* fSrc = srcIt->next();
1999       const SMDS_MeshElement* fPrx = prxIt->next();
2000       if ( fSrc->NbNodes() != fPrx->NbNodes())
2001         return error( "Different elements in a source and a proxy sub-mesh", solidSM->GetId());
2002       for ( int i = 0 ; i < fPrx->NbNodes(); ++i )
2003         pm->setNode2Node( fSrc->GetNode(i), fPrx->GetNode(i), prxSmDS );
2004     }
2005   }
2006   pm->_n2nMapComputed = true;
2007   return true;
2008 }
2009
2010 //================================================================================
2011 /*!
2012  * \brief Does its job
2013  */
2014 //================================================================================
2015
2016 SMESH_ComputeErrorPtr _ViscousBuilder::Compute(SMESH_Mesh&         theMesh,
2017                                                const TopoDS_Shape& theShape)
2018 {
2019   _mesh = & theMesh;
2020
2021   _Factory factory;
2022
2023   // check if proxy mesh already computed
2024   TopExp_Explorer exp( theShape, TopAbs_SOLID );
2025   if ( !exp.More() )
2026     return error("No SOLID's in theShape"), _error;
2027
2028   if ( _ViscousListener::GetSolidMesh( _mesh, exp.Current(), /*toCreate=*/false))
2029     return SMESH_ComputeErrorPtr(); // everything already computed
2030
2031   // TODO: ignore already computed SOLIDs
2032   if ( !findSolidsWithLayers())
2033     return _error;
2034
2035   if ( !findFacesWithLayers() )
2036     return _error;
2037
2038   if ( !makeEdgesOnShape() )
2039     return _error;
2040
2041   findPeriodicFaces();
2042
2043   PyDump debugDump( theMesh );
2044   _pyDump = &debugDump;
2045
2046
2047   for ( size_t i = 0; i < _sdVec.size(); ++i )
2048   {
2049     size_t iSD = 0;
2050     for ( iSD = 0; iSD < _sdVec.size(); ++iSD ) // find next SOLID to compute
2051       if ( _sdVec[iSD]._before.IsEmpty() &&
2052            !_sdVec[iSD]._solid.IsNull() &&
2053            !_sdVec[iSD]._done )
2054         break;
2055     if ( iSD == _sdVec.size() )
2056       break; // all done
2057
2058     if ( ! makeLayer(_sdVec[iSD]) )   // create _LayerEdge's
2059       return _error;
2060
2061     if ( _sdVec[iSD]._n2eMap.size() == 0 ) // no layers in a SOLID
2062     {
2063       _sdVec[iSD]._solid.Nullify();
2064       continue;
2065     }
2066
2067     if ( ! inflate(_sdVec[iSD]) )     // increase length of _LayerEdge's
2068       return _error;
2069
2070     if ( ! refine(_sdVec[iSD]) )      // create nodes and prisms
2071       return _error;
2072
2073     if ( ! shrink(_sdVec[iSD]) )      // shrink 2D mesh on FACEs w/o layer
2074       return _error;
2075
2076     addBoundaryElements(_sdVec[iSD]); // create quadrangles on prism bare sides
2077
2078     _sdVec[iSD]._done = true;
2079
2080     const TopoDS_Shape& solid = _sdVec[iSD]._solid;
2081     for ( iSD = 0; iSD < _sdVec.size(); ++iSD )
2082       _sdVec[iSD]._before.Remove( solid );
2083   }
2084
2085   makeGroupOfLE(); // debug
2086   debugDump.Finish();
2087
2088   return _error;
2089 }
2090
2091 //================================================================================
2092 /*!
2093  * \brief Check validity of hypotheses
2094  */
2095 //================================================================================
2096
2097 SMESH_ComputeErrorPtr _ViscousBuilder::CheckHypotheses( SMESH_Mesh&         mesh,
2098                                                         const TopoDS_Shape& shape )
2099 {
2100   _mesh = & mesh;
2101
2102   if ( _ViscousListener::GetSolidMesh( _mesh, shape, /*toCreate=*/false))
2103     return SMESH_ComputeErrorPtr(); // everything already computed
2104
2105
2106   findSolidsWithLayers( /*checkFaceMesh=*/false );
2107   bool ok = findFacesWithLayers( true );
2108
2109   // remove _MeshOfSolid's of _SolidData's
2110   for ( size_t i = 0; i < _sdVec.size(); ++i )
2111     _ViscousListener::RemoveSolidMesh( _mesh, _sdVec[i]._solid );
2112
2113   if ( !ok )
2114     return _error;
2115
2116   return SMESH_ComputeErrorPtr();
2117 }
2118
2119 //================================================================================
2120 /*!
2121  * \brief Finds SOLIDs to compute using viscous layers. Fills _sdVec
2122  */
2123 //================================================================================
2124
2125 bool _ViscousBuilder::findSolidsWithLayers(const bool checkFaceMesh)
2126 {
2127   // get all solids
2128   TopTools_IndexedMapOfShape allSolids;
2129   TopExp::MapShapes( _mesh->GetShapeToMesh(), TopAbs_SOLID, allSolids );
2130   _sdVec.reserve( allSolids.Extent());
2131
2132   SMESH_HypoFilter filter;
2133   for ( int i = 1; i <= allSolids.Extent(); ++i )
2134   {
2135     SMESH_subMesh* sm = _mesh->GetSubMesh( allSolids(i) );
2136     if ( sm->GetSubMeshDS() && sm->GetSubMeshDS()->NbElements() > 0 )
2137       continue; // solid is already meshed
2138     // TODO: check if algo is hidden
2139     SMESH_Algo* algo = sm->GetAlgo();
2140     if ( !algo ) continue;
2141     // check if all FACEs are meshed, which can be false if Compute() a sub-shape
2142     if ( checkFaceMesh )
2143     {
2144       bool facesMeshed = true;
2145       SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(false,true);
2146       while ( smIt->more() && facesMeshed )
2147       {
2148         SMESH_subMesh * faceSM = smIt->next();
2149         if ( faceSM->GetSubShape().ShapeType() != TopAbs_FACE )
2150           break;
2151         facesMeshed = faceSM->IsMeshComputed();
2152       }
2153       if ( !facesMeshed )
2154         continue;
2155     }
2156     // find StdMeshers_ViscousLayers hyp assigned to the i-th solid
2157     const list <const SMESHDS_Hypothesis *> & allHyps =
2158       algo->GetUsedHypothesis(*_mesh, allSolids(i), /*ignoreAuxiliary=*/false);
2159     _SolidData* soData = 0;
2160     list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
2161     const StdMeshers_ViscousLayers* viscHyp = 0;
2162     for ( ; hyp != allHyps.end(); ++hyp )
2163       if (( viscHyp = dynamic_cast<const StdMeshers_ViscousLayers*>( *hyp )))
2164       {
2165         TopoDS_Shape hypShape;
2166         filter.Init( filter.Is( viscHyp ));
2167         _mesh->GetHypothesis( allSolids(i), filter, true, &hypShape );
2168
2169         if ( !soData )
2170         {
2171           _MeshOfSolid* proxyMesh = _ViscousListener::GetSolidMesh( _mesh,
2172                                                                     allSolids(i),
2173                                                                     /*toCreate=*/true);
2174           _sdVec.push_back( _SolidData( allSolids(i), proxyMesh ));
2175           soData = & _sdVec.back();
2176           soData->_index = getMeshDS()->ShapeToIndex( allSolids(i));
2177           soData->_helper = new SMESH_MesherHelper( *_mesh );
2178           soData->_helper->SetSubShape( allSolids(i) );
2179           _solids.Add( allSolids(i) );
2180         }
2181         soData->_hyps.push_back( viscHyp );
2182         soData->_hypShapes.push_back( hypShape );
2183       }
2184   }
2185   if ( _sdVec.empty() )
2186     return error
2187       ( SMESH_Comment(StdMeshers_ViscousLayers::GetHypType()) << " hypothesis not found",0);
2188
2189   return true;
2190 }
2191
2192 //================================================================================
2193 /*!
2194  * \brief Set a _SolidData to be computed before another
2195  */
2196 //================================================================================
2197
2198 bool _ViscousBuilder::setBefore( _SolidData& solidBefore, _SolidData& solidAfter )
2199 {
2200   // check possibility to set this order; get all solids before solidBefore
2201   TopTools_IndexedMapOfShape allSolidsBefore;
2202   allSolidsBefore.Add( solidBefore._solid );
2203   for ( int i = 1; i <= allSolidsBefore.Extent(); ++i )
2204   {
2205     int iSD = _solids.FindIndex( allSolidsBefore(i) );
2206     if ( iSD )
2207     {
2208       TopTools_MapIteratorOfMapOfShape soIt( _sdVec[ iSD-1 ]._before );
2209       for ( ; soIt.More(); soIt.Next() )
2210         allSolidsBefore.Add( soIt.Value() );
2211     }
2212   }
2213   if ( allSolidsBefore.Contains( solidAfter._solid ))
2214     return false;
2215
2216   for ( int i = 1; i <= allSolidsBefore.Extent(); ++i )
2217     solidAfter._before.Add( allSolidsBefore(i) );
2218
2219   return true;
2220 }
2221
2222 //================================================================================
2223 /*!
2224  * \brief
2225  */
2226 //================================================================================
2227
2228 bool _ViscousBuilder::findFacesWithLayers(const bool onlyWith)
2229 {
2230   SMESH_MesherHelper helper( *_mesh );
2231   TopExp_Explorer exp;
2232
2233   // collect all faces-to-ignore defined by hyp
2234   for ( size_t i = 0; i < _sdVec.size(); ++i )
2235   {
2236     // get faces-to-ignore defined by each hyp
2237     typedef const StdMeshers_ViscousLayers* THyp;
2238     typedef std::pair< set<TGeomID>, THyp > TFacesOfHyp;
2239     list< TFacesOfHyp > ignoreFacesOfHyps;
2240     list< THyp >::iterator              hyp = _sdVec[i]._hyps.begin();
2241     list< TopoDS_Shape >::iterator hypShape = _sdVec[i]._hypShapes.begin();
2242     for ( ; hyp != _sdVec[i]._hyps.end(); ++hyp, ++hypShape )
2243     {
2244       ignoreFacesOfHyps.push_back( TFacesOfHyp( set<TGeomID>(), *hyp ));
2245       getIgnoreFaces( _sdVec[i]._solid, *hyp, *hypShape, ignoreFacesOfHyps.back().first );
2246     }
2247
2248     // fill _SolidData::_face2hyp and check compatibility of hypotheses
2249     const int nbHyps = _sdVec[i]._hyps.size();
2250     if ( nbHyps > 1 )
2251     {
2252       // check if two hypotheses define different parameters for the same FACE
2253       list< TFacesOfHyp >::iterator igFacesOfHyp;
2254       for ( exp.Init( _sdVec[i]._solid, TopAbs_FACE ); exp.More(); exp.Next() )
2255       {
2256         const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
2257         THyp hyp = 0;
2258         igFacesOfHyp = ignoreFacesOfHyps.begin();
2259         for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
2260           if ( ! igFacesOfHyp->first.count( faceID ))
2261           {
2262             if ( hyp )
2263               return error(SMESH_Comment("Several hypotheses define "
2264                                          "Viscous Layers on the face #") << faceID );
2265             hyp = igFacesOfHyp->second;
2266           }
2267         if ( hyp )
2268           _sdVec[i]._face2hyp.insert( make_pair( faceID, hyp ));
2269         else
2270           _sdVec[i]._ignoreFaceIds.insert( faceID );
2271       }
2272
2273       // check if two hypotheses define different number of viscous layers for
2274       // adjacent faces of a solid
2275       set< int > nbLayersSet;
2276       igFacesOfHyp = ignoreFacesOfHyps.begin();
2277       for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
2278       {
2279         nbLayersSet.insert( igFacesOfHyp->second->GetNumberLayers() );
2280       }
2281       if ( nbLayersSet.size() > 1 )
2282       {
2283         for ( exp.Init( _sdVec[i]._solid, TopAbs_EDGE ); exp.More(); exp.Next() )
2284         {
2285           PShapeIteratorPtr fIt = helper.GetAncestors( exp.Current(), *_mesh, TopAbs_FACE );
2286           THyp hyp1 = 0, hyp2 = 0;
2287           while( const TopoDS_Shape* face = fIt->next() )
2288           {
2289             const TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
2290             map< TGeomID, THyp >::iterator f2h = _sdVec[i]._face2hyp.find( faceID );
2291             if ( f2h != _sdVec[i]._face2hyp.end() )
2292             {
2293               ( hyp1 ? hyp2 : hyp1 ) = f2h->second;
2294             }
2295           }
2296           if ( hyp1 && hyp2 &&
2297                hyp1->GetNumberLayers() != hyp2->GetNumberLayers() )
2298           {
2299             return error("Two hypotheses define different number of "
2300                          "viscous layers on adjacent faces");
2301           }
2302         }
2303       }
2304     } // if ( nbHyps > 1 )
2305     else
2306     {
2307       _sdVec[i]._ignoreFaceIds.swap( ignoreFacesOfHyps.back().first );
2308     }
2309   } // loop on _sdVec
2310
2311   if ( onlyWith ) // is called to check hypotheses compatibility only
2312     return true;
2313
2314   // fill _SolidData::_reversedFaceIds
2315   for ( size_t i = 0; i < _sdVec.size(); ++i )
2316   {
2317     exp.Init( _sdVec[i]._solid.Oriented( TopAbs_FORWARD ), TopAbs_FACE );
2318     for ( ; exp.More(); exp.Next() )
2319     {
2320       const TopoDS_Face& face = TopoDS::Face( exp.Current() );
2321       const TGeomID    faceID = getMeshDS()->ShapeToIndex( face );
2322       if ( //!sdVec[i]._ignoreFaceIds.count( faceID ) &&
2323           helper.NbAncestors( face, *_mesh, TopAbs_SOLID ) > 1 &&
2324           helper.IsReversedSubMesh( face ))
2325       {
2326         _sdVec[i]._reversedFaceIds.insert( faceID );
2327       }
2328     }
2329   }
2330
2331   // Find FACEs to shrink mesh on (solution 2 in issue 0020832): fill in _shrinkShape2Shape
2332   TopTools_IndexedMapOfShape shapes;
2333   std::string structAlgoName = "Hexa_3D";
2334   for ( size_t i = 0; i < _sdVec.size(); ++i )
2335   {
2336     shapes.Clear();
2337     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_EDGE, shapes);
2338     for ( int iE = 1; iE <= shapes.Extent(); ++iE )
2339     {
2340       const TopoDS_Shape& edge = shapes(iE);
2341       // find 2 FACEs sharing an EDGE
2342       TopoDS_Shape FF[2];
2343       PShapeIteratorPtr fIt = helper.GetAncestors(edge, *_mesh, TopAbs_FACE, &_sdVec[i]._solid);
2344       while ( fIt->more())
2345       {
2346         const TopoDS_Shape* f = fIt->next();
2347         FF[ int( !FF[0].IsNull()) ] = *f;
2348       }
2349       if( FF[1].IsNull() ) continue; // seam edge can be shared by 1 FACE only
2350
2351       // check presence of layers on them
2352       int ignore[2];
2353       for ( int j = 0; j < 2; ++j )
2354         ignore[j] = _sdVec[i]._ignoreFaceIds.count( getMeshDS()->ShapeToIndex( FF[j] ));
2355       if ( ignore[0] == ignore[1] )
2356         continue; // nothing interesting
2357       TopoDS_Shape fWOL = FF[ ignore[0] ? 0 : 1 ]; // FACE w/o layers
2358
2359       // add EDGE to maps
2360       if ( !fWOL.IsNull())
2361       {
2362         TGeomID edgeInd = getMeshDS()->ShapeToIndex( edge );
2363         _sdVec[i]._shrinkShape2Shape.insert( make_pair( edgeInd, fWOL ));
2364       }
2365     }
2366   }
2367
2368   // Find the SHAPE along which to inflate _LayerEdge based on VERTEX
2369
2370   for ( size_t i = 0; i < _sdVec.size(); ++i )
2371   {
2372     shapes.Clear();
2373     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_VERTEX, shapes);
2374     for ( int iV = 1; iV <= shapes.Extent(); ++iV )
2375     {
2376       const TopoDS_Shape& vertex = shapes(iV);
2377       // find faces WOL sharing the vertex
2378       vector< TopoDS_Shape > facesWOL;
2379       size_t totalNbFaces = 0;
2380       PShapeIteratorPtr fIt = helper.GetAncestors(vertex, *_mesh, TopAbs_FACE, &_sdVec[i]._solid );
2381       while ( fIt->more())
2382       {
2383         const TopoDS_Shape* f = fIt->next();
2384         totalNbFaces++;
2385         const int fID = getMeshDS()->ShapeToIndex( *f );
2386         if ( _sdVec[i]._ignoreFaceIds.count ( fID ) /*&& !_sdVec[i]._noShrinkShapes.count( fID )*/)
2387           facesWOL.push_back( *f );
2388       }
2389       if ( facesWOL.size() == totalNbFaces || facesWOL.empty() )
2390         continue; // no layers at this vertex or no WOL
2391       TGeomID vInd = getMeshDS()->ShapeToIndex( vertex );
2392       switch ( facesWOL.size() )
2393       {
2394       case 1:
2395       {
2396         helper.SetSubShape( facesWOL[0] );
2397         if ( helper.IsRealSeam( vInd )) // inflate along a seam edge?
2398         {
2399           TopoDS_Shape seamEdge;
2400           PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
2401           while ( eIt->more() && seamEdge.IsNull() )
2402           {
2403             const TopoDS_Shape* e = eIt->next();
2404             if ( helper.IsRealSeam( *e ) )
2405               seamEdge = *e;
2406           }
2407           if ( !seamEdge.IsNull() )
2408           {
2409             _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, seamEdge ));
2410             break;
2411           }
2412         }
2413         _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, facesWOL[0] ));
2414         break;
2415       }
2416       case 2:
2417       {
2418         // find an edge shared by 2 faces
2419         PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
2420         while ( eIt->more())
2421         {
2422           const TopoDS_Shape* e = eIt->next();
2423           if ( helper.IsSubShape( *e, facesWOL[0]) &&
2424                helper.IsSubShape( *e, facesWOL[1]))
2425           {
2426             _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, *e )); break;
2427           }
2428         }
2429         break;
2430       }
2431       default:
2432         return error("Not yet supported case", _sdVec[i]._index);
2433       }
2434     }
2435   }
2436
2437   // Add to _noShrinkShapes sub-shapes of FACE's that can't be shrunk since
2438   // the algo of the SOLID sharing the FACE does not support it or for other reasons
2439   set< string > notSupportAlgos; notSupportAlgos.insert( structAlgoName );
2440   for ( size_t i = 0; i < _sdVec.size(); ++i )
2441   {
2442     map< TGeomID, TopoDS_Shape >::iterator e2f = _sdVec[i]._shrinkShape2Shape.begin();
2443     for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); ++e2f )
2444     {
2445       const TopoDS_Shape& fWOL = e2f->second;
2446       const TGeomID     edgeID = e2f->first;
2447       TGeomID           faceID = getMeshDS()->ShapeToIndex( fWOL );
2448       TopoDS_Shape        edge = getMeshDS()->IndexToShape( edgeID );
2449       if ( edge.ShapeType() != TopAbs_EDGE )
2450         continue; // shrink shape is VERTEX
2451
2452       TopoDS_Shape solid;
2453       PShapeIteratorPtr soIt = helper.GetAncestors(fWOL, *_mesh, TopAbs_SOLID);
2454       while ( soIt->more() && solid.IsNull() )
2455       {
2456         const TopoDS_Shape* so = soIt->next();
2457         if ( !so->IsSame( _sdVec[i]._solid ))
2458           solid = *so;
2459       }
2460       if ( solid.IsNull() )
2461         continue;
2462
2463       bool noShrinkE = false;
2464       SMESH_Algo*  algo = _mesh->GetSubMesh( solid )->GetAlgo();
2465       bool isStructured = ( algo && algo->GetName() == structAlgoName );
2466       size_t     iSolid = _solids.FindIndex( solid ) - 1;
2467       if ( iSolid < _sdVec.size() && _sdVec[ iSolid ]._ignoreFaceIds.count( faceID ))
2468       {
2469         // the adjacent SOLID has NO layers on fWOL;
2470         // shrink allowed if
2471         // - there are layers on the EDGE in the adjacent SOLID
2472         // - there are NO layers in the adjacent SOLID && algo is unstructured and computed later
2473         bool hasWLAdj = (_sdVec[iSolid]._shrinkShape2Shape.count( edgeID ));
2474         bool shrinkAllowed = (( hasWLAdj ) ||
2475                               ( !isStructured && setBefore( _sdVec[ i ], _sdVec[ iSolid ] )));
2476         noShrinkE = !shrinkAllowed;
2477       }
2478       else if ( iSolid < _sdVec.size() )
2479       {
2480         // the adjacent SOLID has layers on fWOL;
2481         // check if SOLID's mesh is unstructured and then try to set it
2482         // to be computed after the i-th solid
2483         if ( isStructured || !setBefore( _sdVec[ i ], _sdVec[ iSolid ] ))
2484           noShrinkE = true; // don't shrink fWOL
2485       }
2486       else
2487       {
2488         // the adjacent SOLID has NO layers at all
2489         noShrinkE = isStructured;
2490       }
2491
2492       if ( noShrinkE )
2493       {
2494         _sdVec[i]._noShrinkShapes.insert( edgeID );
2495
2496         // check if there is a collision with to-shrink-from EDGEs in iSolid
2497         // if ( iSolid < _sdVec.size() )
2498         // {
2499         //   shapes.Clear();
2500         //   TopExp::MapShapes( fWOL, TopAbs_EDGE, shapes);
2501         //   for ( int iE = 1; iE <= shapes.Extent(); ++iE )
2502         //   {
2503         //     const TopoDS_Edge& E = TopoDS::Edge( shapes( iE ));
2504         //     const TGeomID    eID = getMeshDS()->ShapeToIndex( E );
2505         //     if ( eID == edgeID ||
2506         //          !_sdVec[iSolid]._shrinkShape2Shape.count( eID ) ||
2507         //          _sdVec[i]._noShrinkShapes.count( eID ))
2508         //       continue;
2509         //     for ( int is1st = 0; is1st < 2; ++is1st )
2510         //     {
2511         //       TopoDS_Vertex V = helper.IthVertex( is1st, E );
2512         //       if ( _sdVec[i]._noShrinkShapes.count( getMeshDS()->ShapeToIndex( V ) ))
2513         //       {
2514         //         return error("No way to make a conformal mesh with "
2515         //                      "the given set of faces with layers", _sdVec[i]._index);
2516         //       }
2517         //     }
2518         //   }
2519         // }
2520       }
2521
2522       // add VERTEXes of the edge in _noShrinkShapes, which is necessary if
2523       // _shrinkShape2Shape is different in the adjacent SOLID
2524       for ( TopoDS_Iterator vIt( edge ); vIt.More(); vIt.Next() )
2525       {
2526         TGeomID vID = getMeshDS()->ShapeToIndex( vIt.Value() );
2527         bool noShrinkV = false, noShrinkIfAdjMeshed = false;
2528
2529         if ( iSolid < _sdVec.size() )
2530         {
2531           if ( _sdVec[ iSolid ]._ignoreFaceIds.count( faceID ))
2532           {
2533             map< TGeomID, TopoDS_Shape >::iterator i2S, i2SAdj;
2534             i2S    = _sdVec[i     ]._shrinkShape2Shape.find( vID );
2535             i2SAdj = _sdVec[iSolid]._shrinkShape2Shape.find( vID );
2536             if ( i2SAdj == _sdVec[iSolid]._shrinkShape2Shape.end() )
2537               noShrinkV = (( isStructured ) ||
2538                            ( noShrinkIfAdjMeshed = i2S->second.ShapeType() == TopAbs_EDGE ));
2539             else
2540               noShrinkV = ( ! i2S->second.IsSame( i2SAdj->second ));
2541           }
2542           else
2543           {
2544             noShrinkV = noShrinkE;
2545           }
2546         }
2547         else
2548         {
2549           // the adjacent SOLID has NO layers at all
2550           if ( isStructured )
2551           {
2552             noShrinkV = true;
2553           }
2554           else
2555           {
2556             noShrinkV = noShrinkIfAdjMeshed =
2557               ( _sdVec[i]._shrinkShape2Shape[ vID ].ShapeType() == TopAbs_EDGE );
2558           }
2559         }
2560
2561         if ( noShrinkV && noShrinkIfAdjMeshed )
2562         {
2563           // noShrinkV if FACEs in the adjacent SOLID are meshed
2564           PShapeIteratorPtr fIt = helper.GetAncestors( _sdVec[i]._shrinkShape2Shape[ vID ],
2565                                                        *_mesh, TopAbs_FACE, &solid );
2566           while ( fIt->more() )
2567           {
2568             const TopoDS_Shape* f = fIt->next();
2569             if ( !f->IsSame( fWOL ))
2570             {
2571               noShrinkV = ! _mesh->GetSubMesh( *f )->IsEmpty();
2572               break;
2573             }
2574           }
2575         }
2576         if ( noShrinkV )
2577           _sdVec[i]._noShrinkShapes.insert( vID );
2578       }
2579
2580     } // loop on _sdVec[i]._shrinkShape2Shape
2581   } // loop on _sdVec to fill in _SolidData::_noShrinkShapes
2582
2583
2584     // add FACEs of other SOLIDs to _ignoreFaceIds
2585   for ( size_t i = 0; i < _sdVec.size(); ++i )
2586   {
2587     shapes.Clear();
2588     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_FACE, shapes);
2589
2590     for ( exp.Init( _mesh->GetShapeToMesh(), TopAbs_FACE ); exp.More(); exp.Next() )
2591     {
2592       if ( !shapes.Contains( exp.Current() ))
2593         _sdVec[i]._ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( exp.Current() ));
2594     }
2595   }
2596
2597   return true;
2598 }
2599
2600 //================================================================================
2601 /*!
2602  * \brief Finds FACEs w/o layers for a given SOLID by an hypothesis
2603  */
2604 //================================================================================
2605
2606 void _ViscousBuilder::getIgnoreFaces(const TopoDS_Shape&             solid,
2607                                      const StdMeshers_ViscousLayers* hyp,
2608                                      const TopoDS_Shape&             hypShape,
2609                                      set<TGeomID>&                   ignoreFaceIds)
2610 {
2611   TopExp_Explorer exp;
2612
2613   vector<TGeomID> ids = hyp->GetBndShapes();
2614   if ( hyp->IsToIgnoreShapes() ) // FACEs to ignore are given
2615   {
2616     for ( size_t ii = 0; ii < ids.size(); ++ii )
2617     {
2618       const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[ii] );
2619       if ( !s.IsNull() && s.ShapeType() == TopAbs_FACE )
2620         ignoreFaceIds.insert( ids[ii] );
2621     }
2622   }
2623   else // FACEs with layers are given
2624   {
2625     exp.Init( solid, TopAbs_FACE );
2626     for ( ; exp.More(); exp.Next() )
2627     {
2628       TGeomID faceInd = getMeshDS()->ShapeToIndex( exp.Current() );
2629       if ( find( ids.begin(), ids.end(), faceInd ) == ids.end() )
2630         ignoreFaceIds.insert( faceInd );
2631     }
2632   }
2633
2634   // ignore internal FACEs if inlets and outlets are specified
2635   if ( hyp->IsToIgnoreShapes() )
2636   {
2637     TopTools_IndexedDataMapOfShapeListOfShape solidsOfFace;
2638     TopExp::MapShapesAndAncestors( hypShape,
2639                                    TopAbs_FACE, TopAbs_SOLID, solidsOfFace);
2640
2641     for ( exp.Init( solid, TopAbs_FACE ); exp.More(); exp.Next() )
2642     {
2643       const TopoDS_Face& face = TopoDS::Face( exp.Current() );
2644       if ( SMESH_MesherHelper::NbAncestors( face, *_mesh, TopAbs_SOLID ) < 2 )
2645         continue;
2646
2647       int nbSolids = solidsOfFace.FindFromKey( face ).Extent();
2648       if ( nbSolids > 1 )
2649         ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( face ));
2650     }
2651   }
2652 }
2653
2654 //================================================================================
2655 /*!
2656  * \brief Create the inner surface of the viscous layer and prepare data for infation
2657  */
2658 //================================================================================
2659
2660 bool _ViscousBuilder::makeLayer(_SolidData& data)
2661 {
2662   // make a map to find new nodes on sub-shapes shared with other SOLID
2663   map< TGeomID, TNode2Edge* >::iterator s2ne;
2664   map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
2665   for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
2666   {
2667     TGeomID shapeInd = s2s->first;
2668     for ( size_t i = 0; i < _sdVec.size(); ++i )
2669     {
2670       if ( _sdVec[i]._index == data._index ) continue;
2671       map< TGeomID, TopoDS_Shape >::iterator s2s2 = _sdVec[i]._shrinkShape2Shape.find( shapeInd );
2672       if ( s2s2 != _sdVec[i]._shrinkShape2Shape.end() &&
2673            *s2s == *s2s2 && !_sdVec[i]._n2eMap.empty() )
2674       {
2675         data._s2neMap.insert( make_pair( shapeInd, &_sdVec[i]._n2eMap ));
2676         break;
2677       }
2678     }
2679   }
2680
2681   // Create temporary faces and _LayerEdge's
2682
2683   debugMsg( "######################" );
2684   dumpFunction(SMESH_Comment("makeLayers_")<<data._index);
2685
2686   vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
2687
2688   data._stepSize = Precision::Infinite();
2689   data._stepSizeNodes[0] = 0;
2690
2691   SMESH_MesherHelper helper( *_mesh );
2692   helper.SetSubShape( data._solid );
2693   helper.SetElementsOnShape( true );
2694
2695   vector< const SMDS_MeshNode*> newNodes; // of a mesh face
2696   TNode2Edge::iterator n2e2;
2697
2698   // make _LayerEdge's
2699   for ( TopExp_Explorer exp( data._solid, TopAbs_FACE ); exp.More(); exp.Next() )
2700   {
2701     const TopoDS_Face& F = TopoDS::Face( exp.Current() );
2702     SMESH_subMesh*    sm = _mesh->GetSubMesh( F );
2703     const TGeomID     id = sm->GetId();
2704     if ( edgesByGeom[ id ]._shape.IsNull() )
2705       continue; // no layers
2706     SMESH_ProxyMesh::SubMesh* proxySub =
2707       data._proxyMesh->getFaceSubM( F, /*create=*/true);
2708
2709     SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2710     if ( !smDS ) return error(SMESH_Comment("Not meshed face ") << id, data._index );
2711
2712     SMDS_ElemIteratorPtr eIt = smDS->GetElements();
2713     while ( eIt->more() )
2714     {
2715       const SMDS_MeshElement* face = eIt->next();
2716       double          faceMaxCosin = -1;
2717       _LayerEdge*     maxCosinEdge = 0;
2718       int             nbDegenNodes = 0;
2719
2720       newNodes.resize( face->NbCornerNodes() );
2721       for ( size_t i = 0 ; i < newNodes.size(); ++i )
2722       {
2723         const SMDS_MeshNode* n = face->GetNode( i );
2724         const int      shapeID = n->getshapeId();
2725         const bool onDegenShap = helper.IsDegenShape( shapeID );
2726         const bool onDegenEdge = ( onDegenShap && n->GetPosition()->GetDim() == 1 );
2727         if ( onDegenShap )
2728         {
2729           if ( onDegenEdge )
2730           {
2731             // substitute n on a degenerated EDGE with a node on a corresponding VERTEX
2732             const TopoDS_Shape& E = getMeshDS()->IndexToShape( shapeID );
2733             TopoDS_Vertex       V = helper.IthVertex( 0, TopoDS::Edge( E ));
2734             if ( const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() )) {
2735               n = vN;
2736               nbDegenNodes++;
2737             }
2738           }
2739           else
2740           {
2741             nbDegenNodes++;
2742           }
2743         }
2744         TNode2Edge::iterator n2e = data._n2eMap.insert({ n, nullptr }).first;
2745         if ( !(*n2e).second )
2746         {
2747           // add a _LayerEdge
2748           _LayerEdge* edge = _Factory::NewLayerEdge();
2749           edge->_nodes.push_back( n );
2750           n2e->second = edge;
2751           edgesByGeom[ shapeID ]._edges.push_back( edge );
2752           const bool noShrink = data._noShrinkShapes.count( shapeID );
2753
2754           SMESH_TNodeXYZ xyz( n );
2755
2756           // set edge data or find already refined _LayerEdge and get data from it
2757           if (( !noShrink                                                     ) &&
2758               ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE        ) &&
2759               (( s2ne = data._s2neMap.find( shapeID )) != data._s2neMap.end() ) &&
2760               (( n2e2 = (*s2ne).second->find( n )) != s2ne->second->end()     ))
2761           {
2762             _LayerEdge* foundEdge = (*n2e2).second;
2763             gp_XYZ        lastPos = edge->Copy( *foundEdge, edgesByGeom[ shapeID ], helper );
2764             foundEdge->_pos.push_back( lastPos );
2765             // location of the last node is modified and we restore it by foundEdge->_pos.back()
2766             const_cast< SMDS_MeshNode* >
2767               ( edge->_nodes.back() )->setXYZ( xyz.X(), xyz.Y(), xyz.Z() );
2768           }
2769           else
2770           {
2771             if ( !noShrink )
2772             {
2773               edge->_nodes.push_back( helper.AddNode( xyz.X(), xyz.Y(), xyz.Z() ));
2774             }
2775             if ( !setEdgeData( *edge, edgesByGeom[ shapeID ], helper, data ))
2776               return false;
2777
2778             if ( edge->_nodes.size() < 2 )
2779               edge->Block( data );
2780               //data._noShrinkShapes.insert( shapeID );
2781           }
2782           dumpMove(edge->_nodes.back());
2783
2784           if ( edge->_cosin > faceMaxCosin && !edge->Is( _LayerEdge::BLOCKED ))
2785           {
2786             faceMaxCosin = edge->_cosin;
2787             maxCosinEdge = edge;
2788           }
2789         }
2790         newNodes[ i ] = n2e->second->_nodes.back();
2791
2792         if ( onDegenEdge )
2793           data._n2eMap.insert( make_pair( face->GetNode( i ), n2e->second ));
2794       }
2795       if ( newNodes.size() - nbDegenNodes < 2 )
2796         continue;
2797
2798       // create a temporary face
2799       const SMDS_MeshElement* newFace =
2800         new _TmpMeshFace( newNodes, --_tmpFaceID, face->GetShapeID(), face );
2801       proxySub->AddElement( newFace );
2802
2803       // compute inflation step size by min size of element on a convex surface
2804       if ( faceMaxCosin > theMinSmoothCosin )
2805         limitStepSize( data, face, maxCosinEdge );
2806
2807     } // loop on 2D elements on a FACE
2808   } // loop on FACEs of a SOLID to create _LayerEdge's
2809
2810
2811   // Set _LayerEdge::_neibors
2812   TNode2Edge::iterator n2e;
2813   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2814   {
2815     _EdgesOnShape& eos = data._edgesOnShape[iS];
2816     for ( size_t i = 0; i < eos._edges.size(); ++i )
2817     {
2818       _LayerEdge* edge = eos._edges[i];
2819       TIDSortedNodeSet nearNodes;
2820       SMDS_ElemIteratorPtr fIt = edge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2821       while ( fIt->more() )
2822       {
2823         const SMDS_MeshElement* f = fIt->next();
2824         if ( !data._ignoreFaceIds.count( f->getshapeId() ))
2825           nearNodes.insert( f->begin_nodes(), f->end_nodes() );
2826       }
2827       nearNodes.erase( edge->_nodes[0] );
2828       edge->_neibors.reserve( nearNodes.size() );
2829       TIDSortedNodeSet::iterator node = nearNodes.begin();
2830       for ( ; node != nearNodes.end(); ++node )
2831         if (( n2e = data._n2eMap.find( *node )) != data._n2eMap.end() )
2832           edge->_neibors.push_back( n2e->second );
2833     }
2834
2835     // Fix uv of nodes on periodic FACEs (bos #20643)
2836
2837     if ( eos.ShapeType() != TopAbs_EDGE ||
2838          eos.SWOLType()  != TopAbs_FACE ||
2839          eos.size() == 0 )
2840       continue;
2841
2842     const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
2843     SMESH_MesherHelper faceHelper( *_mesh );
2844     faceHelper.SetSubShape( F );
2845     faceHelper.ToFixNodeParameters( true );
2846     if ( faceHelper.GetPeriodicIndex() == 0 )
2847       continue;
2848
2849     SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( F );
2850     if ( !smDS || smDS->GetNodes() == 0 )
2851       continue;
2852
2853     bool toCheck = true;
2854     const double tol = 2 * helper.MaxTolerance( F );
2855     for ( SMDS_NodeIteratorPtr nIt = smDS->GetNodes(); nIt->more(); )
2856     {
2857       const SMDS_MeshNode* node = nIt->next();
2858       gp_XY uvNew( Precision::Infinite(), 0 );
2859       if ( toCheck )
2860       {
2861         toCheck = false;
2862         gp_XY uv = faceHelper.GetNodeUV( F, node );
2863         if ( ! faceHelper.CheckNodeUV( F, node, uvNew, tol, /*force=*/true ))
2864           break; // projection on F failed
2865         if (( uv - uvNew ).Modulus() < Precision::Confusion() )
2866           break; // current uv is OK
2867       }
2868       faceHelper.CheckNodeUV( F, node, uvNew, tol, /*force=*/true );
2869     }
2870   }
2871
2872   data._epsilon = 1e-7;
2873   if ( data._stepSize < 1. )
2874     data._epsilon *= data._stepSize;
2875
2876   if ( !findShapesToSmooth( data )) // _LayerEdge::_maxLen is computed here
2877     return false;
2878
2879   // limit data._stepSize depending on surface curvature and fill data._convexFaces
2880   limitStepSizeByCurvature( data ); // !!! it must be before node substitution in _Simplex
2881
2882   // Set target nodes into _Simplex and _LayerEdge's to _2NearEdges
2883   const SMDS_MeshNode* nn[2];
2884   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2885   {
2886     _EdgesOnShape& eos = data._edgesOnShape[iS];
2887     for ( size_t i = 0; i < eos._edges.size(); ++i )
2888     {
2889       _LayerEdge* edge = eos._edges[i];
2890       if ( edge->IsOnEdge() )
2891       {
2892         // get neighbor nodes
2893         bool hasData = ( edge->_2neibors->_edges[0] );
2894         if ( hasData ) // _LayerEdge is a copy of another one
2895         {
2896           nn[0] = edge->_2neibors->srcNode(0);
2897           nn[1] = edge->_2neibors->srcNode(1);
2898         }
2899         else if ( !findNeiborsOnEdge( edge, nn[0],nn[1], eos, data ))
2900         {
2901           return false;
2902         }
2903         // set neighbor _LayerEdge's
2904         for ( int j = 0; j < 2; ++j )
2905         {
2906           if (( n2e = data._n2eMap.find( nn[j] )) == data._n2eMap.end() )
2907             return error("_LayerEdge not found by src node", data._index);
2908           edge->_2neibors->_edges[j] = n2e->second;
2909         }
2910         if ( !hasData )
2911           edge->SetDataByNeighbors( nn[0], nn[1], eos, helper );
2912       }
2913
2914       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
2915       {
2916         _Simplex& s = edge->_simplices[j];
2917         s._nNext = data._n2eMap[ s._nNext ]->_nodes.back();
2918         s._nPrev = data._n2eMap[ s._nPrev ]->_nodes.back();
2919       }
2920
2921       // For an _LayerEdge on a degenerated EDGE, copy some data from
2922       // a corresponding _LayerEdge on a VERTEX
2923       // (issue 52453, pb on a downloaded SampleCase2-Tet-netgen-mephisto.hdf)
2924       if ( helper.IsDegenShape( edge->_nodes[0]->getshapeId() ))
2925       {
2926         // Generally we should not get here
2927         if ( eos.ShapeType() != TopAbs_EDGE )
2928           continue;
2929         TopoDS_Vertex V = helper.IthVertex( 0, TopoDS::Edge( eos._shape ));
2930         const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() );
2931         if (( n2e = data._n2eMap.find( vN )) == data._n2eMap.end() )
2932           continue;
2933         const _LayerEdge* vEdge = n2e->second;
2934         edge->_normal    = vEdge->_normal;
2935         edge->_lenFactor = vEdge->_lenFactor;
2936         edge->_cosin     = vEdge->_cosin;
2937       }
2938
2939     } // loop on data._edgesOnShape._edges
2940   } // loop on data._edgesOnShape
2941
2942   // fix _LayerEdge::_2neibors on EDGEs to smooth
2943   // map< TGeomID,Handle(Geom_Curve)>::iterator e2c = data._edge2curve.begin();
2944   // for ( ; e2c != data._edge2curve.end(); ++e2c )
2945   //   if ( !e2c->second.IsNull() )
2946   //   {
2947   //     if ( _EdgesOnShape* eos = data.GetShapeEdges( e2c->first ))
2948   //       data.Sort2NeiborsOnEdge( eos->_edges );
2949   //   }
2950
2951   dumpFunctionEnd();
2952   return true;
2953 }
2954
2955 //================================================================================
2956 /*!
2957  * \brief Compute inflation step size by min size of element on a convex surface
2958  */
2959 //================================================================================
2960
2961 void _ViscousBuilder::limitStepSize( _SolidData&             data,
2962                                      const SMDS_MeshElement* face,
2963                                      const _LayerEdge*       maxCosinEdge )
2964 {
2965   int iN = 0;
2966   double minSize = 10 * data._stepSize;
2967   const int nbNodes = face->NbCornerNodes();
2968   for ( int i = 0; i < nbNodes; ++i )
2969   {
2970     const SMDS_MeshNode* nextN = face->GetNode( SMESH_MesherHelper::WrapIndex( i+1, nbNodes ));
2971     const SMDS_MeshNode*  curN = face->GetNode( i );
2972     if ( nextN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ||
2973          curN-> GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
2974     {
2975       double dist = SMESH_TNodeXYZ( curN ).Distance( nextN );
2976       if ( dist < minSize )
2977         minSize = dist, iN = i;
2978     }
2979   }
2980   double newStep = 0.8 * minSize / maxCosinEdge->_lenFactor;
2981   if ( newStep < data._stepSize )
2982   {
2983     data._stepSize = newStep;
2984     data._stepSizeCoeff = 0.8 / maxCosinEdge->_lenFactor;
2985     data._stepSizeNodes[0] = face->GetNode( iN );
2986     data._stepSizeNodes[1] = face->GetNode( SMESH_MesherHelper::WrapIndex( iN+1, nbNodes ));
2987   }
2988 }
2989
2990 //================================================================================
2991 /*!
2992  * \brief Compute inflation step size by min size of element on a convex surface
2993  */
2994 //================================================================================
2995
2996 void _ViscousBuilder::limitStepSize( _SolidData& data, const double minSize )
2997 {
2998   if ( minSize < data._stepSize )
2999   {
3000     data._stepSize = minSize;
3001     if ( data._stepSizeNodes[0] )
3002     {
3003       double dist =
3004         SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
3005       data._stepSizeCoeff = data._stepSize / dist;
3006     }
3007   }
3008 }
3009
3010 //================================================================================
3011 /*!
3012  * \brief Limit data._stepSize by evaluating curvature of shapes and fill data._convexFaces
3013  */
3014 //================================================================================
3015
3016 void _ViscousBuilder::limitStepSizeByCurvature( _SolidData& data )
3017 {
3018   SMESH_MesherHelper helper( *_mesh );
3019
3020   BRepLProp_SLProps surfProp( 2, 1e-6 );
3021   data._convexFaces.clear();
3022
3023   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
3024   {
3025     _EdgesOnShape& eof = data._edgesOnShape[iS];
3026     if ( eof.ShapeType() != TopAbs_FACE ||
3027          data._ignoreFaceIds.count( eof._shapeID ))
3028       continue;
3029
3030     TopoDS_Face        F = TopoDS::Face( eof._shape );
3031     const TGeomID faceID = eof._shapeID;
3032
3033     BRepAdaptor_Surface surface( F, false );
3034     surfProp.SetSurface( surface );
3035
3036     _ConvexFace cnvFace;
3037     cnvFace._face = F;
3038     cnvFace._normalsFixed = false;
3039     cnvFace._isTooCurved = false;
3040
3041     double maxCurvature = cnvFace.GetMaxCurvature( data, eof, surfProp, helper );
3042     if ( maxCurvature > 0 )
3043     {
3044       limitStepSize( data, 0.9 / maxCurvature );
3045       findEdgesToUpdateNormalNearConvexFace( cnvFace, data, helper );
3046     }
3047     if ( !cnvFace._isTooCurved ) continue;
3048
3049     _ConvexFace & convFace =
3050       data._convexFaces.insert( make_pair( faceID, cnvFace )).first->second;
3051
3052     // skip a closed surface (data._convexFaces is useful anyway)
3053     bool isClosedF = false;
3054     helper.SetSubShape( F );
3055     if ( helper.HasRealSeam() )
3056     {
3057       // in the closed surface there must be a closed EDGE
3058       for ( TopExp_Explorer eIt( F, TopAbs_EDGE ); eIt.More() && !isClosedF; eIt.Next() )
3059         isClosedF = helper.IsClosedEdge( TopoDS::Edge( eIt.Current() ));
3060     }
3061     if ( isClosedF )
3062     {
3063       // limit _LayerEdge::_maxLen on the FACE
3064       const double oriFactor    = ( F.Orientation() == TopAbs_REVERSED ? +1. : -1. );
3065       const double minCurvature =
3066         1. / ( eof._hyp.GetTotalThickness() * ( 1 + theThickToIntersection ));
3067       map< TGeomID, _EdgesOnShape* >::iterator id2eos = cnvFace._subIdToEOS.find( faceID );
3068       if ( id2eos != cnvFace._subIdToEOS.end() )
3069       {
3070         _EdgesOnShape& eos = * id2eos->second;
3071         for ( size_t i = 0; i < eos._edges.size(); ++i )
3072         {
3073           _LayerEdge* ledge = eos._edges[ i ];
3074           gp_XY uv = helper.GetNodeUV( F, ledge->_nodes[0] );
3075           surfProp.SetParameters( uv.X(), uv.Y() );
3076           if ( surfProp.IsCurvatureDefined() )
3077           {
3078             double curvature = Max( surfProp.MaxCurvature() * oriFactor,
3079                                     surfProp.MinCurvature() * oriFactor );
3080             if ( curvature > minCurvature )
3081               ledge->SetMaxLen( Min( ledge->_maxLen, 1. / curvature ));
3082           }
3083         }
3084       }
3085       continue;
3086     }
3087
3088     // Fill _ConvexFace::_simplexTestEdges. These _LayerEdge's are used to detect
3089     // prism distortion.
3090     map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.find( faceID );
3091     if ( id2eos != convFace._subIdToEOS.end() && !id2eos->second->_edges.empty() )
3092     {
3093       // there are _LayerEdge's on the FACE it-self;
3094       // select _LayerEdge's near EDGEs
3095       _EdgesOnShape& eos = * id2eos->second;
3096       for ( size_t i = 0; i < eos._edges.size(); ++i )
3097       {
3098         _LayerEdge* ledge = eos._edges[ i ];
3099         for ( size_t j = 0; j < ledge->_simplices.size(); ++j )
3100           if ( ledge->_simplices[j]._nNext->GetPosition()->GetDim() < 2 )
3101           {
3102             // do not select _LayerEdge's neighboring sharp EDGEs
3103             bool sharpNbr = false;
3104             for ( size_t iN = 0; iN < ledge->_neibors.size()  && !sharpNbr; ++iN )
3105               sharpNbr = ( ledge->_neibors[iN]->_cosin > theMinSmoothCosin );
3106             if ( !sharpNbr )
3107               convFace._simplexTestEdges.push_back( ledge );
3108             break;
3109           }
3110       }
3111     }
3112     else
3113     {
3114       // where there are no _LayerEdge's on a _ConvexFace,
3115       // as e.g. on a fillet surface with no internal nodes - issue 22580,
3116       // so that collision of viscous internal faces is not detected by check of
3117       // intersection of _LayerEdge's with the viscous internal faces.
3118
3119       set< const SMDS_MeshNode* > usedNodes;
3120
3121       // look for _LayerEdge's with null _sWOL
3122       id2eos = convFace._subIdToEOS.begin();
3123       for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
3124       {
3125         _EdgesOnShape& eos = * id2eos->second;
3126         if ( !eos._sWOL.IsNull() )
3127           continue;
3128         for ( size_t i = 0; i < eos._edges.size(); ++i )
3129         {
3130           _LayerEdge* ledge = eos._edges[ i ];
3131           const SMDS_MeshNode* srcNode = ledge->_nodes[0];
3132           if ( !usedNodes.insert( srcNode ).second ) continue;
3133
3134           for ( size_t i = 0; i < ledge->_simplices.size(); ++i )
3135           {
3136             usedNodes.insert( ledge->_simplices[i]._nPrev );
3137             usedNodes.insert( ledge->_simplices[i]._nNext );
3138           }
3139           convFace._simplexTestEdges.push_back( ledge );
3140         }
3141       }
3142     }
3143   } // loop on FACEs of data._solid
3144 }
3145
3146 //================================================================================
3147 /*!
3148  * \brief Detect shapes (and _LayerEdge's on them) to smooth
3149  */
3150 //================================================================================
3151
3152 bool _ViscousBuilder::findShapesToSmooth( _SolidData& data )
3153 {
3154   // define allowed thickness
3155   computeGeomSize( data ); // compute data._geomSize and _LayerEdge::_maxLen
3156
3157
3158   // Find shapes needing smoothing; such a shape has _LayerEdge._normal on it's
3159   // boundary inclined to the shape at a sharp angle
3160
3161   TopTools_MapOfShape edgesOfSmooFaces;
3162   SMESH_MesherHelper helper( *_mesh );
3163   bool ok = true;
3164
3165   vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
3166   data._nbShapesToSmooth = 0;
3167
3168   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check FACEs
3169   {
3170     _EdgesOnShape& eos = edgesByGeom[iS];
3171     eos._toSmooth = false;
3172     if ( eos._edges.empty() || eos.ShapeType() != TopAbs_FACE )
3173       continue;
3174
3175     double tgtThick = eos._hyp.GetTotalThickness();
3176     SMESH_subMeshIteratorPtr subIt = eos._subMesh->getDependsOnIterator(/*includeSelf=*/false );
3177     while ( subIt->more() && !eos._toSmooth )
3178     {
3179       TGeomID iSub = subIt->next()->GetId();
3180       const vector<_LayerEdge*>& eSub = edgesByGeom[ iSub ]._edges;
3181       if ( eSub.empty() ) continue;
3182
3183       double faceSize;
3184       for ( size_t i = 0; i < eSub.size() && !eos._toSmooth; ++i )
3185         if ( eSub[i]->_cosin > theMinSmoothCosin )
3186         {
3187           SMDS_ElemIteratorPtr fIt = eSub[i]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
3188           while ( fIt->more() && !eos._toSmooth )
3189           {
3190             const SMDS_MeshElement* face = fIt->next();
3191             if ( face->getshapeId() == eos._shapeID &&
3192                  getDistFromEdge( face, eSub[i]->_nodes[0], faceSize ))
3193             {
3194               eos._toSmooth = needSmoothing( eSub[i]->_cosin,
3195                                              tgtThick * eSub[i]->_lenFactor,
3196                                              faceSize);
3197             }
3198           }
3199         }
3200     }
3201     if ( eos._toSmooth )
3202     {
3203       for ( TopExp_Explorer eExp( edgesByGeom[iS]._shape, TopAbs_EDGE ); eExp.More(); eExp.Next() )
3204         edgesOfSmooFaces.Add( eExp.Current() );
3205
3206       data.PrepareEdgesToSmoothOnFace( &edgesByGeom[iS], /*substituteSrcNodes=*/false );
3207     }
3208     data._nbShapesToSmooth += eos._toSmooth;
3209
3210   }  // check FACEs
3211
3212   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check EDGEs
3213   {
3214     _EdgesOnShape& eos = edgesByGeom[iS];
3215     eos._edgeSmoother = NULL;
3216     if ( eos._edges.empty() || eos.ShapeType() != TopAbs_EDGE ) continue;
3217     if ( !eos._hyp.ToSmooth() ) continue;
3218
3219     const TopoDS_Edge& E = TopoDS::Edge( edgesByGeom[iS]._shape );
3220     if ( SMESH_Algo::isDegenerated( E ) || !edgesOfSmooFaces.Contains( E ))
3221       continue;
3222
3223     double tgtThick = eos._hyp.GetTotalThickness(), h0 = eos._hyp.Get1stLayerThickness();
3224     for ( TopoDS_Iterator vIt( E ); vIt.More() && !eos._toSmooth; vIt.Next() )
3225     {
3226       TGeomID iV = getMeshDS()->ShapeToIndex( vIt.Value() );
3227       vector<_LayerEdge*>& eV = edgesByGeom[ iV ]._edges;
3228       if ( eV.empty() || eV[0]->Is( _LayerEdge::MULTI_NORMAL )) continue;
3229       gp_Vec  eDir    = getEdgeDir( E, TopoDS::Vertex( vIt.Value() ), h0 );
3230       double angle    = eDir.Angle( eV[0]->_normal );
3231       double cosin    = Cos( angle );
3232       double cosinAbs = Abs( cosin );
3233       if ( cosinAbs > theMinSmoothCosin )
3234       {
3235         // always smooth analytic EDGEs
3236         Handle(Geom_Curve) curve = _Smoother1D::CurveForSmooth( E, eos, helper );
3237         eos._toSmooth = ! curve.IsNull();
3238
3239         // compare tgtThick with the length of an end segment
3240         SMDS_ElemIteratorPtr eIt = eV[0]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
3241         while ( eIt->more() && !eos._toSmooth )
3242         {
3243           const SMDS_MeshElement* endSeg = eIt->next();
3244           if ( endSeg->getshapeId() == (int) iS )
3245           {
3246             double segLen =
3247               SMESH_TNodeXYZ( endSeg->GetNode( 0 )).Distance( endSeg->GetNode( 1 ));
3248             eos._toSmooth = needSmoothing( cosinAbs, tgtThick * eV[0]->_lenFactor, segLen );
3249           }
3250         }
3251         if ( eos._toSmooth )
3252         {
3253           eos._edgeSmoother = new _Smoother1D( curve, eos );
3254
3255           // for ( size_t i = 0; i < eos._edges.size(); ++i )
3256           //   eos._edges[i]->Set( _LayerEdge::TO_SMOOTH );
3257         }
3258       }
3259     }
3260     data._nbShapesToSmooth += eos._toSmooth;
3261
3262   } // check EDGEs
3263
3264   // Reset _cosin if no smooth is allowed by the user
3265   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
3266   {
3267     _EdgesOnShape& eos = edgesByGeom[iS];
3268     if ( eos._edges.empty() ) continue;
3269
3270     if ( !eos._hyp.ToSmooth() )
3271       for ( size_t i = 0; i < eos._edges.size(); ++i )
3272         //eos._edges[i]->SetCosin( 0 ); // keep _cosin to use in limitMaxLenByCurvature()
3273         eos._edges[i]->_lenFactor = 1;
3274   }
3275
3276
3277   // Fill _eosC1 to make that C1 FACEs and EDGEs between them to be smoothed as a whole
3278
3279   TopTools_MapOfShape c1VV;
3280
3281   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check FACEs
3282   {
3283     _EdgesOnShape& eos = edgesByGeom[iS];
3284     if ( eos._edges.empty() ||
3285          eos.ShapeType() != TopAbs_FACE ||
3286          !eos._toSmooth )
3287       continue;
3288
3289     // check EDGEs of a FACE
3290     TopTools_MapOfShape checkedEE, allVV;
3291     list< SMESH_subMesh* > smQueue( 1, eos._subMesh ); // sm of FACEs
3292     while ( !smQueue.empty() )
3293     {
3294       SMESH_subMesh* sm = smQueue.front();
3295       smQueue.pop_front();
3296       SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/false);
3297       while ( smIt->more() )
3298       {
3299         sm = smIt->next();
3300         if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
3301           allVV.Add( sm->GetSubShape() );
3302         if ( sm->GetSubShape().ShapeType() != TopAbs_EDGE ||
3303              !checkedEE.Add( sm->GetSubShape() ))
3304           continue;
3305
3306         _EdgesOnShape*      eoe = data.GetShapeEdges( sm->GetId() );
3307         vector<_LayerEdge*>& eE = eoe->_edges;
3308         if ( eE.empty() || !eoe->_sWOL.IsNull() )
3309           continue;
3310
3311         bool isC1 = true; // check continuity along an EDGE
3312         for ( size_t i = 0; i < eE.size() && isC1; ++i )
3313           isC1 = ( Abs( eE[i]->_cosin ) < theMinSmoothCosin );
3314         if ( !isC1 )
3315           continue;
3316
3317         // check that mesh faces are C1 as well
3318         {
3319           gp_XYZ norm1, norm2;
3320           const SMDS_MeshNode*   n = eE[ eE.size() / 2 ]->_nodes[0];
3321           SMDS_ElemIteratorPtr fIt = n->GetInverseElementIterator(SMDSAbs_Face);
3322           if ( !SMESH_MeshAlgos::FaceNormal( fIt->next(), norm1, /*normalized=*/true ))
3323             continue;
3324           while ( fIt->more() && isC1 )
3325             isC1 = ( SMESH_MeshAlgos::FaceNormal( fIt->next(), norm2, /*normalized=*/true ) &&
3326                      Abs( norm1 * norm2 ) >= ( 1. - theMinSmoothCosin ));
3327           if ( !isC1 )
3328             continue;
3329         }
3330
3331         // add the EDGE and an adjacent FACE to _eosC1
3332         PShapeIteratorPtr fIt = helper.GetAncestors( sm->GetSubShape(), *_mesh, TopAbs_FACE );
3333         while ( const TopoDS_Shape* face = fIt->next() )
3334         {
3335           _EdgesOnShape* eof = data.GetShapeEdges( *face );
3336           if ( !eof ) continue; // other solid
3337           if ( eos._shapeID == eof->_shapeID ) continue;
3338           if ( !eos.HasC1( eof ))
3339           {
3340             // check the FACEs
3341             eos._eosC1.push_back( eof );
3342             eof->_toSmooth = false;
3343             data.PrepareEdgesToSmoothOnFace( eof, /*substituteSrcNodes=*/false );
3344             smQueue.push_back( eof->_subMesh );
3345           }
3346           if ( !eos.HasC1( eoe ))
3347           {
3348             eos._eosC1.push_back( eoe );
3349             eoe->_toSmooth = false;
3350             data.PrepareEdgesToSmoothOnFace( eoe, /*substituteSrcNodes=*/false );
3351           }
3352         }
3353       }
3354     }
3355     if ( eos._eosC1.empty() )
3356       continue;
3357
3358     // check VERTEXes of C1 FACEs
3359     TopTools_MapIteratorOfMapOfShape vIt( allVV );
3360     for ( ; vIt.More(); vIt.Next() )
3361     {
3362       _EdgesOnShape* eov = data.GetShapeEdges( vIt.Key() );
3363       if ( !eov || eov->_edges.empty() || !eov->_sWOL.IsNull() )
3364         continue;
3365
3366       bool isC1 = true; // check if all adjacent FACEs are in eos._eosC1
3367       PShapeIteratorPtr fIt = helper.GetAncestors( vIt.Key(), *_mesh, TopAbs_FACE );
3368       while ( const TopoDS_Shape* face = fIt->next() )
3369       {
3370         _EdgesOnShape* eof = data.GetShapeEdges( *face );
3371         if ( !eof ) continue; // other solid
3372         isC1 = ( face->IsSame( eos._shape ) || eos.HasC1( eof ));
3373         if ( !isC1 )
3374           break;
3375       }
3376       if ( isC1 )
3377       {
3378         eos._eosC1.push_back( eov );
3379         data.PrepareEdgesToSmoothOnFace( eov, /*substituteSrcNodes=*/false );
3380         c1VV.Add( eov->_shape );
3381       }
3382     }
3383
3384   } // fill _eosC1 of FACEs
3385
3386
3387   // Find C1 EDGEs
3388
3389   vector< pair< _EdgesOnShape*, gp_XYZ > > dirOfEdges;
3390
3391   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check VERTEXes
3392   {
3393     _EdgesOnShape& eov = edgesByGeom[iS];
3394     if ( eov._edges.empty() ||
3395          eov.ShapeType() != TopAbs_VERTEX ||
3396          c1VV.Contains( eov._shape ))
3397       continue;
3398     const TopoDS_Vertex& V = TopoDS::Vertex( eov._shape );
3399
3400     // get directions of surrounding EDGEs
3401     dirOfEdges.clear();
3402     PShapeIteratorPtr fIt = helper.GetAncestors( eov._shape, *_mesh, TopAbs_EDGE );
3403     while ( const TopoDS_Shape* e = fIt->next() )
3404     {
3405       _EdgesOnShape* eoe = data.GetShapeEdges( *e );
3406       if ( !eoe ) continue; // other solid
3407       gp_XYZ eDir = getEdgeDir( TopoDS::Edge( *e ), V, eoe->_hyp.Get1stLayerThickness() );
3408       if ( !Precision::IsInfinite( eDir.X() ))
3409         dirOfEdges.push_back( make_pair( eoe, eDir.Normalized() ));
3410     }
3411
3412     // find EDGEs with C1 directions
3413     for ( size_t i = 0; i < dirOfEdges.size(); ++i )
3414       for ( size_t j = i+1; j < dirOfEdges.size(); ++j )
3415         if ( dirOfEdges[i].first && dirOfEdges[j].first )
3416         {
3417           double dot = dirOfEdges[i].second * dirOfEdges[j].second;
3418           bool isC1 = ( dot < - ( 1. - theMinSmoothCosin ));
3419           if ( isC1 )
3420           {
3421             double maxEdgeLen = 3 * Min( eov._edges[0]->_maxLen, eov._hyp.GetTotalThickness() );
3422             for ( int isJ = 0; isJ < 2; ++isJ ) // loop on [i,j]
3423             {
3424               size_t k = isJ ? j : i;
3425               const TopoDS_Edge& e = TopoDS::Edge( dirOfEdges[k].first->_shape );
3426               double eLen = SMESH_Algo::EdgeLength( e );
3427               if ( eLen < maxEdgeLen )
3428               {
3429                 TopoDS_Shape oppV = SMESH_MesherHelper::IthVertex( 0, e );
3430                 if ( oppV.IsSame( V ))
3431                   oppV = SMESH_MesherHelper::IthVertex( 1, e );
3432                 _EdgesOnShape* eovOpp = data.GetShapeEdges( oppV );
3433                 if ( dirOfEdges[k].second * eovOpp->_edges[0]->_normal < 0 )
3434                   eov._eosC1.push_back( dirOfEdges[k].first );
3435               }
3436               dirOfEdges[k].first = 0;
3437             }
3438           }
3439         }
3440   } // fill _eosC1 of VERTEXes
3441
3442
3443
3444   return ok;
3445 }
3446
3447 //================================================================================
3448 /*!
3449  * \brief Set up _SolidData::_edgesOnShape
3450  */
3451 //================================================================================
3452
3453 int _ViscousBuilder::makeEdgesOnShape()
3454 {
3455   const int nbShapes = getMeshDS()->MaxShapeIndex();
3456   int nbSolidsWL = 0;
3457
3458   for ( size_t i = 0; i < _sdVec.size(); ++i )
3459   {
3460     _SolidData& data = _sdVec[ i ];
3461     vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
3462     edgesByGeom.resize( nbShapes+1 );
3463
3464     // set data of _EdgesOnShape's
3465     int nbShapesWL = 0;
3466     if ( SMESH_subMesh* sm = _mesh->GetSubMesh( data._solid ))
3467     {
3468       SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/false);
3469       while ( smIt->more() )
3470       {
3471         sm = smIt->next();
3472         if ( sm->GetSubShape().ShapeType() == TopAbs_FACE &&
3473              data._ignoreFaceIds.count( sm->GetId() ))
3474           continue;
3475
3476         setShapeData( edgesByGeom[ sm->GetId() ], sm, data );
3477
3478         nbShapesWL += ( sm->GetSubShape().ShapeType() == TopAbs_FACE );
3479       }
3480     }
3481     if ( nbShapesWL == 0 ) // no shapes with layers in a SOLID
3482     {
3483       data._done = true;
3484       SMESHUtils::FreeVector( edgesByGeom );
3485     }
3486     else
3487     {
3488       ++nbSolidsWL;
3489     }
3490   }
3491   return nbSolidsWL;
3492 }
3493
3494 //================================================================================
3495 /*!
3496  * \brief initialize data of _EdgesOnShape
3497  */
3498 //================================================================================
3499
3500 void _ViscousBuilder::setShapeData( _EdgesOnShape& eos,
3501                                     SMESH_subMesh* sm,
3502                                     _SolidData&    data )
3503 {
3504   if ( !eos._shape.IsNull() ||
3505        sm->GetSubShape().ShapeType() == TopAbs_WIRE )
3506     return;
3507
3508   SMESH_MesherHelper helper( *_mesh );
3509
3510   eos._subMesh = sm;
3511   eos._shapeID = sm->GetId();
3512   eos._shape   = sm->GetSubShape();
3513   if ( eos.ShapeType() == TopAbs_FACE )
3514     eos._shape.Orientation( helper.GetSubShapeOri( data._solid, eos._shape ));
3515   eos._toSmooth = false;
3516   eos._data = &data;
3517   eos._mapper2D = nullptr;
3518
3519   // set _SWOL
3520   map< TGeomID, TopoDS_Shape >::const_iterator s2s =
3521     data._shrinkShape2Shape.find( eos._shapeID );
3522   if ( s2s != data._shrinkShape2Shape.end() )
3523     eos._sWOL = s2s->second;
3524
3525   eos._isRegularSWOL = true;
3526   if ( eos.SWOLType() == TopAbs_FACE )
3527   {
3528     const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
3529     Handle(ShapeAnalysis_Surface) surface = helper.GetSurface( F );
3530     eos._isRegularSWOL = ( ! surface->HasSingularities( 1e-7 ));
3531   }
3532
3533   // set _hyp
3534   if ( data._hyps.size() == 1 )
3535   {
3536     eos._hyp = data._hyps.back();
3537   }
3538   else
3539   {
3540     // compute average StdMeshers_ViscousLayers parameters
3541     map< TGeomID, const StdMeshers_ViscousLayers* >::iterator f2hyp;
3542     if ( eos.ShapeType() == TopAbs_FACE )
3543     {
3544       if (( f2hyp = data._face2hyp.find( eos._shapeID )) != data._face2hyp.end() )
3545         eos._hyp = f2hyp->second;
3546     }
3547     else
3548     {
3549       PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
3550       while ( const TopoDS_Shape* face = fIt->next() )
3551       {
3552         TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
3553         if (( f2hyp = data._face2hyp.find( faceID )) != data._face2hyp.end() )
3554           eos._hyp.Add( f2hyp->second );
3555       }
3556     }
3557   }
3558
3559   // set _faceNormals
3560   if ( ! eos._hyp.UseSurfaceNormal() )
3561   {
3562     if ( eos.ShapeType() == TopAbs_FACE ) // get normals to elements on a FACE
3563     {
3564       SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3565       if ( !smDS ) return;
3566       eos._faceNormals.reserve( smDS->NbElements() );
3567
3568       double oriFactor = helper.IsReversedSubMesh( TopoDS::Face( eos._shape )) ? 1.: -1.;
3569       SMDS_ElemIteratorPtr eIt = smDS->GetElements();
3570       for ( ; eIt->more(); )
3571       {
3572         const SMDS_MeshElement* face = eIt->next();
3573         gp_XYZ&                 norm = eos._faceNormals[face];
3574         if ( !SMESH_MeshAlgos::FaceNormal( face, norm, /*normalized=*/true ))
3575           norm.SetCoord( 0,0,0 );
3576         norm *= oriFactor;
3577       }
3578     }
3579     else // find EOS of adjacent FACEs
3580     {
3581       PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
3582       while ( const TopoDS_Shape* face = fIt->next() )
3583       {
3584         TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
3585         eos._faceEOS.push_back( & data._edgesOnShape[ faceID ]);
3586         if ( eos._faceEOS.back()->_shape.IsNull() )
3587           // avoid using uninitialised _shapeID in GetNormal()
3588           eos._faceEOS.back()->_shapeID = faceID;
3589       }
3590     }
3591   }
3592 }
3593
3594 //================================================================================
3595 /*!
3596  * \brief Returns normal of a face
3597  */
3598 //================================================================================
3599
3600 bool _EdgesOnShape::GetNormal( const SMDS_MeshElement* face, gp_Vec& norm )
3601 {
3602   bool ok = false;
3603   _EdgesOnShape* eos = 0;
3604
3605   if ( face->getshapeId() == _shapeID )
3606   {
3607     eos = this;
3608   }
3609   else
3610   {
3611     for ( size_t iF = 0; iF < _faceEOS.size() && !eos; ++iF )
3612       if ( face->getshapeId() == _faceEOS[ iF ]->_shapeID )
3613         eos = _faceEOS[ iF ];
3614   }
3615
3616   if (( eos ) &&
3617       ( ok = ( eos->_faceNormals.count( face ) )))
3618   {
3619     norm = eos->_faceNormals[ face ];
3620   }
3621   else if ( !eos )
3622   {
3623     debugMsg( "_EdgesOnShape::Normal() failed for face "<<face->GetID()
3624               << " on _shape #" << _shapeID );
3625   }
3626   return ok;
3627 }
3628
3629 //================================================================================
3630 /*!
3631  * \brief EdgesOnShape destructor
3632  */
3633 //================================================================================
3634
3635 _EdgesOnShape::~_EdgesOnShape()
3636 {
3637   delete _edgeSmoother;
3638   delete _mapper2D;
3639 }
3640
3641 //================================================================================
3642 /*!
3643  * \brief Set data of _LayerEdge needed for smoothing
3644  */
3645 //================================================================================
3646
3647 bool _ViscousBuilder::setEdgeData(_LayerEdge&         edge,
3648                                   _EdgesOnShape&      eos,
3649                                   SMESH_MesherHelper& helper,
3650                                   _SolidData&         data)
3651 {
3652   const SMDS_MeshNode* node = edge._nodes[0]; // source node
3653
3654   edge._len          = 0;
3655   edge._maxLen       = Precision::Infinite();
3656   edge._minAngle     = 0;
3657   edge._2neibors     = 0;
3658   edge._curvature    = 0;
3659   edge._flags        = 0;
3660   edge._smooFunction = 0;
3661
3662   // --------------------------
3663   // Compute _normal and _cosin
3664   // --------------------------
3665
3666   edge._cosin     = 0;
3667   edge._lenFactor = 1.;
3668   edge._normal.SetCoord(0,0,0);
3669   _Simplex::GetSimplices( node, edge._simplices, data._ignoreFaceIds, &data );
3670
3671   int totalNbFaces = 0;
3672   TopoDS_Face F;
3673   std::pair< TopoDS_Face, gp_XYZ > face2Norm[20];
3674   gp_Vec geomNorm;
3675   bool normOK = true;
3676
3677   const bool onShrinkShape = !eos._sWOL.IsNull();
3678   const bool useGeometry   = (( eos._hyp.UseSurfaceNormal() ) ||
3679                               ( eos.ShapeType() != TopAbs_FACE /*&& !onShrinkShape*/ ));
3680
3681   // get geom FACEs the node lies on
3682   //if ( useGeometry )
3683   {
3684     set<TGeomID> faceIds;
3685     if  ( eos.ShapeType() == TopAbs_FACE )
3686     {
3687       faceIds.insert( eos._shapeID );
3688     }
3689     else
3690     {
3691       SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3692       while ( fIt->more() )
3693         faceIds.insert( fIt->next()->getshapeId() );
3694     }
3695     set<TGeomID>::iterator id = faceIds.begin();
3696     for ( ; id != faceIds.end(); ++id )
3697     {
3698       const TopoDS_Shape& s = getMeshDS()->IndexToShape( *id );
3699       if ( s.IsNull() || s.ShapeType() != TopAbs_FACE || data._ignoreFaceIds.count( *id ))
3700         continue;
3701       F = TopoDS::Face( s );
3702       face2Norm[ totalNbFaces ].first = F;
3703       totalNbFaces++;
3704     }
3705   }
3706
3707   // find _normal
3708   bool fromVonF = false;
3709   if ( useGeometry )
3710   {
3711     fromVonF = ( eos.ShapeType() == TopAbs_VERTEX &&
3712                  eos.SWOLType()  == TopAbs_FACE  &&
3713                  totalNbFaces > 1 );
3714
3715     if ( onShrinkShape && !fromVonF ) // one of faces the node is on has no layers
3716     {
3717       if ( eos.SWOLType() == TopAbs_EDGE )
3718       {
3719         // inflate from VERTEX along EDGE
3720         edge._normal = getEdgeDir( TopoDS::Edge( eos._sWOL ), TopoDS::Vertex( eos._shape ),
3721                                    eos._hyp.Get1stLayerThickness(), &eos._isRegularSWOL );
3722       }
3723       else if ( eos.ShapeType() == TopAbs_VERTEX )
3724       {
3725         // inflate from VERTEX along FACE
3726         edge._normal = getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Vertex( eos._shape ),
3727                                    node, helper, normOK/*, &edge._cosin*/);
3728       }
3729       else
3730       {
3731         // inflate from EDGE along FACE
3732         edge._normal = getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Edge( eos._shape ),
3733                                    node, helper, normOK);
3734       }
3735     }
3736     else // layers are on all FACEs of SOLID the node is on (or fromVonF)
3737     {
3738       if ( fromVonF )
3739         face2Norm[ totalNbFaces++ ].first = TopoDS::Face( eos._sWOL );
3740
3741       int nbOkNorms = 0;
3742       for ( int iF = totalNbFaces - 1; iF >= 0; --iF )
3743       {
3744         F = face2Norm[ iF ].first;
3745         geomNorm = getFaceNormal( node, F, helper, normOK );
3746         if ( !normOK ) continue;
3747         nbOkNorms++;
3748
3749         if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3750           geomNorm.Reverse();
3751         face2Norm[ iF ].second = geomNorm.XYZ();
3752         edge._normal += geomNorm.XYZ();
3753       }
3754       if ( nbOkNorms == 0 )
3755         return error(SMESH_Comment("Can't get normal to node ") << node->GetID(), data._index);
3756
3757       if ( totalNbFaces >= 3 )
3758       {
3759         edge._normal = getNormalByOffset( &edge, face2Norm, totalNbFaces, fromVonF );
3760       }
3761
3762       if ( edge._normal.Modulus() < 1e-3 && nbOkNorms > 1 )
3763       {
3764         // opposite normals, re-get normals at shifted positions (IPAL 52426)
3765         edge._normal.SetCoord( 0,0,0 );
3766         for ( int iF = 0; iF < totalNbFaces - fromVonF; ++iF )
3767         {
3768           const TopoDS_Face& F = face2Norm[iF].first;
3769           geomNorm = getFaceNormal( node, F, helper, normOK, /*shiftInside=*/true );
3770           if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3771             geomNorm.Reverse();
3772           if ( normOK )
3773             face2Norm[ iF ].second = geomNorm.XYZ();
3774           edge._normal += face2Norm[ iF ].second;
3775         }
3776       }
3777     }
3778   }
3779   else // !useGeometry - get _normal using surrounding mesh faces
3780   {
3781     edge._normal = getWeigthedNormal( &edge );
3782
3783     // set<TGeomID> faceIds;
3784     //
3785     // SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3786     // while ( fIt->more() )
3787     // {
3788     //   const SMDS_MeshElement* face = fIt->next();
3789     //   if ( eos.GetNormal( face, geomNorm ))
3790     //   {
3791     //     if ( onShrinkShape && !faceIds.insert( face->getshapeId() ).second )
3792     //       continue; // use only one mesh face on FACE
3793     //     edge._normal += geomNorm.XYZ();
3794     //     totalNbFaces++;
3795     //   }
3796     // }
3797   }
3798
3799   // compute _cosin
3800   //if ( eos._hyp.UseSurfaceNormal() )
3801   {
3802     switch ( eos.ShapeType() )
3803     {
3804     case TopAbs_FACE: {
3805       edge._cosin = 0;
3806       break;
3807     }
3808     case TopAbs_EDGE: {
3809       TopoDS_Edge E    = TopoDS::Edge( eos._shape );
3810       gp_Vec inFaceDir = getFaceDir( F, E, node, helper, normOK );
3811       double angle     = inFaceDir.Angle( edge._normal ); // [0,PI]
3812       edge._cosin      = Cos( angle );
3813       break;
3814     }
3815     case TopAbs_VERTEX: {
3816       TopoDS_Vertex V  = TopoDS::Vertex( eos._shape );
3817       gp_Vec inFaceDir = getFaceDir( face2Norm[0].first , V, node, helper, normOK );
3818       double angle     = inFaceDir.Angle( edge._normal ); // [0,PI]
3819       edge._cosin      = Cos( angle );
3820       if ( fromVonF )
3821         totalNbFaces--;
3822       if ( totalNbFaces > 1 || helper.IsSeamShape( node->getshapeId() ))
3823         for ( int iF = 1; iF < totalNbFaces; ++iF )
3824         {
3825           F = face2Norm[ iF ].first;
3826           inFaceDir = getFaceDir( F, V, node, helper, normOK=true );
3827           if ( normOK ) {
3828             if ( onShrinkShape )
3829             {
3830               gp_Vec faceNorm = getFaceNormal( node, F, helper, normOK );
3831               if ( !normOK ) continue;
3832               if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3833                 faceNorm.Reverse();
3834               angle = 0.5 * M_PI - faceNorm.Angle( edge._normal );
3835               if ( inFaceDir * edge._normal < 0 )
3836                 angle = M_PI - angle;
3837             }
3838             else
3839             {
3840               angle = inFaceDir.Angle( edge._normal );
3841             }
3842             double cosin = Cos( angle );
3843             if ( Abs( cosin ) > Abs( edge._cosin ))
3844               edge._cosin = cosin;
3845           }
3846         }
3847       break;
3848     }
3849     default:
3850       return error(SMESH_Comment("Invalid shape position of node ")<<node, data._index);
3851     }
3852   }
3853
3854   double normSize = edge._normal.SquareModulus();
3855   if ( normSize < numeric_limits<double>::min() )
3856     return error(SMESH_Comment("Bad normal at node ")<< node->GetID(), data._index );
3857
3858   edge._normal /= sqrt( normSize );
3859
3860   if ( edge.Is( _LayerEdge::MULTI_NORMAL ) && edge._nodes.size() == 2 )
3861   {
3862     getMeshDS()->RemoveFreeNode( edge._nodes.back(), 0, /*fromGroups=*/false );
3863     edge._nodes.resize( 1 );
3864     edge._normal.SetCoord( 0,0,0 );
3865     edge.SetMaxLen( 0 );
3866   }
3867
3868   // Set the rest data
3869   // --------------------
3870
3871   double realLenFactor = edge.SetCosin( edge._cosin ); // to update edge._lenFactor
3872   // if ( realLenFactor > 3 )
3873   // {
3874   //   edge._cosin = 1;
3875   //   if ( onShrinkShape )
3876   //   {
3877   //     edge.Set( _LayerEdge::RISKY_SWOL );
3878   //     edge._lenFactor = 2;
3879   //   }
3880   //   else
3881   //   {
3882   //     edge._lenFactor = 1;
3883   //   }
3884   // }
3885
3886   if ( onShrinkShape )
3887   {
3888     const SMDS_MeshNode* tgtNode = edge._nodes.back();
3889     if ( SMESHDS_SubMesh* sm = getMeshDS()->MeshElements( data._solid ))
3890       sm->RemoveNode( tgtNode );
3891
3892     // set initial position which is parameters on _sWOL in this case
3893     if ( eos.SWOLType() == TopAbs_EDGE )
3894     {
3895       double u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), node, 0, &normOK );
3896       edge._pos.push_back( gp_XYZ( u, 0, 0 ));
3897       if ( edge._nodes.size() > 1 )
3898         getMeshDS()->SetNodeOnEdge( tgtNode, TopoDS::Edge( eos._sWOL ), u );
3899     }
3900     else // eos.SWOLType() == TopAbs_FACE
3901     {
3902       gp_XY uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), node, 0, &normOK );
3903       edge._pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
3904       if ( edge._nodes.size() > 1 )
3905         getMeshDS()->SetNodeOnFace( tgtNode, TopoDS::Face( eos._sWOL ), uv.X(), uv.Y() );
3906     }
3907
3908     if ( edge._nodes.size() > 1 )
3909     {
3910       // check if an angle between a FACE with layers and SWOL is sharp,
3911       // else the edge should not inflate
3912       F.Nullify();
3913       for ( int iF = 0; iF < totalNbFaces  &&  F.IsNull();  ++iF ) // find a FACE with VL
3914         if ( ! helper.IsSubShape( eos._sWOL, face2Norm[iF].first ))
3915           F = face2Norm[iF].first;
3916       if ( !F.IsNull())
3917       {
3918         geomNorm = getFaceNormal( node, F, helper, normOK );
3919         if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3920           geomNorm.Reverse(); // inside the SOLID
3921         if ( geomNorm * edge._normal < -0.001 )
3922         {
3923           getMeshDS()->RemoveFreeNode( tgtNode, 0, /*fromGroups=*/false );
3924           edge._nodes.resize( 1 );
3925         }
3926         else if ( realLenFactor > 3 ) ///  -- moved to SetCosin()
3927           //else if ( edge._lenFactor > 3 )
3928         {
3929           edge._lenFactor = 2;
3930           edge.Set( _LayerEdge::RISKY_SWOL );
3931         }
3932       }
3933     }
3934   }
3935   else
3936   {
3937     edge._pos.push_back( SMESH_TNodeXYZ( node ));
3938
3939     if ( eos.ShapeType() == TopAbs_FACE )
3940     {
3941       double angle;
3942       for ( size_t i = 0; i < edge._simplices.size(); ++i )
3943       {
3944         edge._simplices[i].IsMinAngleOK( edge._pos.back(), angle );
3945         edge._minAngle = Max( edge._minAngle, angle ); // "angle" is actually cosine
3946       }
3947     }
3948   }
3949
3950   // Set neighbor nodes for a _LayerEdge based on EDGE
3951
3952   if ( eos.ShapeType() == TopAbs_EDGE /*||
3953        ( onShrinkShape && posType == SMDS_TOP_VERTEX && fabs( edge._cosin ) < 1e-10 )*/)
3954   {
3955     edge._2neibors = _Factory::NewNearEdges();
3956     // target nodes instead of source ones will be set later
3957   }
3958
3959   return true;
3960 }
3961
3962 //================================================================================
3963 /*!
3964  * \brief Return normal to a FACE at a node
3965  *  \param [in] n - node
3966  *  \param [in] face - FACE
3967  *  \param [in] helper - helper
3968  *  \param [out] isOK - true or false
3969  *  \param [in] shiftInside - to find normal at a position shifted inside the face
3970  *  \return gp_XYZ - normal
3971  */
3972 //================================================================================
3973
3974 gp_XYZ _ViscousBuilder::getFaceNormal(const SMDS_MeshNode* node,
3975                                       const TopoDS_Face&   face,
3976                                       SMESH_MesherHelper&  helper,
3977                                       bool&                isOK,
3978                                       bool                 shiftInside)
3979 {
3980   gp_XY uv;
3981   if ( shiftInside )
3982   {
3983     // get a shifted position
3984     gp_Pnt p = SMESH_TNodeXYZ( node );
3985     gp_XYZ shift( 0,0,0 );
3986     TopoDS_Shape S = helper.GetSubShapeByNode( node, helper.GetMeshDS() );
3987     switch ( S.ShapeType() ) {
3988     case TopAbs_VERTEX:
3989     {
3990       shift = getFaceDir( face, TopoDS::Vertex( S ), node, helper, isOK );
3991       break;
3992     }
3993     case TopAbs_EDGE:
3994     {
3995       shift = getFaceDir( face, TopoDS::Edge( S ), node, helper, isOK );
3996       break;
3997     }
3998     default:
3999       isOK = false;
4000     }
4001     if ( isOK )
4002       shift.Normalize();
4003     p.Translate( shift * 1e-5 );
4004
4005     TopLoc_Location loc;
4006     GeomAPI_ProjectPointOnSurf& projector = helper.GetProjector( face, loc, 1e-7 );
4007
4008     if ( !loc.IsIdentity() ) p.Transform( loc.Transformation().Inverted() );
4009     
4010     projector.Perform( p );
4011     if ( !projector.IsDone() || projector.NbPoints() < 1 )
4012     {
4013       isOK = false;
4014       return p.XYZ();
4015     }
4016     Standard_Real U,V;
4017     projector.LowerDistanceParameters(U,V);
4018     uv.SetCoord( U,V );
4019   }
4020   else
4021   {
4022     uv = helper.GetNodeUV( face, node, 0, &isOK );
4023   }
4024
4025   gp_Dir normal;
4026   isOK = false;
4027
4028   Handle(Geom_Surface) surface = BRep_Tool::Surface( face );
4029
4030   if ( !shiftInside &&
4031        helper.IsDegenShape( node->getshapeId() ) &&
4032        getFaceNormalAtSingularity( uv, face, helper, normal ))
4033   {
4034     isOK = true;
4035     return normal.XYZ();
4036   }
4037
4038   int pointKind = GeomLib::NormEstim( surface, uv, 1e-5, normal );
4039   enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
4040
4041   if ( pointKind == IMPOSSIBLE &&
4042        node->GetPosition()->GetDim() == 2 ) // node inside the FACE
4043   {
4044     // probably NormEstim() failed due to a too high tolerance
4045     pointKind = GeomLib::NormEstim( surface, uv, 1e-20, normal );
4046     isOK = ( pointKind < IMPOSSIBLE );
4047   }
4048   if ( pointKind < IMPOSSIBLE )
4049   {
4050     if ( pointKind != REGULAR &&
4051          !shiftInside &&
4052          node->GetPosition()->GetDim() < 2 ) // FACE boundary
4053     {
4054       gp_XYZ normShift = getFaceNormal( node, face, helper, isOK, /*shiftInside=*/true );
4055       if ( normShift * normal.XYZ() < 0. )
4056         normal = normShift;
4057     }
4058     isOK = true;
4059   }
4060
4061   if ( !isOK ) // hard singularity, to call with shiftInside=true ?
4062   {
4063     const TGeomID faceID = helper.GetMeshDS()->ShapeToIndex( face );
4064
4065     SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
4066     while ( fIt->more() )
4067     {
4068       const SMDS_MeshElement* f = fIt->next();
4069       if ( f->getshapeId() == faceID )
4070       {
4071         isOK = SMESH_MeshAlgos::FaceNormal( f, (gp_XYZ&) normal.XYZ(), /*normalized=*/true );
4072         if ( isOK )
4073         {
4074           TopoDS_Face ff = face;
4075           ff.Orientation( TopAbs_FORWARD );
4076           if ( helper.IsReversedSubMesh( ff ))
4077             normal.Reverse();
4078           break;
4079         }
4080       }
4081     }
4082   }
4083   return normal.XYZ();
4084 }
4085
4086 //================================================================================
4087 /*!
4088  * \brief Try to get normal at a singularity of a surface basing on it's nature
4089  */
4090 //================================================================================
4091
4092 bool _ViscousBuilder::getFaceNormalAtSingularity( const gp_XY&        uv,
4093                                                   const TopoDS_Face&  face,
4094                                                   SMESH_MesherHelper& /*helper*/,
4095                                                   gp_Dir&             normal )
4096 {
4097   BRepAdaptor_Surface surface( face );
4098   gp_Dir axis;
4099   if ( !getRovolutionAxis( surface, axis ))
4100     return false;
4101
4102   double f,l, d, du, dv;
4103   f = surface.FirstUParameter();
4104   l = surface.LastUParameter();
4105   d = ( uv.X() - f ) / ( l - f );
4106   du = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
4107   f = surface.FirstVParameter();
4108   l = surface.LastVParameter();
4109   d = ( uv.Y() - f ) / ( l - f );
4110   dv = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
4111
4112   gp_Dir refDir;
4113   gp_Pnt2d testUV = uv;
4114   enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
4115   double tol = 1e-5;
4116   Handle(Geom_Surface) geomsurf = surface.Surface().Surface();
4117   for ( int iLoop = 0; true ; ++iLoop )
4118   {
4119     testUV.SetCoord( testUV.X() + du, testUV.Y() + dv );
4120     if ( GeomLib::NormEstim( geomsurf, testUV, tol, refDir ) == REGULAR )
4121       break;
4122     if ( iLoop > 20 )
4123       return false;
4124     tol /= 10.;
4125   }
4126
4127   if ( axis * refDir < 0. )
4128     axis.Reverse();
4129
4130   normal = axis;
4131
4132   return true;
4133 }
4134
4135 //================================================================================
4136 /*!
4137  * \brief Return a normal at a node weighted with angles taken by faces
4138  */
4139 //================================================================================
4140
4141 gp_XYZ _ViscousBuilder::getWeigthedNormal( const _LayerEdge* edge )
4142 {
4143   const SMDS_MeshNode* n = edge->_nodes[0];
4144
4145   gp_XYZ resNorm(0,0,0);
4146   SMESH_TNodeXYZ p0( n ), pP, pN;
4147   for ( size_t i = 0; i < edge->_simplices.size(); ++i )
4148   {
4149     pP.Set( edge->_simplices[i]._nPrev );
4150     pN.Set( edge->_simplices[i]._nNext );
4151     gp_Vec v0P( p0, pP ), v0N( p0, pN ), vPN( pP, pN ), norm = v0P ^ v0N;
4152     double l0P = v0P.SquareMagnitude();
4153     double l0N = v0N.SquareMagnitude();
4154     double lPN = vPN.SquareMagnitude();
4155     if ( l0P < std::numeric_limits<double>::min() ||
4156          l0N < std::numeric_limits<double>::min() ||
4157          lPN < std::numeric_limits<double>::min() )
4158       continue;
4159     double lNorm = norm.SquareMagnitude();
4160     double  sin2 = lNorm / l0P / l0N;
4161     double angle = ACos(( v0P * v0N ) / Sqrt( l0P ) / Sqrt( l0N ));
4162
4163     double weight = sin2 * angle / lPN;
4164     resNorm += weight * norm.XYZ() / Sqrt( lNorm );
4165   }
4166
4167   return resNorm;
4168 }
4169
4170 //================================================================================
4171 /*!
4172  * \brief Return a normal at a node by getting a common point of offset planes
4173  *        defined by the FACE normals
4174  */
4175 //================================================================================
4176
4177 gp_XYZ _ViscousBuilder::getNormalByOffset( _LayerEdge*                      edge,
4178                                            std::pair< TopoDS_Face, gp_XYZ > f2Normal[],
4179                                            int                              nbFaces,
4180                                            bool                             lastNoOffset)
4181 {
4182   SMESH_TNodeXYZ p0 = edge->_nodes[0];
4183
4184   gp_XYZ resNorm(0,0,0);
4185   TopoDS_Shape V = SMESH_MesherHelper::GetSubShapeByNode( p0._node, getMeshDS() );
4186   if ( V.ShapeType() != TopAbs_VERTEX || nbFaces < 3 )
4187   {
4188     for ( int i = 0; i < nbFaces; ++i )
4189       resNorm += f2Normal[i].second;
4190     return resNorm;
4191   }
4192
4193   // prepare _OffsetPlane's
4194   vector< _OffsetPlane > pln( nbFaces );
4195   for ( int i = 0; i < nbFaces - lastNoOffset; ++i )
4196   {
4197     pln[i]._faceIndex = i;
4198     pln[i]._plane = gp_Pln( p0 + f2Normal[i].second, f2Normal[i].second );
4199   }
4200   if ( lastNoOffset )
4201   {
4202     pln[ nbFaces - 1 ]._faceIndex = nbFaces - 1;
4203     pln[ nbFaces - 1 ]._plane = gp_Pln( p0, f2Normal[ nbFaces - 1 ].second );
4204   }
4205
4206   // intersect neighboring OffsetPlane's
4207   PShapeIteratorPtr edgeIt = SMESH_MesherHelper::GetAncestors( V, *_mesh, TopAbs_EDGE );
4208   while ( const TopoDS_Shape* edge = edgeIt->next() )
4209   {
4210     int f1 = -1, f2 = -1;
4211     for ( int i = 0; i < nbFaces &&  f2 < 0;  ++i )
4212       if ( SMESH_MesherHelper::IsSubShape( *edge, f2Normal[i].first ))
4213         (( f1 < 0 ) ? f1 : f2 ) = i;
4214
4215     if ( f2 >= 0 )
4216       pln[ f1 ].ComputeIntersectionLine( pln[ f2 ], TopoDS::Edge( *edge ), TopoDS::Vertex( V ));
4217   }
4218
4219   // get a common point
4220   gp_XYZ commonPnt( 0, 0, 0 );
4221   int nbPoints = 0;
4222   bool isPointFound;
4223   for ( int i = 0; i < nbFaces; ++i )
4224   {
4225     commonPnt += pln[ i ].GetCommonPoint( isPointFound, TopoDS::Vertex( V ));
4226     nbPoints  += isPointFound;
4227   }
4228   gp_XYZ wgtNorm = getWeigthedNormal( edge );
4229   if ( nbPoints == 0 )
4230     return wgtNorm;
4231
4232   commonPnt /= nbPoints;
4233   resNorm = commonPnt - p0;
4234   if ( lastNoOffset )
4235     return resNorm;
4236
4237   // choose the best among resNorm and wgtNorm
4238   resNorm.Normalize();
4239   wgtNorm.Normalize();
4240   double resMinDot = std::numeric_limits<double>::max();
4241   double wgtMinDot = std::numeric_limits<double>::max();
4242   for ( int i = 0; i < nbFaces - lastNoOffset; ++i )
4243   {
4244     resMinDot = Min( resMinDot, resNorm * f2Normal[i].second );
4245     wgtMinDot = Min( wgtMinDot, wgtNorm * f2Normal[i].second );
4246   }
4247
4248   if ( Max( resMinDot, wgtMinDot ) < theMinSmoothCosin )
4249   {
4250     edge->Set( _LayerEdge::MULTI_NORMAL );
4251   }
4252
4253   return ( resMinDot > wgtMinDot ) ? resNorm : wgtNorm;
4254 }
4255
4256 //================================================================================
4257 /*!
4258  * \brief Compute line of intersection of 2 planes
4259  */
4260 //================================================================================
4261
4262 void _OffsetPlane::ComputeIntersectionLine( _OffsetPlane&        pln,
4263                                             const TopoDS_Edge&   E,
4264                                             const TopoDS_Vertex& V )
4265 {
4266   int iNext = bool( _faceIndexNext[0] >= 0 );
4267   _faceIndexNext[ iNext ] = pln._faceIndex;
4268
4269   gp_XYZ n1 = _plane.Axis().Direction().XYZ();
4270   gp_XYZ n2 = pln._plane.Axis().Direction().XYZ();
4271
4272   gp_XYZ lineDir = n1 ^ n2;
4273
4274   double x = Abs( lineDir.X() );
4275   double y = Abs( lineDir.Y() );
4276   double z = Abs( lineDir.Z() );
4277
4278   int cooMax; // max coordinate
4279   if (x > y) {
4280     if (x > z) cooMax = 1;
4281     else       cooMax = 3;
4282   }
4283   else {
4284     if (y > z) cooMax = 2;
4285     else       cooMax = 3;
4286   }
4287
4288   gp_Pnt linePos;
4289   if ( Abs( lineDir.Coord( cooMax )) < 0.05 )
4290   {
4291     // parallel planes - intersection is an offset of the common EDGE
4292     gp_Pnt p = BRep_Tool::Pnt( V );
4293     linePos  = 0.5 * (( p.XYZ() + n1 ) + ( p.XYZ() + n2 ));
4294     lineDir  = getEdgeDir( E, V, 0.1 * SMESH_Algo::EdgeLength( E ));
4295   }
4296   else
4297   {
4298     // the constants in the 2 plane equations
4299     double d1 = - ( _plane.Axis().Direction().XYZ()     * _plane.Location().XYZ() );
4300     double d2 = - ( pln._plane.Axis().Direction().XYZ() * pln._plane.Location().XYZ() );
4301
4302     switch ( cooMax ) {
4303     case 1:
4304       linePos.SetX(  0 );
4305       linePos.SetY(( d2*n1.Z() - d1*n2.Z()) / lineDir.X() );
4306       linePos.SetZ(( d1*n2.Y() - d2*n1.Y()) / lineDir.X() );
4307       break;
4308     case 2:
4309       linePos.SetX(( d1*n2.Z() - d2*n1.Z()) / lineDir.Y() );
4310       linePos.SetY(  0 );
4311       linePos.SetZ(( d2*n1.X() - d1*n2.X()) / lineDir.Y() );
4312       break;
4313     case 3:
4314       linePos.SetX(( d2*n1.Y() - d1*n2.Y()) / lineDir.Z() );
4315       linePos.SetY(( d1*n2.X() - d2*n1.X()) / lineDir.Z() );
4316       linePos.SetZ(  0 );
4317     }
4318   }
4319   gp_Lin& line = _lines[ iNext ];
4320   line.SetDirection( lineDir );
4321   line.SetLocation ( linePos );
4322
4323   _isLineOK[ iNext ] = true;
4324
4325
4326   iNext = bool( pln._faceIndexNext[0] >= 0 );
4327   pln._lines        [ iNext ] = line;
4328   pln._faceIndexNext[ iNext ] = this->_faceIndex;
4329   pln._isLineOK     [ iNext ] = true;
4330 }
4331
4332 //================================================================================
4333 /*!
4334  * \brief Computes intersection point of two _lines
4335  */
4336 //================================================================================
4337
4338 gp_XYZ _OffsetPlane::GetCommonPoint(bool&                 isFound,
4339                                     const TopoDS_Vertex & V) const
4340 {
4341   gp_XYZ p( 0,0,0 );
4342   isFound = false;
4343
4344   if ( NbLines() == 2 )
4345   {
4346     gp_Vec lPerp0 = _lines[0].Direction().XYZ() ^ _plane.Axis().Direction().XYZ();
4347     double  dot01 = lPerp0 * _lines[1].Direction().XYZ();
4348     if ( Abs( dot01 ) > 0.05 )
4349     {
4350       gp_Vec l0l1 = _lines[1].Location().XYZ() - _lines[0].Location().XYZ();
4351       double   u1 = - ( lPerp0 * l0l1 ) / dot01;
4352       p = ( _lines[1].Location().XYZ() + _lines[1].Direction().XYZ() * u1 );
4353       isFound = true;
4354     }
4355     else
4356     {
4357       gp_Pnt  pV ( BRep_Tool::Pnt( V ));
4358       gp_Vec  lv0( _lines[0].Location(), pV    ),  lv1(_lines[1].Location(), pV     );
4359       double dot0( lv0 * _lines[0].Direction() ), dot1( lv1 * _lines[1].Direction() );
4360       p += 0.5 * ( _lines[0].Location().XYZ() + _lines[0].Direction().XYZ() * dot0 );
4361       p += 0.5 * ( _lines[1].Location().XYZ() + _lines[1].Direction().XYZ() * dot1 );
4362       isFound = true;
4363     }
4364   }
4365
4366   return p;
4367 }
4368
4369 //================================================================================
4370 /*!
4371  * \brief Find 2 neighbor nodes of a node on EDGE
4372  */
4373 //================================================================================
4374
4375 bool _ViscousBuilder::findNeiborsOnEdge(const _LayerEdge*     edge,
4376                                         const SMDS_MeshNode*& n1,
4377                                         const SMDS_MeshNode*& n2,
4378                                         _EdgesOnShape&        eos,
4379                                         _SolidData&           data)
4380 {
4381   const SMDS_MeshNode* node = edge->_nodes[0];
4382   const int        shapeInd = eos._shapeID;
4383   SMESHDS_SubMesh*   edgeSM = 0;
4384   if ( eos.ShapeType() == TopAbs_EDGE )
4385   {
4386     edgeSM = eos._subMesh->GetSubMeshDS();
4387     if ( !edgeSM || edgeSM->NbElements() == 0 )
4388       return error(SMESH_Comment("Not meshed EDGE ") << shapeInd, data._index);
4389   }
4390   int iN = 0;
4391   n2 = 0;
4392   SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Edge);
4393   while ( eIt->more() && !n2 )
4394   {
4395     const SMDS_MeshElement* e = eIt->next();
4396     const SMDS_MeshNode*   nNeibor = e->GetNode( 0 );
4397     if ( nNeibor == node ) nNeibor = e->GetNode( 1 );
4398     if ( edgeSM )
4399     {
4400       if (!edgeSM->Contains(e)) continue;
4401     }
4402     else
4403     {
4404       TopoDS_Shape s = SMESH_MesherHelper::GetSubShapeByNode( nNeibor, getMeshDS() );
4405       if ( !SMESH_MesherHelper::IsSubShape( s, eos._sWOL )) continue;
4406     }
4407     ( iN++ ? n2 : n1 ) = nNeibor;
4408   }
4409   if ( !n2 )
4410     return error(SMESH_Comment("Wrongly meshed EDGE ") << shapeInd, data._index);
4411   return true;
4412 }
4413
4414 //================================================================================
4415 /*!
4416  * \brief Create _Curvature
4417  */
4418 //================================================================================
4419
4420 _Curvature* _Curvature::New( double avgNormProj, double avgDist )
4421 {
4422   // double   _r; // radius
4423   // double   _k; // factor to correct node smoothed position
4424   // double   _h2lenRatio; // avgNormProj / (2*avgDist)
4425   // gp_Pnt2d _uv; // UV used in putOnOffsetSurface()
4426
4427   _Curvature* c = 0;
4428   if ( fabs( avgNormProj / avgDist ) > 1./200 )
4429   {
4430     c = _Factory::NewCurvature();
4431     c->_r = avgDist * avgDist / avgNormProj;
4432     c->_k = avgDist * avgDist / c->_r / c->_r;
4433     //c->_k = avgNormProj / c->_r;
4434     c->_k *= ( c->_r < 0 ? 1/1.1 : 1.1 ); // not to be too restrictive
4435     c->_h2lenRatio = avgNormProj / ( avgDist + avgDist );
4436
4437     c->_uv.SetCoord( 0., 0. );
4438   }
4439   return c;
4440 }
4441
4442 //================================================================================
4443 /*!
4444  * \brief Set _curvature and _2neibors->_plnNorm by 2 neighbor nodes residing the same EDGE
4445  */
4446 //================================================================================
4447
4448 void _LayerEdge::SetDataByNeighbors( const SMDS_MeshNode* n1,
4449                                      const SMDS_MeshNode* n2,
4450                                      const _EdgesOnShape& eos,
4451                                      SMESH_MesherHelper&  helper)
4452 {
4453   if ( eos.ShapeType() != TopAbs_EDGE )
4454     return;
4455   if ( _curvature && Is( SMOOTHED_C1 ))
4456     return;
4457
4458   gp_XYZ  pos = SMESH_TNodeXYZ( _nodes[0] );
4459   gp_XYZ vec1 = pos - SMESH_TNodeXYZ( n1 );
4460   gp_XYZ vec2 = pos - SMESH_TNodeXYZ( n2 );
4461
4462   // Set _curvature
4463
4464   double      sumLen = vec1.Modulus() + vec2.Modulus();
4465   _2neibors->_wgt[0] = 1 - vec1.Modulus() / sumLen;
4466   _2neibors->_wgt[1] = 1 - vec2.Modulus() / sumLen;
4467   double avgNormProj = 0.5 * ( _normal * vec1 + _normal * vec2 );
4468   double      avgLen = 0.5 * ( vec1.Modulus() + vec2.Modulus() );
4469   _curvature = _Curvature::New( avgNormProj, avgLen );
4470   // if ( _curvature )
4471   //   debugMsg( _nodes[0]->GetID()
4472   //             << " CURV r,k: " << _curvature->_r<<","<<_curvature->_k
4473   //             << " proj = "<<avgNormProj<< " len = " << avgLen << "| lenDelta(0) = "
4474   //             << _curvature->lenDelta(0) );
4475
4476   // Set _plnNorm
4477
4478   if ( eos._sWOL.IsNull() )
4479   {
4480     TopoDS_Edge  E = TopoDS::Edge( eos._shape );
4481     // if ( SMESH_Algo::isDegenerated( E ))
4482     //   return;
4483     gp_XYZ dirE    = getEdgeDir( E, _nodes[0], helper );
4484     gp_XYZ plnNorm = dirE ^ _normal;
4485     double proj0   = plnNorm * vec1;
4486     double proj1   = plnNorm * vec2;
4487     if ( fabs( proj0 ) > 1e-10 || fabs( proj1 ) > 1e-10 )
4488     {
4489       if ( _2neibors->_plnNorm ) delete _2neibors->_plnNorm;
4490       _2neibors->_plnNorm = new gp_XYZ( plnNorm.Normalized() );
4491     }
4492   }
4493 }
4494
4495 //================================================================================
4496 /*!
4497  * \brief Copy data from a _LayerEdge of other SOLID and based on the same node;
4498  * this and the other _LayerEdge are inflated along a FACE or an EDGE
4499  */
4500 //================================================================================
4501
4502 gp_XYZ _LayerEdge::Copy( _LayerEdge&         other,
4503                          _EdgesOnShape&      eos,
4504                          SMESH_MesherHelper& helper )
4505 {
4506   _nodes     = other._nodes;
4507   _normal    = other._normal;
4508   _len       = 0;
4509   _lenFactor = other._lenFactor;
4510   _cosin     = other._cosin;
4511   _2neibors  = other._2neibors;
4512   _curvature = other._curvature;
4513   _2neibors  = other._2neibors;
4514   _maxLen    = Precision::Infinite();//other._maxLen;
4515   _flags     = 0;
4516   _smooFunction = 0;
4517
4518   gp_XYZ lastPos( 0,0,0 );
4519   if ( eos.SWOLType() == TopAbs_EDGE )
4520   {
4521     double u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), _nodes[0] );
4522     _pos.push_back( gp_XYZ( u, 0, 0));
4523
4524     u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), _nodes.back() );
4525     lastPos.SetX( u );
4526   }
4527   else // TopAbs_FACE
4528   {
4529     gp_XY uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), _nodes[0]);
4530     _pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
4531
4532     uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), _nodes.back() );
4533     lastPos.SetX( uv.X() );
4534     lastPos.SetY( uv.Y() );
4535   }
4536   return lastPos;
4537 }
4538
4539 //================================================================================
4540 /*!
4541  * \brief Set _cosin and _lenFactor
4542  */
4543 //================================================================================
4544
4545 double _LayerEdge::SetCosin( double cosin )
4546 {
4547   _cosin = cosin;
4548   cosin = Abs( _cosin );
4549   //_lenFactor = ( cosin < 1.-1e-12 ) ?  1./sqrt(1-cosin*cosin ) : 1.0;
4550   double realLenFactor;
4551   if ( cosin < 1.-1e-12 )
4552   {
4553     _lenFactor = realLenFactor = 1./sqrt(1-cosin*cosin );
4554   }
4555   else
4556   {
4557     _lenFactor = 1;
4558     realLenFactor = Precision::Infinite();
4559   }
4560
4561   return realLenFactor;
4562 }
4563
4564 //================================================================================
4565 /*!
4566  * \brief Check if another _LayerEdge is a neighbor on EDGE
4567  */
4568 //================================================================================
4569
4570 bool _LayerEdge::IsNeiborOnEdge( const _LayerEdge* edge ) const
4571 {
4572   return (( this->_2neibors && this->_2neibors->include( edge )) ||
4573           ( edge->_2neibors && edge->_2neibors->include( this )));
4574 }
4575
4576 //================================================================================
4577 /*!
4578  * \brief Fills a vector<_Simplex > 
4579  */
4580 //================================================================================
4581
4582 void _Simplex::GetSimplices( const SMDS_MeshNode* node,
4583                              vector<_Simplex>&    simplices,
4584                              const set<TGeomID>&  ingnoreShapes,
4585                              const _SolidData*    dataToCheckOri,
4586                              const bool           toSort)
4587 {
4588   simplices.clear();
4589   SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
4590   while ( fIt->more() )
4591   {
4592     const SMDS_MeshElement* f = fIt->next();
4593     const TGeomID    shapeInd = f->getshapeId();
4594     if ( ingnoreShapes.count( shapeInd )) continue;
4595     const int nbNodes = f->NbCornerNodes();
4596     const int  srcInd = f->GetNodeIndex( node );
4597     const SMDS_MeshNode* nPrev = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd-1, nbNodes ));
4598     const SMDS_MeshNode* nNext = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+1, nbNodes ));
4599     const SMDS_MeshNode* nOpp  = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+2, nbNodes ));
4600     if ( dataToCheckOri && dataToCheckOri->_reversedFaceIds.count( shapeInd ))
4601       std::swap( nPrev, nNext );
4602     simplices.push_back( _Simplex( nPrev, nNext, ( nbNodes == 3 ? 0 : nOpp )));
4603   }
4604
4605   if ( toSort )
4606     SortSimplices( simplices );
4607 }
4608
4609 //================================================================================
4610 /*!
4611  * \brief Set neighbor simplices side by side
4612  */
4613 //================================================================================
4614
4615 void _Simplex::SortSimplices(vector<_Simplex>& simplices)
4616 {
4617   vector<_Simplex> sortedSimplices( simplices.size() );
4618   sortedSimplices[0] = simplices[0];
4619   size_t nbFound = 0;
4620   for ( size_t i = 1; i < simplices.size(); ++i )
4621   {
4622     for ( size_t j = 1; j < simplices.size(); ++j )
4623       if ( sortedSimplices[i-1]._nNext == simplices[j]._nPrev )
4624       {
4625         sortedSimplices[i] = simplices[j];
4626         nbFound++;
4627         break;
4628       }
4629   }
4630   if ( nbFound == simplices.size() - 1 )
4631     simplices.swap( sortedSimplices );
4632 }
4633
4634 //================================================================================
4635 /*!
4636  * \brief DEBUG. Create groups containing temporary data of _LayerEdge's
4637  */
4638 //================================================================================
4639
4640 void _ViscousBuilder::makeGroupOfLE()
4641 {
4642 #ifdef _DEBUG_
4643   for ( size_t i = 0 ; i < _sdVec.size(); ++i )
4644   {
4645     if ( _sdVec[i]._n2eMap.empty() ) continue;
4646
4647     dumpFunction( SMESH_Comment("make_LayerEdge_") << i );
4648     TNode2Edge::iterator n2e;
4649     for ( n2e = _sdVec[i]._n2eMap.begin(); n2e != _sdVec[i]._n2eMap.end(); ++n2e )
4650     {
4651       _LayerEdge* le = n2e->second;
4652       // for ( size_t iN = 1; iN < le->_nodes.size(); ++iN )
4653       //   dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[iN-1]->GetID()
4654       //           << ", " << le->_nodes[iN]->GetID() <<"])");
4655       if ( le ) {
4656         dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[0]->GetID()
4657                 << ", " << le->_nodes.back()->GetID() <<"]) # " << le->_flags );
4658       }
4659     }
4660     dumpFunctionEnd();
4661
4662     dumpFunction( SMESH_Comment("makeNormals") << i );
4663     for ( n2e = _sdVec[i]._n2eMap.begin(); n2e != _sdVec[i]._n2eMap.end(); ++n2e )
4664     {
4665       _LayerEdge* edge = n2e->second;
4666       SMESH_TNodeXYZ nXYZ( edge->_nodes[0] );
4667       nXYZ += edge->_normal * _sdVec[i]._stepSize;
4668       dumpCmd(SMESH_Comment("mesh.AddEdge([ ") << edge->_nodes[0]->GetID()
4669               << ", mesh.AddNode( "<< nXYZ.X()<<","<< nXYZ.Y()<<","<< nXYZ.Z()<<")])");
4670     }
4671     dumpFunctionEnd();
4672
4673     dumpFunction( SMESH_Comment("makeTmpFaces_") << i );
4674     dumpCmd( "faceId1 = mesh.NbElements()" );
4675     TopExp_Explorer fExp( _sdVec[i]._solid, TopAbs_FACE );
4676     for ( ; fExp.More(); fExp.Next() )
4677     {
4678       if ( const SMESHDS_SubMesh* sm = _sdVec[i]._proxyMesh->GetProxySubMesh( fExp.Current() ))
4679       {
4680         if ( sm->NbElements() == 0 ) continue;
4681         SMDS_ElemIteratorPtr fIt = sm->GetElements();
4682         while ( fIt->more())
4683         {
4684           const SMDS_MeshElement* e = fIt->next();
4685           SMESH_Comment cmd("mesh.AddFace([");
4686           for ( int j = 0; j < e->NbCornerNodes(); ++j )
4687             cmd << e->GetNode(j)->GetID() << (j+1 < e->NbCornerNodes() ? ",": "])");
4688           dumpCmd( cmd );
4689         }
4690       }
4691     }
4692     dumpCmd( "faceId2 = mesh.NbElements()" );
4693     dumpCmd( SMESH_Comment( "mesh.MakeGroup( 'tmpFaces_" ) << i << "',"
4694              << "SMESH.FACE, SMESH.FT_RangeOfIds,'=',"
4695              << "'%s-%s' % (faceId1+1, faceId2))");
4696     dumpFunctionEnd();
4697   }
4698 #endif
4699 }
4700
4701 //================================================================================
4702 /*!
4703  * \brief Find maximal _LayerEdge length (layer thickness) limited by geometry
4704  */
4705 //================================================================================
4706
4707 void _ViscousBuilder::computeGeomSize( _SolidData& data )
4708 {
4709   data._geomSize = Precision::Infinite();
4710   double intersecDist;
4711   const SMDS_MeshElement* face;
4712   SMESH_MesherHelper helper( *_mesh );
4713
4714   SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
4715     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
4716                                            data._proxyMesh->GetFaces( data._solid )));
4717
4718   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4719   {
4720     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4721     if ( eos._edges.empty() )
4722       continue;
4723     // get neighbor faces, intersection with which should not be considered since
4724     // collisions are avoided by means of smoothing
4725     set< TGeomID > neighborFaces;
4726     if ( eos._hyp.ToSmooth() )
4727     {
4728       SMESH_subMeshIteratorPtr subIt =
4729         eos._subMesh->getDependsOnIterator(/*includeSelf=*/eos.ShapeType() != TopAbs_FACE );
4730       while ( subIt->more() )
4731       {
4732         SMESH_subMesh* sm = subIt->next();
4733         PShapeIteratorPtr fIt = helper.GetAncestors( sm->GetSubShape(), *_mesh, TopAbs_FACE );
4734         while ( const TopoDS_Shape* face = fIt->next() )
4735           neighborFaces.insert( getMeshDS()->ShapeToIndex( *face ));
4736       }
4737     }
4738     // find intersections
4739     double thinkness = eos._hyp.GetTotalThickness();
4740     for ( size_t i = 0; i < eos._edges.size(); ++i )
4741     {
4742       if ( eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
4743       eos._edges[i]->SetMaxLen( thinkness );
4744       eos._edges[i]->FindIntersection( *searcher, intersecDist, data._epsilon, eos, &face );
4745       if ( intersecDist > 0 && face )
4746       {
4747         data._geomSize = Min( data._geomSize, intersecDist );
4748         if ( !neighborFaces.count( face->getshapeId() ))
4749           eos[i]->SetMaxLen( Min( thinkness, intersecDist / ( face->GetID() < 0 ? 3. : 2. )));
4750       }
4751     }
4752   }
4753
4754   data._maxThickness = 0;
4755   data._minThickness = 1e100;
4756   list< const StdMeshers_ViscousLayers* >::iterator hyp = data._hyps.begin();
4757   for ( ; hyp != data._hyps.end(); ++hyp )
4758   {
4759     data._maxThickness = Max( data._maxThickness, (*hyp)->GetTotalThickness() );
4760     data._minThickness = Min( data._minThickness, (*hyp)->GetTotalThickness() );
4761   }
4762
4763   // Limit inflation step size by geometry size found by intersecting
4764   // normals of _LayerEdge's with mesh faces
4765   if ( data._stepSize > 0.3 * data._geomSize )
4766     limitStepSize( data, 0.3 * data._geomSize );
4767
4768   if ( data._stepSize > data._minThickness )
4769     limitStepSize( data, data._minThickness );
4770
4771
4772   // -------------------------------------------------------------------------
4773   // Detect _LayerEdge which can't intersect with opposite or neighbor layer,
4774   // so no need in detecting intersection at each inflation step
4775   // -------------------------------------------------------------------------
4776
4777   int nbSteps = data._maxThickness / data._stepSize;
4778   if ( nbSteps < 3 || nbSteps * data._n2eMap.size() < 100000 )
4779     return;
4780
4781   vector< const SMDS_MeshElement* > closeFaces;
4782   int nbDetected = 0;
4783
4784   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4785   {
4786     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4787     if ( eos._edges.empty() || eos.ShapeType() != TopAbs_FACE )
4788       continue;
4789
4790     for ( size_t i = 0; i < eos.size(); ++i )
4791     {
4792       SMESH_NodeXYZ p( eos[i]->_nodes[0] );
4793       double radius = data._maxThickness + 2 * eos[i]->_maxLen;
4794       closeFaces.clear();
4795       searcher->GetElementsInSphere( p, radius, SMDSAbs_Face, closeFaces );
4796
4797       bool toIgnore = true;
4798       for ( size_t iF = 0; iF < closeFaces.size()  && toIgnore; ++iF )
4799         if ( !( toIgnore = ( closeFaces[ iF ]->getshapeId() == eos._shapeID ||
4800                              data._ignoreFaceIds.count( closeFaces[ iF ]->getshapeId() ))))
4801         {
4802           // check if a _LayerEdge will inflate in a direction opposite to a direction
4803           // toward a close face
4804           bool allBehind = true;
4805           for ( int iN = 0; iN < closeFaces[ iF ]->NbCornerNodes()  && allBehind; ++iN )
4806           {
4807             SMESH_NodeXYZ pi( closeFaces[ iF ]->GetNode( iN ));
4808             allBehind = (( pi - p ) * eos[i]->_normal < 0.1 * data._stepSize );
4809           }
4810           toIgnore = allBehind;
4811         }
4812
4813
4814       if ( toIgnore ) // no need to detect intersection
4815       {
4816         eos[i]->Set( _LayerEdge::INTERSECTED );
4817         ++nbDetected;
4818       }
4819     }
4820   }
4821
4822   debugMsg( "Nb LE to intersect " << data._n2eMap.size()-nbDetected << ", ignore " << nbDetected );
4823
4824   return;
4825 }
4826
4827 //================================================================================
4828 /*!
4829  * \brief Increase length of _LayerEdge's to reach the required thickness of layers
4830  */
4831 //================================================================================
4832
4833 bool _ViscousBuilder::inflate(_SolidData& data)
4834 {
4835   SMESH_MesherHelper helper( *_mesh );
4836
4837   const double tgtThick = data._maxThickness;
4838
4839   if ( data._stepSize < 1. )
4840     data._epsilon = data._stepSize * 1e-7;
4841
4842   debugMsg( "-- geomSize = " << data._geomSize << ", stepSize = " << data._stepSize );
4843   _pyDump->Pause();
4844
4845   findCollisionEdges( data, helper );
4846
4847   limitMaxLenByCurvature( data, helper );
4848
4849   _pyDump->Resume();
4850
4851   // limit length of _LayerEdge's around MULTI_NORMAL _LayerEdge's
4852   for ( size_t i = 0; i < data._edgesOnShape.size(); ++i )
4853     if ( data._edgesOnShape[i].ShapeType() == TopAbs_VERTEX &&
4854          data._edgesOnShape[i]._edges.size() > 0 &&
4855          data._edgesOnShape[i]._edges[0]->Is( _LayerEdge::MULTI_NORMAL ))
4856     {
4857       data._edgesOnShape[i]._edges[0]->Unset( _LayerEdge::BLOCKED );
4858       data._edgesOnShape[i]._edges[0]->Block( data );
4859     }
4860
4861   const double safeFactor = ( 2*data._maxThickness < data._geomSize ) ? 1 : theThickToIntersection;
4862
4863   double avgThick = 0, curThick = 0, distToIntersection = Precision::Infinite();
4864   int nbSteps = 0, nbRepeats = 0;
4865   while ( avgThick < 0.99 )
4866   {
4867     // new target length
4868     double prevThick = curThick;
4869     curThick += data._stepSize;
4870     if ( curThick > tgtThick )
4871     {
4872       curThick = tgtThick + tgtThick*( 1.-avgThick ) * nbRepeats;
4873       nbRepeats++;
4874     }
4875
4876     double stepSize = curThick - prevThick;
4877     updateNormalsOfSmoothed( data, helper, nbSteps, stepSize ); // to ease smoothing
4878
4879     // Elongate _LayerEdge's
4880     dumpFunction(SMESH_Comment("inflate")<<data._index<<"_step"<<nbSteps); // debug
4881     for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4882     {
4883       _EdgesOnShape& eos = data._edgesOnShape[iS];
4884       if ( eos._edges.empty() ) continue;
4885
4886       const double shapeCurThick = Min( curThick, eos._hyp.GetTotalThickness() );
4887       for ( size_t i = 0; i < eos._edges.size(); ++i )
4888       {
4889         eos._edges[i]->SetNewLength( shapeCurThick, eos, helper );
4890       }
4891     }
4892     dumpFunctionEnd();
4893
4894     if ( !updateNormals( data, helper, nbSteps, stepSize )) // to avoid collisions
4895       return false;
4896
4897     // Improve and check quality
4898     if ( !smoothAndCheck( data, nbSteps, distToIntersection ))
4899     {
4900       if ( nbSteps > 0 )
4901       {
4902 #ifdef __NOT_INVALIDATE_BAD_SMOOTH
4903         debugMsg("NOT INVALIDATED STEP!");
4904         return error("Smoothing failed", data._index);
4905 #endif
4906         dumpFunction(SMESH_Comment("invalidate")<<data._index<<"_step"<<nbSteps); // debug
4907         for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4908         {
4909           _EdgesOnShape& eos = data._edgesOnShape[iS];
4910           for ( size_t i = 0; i < eos._edges.size(); ++i )
4911             eos._edges[i]->InvalidateStep( nbSteps+1, eos );
4912         }
4913         dumpFunctionEnd();
4914       }
4915       break; // no more inflating possible
4916     }
4917     nbSteps++;
4918
4919     // Evaluate achieved thickness
4920     avgThick = 0;
4921     int nbActiveEdges = 0;
4922     for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4923     {
4924       _EdgesOnShape& eos = data._edgesOnShape[iS];
4925       if ( eos._edges.empty() ) continue;
4926
4927       const double shapeTgtThick = eos._hyp.GetTotalThickness();
4928       for ( size_t i = 0; i < eos._edges.size(); ++i )
4929       {
4930         if ( eos._edges[i]->_nodes.size() > 1 )
4931           avgThick    += Min( 1., eos._edges[i]->_len / shapeTgtThick );
4932         else
4933           avgThick    += shapeTgtThick;
4934         nbActiveEdges += ( ! eos._edges[i]->Is( _LayerEdge::BLOCKED ));
4935       }
4936     }
4937     avgThick /= data._n2eMap.size();
4938     debugMsg( "-- Thickness " << curThick << " ("<< avgThick*100 << "%) reached" );
4939
4940 #ifdef BLOCK_INFLATION
4941     if ( nbActiveEdges == 0 )
4942     {
4943       debugMsg( "-- Stop inflation since all _LayerEdge's BLOCKED " );
4944       break;
4945     }
4946 #else
4947     if ( distToIntersection < tgtThick * avgThick * safeFactor && avgThick < 0.9 )
4948     {
4949       debugMsg( "-- Stop inflation since "
4950                 << " distToIntersection( "<<distToIntersection<<" ) < avgThick( "
4951                 << tgtThick * avgThick << " ) * " << safeFactor );
4952       break;
4953     }
4954 #endif
4955
4956     // new step size
4957     limitStepSize( data, 0.25 * distToIntersection );
4958     if ( data._stepSizeNodes[0] )
4959       data._stepSize = data._stepSizeCoeff *
4960         SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
4961
4962   } // while ( avgThick < 0.99 )
4963
4964   if ( nbSteps == 0 )
4965     return error("failed at the very first inflation step", data._index);
4966
4967   if ( avgThick < 0.99 )
4968   {
4969     if ( !data._proxyMesh->_warning || data._proxyMesh->_warning->IsOK() )
4970     {
4971       data._proxyMesh->_warning.reset
4972         ( new SMESH_ComputeError (COMPERR_WARNING,
4973                                   SMESH_Comment("Thickness ") << tgtThick <<
4974                                   " of viscous layers not reached,"
4975                                   " average reached thickness is " << avgThick*tgtThick));
4976     }
4977   }
4978
4979   // Restore position of src nodes moved by inflation on _noShrinkShapes
4980   dumpFunction(SMESH_Comment("restoNoShrink_So")<<data._index); // debug
4981   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4982   {
4983     _EdgesOnShape& eos = data._edgesOnShape[iS];
4984     if ( !eos._edges.empty() && eos._edges[0]->_nodes.size() == 1 )
4985       for ( size_t i = 0; i < eos._edges.size(); ++i )
4986       {
4987         restoreNoShrink( *eos._edges[ i ] );
4988       }
4989   }
4990   dumpFunctionEnd();
4991
4992   return safeFactor > 0; // == true (avoid warning: unused variable 'safeFactor')
4993 }
4994
4995 //================================================================================
4996 /*!
4997  * \brief Improve quality of layer inner surface and check intersection
4998  */
4999 //================================================================================
5000
5001 bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
5002                                      const int   infStep,
5003                                      double &    distToIntersection)
5004 {
5005   if ( data._nbShapesToSmooth == 0 )
5006     return true; // no shapes needing smoothing
5007
5008   bool moved, improved;
5009   double vol;
5010   vector< _LayerEdge* >    movedEdges, badEdges;
5011   vector< _EdgesOnShape* > eosC1; // C1 continues shapes
5012   vector< bool >           isConcaveFace;
5013
5014   SMESH_MesherHelper helper(*_mesh);
5015   Handle(ShapeAnalysis_Surface) surface;
5016   TopoDS_Face F;
5017
5018   for ( int isFace = 0; isFace < 2; ++isFace ) // smooth on [ EDGEs, FACEs ]
5019   {
5020     const TopAbs_ShapeEnum shapeType = isFace ? TopAbs_FACE : TopAbs_EDGE;
5021
5022     for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
5023     {
5024       _EdgesOnShape& eos = data._edgesOnShape[ iS ];
5025       if ( !eos._toSmooth ||
5026            eos.ShapeType() != shapeType ||
5027            eos._edges.empty() )
5028         continue;
5029
5030       // already smoothed?
5031       // bool toSmooth = ( eos._edges[ 0 ]->NbSteps() >= infStep+1 );
5032       // if ( !toSmooth ) continue;
5033
5034       if ( !eos._hyp.ToSmooth() )
5035       {
5036         // smooth disabled by the user; check validy only
5037         if ( !isFace ) continue;
5038         badEdges.clear();
5039         for ( size_t i = 0; i < eos._edges.size(); ++i )
5040         {
5041           _LayerEdge* edge = eos._edges[i];
5042           for ( size_t iF = 0; iF < edge->_simplices.size(); ++iF )
5043             if ( !edge->_simplices[iF].IsForward( edge->_nodes[0], edge->_pos.back(), vol ))
5044             {
5045               // debugMsg( "-- Stop inflation. Bad simplex ("
5046               //           << " "<< edge->_nodes[0]->GetID()
5047               //           << " "<< edge->_nodes.back()->GetID()
5048               //           << " "<< edge->_simplices[iF]._nPrev->GetID()
5049               //           << " "<< edge->_simplices[iF]._nNext->GetID() << " ) ");
5050               // return false;
5051               badEdges.push_back( edge );
5052             }
5053         }
5054         if ( !badEdges.empty() )
5055         {
5056           eosC1.resize(1);
5057           eosC1[0] = &eos;
5058           int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
5059           if ( nbBad > 0 )
5060             return false;
5061         }
5062         continue; // goto the next EDGE or FACE
5063       }
5064
5065       // prepare data
5066       if ( eos.SWOLType() == TopAbs_FACE )
5067       {
5068         if ( !F.IsSame( eos._sWOL )) {
5069           F = TopoDS::Face( eos._sWOL );
5070           helper.SetSubShape( F );
5071           surface = helper.GetSurface( F );
5072         }
5073       }
5074       else
5075       {
5076         F.Nullify(); surface.Nullify();
5077       }
5078       const TGeomID sInd = eos._shapeID;
5079
5080       // perform smoothing
5081
5082       if ( eos.ShapeType() == TopAbs_EDGE )
5083       {
5084         dumpFunction(SMESH_Comment("smooth")<<data._index << "_Ed"<<sInd <<"_InfStep"<<infStep);
5085
5086         if ( !eos._edgeSmoother->Perform( data, surface, F, helper ))
5087         {
5088           // smooth on EDGE's (normally we should not get here)
5089           int step = 0;
5090           do {
5091             moved = false;
5092             for ( size_t i = 0; i < eos._edges.size(); ++i )
5093             {
5094               moved |= eos._edges[i]->SmoothOnEdge( surface, F, helper );
5095             }
5096             dumpCmd( SMESH_Comment("# end step ")<<step);
5097           }
5098           while ( moved && step++ < 5 );
5099         }
5100         dumpFunctionEnd();
5101       }
5102
5103       else // smooth on FACE
5104       {
5105         eosC1.clear();
5106         eosC1.push_back( & eos );
5107         eosC1.insert( eosC1.end(), eos._eosC1.begin(), eos._eosC1.end() );
5108
5109         movedEdges.clear();
5110         isConcaveFace.resize( eosC1.size() );
5111         for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
5112         {
5113           isConcaveFace[ iEOS ] = data._concaveFaces.count( eosC1[ iEOS ]->_shapeID  );
5114
5115           if ( eosC1[ iEOS ]->_mapper2D )
5116           {
5117             // compute node position by boundary node position in structured mesh
5118             dumpFunction(SMESH_Comment("map2dS")<<data._index<<"_Fa"<<eos._shapeID
5119                          <<"_InfStep"<<infStep);
5120
5121             eosC1[ iEOS ]->_mapper2D->ComputeNodePositions();
5122
5123             for ( _LayerEdge* le : eosC1[ iEOS ]->_edges )
5124               le->_pos.back() = SMESH_NodeXYZ( le->_nodes.back() );
5125
5126             dumpFunctionEnd();
5127           }
5128           else
5129           {
5130             for ( _LayerEdge* le : eosC1[ iEOS ]->_edges )
5131               if ( le->Is( _LayerEdge::MOVED ) ||
5132                    le->Is( _LayerEdge::NEAR_BOUNDARY ))
5133                 movedEdges.push_back( le );
5134           }
5135           makeOffsetSurface( *eosC1[ iEOS ], helper );
5136         }
5137
5138         int step = 0, stepLimit = 5, nbBad = 0;
5139         while (( ++step <= stepLimit ) || improved )
5140         {
5141           int oldBadNb = nbBad;
5142           badEdges.clear();
5143
5144 #ifdef INCREMENTAL_SMOOTH
5145           // smooth moved only
5146           if ( !movedEdges.empty() )
5147             dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
5148                          <<"_InfStep"<<infStep<<"_"<<step); // debug
5149           bool findBest = false; // ( step == stepLimit );
5150           for ( size_t i = 0; i < movedEdges.size(); ++i )
5151           {
5152             movedEdges[i]->Unset( _LayerEdge::SMOOTHED );
5153             if ( movedEdges[i]->Smooth( step, findBest, movedEdges ) > 0 )
5154               badEdges.push_back( movedEdges[i] );
5155           }
5156 #else
5157           // smooth all
5158           dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
5159                        <<"_InfStep"<<infStep<<"_"<<step); // debug
5160           bool findBest = ( step == stepLimit || isConcaveFace[ iEOS ]);
5161           for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
5162           {
5163             if ( eosC1[ iEOS ]->_mapper2D )
5164               continue;
5165             vector< _LayerEdge* > & edges = eosC1[ iEOS ]->_edges;
5166             for ( size_t i = 0; i < edges.size(); ++i )
5167             {
5168               edges[i]->Unset( _LayerEdge::SMOOTHED );
5169               if ( edges[i]->Smooth( step, findBest, false ) > 0 )
5170                 badEdges.push_back( eos._edges[i] );
5171             }
5172           }
5173 #endif
5174           nbBad = badEdges.size();
5175
5176           if ( nbBad > 0 )
5177             debugMsg(SMESH_Comment("nbBad = ") << nbBad );
5178
5179           if ( !badEdges.empty() && step >= stepLimit / 2 )
5180           {
5181             if ( badEdges[0]->Is( _LayerEdge::ON_CONCAVE_FACE ))
5182               stepLimit = 9;
5183
5184             // resolve hard smoothing situation around concave VERTEXes
5185             for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
5186             {
5187               vector< _EdgesOnShape* > & eosCoVe = eosC1[ iEOS ]->_eosConcaVer;
5188               for ( size_t i = 0; i < eosCoVe.size(); ++i )
5189                 eosCoVe[i]->_edges[0]->MoveNearConcaVer( eosCoVe[i], eosC1[ iEOS ],
5190                                                          step, badEdges );
5191             }
5192             // look for the best smooth of _LayerEdge's neighboring badEdges
5193             nbBad = 0;
5194             for ( size_t i = 0; i < badEdges.size(); ++i )
5195             {
5196               _LayerEdge* ledge = badEdges[i];
5197               for ( size_t iN = 0; iN < ledge->_neibors.size(); ++iN )
5198               {
5199                 ledge->_neibors[iN]->Unset( _LayerEdge::SMOOTHED );
5200                 nbBad += ledge->_neibors[iN]->Smooth( step, true, /*findBest=*/true );
5201               }
5202               ledge->Unset( _LayerEdge::SMOOTHED );
5203               nbBad += ledge->Smooth( step, true, /*findBest=*/true );
5204             }
5205             debugMsg(SMESH_Comment("nbBad = ") << nbBad );
5206           }
5207
5208           if ( nbBad == oldBadNb  &&
5209                nbBad > 0 &&
5210                step < stepLimit ) // smooth w/o check of validity
5211           {
5212             dumpFunctionEnd();
5213             dumpFunction(SMESH_Comment("smoothWoCheck")<<data._index<<"_Fa"<<sInd
5214                          <<"_InfStep"<<infStep<<"_"<<step); // debug
5215             for ( size_t i = 0; i < movedEdges.size(); ++i )
5216             {
5217               movedEdges[i]->SmoothWoCheck();
5218             }
5219             if ( stepLimit < 9 )
5220               stepLimit++;
5221           }
5222
5223           improved = ( nbBad < oldBadNb );
5224
5225           dumpFunctionEnd();
5226
5227           if (( step % 3 == 1 ) || ( nbBad > 0 && step >= stepLimit / 2 ))
5228             for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
5229             {
5230               putOnOffsetSurface( *eosC1[ iEOS ], infStep, eosC1, step, /*moveAll=*/step == 1 );
5231             }
5232
5233         } // smoothing steps
5234
5235         // project -- to prevent intersections or to fix bad simplices
5236         for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
5237         {
5238           if ( ! eosC1[ iEOS ]->_eosConcaVer.empty() || nbBad > 0 )
5239             putOnOffsetSurface( *eosC1[ iEOS ], -infStep, eosC1 );
5240         }
5241
5242         //if ( !badEdges.empty() )
5243         {
5244           badEdges.clear();
5245           for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
5246           {
5247             for ( size_t i = 0; i < eosC1[ iEOS ]->_edges.size(); ++i )
5248             {
5249               if ( !eosC1[ iEOS ]->_sWOL.IsNull() ) continue;
5250
5251               _LayerEdge* edge = eosC1[ iEOS ]->_edges[i];
5252               edge->CheckNeiborsOnBoundary( & badEdges );
5253               if (( nbBad > 0 ) ||
5254                   ( edge->Is( _LayerEdge::BLOCKED ) && edge->Is( _LayerEdge::NEAR_BOUNDARY )))
5255               {
5256                 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
5257                 gp_XYZ        prevXYZ = edge->PrevCheckPos();
5258                 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5259                   if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
5260                   {
5261                     debugMsg("Bad simplex ( " << edge->_nodes[0]->GetID()
5262                              << " "<< tgtXYZ._node->GetID()
5263                              << " "<< edge->_simplices[j]._nPrev->GetID()
5264                              << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
5265                     badEdges.push_back( edge );
5266                     break;
5267                   }
5268               }
5269             }
5270           }
5271
5272           // try to fix bad simplices by removing the last inflation step of some _LayerEdge's
5273           nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
5274
5275           if ( nbBad > 0 )
5276             return false;
5277         }
5278
5279       } // // smooth on FACE's
5280     } // loop on shapes
5281   } // smooth on [ EDGEs, FACEs ]
5282
5283   // Check orientation of simplices of _LayerEdge's on EDGEs and VERTEXes
5284   eosC1.resize(1);
5285   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
5286   {
5287     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
5288     if ( eos.ShapeType() == TopAbs_FACE ||
5289          eos._edges.empty() ||
5290          !eos._sWOL.IsNull() )
5291       continue;
5292
5293     badEdges.clear();
5294     for ( size_t i = 0; i < eos._edges.size(); ++i )
5295     {
5296       _LayerEdge*      edge = eos._edges[i];
5297       if ( edge->_nodes.size() < 2 ) continue;
5298       SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
5299       //SMESH_TNodeXYZ prevXYZ = edge->_nodes[0];
5300       gp_XYZ        prevXYZ = edge->PrevCheckPos( &eos );
5301       //const gp_XYZ& prevXYZ = edge->PrevPos();
5302       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5303         if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
5304         {
5305           debugMsg("Bad simplex on bnd ( " << edge->_nodes[0]->GetID()
5306                    << " "<< tgtXYZ._node->GetID()
5307                    << " "<< edge->_simplices[j]._nPrev->GetID()
5308                    << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
5309           badEdges.push_back( edge );
5310           break;
5311         }
5312     }
5313
5314     // try to fix bad simplices by removing the last inflation step of some _LayerEdge's
5315     eosC1[0] = &eos;
5316     int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
5317     if ( nbBad > 0 )
5318       return false;
5319   }
5320
5321
5322   // Check if the last segments of _LayerEdge intersects 2D elements;
5323   // checked elements are either temporary faces or faces on surfaces w/o the layers
5324
5325   SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
5326     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
5327                                            data._proxyMesh->GetFaces( data._solid )) );
5328
5329 #ifdef BLOCK_INFLATION
5330   const bool toBlockInfaltion = true;
5331 #else
5332   const bool toBlockInfaltion = false;
5333 #endif
5334   distToIntersection = Precision::Infinite();
5335   double dist;
5336   const SMDS_MeshElement* intFace = 0;
5337   const SMDS_MeshElement* closestFace = 0;
5338   _LayerEdge* le = 0;
5339   bool is1stBlocked = true; // dbg
5340   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
5341   {
5342     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
5343     if ( eos._edges.empty() || !eos._sWOL.IsNull() )
5344       continue;
5345     for ( size_t i = 0; i < eos._edges.size(); ++i )
5346     {
5347       if ( eos._edges[i]->Is( _LayerEdge::INTERSECTED ) ||
5348            eos._edges[i]->Is( _LayerEdge::MULTI_NORMAL ))
5349         continue;
5350       if ( eos._edges[i]->FindIntersection( *searcher, dist, data._epsilon, eos, &intFace ))
5351       {
5352         return false;
5353         // commented due to "Illegal hash-positionPosition" error in NETGEN
5354         // on Debian60 on viscous_layers_01/B2 case
5355         // Collision; try to deflate _LayerEdge's causing it
5356         // badEdges.clear();
5357         // badEdges.push_back( eos._edges[i] );
5358         // eosC1[0] = & eos;
5359         // int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
5360         // if ( nbBad > 0 )
5361         //   return false;
5362
5363         // badEdges.clear();
5364         // if ( _EdgesOnShape* eof = data.GetShapeEdges( intFace->getshapeId() ))
5365         // {
5366         //   if ( const _TmpMeshFace* f = dynamic_cast< const _TmpMeshFace*>( intFace ))
5367         //   {
5368         //     const SMDS_MeshElement* srcFace =
5369         //       eof->_subMesh->GetSubMeshDS()->GetElement( f->getIdInShape() );
5370         //     SMDS_ElemIteratorPtr nIt = srcFace->nodesIterator();
5371         //     while ( nIt->more() )
5372         //     {
5373         //       const SMDS_MeshNode* srcNode = static_cast<const SMDS_MeshNode*>( nIt->next() );
5374         //       TNode2Edge::iterator n2e = data._n2eMap.find( srcNode );
5375         //       if ( n2e != data._n2eMap.end() )
5376         //         badEdges.push_back( n2e->second );
5377         //     }
5378         //     eosC1[0] = eof;
5379         //     nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
5380         //     if ( nbBad > 0 )
5381         //       return false;
5382         //   }
5383         // }
5384         // if ( eos._edges[i]->FindIntersection( *searcher, dist, data._epsilon, eos, &intFace ))
5385         //   return false;
5386         // else
5387         //   continue;
5388       }
5389       if ( !intFace )
5390       {
5391         SMESH_Comment msg("Invalid? normal at node "); msg << eos._edges[i]->_nodes[0]->GetID();
5392         debugMsg( msg );
5393         continue;
5394       }
5395
5396       const bool isShorterDist = ( distToIntersection > dist );
5397       if ( toBlockInfaltion || isShorterDist )
5398       {
5399         // ignore intersection of a _LayerEdge based on a _ConvexFace with a face
5400         // lying on this _ConvexFace
5401         if ( _ConvexFace* convFace = data.GetConvexFace( intFace->getshapeId() ))
5402           if ( convFace->_isTooCurved && convFace->_subIdToEOS.count ( eos._shapeID ))
5403             continue;
5404
5405         // ignore intersection of a _LayerEdge based on a FACE with an element on this FACE
5406         // ( avoid limiting the thickness on the case of issue 22576)
5407         if ( intFace->getshapeId() == eos._shapeID  )
5408           continue;
5409
5410         // ignore intersection with intFace of an adjacent FACE
5411         if ( dist > 0.01 * eos._edges[i]->_len )
5412         {
5413           bool toIgnore = false;
5414           if (  eos._toSmooth )
5415           {
5416             const TopoDS_Shape& S = getMeshDS()->IndexToShape( intFace->getshapeId() );
5417             if ( !S.IsNull() && S.ShapeType() == TopAbs_FACE )
5418             {
5419               TopExp_Explorer sub( eos._shape,
5420                                    eos.ShapeType() == TopAbs_FACE ? TopAbs_EDGE : TopAbs_VERTEX );
5421               for ( ; !toIgnore && sub.More(); sub.Next() )
5422                 // is adjacent - has a common EDGE or VERTEX
5423                 toIgnore = ( helper.IsSubShape( sub.Current(), S ));
5424
5425               if ( toIgnore ) // check angle between normals
5426               {
5427                 gp_XYZ normal;
5428                 if ( SMESH_MeshAlgos::FaceNormal( intFace, normal, /*normalized=*/true ))
5429                   toIgnore  = ( normal * eos._edges[i]->_normal > -0.5 );
5430               }
5431             }
5432           }
5433           if ( !toIgnore ) // check if the edge is a neighbor of intFace
5434           {
5435             for ( size_t iN = 0; !toIgnore &&  iN < eos._edges[i]->_neibors.size(); ++iN )
5436             {
5437               int nInd = intFace->GetNodeIndex( eos._edges[i]->_neibors[ iN ]->_nodes.back() );
5438               toIgnore = ( nInd >= 0 );
5439             }
5440           }
5441           if ( toIgnore )
5442             continue;
5443         }
5444
5445         // intersection not ignored
5446
5447         if ( toBlockInfaltion &&
5448              dist < ( eos._edges[i]->_len * theThickToIntersection ))
5449         {
5450           if ( is1stBlocked ) { is1stBlocked = false; // debug
5451             dumpFunction(SMESH_Comment("blockIntersected") <<data._index<<"_InfStep"<<infStep);
5452           }
5453           eos._edges[i]->Set( _LayerEdge::INTERSECTED ); // not to intersect
5454           eos._edges[i]->Block( data );                  // not to inflate
5455
5456           //if ( _EdgesOnShape* eof = data.GetShapeEdges( intFace->getshapeId() ))
5457           {
5458             // block _LayerEdge's, on top of which intFace is
5459             if ( const _TmpMeshFace* f = dynamic_cast< const _TmpMeshFace*>( intFace ))
5460             {
5461               const SMDS_MeshElement* srcFace = f->_srcFace;
5462               SMDS_ElemIteratorPtr        nIt = srcFace->nodesIterator();
5463               while ( nIt->more() )
5464               {
5465                 const SMDS_MeshNode* srcNode = static_cast<const SMDS_MeshNode*>( nIt->next() );
5466                 TNode2Edge::iterator n2e = data._n2eMap.find( srcNode );
5467                 if ( n2e != data._n2eMap.end() )
5468                   n2e->second->Block( data );
5469               }
5470             }
5471           }
5472         }
5473
5474         if ( isShorterDist )
5475         {
5476           distToIntersection = dist;
5477           le = eos._edges[i];
5478           closestFace = intFace;
5479         }
5480
5481       } // if ( toBlockInfaltion || isShorterDist )
5482     } // loop on eos._edges
5483   } // loop on data._edgesOnShape
5484
5485   if ( !is1stBlocked )
5486   {
5487     dumpFunctionEnd();
5488   }
5489
5490   if ( closestFace && le )
5491   {
5492 #ifdef __myDEBUG
5493     SMDS_MeshElement::iterator nIt = closestFace->begin_nodes();
5494     cout << "#Shortest distance: _LayerEdge nodes: tgt " << le->_nodes.back()->GetID()
5495          << " src " << le->_nodes[0]->GetID()<< ", intersection with face ("
5496          << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
5497          << ") distance = " << distToIntersection<< endl;
5498 #endif
5499   }
5500
5501   return true;
5502 }
5503
5504 //================================================================================
5505 /*!
5506  * \brief try to fix bad simplices by removing the last inflation step of some _LayerEdge's
5507  *  \param [in,out] badSmooEdges - _LayerEdge's to fix
5508  *  \return int - resulting nb of bad _LayerEdge's
5509  */
5510 //================================================================================
5511
5512 int _ViscousBuilder::invalidateBadSmooth( _SolidData&               data,
5513                                           SMESH_MesherHelper&       helper,
5514                                           vector< _LayerEdge* >&    badSmooEdges,
5515                                           vector< _EdgesOnShape* >& eosC1,
5516                                           const int                 infStep )
5517 {
5518   if ( badSmooEdges.empty() || infStep == 0 ) return 0;
5519
5520   dumpFunction(SMESH_Comment("invalidateBadSmooth")<<"_S"<<eosC1[0]->_shapeID<<"_InfStep"<<infStep);
5521
5522   enum {
5523     INVALIDATED   = _LayerEdge::UNUSED_FLAG,
5524     TO_INVALIDATE = _LayerEdge::UNUSED_FLAG * 2,
5525     ADDED         = _LayerEdge::UNUSED_FLAG * 4
5526   };
5527   data.UnmarkEdges( TO_INVALIDATE & INVALIDATED & ADDED );
5528
5529   double vol;
5530   bool haveInvalidated = true;
5531   while ( haveInvalidated )
5532   {
5533     haveInvalidated = false;
5534     for ( size_t i = 0; i < badSmooEdges.size(); ++i )
5535     {
5536       _LayerEdge*   edge = badSmooEdges[i];
5537       _EdgesOnShape* eos = data.GetShapeEdges( edge );
5538       edge->Set( ADDED );
5539       bool invalidated = false;
5540       if ( edge->Is( TO_INVALIDATE ) && edge->NbSteps() > 1 )
5541       {
5542         edge->InvalidateStep( edge->NbSteps(), *eos, /*restoreLength=*/true );
5543         edge->Block( data );
5544         edge->Set( INVALIDATED );
5545         edge->Unset( TO_INVALIDATE );
5546         invalidated = true;
5547         haveInvalidated = true;
5548       }
5549
5550       // look for _LayerEdge's of bad _simplices
5551       int nbBad = 0;
5552       SMESH_TNodeXYZ tgtXYZ  = edge->_nodes.back();
5553       gp_XYZ        prevXYZ1 = edge->PrevCheckPos( eos );
5554       //const gp_XYZ& prevXYZ2 = edge->PrevPos();
5555       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5556       {
5557         if (( edge->_simplices[j].IsForward( &prevXYZ1, &tgtXYZ, vol ))/* &&
5558             ( &prevXYZ1 == &prevXYZ2 || edge->_simplices[j].IsForward( &prevXYZ2, &tgtXYZ, vol ))*/)
5559           continue;
5560
5561         bool isBad = true;
5562         _LayerEdge* ee[2] = { 0,0 };
5563         for ( size_t iN = 0; iN < edge->_neibors.size() &&   !ee[1]  ; ++iN )
5564           if ( edge->_simplices[j].Includes( edge->_neibors[iN]->_nodes.back() ))
5565             ee[ ee[0] != 0 ] = edge->_neibors[iN];
5566
5567         int maxNbSteps = Max( ee[0]->NbSteps(), ee[1]->NbSteps() );
5568         while ( maxNbSteps > edge->NbSteps() && isBad )
5569         {
5570           --maxNbSteps;
5571           for ( int iE = 0; iE < 2; ++iE )
5572           {
5573             if ( ee[ iE ]->NbSteps() > maxNbSteps &&
5574                  ee[ iE ]->NbSteps() > 1 )
5575             {
5576               _EdgesOnShape* eos = data.GetShapeEdges( ee[ iE ] );
5577               ee[ iE ]->InvalidateStep( ee[ iE ]->NbSteps(), *eos, /*restoreLength=*/true );
5578               ee[ iE ]->Block( data );
5579               ee[ iE ]->Set( INVALIDATED );
5580               haveInvalidated = true;
5581             }
5582           }
5583           if (( edge->_simplices[j].IsForward( &prevXYZ1, &tgtXYZ, vol )) /*&&
5584               ( &prevXYZ1 == &prevXYZ2 || edge->_simplices[j].IsForward( &prevXYZ2, &tgtXYZ, vol ))*/)
5585             isBad = false;
5586         }
5587         nbBad += isBad;
5588         if ( !ee[0]->Is( ADDED )) badSmooEdges.push_back( ee[0] );
5589         if ( !ee[1]->Is( ADDED )) badSmooEdges.push_back( ee[1] );
5590         ee[0]->Set( ADDED );
5591         ee[1]->Set( ADDED );
5592         if ( isBad )
5593         {
5594           ee[0]->Set( TO_INVALIDATE );
5595           ee[1]->Set( TO_INVALIDATE );
5596         }
5597       }
5598
5599       if ( !invalidated &&  nbBad > 0  &&  edge->NbSteps() > 1 )
5600       {
5601         _EdgesOnShape* eos = data.GetShapeEdges( edge );
5602         edge->InvalidateStep( edge->NbSteps(), *eos, /*restoreLength=*/true );
5603         edge->Block( data );
5604         edge->Set( INVALIDATED );
5605         edge->Unset( TO_INVALIDATE );
5606         haveInvalidated = true;
5607       }
5608     } // loop on badSmooEdges
5609   } // while ( haveInvalidated )
5610
5611   // re-smooth on analytical EDGEs
5612   for ( size_t i = 0; i < badSmooEdges.size(); ++i )
5613   {
5614     _LayerEdge* edge = badSmooEdges[i];
5615     if ( !edge->Is( INVALIDATED )) continue;
5616
5617     _EdgesOnShape* eos = data.GetShapeEdges( edge );
5618     if ( eos->ShapeType() == TopAbs_VERTEX )
5619     {
5620       PShapeIteratorPtr eIt = helper.GetAncestors( eos->_shape, *_mesh, TopAbs_EDGE );
5621       while ( const TopoDS_Shape* e = eIt->next() )
5622         if ( _EdgesOnShape* eoe = data.GetShapeEdges( *e ))
5623           if ( eoe->_edgeSmoother && eoe->_edgeSmoother->isAnalytic() )
5624           {
5625             // TopoDS_Face F; Handle(ShapeAnalysis_Surface) surface;
5626             // if ( eoe->SWOLType() == TopAbs_FACE ) {
5627             //   F       = TopoDS::Face( eoe->_sWOL );
5628             //   surface = helper.GetSurface( F );
5629             // }
5630             // eoe->_edgeSmoother->Perform( data, surface, F, helper );
5631             eoe->_edgeSmoother->_anaCurve.Nullify();
5632           }
5633     }
5634   }
5635
5636
5637   // check result of invalidation
5638
5639   int nbBad = 0;
5640   for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
5641   {
5642     for ( size_t i = 0; i < eosC1[ iEOS ]->_edges.size(); ++i )
5643     {
5644       if ( !eosC1[ iEOS ]->_sWOL.IsNull() ) continue;
5645       _LayerEdge*      edge = eosC1[ iEOS ]->_edges[i];
5646       SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
5647       gp_XYZ        prevXYZ = edge->PrevCheckPos( eosC1[ iEOS ]);
5648       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5649         if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
5650         {
5651           ++nbBad;
5652           debugMsg("Bad simplex remains ( " << edge->_nodes[0]->GetID()
5653                    << " "<< tgtXYZ._node->GetID()
5654                    << " "<< edge->_simplices[j]._nPrev->GetID()
5655                    << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
5656         }
5657     }
5658   }
5659   dumpFunctionEnd();
5660
5661   return nbBad;
5662 }
5663
5664 //================================================================================
5665 /*!
5666  * \brief Create an offset surface
5667  */
5668 //================================================================================
5669
5670 void _ViscousBuilder::makeOffsetSurface( _EdgesOnShape& eos, SMESH_MesherHelper& helper )
5671 {
5672   if ( eos._offsetSurf.IsNull() ||
5673        eos._edgeForOffset == 0 ||
5674        eos._edgeForOffset->Is( _LayerEdge::BLOCKED ))
5675     return;
5676
5677   Handle(ShapeAnalysis_Surface) baseSurface = helper.GetSurface( TopoDS::Face( eos._shape ));
5678
5679   // find offset
5680   gp_Pnt   tgtP = SMESH_TNodeXYZ( eos._edgeForOffset->_nodes.back() );
5681   /*gp_Pnt2d uv=*/baseSurface->ValueOfUV( tgtP, Precision::Confusion() );
5682   eos._offsetValue = baseSurface->Gap();
5683
5684   eos._offsetSurf.Nullify();
5685
5686   try
5687   {
5688     BRepOffsetAPI_MakeOffsetShape offsetMaker;
5689     offsetMaker.PerformByJoin( eos._shape, -eos._offsetValue, Precision::Confusion() );
5690     if ( !offsetMaker.IsDone() ) return;
5691
5692     TopExp_Explorer fExp( offsetMaker.Shape(), TopAbs_FACE );
5693     if ( !fExp.More() ) return;
5694
5695     TopoDS_Face F = TopoDS::Face( fExp.Current() );
5696     Handle(Geom_Surface) surf = BRep_Tool::Surface( F );
5697     if ( surf.IsNull() ) return;
5698
5699     eos._offsetSurf = new ShapeAnalysis_Surface( surf );
5700   }
5701   catch ( Standard_Failure& )
5702   {
5703   }
5704 }
5705
5706 //================================================================================
5707 /*!
5708  * \brief Put nodes of a curved FACE to its offset surface
5709  */
5710 //================================================================================
5711
5712 void _ViscousBuilder::putOnOffsetSurface( _EdgesOnShape&            eos,
5713                                           int                       infStep,
5714                                           vector< _EdgesOnShape* >& eosC1,
5715                                           int                       smooStep,
5716                                           int                       moveAll )
5717 {
5718   _EdgesOnShape * eof = & eos;
5719   if ( eos.ShapeType() != TopAbs_FACE ) // eos is a boundary of C1 FACE, look for the FACE eos
5720   {
5721     eof = 0;
5722     for ( size_t i = 0; i < eosC1.size() && !eof; ++i )
5723     {
5724       if ( eosC1[i]->_offsetSurf.IsNull() ||
5725            eosC1[i]->ShapeType() != TopAbs_FACE ||
5726            eosC1[i]->_edgeForOffset == 0 ||
5727            eosC1[i]->_edgeForOffset->Is( _LayerEdge::BLOCKED ))
5728         continue;
5729       if ( SMESH_MesherHelper::IsSubShape( eos._shape, eosC1[i]->_shape ))
5730         eof = eosC1[i];
5731     }
5732   }
5733   if ( !eof ||
5734        eof->_offsetSurf.IsNull() ||
5735        eof->ShapeType() != TopAbs_FACE ||
5736        eof->_edgeForOffset == 0 ||
5737        eof->_edgeForOffset->Is( _LayerEdge::BLOCKED ))
5738     return;
5739
5740   double preci = BRep_Tool::Tolerance( TopoDS::Face( eof->_shape )), vol;
5741   bool neighborHasRiskySWOL = false;
5742   for ( size_t i = 0; i < eos._edges.size(); ++i )
5743   {
5744     _LayerEdge* edge = eos._edges[i];
5745     edge->Unset( _LayerEdge::MARKED );
5746     if ( edge->Is( _LayerEdge::BLOCKED ) || !edge->_curvature )
5747       continue;
5748     if ( moveAll == _LayerEdge::UPD_NORMAL_CONV )
5749     {
5750       if ( !edge->Is( _LayerEdge::UPD_NORMAL_CONV ))
5751         continue;
5752     }
5753     else if ( moveAll == _LayerEdge::RISKY_SWOL )
5754     {
5755       if ( !edge->Is( _LayerEdge::RISKY_SWOL ) ||
5756            edge->_cosin < 0 )
5757         continue;
5758     }
5759     else if ( !moveAll && !edge->Is( _LayerEdge::MOVED ))
5760       continue;
5761
5762     int nbBlockedAround = 0;
5763     for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
5764     {
5765       nbBlockedAround += edge->_neibors[iN]->Is( _LayerEdge::BLOCKED );
5766       if ( edge->_neibors[iN]->Is( _LayerEdge::RISKY_SWOL ) &&
5767            edge->_neibors[iN]->_cosin > 0 )
5768         neighborHasRiskySWOL = true;
5769     }
5770     if ( nbBlockedAround > 1 )
5771       continue;
5772
5773     gp_Pnt tgtP = SMESH_TNodeXYZ( edge->_nodes.back() );
5774     gp_Pnt2d uv = eof->_offsetSurf->NextValueOfUV( edge->_curvature->_uv, tgtP, preci );
5775     if ( eof->_offsetSurf->Gap() > edge->_len ) continue; // NextValueOfUV() bug
5776     edge->_curvature->_uv = uv;
5777     if ( eof->_offsetSurf->Gap() < 10 * preci ) continue; // same pos
5778
5779     gp_XYZ  newP = eof->_offsetSurf->Value( uv ).XYZ();
5780     gp_XYZ prevP = edge->PrevCheckPos();
5781     bool      ok = true;
5782     if ( !moveAll )
5783       for ( size_t iS = 0; iS < edge->_simplices.size() && ok; ++iS )
5784       {
5785         ok = edge->_simplices[iS].IsForward( &prevP, &newP, vol );
5786       }
5787     if ( ok )
5788     {
5789       SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( edge->_nodes.back() );
5790       n->setXYZ( newP.X(), newP.Y(), newP.Z());
5791       edge->_pos.back() = newP;
5792
5793       edge->Set( _LayerEdge::MARKED );
5794       if ( moveAll == _LayerEdge::UPD_NORMAL_CONV )
5795       {
5796         edge->_normal = ( newP - prevP ).Normalized();
5797       }
5798       // if ( edge->_len < eof->_offsetValue )
5799       //   edge->_len = eof->_offsetValue;
5800
5801       if ( !eos._sWOL.IsNull() ) // RISKY_SWOL
5802       {
5803         double change = eof->_offsetSurf->Gap() / eof->_offsetValue;
5804         if (( newP - tgtP.XYZ() ) * edge->_normal < 0 )
5805           change = 1 - change;
5806         else
5807           change = 1 + change;
5808         gp_XYZ shitfVec    = tgtP.XYZ() - SMESH_NodeXYZ( edge->_nodes[0] );
5809         gp_XYZ newShiftVec = shitfVec * change;
5810         double shift       = edge->_normal * shitfVec;
5811         double newShift    = edge->_normal * newShiftVec;
5812         newP = tgtP.XYZ() + edge->_normal * ( newShift - shift );
5813
5814         uv = eof->_offsetSurf->NextValueOfUV( edge->_curvature->_uv, newP, preci );
5815         if ( eof->_offsetSurf->Gap() < edge->_len )
5816         {
5817           edge->_curvature->_uv = uv;
5818           newP = eof->_offsetSurf->Value( uv ).XYZ();
5819         }
5820         n->setXYZ( newP.X(), newP.Y(), newP.Z());
5821         if ( !edge->UpdatePositionOnSWOL( n, /*tol=*/10 * edge->_len / ( edge->NbSteps() + 1 ),
5822                                           eos, eos.GetData().GetHelper() ))
5823         {
5824           debugMsg("UpdatePositionOnSWOL fails in putOnOffsetSurface()" );
5825         }
5826       }
5827     }
5828   }
5829
5830
5831
5832 #ifdef _DEBUG_
5833   // dumpMove() for debug
5834   size_t i = 0;
5835   for ( ; i < eos._edges.size(); ++i )
5836     if ( eos._edges[i]->Is( _LayerEdge::MARKED ))
5837       break;
5838   if ( i < eos._edges.size() )
5839   {
5840     dumpFunction(SMESH_Comment("putOnOffsetSurface_") << eos.ShapeTypeLetter() << eos._shapeID
5841                  << "_InfStep" << infStep << "_" << Abs( smooStep ));
5842     for ( ; i < eos._edges.size(); ++i )
5843     {
5844       if ( eos._edges[i]->Is( _LayerEdge::MARKED )) {
5845         dumpMove( eos._edges[i]->_nodes.back() );
5846       }
5847     }
5848     dumpFunctionEnd();
5849   }
5850 #endif
5851
5852   _ConvexFace* cnvFace;
5853   if ( moveAll != _LayerEdge::UPD_NORMAL_CONV &&
5854        eos.ShapeType() == TopAbs_FACE &&
5855        (cnvFace = eos.GetData().GetConvexFace( eos._shapeID )) &&
5856        !cnvFace->_normalsFixedOnBorders )
5857   {
5858     // put on the surface nodes built on FACE boundaries
5859     SMESH_subMeshIteratorPtr smIt = eos._subMesh->getDependsOnIterator(/*includeSelf=*/false);
5860     while ( smIt->more() )
5861     {
5862       SMESH_subMesh*     sm = smIt->next();
5863       _EdgesOnShape* subEOS = eos.GetData().GetShapeEdges( sm->GetId() );
5864       if ( !subEOS->_sWOL.IsNull() ) continue;
5865       if ( std::find( eosC1.begin(), eosC1.end(), subEOS ) != eosC1.end() ) continue;
5866
5867       putOnOffsetSurface( *subEOS, infStep, eosC1, smooStep, _LayerEdge::UPD_NORMAL_CONV );
5868     }
5869     cnvFace->_normalsFixedOnBorders = true;
5870   }
5871
5872
5873   // bos #20643
5874   // negative smooStep means "final step", where we don't treat RISKY_SWOL edges
5875   // as edges based on FACE are a bit late comparing with them
5876   if ( smooStep >= 0 &&
5877        neighborHasRiskySWOL &&
5878        moveAll != _LayerEdge::RISKY_SWOL &&
5879        eos.ShapeType() == TopAbs_FACE )
5880   {
5881     // put on the surface nodes built on FACE boundaries
5882     SMESH_subMeshIteratorPtr smIt = eos._subMesh->getDependsOnIterator(/*includeSelf=*/false);
5883     while ( smIt->more() )
5884     {
5885       SMESH_subMesh*     sm = smIt->next();
5886       _EdgesOnShape* subEOS = eos.GetData().GetShapeEdges( sm->GetId() );
5887       if ( subEOS->_sWOL.IsNull() ) continue;
5888       if ( std::find( eosC1.begin(), eosC1.end(), subEOS ) != eosC1.end() ) continue;
5889
5890       putOnOffsetSurface( *subEOS, infStep, eosC1, smooStep, _LayerEdge::RISKY_SWOL );
5891     }
5892   }
5893 }
5894
5895 //================================================================================
5896 /*!
5897  * \brief Return a curve of the EDGE to be used for smoothing and arrange
5898  *        _LayerEdge's to be in a consequent order
5899  */
5900 //================================================================================
5901
5902 Handle(Geom_Curve) _Smoother1D::CurveForSmooth( const TopoDS_Edge&  E,
5903                                                 _EdgesOnShape&      eos,
5904                                                 SMESH_MesherHelper& helper)
5905 {
5906   SMESHDS_SubMesh* smDS = eos._subMesh->GetSubMeshDS();
5907
5908   TopLoc_Location loc; double f,l;
5909
5910   Handle(Geom_Line)   line;
5911   Handle(Geom_Circle) circle;
5912   bool isLine, isCirc;
5913   if ( eos._sWOL.IsNull() ) /////////////////////////////////////////// 3D case
5914   {
5915     // check if the EDGE is a line
5916     Handle(Geom_Curve) curve = BRep_Tool::Curve( E, f, l);
5917     if ( curve->IsKind( STANDARD_TYPE( Geom_TrimmedCurve )))
5918       curve = Handle(Geom_TrimmedCurve)::DownCast( curve )->BasisCurve();
5919
5920     line   = Handle(Geom_Line)::DownCast( curve );
5921     circle = Handle(Geom_Circle)::DownCast( curve );
5922     isLine = (!line.IsNull());
5923     isCirc = (!circle.IsNull());
5924
5925     if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
5926     {
5927       isLine = SMESH_Algo::IsStraight( E );
5928
5929       if ( isLine )
5930         line = new Geom_Line( gp::OX() ); // only type does matter
5931     }
5932     if ( !isLine && !isCirc && eos._edges.size() > 2) // Check if the EDGE is close to a circle
5933     {
5934       // TODO
5935     }
5936   }
5937   else //////////////////////////////////////////////////////////////////////// 2D case
5938   {
5939     if ( !eos._isRegularSWOL ) // 23190
5940       return NULL;
5941
5942     const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
5943
5944     // check if the EDGE is a line
5945     Handle(Geom2d_Curve) curve = BRep_Tool::CurveOnSurface( E, F, f, l );
5946     if ( curve->IsKind( STANDARD_TYPE( Geom2d_TrimmedCurve )))
5947       curve = Handle(Geom2d_TrimmedCurve)::DownCast( curve )->BasisCurve();
5948
5949     Handle(Geom2d_Line)   line2d   = Handle(Geom2d_Line)::DownCast( curve );
5950     Handle(Geom2d_Circle) circle2d = Handle(Geom2d_Circle)::DownCast( curve );
5951     isLine = (!line2d.IsNull());
5952     isCirc = (!circle2d.IsNull());
5953
5954     if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
5955     {
5956       Bnd_B2d bndBox;
5957       SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
5958       while ( nIt->more() )
5959         bndBox.Add( helper.GetNodeUV( F, nIt->next() ));
5960       gp_XY size = bndBox.CornerMax() - bndBox.CornerMin();
5961
5962       const double lineTol = 1e-2 * sqrt( bndBox.SquareExtent() );
5963       for ( int i = 0; i < 2 && !isLine; ++i )
5964         isLine = ( size.Coord( i+1 ) <= lineTol );
5965     }
5966     if ( !isLine && !isCirc && eos._edges.size() > 2 ) // Check if the EDGE is close to a circle
5967     {
5968       // TODO
5969     }
5970     if ( isLine )
5971     {
5972       line = new Geom_Line( gp::OX() ); // only type does matter
5973     }
5974     else if ( isCirc )
5975     {
5976       gp_Pnt2d p = circle2d->Location();
5977       gp_Ax2 ax( gp_Pnt( p.X(), p.Y(), 0), gp::DX());
5978       circle = new Geom_Circle( ax, 1.); // only center position does matter
5979     }
5980   }
5981
5982   if ( isLine )
5983     return line;
5984   if ( isCirc )
5985     return circle;
5986
5987   return Handle(Geom_Curve)();
5988 }
5989
5990 //================================================================================
5991 /*!
5992  * \brief Smooth edges on EDGE
5993  */
5994 //================================================================================
5995
5996 bool _Smoother1D::Perform(_SolidData&                    data,
5997                           Handle(ShapeAnalysis_Surface)& surface,
5998                           const TopoDS_Face&             F,
5999                           SMESH_MesherHelper&            helper )
6000 {
6001   if ( _leParams.empty() || ( !isAnalytic() && _offPoints.empty() ))
6002     prepare( data );
6003
6004   findEdgesToSmooth();
6005   if ( isAnalytic() )
6006     return smoothAnalyticEdge( data, surface, F, helper );
6007   else
6008     return smoothComplexEdge ( data, surface, F, helper );
6009 }
6010
6011 //================================================================================
6012 /*!
6013  * \brief Find edges to smooth
6014  */
6015 //================================================================================
6016
6017 void _Smoother1D::findEdgesToSmooth()
6018 {
6019   _LayerEdge* leOnV[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
6020   for ( int iEnd = 0; iEnd < 2; ++iEnd )
6021     if ( leOnV[iEnd]->Is( _LayerEdge::NORMAL_UPDATED ))
6022       _leOnV[iEnd]._cosin = Abs( _edgeDir[iEnd].Normalized() * leOnV[iEnd]->_normal );
6023
6024   _eToSmooth[0].first = _eToSmooth[0].second = 0;
6025
6026   for ( size_t i = 0; i < _eos.size(); ++i )
6027   {
6028     if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH ))
6029     {
6030       if ( needSmoothing( _leOnV[0]._cosin,
6031                           _eos[i]->_len * leOnV[0]->_lenFactor, _curveLen * _leParams[i] ) ||
6032            isToSmooth( i )
6033            )
6034         _eos[i]->Set( _LayerEdge::TO_SMOOTH );
6035       else
6036         break;
6037     }
6038     _eToSmooth[0].second = i+1;
6039   }
6040
6041   _eToSmooth[1].first = _eToSmooth[1].second = _eos.size();
6042
6043   for ( int i = _eos.size() - 1; i >= _eToSmooth[0].second; --i )
6044   {
6045     if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH ))
6046     {
6047       if ( needSmoothing( _leOnV[1]._cosin,
6048                           _eos[i]->_len * leOnV[1]->_lenFactor, _curveLen * ( 1.-_leParams[i] )) ||
6049            isToSmooth( i ))
6050         _eos[i]->Set( _LayerEdge::TO_SMOOTH );
6051       else
6052         break;
6053     }
6054     _eToSmooth[1].first = i;
6055   }
6056 }
6057
6058 //================================================================================
6059 /*!
6060  * \brief Check if iE-th _LayerEdge needs smoothing
6061  */
6062 //================================================================================
6063
6064 bool _Smoother1D::isToSmooth( int iE )
6065 {
6066   SMESH_NodeXYZ pi( _eos[iE]->_nodes[0] );
6067   SMESH_NodeXYZ p0( _eos[iE]->_2neibors->srcNode(0) );
6068   SMESH_NodeXYZ p1( _eos[iE]->_2neibors->srcNode(1) );
6069   gp_XYZ       seg0 = pi - p0;
6070   gp_XYZ       seg1 = p1 - pi;
6071   gp_XYZ    tangent =  seg0 + seg1;
6072   double tangentLen = tangent.Modulus();
6073   double  segMinLen = Min( seg0.Modulus(), seg1.Modulus() );
6074   if ( tangentLen < std::numeric_limits<double>::min() )
6075     return false;
6076   tangent /= tangentLen;
6077
6078   for ( size_t i = 0; i < _eos[iE]->_neibors.size(); ++i )
6079   {
6080     _LayerEdge* ne = _eos[iE]->_neibors[i];
6081     if ( !ne->Is( _LayerEdge::TO_SMOOTH ) ||
6082          ne->_nodes.size() < 2 ||
6083          ne->_nodes[0]->GetPosition()->GetDim() != 2 )
6084       continue;
6085     gp_XYZ edgeVec = SMESH_NodeXYZ( ne->_nodes.back() ) - SMESH_NodeXYZ( ne->_nodes[0] );
6086     double    proj = edgeVec * tangent;
6087     if ( needSmoothing( 1., proj, segMinLen ))
6088       return true;
6089   }
6090   return false;
6091 }
6092
6093 //================================================================================
6094 /*!
6095  * \brief smooth _LayerEdge's on a staight EDGE or circular EDGE
6096  */
6097 //================================================================================
6098
6099 bool _Smoother1D::smoothAnalyticEdge( _SolidData&                    data,
6100                                       Handle(ShapeAnalysis_Surface)& surface,
6101                                       const TopoDS_Face&             F,
6102                                       SMESH_MesherHelper&            helper)
6103 {
6104   if ( !isAnalytic() ) return false;
6105
6106   size_t iFrom = 0, iTo = _eos._edges.size();
6107
6108   if ( _anaCurve->IsKind( STANDARD_TYPE( Geom_Line )))
6109   {
6110     if ( F.IsNull() ) // 3D
6111     {
6112       SMESH_TNodeXYZ pSrc0( _eos._edges[iFrom]->_2neibors->srcNode(0) );
6113       SMESH_TNodeXYZ pSrc1( _eos._edges[iTo-1]->_2neibors->srcNode(1) );
6114       //const   gp_XYZ lineDir = pSrc1 - pSrc0;
6115       //_LayerEdge* vLE0 = getLEdgeOnV( 0 );
6116       //_LayerEdge* vLE1 = getLEdgeOnV( 1 );
6117       // bool shiftOnly = ( vLE0->Is( _LayerEdge::NORMAL_UPDATED ) ||
6118       //                    vLE0->Is( _LayerEdge::BLOCKED ) ||
6119       //                    vLE1->Is( _LayerEdge::NORMAL_UPDATED ) ||
6120       //                    vLE1->Is( _LayerEdge::BLOCKED ));
6121       for ( int iEnd = 0; iEnd < 2; ++iEnd )
6122       {
6123         iFrom = _eToSmooth[ iEnd ].first, iTo = _eToSmooth[ iEnd ].second;
6124         if ( iFrom >= iTo ) continue;
6125         SMESH_TNodeXYZ p0( _eos[iFrom]->_2neibors->tgtNode(0) );
6126         SMESH_TNodeXYZ p1( _eos[iTo-1]->_2neibors->tgtNode(1) );
6127         double param0 = ( iFrom == 0 ) ? 0. : _leParams[ iFrom-1 ];
6128         double param1 = _leParams[ iTo ];
6129         for ( size_t i = iFrom; i < iTo; ++i )
6130         {
6131           _LayerEdge*       edge = _eos[i];
6132           SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edge->_nodes.back() );
6133           double           param = ( _leParams[i] - param0 ) / ( param1 - param0 );
6134           gp_XYZ          newPos = p0 * ( 1. - param ) + p1 * param;
6135
6136           // if ( shiftOnly || edge->Is( _LayerEdge::NORMAL_UPDATED ))
6137           // {
6138           //   gp_XYZ curPos = SMESH_TNodeXYZ ( tgtNode );
6139           //   double  shift = ( lineDir * ( newPos - pSrc0 ) -
6140           //                     lineDir * ( curPos - pSrc0 ));
6141           //   newPos = curPos + lineDir * shift / lineDir.SquareModulus();
6142           // }
6143           if ( edge->Is( _LayerEdge::BLOCKED ))
6144           {
6145             SMESH_TNodeXYZ pSrc( edge->_nodes[0] );
6146             double curThick = pSrc.SquareDistance( tgtNode );
6147             double newThink = ( pSrc - newPos ).SquareModulus();
6148             if ( newThink > curThick )
6149               continue;
6150           }
6151           edge->_pos.back() = newPos;
6152           tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
6153           dumpMove( tgtNode );
6154         }
6155       }
6156     }
6157     else // 2D
6158     {
6159       _LayerEdge* eV0 = getLEdgeOnV( 0 );
6160       _LayerEdge* eV1 = getLEdgeOnV( 1 );
6161       gp_XY      uvV0 = eV0->LastUV( F, *data.GetShapeEdges( eV0 ));
6162       gp_XY      uvV1 = eV1->LastUV( F, *data.GetShapeEdges( eV1 ));
6163       if ( eV0->_nodes.back() == eV1->_nodes.back() ) // closed edge
6164       {
6165         int iPeriodic = helper.GetPeriodicIndex();
6166         if ( iPeriodic == 1 || iPeriodic == 2 )
6167         {
6168           uvV1.SetCoord( iPeriodic, helper.GetOtherParam( uvV1.Coord( iPeriodic )));
6169           if ( uvV0.Coord( iPeriodic ) > uvV1.Coord( iPeriodic ))
6170             std::swap( uvV0, uvV1 );
6171         }
6172       }
6173       for ( int iEnd = 0; iEnd < 2; ++iEnd )
6174       {
6175         iFrom = _eToSmooth[ iEnd ].first, iTo = _eToSmooth[ iEnd ].second;
6176         if ( iFrom >= iTo ) continue;
6177         _LayerEdge* e0 = _eos[iFrom]->_2neibors->_edges[0];
6178         _LayerEdge* e1 = _eos[iTo-1]->_2neibors->_edges[1];
6179         gp_XY      uv0 = ( e0 == eV0 ) ? uvV0 : e0->LastUV( F, _eos );
6180         gp_XY      uv1 = ( e1 == eV1 ) ? uvV1 : e1->LastUV( F, _eos );
6181         double  param0 = ( iFrom == 0 ) ? 0. : _leParams[ iFrom-1 ];
6182         double  param1 = _leParams[ iTo ];
6183         gp_XY  rangeUV = uv1 - uv0;
6184         for ( size_t i = iFrom; i < iTo; ++i )
6185         {
6186           if ( _eos[i]->Is( _LayerEdge::BLOCKED )) continue;
6187           double param = ( _leParams[i] - param0 ) / ( param1 - param0 );
6188           gp_XY newUV = uv0 + param * rangeUV;
6189
6190           gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
6191           SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos[i]->_nodes.back() );
6192           tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
6193           dumpMove( tgtNode );
6194
6195           SMDS_FacePositionPtr pos = tgtNode->GetPosition();
6196           pos->SetUParameter( newUV.X() );
6197           pos->SetVParameter( newUV.Y() );
6198
6199           gp_XYZ newUV0( newUV.X(), newUV.Y(), 0 );
6200
6201           if ( !_eos[i]->Is( _LayerEdge::SMOOTHED ))
6202           {
6203             _eos[i]->Set( _LayerEdge::SMOOTHED ); // to check in refine() (IPAL54237)
6204             if ( _eos[i]->_pos.size() > 2 )
6205             {
6206               // modify previous positions to make _LayerEdge less sharply bent
6207               vector<gp_XYZ>& uvVec = _eos[i]->_pos;
6208               const gp_XYZ  uvShift = newUV0 - uvVec.back();
6209               const double     len2 = ( uvVec.back() - uvVec[ 0 ] ).SquareModulus();
6210               int iPrev = uvVec.size() - 2;
6211               while ( iPrev > 0 )
6212               {
6213                 double r = ( uvVec[ iPrev ] - uvVec[0] ).SquareModulus() / len2;
6214                 uvVec[ iPrev ] += uvShift * r;
6215                 --iPrev;
6216               }
6217             }
6218           }
6219           _eos[i]->_pos.back() = newUV0;
6220         }
6221       }
6222     }
6223     return true;
6224   }
6225
6226   if ( _anaCurve->IsKind( STANDARD_TYPE( Geom_Circle )))
6227   {
6228     Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast( _anaCurve );
6229     gp_Pnt center3D = circle->Location();
6230
6231     if ( F.IsNull() ) // 3D
6232     {
6233       if ( getLEdgeOnV( 0 )->_nodes.back() == getLEdgeOnV( 1 )->_nodes.back() )
6234         return true; // closed EDGE - nothing to do
6235
6236       // circle is a real curve of EDGE
6237       gp_Circ circ = circle->Circ();
6238
6239       // new center is shifted along its axis
6240       const gp_Dir& axis = circ.Axis().Direction();
6241       _LayerEdge*     e0 = getLEdgeOnV(0);
6242       _LayerEdge*     e1 = getLEdgeOnV(1);
6243       SMESH_TNodeXYZ  p0 = e0->_nodes.back();
6244       SMESH_TNodeXYZ  p1 = e1->_nodes.back();
6245       double      shift1 = axis.XYZ() * ( p0 - center3D.XYZ() );
6246       double      shift2 = axis.XYZ() * ( p1 - center3D.XYZ() );
6247       gp_Pnt   newCenter = center3D.XYZ() + axis.XYZ() * 0.5 * ( shift1 + shift2 );
6248
6249       double newRadius = 0.5 * ( newCenter.Distance( p0 ) + newCenter.Distance( p1 ));
6250
6251       gp_Ax2  newAxis( newCenter, axis, gp_Vec( newCenter, p0 ));
6252       gp_Circ newCirc( newAxis, newRadius );
6253       gp_Vec  vecC1  ( newCenter, p1 );
6254
6255       double uLast = newAxis.XDirection().AngleWithRef( vecC1, newAxis.Direction() ); // -PI - +PI
6256       if ( uLast < 0 )
6257         uLast += 2 * M_PI;
6258       
6259       for ( size_t i = 0; i < _eos.size(); ++i )
6260       {
6261         if ( _eos[i]->Is( _LayerEdge::BLOCKED )) continue;
6262         //if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH )) continue;
6263         double u = uLast * _leParams[i];
6264         gp_Pnt p = ElCLib::Value( u, newCirc );
6265         _eos._edges[i]->_pos.back() = p.XYZ();
6266
6267         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
6268         tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
6269         dumpMove( tgtNode );
6270       }
6271       return true;
6272     }
6273     else // 2D
6274     {
6275       const gp_XY center( center3D.X(), center3D.Y() );
6276
6277       _LayerEdge* e0 = getLEdgeOnV(0);
6278       _LayerEdge* eM = _eos._edges[ 0 ];
6279       _LayerEdge* e1 = getLEdgeOnV(1);
6280       gp_XY      uv0 = e0->LastUV( F, *data.GetShapeEdges( e0 ) );
6281       gp_XY      uvM = eM->LastUV( F, *data.GetShapeEdges( eM ) );
6282       gp_XY      uv1 = e1->LastUV( F, *data.GetShapeEdges( e1 ) );
6283       gp_Vec2d vec0( center, uv0 );
6284       gp_Vec2d vecM( center, uvM );
6285       gp_Vec2d vec1( center, uv1 );
6286       double uLast = vec0.Angle( vec1 ); // -PI - +PI
6287       double uMidl = vec0.Angle( vecM );
6288       if ( uLast * uMidl <= 0. )
6289         uLast += ( uMidl > 0 ? +2. : -2. ) * M_PI;
6290       const double radius = 0.5 * ( vec0.Magnitude() + vec1.Magnitude() );
6291
6292       gp_Ax2d   axis( center, vec0 );
6293       gp_Circ2d circ( axis, radius );
6294       for ( size_t i = 0; i < _eos.size(); ++i )
6295       {
6296         if ( _eos[i]->Is( _LayerEdge::BLOCKED )) continue;
6297         //if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH )) continue;
6298         double    newU = uLast * _leParams[i];
6299         gp_Pnt2d newUV = ElCLib::Value( newU, circ );
6300         _eos._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
6301
6302         gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
6303         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
6304         tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
6305         dumpMove( tgtNode );
6306
6307         SMDS_FacePositionPtr pos = tgtNode->GetPosition();
6308         pos->SetUParameter( newUV.X() );
6309         pos->SetVParameter( newUV.Y() );
6310
6311         _eos[i]->Set( _LayerEdge::SMOOTHED ); // to check in refine() (IPAL54237)
6312       }
6313     }
6314     return true;
6315   }
6316
6317   return false;
6318 }
6319
6320 //================================================================================
6321 /*!
6322  * \brief smooth _LayerEdge's on a an EDGE
6323  */
6324 //================================================================================
6325
6326 bool _Smoother1D::smoothComplexEdge( _SolidData&                    /*data*/,
6327                                      Handle(ShapeAnalysis_Surface)& surface,
6328                                      const TopoDS_Face&             F,
6329                                      SMESH_MesherHelper&            /*helper*/)
6330 {
6331   if ( _offPoints.empty() )
6332     return false;
6333
6334   // ----------------------------------------------
6335   // move _offPoints along normals of _LayerEdge's
6336   // ----------------------------------------------
6337
6338   _LayerEdge* e[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
6339   if ( e[0]->Is( _LayerEdge::NORMAL_UPDATED ))
6340     _leOnV[0]._normal = getNormalNormal( e[0]->_normal, _edgeDir[0] );
6341   if ( e[1]->Is( _LayerEdge::NORMAL_UPDATED )) 
6342     _leOnV[1]._normal = getNormalNormal( e[1]->_normal, _edgeDir[1] );
6343   _leOnV[0]._len = e[0]->_len;
6344   _leOnV[1]._len = e[1]->_len;
6345   for ( size_t i = 0; i < _offPoints.size(); i++ )
6346   {
6347     _LayerEdge*  e0 = _offPoints[i]._2edges._edges[0];
6348     _LayerEdge*  e1 = _offPoints[i]._2edges._edges[1];
6349     const double w0 = _offPoints[i]._2edges._wgt[0];
6350     const double w1 = _offPoints[i]._2edges._wgt[1];
6351     gp_XYZ  avgNorm = ( e0->_normal    * w0 + e1->_normal    * w1 ).Normalized();
6352     double  avgLen  = ( e0->_len       * w0 + e1->_len       * w1 );
6353     double  avgFact = ( e0->_lenFactor * w0 + e1->_lenFactor * w1 );
6354     if ( e0->Is( _LayerEdge::NORMAL_UPDATED ) ||
6355          e1->Is( _LayerEdge::NORMAL_UPDATED ))
6356       avgNorm = getNormalNormal( avgNorm, _offPoints[i]._edgeDir );
6357
6358     _offPoints[i]._xyz += avgNorm * ( avgLen - _offPoints[i]._len ) * avgFact;
6359     _offPoints[i]._len  = avgLen;
6360   }
6361
6362   double fTol = 0;
6363   if ( !surface.IsNull() ) // project _offPoints to the FACE
6364   {
6365     fTol = 100 * BRep_Tool::Tolerance( F );
6366     //const double segLen = _offPoints[0].Distance( _offPoints[1] );
6367
6368     gp_Pnt2d uv = surface->ValueOfUV( _offPoints[0]._xyz, fTol );
6369     //if ( surface->Gap() < 0.5 * segLen )
6370       _offPoints[0]._xyz = surface->Value( uv ).XYZ();
6371
6372     for ( size_t i = 1; i < _offPoints.size(); ++i )
6373     {
6374       uv = surface->NextValueOfUV( uv, _offPoints[i]._xyz, fTol );
6375       //if ( surface->Gap() < 0.5 * segLen )
6376         _offPoints[i]._xyz = surface->Value( uv ).XYZ();
6377     }
6378   }
6379
6380   // -----------------------------------------------------------------
6381   // project tgt nodes of extreme _LayerEdge's to the offset segments
6382   // -----------------------------------------------------------------
6383
6384   const int updatedOrBlocked = _LayerEdge::NORMAL_UPDATED | _LayerEdge::BLOCKED;
6385   if ( e[0]->Is( updatedOrBlocked )) _iSeg[0] = 0;
6386   if ( e[1]->Is( updatedOrBlocked )) _iSeg[1] = _offPoints.size()-2;
6387
6388   gp_Pnt pExtreme[2], pProj[2];
6389   bool isProjected[2];
6390   for ( int is2nd = 0; is2nd < 2; ++is2nd )
6391   {
6392     pExtreme[ is2nd ] = SMESH_TNodeXYZ( e[is2nd]->_nodes.back() );
6393     int  i = _iSeg[ is2nd ];
6394     int di = is2nd ? -1 : +1;
6395     bool & projected = isProjected[ is2nd ];
6396     projected = false;
6397     double uOnSeg, distMin = Precision::Infinite(), dist, distPrev = 0;
6398     int nbWorse = 0;
6399     do {
6400       gp_Vec v0p( _offPoints[i]._xyz, pExtreme[ is2nd ]    );
6401       gp_Vec v01( _offPoints[i]._xyz, _offPoints[i+1]._xyz );
6402       uOnSeg     = ( v0p * v01 ) / v01.SquareMagnitude();  // param [0,1] along v01
6403       projected  = ( Abs( uOnSeg - 0.5 ) <= 0.5 );
6404       dist       =  pExtreme[ is2nd ].SquareDistance( _offPoints[ i + ( uOnSeg > 0.5 )]._xyz );
6405       if ( dist < distMin || projected )
6406       {
6407         _iSeg[ is2nd ] = i;
6408         pProj[ is2nd ] = _offPoints[i]._xyz + ( v01 * uOnSeg ).XYZ();
6409         distMin = dist;
6410       }
6411       else if ( dist > distPrev )
6412       {
6413         if ( ++nbWorse > 3 ) // avoid projection to the middle of a closed EDGE
6414           break;
6415       }
6416       distPrev = dist;
6417       i += di;
6418     }
6419     while ( !projected &&
6420             i >= 0 && i+1 < (int)_offPoints.size() );
6421
6422     if ( !projected )
6423     {
6424       if (( is2nd && _iSeg[1] != _offPoints.size()-2 ) || ( !is2nd && _iSeg[0] != 0 ))
6425       {
6426         _iSeg[0] = 0;
6427         _iSeg[1] = _offPoints.size()-2;
6428         debugMsg( "smoothComplexEdge() failed to project nodes of extreme _LayerEdge's" );
6429         return false;
6430       }
6431     }
6432   }
6433   if ( _iSeg[0] > _iSeg[1] )
6434   {
6435     debugMsg( "smoothComplexEdge() incorrectly projected nodes of extreme _LayerEdge's" );
6436     return false;
6437   }
6438
6439   // adjust length of extreme LE (test viscous_layers_01/B7)
6440   gp_Vec vDiv0( pExtreme[0], pProj[0] );
6441   gp_Vec vDiv1( pExtreme[1], pProj[1] );
6442   double d0 = vDiv0.Magnitude();
6443   double d1 = isProjected[1] ? vDiv1.Magnitude() : 0;
6444   if ( e[0]->Is( _LayerEdge::BLOCKED )) {
6445     if ( e[0]->_normal * vDiv0.XYZ() < 0 ) e[0]->_len += d0;
6446     else                                   e[0]->_len -= d0;
6447   }
6448   if ( e[1]->Is( _LayerEdge::BLOCKED )) {
6449     if ( e[1]->_normal * vDiv1.XYZ() < 0 ) e[1]->_len += d1;
6450     else                                   e[1]->_len -= d1;
6451   }
6452
6453   // ---------------------------------------------------------------------------------
6454   // compute normalized length of the offset segments located between the projections
6455   // ---------------------------------------------------------------------------------
6456
6457   // temporary replace extreme _offPoints by pExtreme
6458   gp_XYZ opXYZ[2] = { _offPoints[ _iSeg[0]   ]._xyz,
6459                       _offPoints[ _iSeg[1]+1 ]._xyz };
6460   _offPoints[ _iSeg[0]   ]._xyz = pExtreme[0].XYZ();
6461   _offPoints[ _iSeg[1]+ 1]._xyz = pExtreme[1].XYZ();
6462
6463   size_t iSeg = 0, nbSeg = _iSeg[1] - _iSeg[0] + 1;
6464   vector< double > len( nbSeg + 1 );
6465   len[ iSeg++ ] = 0;
6466   len[ iSeg++ ] = pProj[ 0 ].Distance( _offPoints[ _iSeg[0]+1 ]._xyz );
6467   for ( size_t i = _iSeg[0]+1; i <= _iSeg[1]; ++i, ++iSeg )
6468   {
6469     len[ iSeg ] = len[ iSeg-1 ] + _offPoints[i].Distance( _offPoints[i+1] );
6470   }
6471   // if ( isProjected[ 1 ])
6472   //   len[ nbSeg ] -= pProj[ 1 ].Distance( _offPoints[ _iSeg[1]+1 ]._xyz );
6473   // else
6474   //   len[ nbSeg ] += pExtreme[ 1 ].Distance( _offPoints[ _iSeg[1]+1 ]._xyz );
6475
6476   double fullLen = len.back() - d0 - d1;
6477   for ( iSeg = 0; iSeg < len.size(); ++iSeg )
6478     len[iSeg] = ( len[iSeg] - d0 ) / fullLen;
6479
6480   // -------------------------------------------------------------
6481   // distribute tgt nodes of _LayerEdge's between the projections
6482   // -------------------------------------------------------------
6483
6484   iSeg = 0;
6485   for ( size_t i = 0; i < _eos.size(); ++i )
6486   {
6487     if ( _eos[i]->Is( _LayerEdge::BLOCKED )) continue;
6488     //if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH )) continue;
6489     while ( iSeg+2 < len.size() && _leParams[i] > len[ iSeg+1 ] )
6490       iSeg++;
6491     double r = ( _leParams[i] - len[ iSeg ]) / ( len[ iSeg+1 ] - len[ iSeg ]);
6492     gp_XYZ p = ( _offPoints[ iSeg + _iSeg[0]     ]._xyz * ( 1 - r ) +
6493                  _offPoints[ iSeg + _iSeg[0] + 1 ]._xyz * r );
6494
6495     if ( surface.IsNull() )
6496     {
6497       _eos[i]->_pos.back() = p;
6498     }
6499     else // project a new node position to a FACE
6500     {
6501       gp_Pnt2d uv ( _eos[i]->_pos.back().X(), _eos[i]->_pos.back().Y() );
6502       gp_Pnt2d uv2( surface->NextValueOfUV( uv, p, fTol ));
6503
6504       p = surface->Value( uv2 ).XYZ();
6505       _eos[i]->_pos.back().SetCoord( uv2.X(), uv2.Y(), 0 );
6506     }
6507     SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos[i]->_nodes.back() );
6508     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
6509     dumpMove( tgtNode );
6510   }
6511
6512   _offPoints[ _iSeg[0]   ]._xyz = opXYZ[0];
6513   _offPoints[ _iSeg[1]+1 ]._xyz = opXYZ[1];
6514
6515   return true;
6516 }
6517
6518 //================================================================================
6519 /*!
6520  * \brief Prepare for smoothing
6521  */
6522 //================================================================================
6523
6524 void _Smoother1D::prepare(_SolidData& data)
6525 {
6526   const TopoDS_Edge& E = TopoDS::Edge( _eos._shape );
6527   _curveLen = SMESH_Algo::EdgeLength( E );
6528
6529   // sort _LayerEdge's by position on the EDGE
6530   data.SortOnEdge( E, _eos._edges );
6531
6532   // compute normalized param of _eos._edges on EDGE
6533   _leParams.resize( _eos._edges.size() + 1 );
6534   {
6535     double curLen;
6536     gp_Pnt pPrev = SMESH_TNodeXYZ( getLEdgeOnV( 0 )->_nodes[0] );
6537     _leParams[0] = 0;
6538     for ( size_t i = 0; i < _eos._edges.size(); ++i )
6539     {
6540       gp_Pnt p       = SMESH_TNodeXYZ( _eos._edges[i]->_nodes[0] );
6541       curLen         = p.Distance( pPrev );
6542       _leParams[i+1] = _leParams[i] + curLen;
6543       pPrev          = p;
6544     }
6545     double fullLen = _leParams.back() + pPrev.Distance( SMESH_TNodeXYZ( getLEdgeOnV(1)->_nodes[0]));
6546     for ( size_t i = 0; i < _leParams.size()-1; ++i )
6547       _leParams[i] = _leParams[i+1] / fullLen;
6548     _leParams.back() = 1.;
6549   }
6550
6551   _LayerEdge* leOnV[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
6552
6553   // get cosin to use in findEdgesToSmooth()
6554   _edgeDir[0] = getEdgeDir( E, leOnV[0]->_nodes[0], data.GetHelper() );
6555   _edgeDir[1] = getEdgeDir( E, leOnV[1]->_nodes[0], data.GetHelper() );
6556   _leOnV[0]._cosin = Abs( leOnV[0]->_cosin );
6557   _leOnV[1]._cosin = Abs( leOnV[1]->_cosin );
6558   if ( _eos._sWOL.IsNull() ) // 3D
6559     for ( int iEnd = 0; iEnd < 2; ++iEnd )
6560       _leOnV[iEnd]._cosin = Abs( _edgeDir[iEnd].Normalized() * leOnV[iEnd]->_normal );
6561
6562   if ( isAnalytic() )
6563     return;
6564
6565   // divide E to have offset segments with low deflection
6566   BRepAdaptor_Curve c3dAdaptor( E );
6567   const double curDeflect = 0.1; //0.01; // Curvature deflection == |p1p2|*sin(p1p2,p1pM)
6568   const double angDeflect = 0.1; //0.09; // Angular deflection == sin(p1pM,pMp2)
6569   GCPnts_TangentialDeflection discret(c3dAdaptor, angDeflect, curDeflect);
6570   if ( discret.NbPoints() <= 2 )
6571   {
6572     _anaCurve = new Geom_Line( gp::OX() ); // only type does matter
6573     return;
6574   }
6575
6576   const double u0 = c3dAdaptor.FirstParameter();
6577   gp_Pnt p; gp_Vec tangent;
6578   if ( discret.NbPoints() >= (int) _eos.size() + 2 )
6579   {
6580     _offPoints.resize( discret.NbPoints() );
6581     for ( size_t i = 0; i < _offPoints.size(); i++ )
6582     {
6583       double u = discret.Parameter( i+1 );
6584       c3dAdaptor.D1( u, p, tangent );
6585       _offPoints[i]._xyz     = p.XYZ();
6586       _offPoints[i]._edgeDir = tangent.XYZ();
6587       _offPoints[i]._param = GCPnts_AbscissaPoint::Length( c3dAdaptor, u0, u ) / _curveLen;
6588     }
6589   }
6590   else
6591   {
6592     std::vector< double > params( _eos.size() + 2 );
6593
6594     params[0]     = data.GetHelper().GetNodeU( E, leOnV[0]->_nodes[0] );
6595     params.back() = data.GetHelper().GetNodeU( E, leOnV[1]->_nodes[0] );
6596     for ( size_t i = 0; i < _eos.size(); i++ )
6597       params[i+1] = data.GetHelper().GetNodeU( E, _eos[i]->_nodes[0] );
6598
6599     if ( params[1] > params[ _eos.size() ] )
6600       std::reverse( params.begin() + 1, params.end() - 1 );
6601
6602     _offPoints.resize( _eos.size() + 2 );
6603     for ( size_t i = 0; i < _offPoints.size(); i++ )
6604     {
6605       const double u = params[i];
6606       c3dAdaptor.D1( u, p, tangent );
6607       _offPoints[i]._xyz     = p.XYZ();
6608       _offPoints[i]._edgeDir = tangent.XYZ();
6609       _offPoints[i]._param = GCPnts_AbscissaPoint::Length( c3dAdaptor, u0, u ) / _curveLen;
6610     }
6611   }
6612
6613   // set _2edges
6614   _offPoints    [0]._2edges.set( &_leOnV[0], &_leOnV[0], 0.5, 0.5 );
6615   _offPoints.back()._2edges.set( &_leOnV[1], &_leOnV[1], 0.5, 0.5 );
6616   _2NearEdges tmp2edges;
6617   tmp2edges._edges[1] = _eos._edges[0];
6618   _leOnV[0]._2neibors = & tmp2edges;
6619   _leOnV[0]._nodes    = leOnV[0]->_nodes;
6620   _leOnV[1]._nodes    = leOnV[1]->_nodes;
6621   _LayerEdge* eNext, *ePrev = & _leOnV[0];
6622   for ( size_t iLE = 0, i = 1; i < _offPoints.size()-1; i++ )
6623   {
6624     // find _LayerEdge's located before and after an offset point
6625     // (_eos._edges[ iLE ] is next after ePrev)
6626     while ( iLE < _eos._edges.size() && _offPoints[i]._param > _leParams[ iLE ] )
6627       ePrev = _eos._edges[ iLE++ ];
6628     eNext = ePrev->_2neibors->_edges[1];
6629
6630     gp_Pnt p0 = SMESH_TNodeXYZ( ePrev->_nodes[0] );
6631     gp_Pnt p1 = SMESH_TNodeXYZ( eNext->_nodes[0] );
6632     double  r = p0.Distance( _offPoints[i]._xyz ) / p0.Distance( p1 );
6633     _offPoints[i]._2edges.set( ePrev, eNext, 1-r, r );
6634   }
6635
6636   // replace _LayerEdge's on VERTEX by _leOnV in _offPoints._2edges
6637   for ( size_t i = 0; i < _offPoints.size(); i++ )
6638     if ( _offPoints[i]._2edges._edges[0] == leOnV[0] )
6639       _offPoints[i]._2edges._edges[0] = & _leOnV[0];
6640     else break;
6641   for ( size_t i = _offPoints.size()-1; i > 0; i-- )
6642     if ( _offPoints[i]._2edges._edges[1] == leOnV[1] )
6643       _offPoints[i]._2edges._edges[1] = & _leOnV[1];
6644     else break;
6645
6646   // set _normal of _leOnV[0] and _leOnV[1] to be normal to the EDGE
6647
6648   int iLBO = _offPoints.size() - 2; // last but one
6649
6650   if ( leOnV[ 0 ]->Is( _LayerEdge::MULTI_NORMAL ))
6651     _leOnV[ 0 ]._normal = getNormalNormal( _eos._edges[1]->_normal, _edgeDir[0] );
6652   else
6653     _leOnV[ 0 ]._normal = getNormalNormal( leOnV[0]->_normal,       _edgeDir[0] );
6654   if ( leOnV[ 1 ]->Is( _LayerEdge::MULTI_NORMAL ))
6655     _leOnV[ 1 ]._normal = getNormalNormal( _eos._edges.back()->_normal, _edgeDir[1] );
6656   else
6657     _leOnV[ 1 ]._normal = getNormalNormal( leOnV[1]->_normal,           _edgeDir[1] );
6658   _leOnV[ 0 ]._len = 0;
6659   _leOnV[ 1 ]._len = 0;
6660   _leOnV[ 0 ]._lenFactor = _offPoints[1   ]._2edges._edges[1]->_lenFactor;
6661   _leOnV[ 1 ]._lenFactor = _offPoints[iLBO]._2edges._edges[0]->_lenFactor;
6662
6663   _iSeg[0] = 0;
6664   _iSeg[1] = _offPoints.size()-2;
6665
6666   // initialize OffPnt::_len
6667   for ( size_t i = 0; i < _offPoints.size(); ++i )
6668     _offPoints[i]._len = 0;
6669
6670   if ( _eos._edges[0]->NbSteps() > 1 ) // already inflated several times, init _xyz
6671   {
6672     _leOnV[0]._len = leOnV[0]->_len;
6673     _leOnV[1]._len = leOnV[1]->_len;
6674     for ( size_t i = 0; i < _offPoints.size(); i++ )
6675     {
6676       _LayerEdge*  e0 = _offPoints[i]._2edges._edges[0];
6677       _LayerEdge*  e1 = _offPoints[i]._2edges._edges[1];
6678       const double w0 = _offPoints[i]._2edges._wgt[0];
6679       const double w1 = _offPoints[i]._2edges._wgt[1];
6680       double  avgLen  = ( e0->_len * w0 + e1->_len * w1 );
6681       gp_XYZ  avgXYZ  = ( SMESH_TNodeXYZ( e0->_nodes.back() ) * w0 +
6682                           SMESH_TNodeXYZ( e1->_nodes.back() ) * w1 );
6683       _offPoints[i]._xyz = avgXYZ;
6684       _offPoints[i]._len = avgLen;
6685     }
6686   }
6687 }
6688
6689 //================================================================================
6690 /*!
6691  * \brief return _normal of _leOnV[is2nd] normal to the EDGE
6692  */
6693 //================================================================================
6694
6695 gp_XYZ _Smoother1D::getNormalNormal( const gp_XYZ & normal,
6696                                      const gp_XYZ&  edgeDir)
6697 {
6698   gp_XYZ cross = normal ^ edgeDir;
6699   gp_XYZ  norm = edgeDir ^ cross;
6700   double  size = norm.Modulus();
6701
6702   // if ( size == 0 ) // MULTI_NORMAL _LayerEdge
6703   //   return gp_XYZ( 1e-100, 1e-100, 1e-100 );
6704
6705   if ( size < 1e-5 ) // normal || edgeDir (almost) at inflation along EDGE (bos #20643)
6706   {
6707     const _LayerEdge* le = _eos._edges[ _eos._edges.size() / 2 ];
6708     const gp_XYZ& leNorm = le->_normal;
6709
6710     cross = leNorm ^ edgeDir;
6711     norm = edgeDir ^ cross;
6712     size = norm.Modulus();
6713   }
6714
6715   return norm / size;
6716 }
6717
6718 //================================================================================
6719 /*!
6720  * \brief Writes a script creating a mesh composed of _offPoints
6721  */
6722 //================================================================================
6723
6724 void _Smoother1D::offPointsToPython() const
6725 {
6726   const char* fname = "/tmp/offPoints.py";
6727   cout << "exec(open('"<<fname<<"','rb').read() )"<<endl;
6728   ofstream py(fname);
6729   py << "import SMESH" << endl
6730      << "from salome.smesh import smeshBuilder" << endl
6731      << "smesh  = smeshBuilder.New(salome.myStudy)" << endl
6732      << "mesh   = smesh.Mesh( 'offPoints' )"<<endl;
6733   for ( size_t i = 0; i < _offPoints.size(); i++ )
6734   {
6735     py << "mesh.AddNode( "
6736        << _offPoints[i]._xyz.X() << ", "
6737        << _offPoints[i]._xyz.Y() << ", "
6738        << _offPoints[i]._xyz.Z() << " )" << endl;
6739   }
6740 }
6741
6742 //================================================================================
6743 /*!
6744  * \brief Sort _LayerEdge's by a parameter on a given EDGE
6745  */
6746 //================================================================================
6747
6748 void _SolidData::SortOnEdge( const TopoDS_Edge&     E,
6749                              vector< _LayerEdge* >& edges)
6750 {
6751   map< double, _LayerEdge* > u2edge;
6752   for ( size_t i = 0; i < edges.size(); ++i )
6753     u2edge.insert( u2edge.end(),
6754                    make_pair( _helper->GetNodeU( E, edges[i]->_nodes[0] ), edges[i] ));
6755
6756   ASSERT( u2edge.size() == edges.size() );
6757   map< double, _LayerEdge* >::iterator u2e = u2edge.begin();
6758   for ( size_t i = 0; i < edges.size(); ++i, ++u2e )
6759     edges[i] = u2e->second;
6760
6761   Sort2NeiborsOnEdge( edges );
6762 }
6763
6764 //================================================================================
6765 /*!
6766  * \brief Set _2neibors according to the order of _LayerEdge on EDGE
6767  */
6768 //================================================================================
6769
6770 void _SolidData::Sort2NeiborsOnEdge( vector< _LayerEdge* >& edges )
6771 {
6772   if ( edges.size() < 2 || !edges[0]->_2neibors ) return;
6773
6774   for ( size_t i = 0; i < edges.size()-1; ++i )
6775     if ( edges[i]->_2neibors->tgtNode(1) != edges[i+1]->_nodes.back() )
6776       edges[i]->_2neibors->reverse();
6777
6778   const size_t iLast = edges.size() - 1;
6779   if ( edges.size() > 1 &&
6780        edges[iLast]->_2neibors->tgtNode(0) != edges[iLast-1]->_nodes.back() )
6781     edges[iLast]->_2neibors->reverse();
6782 }
6783
6784 //================================================================================
6785 /*!
6786  * \brief Return _EdgesOnShape* corresponding to the shape
6787  */
6788 //================================================================================
6789
6790 _EdgesOnShape* _SolidData::GetShapeEdges(const TGeomID shapeID )
6791 {
6792   if ( shapeID < (int)_edgesOnShape.size() &&
6793        _edgesOnShape[ shapeID ]._shapeID == shapeID )
6794     return _edgesOnShape[ shapeID ]._subMesh ? & _edgesOnShape[ shapeID ] : 0;
6795
6796   for ( size_t i = 0; i < _edgesOnShape.size(); ++i )
6797     if ( _edgesOnShape[i]._shapeID == shapeID )
6798       return _edgesOnShape[i]._subMesh ? & _edgesOnShape[i] : 0;
6799
6800   return 0;
6801 }
6802
6803 //================================================================================
6804 /*!
6805  * \brief Return _EdgesOnShape* corresponding to the shape
6806  */
6807 //================================================================================
6808
6809 _EdgesOnShape* _SolidData::GetShapeEdges(const TopoDS_Shape& shape )
6810 {
6811   SMESHDS_Mesh* meshDS = _proxyMesh->GetMesh()->GetMeshDS();
6812   return GetShapeEdges( meshDS->ShapeToIndex( shape ));
6813 }
6814
6815 //================================================================================
6816 /*!
6817  * \brief Prepare data of the _LayerEdge for smoothing on FACE
6818  */
6819 //================================================================================
6820
6821 void _SolidData::PrepareEdgesToSmoothOnFace( _EdgesOnShape* eos, bool substituteSrcNodes )
6822 {
6823   SMESH_MesherHelper helper( *_proxyMesh->GetMesh() );
6824
6825   set< TGeomID > vertices;
6826   TopoDS_Face F;
6827   if ( eos->ShapeType() == TopAbs_FACE )
6828   {
6829     // check FACE concavity and get concave VERTEXes
6830     F = TopoDS::Face( eos->_shape );
6831     if ( isConcave( F, helper, &vertices ))
6832       _concaveFaces.insert( eos->_shapeID );
6833
6834     // set eos._eosConcaVer
6835     eos->_eosConcaVer.clear();
6836     eos->_eosConcaVer.reserve( vertices.size() );
6837     for ( set< TGeomID >::iterator v = vertices.begin(); v != vertices.end(); ++v )
6838     {
6839       _EdgesOnShape* eov = GetShapeEdges( *v );
6840       if ( eov && eov->_edges.size() == 1 )
6841       {
6842         eos->_eosConcaVer.push_back( eov );
6843         for ( size_t i = 0; i < eov->_edges[0]->_neibors.size(); ++i )
6844           eov->_edges[0]->_neibors[i]->Set( _LayerEdge::DIFFICULT );
6845       }
6846     }
6847
6848     // SetSmooLen() to _LayerEdge's on FACE
6849     // for ( size_t i = 0; i < eos->_edges.size(); ++i )
6850     // {
6851     //   eos->_edges[i]->SetSmooLen( Precision::Infinite() );
6852     // }
6853     // SMESH_subMeshIteratorPtr smIt = eos->_subMesh->getDependsOnIterator(/*includeSelf=*/false);
6854     // while ( smIt->more() ) // loop on sub-shapes of the FACE
6855     // {
6856     //   _EdgesOnShape* eoe = GetShapeEdges( smIt->next()->GetId() );
6857     //   if ( !eoe ) continue;
6858
6859     //   vector<_LayerEdge*>& eE = eoe->_edges;
6860     //   for ( size_t iE = 0; iE < eE.size(); ++iE ) // loop on _LayerEdge's on EDGE or VERTEX
6861     //   {
6862     //     if ( eE[iE]->_cosin <= theMinSmoothCosin )
6863     //       continue;
6864
6865     //     SMDS_ElemIteratorPtr segIt = eE[iE]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
6866     //     while ( segIt->more() )
6867     //     {
6868     //       const SMDS_MeshElement* seg = segIt->next();
6869     //       if ( !eos->_subMesh->DependsOn( seg->getshapeId() ))
6870     //         continue;
6871     //       if ( seg->GetNode(0) != eE[iE]->_nodes[0] )
6872     //         continue; // not to check a seg twice
6873     //       for ( size_t iN = 0; iN < eE[iE]->_neibors.size(); ++iN )
6874     //       {
6875     //         _LayerEdge* eN = eE[iE]->_neibors[iN];
6876     //         if ( eN->_nodes[0]->getshapeId() != eos->_shapeID )
6877     //           continue;
6878     //         double dist    = SMESH_MeshAlgos::GetDistance( seg, SMESH_TNodeXYZ( eN->_nodes[0] ));
6879     //         double smooLen = getSmoothingThickness( eE[iE]->_cosin, dist );
6880     //         eN->SetSmooLen( Min( smooLen, eN->GetSmooLen() ));
6881     //         eN->Set( _LayerEdge::NEAR_BOUNDARY );
6882     //       }
6883     //     }
6884     //   }
6885     // }
6886   } // if ( eos->ShapeType() == TopAbs_FACE )
6887
6888   for ( size_t i = 0; i < eos->_edges.size(); ++i )
6889   {
6890     eos->_edges[i]->_smooFunction = 0;
6891     eos->_edges[i]->Set( _LayerEdge::TO_SMOOTH );
6892   }
6893   bool isCurved = false;
6894   for ( size_t i = 0; i < eos->_edges.size(); ++i )
6895   {
6896     _LayerEdge* edge = eos->_edges[i];
6897
6898     // get simplices sorted
6899     _Simplex::SortSimplices( edge->_simplices );
6900
6901     // smoothing function
6902     edge->ChooseSmooFunction( vertices, _n2eMap );
6903
6904     // set _curvature
6905     double avgNormProj = 0, avgLen = 0;
6906     for ( size_t iS = 0; iS < edge->_simplices.size(); ++iS )
6907     {
6908       _Simplex& s = edge->_simplices[iS];
6909
6910       gp_XYZ  vec = edge->_pos.back() - SMESH_TNodeXYZ( s._nPrev );
6911       avgNormProj += edge->_normal * vec;
6912       avgLen      += vec.Modulus();
6913       if ( substituteSrcNodes )
6914       {
6915         s._nNext = _n2eMap[ s._nNext ]->_nodes.back();
6916         s._nPrev = _n2eMap[ s._nPrev ]->_nodes.back();
6917       }
6918     }
6919     avgNormProj /= edge->_simplices.size();
6920     avgLen      /= edge->_simplices.size();
6921     if (( edge->_curvature = _Curvature::New( avgNormProj, avgLen )))
6922     {
6923       edge->Set( _LayerEdge::SMOOTHED_C1 );
6924       isCurved = true;
6925       SMDS_FacePositionPtr fPos = edge->_nodes[0]->GetPosition();
6926       if ( !fPos )
6927         for ( size_t iS = 0; iS < edge->_simplices.size()  &&  !fPos; ++iS )
6928           fPos = edge->_simplices[iS]._nPrev->GetPosition();
6929       if ( fPos )
6930         edge->_curvature->_uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
6931     }
6932   }
6933
6934   // prepare for putOnOffsetSurface()
6935   if (( eos->ShapeType() == TopAbs_FACE ) &&
6936       ( isCurved || !eos->_eosConcaVer.empty() ))
6937   {
6938     eos->_offsetSurf = helper.GetSurface( TopoDS::Face( eos->_shape ));
6939     eos->_edgeForOffset = 0;
6940
6941     double maxCosin = -1;
6942     bool hasNoShrink = false;
6943     for ( TopExp_Explorer eExp( eos->_shape, TopAbs_EDGE ); eExp.More(); eExp.Next() )
6944     {
6945       _EdgesOnShape* eoe = GetShapeEdges( eExp.Current() );
6946       if ( !eoe || eoe->_edges.empty() ) continue;
6947
6948       if ( eos->GetData()._noShrinkShapes.count( eoe->_shapeID ))
6949         hasNoShrink = true;
6950
6951       vector<_LayerEdge*>& eE = eoe->_edges;
6952       _LayerEdge* e = eE[ eE.size() / 2 ];
6953       if ( !e->Is( _LayerEdge::RISKY_SWOL ) && e->_cosin > maxCosin )
6954       {
6955         eos->_edgeForOffset = e;
6956         maxCosin = e->_cosin;
6957       }
6958
6959       if ( !eoe->_sWOL.IsNull() )
6960         for ( _LayerEdge* le : eoe->_edges )
6961           if ( le->Is( _LayerEdge::RISKY_SWOL ) && e->_cosin > 0 )
6962           {
6963             // make _neibors on FACE be smoothed after le->Is( BLOCKED )
6964             for ( _LayerEdge* neibor : le->_neibors )
6965             {
6966               int shapeDim =  neibor->BaseShapeDim();
6967               if ( shapeDim == 2 )
6968                 neibor->Set( _LayerEdge::NEAR_BOUNDARY ); // on FACE
6969               else if ( shapeDim == 0 )
6970                 neibor->Set( _LayerEdge::RISKY_SWOL );    // on VERTEX
6971
6972               if ( !neibor->_curvature )
6973               {
6974                 gp_XY uv = helper.GetNodeUV( F, neibor->_nodes[0] );
6975                 neibor->_curvature = _Factory::NewCurvature();
6976                 neibor->_curvature->_r = 0;
6977                 neibor->_curvature->_k = 0;
6978                 neibor->_curvature->_h2lenRatio = 0;
6979                 neibor->_curvature->_uv = uv;
6980               }
6981             }
6982           }
6983     } // loop on EDGEs
6984
6985     // Try to initialize _Mapper2D
6986
6987     if ( hasNoShrink )
6988       return;
6989
6990     SMDS_ElemIteratorPtr fIt = eos->_subMesh->GetSubMeshDS()->GetElements();
6991     if ( !fIt->more() || fIt->next()->NbCornerNodes() != 4 )
6992       return;
6993
6994     // get EDGEs of quadrangle bottom
6995     std::list< TopoDS_Edge > edges;
6996     std::list< int > nbEdgesInWire;
6997     int nbWire = SMESH_Block::GetOrderedEdges( F, edges, nbEdgesInWire );
6998     if ( nbWire != 1 || nbEdgesInWire.front() < 4 )
6999       return;
7000     const SMDS_MeshNode* node;
7001     while ( true ) // make edges start at a corner VERTEX
7002     {
7003       node = SMESH_Algo::VertexNode( helper.IthVertex( 0, edges.front() ), helper.GetMeshDS() );
7004       if ( node && helper.IsCornerOfStructure( node, eos->_subMesh->GetSubMeshDS(), helper ))
7005         break;
7006       edges.pop_front();
7007       if ( edges.empty() )
7008         return;
7009     }
7010     std::list< TopoDS_Edge >::iterator edgeIt = edges.begin();
7011     while ( true ) // make edges finish at a corner VERTEX
7012     {
7013       node = SMESH_Algo::VertexNode( helper.IthVertex( 1, *edgeIt ), helper.GetMeshDS() );
7014       ++edgeIt;
7015       if ( node && helper.IsCornerOfStructure( node, eos->_subMesh->GetSubMeshDS(), helper ))
7016       {
7017         edges.erase( edgeIt, edges.end() );
7018         break;
7019       }
7020       if ( edgeIt == edges.end() )
7021         return;
7022     }
7023
7024     // get structure of nodes
7025     TParam2ColumnMap param2ColumnMap;
7026     if ( !helper.LoadNodeColumns( param2ColumnMap, F, edges, helper.GetMeshDS() ))
7027       return;
7028
7029     eos->_mapper2D = new _Mapper2D( param2ColumnMap, eos->GetData()._n2eMap );
7030
7031   } // if eos is of curved FACE
7032
7033   return;
7034 }
7035
7036 //================================================================================
7037 /*!
7038  * \brief Add faces for smoothing
7039  */
7040 //================================================================================
7041
7042 void _SolidData::AddShapesToSmooth( const set< _EdgesOnShape* >& eosToSmooth,
7043                                     const set< _EdgesOnShape* >* edgesNoAnaSmooth )
7044 {
7045   set< _EdgesOnShape * >::const_iterator eos = eosToSmooth.begin();
7046   for ( ; eos != eosToSmooth.end(); ++eos )
7047   {
7048     if ( !*eos || (*eos)->_toSmooth ) continue;
7049
7050     (*eos)->_toSmooth = true;
7051
7052     if ( (*eos)->ShapeType() == TopAbs_FACE )
7053     {
7054       PrepareEdgesToSmoothOnFace( *eos, /*substituteSrcNodes=*/false );
7055       (*eos)->_toSmooth = true;
7056     }
7057   }
7058
7059   // avoid _Smoother1D::smoothAnalyticEdge() of edgesNoAnaSmooth
7060   if ( edgesNoAnaSmooth )
7061     for ( eos = edgesNoAnaSmooth->begin(); eos != edgesNoAnaSmooth->end(); ++eos )
7062     {
7063       if ( (*eos)->_edgeSmoother )
7064         (*eos)->_edgeSmoother->_anaCurve.Nullify();
7065     }
7066 }
7067
7068 //================================================================================
7069 /*!
7070  * \brief Limit _LayerEdge::_maxLen according to local curvature
7071  */
7072 //================================================================================
7073
7074 void _ViscousBuilder::limitMaxLenByCurvature( _SolidData& data, SMESH_MesherHelper& /*helper*/ )
7075 {
7076   // find intersection of neighbor _LayerEdge's to limit _maxLen
7077   // according to local curvature (IPAL52648)
7078
7079   // This method must be called after findCollisionEdges() where _LayerEdge's
7080   // get _lenFactor initialized in the case of eos._hyp.IsOffsetMethod()
7081
7082   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
7083   {
7084     _EdgesOnShape& eosI = data._edgesOnShape[iS];
7085     if ( eosI._edges.empty() ) continue;
7086     if ( !eosI._hyp.ToSmooth() )
7087     {
7088       for ( size_t i = 0; i < eosI._edges.size(); ++i )
7089       {
7090         _LayerEdge* eI = eosI._edges[i];
7091         for ( size_t iN = 0; iN < eI->_neibors.size(); ++iN )
7092         {
7093           _LayerEdge* eN = eI->_neibors[iN];
7094           if ( eI->_nodes[0]->GetID() < eN->_nodes[0]->GetID() ) // treat this pair once
7095           {
7096             _EdgesOnShape* eosN = data.GetShapeEdges( eN );
7097             limitMaxLenByCurvature( eI, eN, eosI, *eosN, eosI._hyp.ToSmooth() );
7098           }
7099         }
7100       }
7101     }
7102     else if ( eosI.ShapeType() == TopAbs_EDGE )
7103     {
7104       const TopoDS_Edge& E = TopoDS::Edge( eosI._shape );
7105       if ( SMESH_Algo::IsStraight( E, /*degenResult=*/true )) continue;
7106
7107       _LayerEdge* e0 = eosI._edges[0];
7108       for ( size_t i = 1; i < eosI._edges.size(); ++i )
7109       {
7110         _LayerEdge* eI = eosI._edges[i];
7111         limitMaxLenByCurvature( eI, e0, eosI, eosI, eosI._hyp.ToSmooth() );
7112         e0 = eI;
7113       }
7114     }
7115   }
7116 }
7117
7118 //================================================================================
7119 /*!
7120  * \brief Limit _LayerEdge::_maxLen according to local curvature
7121  */
7122 //================================================================================
7123
7124 void _ViscousBuilder::limitMaxLenByCurvature( _LayerEdge*    e1,
7125                                               _LayerEdge*    e2,
7126                                               _EdgesOnShape& /*eos1*/,
7127                                               _EdgesOnShape& /*eos2*/,
7128                                               const bool     /*isSmoothable*/ )
7129 {
7130   if (( e1->_nodes[0]->GetPosition()->GetDim() !=
7131         e2->_nodes[0]->GetPosition()->GetDim() ) &&
7132       ( e1->_cosin < 0.75 ))
7133     return; // angle > 90 deg at e1
7134
7135   gp_XYZ plnNorm = e1->_normal ^ e2->_normal;
7136   double norSize = plnNorm.SquareModulus();
7137   if ( norSize < std::numeric_limits<double>::min() )
7138     return; // parallel normals
7139
7140   // find closest points of skew _LayerEdge's
7141   SMESH_TNodeXYZ src1( e1->_nodes[0] ), src2( e2->_nodes[0] );
7142   gp_XYZ dir12 = src2 - src1;
7143   gp_XYZ perp1 = e1->_normal ^ plnNorm;
7144   gp_XYZ perp2 = e2->_normal ^ plnNorm;
7145   double  dot1 = perp2 * e1->_normal;
7146   double  dot2 = perp1 * e2->_normal;
7147   double    u1 =   ( perp2 * dir12 ) / dot1;
7148   double    u2 = - ( perp1 * dir12 ) / dot2;
7149   if ( u1 > 0 && u2 > 0 )
7150   {
7151     double ovl = ( u1 * e1->_normal * dir12 -
7152                    u2 * e2->_normal * dir12 ) / dir12.SquareModulus();
7153     if ( ovl > theSmoothThickToElemSizeRatio )
7154     {
7155       const double coef = 0.75;
7156       e1->SetMaxLen( Min( e1->_maxLen, coef * u1 / e1->_lenFactor ));
7157       e2->SetMaxLen( Min( e2->_maxLen, coef * u2 / e2->_lenFactor ));
7158     }
7159   }
7160 }
7161
7162 //================================================================================
7163 /*!
7164  * \brief Fill data._collisionEdges
7165  */
7166 //================================================================================
7167
7168 void _ViscousBuilder::findCollisionEdges( _SolidData& data, SMESH_MesherHelper& helper )
7169 {
7170   data._collisionEdges.clear();
7171
7172   // set the full thickness of the layers to LEs
7173   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
7174   {
7175     _EdgesOnShape& eos = data._edgesOnShape[iS];
7176     if ( eos._edges.empty() ) continue;
7177     if ( eos.ShapeType() != TopAbs_EDGE && eos.ShapeType() != TopAbs_VERTEX ) continue;
7178     if ( !eos._sWOL.IsNull() ) continue; // PAL23566
7179
7180     for ( size_t i = 0; i < eos._edges.size(); ++i )
7181     {
7182       if ( eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
7183       double maxLen = eos._edges[i]->_maxLen;
7184       eos._edges[i]->_maxLen = Precision::Infinite(); // avoid blocking
7185       eos._edges[i]->SetNewLength( 1.5 * maxLen, eos, helper );
7186       eos._edges[i]->_maxLen = maxLen;
7187     }
7188   }
7189
7190   // make temporary quadrangles got by extrusion of
7191   // mesh edges along _LayerEdge._normal's
7192
7193   vector< const SMDS_MeshElement* > tmpFaces;
7194
7195   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
7196   {
7197     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
7198     if ( eos.ShapeType() != TopAbs_EDGE )
7199       continue;
7200     if ( eos._edges.empty() )
7201     {
7202       _LayerEdge* edge[2] = { 0, 0 }; // LE of 2 VERTEX'es
7203       SMESH_subMeshIteratorPtr smIt = eos._subMesh->getDependsOnIterator(/*includeSelf=*/false);
7204       while ( smIt->more() )
7205         if ( _EdgesOnShape* eov = data.GetShapeEdges( smIt->next()->GetId() ))
7206           if ( eov->_edges.size() == 1 )
7207             edge[ bool( edge[0]) ] = eov->_edges[0];
7208
7209       if ( edge[1] )
7210       {
7211         _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge[0], edge[1], --_tmpFaceID );
7212         tmpFaces.push_back( f );
7213       }
7214     }
7215     for ( size_t i = 0; i < eos._edges.size(); ++i )
7216     {
7217       _LayerEdge* edge = eos._edges[i];
7218       for ( int j = 0; j < 2; ++j ) // loop on _2NearEdges
7219       {
7220         const SMDS_MeshNode* src2 = edge->_2neibors->srcNode(j);
7221         if ( src2->GetPosition()->GetDim() > 0 &&
7222              src2->GetID() < edge->_nodes[0]->GetID() )
7223           continue; // avoid using same segment twice
7224
7225         // a _LayerEdge containing tgt2
7226         _LayerEdge* neiborEdge = edge->_2neibors->_edges[j];
7227
7228         _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge, neiborEdge, --_tmpFaceID );
7229         tmpFaces.push_back( f );
7230       }
7231     }
7232   }
7233
7234   // Find _LayerEdge's intersecting tmpFaces.
7235
7236   SMDS_ElemIteratorPtr fIt( new SMDS_ElementVectorIterator( tmpFaces.begin(),
7237                                                             tmpFaces.end()));
7238   SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
7239     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(), fIt ));
7240
7241   double dist1, dist2, segLen, eps = 0.5;
7242   _CollisionEdges collEdges;
7243   vector< const SMDS_MeshElement* > suspectFaces;
7244   const double angle45 = Cos( 45. * M_PI / 180. );
7245
7246   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
7247   {
7248     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
7249     if ( eos.ShapeType() == TopAbs_FACE || !eos._sWOL.IsNull() )
7250       continue;
7251     // find sub-shapes whose VL can influence VL on eos
7252     set< TGeomID > neighborShapes;
7253     PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
7254     while ( const TopoDS_Shape* face = fIt->next() )
7255     {
7256       TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
7257       if ( _EdgesOnShape* eof = data.GetShapeEdges( faceID ))
7258       {
7259         SMESH_subMeshIteratorPtr subIt = eof->_subMesh->getDependsOnIterator(/*includeSelf=*/false);
7260         while ( subIt->more() )
7261           neighborShapes.insert( subIt->next()->GetId() );
7262       }
7263     }
7264     if ( eos.ShapeType() == TopAbs_VERTEX )
7265     {
7266       PShapeIteratorPtr eIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_EDGE );
7267       while ( const TopoDS_Shape* edge = eIt->next() )
7268         neighborShapes.erase( getMeshDS()->ShapeToIndex( *edge ));
7269     }
7270     // find intersecting _LayerEdge's
7271     for ( size_t i = 0; i < eos._edges.size(); ++i )
7272     {
7273       if ( eos._edges[i]->Is( _LayerEdge::MULTI_NORMAL )) continue;
7274       _LayerEdge*   edge = eos._edges[i];
7275       gp_Ax1 lastSegment = edge->LastSegment( segLen, eos );
7276       segLen *= 1.2;
7277
7278       gp_Vec eSegDir0, eSegDir1;
7279       if ( edge->IsOnEdge() )
7280       {
7281         SMESH_TNodeXYZ eP( edge->_nodes[0] );
7282         eSegDir0 = SMESH_TNodeXYZ( edge->_2neibors->srcNode(0) ) - eP;
7283         eSegDir1 = SMESH_TNodeXYZ( edge->_2neibors->srcNode(1) ) - eP;
7284       }
7285       suspectFaces.clear();
7286       searcher->GetElementsInSphere( SMESH_TNodeXYZ( edge->_nodes.back()), edge->_len * 2,
7287                                      SMDSAbs_Face, suspectFaces );
7288       collEdges._intEdges.clear();
7289       for ( size_t j = 0 ; j < suspectFaces.size(); ++j )
7290       {
7291         const _TmpMeshFaceOnEdge* f = (const _TmpMeshFaceOnEdge*) suspectFaces[j];
7292         if ( f->_le1 == edge || f->_le2 == edge ) continue;
7293         if ( !neighborShapes.count( f->_le1->_nodes[0]->getshapeId() )) continue;
7294         if ( !neighborShapes.count( f->_le2->_nodes[0]->getshapeId() )) continue;
7295         if ( edge->IsOnEdge() ) {
7296           if ( edge->_2neibors->include( f->_le1 ) ||
7297                edge->_2neibors->include( f->_le2 )) continue;
7298         }
7299         else {
7300           if (( f->_le1->IsOnEdge() && f->_le1->_2neibors->include( edge )) ||
7301               ( f->_le2->IsOnEdge() && f->_le2->_2neibors->include( edge )))  continue;
7302         }
7303         dist1 = dist2 = Precision::Infinite();
7304         if ( !edge->SegTriaInter( lastSegment, f->n(0), f->n(1), f->n(2), dist1, eps ))
7305           dist1 = Precision::Infinite();
7306         if ( !edge->SegTriaInter( lastSegment, f->n(3), f->n(2), f->n(0), dist2, eps ))
7307           dist2 = Precision::Infinite();
7308         if (( dist1 > segLen ) && ( dist2 > segLen ))
7309           continue;
7310
7311         if ( edge->IsOnEdge() )
7312         {
7313           // skip perpendicular EDGEs
7314           gp_Vec fSegDir  = SMESH_TNodeXYZ( f->n(0) ) - SMESH_TNodeXYZ( f->n(3) );
7315           bool isParallel = ( isLessAngle( eSegDir0, fSegDir, angle45 ) ||
7316                               isLessAngle( eSegDir1, fSegDir, angle45 ) ||
7317                               isLessAngle( eSegDir0, fSegDir.Reversed(), angle45 ) ||
7318                               isLessAngle( eSegDir1, fSegDir.Reversed(), angle45 ));
7319           if ( !isParallel )
7320             continue;
7321         }
7322
7323         // either limit inflation of edges or remember them for updating _normal
7324         // double dot = edge->_normal * f->GetDir();
7325         // if ( dot > 0.1 )
7326         {
7327           collEdges._intEdges.push_back( f->_le1 );
7328           collEdges._intEdges.push_back( f->_le2 );
7329         }
7330         // else
7331         // {
7332         //   double shortLen = 0.75 * ( Min( dist1, dist2 ) / edge->_lenFactor );
7333         //   edge->SetMaxLen( Min( shortLen, edge->_maxLen ));
7334         // }
7335       }
7336
7337       if ( !collEdges._intEdges.empty() )
7338       {
7339         collEdges._edge = edge;
7340         data._collisionEdges.push_back( collEdges );
7341       }
7342     }
7343   }
7344
7345   for ( size_t i = 0 ; i < tmpFaces.size(); ++i )
7346     delete tmpFaces[i];
7347
7348   // restore the zero thickness
7349   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
7350   {
7351     _EdgesOnShape& eos = data._edgesOnShape[iS];
7352     if ( eos._edges.empty() ) continue;
7353     if ( eos.ShapeType() != TopAbs_EDGE && eos.ShapeType() != TopAbs_VERTEX ) continue;
7354
7355     for ( size_t i = 0; i < eos._edges.size(); ++i )
7356     {
7357       eos._edges[i]->InvalidateStep( 1, eos );
7358       eos._edges[i]->_len = 0;
7359     }
7360   }
7361 }
7362
7363 //================================================================================
7364 /*!
7365  * \brief Find _LayerEdge's located on boundary of a convex FACE whose normal
7366  *        will be updated at each inflation step
7367  */
7368 //================================================================================
7369
7370 void _ViscousBuilder::findEdgesToUpdateNormalNearConvexFace( _ConvexFace &       convFace,
7371                                                              _SolidData&         data,
7372                                                              SMESH_MesherHelper& helper )
7373 {
7374   const TGeomID convFaceID = getMeshDS()->ShapeToIndex( convFace._face );
7375   const double       preci = BRep_Tool::Tolerance( convFace._face );
7376   Handle(ShapeAnalysis_Surface) surface = helper.GetSurface( convFace._face );
7377
7378   bool edgesToUpdateFound = false;
7379
7380   map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.begin();
7381   for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7382   {
7383     _EdgesOnShape& eos = * id2eos->second;
7384     if ( !eos._sWOL.IsNull() ) continue;
7385     if ( !eos._hyp.ToSmooth() ) continue;
7386     for ( size_t i = 0; i < eos._edges.size(); ++i )
7387     {
7388       _LayerEdge* ledge = eos._edges[ i ];
7389       if ( ledge->Is( _LayerEdge::UPD_NORMAL_CONV )) continue; // already checked
7390       if ( ledge->Is( _LayerEdge::MULTI_NORMAL )) continue; // not inflatable
7391
7392       gp_XYZ tgtPos = ( SMESH_NodeXYZ( ledge->_nodes[0] ) +
7393                         ledge->_normal * ledge->_lenFactor * ledge->_maxLen );
7394
7395       // the normal must be updated if distance from tgtPos to surface is less than
7396       // target thickness
7397
7398       // find an initial UV for search of a projection of tgtPos to surface
7399       const SMDS_MeshNode* nodeInFace = 0;
7400       SMDS_ElemIteratorPtr fIt = ledge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
7401       while ( fIt->more() && !nodeInFace )
7402       {
7403         const SMDS_MeshElement* f = fIt->next();
7404         if ( convFaceID != f->getshapeId() ) continue;
7405
7406         SMDS_ElemIteratorPtr nIt = f->nodesIterator();
7407         while ( nIt->more() && !nodeInFace )
7408         {
7409           const SMDS_MeshElement* n = nIt->next();
7410           if ( n->getshapeId() == convFaceID )
7411             nodeInFace = static_cast< const SMDS_MeshNode* >( n );
7412         }
7413       }
7414       if ( !nodeInFace )
7415         continue;
7416       gp_XY uv = helper.GetNodeUV( convFace._face, nodeInFace );
7417
7418       // projection
7419       surface->NextValueOfUV( uv, tgtPos, preci );
7420       double  dist = surface->Gap();
7421       if ( dist < 0.95 * ledge->_maxLen )
7422       {
7423         ledge->Set( _LayerEdge::UPD_NORMAL_CONV );
7424         if ( !ledge->_curvature ) ledge->_curvature = _Factory::NewCurvature();
7425         ledge->_curvature->_uv.SetCoord( uv.X(), uv.Y() );
7426         edgesToUpdateFound = true;
7427       }
7428     }
7429   }
7430
7431   if ( !convFace._isTooCurved && edgesToUpdateFound )
7432   {
7433     data._convexFaces.insert( make_pair( convFaceID, convFace )).first->second;
7434   }
7435 }
7436
7437 //================================================================================
7438 /*!
7439  * \brief Modify normals of _LayerEdge's on EDGE's to avoid intersection with
7440  * _LayerEdge's on neighbor EDGE's
7441  */
7442 //================================================================================
7443
7444 bool _ViscousBuilder::updateNormals( _SolidData&         data,
7445                                      SMESH_MesherHelper& helper,
7446                                      int                 stepNb,
7447                                      double              /*stepSize*/)
7448 {
7449   updateNormalsOfC1Vertices( data );
7450
7451   if ( stepNb > 0 && !updateNormalsOfConvexFaces( data, helper, stepNb ))
7452     return false;
7453
7454   // map to store new _normal and _cosin for each intersected edge
7455   map< _LayerEdge*, _LayerEdge, _LayerEdgeCmp >           edge2newEdge;
7456   map< _LayerEdge*, _LayerEdge, _LayerEdgeCmp >::iterator e2neIt;
7457   _LayerEdge zeroEdge;
7458   zeroEdge._normal.SetCoord( 0,0,0 );
7459   zeroEdge._maxLen = Precision::Infinite();
7460   zeroEdge._nodes.resize(1); // to init _TmpMeshFaceOnEdge
7461
7462   set< _EdgesOnShape* > shapesToSmooth, edgesNoAnaSmooth;
7463
7464   double segLen, dist1, dist2, dist;
7465   vector< pair< _LayerEdge*, double > > intEdgesDist;
7466   _TmpMeshFaceOnEdge quad( &zeroEdge, &zeroEdge, 0 );
7467
7468   for ( int iter = 0; iter < 5; ++iter )
7469   {
7470     edge2newEdge.clear();
7471
7472     for ( size_t iE = 0; iE < data._collisionEdges.size(); ++iE )
7473     {
7474       _CollisionEdges& ce = data._collisionEdges[iE];
7475       _LayerEdge*   edge1 = ce._edge;
7476       if ( !edge1 /*|| edge1->Is( _LayerEdge::BLOCKED )*/) continue;
7477       _EdgesOnShape* eos1 = data.GetShapeEdges( edge1 );
7478       if ( !eos1 ) continue;
7479
7480       // detect intersections
7481       gp_Ax1 lastSeg = edge1->LastSegment( segLen, *eos1 );
7482       double testLen = 1.5 * edge1->_maxLen * edge1->_lenFactor;
7483       double     eps = 0.5;
7484       intEdgesDist.clear();
7485       double minIntDist = Precision::Infinite();
7486       for ( size_t i = 0; i < ce._intEdges.size(); i += 2 )
7487       {
7488         if ( edge1->Is( _LayerEdge::BLOCKED ) &&
7489              ce._intEdges[i  ]->Is( _LayerEdge::BLOCKED ) &&
7490              ce._intEdges[i+1]->Is( _LayerEdge::BLOCKED ))
7491           continue;
7492         double dot  = edge1->_normal * quad.GetDir( ce._intEdges[i], ce._intEdges[i+1] );
7493         double fact = ( 1.1 + dot * dot );
7494         SMESH_TNodeXYZ pSrc0( ce.nSrc(i) ), pSrc1( ce.nSrc(i+1) );
7495         SMESH_TNodeXYZ pTgt0( ce.nTgt(i) ), pTgt1( ce.nTgt(i+1) );
7496         gp_XYZ pLast0 = pSrc0 + ( pTgt0 - pSrc0 ) * fact;
7497         gp_XYZ pLast1 = pSrc1 + ( pTgt1 - pSrc1 ) * fact;
7498         dist1 = dist2 = Precision::Infinite();
7499         if ( !edge1->SegTriaInter( lastSeg, pSrc0, pLast0, pSrc1,  dist1, eps ) &&
7500              !edge1->SegTriaInter( lastSeg, pSrc1, pLast1, pLast0, dist2, eps ))
7501           continue;
7502         dist = dist1;
7503         if ( dist > testLen || dist <= 0 )
7504         {
7505           dist = dist2;
7506           if ( dist > testLen || dist <= 0 )
7507             continue;
7508         }
7509         // choose a closest edge
7510         gp_Pnt intP( lastSeg.Location().XYZ() + lastSeg.Direction().XYZ() * ( dist + segLen ));
7511         double d1 = intP.SquareDistance( pSrc0 );
7512         double d2 = intP.SquareDistance( pSrc1 );
7513         int iClose = i + ( d2 < d1 );
7514         _LayerEdge* edge2 = ce._intEdges[iClose];
7515         edge2->Unset( _LayerEdge::MARKED );
7516
7517         // choose a closest edge among neighbors
7518         gp_Pnt srcP( SMESH_TNodeXYZ( edge1->_nodes[0] ));
7519         d1 = srcP.SquareDistance( SMESH_TNodeXYZ( edge2->_nodes[0] ));
7520         for ( size_t j = 0; j < intEdgesDist.size(); ++j )
7521         {
7522           _LayerEdge * edgeJ = intEdgesDist[j].first;
7523           if ( edge2->IsNeiborOnEdge( edgeJ ))
7524           {
7525             d2 = srcP.SquareDistance( SMESH_TNodeXYZ( edgeJ->_nodes[0] ));
7526             ( d1 < d2 ? edgeJ : edge2 )->Set( _LayerEdge::MARKED );
7527           }
7528         }
7529         intEdgesDist.push_back( make_pair( edge2, dist ));
7530         // if ( Abs( d2 - d1 ) / Max( d2, d1 ) < 0.5 )
7531         // {
7532         //   iClose = i + !( d2 < d1 );
7533         //   intEdges.push_back( ce._intEdges[iClose] );
7534         //   ce._intEdges[iClose]->Unset( _LayerEdge::MARKED );
7535         // }
7536         minIntDist = Min( edge1->_len * edge1->_lenFactor - segLen + dist, minIntDist );
7537       }
7538
7539       //ce._edge = 0;
7540
7541       // compute new _normals
7542       for ( size_t i = 0; i < intEdgesDist.size(); ++i )
7543       {
7544         _LayerEdge* edge2   = intEdgesDist[i].first;
7545         double      distWgt = edge1->_len / intEdgesDist[i].second;
7546         // if ( edge1->Is( _LayerEdge::BLOCKED ) &&
7547         //      edge2->Is( _LayerEdge::BLOCKED )) continue;        
7548         if ( edge2->Is( _LayerEdge::MARKED )) continue;
7549         edge2->Set( _LayerEdge::MARKED );
7550
7551         // get a new normal
7552         gp_XYZ dir1 = edge1->_normal, dir2 = edge2->_normal;
7553
7554         double cos1 = Abs( edge1->_cosin ), cos2 = Abs( edge2->_cosin );
7555         double wgt1 = ( cos1 + 0.001 ) / ( cos1 + cos2 + 0.002 );
7556         double wgt2 = ( cos2 + 0.001 ) / ( cos1 + cos2 + 0.002 );
7557         // double cos1 = Abs( edge1->_cosin ),        cos2 = Abs( edge2->_cosin );
7558         // double sgn1 = 0.1 * ( 1 + edge1->_cosin ), sgn2 = 0.1 * ( 1 + edge2->_cosin );
7559         // double wgt1 = ( cos1 + sgn1 ) / ( cos1 + cos2 + sgn1 + sgn2 );
7560         // double wgt2 = ( cos2 + sgn2 ) / ( cos1 + cos2 + sgn1 + sgn2 );
7561         gp_XYZ newNormal = wgt1 * dir1 + wgt2 * dir2;
7562         newNormal.Normalize();
7563
7564         // get new cosin
7565         double newCos;
7566         double sgn1 = edge1->_cosin / cos1, sgn2 = edge2->_cosin / cos2;
7567         if ( cos1 < theMinSmoothCosin )
7568         {
7569           newCos = cos2 * sgn1;
7570         }
7571         else if ( cos2 > theMinSmoothCosin ) // both cos1 and cos2 > theMinSmoothCosin
7572         {
7573           newCos = ( wgt1 * cos1 + wgt2 * cos2 ) * edge1->_cosin / cos1;
7574         }
7575         else
7576         {
7577           newCos = edge1->_cosin;
7578         }
7579
7580         e2neIt = edge2newEdge.insert( make_pair( edge1, zeroEdge )).first;
7581         e2neIt->second._normal += distWgt * newNormal;
7582         e2neIt->second._cosin   = newCos;
7583         e2neIt->second.SetMaxLen( 0.7 * minIntDist / edge1->_lenFactor );
7584         if ( iter > 0 && sgn1 * sgn2 < 0 && edge1->_cosin < 0 )
7585           e2neIt->second._normal += dir2;
7586
7587         e2neIt = edge2newEdge.insert( make_pair( edge2, zeroEdge )).first;
7588         e2neIt->second._normal += distWgt * newNormal;
7589         if ( Precision::IsInfinite( zeroEdge._maxLen ))
7590         {
7591           e2neIt->second._cosin  = edge2->_cosin;
7592           e2neIt->second.SetMaxLen( 1.3 * minIntDist / edge1->_lenFactor );
7593         }
7594         if ( iter > 0 && sgn1 * sgn2 < 0 && edge2->_cosin < 0 )
7595           e2neIt->second._normal += dir1;
7596       }
7597     }
7598
7599     if ( edge2newEdge.empty() )
7600       break; //return true;
7601
7602     dumpFunction(SMESH_Comment("updateNormals")<< data._index << "_" << stepNb << "_it" << iter);
7603
7604     // Update data of edges depending on a new _normal
7605
7606     data.UnmarkEdges();
7607     for ( e2neIt = edge2newEdge.begin(); e2neIt != edge2newEdge.end(); ++e2neIt )
7608     {
7609       _LayerEdge*    edge = e2neIt->first;
7610       _LayerEdge& newEdge = e2neIt->second;
7611       _EdgesOnShape*  eos = data.GetShapeEdges( edge );
7612       if ( edge->Is( _LayerEdge::BLOCKED ) && newEdge._maxLen > edge->_len )
7613         continue;
7614
7615       // Check if a new _normal is OK:
7616       newEdge._normal.Normalize();
7617       if ( !isNewNormalOk( data, *edge, newEdge._normal ))
7618       {
7619         if ( newEdge._maxLen < edge->_len && iter > 0 ) // limit _maxLen
7620         {
7621           edge->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true  );
7622           edge->SetMaxLen( newEdge._maxLen );
7623           edge->SetNewLength( newEdge._maxLen, *eos, helper );
7624         }
7625         continue; // the new _normal is bad
7626       }
7627       // the new _normal is OK
7628
7629       // find shapes that need smoothing due to change of _normal
7630       if ( edge->_cosin   < theMinSmoothCosin &&
7631            newEdge._cosin > theMinSmoothCosin )
7632       {
7633         if ( eos->_sWOL.IsNull() )
7634         {
7635           SMDS_ElemIteratorPtr fIt = edge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
7636           while ( fIt->more() )
7637             shapesToSmooth.insert( data.GetShapeEdges( fIt->next()->getshapeId() ));
7638         }
7639         else // edge inflates along a FACE
7640         {
7641           TopoDS_Shape V = helper.GetSubShapeByNode( edge->_nodes[0], getMeshDS() );
7642           PShapeIteratorPtr eIt = helper.GetAncestors( V, *_mesh, TopAbs_EDGE, &eos->_sWOL );
7643           while ( const TopoDS_Shape* E = eIt->next() )
7644           {
7645             gp_Vec edgeDir = getEdgeDir( TopoDS::Edge( *E ), TopoDS::Vertex( V ),
7646                                          eos->_hyp.Get1stLayerThickness() );
7647             double   angle = edgeDir.Angle( newEdge._normal ); // [0,PI]
7648             if ( angle < M_PI / 2 )
7649               shapesToSmooth.insert( data.GetShapeEdges( *E ));
7650           }
7651         }
7652       }
7653
7654       double len = edge->_len;
7655       edge->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true  );
7656       edge->SetNormal( newEdge._normal );
7657       edge->SetCosin( newEdge._cosin );
7658       edge->SetNewLength( len, *eos, helper );
7659       edge->Set( _LayerEdge::MARKED );
7660       edge->Set( _LayerEdge::NORMAL_UPDATED );
7661       edgesNoAnaSmooth.insert( eos );
7662     }
7663
7664     // Update normals and other dependent data of not intersecting _LayerEdge's
7665     // neighboring the intersecting ones
7666
7667     for ( e2neIt = edge2newEdge.begin(); e2neIt != edge2newEdge.end(); ++e2neIt )
7668     {
7669       _LayerEdge*   edge1 = e2neIt->first;
7670       _EdgesOnShape* eos1 = data.GetShapeEdges( edge1 );
7671       if ( !edge1->Is( _LayerEdge::MARKED ))
7672         continue;
7673
7674       if ( edge1->IsOnEdge() )
7675       {
7676         const SMDS_MeshNode * n1 = edge1->_2neibors->srcNode(0);
7677         const SMDS_MeshNode * n2 = edge1->_2neibors->srcNode(1);
7678         edge1->SetDataByNeighbors( n1, n2, *eos1, helper );
7679       }
7680
7681       if ( !edge1->_2neibors || !eos1->_sWOL.IsNull() )
7682         continue;
7683       for ( int j = 0; j < 2; ++j ) // loop on 2 neighbors
7684       {
7685         _LayerEdge* neighbor = edge1->_2neibors->_edges[j];
7686         if ( neighbor->Is( _LayerEdge::MARKED ) /*edge2newEdge.count ( neighbor )*/)
7687           continue; // j-th neighbor is also intersected
7688         _LayerEdge* prevEdge = edge1;
7689         const int nbSteps = 10;
7690         for ( int step = nbSteps; step; --step ) // step from edge1 in j-th direction
7691         {
7692           if ( neighbor->Is( _LayerEdge::BLOCKED ) ||
7693                neighbor->Is( _LayerEdge::MARKED ))
7694             break;
7695           _EdgesOnShape* eos = data.GetShapeEdges( neighbor );
7696           if ( !eos ) continue;
7697           _LayerEdge* nextEdge = neighbor;
7698           if ( neighbor->_2neibors )
7699           {
7700             int iNext = 0;
7701             nextEdge = neighbor->_2neibors->_edges[iNext];
7702             if ( nextEdge == prevEdge )
7703               nextEdge = neighbor->_2neibors->_edges[ ++iNext ];
7704           }
7705           double r = double(step-1)/nbSteps/(iter+1);
7706           if ( !nextEdge->_2neibors )
7707             r = Min( r, 0.5 );
7708
7709           gp_XYZ newNorm = prevEdge->_normal * r + nextEdge->_normal * (1-r);
7710           newNorm.Normalize();
7711           if ( !isNewNormalOk( data, *neighbor, newNorm ))
7712             break;
7713
7714           double len = neighbor->_len;
7715           neighbor->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true  );
7716           neighbor->SetNormal( newNorm );
7717           neighbor->SetCosin( prevEdge->_cosin * r + nextEdge->_cosin * (1-r) );
7718           if ( neighbor->_2neibors )
7719             neighbor->SetDataByNeighbors( prevEdge->_nodes[0], nextEdge->_nodes[0], *eos, helper );
7720           neighbor->SetNewLength( len, *eos, helper );
7721           neighbor->Set( _LayerEdge::MARKED );
7722           neighbor->Set( _LayerEdge::NORMAL_UPDATED );
7723           edgesNoAnaSmooth.insert( eos );
7724
7725           if ( !neighbor->_2neibors )
7726             break; // neighbor is on VERTEX
7727
7728           // goto the next neighbor
7729           prevEdge = neighbor;
7730           neighbor = nextEdge;
7731         }
7732       }
7733     }
7734     dumpFunctionEnd();
7735   } // iterations
7736
7737   data.AddShapesToSmooth( shapesToSmooth, &edgesNoAnaSmooth );
7738
7739   return true;
7740 }
7741
7742 //================================================================================
7743 /*!
7744  * \brief Check if a new normal is OK
7745  */
7746 //================================================================================
7747
7748 bool _ViscousBuilder::isNewNormalOk( _SolidData&   data,
7749                                      _LayerEdge&   edge,
7750                                      const gp_XYZ& newNormal)
7751 {
7752   // check a min angle between the newNormal and surrounding faces
7753   vector<_Simplex> simplices;
7754   SMESH_TNodeXYZ n0( edge._nodes[0] ), n1, n2;
7755   _Simplex::GetSimplices( n0._node, simplices, data._ignoreFaceIds, &data );
7756   double newMinDot = 1, curMinDot = 1;
7757   for ( size_t i = 0; i < simplices.size(); ++i )
7758   {
7759     n1.Set( simplices[i]._nPrev );
7760     n2.Set( simplices[i]._nNext );
7761     gp_XYZ normFace = ( n1 - n0 ) ^ ( n2 - n0 );
7762     double normLen2 = normFace.SquareModulus();
7763     if ( normLen2 < std::numeric_limits<double>::min() )
7764       continue;
7765     normFace /= Sqrt( normLen2 );
7766     newMinDot = Min( newNormal    * normFace, newMinDot );
7767     curMinDot = Min( edge._normal * normFace, curMinDot );
7768   }
7769   bool ok = true;
7770   if ( newMinDot < 0.5 )
7771   {
7772     ok = ( newMinDot >= curMinDot * 0.9 );
7773     //return ( newMinDot >= ( curMinDot * ( 0.8 + 0.1 * edge.NbSteps() )));
7774     // double initMinDot2 = 1. - edge._cosin * edge._cosin;
7775     // return ( newMinDot * newMinDot ) >= ( 0.8 * initMinDot2 );
7776   }
7777
7778   return ok;
7779 }
7780
7781 //================================================================================
7782 /*!
7783  * \brief Modify normals of _LayerEdge's on FACE to reflex smoothing
7784  */
7785 //================================================================================
7786
7787 bool _ViscousBuilder::updateNormalsOfSmoothed( _SolidData&         data,
7788                                                SMESH_MesherHelper& /*helper*/,
7789                                                const int           nbSteps,
7790                                                const double        stepSize )
7791 {
7792   if ( data._nbShapesToSmooth == 0 || nbSteps == 0 )
7793     return true; // no shapes needing smoothing
7794
7795   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
7796   {
7797     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
7798     if ( //!eos._toSmooth ||  _eosC1 have _toSmooth == false
7799          !eos._hyp.ToSmooth() ||
7800          eos.ShapeType() != TopAbs_FACE ||
7801          eos._edges.empty() )
7802       continue;
7803
7804     bool toSmooth = ( eos._edges[ 0 ]->NbSteps() >= nbSteps+1 );
7805     if ( !toSmooth ) continue;
7806
7807     for ( size_t i = 0; i < eos._edges.size(); ++i )
7808     {
7809       _LayerEdge* edge = eos._edges[i];
7810       if ( !edge->Is( _LayerEdge::SMOOTHED ))
7811         continue;
7812       if ( edge->Is( _LayerEdge::DIFFICULT ) && nbSteps != 1 )
7813         continue;
7814
7815       const gp_XYZ& pPrev = edge->PrevPos();
7816       const gp_XYZ& pLast = edge->_pos.back();
7817       gp_XYZ      stepVec = pLast - pPrev;
7818       double realStepSize = stepVec.Modulus();
7819       if ( realStepSize < numeric_limits<double>::min() )
7820         continue;
7821
7822       edge->_lenFactor = realStepSize / stepSize;
7823       edge->_normal    = stepVec / realStepSize;
7824       edge->Set( _LayerEdge::NORMAL_UPDATED );
7825     }
7826   }
7827
7828   return true;
7829 }
7830
7831 //================================================================================
7832 /*!
7833  * \brief Modify normals of _LayerEdge's on C1 VERTEXes
7834  */
7835 //================================================================================
7836
7837 void _ViscousBuilder::updateNormalsOfC1Vertices( _SolidData& data )
7838 {
7839   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
7840   {
7841     _EdgesOnShape& eov = data._edgesOnShape[ iS ];
7842     if ( eov._eosC1.empty() ||
7843          eov.ShapeType() != TopAbs_VERTEX ||
7844          eov._edges.empty() )
7845       continue;
7846
7847     gp_XYZ newNorm   = eov._edges[0]->_normal;
7848     double curThick  = eov._edges[0]->_len * eov._edges[0]->_lenFactor;
7849     bool normChanged = false;
7850
7851     for ( size_t i = 0; i < eov._eosC1.size(); ++i )
7852     {
7853       _EdgesOnShape*   eoe = eov._eosC1[i];
7854       const TopoDS_Edge& e = TopoDS::Edge( eoe->_shape );
7855       const double    eLen = SMESH_Algo::EdgeLength( e );
7856       TopoDS_Shape    oppV = SMESH_MesherHelper::IthVertex( 0, e );
7857       if ( oppV.IsSame( eov._shape ))
7858         oppV = SMESH_MesherHelper::IthVertex( 1, e );
7859       _EdgesOnShape* eovOpp = data.GetShapeEdges( oppV );
7860       if ( !eovOpp || eovOpp->_edges.empty() ) continue;
7861       if ( eov._edges[0]->Is( _LayerEdge::BLOCKED )) continue;
7862
7863       double curThickOpp = eovOpp->_edges[0]->_len * eovOpp->_edges[0]->_lenFactor;
7864       if ( curThickOpp + curThick < eLen )
7865         continue;
7866
7867       double wgt = 2. * curThick / eLen;
7868       newNorm += wgt * eovOpp->_edges[0]->_normal;
7869       normChanged = true;
7870     }
7871     if ( normChanged )
7872     {
7873       eov._edges[0]->SetNormal( newNorm.Normalized() );
7874       eov._edges[0]->Set( _LayerEdge::NORMAL_UPDATED );
7875     }
7876   }
7877 }
7878
7879 //================================================================================
7880 /*!
7881  * \brief Modify normals of _LayerEdge's on _ConvexFace's
7882  */
7883 //================================================================================
7884
7885 bool _ViscousBuilder::updateNormalsOfConvexFaces( _SolidData&         data,
7886                                                   SMESH_MesherHelper& helper,
7887                                                   int                 stepNb )
7888 {
7889   SMESHDS_Mesh* meshDS = helper.GetMeshDS();
7890   bool isOK;
7891
7892   map< TGeomID, _ConvexFace >::iterator id2face = data._convexFaces.begin();
7893   for ( ; id2face != data._convexFaces.end(); ++id2face )
7894   {
7895     _ConvexFace & convFace = (*id2face).second;
7896     convFace._normalsFixedOnBorders = false; // to update at each inflation step
7897
7898     if ( convFace._normalsFixed )
7899       continue; // already fixed
7900     if ( convFace.CheckPrisms() )
7901       continue; // nothing to fix
7902
7903     convFace._normalsFixed = true;
7904
7905     BRepAdaptor_Surface surface ( convFace._face, false );
7906     BRepLProp_SLProps   surfProp( surface, 2, 1e-6 );
7907
7908     // check if the convex FACE is of spherical shape
7909
7910     Bnd_B3d centersBox; // bbox of centers of curvature of _LayerEdge's on VERTEXes
7911     Bnd_B3d nodesBox;
7912     gp_Pnt  center;
7913
7914     map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.begin();
7915     for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7916     {
7917       _EdgesOnShape& eos = *(id2eos->second);
7918       if ( eos.ShapeType() == TopAbs_VERTEX )
7919       {
7920         _LayerEdge* ledge = eos._edges[ 0 ];
7921         if ( convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
7922           centersBox.Add( center );
7923       }
7924       for ( size_t i = 0; i < eos._edges.size(); ++i )
7925         nodesBox.Add( SMESH_TNodeXYZ( eos._edges[ i ]->_nodes[0] ));
7926     }
7927     if ( centersBox.IsVoid() )
7928     {
7929       debugMsg( "Error: centersBox.IsVoid()" );
7930       return false;
7931     }
7932     const bool isSpherical =
7933       ( centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
7934
7935     int nbEdges = helper.Count( convFace._face, TopAbs_EDGE, /*ignoreSame=*/false );
7936     vector < _CentralCurveOnEdge > centerCurves( nbEdges );
7937
7938     if ( isSpherical )
7939     {
7940       // set _LayerEdge::_normal as average of all normals
7941
7942       // WARNING: different density of nodes on EDGEs is not taken into account that
7943       // can lead to an improper new normal
7944
7945       gp_XYZ avgNormal( 0,0,0 );
7946       nbEdges = 0;
7947       id2eos = convFace._subIdToEOS.begin();
7948       for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7949       {
7950         _EdgesOnShape& eos = *(id2eos->second);
7951         // set data of _CentralCurveOnEdge
7952         if ( eos.ShapeType() == TopAbs_EDGE )
7953         {
7954           _CentralCurveOnEdge& ceCurve = centerCurves[ nbEdges++ ];
7955           ceCurve.SetShapes( TopoDS::Edge( eos._shape ), convFace, data, helper );
7956           if ( !eos._sWOL.IsNull() )
7957             ceCurve._adjFace.Nullify();
7958           else
7959             ceCurve._ledges.insert( ceCurve._ledges.end(),
7960                                     eos._edges.begin(), eos._edges.end());
7961         }
7962         // summarize normals
7963         for ( size_t i = 0; i < eos._edges.size(); ++i )
7964           avgNormal += eos._edges[ i ]->_normal;
7965       }
7966       double normSize = avgNormal.SquareModulus();
7967       if ( normSize < 1e-200 )
7968       {
7969         debugMsg( "updateNormalsOfConvexFaces(): zero avgNormal" );
7970         return false;
7971       }
7972       avgNormal /= Sqrt( normSize );
7973
7974       // compute new _LayerEdge::_cosin on EDGEs
7975       double avgCosin = 0;
7976       int     nbCosin = 0;
7977       gp_Vec inFaceDir;
7978       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7979       {
7980         _CentralCurveOnEdge& ceCurve = centerCurves[ iE ];
7981         if ( ceCurve._adjFace.IsNull() )
7982           continue;
7983         for ( size_t iLE = 0; iLE < ceCurve._ledges.size(); ++iLE )
7984         {
7985           const SMDS_MeshNode* node = ceCurve._ledges[ iLE ]->_nodes[0];
7986           inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
7987           if ( isOK )
7988           {
7989             double angle = inFaceDir.Angle( avgNormal ); // [0,PI]
7990             ceCurve._ledges[ iLE ]->_cosin = Cos( angle );
7991             avgCosin += ceCurve._ledges[ iLE ]->_cosin;
7992             nbCosin++;
7993           }
7994         }
7995       }
7996       if ( nbCosin > 0 )
7997         avgCosin /= nbCosin;
7998
7999       // set _LayerEdge::_normal = avgNormal
8000       id2eos = convFace._subIdToEOS.begin();
8001       for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
8002       {
8003         _EdgesOnShape& eos = *(id2eos->second);
8004         if ( eos.ShapeType() != TopAbs_EDGE )
8005           for ( size_t i = 0; i < eos._edges.size(); ++i )
8006             eos._edges[ i ]->_cosin = avgCosin;
8007
8008         for ( size_t i = 0; i < eos._edges.size(); ++i )
8009         {
8010           eos._edges[ i ]->SetNormal( avgNormal );
8011           eos._edges[ i ]->Set( _LayerEdge::NORMAL_UPDATED );
8012         }
8013       }
8014     }
8015     else // if ( isSpherical )
8016     {
8017       // We suppose that centers of curvature at all points of the FACE
8018       // lie on some curve, let's call it "central curve". For all _LayerEdge's
8019       // having a common center of curvature we define the same new normal
8020       // as a sum of normals of _LayerEdge's on EDGEs among them.
8021
8022       // get all centers of curvature for each EDGE
8023
8024       helper.SetSubShape( convFace._face );
8025       _LayerEdge* vertexLEdges[2], **edgeLEdge, **edgeLEdgeEnd;
8026
8027       TopExp_Explorer edgeExp( convFace._face, TopAbs_EDGE );
8028       for ( int iE = 0; edgeExp.More(); edgeExp.Next(), ++iE )
8029       {
8030         const TopoDS_Edge& edge = TopoDS::Edge( edgeExp.Current() );
8031
8032         // set adjacent FACE
8033         centerCurves[ iE ].SetShapes( edge, convFace, data, helper );
8034
8035         // get _LayerEdge's of the EDGE
8036         TGeomID edgeID = meshDS->ShapeToIndex( edge );
8037         _EdgesOnShape* eos = data.GetShapeEdges( edgeID );
8038         if ( !eos || eos->_edges.empty() )
8039         {
8040           // no _LayerEdge's on EDGE, use _LayerEdge's on VERTEXes
8041           for ( int iV = 0; iV < 2; ++iV )
8042           {
8043             TopoDS_Vertex v = helper.IthVertex( iV, edge );
8044             TGeomID     vID = meshDS->ShapeToIndex( v );
8045             eos = data.GetShapeEdges( vID );
8046             vertexLEdges[ iV ] = eos->_edges[ 0 ];
8047           }
8048           edgeLEdge    = &vertexLEdges[0];
8049           edgeLEdgeEnd = edgeLEdge + 2;
8050
8051           centerCurves[ iE ]._adjFace.Nullify();
8052         }
8053         else
8054         {
8055           if ( ! eos->_toSmooth )
8056             data.SortOnEdge( edge, eos->_edges );
8057           edgeLEdge    = &eos->_edges[ 0 ];
8058           edgeLEdgeEnd = edgeLEdge + eos->_edges.size();
8059           vertexLEdges[0] = eos->_edges.front()->_2neibors->_edges[0];
8060           vertexLEdges[1] = eos->_edges.back() ->_2neibors->_edges[1];
8061
8062           if ( ! eos->_sWOL.IsNull() )
8063             centerCurves[ iE ]._adjFace.Nullify();
8064         }
8065
8066         // Get curvature centers
8067
8068         centersBox.Clear();
8069
8070         if ( edgeLEdge[0]->IsOnEdge() &&
8071              convFace.GetCenterOfCurvature( vertexLEdges[0], surfProp, helper, center ))
8072         { // 1st VERTEX
8073           centerCurves[ iE ].Append( center, vertexLEdges[0] );
8074           centersBox.Add( center );
8075         }
8076         for ( ; edgeLEdge < edgeLEdgeEnd; ++edgeLEdge )
8077           if ( convFace.GetCenterOfCurvature( *edgeLEdge, surfProp, helper, center ))
8078           { // EDGE or VERTEXes
8079             centerCurves[ iE ].Append( center, *edgeLEdge );
8080             centersBox.Add( center );
8081           }
8082         if ( edgeLEdge[-1]->IsOnEdge() &&
8083              convFace.GetCenterOfCurvature( vertexLEdges[1], surfProp, helper, center ))
8084         { // 2nd VERTEX
8085           centerCurves[ iE ].Append( center, vertexLEdges[1] );
8086           centersBox.Add( center );
8087         }
8088         centerCurves[ iE ]._isDegenerated =
8089           ( centersBox.IsVoid() || centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
8090
8091       } // loop on EDGES of convFace._face to set up data of centerCurves
8092
8093       // Compute new normals for _LayerEdge's on EDGEs
8094
8095       double avgCosin = 0;
8096       int     nbCosin = 0;
8097       gp_Vec inFaceDir;
8098       for ( size_t iE1 = 0; iE1 < centerCurves.size(); ++iE1 )
8099       {
8100         _CentralCurveOnEdge& ceCurve = centerCurves[ iE1 ];
8101         if ( ceCurve._isDegenerated )
8102           continue;
8103         const vector< gp_Pnt >& centers = ceCurve._curvaCenters;
8104         vector< gp_XYZ > &   newNormals = ceCurve._normals;
8105         for ( size_t iC1 = 0; iC1 < centers.size(); ++iC1 )
8106         {
8107           isOK = false;
8108           for ( size_t iE2 = 0; iE2 < centerCurves.size() && !isOK; ++iE2 )
8109           {
8110             if ( iE1 != iE2 )
8111               isOK = centerCurves[ iE2 ].FindNewNormal( centers[ iC1 ], newNormals[ iC1 ]);
8112           }
8113           if ( isOK && !ceCurve._adjFace.IsNull() )
8114           {
8115             // compute new _LayerEdge::_cosin
8116             const SMDS_MeshNode* node = ceCurve._ledges[ iC1 ]->_nodes[0];
8117             inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
8118             if ( isOK )
8119             {
8120               double angle = inFaceDir.Angle( newNormals[ iC1 ] ); // [0,PI]
8121               ceCurve._ledges[ iC1 ]->_cosin = Cos( angle );
8122               avgCosin += ceCurve._ledges[ iC1 ]->_cosin;
8123               nbCosin++;
8124             }
8125           }
8126         }
8127       }
8128       // set new normals to _LayerEdge's of NOT degenerated central curves
8129       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
8130       {
8131         if ( centerCurves[ iE ]._isDegenerated )
8132           continue;
8133         for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
8134         {
8135           centerCurves[ iE ]._ledges[ iLE ]->SetNormal( centerCurves[ iE ]._normals[ iLE ]);
8136           centerCurves[ iE ]._ledges[ iLE ]->Set( _LayerEdge::NORMAL_UPDATED );
8137         }
8138       }
8139       // set new normals to _LayerEdge's of     degenerated central curves
8140       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
8141       {
8142         if ( !centerCurves[ iE ]._isDegenerated ||
8143              centerCurves[ iE ]._ledges.size() < 3 )
8144           continue;
8145         // new normal is an average of new normals at VERTEXes that
8146         // was computed on non-degenerated _CentralCurveOnEdge's
8147         gp_XYZ newNorm = ( centerCurves[ iE ]._ledges.front()->_normal +
8148                            centerCurves[ iE ]._ledges.back ()->_normal );
8149         double sz = newNorm.Modulus();
8150         if ( sz < 1e-200 )
8151           continue;
8152         newNorm /= sz;
8153         double newCosin = ( 0.5 * centerCurves[ iE ]._ledges.front()->_cosin +
8154                             0.5 * centerCurves[ iE ]._ledges.back ()->_cosin );
8155         for ( size_t iLE = 1, nb = centerCurves[ iE ]._ledges.size() - 1; iLE < nb; ++iLE )
8156         {
8157           centerCurves[ iE ]._ledges[ iLE ]->SetNormal( newNorm );
8158           centerCurves[ iE ]._ledges[ iLE ]->_cosin   = newCosin;
8159           centerCurves[ iE ]._ledges[ iLE ]->Set( _LayerEdge::NORMAL_UPDATED );
8160         }
8161       }
8162
8163       // Find new normals for _LayerEdge's based on FACE
8164
8165       if ( nbCosin > 0 )
8166         avgCosin /= nbCosin;
8167       const TGeomID faceID = meshDS->ShapeToIndex( convFace._face );
8168       map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.find( faceID );
8169       if ( id2eos != convFace._subIdToEOS.end() )
8170       {
8171         int iE = 0;
8172         gp_XYZ newNorm;
8173         _EdgesOnShape& eos = * ( id2eos->second );
8174         for ( size_t i = 0; i < eos._edges.size(); ++i )
8175         {
8176           _LayerEdge* ledge = eos._edges[ i ];
8177           if ( !convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
8178             continue;
8179           for ( size_t i = 0; i < centerCurves.size(); ++i, ++iE )
8180           {
8181             iE = iE % centerCurves.size();
8182             if ( centerCurves[ iE ]._isDegenerated )
8183               continue;
8184             newNorm.SetCoord( 0,0,0 );
8185             if ( centerCurves[ iE ].FindNewNormal( center, newNorm ))
8186             {
8187               ledge->SetNormal( newNorm );
8188               ledge->_cosin  = avgCosin;
8189               ledge->Set( _LayerEdge::NORMAL_UPDATED );
8190               break;
8191             }
8192           }
8193         }
8194       }
8195
8196     } // not a quasi-spherical FACE
8197
8198     // Update _LayerEdge's data according to a new normal
8199
8200     dumpFunction(SMESH_Comment("updateNormalsOfConvexFaces")<<data._index
8201                  <<"_F"<<meshDS->ShapeToIndex( convFace._face ));
8202
8203     id2eos = convFace._subIdToEOS.begin();
8204     for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
8205     {
8206       _EdgesOnShape& eos = * ( id2eos->second );
8207       for ( size_t i = 0; i < eos._edges.size(); ++i )
8208       {
8209         _LayerEdge* & ledge = eos._edges[ i ];
8210         double len = ledge->_len;
8211         ledge->InvalidateStep( stepNb + 1, eos, /*restoreLength=*/true );
8212         ledge->SetCosin( ledge->_cosin );
8213         ledge->SetNewLength( len, eos, helper );
8214       }
8215       if ( eos.ShapeType() != TopAbs_FACE )
8216         for ( size_t i = 0; i < eos._edges.size(); ++i )
8217         {
8218           _LayerEdge* ledge = eos._edges[ i ];
8219           for ( size_t iN = 0; iN < ledge->_neibors.size(); ++iN )
8220           {
8221             _LayerEdge* neibor = ledge->_neibors[iN];
8222             if ( neibor->_nodes[0]->GetPosition()->GetDim() == 2 )
8223             {
8224               neibor->Set( _LayerEdge::NEAR_BOUNDARY );
8225               neibor->Set( _LayerEdge::MOVED );
8226               neibor->SetSmooLen( neibor->_len );
8227             }
8228           }
8229         }
8230     } // loop on sub-shapes of convFace._face
8231
8232     // Find FACEs adjacent to convFace._face that got necessity to smooth
8233     // as a result of normals modification
8234
8235     set< _EdgesOnShape* > adjFacesToSmooth;
8236     for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
8237     {
8238       if ( centerCurves[ iE ]._adjFace.IsNull() ||
8239            centerCurves[ iE ]._adjFaceToSmooth )
8240         continue;
8241       for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
8242       {
8243         if ( centerCurves[ iE ]._ledges[ iLE ]->_cosin > theMinSmoothCosin )
8244         {
8245           adjFacesToSmooth.insert( data.GetShapeEdges( centerCurves[ iE ]._adjFace ));
8246           break;
8247         }
8248       }
8249     }
8250     data.AddShapesToSmooth( adjFacesToSmooth );
8251
8252     dumpFunctionEnd();
8253
8254
8255   } // loop on data._convexFaces
8256
8257   return true;
8258 }
8259
8260 //================================================================================
8261 /*!
8262  * \brief Return max curvature of a FACE
8263  */
8264 //================================================================================
8265
8266 double _ConvexFace::GetMaxCurvature( _SolidData&         data,
8267                                      _EdgesOnShape&      eof,
8268                                      BRepLProp_SLProps&  surfProp,
8269                                      SMESH_MesherHelper& helper)
8270 {
8271   double maxCurvature = 0;
8272
8273   TopoDS_Face F = TopoDS::Face( eof._shape );
8274
8275   const int           nbTestPnt = 5;
8276   const double        oriFactor = ( F.Orientation() == TopAbs_REVERSED ? +1. : -1. );
8277   SMESH_subMeshIteratorPtr smIt = eof._subMesh->getDependsOnIterator(/*includeSelf=*/true);
8278   while ( smIt->more() )
8279   {
8280     SMESH_subMesh* sm = smIt->next();
8281     const TGeomID subID = sm->GetId();
8282
8283     // find _LayerEdge's of a sub-shape
8284     _EdgesOnShape* eos;
8285     if (( eos = data.GetShapeEdges( subID )))
8286       this->_subIdToEOS.insert( make_pair( subID, eos ));
8287     else
8288       continue;
8289
8290     // check concavity and curvature and limit data._stepSize
8291     const double minCurvature =
8292       1. / ( eos->_hyp.GetTotalThickness() * ( 1 + theThickToIntersection ));
8293     size_t iStep = Max( 1, eos->_edges.size() / nbTestPnt );
8294     for ( size_t i = 0; i < eos->_edges.size(); i += iStep )
8295     {
8296       gp_XY uv = helper.GetNodeUV( F, eos->_edges[ i ]->_nodes[0] );
8297       surfProp.SetParameters( uv.X(), uv.Y() );
8298       if ( surfProp.IsCurvatureDefined() )
8299       {
8300         double curvature = Max( surfProp.MaxCurvature() * oriFactor,
8301                                 surfProp.MinCurvature() * oriFactor );
8302         maxCurvature = Max( maxCurvature, curvature );
8303
8304         if ( curvature > minCurvature )
8305           this->_isTooCurved = true;
8306       }
8307     }
8308   } // loop on sub-shapes of the FACE
8309
8310   return maxCurvature;
8311 }
8312
8313 //================================================================================
8314 /*!
8315  * \brief Finds a center of curvature of a surface at a _LayerEdge
8316  */
8317 //================================================================================
8318
8319 bool _ConvexFace::GetCenterOfCurvature( _LayerEdge*         ledge,
8320                                         BRepLProp_SLProps&  surfProp,
8321                                         SMESH_MesherHelper& helper,
8322                                         gp_Pnt &            center ) const
8323 {
8324   gp_XY uv = helper.GetNodeUV( _face, ledge->_nodes[0] );
8325   surfProp.SetParameters( uv.X(), uv.Y() );
8326   if ( !surfProp.IsCurvatureDefined() )
8327     return false;
8328
8329   const double oriFactor = ( _face.Orientation() == TopAbs_REVERSED ? +1. : -1. );
8330   double surfCurvatureMax = surfProp.MaxCurvature() * oriFactor;
8331   double surfCurvatureMin = surfProp.MinCurvature() * oriFactor;
8332   if ( surfCurvatureMin > surfCurvatureMax )
8333     center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMin * oriFactor );
8334   else
8335     center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMax * oriFactor );
8336
8337   return true;
8338 }
8339
8340 //================================================================================
8341 /*!
8342  * \brief Check that prisms are not distorted
8343  */
8344 //================================================================================
8345
8346 bool _ConvexFace::CheckPrisms() const
8347 {
8348   double vol = 0;
8349   for ( size_t i = 0; i < _simplexTestEdges.size(); ++i )
8350   {
8351     const _LayerEdge* edge = _simplexTestEdges[i];
8352     SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
8353     for ( size_t j = 0; j < edge->_simplices.size(); ++j )
8354       if ( !edge->_simplices[j].IsForward( edge->_nodes[0], tgtXYZ, vol ))
8355       {
8356         debugMsg( "Bad simplex of _simplexTestEdges ("
8357                   << " "<< edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
8358                   << " "<< edge->_simplices[j]._nPrev->GetID()
8359                   << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
8360         return false;
8361       }
8362   }
8363   return true;
8364 }
8365
8366 //================================================================================
8367 /*!
8368  * \brief Try to compute a new normal by interpolating normals of _LayerEdge's
8369  *        stored in this _CentralCurveOnEdge.
8370  *  \param [in] center - curvature center of a point of another _CentralCurveOnEdge.
8371  *  \param [in,out] newNormal - current normal at this point, to be redefined
8372  *  \return bool - true if succeeded.
8373  */
8374 //================================================================================
8375
8376 bool _CentralCurveOnEdge::FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal )
8377 {
8378   if ( this->_isDegenerated )
8379     return false;
8380
8381   // find two centers the given one lies between
8382
8383   for ( size_t i = 0, nb = _curvaCenters.size()-1;  i < nb;  ++i )
8384   {
8385     double sl2 = 1.001 * _segLength2[ i ];
8386
8387     double d1 = center.SquareDistance( _curvaCenters[ i ]);
8388     if ( d1 > sl2 )
8389       continue;
8390     
8391     double d2 = center.SquareDistance( _curvaCenters[ i+1 ]);
8392     if ( d2 > sl2 || d2 + d1 < 1e-100 )
8393       continue;
8394
8395     d1 = Sqrt( d1 );
8396     d2 = Sqrt( d2 );
8397     double r = d1 / ( d1 + d2 );
8398     gp_XYZ norm = (( 1. - r ) * _ledges[ i   ]->_normal +
8399                    (      r ) * _ledges[ i+1 ]->_normal );
8400     norm.Normalize();
8401
8402     newNormal += norm;
8403     double sz = newNormal.Modulus();
8404     if ( sz < 1e-200 )
8405       break;
8406     newNormal /= sz;
8407     return true;
8408   }
8409   return false;
8410 }
8411
8412 //================================================================================
8413 /*!
8414  * \brief Set shape members
8415  */
8416 //================================================================================
8417
8418 void _CentralCurveOnEdge::SetShapes( const TopoDS_Edge&  edge,
8419                                      const _ConvexFace&  convFace,
8420                                      _SolidData&         data,
8421                                      SMESH_MesherHelper& helper)
8422 {
8423   _edge = edge;
8424
8425   PShapeIteratorPtr fIt = helper.GetAncestors( edge, *helper.GetMesh(), TopAbs_FACE );
8426   while ( const TopoDS_Shape* F = fIt->next())
8427     if ( !convFace._face.IsSame( *F ))
8428     {
8429       _adjFace = TopoDS::Face( *F );
8430       _adjFaceToSmooth = false;
8431       // _adjFace already in a smoothing queue ?
8432       if ( _EdgesOnShape* eos = data.GetShapeEdges( _adjFace ))
8433         _adjFaceToSmooth = eos->_toSmooth;
8434       break;
8435     }
8436 }
8437
8438 //================================================================================
8439 /*!
8440  * \brief Looks for intersection of it's last segment with faces
8441  *  \param distance - returns shortest distance from the last node to intersection
8442  */
8443 //================================================================================
8444
8445 bool _LayerEdge::FindIntersection( SMESH_ElementSearcher&   searcher,
8446                                    double &                 distance,
8447                                    const double&            epsilon,
8448                                    _EdgesOnShape&           eos,
8449                                    const SMDS_MeshElement** intFace)
8450 {
8451   vector< const SMDS_MeshElement* > suspectFaces;
8452   double segLen;
8453   gp_Ax1 lastSegment = LastSegment( segLen, eos );
8454   searcher.GetElementsNearLine( lastSegment, SMDSAbs_Face, suspectFaces );
8455
8456   bool segmentIntersected = false;
8457   distance = Precision::Infinite();
8458   int iFace = -1; // intersected face
8459   for ( size_t j = 0 ; j < suspectFaces.size() /*&& !segmentIntersected*/; ++j )
8460   {
8461     const SMDS_MeshElement* face = suspectFaces[j];
8462     if ( face->GetNodeIndex( _nodes.back() ) >= 0 ||
8463          face->GetNodeIndex( _nodes[0]     ) >= 0 )
8464       continue; // face sharing _LayerEdge node
8465     const int nbNodes = face->NbCornerNodes();
8466     bool intFound = false;
8467     double dist;
8468     SMDS_MeshElement::iterator nIt = face->begin_nodes();
8469     if ( nbNodes == 3 )
8470     {
8471       intFound = SegTriaInter( lastSegment, *nIt++, *nIt++, *nIt++, dist, epsilon );
8472     }
8473     else
8474     {
8475       const SMDS_MeshNode* tria[3];
8476       tria[0] = *nIt++;
8477       tria[1] = *nIt++;
8478       for ( int n2 = 2; n2 < nbNodes && !intFound; ++n2 )
8479       {
8480         tria[2] = *nIt++;
8481         intFound = SegTriaInter(lastSegment, tria[0], tria[1], tria[2], dist, epsilon );
8482         tria[1] = tria[2];
8483       }
8484     }
8485     if ( intFound )
8486     {
8487       if ( dist < segLen*(1.01) && dist > -(_len*_lenFactor-segLen) )
8488         segmentIntersected = true;
8489       if ( distance > dist )
8490         distance = dist, iFace = j;
8491     }
8492   }
8493   if ( intFace ) *intFace = ( iFace != -1 ) ? suspectFaces[iFace] : 0;
8494
8495   distance -= segLen;
8496
8497   if ( segmentIntersected )
8498   {
8499 #ifdef __myDEBUG
8500     SMDS_MeshElement::iterator nIt = suspectFaces[iFace]->begin_nodes();
8501     gp_XYZ intP( lastSegment.Location().XYZ() + lastSegment.Direction().XYZ() * ( distance+segLen ));
8502     cout << "nodes: tgt " << _nodes.back()->GetID() << " src " << _nodes[0]->GetID()
8503          << ", intersection with face ("
8504          << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
8505          << ") at point (" << intP.X() << ", " << intP.Y() << ", " << intP.Z()
8506          << ") distance = " << distance << endl;
8507 #endif
8508   }
8509
8510   return segmentIntersected;
8511 }
8512
8513 //================================================================================
8514 /*!
8515  * \brief Returns a point used to check orientation of _simplices
8516  */
8517 //================================================================================
8518
8519 gp_XYZ _LayerEdge::PrevCheckPos( _EdgesOnShape* eos ) const
8520 {
8521   size_t i = Is( NORMAL_UPDATED ) && IsOnFace() ? _pos.size()-2 : 0;
8522
8523   if ( !eos || eos->_sWOL.IsNull() )
8524     return _pos[ i ];
8525
8526   if ( eos->SWOLType() == TopAbs_EDGE )
8527   {
8528     return BRepAdaptor_Curve( TopoDS::Edge( eos->_sWOL )).Value( _pos[i].X() ).XYZ();
8529   }
8530   //else //  TopAbs_FACE
8531
8532   return BRepAdaptor_Surface( TopoDS::Face( eos->_sWOL )).Value(_pos[i].X(), _pos[i].Y() ).XYZ();
8533 }
8534
8535 //================================================================================
8536 /*!
8537  * \brief Returns size and direction of the last segment
8538  */
8539 //================================================================================
8540
8541 gp_Ax1 _LayerEdge::LastSegment(double& segLen, _EdgesOnShape& eos) const
8542 {
8543   // find two non-coincident positions
8544   gp_XYZ orig = _pos.back();
8545   gp_XYZ vec;
8546   int iPrev = _pos.size() - 2;
8547   //const double tol = ( _len > 0 ) ? 0.3*_len : 1e-100; // adjusted for IPAL52478 + PAL22576
8548   const double tol = ( _len > 0 ) ? ( 1e-6 * _len ) : 1e-100;
8549   while ( iPrev >= 0 )
8550   {
8551     vec = orig - _pos[iPrev];
8552     if ( vec.SquareModulus() > tol*tol )
8553       break;
8554     else
8555       iPrev--;
8556   }
8557
8558   // make gp_Ax1
8559   gp_Ax1 segDir;
8560   if ( iPrev < 0 )
8561   {
8562     segDir.SetLocation( SMESH_TNodeXYZ( _nodes[0] ));
8563     segDir.SetDirection( _normal );
8564     segLen = 0;
8565   }
8566   else
8567   {
8568     gp_Pnt pPrev = _pos[ iPrev ];
8569     if ( !eos._sWOL.IsNull() )
8570     {
8571       TopLoc_Location loc;
8572       if ( eos.SWOLType() == TopAbs_EDGE )
8573       {
8574         double f,l;
8575         Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eos._sWOL ), loc, f,l);
8576         pPrev = curve->Value( pPrev.X() ).Transformed( loc );
8577       }
8578       else
8579       {
8580         Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face( eos._sWOL ), loc );
8581         pPrev = surface->Value( pPrev.X(), pPrev.Y() ).Transformed( loc );
8582       }
8583       vec = SMESH_TNodeXYZ( _nodes.back() ) - pPrev.XYZ();
8584     }
8585     segDir.SetLocation( pPrev );
8586     segDir.SetDirection( vec );
8587     segLen = vec.Modulus();
8588   }
8589
8590   return segDir;
8591 }
8592
8593 //================================================================================
8594 /*!
8595  * \brief Return the last (or \a which) position of the target node on a FACE. 
8596  *  \param [in] F - the FACE this _LayerEdge is inflated along
8597  *  \param [in] which - index of position
8598  *  \return gp_XY - result UV
8599  */
8600 //================================================================================
8601
8602 gp_XY _LayerEdge::LastUV( const TopoDS_Face& F, _EdgesOnShape& eos, int which ) const
8603 {
8604   if ( F.IsSame( eos._sWOL )) // F is my FACE
8605     return gp_XY( _pos.back().X(), _pos.back().Y() );
8606
8607   if ( eos.SWOLType() != TopAbs_EDGE ) // wrong call
8608     return gp_XY( 1e100, 1e100 );
8609
8610   // _sWOL is EDGE of F; _pos.back().X() is the last U on the EDGE
8611   double f, l, u = _pos[ which < 0 ? _pos.size()-1 : which ].X();
8612   Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( TopoDS::Edge(eos._sWOL), F, f,l);
8613   if ( !C2d.IsNull() && f <= u && u <= l )
8614     return C2d->Value( u ).XY();
8615
8616   return gp_XY( 1e100, 1e100 );
8617 }
8618
8619 //================================================================================
8620 /*!
8621  * \brief Test intersection of the last segment with a given triangle
8622  *   using Moller-Trumbore algorithm
8623  * Intersection is detected if distance to intersection is less than _LayerEdge._len
8624  */
8625 //================================================================================
8626
8627 bool _LayerEdge::SegTriaInter( const gp_Ax1& lastSegment,
8628                                const gp_XYZ& vert0,
8629                                const gp_XYZ& vert1,
8630                                const gp_XYZ& vert2,
8631                                double&       t,
8632                                const double& EPSILON) const
8633 {
8634   const gp_Pnt& orig = lastSegment.Location();
8635   const gp_Dir& dir  = lastSegment.Direction();
8636
8637   /* calculate distance from vert0 to ray origin */
8638   //gp_XYZ tvec = orig.XYZ() - vert0;
8639
8640   //if ( tvec * dir > EPSILON )
8641     // intersected face is at back side of the temporary face this _LayerEdge belongs to
8642     //return false;
8643
8644   gp_XYZ edge1 = vert1 - vert0;
8645   gp_XYZ edge2 = vert2 - vert0;
8646
8647   /* begin calculating determinant - also used to calculate U parameter */
8648   gp_XYZ pvec = dir.XYZ() ^ edge2;
8649
8650   /* if determinant is near zero, ray lies in plane of triangle */
8651   double det = edge1 * pvec;
8652
8653   const double ANGL_EPSILON = 1e-12;
8654   if ( det > -ANGL_EPSILON && det < ANGL_EPSILON )
8655     return false;
8656
8657   /* calculate distance from vert0 to ray origin */
8658   gp_XYZ tvec = orig.XYZ() - vert0;
8659
8660   /* calculate U parameter and test bounds */
8661   double u = ( tvec * pvec ) / det;
8662   //if (u < 0.0 || u > 1.0)
8663   if ( u < -EPSILON || u > 1.0 + EPSILON )
8664     return false;
8665
8666   /* prepare to test V parameter */
8667   gp_XYZ qvec = tvec ^ edge1;
8668
8669   /* calculate V parameter and test bounds */
8670   double v = (dir.XYZ() * qvec) / det;
8671   //if ( v < 0.0 || u + v > 1.0 )
8672   if ( v < -EPSILON || u + v > 1.0 + EPSILON )
8673     return false;
8674
8675   /* calculate t, ray intersects triangle */
8676   t = (edge2 * qvec) / det;
8677
8678   //return true;
8679   return t > 0.;
8680 }
8681
8682 //================================================================================
8683 /*!
8684  * \brief _LayerEdge, located at a concave VERTEX of a FACE, moves target nodes of
8685  *        neighbor _LayerEdge's by it's own inflation vector.
8686  *  \param [in] eov - EOS of the VERTEX
8687  *  \param [in] eos - EOS of the FACE
8688  *  \param [in] step - inflation step
8689  *  \param [in,out] badSmooEdges - tangled _LayerEdge's
8690  */
8691 //================================================================================
8692
8693 void _LayerEdge::MoveNearConcaVer( const _EdgesOnShape*    eov,
8694                                    const _EdgesOnShape*    eos,
8695                                    const int               step,
8696                                    vector< _LayerEdge* > & badSmooEdges )
8697 {
8698   // check if any of _neibors is in badSmooEdges
8699   if ( std::find_first_of( _neibors.begin(), _neibors.end(),
8700                            badSmooEdges.begin(), badSmooEdges.end() ) == _neibors.end() )
8701     return;
8702
8703   // get all edges to move
8704
8705   set< _LayerEdge* > edges;
8706
8707   // find a distance between _LayerEdge on VERTEX and its neighbors
8708   gp_XYZ  curPosV = SMESH_TNodeXYZ( _nodes.back() );
8709   double dist2 = 0;
8710   for ( size_t i = 0; i < _neibors.size(); ++i )
8711   {
8712     _LayerEdge* nEdge = _neibors[i];
8713     if ( nEdge->_nodes[0]->getshapeId() == eos->_shapeID )
8714     {
8715       edges.insert( nEdge );
8716       dist2 = Max( dist2, ( curPosV - nEdge->_pos.back() ).SquareModulus() );
8717     }
8718   }
8719   // add _LayerEdge's close to curPosV
8720   size_t nbE;
8721   do {
8722     nbE = edges.size();
8723     for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
8724     {
8725       _LayerEdge* edgeF = *e;
8726       for ( size_t i = 0; i < edgeF->_neibors.size(); ++i )
8727       {
8728         _LayerEdge* nEdge = edgeF->_neibors[i];
8729         if ( nEdge->_nodes[0]->getshapeId() == eos->_shapeID &&
8730              dist2 > ( curPosV - nEdge->_pos.back() ).SquareModulus() )
8731           edges.insert( nEdge );
8732       }
8733     }
8734   }
8735   while ( nbE < edges.size() );
8736
8737   // move the target node of the got edges
8738
8739   gp_XYZ prevPosV = PrevPos();
8740   if ( eov->SWOLType() == TopAbs_EDGE )
8741   {
8742     BRepAdaptor_Curve curve ( TopoDS::Edge( eov->_sWOL ));
8743     prevPosV = curve.Value( prevPosV.X() ).XYZ();
8744   }
8745   else if ( eov->SWOLType() == TopAbs_FACE )
8746   {
8747     BRepAdaptor_Surface surface( TopoDS::Face( eov->_sWOL ));
8748     prevPosV = surface.Value( prevPosV.X(), prevPosV.Y() ).XYZ();
8749   }
8750
8751   SMDS_FacePositionPtr fPos;
8752   //double r = 1. - Min( 0.9, step / 10. );
8753   for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
8754   {
8755     _LayerEdge*       edgeF = *e;
8756     const gp_XYZ     prevVF = edgeF->PrevPos() - prevPosV;
8757     const gp_XYZ    newPosF = curPosV + prevVF;
8758     SMDS_MeshNode* tgtNodeF = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
8759     tgtNodeF->setXYZ( newPosF.X(), newPosF.Y(), newPosF.Z() );
8760     edgeF->_pos.back() = newPosF;
8761     dumpMoveComm( tgtNodeF, "MoveNearConcaVer" ); // debug
8762
8763     // set _curvature to make edgeF updated by putOnOffsetSurface()
8764     if ( !edgeF->_curvature )
8765       if (( fPos = edgeF->_nodes[0]->GetPosition() ))
8766       {
8767         edgeF->_curvature = _Factory::NewCurvature();
8768         edgeF->_curvature->_r = 0;
8769         edgeF->_curvature->_k = 0;
8770         edgeF->_curvature->_h2lenRatio = 0;
8771         edgeF->_curvature->_uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
8772       }
8773   }
8774   // gp_XYZ inflationVec( SMESH_TNodeXYZ( _nodes.back() ) -
8775   //                      SMESH_TNodeXYZ( _nodes[0]    ));
8776   // for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
8777   // {
8778   //   _LayerEdge*      edgeF = *e;
8779   //   gp_XYZ          newPos = SMESH_TNodeXYZ( edgeF->_nodes[0] ) + inflationVec;
8780   //   SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
8781   //   tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8782   //   edgeF->_pos.back() = newPosF;
8783   //   dumpMoveComm( tgtNode, "MoveNearConcaVer" ); // debug
8784   // }
8785
8786   // smooth _LayerEdge's around moved nodes
8787   //size_t nbBadBefore = badSmooEdges.size();
8788   for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
8789   {
8790     _LayerEdge* edgeF = *e;
8791     for ( size_t j = 0; j < edgeF->_neibors.size(); ++j )
8792       if ( edgeF->_neibors[j]->_nodes[0]->getshapeId() == eos->_shapeID )
8793         //&& !edges.count( edgeF->_neibors[j] ))
8794       {
8795         _LayerEdge* edgeFN = edgeF->_neibors[j];
8796         edgeFN->Unset( SMOOTHED );
8797         int nbBad = edgeFN->Smooth( step, /*isConcaFace=*/true, /*findBest=*/true );
8798         // if ( nbBad > 0 )
8799         // {
8800         //   gp_XYZ         newPos = SMESH_TNodeXYZ( edgeFN->_nodes[0] ) + inflationVec;
8801         //   const gp_XYZ& prevPos = edgeFN->_pos[ edgeFN->_pos.size()-2 ];
8802         //   int        nbBadAfter = edgeFN->_simplices.size();
8803         //   double vol;
8804         //   for ( size_t iS = 0; iS < edgeFN->_simplices.size(); ++iS )
8805         //   {
8806         //     nbBadAfter -= edgeFN->_simplices[iS].IsForward( &prevPos, &newPos, vol );
8807         //   }
8808         //   if ( nbBadAfter <= nbBad )
8809         //   {
8810         //     SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeFN->_nodes.back() );
8811         //     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8812         //     edgeF->_pos.back() = newPosF;
8813         //     dumpMoveComm( tgtNode, "MoveNearConcaVer 2" ); // debug
8814         //     nbBad = nbBadAfter;
8815         //   }
8816         // }
8817         if ( nbBad > 0 )
8818           badSmooEdges.push_back( edgeFN );
8819       }
8820   }
8821     // move a bit not smoothed around moved nodes
8822   //   for ( size_t i = nbBadBefore; i < badSmooEdges.size(); ++i )
8823   //   {
8824   //   _LayerEdge*      edgeF = badSmooEdges[i];
8825   //   SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
8826   //   gp_XYZ         newPos1 = SMESH_TNodeXYZ( edgeF->_nodes[0] ) + inflationVec;
8827   //   gp_XYZ         newPos2 = 0.5 * ( newPos1 + SMESH_TNodeXYZ( tgtNode ));
8828   //   tgtNode->setXYZ( newPos2.X(), newPos2.Y(), newPos2.Z() );
8829   //   edgeF->_pos.back() = newPosF;
8830   //   dumpMoveComm( tgtNode, "MoveNearConcaVer 2" ); // debug
8831   // }
8832 }
8833
8834 //================================================================================
8835 /*!
8836  * \brief Perform smooth of _LayerEdge's based on EDGE's
8837  *  \retval bool - true if node has been moved
8838  */
8839 //================================================================================
8840
8841 bool _LayerEdge::SmoothOnEdge(Handle(ShapeAnalysis_Surface)& surface,
8842                               const TopoDS_Face&             F,
8843                               SMESH_MesherHelper&            helper)
8844 {
8845   ASSERT( IsOnEdge() );
8846
8847   SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
8848   SMESH_TNodeXYZ oldPos( tgtNode );
8849   double dist01, distNewOld;
8850   
8851   SMESH_TNodeXYZ p0( _2neibors->tgtNode(0));
8852   SMESH_TNodeXYZ p1( _2neibors->tgtNode(1));
8853   dist01 = p0.Distance( _2neibors->tgtNode(1) );
8854
8855   gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
8856   double lenDelta = 0;
8857   if ( _curvature )
8858   {
8859     //lenDelta = _curvature->lenDelta( _len );
8860     lenDelta = _curvature->lenDeltaByDist( dist01 );
8861     newPos.ChangeCoord() += _normal * lenDelta;
8862   }
8863
8864   distNewOld = newPos.Distance( oldPos );
8865
8866   if ( F.IsNull() )
8867   {
8868     if ( _2neibors->_plnNorm )
8869     {
8870       // put newPos on the plane defined by source node and _plnNorm
8871       gp_XYZ new2src = SMESH_TNodeXYZ( _nodes[0] ) - newPos.XYZ();
8872       double new2srcProj = (*_2neibors->_plnNorm) * new2src;
8873       newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
8874     }
8875     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8876     _pos.back() = newPos.XYZ();
8877   }
8878   else
8879   {
8880     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8881     gp_XY uv( Precision::Infinite(), 0 );
8882     helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
8883     _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
8884
8885     newPos = surface->Value( uv );
8886     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8887   }
8888
8889   // commented for IPAL0052478
8890   // if ( _curvature && lenDelta < 0 )
8891   // {
8892   //   gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
8893   //   _len -= prevPos.Distance( oldPos );
8894   //   _len += prevPos.Distance( newPos );
8895   // }
8896   bool moved = distNewOld > dist01/50;
8897   //if ( moved )
8898   dumpMove( tgtNode ); // debug
8899
8900   return moved;
8901 }
8902
8903 //================================================================================
8904 /*!
8905  * \brief Perform 3D smooth of nodes inflated from FACE. No check of validity
8906  */
8907 //================================================================================
8908
8909 void _LayerEdge::SmoothWoCheck()
8910 {
8911   if ( Is( DIFFICULT ))
8912     return;
8913
8914   bool moved = Is( SMOOTHED );
8915   for ( size_t i = 0; i < _neibors.size()  &&  !moved; ++i )
8916     moved = _neibors[i]->Is( SMOOTHED );
8917   if ( !moved )
8918     return;
8919
8920   gp_XYZ newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
8921
8922   SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
8923   n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
8924   _pos.back() = newPos;
8925
8926   dumpMoveComm( n, SMESH_Comment("No check - ") << _funNames[ smooFunID() ]);
8927 }
8928
8929 //================================================================================
8930 /*!
8931  * \brief Checks validity of _neibors on EDGEs and VERTEXes
8932  */
8933 //================================================================================
8934
8935 int _LayerEdge::CheckNeiborsOnBoundary( vector< _LayerEdge* >* badNeibors, bool * needSmooth )
8936 {
8937   if ( ! Is( NEAR_BOUNDARY ))
8938     return 0;
8939
8940   int nbBad = 0;
8941   double vol;
8942   for ( size_t iN = 0; iN < _neibors.size(); ++iN )
8943   {
8944     _LayerEdge* eN = _neibors[iN];
8945     if ( eN->_nodes[0]->getshapeId() == _nodes[0]->getshapeId() )
8946       continue;
8947     if ( needSmooth )
8948       *needSmooth |= ( eN->Is( _LayerEdge::BLOCKED ) ||
8949                        eN->Is( _LayerEdge::NORMAL_UPDATED ) ||
8950                        eN->_pos.size() != _pos.size() );
8951
8952     SMESH_TNodeXYZ curPosN ( eN->_nodes.back() );
8953     SMESH_TNodeXYZ prevPosN( eN->_nodes[0] );
8954     for ( size_t i = 0; i < eN->_simplices.size(); ++i )
8955       if ( eN->_nodes.size() > 1 &&
8956            eN->_simplices[i].Includes( _nodes.back() ) &&
8957            !eN->_simplices[i].IsForward( &prevPosN, &curPosN, vol ))
8958       {
8959         ++nbBad;
8960         if ( badNeibors )
8961         {
8962           badNeibors->push_back( eN );
8963           debugMsg("Bad boundary simplex ( "
8964                    << " "<< eN->_nodes[0]->GetID()
8965                    << " "<< eN->_nodes.back()->GetID()
8966                    << " "<< eN->_simplices[i]._nPrev->GetID()
8967                    << " "<< eN->_simplices[i]._nNext->GetID() << " )" );
8968         }
8969         else
8970         {
8971           break;
8972         }
8973       }
8974   }
8975   return nbBad;
8976 }
8977
8978 //================================================================================
8979 /*!
8980  * \brief Perform 'smart' 3D smooth of nodes inflated from FACE
8981  *  \retval int - nb of bad simplices around this _LayerEdge
8982  */
8983 //================================================================================
8984
8985 int _LayerEdge::Smooth(const int step, bool findBest, vector< _LayerEdge* >& toSmooth )
8986 {
8987   if ( !Is( MOVED ) || Is( SMOOTHED ) || Is( BLOCKED ))
8988     return 0; // shape of simplices not changed
8989   if ( _simplices.size() < 2 )
8990     return 0; // _LayerEdge inflated along EDGE or FACE
8991
8992   if ( Is( DIFFICULT )) // || Is( ON_CONCAVE_FACE )
8993     findBest = true;
8994
8995   const gp_XYZ& curPos  = _pos.back();
8996   const gp_XYZ& prevPos = _pos[0]; //PrevPos();
8997
8998   // quality metrics (orientation) of tetras around _tgtNode
8999   int nbOkBefore = 0;
9000   double vol, minVolBefore = 1e100;
9001   for ( size_t i = 0; i < _simplices.size(); ++i )
9002   {
9003     nbOkBefore += _simplices[i].IsForward( &prevPos, &curPos, vol );
9004     minVolBefore = Min( minVolBefore, vol );
9005   }
9006   int nbBad = _simplices.size() - nbOkBefore;
9007
9008   bool bndNeedSmooth = false;
9009   if ( nbBad == 0 )
9010     nbBad = CheckNeiborsOnBoundary( 0, & bndNeedSmooth );
9011   if ( nbBad > 0 )
9012     Set( DISTORTED );
9013
9014   // evaluate min angle
9015   if ( nbBad == 0 && !findBest && !bndNeedSmooth )
9016   {
9017     size_t nbGoodAngles = _simplices.size();
9018     double angle;
9019     for ( size_t i = 0; i < _simplices.size(); ++i )
9020     {
9021       if ( !_simplices[i].IsMinAngleOK( curPos, angle ) && angle > _minAngle )
9022         --nbGoodAngles;
9023     }
9024     if ( nbGoodAngles == _simplices.size() )
9025     {
9026       Unset( MOVED );
9027       return 0;
9028     }
9029   }
9030   if ( Is( ON_CONCAVE_FACE ))
9031     findBest = true;
9032
9033   if ( step % 2 == 0 )
9034     findBest = false;
9035
9036   if ( Is( ON_CONCAVE_FACE ) && !findBest ) // alternate FUN_CENTROIDAL and FUN_LAPLACIAN
9037   {
9038     if ( _smooFunction == _funs[ FUN_LAPLACIAN ] )
9039       _smooFunction = _funs[ FUN_CENTROIDAL ];
9040     else
9041       _smooFunction = _funs[ FUN_LAPLACIAN ];
9042   }
9043
9044   // compute new position for the last _pos using different _funs
9045   gp_XYZ newPos;
9046   bool moved = false;
9047   for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
9048   {
9049     if ( iFun < 0 )
9050       newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
9051     else if ( _funs[ iFun ] == _smooFunction )
9052       continue; // _smooFunction again
9053     else if ( step > 1 )
9054       newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
9055     else
9056       break; // let "easy" functions improve elements around distorted ones
9057
9058     if ( _curvature )
9059     {
9060       double delta  = _curvature->lenDelta( _len );
9061       if ( delta > 0 )
9062         newPos += _normal * delta;
9063       else
9064       {
9065         double segLen = _normal * ( newPos - prevPos );
9066         if ( segLen + delta > 0 )
9067           newPos += _normal * delta;
9068       }
9069       // double segLenChange = _normal * ( curPos - newPos );
9070       // newPos += 0.5 * _normal * segLenChange;
9071     }
9072
9073     int nbOkAfter = 0;
9074     double minVolAfter = 1e100;
9075     for ( size_t i = 0; i < _simplices.size(); ++i )
9076     {
9077       nbOkAfter += _simplices[i].IsForward( &prevPos, &newPos, vol );
9078       minVolAfter = Min( minVolAfter, vol );
9079     }
9080     // get worse?
9081     if ( nbOkAfter < nbOkBefore )
9082       continue;
9083
9084     if (( findBest ) &&
9085         ( nbOkAfter == nbOkBefore ) &&
9086         ( minVolAfter <= minVolBefore ))
9087       continue;
9088
9089     nbBad        = _simplices.size() - nbOkAfter;
9090     minVolBefore = minVolAfter;
9091     nbOkBefore   = nbOkAfter;
9092     moved        = true;
9093
9094     SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
9095     n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
9096     _pos.back() = newPos;
9097
9098     dumpMoveComm( n, SMESH_Comment( _funNames[ iFun < 0 ? smooFunID() : iFun ] )
9099                   << (nbBad ? " --BAD" : ""));
9100
9101     if ( iFun > -1 )
9102     {
9103       continue; // look for a better function
9104     }
9105
9106     if ( !findBest )
9107       break;
9108
9109   } // loop on smoothing functions
9110
9111   if ( moved ) // notify _neibors
9112   {
9113     Set( SMOOTHED );
9114     for ( size_t i = 0; i < _neibors.size(); ++i )
9115       if ( !_neibors[i]->Is( MOVED ))
9116       {
9117         _neibors[i]->Set( MOVED );
9118         toSmooth.push_back( _neibors[i] );
9119       }
9120   }
9121
9122   return nbBad;
9123 }
9124
9125 //================================================================================
9126 /*!
9127  * \brief Perform 'smart' 3D smooth of nodes inflated from FACE
9128  *  \retval int - nb of bad simplices around this _LayerEdge
9129  */
9130 //================================================================================
9131
9132 int _LayerEdge::Smooth(const int step, const bool isConcaveFace, bool findBest )
9133 {
9134   if ( !_smooFunction )
9135     return 0; // _LayerEdge inflated along EDGE or FACE
9136   if ( Is( BLOCKED ))
9137     return 0; // not inflated
9138
9139   const gp_XYZ& curPos  = _pos.back();
9140   const gp_XYZ& prevPos = _pos[0]; //PrevCheckPos();
9141
9142   // quality metrics (orientation) of tetras around _tgtNode
9143   int nbOkBefore = 0;
9144   double vol, minVolBefore = 1e100;
9145   for ( size_t i = 0; i < _simplices.size(); ++i )
9146   {
9147     nbOkBefore += _simplices[i].IsForward( &prevPos, &curPos, vol );
9148     minVolBefore = Min( minVolBefore, vol );
9149   }
9150   int nbBad = _simplices.size() - nbOkBefore;
9151
9152   if ( isConcaveFace ) // alternate FUN_CENTROIDAL and FUN_LAPLACIAN
9153   {
9154     if      ( _smooFunction == _funs[ FUN_CENTROIDAL ] && step % 2 )
9155       _smooFunction = _funs[ FUN_LAPLACIAN ];
9156     else if ( _smooFunction == _funs[ FUN_LAPLACIAN ] && !( step % 2 ))
9157       _smooFunction = _funs[ FUN_CENTROIDAL ];
9158   }
9159
9160   // compute new position for the last _pos using different _funs
9161   gp_XYZ newPos;
9162   for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
9163   {
9164     if ( iFun < 0 )
9165       newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
9166     else if ( _funs[ iFun ] == _smooFunction )
9167       continue; // _smooFunction again
9168     else if ( step > 1 )
9169       newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
9170     else
9171       break; // let "easy" functions improve elements around distorted ones
9172
9173     if ( _curvature )
9174     {
9175       double delta  = _curvature->lenDelta( _len );
9176       if ( delta > 0 )
9177         newPos += _normal * delta;
9178       else
9179       {
9180         double segLen = _normal * ( newPos - prevPos );
9181         if ( segLen + delta > 0 )
9182           newPos += _normal * delta;
9183       }
9184       // double segLenChange = _normal * ( curPos - newPos );
9185       // newPos += 0.5 * _normal * segLenChange;
9186     }
9187
9188     int nbOkAfter = 0;
9189     double minVolAfter = 1e100;
9190     for ( size_t i = 0; i < _simplices.size(); ++i )
9191     {
9192       nbOkAfter += _simplices[i].IsForward( &prevPos, &newPos, vol );
9193       minVolAfter = Min( minVolAfter, vol );
9194     }
9195     // get worse?
9196     if ( nbOkAfter < nbOkBefore )
9197       continue;
9198     if (( isConcaveFace || findBest ) &&
9199         ( nbOkAfter == nbOkBefore ) &&
9200         ( minVolAfter <= minVolBefore )
9201         )
9202       continue;
9203
9204     nbBad        = _simplices.size() - nbOkAfter;
9205     minVolBefore = minVolAfter;
9206     nbOkBefore   = nbOkAfter;
9207
9208     SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
9209     n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
9210     _pos.back() = newPos;
9211
9212     dumpMoveComm( n, SMESH_Comment( _funNames[ iFun < 0 ? smooFunID() : iFun ] )
9213                   << ( nbBad ? "--BAD" : ""));
9214
9215     // commented for IPAL0052478
9216     // _len -= prevPos.Distance(SMESH_TNodeXYZ( n ));
9217     // _len += prevPos.Distance(newPos);
9218
9219     if ( iFun > -1 ) // findBest || the chosen _fun makes worse
9220     {
9221       //_smooFunction = _funs[ iFun ];
9222       // cout << "# " << _funNames[ iFun ] << "\t N:" << _nodes.back()->GetID()
9223       // << "\t nbBad: " << _simplices.size() - nbOkAfter
9224       // << " minVol: " << minVolAfter
9225       // << " " << newPos.X() << " " << newPos.Y() << " " << newPos.Z()
9226       // << endl;
9227       continue; // look for a better function
9228     }
9229
9230     if ( !findBest )
9231       break;
9232
9233   } // loop on smoothing functions
9234
9235   return nbBad;
9236 }
9237
9238 //================================================================================
9239 /*!
9240  * \brief Chooses a smoothing technique giving a position most close to an initial one.
9241  *        For a correct result, _simplices must contain nodes lying on geometry.
9242  */
9243 //================================================================================
9244
9245 void _LayerEdge::ChooseSmooFunction( const set< TGeomID >& concaveVertices,
9246                                      const TNode2Edge&     /*n2eMap*/)
9247 {
9248   if ( _smooFunction ) return;
9249
9250   // use smoothNefPolygon() near concaveVertices
9251   if ( !concaveVertices.empty() )
9252   {
9253     _smooFunction = _funs[ FUN_CENTROIDAL ];
9254
9255     Set( ON_CONCAVE_FACE );
9256
9257     for ( size_t i = 0; i < _simplices.size(); ++i )
9258     {
9259       if ( concaveVertices.count( _simplices[i]._nPrev->getshapeId() ))
9260       {
9261         _smooFunction = _funs[ FUN_NEFPOLY ];
9262
9263         // set FUN_CENTROIDAL to neighbor edges
9264         for ( i = 0; i < _neibors.size(); ++i )
9265         {
9266           if ( _neibors[i]->_nodes[0]->GetPosition()->GetDim() == 2 )
9267           {
9268             _neibors[i]->_smooFunction = _funs[ FUN_CENTROIDAL ];
9269           }
9270         }
9271         return;
9272       }
9273     }
9274
9275     // // this choice is done only if ( !concaveVertices.empty() ) for Grids/smesh/bugs_19/X1
9276     // // where the nodes are smoothed too far along a sphere thus creating
9277     // // inverted _simplices
9278     // double dist[theNbSmooFuns];
9279     // //double coef[theNbSmooFuns] = { 1., 1.2, 1.4, 1.4 };
9280     // double coef[theNbSmooFuns] = { 1., 1., 1., 1. };
9281
9282     // double minDist = Precision::Infinite();
9283     // gp_Pnt p = SMESH_TNodeXYZ( _nodes[0] );
9284     // for ( int i = 0; i < FUN_NEFPOLY; ++i )
9285     // {
9286     //   gp_Pnt newP = (this->*_funs[i])();
9287     //   dist[i] = p.SquareDistance( newP );
9288     //   if ( dist[i]*coef[i] < minDist )
9289     //   {
9290     //     _smooFunction = _funs[i];
9291     //     minDist = dist[i]*coef[i];
9292     //   }
9293     // }
9294   }
9295   else
9296   {
9297     _smooFunction = _funs[ FUN_LAPLACIAN ];
9298   }
9299   // int minDim = 3;
9300   // for ( size_t i = 0; i < _simplices.size(); ++i )
9301   //   minDim = Min( minDim, _simplices[i]._nPrev->GetPosition()->GetDim() );
9302   // if ( minDim == 0 )
9303   //   _smooFunction = _funs[ FUN_CENTROIDAL ];
9304   // else if ( minDim == 1 )
9305   //   _smooFunction = _funs[ FUN_CENTROIDAL ];
9306
9307
9308   // int iMin;
9309   // for ( int i = 0; i < FUN_NB; ++i )
9310   // {
9311   //   //cout << dist[i] << " ";
9312   //   if ( _smooFunction == _funs[i] ) {
9313   //     iMin = i;
9314   //     //debugMsg( fNames[i] );
9315   //     break;
9316   //   }
9317   // }
9318   // cout << _funNames[ iMin ] << "\t N:" << _nodes.back()->GetID() << endl;
9319 }
9320
9321 //================================================================================
9322 /*!
9323  * \brief Returns a name of _SmooFunction
9324  */
9325 //================================================================================
9326
9327 int _LayerEdge::smooFunID( _LayerEdge::PSmooFun fun) const
9328 {
9329   if ( !fun )
9330     fun = _smooFunction;
9331   for ( int i = 0; i < theNbSmooFuns; ++i )
9332     if ( fun == _funs[i] )
9333       return i;
9334
9335   return theNbSmooFuns;
9336 }
9337
9338 //================================================================================
9339 /*!
9340  * \brief Computes a new node position using Laplacian smoothing
9341  */
9342 //================================================================================
9343
9344 gp_XYZ _LayerEdge::smoothLaplacian()
9345 {
9346   gp_XYZ newPos (0,0,0);
9347   for ( size_t i = 0; i < _simplices.size(); ++i )
9348     newPos += SMESH_TNodeXYZ( _simplices[i]._nPrev );
9349   newPos /= _simplices.size();
9350
9351   return newPos;
9352 }
9353
9354 //================================================================================
9355 /*!
9356  * \brief Computes a new node position using angular-based smoothing
9357  */
9358 //================================================================================
9359
9360 gp_XYZ _LayerEdge::smoothAngular()
9361 {
9362   vector< gp_Vec > edgeDir;  edgeDir. reserve( _simplices.size() + 1 );
9363   vector< double > edgeSize; edgeSize.reserve( _simplices.size()     );
9364   vector< gp_XYZ > points;   points.  reserve( _simplices.size() + 1 );
9365
9366   gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
9367   gp_XYZ pN( 0,0,0 );
9368   for ( size_t i = 0; i < _simplices.size(); ++i )
9369   {
9370     gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
9371     edgeDir.push_back( p - pPrev );
9372     edgeSize.push_back( edgeDir.back().Magnitude() );
9373     if ( edgeSize.back() < numeric_limits<double>::min() )
9374     {
9375       edgeDir.pop_back();
9376       edgeSize.pop_back();
9377     }
9378     else
9379     {
9380       edgeDir.back() /= edgeSize.back();
9381       points.push_back( p );
9382       pN += p;
9383     }
9384     pPrev = p;
9385   }
9386   edgeDir.push_back ( edgeDir[0] );
9387   edgeSize.push_back( edgeSize[0] );
9388   pN /= points.size();
9389
9390   gp_XYZ newPos(0,0,0);
9391   double sumSize = 0;
9392   for ( size_t i = 0; i < points.size(); ++i )
9393   {
9394     gp_Vec toN    = pN - points[i];
9395     double toNLen = toN.Magnitude();
9396     if ( toNLen < numeric_limits<double>::min() )
9397     {
9398       newPos += pN;
9399       continue;
9400     }
9401     gp_Vec bisec    = edgeDir[i] + edgeDir[i+1];
9402     double bisecLen = bisec.SquareMagnitude();
9403     if ( bisecLen < numeric_limits<double>::min() )
9404     {
9405       gp_Vec norm = edgeDir[i] ^ toN;
9406       bisec = norm ^ edgeDir[i];
9407       bisecLen = bisec.SquareMagnitude();
9408     }
9409     bisecLen = Sqrt( bisecLen );
9410     bisec /= bisecLen;
9411
9412 #if 1
9413     gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * bisecLen;
9414     sumSize += bisecLen;
9415 #else
9416     gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * ( edgeSize[i] + edgeSize[i+1] );
9417     sumSize += ( edgeSize[i] + edgeSize[i+1] );
9418 #endif
9419     newPos += pNew;
9420   }
9421   newPos /= sumSize;
9422
9423   // project newPos to an average plane
9424
9425   gp_XYZ norm(0,0,0); // plane normal
9426   points.push_back( points[0] );
9427   for ( size_t i = 1; i < points.size(); ++i )
9428   {
9429     gp_XYZ vec1 = points[ i-1 ] - pN;
9430     gp_XYZ vec2 = points[ i   ] - pN;
9431     gp_XYZ cross = vec1 ^ vec2;
9432     try {
9433       cross.Normalize();
9434       if ( cross * norm < numeric_limits<double>::min() )
9435         norm += cross.Reversed();
9436       else
9437         norm += cross;
9438     }
9439     catch (Standard_Failure&) { // if |cross| == 0.
9440     }
9441   }
9442   gp_XYZ vec = newPos - pN;
9443   double r   = ( norm * vec ) / norm.SquareModulus();  // param [0,1] on norm
9444   newPos     = newPos - r * norm;
9445
9446   return newPos;
9447 }
9448
9449 //================================================================================
9450 /*!
9451  * \brief Computes a new node position using weighted node positions
9452  */
9453 //================================================================================
9454
9455 gp_XYZ _LayerEdge::smoothLengthWeighted()
9456 {
9457   vector< double > edgeSize; edgeSize.reserve( _simplices.size() + 1);
9458   vector< gp_XYZ > points;   points.  reserve( _simplices.size() );
9459
9460   gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
9461   for ( size_t i = 0; i < _simplices.size(); ++i )
9462   {
9463     gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
9464     edgeSize.push_back( ( p - pPrev ).Modulus() );
9465     if ( edgeSize.back() < numeric_limits<double>::min() )
9466     {
9467       edgeSize.pop_back();
9468     }
9469     else
9470     {
9471       points.push_back( p );
9472     }
9473     pPrev = p;
9474   }
9475   edgeSize.push_back( edgeSize[0] );
9476
9477   gp_XYZ newPos(0,0,0);
9478   double sumSize = 0;
9479   for ( size_t i = 0; i < points.size(); ++i )
9480   {
9481     newPos += points[i] * ( edgeSize[i] + edgeSize[i+1] );
9482     sumSize += edgeSize[i] + edgeSize[i+1];
9483   }
9484   newPos /= sumSize;
9485   return newPos;
9486 }
9487
9488 //================================================================================
9489 /*!
9490  * \brief Computes a new node position using angular-based smoothing
9491  */
9492 //================================================================================
9493
9494 gp_XYZ _LayerEdge::smoothCentroidal()
9495 {
9496   gp_XYZ newPos(0,0,0);
9497   gp_XYZ pN = SMESH_TNodeXYZ( _nodes.back() );
9498   double sumSize = 0;
9499   for ( size_t i = 0; i < _simplices.size(); ++i )
9500   {
9501     gp_XYZ p1 = SMESH_TNodeXYZ( _simplices[i]._nPrev );
9502     gp_XYZ p2 = SMESH_TNodeXYZ( _simplices[i]._nNext );
9503     gp_XYZ gc = ( pN + p1 + p2 ) / 3.;
9504     double size = (( p1 - pN ) ^ ( p2 - pN )).Modulus();
9505
9506     sumSize += size;
9507     newPos += gc * size;
9508   }
9509   newPos /= sumSize;
9510
9511   return newPos;
9512 }
9513
9514 //================================================================================
9515 /*!
9516  * \brief Computes a new node position located inside a Nef polygon
9517  */
9518 //================================================================================
9519
9520 gp_XYZ _LayerEdge::smoothNefPolygon()
9521 #ifdef OLD_NEF_POLYGON
9522 {
9523   gp_XYZ newPos(0,0,0);
9524
9525   // get a plane to search a solution on
9526
9527   vector< gp_XYZ > vecs( _simplices.size() + 1 );
9528   size_t i;
9529   const double tol = numeric_limits<double>::min();
9530   gp_XYZ center(0,0,0);
9531   for ( i = 0; i < _simplices.size(); ++i )
9532   {
9533     vecs[i] = ( SMESH_TNodeXYZ( _simplices[i]._nNext ) -
9534                 SMESH_TNodeXYZ( _simplices[i]._nPrev ));
9535     center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
9536   }
9537   vecs.back() = vecs[0];
9538   center /= _simplices.size();
9539
9540   gp_XYZ zAxis(0,0,0);
9541   for ( i = 0; i < _simplices.size(); ++i )
9542     zAxis += vecs[i] ^ vecs[i+1];
9543
9544   gp_XYZ yAxis;
9545   for ( i = 0; i < _simplices.size(); ++i )
9546   {
9547     yAxis = vecs[i];
9548     if ( yAxis.SquareModulus() > tol )
9549       break;
9550   }
9551   gp_XYZ xAxis = yAxis ^ zAxis;
9552   // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
9553   // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
9554   //                             p0.Distance( _simplices[2]._nPrev ));
9555   // gp_XYZ center = smoothLaplacian();
9556   // gp_XYZ xAxis, yAxis, zAxis;
9557   // for ( i = 0; i < _simplices.size(); ++i )
9558   // {
9559   //   xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9560   //   if ( xAxis.SquareModulus() > tol*tol )
9561   //     break;
9562   // }
9563   // for ( i = 1; i < _simplices.size(); ++i )
9564   // {
9565   //   yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9566   //   zAxis = xAxis ^ yAxis;
9567   //   if ( zAxis.SquareModulus() > tol*tol )
9568   //     break;
9569   // }
9570   // if ( i == _simplices.size() ) return newPos;
9571
9572   yAxis = zAxis ^ xAxis;
9573   xAxis /= xAxis.Modulus();
9574   yAxis /= yAxis.Modulus();
9575
9576   // get half-planes of _simplices
9577
9578   vector< _halfPlane > halfPlns( _simplices.size() );
9579   int nbHP = 0;
9580   for ( size_t i = 0; i < _simplices.size(); ++i )
9581   {
9582     gp_XYZ OP1 = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9583     gp_XYZ OP2 = SMESH_TNodeXYZ( _simplices[i]._nNext ) - center;
9584     gp_XY  p1( OP1 * xAxis, OP1 * yAxis );
9585     gp_XY  p2( OP2 * xAxis, OP2 * yAxis );
9586     gp_XY  vec12 = p2 - p1;
9587     double dist12 = vec12.Modulus();
9588     if ( dist12 < tol )
9589       continue;
9590     vec12 /= dist12;
9591     halfPlns[ nbHP ]._pos = p1;
9592     halfPlns[ nbHP ]._dir = vec12;
9593     halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
9594     ++nbHP;
9595   }
9596
9597   // intersect boundaries of half-planes, define state of intersection points
9598   // in relation to all half-planes and calculate internal point of a 2D polygon
9599
9600   double sumLen = 0;
9601   gp_XY newPos2D (0,0);
9602
9603   enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
9604   typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
9605   TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
9606
9607   vector< vector< TIntPntState > > allIntPnts( nbHP );
9608   for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
9609   {
9610     vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
9611     if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
9612
9613     int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
9614     int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
9615
9616     int nbNotOut = 0;
9617     const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
9618
9619     for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
9620     {
9621       if ( iHP1 == iHP2 ) continue;
9622
9623       TIntPntState & ips1 = intPnts1[ iHP2 ];
9624       if ( ips1.second == UNDEF )
9625       {
9626         // find an intersection point of boundaries of iHP1 and iHP2
9627
9628         if ( iHP2 == iPrev ) // intersection with neighbors is known
9629           ips1.first = halfPlns[ iHP1 ]._pos;
9630         else if ( iHP2 == iNext )
9631           ips1.first = halfPlns[ iHP2 ]._pos;
9632         else if ( !halfPlns[ iHP1 ].FindIntersection( halfPlns[ iHP2 ], ips1.first ))
9633           ips1.second = NO_INT;
9634
9635         // classify the found intersection point
9636         if ( ips1.second != NO_INT )
9637         {
9638           ips1.second = NOT_OUT;
9639           for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
9640             if ( i != iHP1 && i != iHP2 &&
9641                  halfPlns[ i ].IsOut( ips1.first, tol ))
9642               ips1.second = IS_OUT;
9643         }
9644         vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
9645         if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
9646         TIntPntState & ips2 = intPnts2[ iHP1 ];
9647         ips2 = ips1;
9648       }
9649       if ( ips1.second == NOT_OUT )
9650       {
9651         ++nbNotOut;
9652         segEnds[ bool(segEnds[0]) ] = & ips1.first;
9653       }
9654     }
9655
9656     // find a NOT_OUT segment of boundary which is located between
9657     // two NOT_OUT int points
9658
9659     if ( nbNotOut < 2 )
9660       continue; // no such a segment
9661
9662     if ( nbNotOut > 2 )
9663     {
9664       // sort points along the boundary
9665       map< double, TIntPntState* > ipsByParam;
9666       for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
9667       {
9668         TIntPntState & ips1 = intPnts1[ iHP2 ];
9669         if ( ips1.second != NO_INT )
9670         {
9671           gp_XY     op = ips1.first - halfPlns[ iHP1 ]._pos;
9672           double param = op * halfPlns[ iHP1 ]._dir;
9673           ipsByParam.insert( make_pair( param, & ips1 ));
9674         }
9675       }
9676       // look for two neighboring NOT_OUT points
9677       nbNotOut = 0;
9678       map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
9679       for ( ; u2ips != ipsByParam.end(); ++u2ips )
9680       {
9681         TIntPntState & ips1 = *(u2ips->second);
9682         if ( ips1.second == NOT_OUT )
9683           segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
9684         else if ( nbNotOut >= 2 )
9685           break;
9686         else
9687           nbNotOut = 0;
9688       }
9689     }
9690
9691     if ( nbNotOut >= 2 )
9692     {
9693       double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
9694       sumLen += len;
9695
9696       newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
9697     }
9698   }
9699
9700   if ( sumLen > 0 )
9701   {
9702     newPos2D /= sumLen;
9703     newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
9704   }
9705   else
9706   {
9707     newPos = center;
9708   }
9709
9710   return newPos;
9711 }
9712 #else // OLD_NEF_POLYGON
9713 { ////////////////////////////////// NEW
9714   gp_XYZ newPos(0,0,0);
9715
9716   // get a plane to search a solution on
9717
9718   size_t i;
9719   gp_XYZ center(0,0,0);
9720   for ( i = 0; i < _simplices.size(); ++i )
9721     center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
9722   center /= _simplices.size();
9723
9724   vector< gp_XYZ > vecs( _simplices.size() + 1 );
9725   for ( i = 0; i < _simplices.size(); ++i )
9726     vecs[i] = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9727   vecs.back() = vecs[0];
9728
9729   const double tol = numeric_limits<double>::min();
9730   gp_XYZ zAxis(0,0,0);
9731   for ( i = 0; i < _simplices.size(); ++i )
9732   {
9733     gp_XYZ cross = vecs[i] ^ vecs[i+1];
9734     try {
9735       cross.Normalize();
9736       if ( cross * zAxis < tol )
9737         zAxis += cross.Reversed();
9738       else
9739         zAxis += cross;
9740     }
9741     catch (Standard_Failure) { // if |cross| == 0.
9742     }
9743   }
9744
9745   gp_XYZ yAxis;
9746   for ( i = 0; i < _simplices.size(); ++i )
9747   {
9748     yAxis = vecs[i];
9749     if ( yAxis.SquareModulus() > tol )
9750       break;
9751   }
9752   gp_XYZ xAxis = yAxis ^ zAxis;
9753   // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
9754   // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
9755   //                             p0.Distance( _simplices[2]._nPrev ));
9756   // gp_XYZ center = smoothLaplacian();
9757   // gp_XYZ xAxis, yAxis, zAxis;
9758   // for ( i = 0; i < _simplices.size(); ++i )
9759   // {
9760   //   xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9761   //   if ( xAxis.SquareModulus() > tol*tol )
9762   //     break;
9763   // }
9764   // for ( i = 1; i < _simplices.size(); ++i )
9765   // {
9766   //   yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9767   //   zAxis = xAxis ^ yAxis;
9768   //   if ( zAxis.SquareModulus() > tol*tol )
9769   //     break;
9770   // }
9771   // if ( i == _simplices.size() ) return newPos;
9772
9773   yAxis = zAxis ^ xAxis;
9774   xAxis /= xAxis.Modulus();
9775   yAxis /= yAxis.Modulus();
9776
9777   // get half-planes of _simplices
9778
9779   vector< _halfPlane > halfPlns( _simplices.size() );
9780   int nbHP = 0;
9781   for ( size_t i = 0; i < _simplices.size(); ++i )
9782   {
9783     const gp_XYZ& OP1 = vecs[ i   ];
9784     const gp_XYZ& OP2 = vecs[ i+1 ];
9785     gp_XY  p1( OP1 * xAxis, OP1 * yAxis );
9786     gp_XY  p2( OP2 * xAxis, OP2 * yAxis );
9787     gp_XY  vec12 = p2 - p1;
9788     double dist12 = vec12.Modulus();
9789     if ( dist12 < tol )
9790       continue;
9791     vec12 /= dist12;
9792     halfPlns[ nbHP ]._pos = p1;
9793     halfPlns[ nbHP ]._dir = vec12;
9794     halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
9795     ++nbHP;
9796   }
9797
9798   // intersect boundaries of half-planes, define state of intersection points
9799   // in relation to all half-planes and calculate internal point of a 2D polygon
9800
9801   double sumLen = 0;
9802   gp_XY newPos2D (0,0);
9803
9804   enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
9805   typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
9806   TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
9807
9808   vector< vector< TIntPntState > > allIntPnts( nbHP );
9809   for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
9810   {
9811     vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
9812     if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
9813
9814     int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
9815     int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
9816
9817     int nbNotOut = 0;
9818     const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
9819
9820     for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
9821     {
9822       if ( iHP1 == iHP2 ) continue;
9823
9824       TIntPntState & ips1 = intPnts1[ iHP2 ];
9825       if ( ips1.second == UNDEF )
9826       {
9827         // find an intersection point of boundaries of iHP1 and iHP2
9828
9829         if ( iHP2 == iPrev ) // intersection with neighbors is known
9830           ips1.first = halfPlns[ iHP1 ]._pos;
9831         else if ( iHP2 == iNext )
9832           ips1.first = halfPlns[ iHP2 ]._pos;
9833         else if ( !halfPlns[ iHP1 ].FindIntersection( halfPlns[ iHP2 ], ips1.first ))
9834           ips1.second = NO_INT;
9835
9836         // classify the found intersection point
9837         if ( ips1.second != NO_INT )
9838         {
9839           ips1.second = NOT_OUT;
9840           for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
9841             if ( i != iHP1 && i != iHP2 &&
9842                  halfPlns[ i ].IsOut( ips1.first, tol ))
9843               ips1.second = IS_OUT;
9844         }
9845         vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
9846         if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
9847         TIntPntState & ips2 = intPnts2[ iHP1 ];
9848         ips2 = ips1;
9849       }
9850       if ( ips1.second == NOT_OUT )
9851       {
9852         ++nbNotOut;
9853         segEnds[ bool(segEnds[0]) ] = & ips1.first;
9854       }
9855     }
9856
9857     // find a NOT_OUT segment of boundary which is located between
9858     // two NOT_OUT int points
9859
9860     if ( nbNotOut < 2 )
9861       continue; // no such a segment
9862
9863     if ( nbNotOut > 2 )
9864     {
9865       // sort points along the boundary
9866       map< double, TIntPntState* > ipsByParam;
9867       for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
9868       {
9869         TIntPntState & ips1 = intPnts1[ iHP2 ];
9870         if ( ips1.second != NO_INT )
9871         {
9872           gp_XY     op = ips1.first - halfPlns[ iHP1 ]._pos;
9873           double param = op * halfPlns[ iHP1 ]._dir;
9874           ipsByParam.insert( make_pair( param, & ips1 ));
9875         }
9876       }
9877       // look for two neighboring NOT_OUT points
9878       nbNotOut = 0;
9879       map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
9880       for ( ; u2ips != ipsByParam.end(); ++u2ips )
9881       {
9882         TIntPntState & ips1 = *(u2ips->second);
9883         if ( ips1.second == NOT_OUT )
9884           segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
9885         else if ( nbNotOut >= 2 )
9886           break;
9887         else
9888           nbNotOut = 0;
9889       }
9890     }
9891
9892     if ( nbNotOut >= 2 )
9893     {
9894       double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
9895       sumLen += len;
9896
9897       newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
9898     }
9899   }
9900
9901   if ( sumLen > 0 )
9902   {
9903     newPos2D /= sumLen;
9904     newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
9905   }
9906   else
9907   {
9908     newPos = center;
9909   }
9910
9911   return newPos;
9912 }
9913 #endif // OLD_NEF_POLYGON
9914
9915 //================================================================================
9916 /*!
9917  * \brief Add a new segment to _LayerEdge during inflation
9918  */
9919 //================================================================================
9920
9921 void _LayerEdge::SetNewLength( double len, _EdgesOnShape& eos, SMESH_MesherHelper& helper )
9922 {
9923   if ( Is( BLOCKED ))
9924     return;
9925
9926   if ( len > _maxLen )
9927   {
9928     len = _maxLen;
9929     Block( eos.GetData() );
9930   }
9931   const double lenDelta = len - _len;
9932   // if ( lenDelta < 0 )
9933   //   return;
9934   if ( lenDelta < len * 1e-3  )
9935   {
9936     Block( eos.GetData() );
9937     return;
9938   }
9939
9940   SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
9941   gp_XYZ oldXYZ = SMESH_TNodeXYZ( n );
9942   gp_XYZ newXYZ;
9943   if ( eos._hyp.IsOffsetMethod() )
9944   {
9945     newXYZ = oldXYZ;
9946     gp_Vec faceNorm;
9947     SMDS_ElemIteratorPtr faceIt = _nodes[0]->GetInverseElementIterator( SMDSAbs_Face );
9948     while ( faceIt->more() )
9949     {
9950       const SMDS_MeshElement* face = faceIt->next();
9951       if ( !eos.GetNormal( face, faceNorm ))
9952         continue;
9953
9954       // translate plane of a face
9955       gp_XYZ baryCenter = oldXYZ + faceNorm.XYZ() * lenDelta;
9956
9957       // find point of intersection of the face plane located at baryCenter
9958       // and _normal located at newXYZ
9959       double d   = -( faceNorm.XYZ() * baryCenter ); // d of plane equation ax+by+cz+d=0
9960       double dot =  ( faceNorm.XYZ() * _normal );
9961       if ( dot < std::numeric_limits<double>::min() )
9962         dot = lenDelta * 1e-3;
9963       double step = -( faceNorm.XYZ() * newXYZ + d ) / dot;
9964       newXYZ += step * _normal;
9965     }
9966     _lenFactor = _normal * ( newXYZ - oldXYZ ) / lenDelta; // _lenFactor is used in InvalidateStep()
9967   }
9968   else
9969   {
9970     newXYZ = oldXYZ + _normal * lenDelta * _lenFactor;
9971   }
9972
9973   n->setXYZ( newXYZ.X(), newXYZ.Y(), newXYZ.Z() );
9974   _pos.push_back( newXYZ );
9975
9976   if ( !eos._sWOL.IsNull() )
9977     if ( !UpdatePositionOnSWOL( n, 2*lenDelta, eos, helper ))
9978     {
9979       n->setXYZ( oldXYZ.X(), oldXYZ.Y(), oldXYZ.Z() );
9980       _pos.pop_back();
9981       Block( eos.GetData() );
9982       return;
9983     }
9984
9985   _len = len;
9986
9987   // notify _neibors
9988   if ( eos.ShapeType() != TopAbs_FACE )
9989   {
9990     for ( size_t i = 0; i < _neibors.size(); ++i )
9991       //if (  _len > _neibors[i]->GetSmooLen() )
9992       _neibors[i]->Set( MOVED );
9993
9994     Set( MOVED );
9995   }
9996   dumpMove( n ); //debug
9997 }
9998
9999
10000 //================================================================================
10001 /*!
10002  * \brief Update last position on SWOL by projecting node on SWOL
10003 */
10004 //================================================================================
10005
10006 bool _LayerEdge::UpdatePositionOnSWOL( SMDS_MeshNode*      n,
10007                                        double              tol,
10008                                        _EdgesOnShape&      eos,
10009                                        SMESH_MesherHelper& helper )
10010 {
10011   double distXYZ[4];
10012   bool uvOK = false;
10013   if ( eos.SWOLType() == TopAbs_EDGE )
10014   {
10015     double u = Precision::Infinite(); // to force projection w/o distance check
10016     uvOK = helper.CheckNodeU( TopoDS::Edge( eos._sWOL ), n, u, tol, /*force=*/true, distXYZ );
10017     _pos.back().SetCoord( u, 0, 0 );
10018     if ( _nodes.size() > 1 && uvOK )
10019     {
10020       SMDS_EdgePositionPtr pos = n->GetPosition();
10021       pos->SetUParameter( u );
10022     }
10023   }
10024   else //  TopAbs_FACE
10025   {
10026     gp_XY uv( Precision::Infinite(), 0 );
10027     uvOK = helper.CheckNodeUV( TopoDS::Face( eos._sWOL ), n, uv, tol, /*force=*/true, distXYZ );
10028     _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
10029     if ( _nodes.size() > 1 && uvOK )
10030     {
10031       SMDS_FacePositionPtr pos = n->GetPosition();
10032       pos->SetUParameter( uv.X() );
10033       pos->SetVParameter( uv.Y() );
10034     }
10035   }
10036   if ( uvOK )
10037   {
10038     n->setXYZ( distXYZ[1], distXYZ[2], distXYZ[3]);
10039   }
10040   return uvOK;
10041 }
10042
10043 //================================================================================
10044 /*!
10045  * \brief Set BLOCKED flag and propagate limited _maxLen to _neibors
10046  */
10047 //================================================================================
10048
10049 void _LayerEdge::Block( _SolidData& data )
10050 {
10051   //if ( Is( BLOCKED )) return;
10052   Set( BLOCKED );
10053
10054   SMESH_Comment msg( "#BLOCK shape=");
10055   msg << data.GetShapeEdges( this )->_shapeID
10056       << ", nodes " << _nodes[0]->GetID() << ", " << _nodes.back()->GetID();
10057   dumpCmd( msg + " -- BEGIN");
10058
10059   SetMaxLen( _len );
10060   std::queue<_LayerEdge*> queue;
10061   queue.push( this );
10062
10063   gp_Pnt pSrc, pTgt, pSrcN, pTgtN;
10064   while ( !queue.empty() )
10065   {
10066     _LayerEdge* edge = queue.front(); queue.pop();
10067     pSrc = SMESH_TNodeXYZ( edge->_nodes[0] );
10068     pTgt = SMESH_TNodeXYZ( edge->_nodes.back() );
10069     for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
10070     {
10071       _LayerEdge* neibor = edge->_neibors[iN];
10072       if ( neibor->_maxLen < edge->_maxLen * 1.01 )
10073         continue;
10074       pSrcN = SMESH_TNodeXYZ( neibor->_nodes[0] );
10075       pTgtN = SMESH_TNodeXYZ( neibor->_nodes.back() );
10076       double minDist = pSrc.SquareDistance( pSrcN );
10077       minDist   = Min( pTgt.SquareDistance( pTgtN ), minDist );
10078       minDist   = Min( pSrc.SquareDistance( pTgtN ), minDist );
10079       minDist   = Min( pTgt.SquareDistance( pSrcN ), minDist );
10080       double newMaxLen = edge->_maxLen + 0.5 * Sqrt( minDist );
10081       //if ( edge->_nodes[0]->getshapeId() == neibor->_nodes[0]->getshapeId() ) viscous_layers_00/A3
10082       {
10083         //newMaxLen *= edge->_lenFactor / neibor->_lenFactor;
10084         // newMaxLen *= Min( edge->_lenFactor / neibor->_lenFactor,
10085         //                   neibor->_lenFactor / edge->_lenFactor );
10086       }
10087       if ( neibor->_maxLen > newMaxLen )
10088       {
10089         neibor->SetMaxLen( newMaxLen );
10090         if ( neibor->_maxLen < neibor->_len )
10091         {
10092           _EdgesOnShape* eos = data.GetShapeEdges( neibor );
10093           int       lastStep = neibor->Is( BLOCKED ) ? 1 : 0;
10094           while ( neibor->_len > neibor->_maxLen &&
10095                   neibor->NbSteps() > lastStep )
10096             neibor->InvalidateStep( neibor->NbSteps(), *eos, /*restoreLength=*/true );
10097           neibor->SetNewLength( neibor->_maxLen, *eos, data.GetHelper() );
10098           //neibor->Block( data );
10099         }
10100         queue.push( neibor );
10101       }
10102     }
10103   }
10104   dumpCmd( msg + " -- END");
10105 }
10106
10107 //================================================================================
10108 /*!
10109  * \brief Remove last inflation step
10110  */
10111 //================================================================================
10112
10113 void _LayerEdge::InvalidateStep( size_t curStep, const _EdgesOnShape& eos, bool restoreLength )
10114 {
10115   if ( _pos.size() > curStep && _nodes.size() > 1 )
10116   {
10117     _pos.resize( curStep );
10118
10119     gp_Pnt      nXYZ = _pos.back();
10120     SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
10121     SMESH_TNodeXYZ curXYZ( n );
10122     if ( !eos._sWOL.IsNull() )
10123     {
10124       TopLoc_Location loc;
10125       if ( eos.SWOLType() == TopAbs_EDGE )
10126       {
10127         SMDS_EdgePositionPtr pos = n->GetPosition();
10128         pos->SetUParameter( nXYZ.X() );
10129         double f,l;
10130         Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eos._sWOL ), loc, f,l);
10131         nXYZ = curve->Value( nXYZ.X() ).Transformed( loc );
10132       }
10133       else
10134       {
10135         SMDS_FacePositionPtr pos = n->GetPosition();
10136         pos->SetUParameter( nXYZ.X() );
10137         pos->SetVParameter( nXYZ.Y() );
10138         Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(eos._sWOL), loc );
10139         nXYZ = surface->Value( nXYZ.X(), nXYZ.Y() ).Transformed( loc );
10140       }
10141     }
10142     n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
10143     dumpMove( n );
10144
10145     if ( restoreLength )
10146     {
10147       if ( NbSteps() == 0 )
10148         _len = 0.;
10149       else if ( IsOnFace() && Is( MOVED ))
10150         _len = ( nXYZ.XYZ() - SMESH_NodeXYZ( _nodes[0] )) * _normal;
10151       else
10152         _len -= ( nXYZ.XYZ() - curXYZ ).Modulus() / _lenFactor;
10153     }
10154   }
10155   return;
10156 }
10157
10158 //================================================================================
10159 /*!
10160  * \brief Return index of a _pos distant from _normal
10161  */
10162 //================================================================================
10163
10164 int _LayerEdge::GetSmoothedPos( const double tol )
10165 {
10166   int iSmoothed = 0;
10167   for ( size_t i = 1; i < _pos.size() && !iSmoothed; ++i )
10168   {
10169     double normDist = ( _pos[i] - _pos[0] ).Crossed( _normal ).SquareModulus();
10170     if ( normDist > tol * tol )
10171       iSmoothed = i;
10172   }
10173   return iSmoothed;
10174 }
10175
10176 //================================================================================
10177 /*!
10178  * \brief Smooth a path formed by _pos of a _LayerEdge smoothed on FACE
10179  */
10180 //================================================================================
10181
10182 void _LayerEdge::SmoothPos( const vector< double >& segLen, const double tol )
10183 {
10184   if ( /*Is( NORMAL_UPDATED ) ||*/ _pos.size() <= 2 )
10185     return;
10186
10187   // find the 1st smoothed _pos
10188   int iSmoothed = GetSmoothedPos( tol );
10189   if ( !iSmoothed ) return;
10190
10191   gp_XYZ normal = _normal;
10192   if ( Is( NORMAL_UPDATED ))
10193   {
10194     double minDot = 1;
10195     for ( size_t i = 0; i < _neibors.size(); ++i )
10196     {
10197       if ( _neibors[i]->IsOnFace() )
10198       {
10199         double dot = _normal * _neibors[i]->_normal;
10200         if ( dot < minDot )
10201         {
10202           normal = _neibors[i]->_normal;
10203           minDot = dot;
10204         }
10205       }
10206     }
10207     if ( minDot == 1. )
10208       for ( size_t i = 1; i < _pos.size(); ++i )
10209       {
10210         normal = _pos[i] - _pos[0];
10211         double size = normal.Modulus();
10212         if ( size > RealSmall() )
10213         {
10214           normal /= size;
10215           break;
10216         }
10217       }
10218   }
10219   const double r = 0.2;
10220   for ( int iter = 0; iter < 50; ++iter )
10221   {
10222     double minDot = 1;
10223     for ( size_t i = Max( 1, iSmoothed-1-iter ); i < _pos.size()-1; ++i )
10224     {
10225       gp_XYZ midPos = 0.5 * ( _pos[i-1] + _pos[i+1] );
10226       gp_XYZ newPos = ( 1-r ) * midPos + r * _pos[i];
10227       _pos[i] = newPos;
10228       double midLen = 0.5 * ( segLen[i-1] + segLen[i+1] );
10229       double newLen = ( 1-r ) * midLen + r * segLen[i];
10230       const_cast< double& >( segLen[i] ) = newLen;
10231       // check angle between normal and (_pos[i+1], _pos[i] )
10232       gp_XYZ posDir = _pos[i+1] - _pos[i];
10233       double size   = posDir.SquareModulus();
10234       if ( size > RealSmall() )
10235         minDot = Min( minDot, ( normal * posDir ) * ( normal * posDir ) / size );
10236     }
10237     if ( minDot > 0.5 * 0.5 )
10238       break;
10239   }
10240   return;
10241 }
10242
10243 //================================================================================
10244 /*!
10245  * \brief Print flags
10246  */
10247 //================================================================================
10248
10249 std::string _LayerEdge::DumpFlags() const
10250 {
10251   SMESH_Comment dump;
10252   for ( int flag = 1; flag < 0x1000000; flag *= 2 )
10253     if ( _flags & flag )
10254     {
10255       EFlags f = (EFlags) flag;
10256       switch ( f ) {
10257       case TO_SMOOTH:       dump << "TO_SMOOTH";       break;
10258       case MOVED:           dump << "MOVED";           break;
10259       case SMOOTHED:        dump << "SMOOTHED";        break;
10260       case DIFFICULT:       dump << "DIFFICULT";       break;
10261       case ON_CONCAVE_FACE: dump << "ON_CONCAVE_FACE"; break;
10262       case BLOCKED:         dump << "BLOCKED";         break;
10263       case INTERSECTED:     dump << "INTERSECTED";     break;
10264       case NORMAL_UPDATED:  dump << "NORMAL_UPDATED";  break;
10265       case UPD_NORMAL_CONV: dump << "UPD_NORMAL_CONV"; break;
10266       case MARKED:          dump << "MARKED";          break;
10267       case MULTI_NORMAL:    dump << "MULTI_NORMAL";    break;
10268       case NEAR_BOUNDARY:   dump << "NEAR_BOUNDARY";   break;
10269       case SMOOTHED_C1:     dump << "SMOOTHED_C1";     break;
10270       case DISTORTED:       dump << "DISTORTED";       break;
10271       case RISKY_SWOL:      dump << "RISKY_SWOL";      break;
10272       case SHRUNK:          dump << "SHRUNK";          break;
10273       case UNUSED_FLAG:     dump << "UNUSED_FLAG";     break;
10274       }
10275       dump << " ";
10276     }
10277   cout << dump << endl;
10278   return dump;
10279 }
10280
10281
10282 //================================================================================
10283 /*!
10284  * \brief Create layers of prisms
10285  */
10286 //================================================================================
10287
10288 bool _ViscousBuilder::refine(_SolidData& data)
10289 {
10290   SMESH_MesherHelper& helper = data.GetHelper();
10291   helper.SetElementsOnShape(false);
10292
10293   Handle(Geom_Curve) curve;
10294   Handle(ShapeAnalysis_Surface) surface;
10295   TopoDS_Edge geomEdge;
10296   TopoDS_Face geomFace;
10297   TopLoc_Location loc;
10298   double f,l, u = 0;
10299   gp_XY uv;
10300   vector< gp_XYZ > pos3D;
10301   bool isOnEdge, isTooConvexFace = false;
10302   TGeomID prevBaseId = -1;
10303   TNode2Edge* n2eMap = 0;
10304   TNode2Edge::iterator n2e;
10305
10306   // Create intermediate nodes on each _LayerEdge
10307
10308   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
10309   {
10310     _EdgesOnShape& eos = data._edgesOnShape[iS];
10311     if ( eos._edges.empty() ) continue;
10312
10313     if ( eos._edges[0]->_nodes.size() < 2 )
10314       continue; // on _noShrinkShapes
10315
10316     // get data of a shrink shape
10317     isOnEdge = false;
10318     geomEdge.Nullify(); geomFace.Nullify();
10319     curve.Nullify(); surface.Nullify();
10320     if ( !eos._sWOL.IsNull() )
10321     {
10322       isOnEdge = ( eos.SWOLType() == TopAbs_EDGE );
10323       if ( isOnEdge )
10324       {
10325         geomEdge = TopoDS::Edge( eos._sWOL );
10326         curve    = BRep_Tool::Curve( geomEdge, loc, f,l);
10327       }
10328       else
10329       {
10330         geomFace = TopoDS::Face( eos._sWOL );
10331         surface  = helper.GetSurface( geomFace );
10332       }
10333     }
10334     else if ( eos.ShapeType() == TopAbs_FACE && eos._toSmooth )
10335     {
10336       geomFace = TopoDS::Face( eos._shape );
10337       surface  = helper.GetSurface( geomFace );
10338       // propagate _toSmooth back to _eosC1, which was unset in findShapesToSmooth()
10339       for ( size_t i = 0; i < eos._eosC1.size(); ++i )
10340         eos._eosC1[ i ]->_toSmooth = true;
10341
10342       isTooConvexFace = false;
10343       if ( _ConvexFace* cf = data.GetConvexFace( eos._shapeID ))
10344         isTooConvexFace = cf->_isTooCurved;
10345     }
10346
10347     vector< double > segLen;
10348     for ( size_t i = 0; i < eos._edges.size(); ++i )
10349     {
10350       _LayerEdge& edge = *eos._edges[i];
10351       if ( edge._pos.size() < 2 )
10352         continue;
10353
10354       // get accumulated length of segments
10355       segLen.resize( edge._pos.size() );
10356       segLen[0] = 0.0;
10357       if ( eos._sWOL.IsNull() )
10358       {
10359         bool useNormal = true;
10360         bool    usePos = false;
10361         bool  smoothed = false;
10362         double   preci = 0.1 * edge._len;
10363         if ( eos._toSmooth && edge._pos.size() > 2 )
10364         {
10365           smoothed = edge.GetSmoothedPos( preci );
10366         }
10367         if ( smoothed )
10368         {
10369           if ( !surface.IsNull() && !isTooConvexFace ) // edge smoothed on FACE
10370           {
10371             useNormal = usePos = false;
10372             gp_Pnt2d uv = helper.GetNodeUV( geomFace, edge._nodes[0] );
10373             for ( size_t j = 1; j < edge._pos.size() && !useNormal; ++j )
10374             {
10375               uv = surface->NextValueOfUV( uv, edge._pos[j], preci );
10376               if ( surface->Gap() < 2. * edge._len )
10377                 segLen[j] = surface->Gap();
10378               else
10379                 useNormal = true;
10380             }
10381           }
10382         }
10383         else if ( !edge.Is( _LayerEdge::NORMAL_UPDATED ))
10384         {
10385 #ifndef __NODES_AT_POS
10386           useNormal = usePos = false;
10387           edge._pos[1] = edge._pos.back();
10388           edge._pos.resize( 2 );
10389           segLen.resize( 2 );
10390           segLen[ 1 ] = edge._len;
10391 #endif
10392         }
10393         if ( useNormal && edge.Is( _LayerEdge::NORMAL_UPDATED ))
10394         {
10395           useNormal = usePos = false;
10396           _LayerEdge tmpEdge; // get original _normal
10397           tmpEdge._nodes.push_back( edge._nodes[0] );
10398           if ( !setEdgeData( tmpEdge, eos, helper, data ))
10399             usePos = true;
10400           else
10401             for ( size_t j = 1; j < edge._pos.size(); ++j )
10402               segLen[j] = ( edge._pos[j] - edge._pos[0] ) * tmpEdge._normal;
10403         }
10404         if ( useNormal )
10405         {
10406           for ( size_t j = 1; j < edge._pos.size(); ++j )
10407             segLen[j] = ( edge._pos[j] - edge._pos[0] ) * edge._normal;
10408         }
10409         if ( usePos )
10410         {
10411           for ( size_t j = 1; j < edge._pos.size(); ++j )
10412             segLen[j] = segLen[j-1] + ( edge._pos[j-1] - edge._pos[j] ).Modulus();
10413         }
10414         else
10415         {
10416           bool swapped = ( edge._pos.size() > 2 );
10417           while ( swapped )
10418           {
10419             swapped = false;
10420             for ( size_t j = 1; j < edge._pos.size()-1; ++j )
10421               if ( segLen[j] > segLen.back() )
10422               {
10423                 segLen.erase( segLen.begin() + j );
10424                 edge._pos.erase( edge._pos.begin() + j );
10425                 --j;
10426               }
10427               else if ( segLen[j] < segLen[j-1] )
10428               {
10429                 std::swap( segLen[j], segLen[j-1] );
10430                 std::swap( edge._pos[j], edge._pos[j-1] );
10431                 swapped = true;
10432               }
10433           }
10434         }
10435         // smooth a path formed by edge._pos
10436 #ifndef __NODES_AT_POS
10437         if (( smoothed ) /*&&
10438             ( eos.ShapeType() == TopAbs_FACE || edge.Is( _LayerEdge::SMOOTHED_C1 ))*/)
10439           edge.SmoothPos( segLen, preci );
10440 #endif
10441       }
10442       else if ( eos._isRegularSWOL ) // usual SWOL
10443       {
10444         if ( edge.Is( _LayerEdge::SMOOTHED ))
10445         {
10446           SMESH_NodeXYZ p0( edge._nodes[0] );
10447           for ( size_t j = 1; j < edge._pos.size(); ++j )
10448           {
10449             gp_XYZ pj = surface->Value( edge._pos[j].X(), edge._pos[j].Y() ).XYZ();
10450             segLen[j] = ( pj - p0 ) * edge._normal;
10451           }
10452         }
10453         else
10454         {
10455           for ( size_t j = 1; j < edge._pos.size(); ++j )
10456             segLen[j] = segLen[j-1] + (edge._pos[j-1] - edge._pos[j] ).Modulus();
10457         }
10458       }
10459       else // SWOL is surface with singularities or irregularly parametrized curve
10460       {
10461         pos3D.resize( edge._pos.size() );
10462
10463         if ( !surface.IsNull() )
10464           for ( size_t j = 0; j < edge._pos.size(); ++j )
10465             pos3D[j] = surface->Value( edge._pos[j].X(), edge._pos[j].Y() ).XYZ();
10466         else if ( !curve.IsNull() )
10467           for ( size_t j = 0; j < edge._pos.size(); ++j )
10468             pos3D[j] = curve->Value( edge._pos[j].X() ).XYZ();
10469
10470         for ( size_t j = 1; j < edge._pos.size(); ++j )
10471           segLen[j] = segLen[j-1] + ( pos3D[j-1] - pos3D[j] ).Modulus();
10472       }
10473
10474       // allocate memory for new nodes if it is not yet refined
10475       const SMDS_MeshNode* tgtNode = edge._nodes.back();
10476       if ( edge._nodes.size() == 2 )
10477       {
10478 #ifdef __NODES_AT_POS
10479         int nbNodes = edge._pos.size();
10480 #else
10481         int nbNodes = eos._hyp.GetNumberLayers() + 1;
10482 #endif
10483         edge._nodes.resize( nbNodes, 0 );
10484         edge._nodes[1] = 0;
10485         edge._nodes.back() = tgtNode;
10486       }
10487       // restore shapePos of the last node by already treated _LayerEdge of another _SolidData
10488       const TGeomID baseShapeId = edge._nodes[0]->getshapeId();
10489       if ( baseShapeId != prevBaseId )
10490       {
10491         map< TGeomID, TNode2Edge* >::iterator s2ne = data._s2neMap.find( baseShapeId );
10492         n2eMap = ( s2ne == data._s2neMap.end() ) ? 0 : s2ne->second;
10493         prevBaseId = baseShapeId;
10494       }
10495       _LayerEdge* edgeOnSameNode = 0;
10496       bool        useExistingPos = false;
10497       if ( n2eMap && (( n2e = n2eMap->find( edge._nodes[0] )) != n2eMap->end() ))
10498       {
10499         edgeOnSameNode = n2e->second;
10500         useExistingPos = ( edgeOnSameNode->_len < edge._len ||
10501                            segLen[0] == segLen.back() ); // too short inflation step (bos #20643)
10502         const gp_XYZ& otherTgtPos = edgeOnSameNode->_pos.back();
10503         SMDS_PositionPtr  lastPos = tgtNode->GetPosition();
10504         if ( isOnEdge )
10505         {
10506           SMDS_EdgePositionPtr epos = lastPos;
10507           epos->SetUParameter( otherTgtPos.X() );
10508         }
10509         else
10510         {
10511           SMDS_FacePositionPtr fpos = lastPos;
10512           fpos->SetUParameter( otherTgtPos.X() );
10513           fpos->SetVParameter( otherTgtPos.Y() );
10514         }
10515       }
10516
10517       // create intermediate nodes
10518       const double      h0 = eos._hyp.Get1stLayerThickness( segLen.back() );
10519       const double zeroLen = std::numeric_limits<double>::min();
10520       double hSum = 0, hi = h0/eos._hyp.GetStretchFactor();
10521       size_t iSeg = 1;
10522       for ( size_t iStep = 1; iStep < edge._nodes.size(); ++iStep )
10523       {
10524         // compute an intermediate position
10525         hi *= eos._hyp.GetStretchFactor();
10526         hSum += hi;
10527         while ( hSum > segLen[iSeg] && iSeg < segLen.size()-1 )
10528           ++iSeg;
10529         int iPrevSeg = iSeg-1;
10530         while ( fabs( segLen[iPrevSeg] - segLen[iSeg]) <= zeroLen && iPrevSeg > 0 )
10531           --iPrevSeg;
10532         double   r = ( segLen[iSeg] - hSum ) / ( segLen[iSeg] - segLen[iPrevSeg] );
10533         gp_Pnt pos = r * edge._pos[iPrevSeg] + (1-r) * edge._pos[iSeg];
10534 #ifdef __NODES_AT_POS
10535         pos = edge._pos[ iStep ];
10536 #endif
10537         SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >( edge._nodes[ iStep ]);
10538         if ( !eos._sWOL.IsNull() )
10539         {
10540           // compute XYZ by parameters <pos>
10541           if ( isOnEdge )
10542           {
10543             u = pos.X();
10544             if ( !node )
10545               pos = curve->Value( u ).Transformed(loc);
10546           }
10547           else if ( eos._isRegularSWOL )
10548           {
10549             uv.SetCoord( pos.X(), pos.Y() );
10550             if ( !node )
10551               pos = surface->Value( pos.X(), pos.Y() );
10552           }
10553           else
10554           {
10555             uv.SetCoord( pos.X(), pos.Y() );
10556             gp_Pnt p = r * pos3D[ iPrevSeg ] + (1-r) * pos3D[ iSeg ];
10557             uv = surface->NextValueOfUV( uv, p, BRep_Tool::Tolerance( geomFace )).XY();
10558             if ( !node )
10559               pos = surface->Value( uv );
10560           }
10561         }
10562         // create or update the node
10563         if ( !node )
10564         {
10565           node = helper.AddNode( pos.X(), pos.Y(), pos.Z());
10566           if ( !eos._sWOL.IsNull() )
10567           {
10568             if ( isOnEdge )
10569               getMeshDS()->SetNodeOnEdge( node, geomEdge, u );
10570             else
10571               getMeshDS()->SetNodeOnFace( node, geomFace, uv.X(), uv.Y() );
10572           }
10573           else
10574           {
10575             getMeshDS()->SetNodeInVolume( node, helper.GetSubShapeID() );
10576           }
10577         }
10578         else
10579         {
10580           if ( !eos._sWOL.IsNull() )
10581           {
10582             // make average pos from new and current parameters
10583             if ( isOnEdge )
10584             {
10585               //u = 0.5 * ( u + helper.GetNodeU( geomEdge, node ));
10586               if ( useExistingPos )
10587                 u = helper.GetNodeU( geomEdge, node );
10588               pos = curve->Value( u ).Transformed(loc);
10589
10590               SMDS_EdgePositionPtr epos = node->GetPosition();
10591               epos->SetUParameter( u );
10592             }
10593             else
10594             {
10595               //uv = 0.5 * ( uv + helper.GetNodeUV( geomFace, node ));
10596               if ( useExistingPos )
10597                 uv = helper.GetNodeUV( geomFace, node );
10598               pos = surface->Value( uv );
10599
10600               SMDS_FacePositionPtr fpos = node->GetPosition();
10601               fpos->SetUParameter( uv.X() );
10602               fpos->SetVParameter( uv.Y() );
10603             }
10604           }
10605           node->setXYZ( pos.X(), pos.Y(), pos.Z() );
10606         }
10607       } // loop on edge._nodes
10608
10609       if ( !eos._sWOL.IsNull() ) // prepare for shrink()
10610       {
10611         if ( isOnEdge )
10612           edge._pos.back().SetCoord( u, 0,0);
10613         else
10614           edge._pos.back().SetCoord( uv.X(), uv.Y() ,0);
10615
10616         if ( edgeOnSameNode )
10617           edgeOnSameNode->_pos.back() = edge._pos.back();
10618       }
10619
10620     } // loop on eos._edges to create nodes
10621
10622
10623     if ( !getMeshDS()->IsEmbeddedMode() )
10624       // Log node movement
10625       for ( size_t i = 0; i < eos._edges.size(); ++i )
10626       {
10627         SMESH_TNodeXYZ p ( eos._edges[i]->_nodes.back() );
10628         getMeshDS()->MoveNode( p._node, p.X(), p.Y(), p.Z() );
10629       }
10630   }
10631
10632
10633   // Create volumes
10634
10635   helper.SetElementsOnShape(true);
10636
10637   vector< vector<const SMDS_MeshNode*>* > nnVec;
10638   set< vector<const SMDS_MeshNode*>* >    nnSet;
10639   set< int >                       degenEdgeInd;
10640   vector<const SMDS_MeshElement*>     degenVols;
10641
10642   TopExp_Explorer exp( data._solid, TopAbs_FACE );
10643   for ( ; exp.More(); exp.Next() )
10644   {
10645     const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
10646     if ( data._ignoreFaceIds.count( faceID ))
10647       continue;
10648     _EdgesOnShape*    eos = data.GetShapeEdges( faceID );
10649     SMDS_MeshGroup* group = StdMeshers_ViscousLayers::CreateGroup( eos->_hyp.GetGroupName(),
10650                                                                    *helper.GetMesh(),
10651                                                                    SMDSAbs_Volume );
10652     std::vector< const SMDS_MeshElement* > vols;
10653     const bool isReversedFace = data._reversedFaceIds.count( faceID );
10654     SMESHDS_SubMesh*    fSubM = getMeshDS()->MeshElements( exp.Current() );
10655     SMDS_ElemIteratorPtr  fIt = fSubM->GetElements();
10656     while ( fIt->more() )
10657     {
10658       const SMDS_MeshElement* face = fIt->next();
10659       const int            nbNodes = face->NbCornerNodes();
10660       nnVec.resize( nbNodes );
10661       nnSet.clear();
10662       degenEdgeInd.clear();
10663       size_t maxZ = 0, minZ = std::numeric_limits<size_t>::max();
10664       SMDS_NodeIteratorPtr nIt = face->nodeIterator();
10665       for ( int iN = 0; iN < nbNodes; ++iN )
10666       {
10667         const SMDS_MeshNode* n = nIt->next();
10668         _LayerEdge*       edge = data._n2eMap[ n ];
10669         const int i = isReversedFace ? nbNodes-1-iN : iN;
10670         nnVec[ i ] = & edge->_nodes;
10671         maxZ = std::max( maxZ, nnVec[ i ]->size() );
10672         minZ = std::min( minZ, nnVec[ i ]->size() );
10673
10674         if ( helper.HasDegeneratedEdges() )
10675           nnSet.insert( nnVec[ i ]);
10676       }
10677
10678       if ( maxZ == 0 )
10679         continue;
10680       if ( 0 < nnSet.size() && nnSet.size() < 3 )
10681         continue;
10682
10683       vols.clear();
10684       const SMDS_MeshElement* vol;
10685
10686       switch ( nbNodes )
10687       {
10688       case 3: // TRIA
10689       {
10690         // PENTA
10691         for ( size_t iZ = 1; iZ < minZ; ++iZ )
10692         {
10693           vol = helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
10694                                   (*nnVec[0])[iZ],   (*nnVec[1])[iZ],   (*nnVec[2])[iZ]);
10695           vols.push_back( vol );
10696         }
10697
10698         for ( size_t iZ = minZ; iZ < maxZ; ++iZ )
10699         {
10700           for ( int iN = 0; iN < nbNodes; ++iN )
10701             if ( nnVec[ iN ]->size() < iZ+1 )
10702               degenEdgeInd.insert( iN );
10703
10704           if ( degenEdgeInd.size() == 1 )  // PYRAM
10705           {
10706             int i2 = *degenEdgeInd.begin();
10707             int i0 = helper.WrapIndex( i2 - 1, nbNodes );
10708             int i1 = helper.WrapIndex( i2 + 1, nbNodes );
10709             vol = helper.AddVolume( (*nnVec[i0])[iZ-1], (*nnVec[i1])[iZ-1],
10710                                     (*nnVec[i1])[iZ  ], (*nnVec[i0])[iZ  ], (*nnVec[i2]).back());
10711             vols.push_back( vol );
10712           }
10713           else  // TETRA
10714           {
10715             int i3 = !degenEdgeInd.count(0) ? 0 : !degenEdgeInd.count(1) ? 1 : 2;
10716             vol = helper.AddVolume( (*nnVec[  0 ])[ i3 == 0 ? iZ-1 : nnVec[0]->size()-1 ],
10717                                     (*nnVec[  1 ])[ i3 == 1 ? iZ-1 : nnVec[1]->size()-1 ],
10718                                     (*nnVec[  2 ])[ i3 == 2 ? iZ-1 : nnVec[2]->size()-1 ],
10719                                     (*nnVec[ i3 ])[ iZ ]);
10720             vols.push_back( vol );
10721           }
10722         }
10723         break; // TRIA
10724       }
10725       case 4: // QUAD
10726       {
10727         // HEX
10728         for ( size_t iZ = 1; iZ < minZ; ++iZ )
10729         {
10730           vol = helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
10731                                   (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
10732                                   (*nnVec[0])[iZ],   (*nnVec[1])[iZ],
10733                                   (*nnVec[2])[iZ],   (*nnVec[3])[iZ]);
10734           vols.push_back( vol );
10735         }
10736
10737         for ( size_t iZ = minZ; iZ < maxZ; ++iZ )
10738         {
10739           for ( int iN = 0; iN < nbNodes; ++iN )
10740             if ( nnVec[ iN ]->size() < iZ+1 )
10741               degenEdgeInd.insert( iN );
10742
10743           switch ( degenEdgeInd.size() )
10744           {
10745           case 2: // PENTA
10746           {
10747             int i2 = *degenEdgeInd.begin();
10748             int i3 = *degenEdgeInd.rbegin();
10749             bool ok = ( i3 - i2 == 1 );
10750             if ( i2 == 0 && i3 == 3 ) { i2 = 3; i3 = 0; ok = true; }
10751             int i0 = helper.WrapIndex( i3 + 1, nbNodes );
10752             int i1 = helper.WrapIndex( i0 + 1, nbNodes );
10753
10754             vol = helper.AddVolume( nnVec[i3]->back(), (*nnVec[i0])[iZ], (*nnVec[i0])[iZ-1],
10755                                     nnVec[i2]->back(), (*nnVec[i1])[iZ], (*nnVec[i1])[iZ-1]);
10756             vols.push_back( vol );
10757             if ( !ok && vol )
10758               degenVols.push_back( vol );
10759           }
10760           break;
10761
10762           default: // degen HEX
10763           {
10764             vol = helper.AddVolume( nnVec[0]->size() > iZ-1 ? (*nnVec[0])[iZ-1] : nnVec[0]->back(),
10765                                     nnVec[1]->size() > iZ-1 ? (*nnVec[1])[iZ-1] : nnVec[1]->back(),
10766                                     nnVec[2]->size() > iZ-1 ? (*nnVec[2])[iZ-1] : nnVec[2]->back(),
10767                                     nnVec[3]->size() > iZ-1 ? (*nnVec[3])[iZ-1] : nnVec[3]->back(),
10768                                     nnVec[0]->size() > iZ   ? (*nnVec[0])[iZ]   : nnVec[0]->back(),
10769                                     nnVec[1]->size() > iZ   ? (*nnVec[1])[iZ]   : nnVec[1]->back(),
10770                                     nnVec[2]->size() > iZ   ? (*nnVec[2])[iZ]   : nnVec[2]->back(),
10771                                     nnVec[3]->size() > iZ   ? (*nnVec[3])[iZ]   : nnVec[3]->back());
10772             vols.push_back( vol );
10773             degenVols.push_back( vol );
10774           }
10775           }
10776         }
10777         break; // HEX
10778       }
10779       default:
10780         return error("Not supported type of element", data._index);
10781
10782       } // switch ( nbNodes )
10783
10784       if ( group )
10785         for ( size_t i = 0; i < vols.size(); ++i )
10786           group->Add( vols[ i ]);
10787
10788     } // while ( fIt->more() )
10789   } // loop on FACEs
10790
10791   if ( !degenVols.empty() )
10792   {
10793     SMESH_ComputeErrorPtr& err = _mesh->GetSubMesh( data._solid )->GetComputeError();
10794     if ( !err || err->IsOK() )
10795     {
10796       SMESH_BadInputElements* badElems =
10797         new SMESH_BadInputElements( getMeshDS(), COMPERR_WARNING, "Bad quality volumes created" );
10798       badElems->myBadElements.insert( badElems->myBadElements.end(),
10799                                       degenVols.begin(),degenVols.end() );
10800       err.reset( badElems );
10801     }
10802   }
10803
10804   return true;
10805 }
10806
10807 namespace VISCOUS_3D
10808 {
10809   struct ShrinkFace;
10810   //--------------------------------------------------------------------------------
10811   /*!
10812    * \brief Pair of periodic FACEs
10813    */
10814   struct PeriodicFaces
10815   {
10816     typedef StdMeshers_ProjectionUtils::TrsfFinder3D Trsf;
10817
10818     ShrinkFace*  _shriFace[2];
10819     TNodeNodeMap _nnMap;
10820     Trsf         _trsf;
10821
10822     PeriodicFaces( ShrinkFace* sf1, ShrinkFace* sf2 ): _shriFace{ sf1, sf2 } {}
10823     bool IncludeShrunk( const TopoDS_Face& face, const TopTools_MapOfShape& shrunkFaces ) const;
10824     bool MoveNodes( const TopoDS_Face& tgtFace );
10825     void Clear() { _nnMap.clear(); }
10826     bool IsEmpty() const { return _nnMap.empty(); }
10827   };
10828
10829   //--------------------------------------------------------------------------------
10830   /*!
10831    * \brief Shrink FACE data used to find periodic FACEs
10832    */
10833   struct ShrinkFace
10834   {
10835     // ................................................................................
10836     struct BndPart //!< part of FACE boundary, either shrink or no-shrink
10837     {
10838       bool                         _isShrink, _isReverse;
10839       int                          _nbSegments;
10840       AverageHyp*                  _hyp;
10841       std::vector< SMESH_NodeXYZ > _nodes;
10842       TopAbs_ShapeEnum             _vertSWOLType[2]; // shrink part includes VERTEXes
10843       AverageHyp*                  _vertHyp[2];
10844
10845       BndPart():
10846         _isShrink(0), _isReverse(0), _nbSegments(0), _hyp(0),
10847         _vertSWOLType{ TopAbs_WIRE, TopAbs_WIRE }, _vertHyp{ 0, 0 }
10848       {}
10849
10850       bool operator==( const BndPart& other ) const
10851       {
10852         return ( _isShrink       == other._isShrink &&
10853                  _nbSegments     == other._nbSegments &&
10854                  _nodes.size()   == other._nodes.size() &&
10855                  vertSWOLType1() == other.vertSWOLType1() &&
10856                  vertSWOLType2() == other.vertSWOLType2() &&
10857                  (( !_isShrink ) ||
10858                   ( *_hyp        == *other._hyp &&
10859                     vertHyp1()   == other.vertHyp1() &&
10860                     vertHyp2()   == other.vertHyp2() ))
10861                  );
10862       }
10863       bool CanAppend( const BndPart& other )
10864       {
10865         return ( _isShrink  == other._isShrink  &&
10866                  (( !_isShrink ) ||
10867                   ( *_hyp        == *other._hyp &&
10868                     *_hyp        == vertHyp2()  &&
10869                     vertHyp2()   == other.vertHyp1() ))
10870                  );
10871       }
10872       void Append( const BndPart& other )
10873       {
10874         _nbSegments += other._nbSegments;
10875         bool hasCommonNode = ( _nodes.back()->GetID() == other._nodes.front()->GetID() );
10876         _nodes.insert( _nodes.end(), other._nodes.begin() + hasCommonNode, other._nodes.end() );
10877         _vertSWOLType[1] = other._vertSWOLType[1];
10878         if ( _isShrink )
10879           _vertHyp[1] = other._vertHyp[1];
10880       }
10881       const SMDS_MeshNode*    Node(size_t i)  const
10882       {
10883         return _nodes[ _isReverse ? ( _nodes.size() - 1 - i ) : i ]._node;
10884       }
10885       void Reverse() { _isReverse = !_isReverse; }
10886       const TopAbs_ShapeEnum& vertSWOLType1() const { return _vertSWOLType[ _isReverse  ]; }
10887       const TopAbs_ShapeEnum& vertSWOLType2() const { return _vertSWOLType[ !_isReverse ]; }
10888       const AverageHyp&       vertHyp1()      const { return *(_vertHyp[ _isReverse  ]); }
10889       const AverageHyp&       vertHyp2()      const { return *(_vertHyp[ !_isReverse ]); }
10890     };
10891     // ................................................................................
10892
10893     SMESH_subMesh*       _subMesh;
10894     _SolidData*          _data1;
10895     _SolidData*          _data2;
10896
10897     std::list< BndPart > _boundary;
10898     int                  _boundarySize, _nbBoundaryParts;
10899
10900     void Init( SMESH_subMesh* sm, _SolidData* sd1, _SolidData* sd2 )
10901     {
10902       _subMesh = sm; _data1 = sd1; _data2 = sd2;
10903     }
10904     bool IsSame( const TopoDS_Face& face ) const
10905     {
10906       return _subMesh->GetSubShape().IsSame( face );
10907     }
10908     bool IsShrunk( const TopTools_MapOfShape& shrunkFaces ) const
10909     {
10910       return shrunkFaces.Contains( _subMesh->GetSubShape() );
10911     }
10912
10913     //================================================================================
10914     /*!
10915      * Check if meshes on two FACEs are equal
10916      */
10917     bool IsPeriodic( ShrinkFace& other, PeriodicFaces& periodic )
10918     {
10919       if ( !IsSameNbElements( other ))
10920         return false;
10921
10922       this->SetBoundary();
10923       other.SetBoundary();
10924       if ( this->_boundarySize    != other._boundarySize ||
10925            this->_nbBoundaryParts != other._nbBoundaryParts )
10926         return false;
10927
10928       for ( int isReverse = 0; isReverse < 2; ++isReverse )
10929       {
10930         if ( isReverse )
10931           Reverse( _boundary );
10932
10933         // check boundaries
10934         bool equalBoundary = false;
10935         for ( int iP = 0; iP < _nbBoundaryParts &&  !equalBoundary; ++iP )
10936         {
10937           if ( ! ( equalBoundary = ( this->_boundary == other._boundary )))
10938             // set first part at end
10939             _boundary.splice( _boundary.end(), _boundary, _boundary.begin() );
10940         }
10941         if ( !equalBoundary )
10942           continue;
10943
10944         // check connectivity
10945         std::set<const SMDS_MeshElement*> elemsThis, elemsOther;
10946         this->GetElements( elemsThis  );
10947         other.GetElements( elemsOther );
10948         SMESH_MeshEditor::Sew_Error err =
10949           SMESH_MeshEditor::FindMatchingNodes( elemsThis, elemsOther,
10950                                                this->_boundary.front().Node(0),
10951                                                other._boundary.front().Node(0),
10952                                                this->_boundary.front().Node(1),
10953                                                other._boundary.front().Node(1),
10954                                                periodic._nnMap );
10955         if ( err != SMESH_MeshEditor::SEW_OK )
10956           continue;
10957
10958         // check node positions
10959         std::vector< gp_XYZ > srcPnts, tgtPnts;
10960         this->GetBoundaryPoints( srcPnts );
10961         other.GetBoundaryPoints( tgtPnts );
10962         if ( !periodic._trsf.Solve( srcPnts, tgtPnts )) {
10963           continue;
10964         }
10965         double tol = std::numeric_limits<double>::max(); // tolerance by segment size
10966         for ( size_t i = 1; i < srcPnts.size(); ++i ) {
10967           tol = Min( tol, ( srcPnts[i-1] - srcPnts[i] ).SquareModulus() );
10968         }
10969         tol = 0.01 * Sqrt( tol );
10970         for ( BndPart& boundary : _boundary ) { // tolerance by VL thickness
10971           if ( boundary._isShrink )
10972             tol = Min( tol, boundary._hyp->Get1stLayerThickness() / 50. );
10973         }
10974         bool nodeCoincide = true;
10975         TNodeNodeMap::iterator n2n = periodic._nnMap.begin();
10976         for ( ; n2n != periodic._nnMap.end() &&  nodeCoincide; ++n2n )
10977         {
10978           SMESH_NodeXYZ nSrc = n2n->first;
10979           SMESH_NodeXYZ nTgt = n2n->second;
10980           gp_XYZ pTgt = periodic._trsf.Transform( nSrc );
10981           nodeCoincide = (( pTgt - nTgt ).SquareModulus() < tol * tol );
10982         }
10983         if ( nodeCoincide )
10984           return true;
10985       }
10986       return false;
10987     }
10988
10989     bool IsSameNbElements( ShrinkFace& other ) // check number of mesh faces
10990     {
10991       SMESHDS_SubMesh* sm1 = this->_subMesh->GetSubMeshDS();
10992       SMESHDS_SubMesh* sm2 = other._subMesh->GetSubMeshDS();
10993       return ( sm1->NbElements() == sm2->NbElements() &&
10994                sm1->NbNodes()    == sm2->NbNodes() );
10995     }
10996
10997     void Reverse( std::list< BndPart >& boundary )
10998     {
10999       boundary.reverse();
11000       for ( std::list< BndPart >::iterator part = boundary.begin(); part != boundary.end(); ++part )
11001         part->Reverse();
11002     }
11003
11004     void SetBoundary()
11005     {
11006       if ( !_boundary.empty() )
11007         return;
11008
11009       TopoDS_Face F = TopoDS::Face( _subMesh->GetSubShape() );
11010       if ( F.Orientation() >= TopAbs_INTERNAL ) F.Orientation( TopAbs_FORWARD );
11011       std::list< TopoDS_Edge > edges;
11012       std::list< int > nbEdgesInWire;
11013       /*int nbWires =*/ SMESH_Block::GetOrderedEdges (F, edges, nbEdgesInWire);
11014
11015       // std::list< TopoDS_Edge >::iterator edgesEnd = edges.end();
11016       // if ( nbWires > 1 ) {
11017       //   edgesEnd = edges.begin();
11018       //   std::advance( edgesEnd, nbEdgesInWire.front() );
11019       // }
11020       StdMeshers_FaceSide fSide( F, edges, _subMesh->GetFather(),
11021                                  /*fwd=*/true, /*skipMedium=*/true );
11022       _boundarySize = fSide.NbSegments();
11023
11024       //TopoDS_Vertex vv[2];
11025       //std::list< TopoDS_Edge >::iterator edgeIt = edges.begin();
11026       for ( int iE = 0; iE < nbEdgesInWire.front(); ++iE )
11027       {
11028         BndPart bndPart;
11029         _EdgesOnShape*  eos = _data1->GetShapeEdges( fSide.EdgeID( iE ));
11030
11031         bndPart._isShrink = ( eos->SWOLType() == TopAbs_FACE );
11032         if ( bndPart._isShrink )
11033           if ((           _data1->_noShrinkShapes.count( eos->_shapeID )) ||
11034               ( _data2 && _data2->_noShrinkShapes.count( eos->_shapeID )))
11035             bndPart._isShrink = false;
11036
11037         if ( bndPart._isShrink )
11038         {
11039           bndPart._hyp = & eos->_hyp;
11040           _EdgesOnShape* eov[2] = { _data1->GetShapeEdges( fSide.FirstVertex( iE )),
11041                                     _data1->GetShapeEdges( fSide.LastVertex ( iE )) };
11042           for ( int iV = 0; iV < 2; ++iV )
11043           {
11044             bndPart._vertHyp     [iV] = & eov[iV]->_hyp;
11045             bndPart._vertSWOLType[iV] = eov[iV]->SWOLType();
11046             if ( _data1->_noShrinkShapes.count( eov[iV]->_shapeID ))
11047               bndPart._vertSWOLType[iV] = TopAbs_SHAPE;
11048             if ( _data2 && bndPart._vertSWOLType[iV] != TopAbs_SHAPE )
11049             {
11050               eov[iV] = _data2->GetShapeEdges( iV ? fSide.LastVertex(iE) : fSide.FirstVertex(iE ));
11051               if ( _data2->_noShrinkShapes.count( eov[iV]->_shapeID ))
11052                 bndPart._vertSWOLType[iV] = TopAbs_SHAPE;
11053               else if ( eov[iV]->SWOLType() > bndPart._vertSWOLType[iV] )
11054                 bndPart._vertSWOLType[iV] = eov[iV]->SWOLType();
11055             }
11056           }
11057         }
11058         std::vector<const SMDS_MeshNode*> nodes = fSide.GetOrderedNodes( iE );
11059         bndPart._nodes.assign( nodes.begin(), nodes.end() );
11060         bndPart._nbSegments = bndPart._nodes.size() - 1;
11061
11062         if ( _boundary.empty() || ! _boundary.back().CanAppend( bndPart ))
11063           _boundary.push_back( bndPart );
11064         else
11065           _boundary.back().Append( bndPart );
11066       }
11067
11068       _nbBoundaryParts = _boundary.size();
11069       if ( _nbBoundaryParts > 1 && _boundary.front()._isShrink == _boundary.back()._isShrink )
11070       {
11071         _boundary.back().Append( _boundary.front() );
11072         _boundary.pop_front();
11073         --_nbBoundaryParts;
11074       }
11075     }
11076
11077     void GetElements( std::set<const SMDS_MeshElement*>& theElems)
11078     {
11079       if ( SMESHDS_SubMesh* sm = _subMesh->GetSubMeshDS() )
11080         for ( SMDS_ElemIteratorPtr fIt = sm->GetElements(); fIt->more(); )
11081           theElems.insert( theElems.end(), fIt->next() );
11082
11083       return ;
11084     }
11085
11086     void GetBoundaryPoints( std::vector< gp_XYZ >& points )
11087     {
11088       points.reserve( _boundarySize );
11089       size_t  nb = _boundary.rbegin()->_nodes.size();
11090       smIdType lastID = _boundary.rbegin()->Node( nb - 1 )->GetID();
11091       std::list< BndPart >::const_iterator part = _boundary.begin();
11092       for ( ; part != _boundary.end(); ++part )
11093       {
11094         size_t nb = part->_nodes.size();
11095         size_t iF = 0;
11096         size_t iR = nb - 1;
11097         size_t* i = part->_isReverse ? &iR : &iF;
11098         if ( part->_nodes[ *i ]->GetID() == lastID )
11099           ++iF, --iR;
11100         for ( ; iF < nb; ++iF, --iR )
11101           points.push_back( part->_nodes[ *i ]);
11102         --iF, ++iR;
11103         lastID = part->_nodes[ *i ]->GetID();
11104       }
11105     }
11106   }; // struct ShrinkFace
11107
11108   //--------------------------------------------------------------------------------
11109   /*!
11110    * \brief Periodic FACEs
11111    */
11112   struct Periodicity
11113   {
11114     std::vector< ShrinkFace >    _shrinkFaces;
11115     std::vector< PeriodicFaces > _periodicFaces;
11116
11117     PeriodicFaces* GetPeriodic( const TopoDS_Face& face, const TopTools_MapOfShape& shrunkFaces )
11118     {
11119       for ( size_t i = 0; i < _periodicFaces.size(); ++i )
11120         if ( _periodicFaces[ i ].IncludeShrunk( face, shrunkFaces ))
11121           return & _periodicFaces[ i ];
11122       return 0;
11123     }
11124     void ClearPeriodic( const TopoDS_Face& face )
11125     {
11126       for ( size_t i = 0; i < _periodicFaces.size(); ++i )
11127         if ( _periodicFaces[ i ]._shriFace[0]->IsSame( face ) ||
11128              _periodicFaces[ i ]._shriFace[1]->IsSame( face ))
11129           _periodicFaces[ i ].Clear();
11130     }
11131   };
11132
11133   //================================================================================
11134   /*!
11135    * Check if a pair includes the given FACE and the other FACE is already shrunk
11136    */
11137   bool PeriodicFaces::IncludeShrunk( const TopoDS_Face&         face,
11138                                      const TopTools_MapOfShape& shrunkFaces ) const
11139   {
11140     if ( IsEmpty() ) return false;
11141     return (( _shriFace[0]->IsSame( face ) && _shriFace[1]->IsShrunk( shrunkFaces )) ||
11142             ( _shriFace[1]->IsSame( face ) && _shriFace[0]->IsShrunk( shrunkFaces )));
11143   }
11144
11145   //================================================================================
11146   /*!
11147    * Make equal meshes on periodic faces by moving corresponding nodes
11148    */
11149   bool PeriodicFaces::MoveNodes( const TopoDS_Face& tgtFace )
11150   {
11151     int iTgt = _shriFace[1]->IsSame( tgtFace );
11152     int iSrc = 1 - iTgt;
11153
11154     _SolidData* dataSrc = _shriFace[iSrc]->_data1;
11155     _SolidData* dataTgt = _shriFace[iTgt]->_data1;
11156
11157     Trsf * trsf = & _trsf, trsfInverse;
11158     if ( iSrc != 0 )
11159     {
11160       trsfInverse = _trsf;
11161       if ( !trsfInverse.Invert())
11162         return false;
11163       trsf = &trsfInverse;
11164     }
11165     SMESHDS_Mesh* meshDS = dataSrc->GetHelper().GetMeshDS();
11166
11167     TNode2Edge::iterator n2e;
11168     TNodeNodeMap::iterator n2n = _nnMap.begin();
11169     for ( ; n2n != _nnMap.end(); ++n2n )
11170     {
11171       const SMDS_MeshNode* const* nn = & n2n->first;
11172       const SMDS_MeshNode*      nSrc = nn[ iSrc ];
11173       const SMDS_MeshNode*      nTgt = nn[ iTgt ];
11174
11175       if (( nSrc->GetPosition()->GetDim() == 2 ) ||
11176           (( n2e = dataSrc->_n2eMap.find( nSrc )) == dataSrc->_n2eMap.end() ))
11177       {
11178         SMESH_NodeXYZ pSrc = nSrc;
11179         gp_XYZ pTgt = trsf->Transform( pSrc );
11180         meshDS->MoveNode( nTgt, pTgt.X(), pTgt.Y(), pTgt.Z() );
11181       }
11182       else
11183       {
11184         _LayerEdge* leSrc = n2e->second;
11185         n2e = dataTgt->_n2eMap.find( nTgt );
11186         if ( n2e == dataTgt->_n2eMap.end() )
11187           break;
11188         _LayerEdge* leTgt = n2e->second;
11189         if ( leSrc->_nodes.size() != leTgt->_nodes.size() )
11190           break;
11191         for ( size_t iN = 1; iN < leSrc->_nodes.size(); ++iN )
11192         {
11193           SMESH_NodeXYZ pSrc = leSrc->_nodes[ iN ];
11194           gp_XYZ pTgt = trsf->Transform( pSrc );
11195           meshDS->MoveNode( leTgt->_nodes[ iN ], pTgt.X(), pTgt.Y(), pTgt.Z() );
11196         }
11197       }
11198     }
11199     bool done = ( n2n == _nnMap.end() );
11200     debugMsg( "PeriodicFaces::MoveNodes "
11201               << _shriFace[iSrc]->_subMesh->GetId() << " -> "
11202               << _shriFace[iTgt]->_subMesh->GetId() << " -- "
11203               << ( done ? "DONE" : "FAIL"));
11204
11205     return done;
11206   }
11207 } // namespace VISCOUS_3D; Periodicity part
11208
11209
11210 //================================================================================
11211 /*!
11212  * \brief Find FACEs to shrink, that are equally meshed before shrink (i.e. periodic)
11213  *        and should remain equal after shrink
11214  */
11215 //================================================================================
11216
11217 void _ViscousBuilder::findPeriodicFaces()
11218 {
11219   // make map of (ids of FACEs to shrink mesh on) to (list of _SolidData containing
11220   // _LayerEdge's inflated along FACE or EDGE)
11221   std::map< TGeomID, std::list< _SolidData* > > id2sdMap;
11222   for ( size_t i = 0 ; i < _sdVec.size(); ++i )
11223   {
11224     _SolidData& data = _sdVec[i];
11225     std::map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
11226     for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
11227       if ( s2s->second.ShapeType() == TopAbs_FACE )
11228         id2sdMap[ getMeshDS()->ShapeToIndex( s2s->second )].push_back( &data );
11229   }
11230
11231   _periodicity.reset( new Periodicity );
11232   _periodicity->_shrinkFaces.resize( id2sdMap.size() );
11233
11234   std::map< TGeomID, std::list< _SolidData* > >::iterator id2sdIt = id2sdMap.begin();
11235   for ( size_t i = 0; i < id2sdMap.size(); ++i, ++id2sdIt )
11236   {
11237     _SolidData* sd1 = id2sdIt->second.front();
11238     _SolidData* sd2 = id2sdIt->second.back();
11239     _periodicity->_shrinkFaces[ i ].Init( _mesh->GetSubMeshContaining( id2sdIt->first ), sd1, sd2 );
11240   }
11241
11242   for (   size_t i1 = 0;      i1 < _periodicity->_shrinkFaces.size(); ++i1 )
11243     for ( size_t i2 = i1 + 1; i2 < _periodicity->_shrinkFaces.size(); ++i2 )
11244     {
11245       PeriodicFaces pf( & _periodicity->_shrinkFaces[ i1 ],
11246                         & _periodicity->_shrinkFaces[ i2 ]);
11247       if ( pf._shriFace[0]->IsPeriodic( *pf._shriFace[1], pf ))
11248       {
11249         _periodicity->_periodicFaces.push_back( pf );
11250       }
11251     }
11252   return;
11253 }
11254
11255 //================================================================================
11256 /*!
11257  * \brief Shrink 2D mesh on faces to let space for inflated layers
11258  */
11259 //================================================================================
11260
11261 bool _ViscousBuilder::shrink(_SolidData& theData)
11262 {
11263   // make map of (ids of FACEs to shrink mesh on) to (list of _SolidData containing
11264   // _LayerEdge's inflated along FACE or EDGE)
11265   map< TGeomID, list< _SolidData* > > f2sdMap;
11266   for ( size_t i = 0 ; i < _sdVec.size(); ++i )
11267   {
11268     _SolidData& data = _sdVec[i];
11269     map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
11270     for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
11271       if ( s2s->second.ShapeType() == TopAbs_FACE && !_shrunkFaces.Contains( s2s->second ))
11272       {
11273         f2sdMap[ getMeshDS()->ShapeToIndex( s2s->second )].push_back( &data );
11274
11275         // Put mesh faces on the shrunk FACE to the proxy sub-mesh to avoid
11276         // usage of mesh faces made in addBoundaryElements() by the 3D algo or
11277         // by StdMeshers_QuadToTriaAdaptor
11278         if ( SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( s2s->second ))
11279         {
11280           SMESH_ProxyMesh::SubMesh* proxySub =
11281             data._proxyMesh->getFaceSubM( TopoDS::Face( s2s->second ), /*create=*/true);
11282           if ( proxySub->NbElements() == 0 )
11283           {
11284             SMDS_ElemIteratorPtr fIt = smDS->GetElements();
11285             while ( fIt->more() )
11286             {
11287               const SMDS_MeshElement* f = fIt->next();
11288               // as a result 3D algo will use elements from proxySub and not from smDS
11289               proxySub->AddElement( f );
11290               f->setIsMarked( true );
11291
11292               // Mark nodes on the FACE to discriminate them from nodes
11293               // added by addBoundaryElements(); marked nodes are to be smoothed while shrink()
11294               for ( int iN = 0, nbN = f->NbNodes(); iN < nbN; ++iN )
11295               {
11296                 const SMDS_MeshNode* n = f->GetNode( iN );
11297                 if ( n->GetPosition()->GetDim() == 2 )
11298                   n->setIsMarked( true );
11299               }
11300             }
11301           }
11302         }
11303       }
11304   }
11305
11306   SMESH_MesherHelper helper( *_mesh );
11307   helper.ToFixNodeParameters( true );
11308
11309   // EDGEs to shrink
11310   map< TGeomID, _Shrinker1D > e2shrMap;
11311   vector< _EdgesOnShape* > subEOS;
11312   vector< _LayerEdge* > lEdges;
11313
11314   // loop on FACEs to shrink mesh on
11315   map< TGeomID, list< _SolidData* > >::iterator f2sd = f2sdMap.begin();
11316   for ( ; f2sd != f2sdMap.end(); ++f2sd )
11317   {
11318     list< _SolidData* > & dataList = f2sd->second;
11319     if ( dataList.front()->_n2eMap.empty() ||
11320          dataList.back() ->_n2eMap.empty() )
11321       continue; // not yet computed
11322     if ( dataList.front() != &theData &&
11323          dataList.back()  != &theData )
11324       continue;
11325
11326     _SolidData&      data = *dataList.front();
11327     _SolidData*     data2 = dataList.size() > 1 ? dataList.back() : 0;
11328     const TopoDS_Face&  F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
11329     SMESH_subMesh*     sm = _mesh->GetSubMesh( F );
11330     SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
11331
11332     Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
11333
11334     _shrunkFaces.Add( F );
11335     helper.SetSubShape( F );
11336
11337     // ==============================
11338     // Use periodicity to move nodes
11339     // ==============================
11340
11341     PeriodicFaces* periodic = _periodicity->GetPeriodic( F, _shrunkFaces );
11342     bool movedByPeriod = ( periodic && periodic->MoveNodes( F ));
11343
11344     // ===========================
11345     // Prepare data for shrinking
11346     // ===========================
11347
11348     // Collect nodes to smooth (they are marked at the beginning of this method)
11349     vector < const SMDS_MeshNode* > smoothNodes;
11350
11351     if ( !movedByPeriod )
11352     {
11353       SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
11354       while ( nIt->more() )
11355       {
11356         const SMDS_MeshNode* n = nIt->next();
11357         if ( n->isMarked() )
11358           smoothNodes.push_back( n );
11359       }
11360     }
11361     // Find out face orientation
11362     double refSign = 1;
11363     const set<TGeomID> ignoreShapes;
11364     bool isOkUV;
11365     if ( !smoothNodes.empty() )
11366     {
11367       vector<_Simplex> simplices;
11368       _Simplex::GetSimplices( smoothNodes[0], simplices, ignoreShapes );
11369       helper.GetNodeUV( F, simplices[0]._nPrev, 0, &isOkUV ); // fix UV of simplex nodes
11370       helper.GetNodeUV( F, simplices[0]._nNext, 0, &isOkUV );
11371       gp_XY uv = helper.GetNodeUV( F, smoothNodes[0], 0, &isOkUV );
11372       if ( !simplices[0].IsForward(uv, smoothNodes[0], F, helper, refSign ))
11373         refSign = -1;
11374     }
11375
11376     // Find _LayerEdge's inflated along F
11377     subEOS.clear();
11378     lEdges.clear();
11379     {
11380       SMESH_subMeshIteratorPtr subIt = sm->getDependsOnIterator(/*includeSelf=*/false,
11381                                                                 /*complexFirst=*/true); //!!!
11382       while ( subIt->more() )
11383       {
11384         const TGeomID subID = subIt->next()->GetId();
11385         if ( data._noShrinkShapes.count( subID ))
11386           continue;
11387         _EdgesOnShape* eos = data.GetShapeEdges( subID );
11388         if ( !eos || eos->_sWOL.IsNull() )
11389           if ( data2 ) // check in adjacent SOLID
11390           {
11391             eos = data2->GetShapeEdges( subID );
11392             if ( !eos || eos->_sWOL.IsNull() )
11393               continue;
11394           }
11395         subEOS.push_back( eos );
11396
11397         if ( !movedByPeriod )
11398           for ( size_t i = 0; i < eos->_edges.size(); ++i )
11399           {
11400             lEdges.push_back( eos->_edges[ i ] );
11401             prepareEdgeToShrink( *eos->_edges[ i ], *eos, helper, smDS );
11402           }
11403       }
11404     }
11405
11406     dumpFunction(SMESH_Comment("beforeShrinkFace")<<f2sd->first); // debug
11407     SMDS_ElemIteratorPtr fIt = smDS->GetElements();
11408     while ( fIt->more() )
11409       if ( const SMDS_MeshElement* f = fIt->next() )
11410         dumpChangeNodes( f );
11411     dumpFunctionEnd();
11412
11413     // Replace source nodes by target nodes in mesh faces to shrink
11414     dumpFunction(SMESH_Comment("replNodesOnFace")<<f2sd->first); // debug
11415     const SMDS_MeshNode* nodes[20];
11416     for ( size_t iS = 0; iS < subEOS.size(); ++iS )
11417     {
11418       _EdgesOnShape& eos = * subEOS[ iS ];
11419       for ( size_t i = 0; i < eos._edges.size(); ++i )
11420       {
11421         _LayerEdge& edge = *eos._edges[i];
11422         const SMDS_MeshNode* srcNode = edge._nodes[0];
11423         const SMDS_MeshNode* tgtNode = edge._nodes.back();
11424         SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
11425         while ( fIt->more() )
11426         {
11427           const SMDS_MeshElement* f = fIt->next();
11428           if ( !smDS->Contains( f ) || !f->isMarked() )
11429             continue;
11430           SMDS_NodeIteratorPtr nIt = f->nodeIterator();
11431           for ( int iN = 0; nIt->more(); ++iN )
11432           {
11433             const SMDS_MeshNode* n = nIt->next();
11434             nodes[iN] = ( n == srcNode ? tgtNode : n );
11435           }
11436           helper.GetMeshDS()->ChangeElementNodes( f, nodes, f->NbNodes() );
11437           dumpChangeNodes( f );
11438         }
11439       }
11440     }
11441     dumpFunctionEnd();
11442
11443     // find out if a FACE is concave
11444     const bool isConcaveFace = isConcave( F, helper );
11445
11446     // Create _SmoothNode's on face F
11447     vector< _SmoothNode > nodesToSmooth( smoothNodes.size() );
11448     {
11449       dumpFunction(SMESH_Comment("fixUVOnFace")<<f2sd->first); // debug
11450       const bool sortSimplices = isConcaveFace;
11451       for ( size_t i = 0; i < smoothNodes.size(); ++i )
11452       {
11453         const SMDS_MeshNode* n = smoothNodes[i];
11454         nodesToSmooth[ i ]._node = n;
11455         // src nodes must be already replaced by tgt nodes to have tgt nodes in _simplices
11456         _Simplex::GetSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes, 0, sortSimplices);
11457         // fix up incorrect uv of nodes on the FACE
11458         helper.GetNodeUV( F, n, 0, &isOkUV);
11459         dumpMove( n );
11460       }
11461       dumpFunctionEnd();
11462     }
11463     //if ( nodesToSmooth.empty() ) continue;
11464
11465     // Find EDGE's to shrink and set simpices to LayerEdge's
11466     set< _Shrinker1D* > eShri1D;
11467     {
11468       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
11469       {
11470         _EdgesOnShape& eos = * subEOS[ iS ];
11471         if ( eos.SWOLType() == TopAbs_EDGE )
11472         {
11473           SMESH_subMesh* edgeSM = _mesh->GetSubMesh( eos._sWOL );
11474           VISCOUS_3D::ToClearSubWithMain( edgeSM, data._solid );
11475           if ( !movedByPeriod )
11476           {
11477             _Shrinker1D& shrinker = e2shrMap[ edgeSM->GetId() ];
11478             eShri1D.insert( & shrinker );
11479             shrinker.AddEdge( eos._edges[0], eos, helper );
11480             // restore params of nodes on EDGE if the EDGE has been already
11481             // shrunk while shrinking other FACE
11482             shrinker.RestoreParams();
11483           }
11484         }
11485         for ( size_t i = 0; i < eos._edges.size(); ++i )
11486         {
11487           _LayerEdge& edge = * eos._edges[i];
11488           _Simplex::GetSimplices( /*tgtNode=*/edge._nodes.back(), edge._simplices, ignoreShapes );
11489
11490           // additionally mark tgt node; only marked nodes will be used in SetNewLength2d()
11491           // not-marked nodes are those added by refine()
11492           edge._nodes.back()->setIsMarked( true );
11493         }
11494       }
11495     }
11496
11497     bool toFixTria = false; // to improve quality of trias by diagonal swap
11498     if ( isConcaveFace && !movedByPeriod )
11499     {
11500       const bool hasTria = _mesh->NbTriangles(), hasQuad = _mesh->NbQuadrangles();
11501       if ( hasTria != hasQuad ) {
11502         toFixTria = hasTria;
11503       }
11504       else {
11505         set<int> nbNodesSet;
11506         SMDS_ElemIteratorPtr fIt = smDS->GetElements();
11507         while ( fIt->more() && nbNodesSet.size() < 2 )
11508           nbNodesSet.insert( fIt->next()->NbCornerNodes() );
11509         toFixTria = ( *nbNodesSet.begin() == 3 );
11510       }
11511     }
11512
11513     // ==================
11514     // Perform shrinking
11515     // ==================
11516
11517     bool shrunk = !movedByPeriod;
11518     int nbBad, shriStep=0, smooStep=0;
11519     _SmoothNode::SmoothType smoothType
11520       = isConcaveFace ? _SmoothNode::ANGULAR : _SmoothNode::LAPLACIAN;
11521     SMESH_Comment errMsg;
11522     while ( shrunk )
11523     {
11524       shriStep++;
11525       // Move boundary nodes (actually just set new UV)
11526       // -----------------------------------------------
11527       dumpFunction(SMESH_Comment("moveBoundaryOnF")<<f2sd->first<<"_st"<<shriStep ); // debug
11528       shrunk = false;
11529       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
11530       {
11531         _EdgesOnShape& eos = * subEOS[ iS ];
11532         for ( size_t i = 0; i < eos._edges.size(); ++i )
11533         {
11534           shrunk |= eos._edges[i]->SetNewLength2d( surface, F, eos, helper );
11535         }
11536       }
11537       dumpFunctionEnd();
11538
11539       // Move nodes on EDGE's
11540       // (XYZ is set as soon as a needed length reached in SetNewLength2d())
11541       set< _Shrinker1D* >::iterator shr = eShri1D.begin();
11542       for ( ; shr != eShri1D.end(); ++shr )
11543         (*shr)->Compute( /*set3D=*/false, helper );
11544
11545       // Smoothing in 2D
11546       // -----------------
11547       int nbNoImpSteps = 0;
11548       bool       moved = true;
11549       nbBad = 1;
11550       while (( nbNoImpSteps < 5 && nbBad > 0) && moved)
11551       {
11552         dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
11553
11554         int oldBadNb = nbBad;
11555         nbBad = 0;
11556         moved = false;
11557         // '% 5' minimizes NB FUNCTIONS on viscous_layers_00/B2 case
11558         _SmoothNode::SmoothType smooTy = ( smooStep % 5 ) ? smoothType : _SmoothNode::LAPLACIAN;
11559         for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
11560         {
11561           moved |= nodesToSmooth[i].Smooth( nbBad, surface, helper, refSign,
11562                                             smooTy, /*set3D=*/isConcaveFace);
11563         }
11564         if ( nbBad < oldBadNb )
11565           nbNoImpSteps = 0;
11566         else
11567           nbNoImpSteps++;
11568
11569         dumpFunctionEnd();
11570       }
11571
11572       errMsg.clear();
11573       if ( nbBad > 0 )
11574         errMsg << "Can't shrink 2D mesh on face " << f2sd->first;
11575       if ( shriStep > 200 )
11576         errMsg << "Infinite loop at shrinking 2D mesh on face " << f2sd->first;
11577       if ( !errMsg.empty() )
11578         break;
11579
11580       // Fix narrow triangles by swapping diagonals
11581       // ---------------------------------------
11582       if ( toFixTria )
11583       {
11584         set<const SMDS_MeshNode*> usedNodes;
11585         fixBadFaces( F, helper, /*is2D=*/true, shriStep, & usedNodes); // swap diagonals
11586
11587         // update working data
11588         set<const SMDS_MeshNode*>::iterator n;
11589         for ( size_t i = 0; i < nodesToSmooth.size() && !usedNodes.empty(); ++i )
11590         {
11591           n = usedNodes.find( nodesToSmooth[ i ]._node );
11592           if ( n != usedNodes.end())
11593           {
11594             _Simplex::GetSimplices( nodesToSmooth[ i ]._node,
11595                                     nodesToSmooth[ i ]._simplices,
11596                                     ignoreShapes, NULL,
11597                                     /*sortSimplices=*/ smoothType == _SmoothNode::ANGULAR );
11598             usedNodes.erase( n );
11599           }
11600         }
11601         for ( size_t i = 0; i < lEdges.size() && !usedNodes.empty(); ++i )
11602         {
11603           n = usedNodes.find( /*tgtNode=*/ lEdges[i]->_nodes.back() );
11604           if ( n != usedNodes.end())
11605           {
11606             _Simplex::GetSimplices( lEdges[i]->_nodes.back(),
11607                                     lEdges[i]->_simplices,
11608                                     ignoreShapes );
11609             usedNodes.erase( n );
11610           }
11611         }
11612       }
11613       // TODO: check effect of this additional smooth
11614       // additional laplacian smooth to increase allowed shrink step
11615       // for ( int st = 1; st; --st )
11616       // {
11617       //   dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
11618       //   for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
11619       //   {
11620       //     nodesToSmooth[i].Smooth( nbBad,surface,helper,refSign,
11621       //                              _SmoothNode::LAPLACIAN,/*set3D=*/false);
11622       //   }
11623       // }
11624
11625     } // while ( shrunk )
11626
11627     if ( !errMsg.empty() ) // Try to re-compute the shrink FACE
11628     {
11629       debugMsg( "Re-compute FACE " << f2sd->first << " because " << errMsg );
11630
11631       // remove faces
11632       SMESHDS_SubMesh* psm = data._proxyMesh->getFaceSubM( F );
11633       {
11634         vector< const SMDS_MeshElement* > facesToRm;
11635         if ( psm )
11636         {
11637           facesToRm.reserve( psm->NbElements() );
11638           for ( SMDS_ElemIteratorPtr ite = psm->GetElements(); ite->more(); )
11639             facesToRm.push_back( ite->next() );
11640
11641           for ( size_t i = 0 ; i < _sdVec.size(); ++i )
11642             if (( psm = _sdVec[i]._proxyMesh->getFaceSubM( F )))
11643               psm->Clear();
11644         }
11645         for ( size_t i = 0; i < facesToRm.size(); ++i )
11646           getMeshDS()->RemoveFreeElement( facesToRm[i], smDS, /*fromGroups=*/false );
11647       }
11648       // remove nodes
11649       {
11650         TIDSortedNodeSet nodesToKeep; // nodes of _LayerEdge to keep
11651         for ( size_t iS = 0; iS < subEOS.size(); ++iS ) {
11652           for ( size_t i = 0; i < subEOS[iS]->_edges.size(); ++i )
11653             nodesToKeep.insert( ++( subEOS[iS]->_edges[i]->_nodes.begin() ),
11654                                 subEOS[iS]->_edges[i]->_nodes.end() );
11655         }
11656         SMDS_NodeIteratorPtr itn = smDS->GetNodes();
11657         while ( itn->more() ) {
11658           const SMDS_MeshNode* n = itn->next();
11659           if ( !nodesToKeep.count( n ))
11660             getMeshDS()->RemoveFreeNode( n, smDS, /*fromGroups=*/false );
11661         }
11662       }
11663       _periodicity->ClearPeriodic( F );
11664
11665       // restore position and UV of target nodes
11666       gp_Pnt p;
11667       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
11668         for ( size_t i = 0; i < subEOS[iS]->_edges.size(); ++i )
11669         {
11670           _LayerEdge*       edge = subEOS[iS]->_edges[i];
11671           SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( edge->_nodes.back() );
11672           if ( edge->_pos.empty() ||
11673                edge->Is( _LayerEdge::SHRUNK )) continue;
11674           if ( subEOS[iS]->SWOLType() == TopAbs_FACE )
11675           {
11676             SMDS_FacePositionPtr pos = tgtNode->GetPosition();
11677             pos->SetUParameter( edge->_pos[0].X() );
11678             pos->SetVParameter( edge->_pos[0].Y() );
11679             p = surface->Value( edge->_pos[0].X(), edge->_pos[0].Y() );
11680           }
11681           else
11682           {
11683             SMDS_EdgePositionPtr pos = tgtNode->GetPosition();
11684             pos->SetUParameter( edge->_pos[0].Coord( U_TGT ));
11685             p = BRepAdaptor_Curve( TopoDS::Edge( subEOS[iS]->_sWOL )).Value( pos->GetUParameter() );
11686           }
11687           tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
11688           dumpMove( tgtNode );
11689         }
11690       // shrink EDGE sub-meshes and set proxy sub-meshes
11691       UVPtStructVec uvPtVec;
11692       set< _Shrinker1D* >::iterator shrIt = eShri1D.begin();
11693       for ( shrIt = eShri1D.begin(); shrIt != eShri1D.end(); ++shrIt )
11694       {
11695         _Shrinker1D* shr = (*shrIt);
11696         shr->Compute( /*set3D=*/true, helper );
11697
11698         // set proxy mesh of EDGEs w/o layers
11699         map< double, const SMDS_MeshNode* > nodes;
11700         SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), shr->GeomEdge(),/*skipMedium=*/true, nodes);
11701         // remove refinement nodes
11702         const SMDS_MeshNode* sn0 = shr->SrcNode(0), *sn1 = shr->SrcNode(1);
11703         const SMDS_MeshNode* tn0 = shr->TgtNode(0), *tn1 = shr->TgtNode(1);
11704         map< double, const SMDS_MeshNode* >::iterator u2n = nodes.begin();
11705         if ( u2n->second == sn0 || u2n->second == sn1 )
11706         {
11707           while ( u2n->second != tn0 && u2n->second != tn1 )
11708             ++u2n;
11709           nodes.erase( nodes.begin(), u2n );
11710         }
11711         u2n = --nodes.end();
11712         if ( u2n->second == sn0 || u2n->second == sn1 )
11713         {
11714           while ( u2n->second != tn0 && u2n->second != tn1 )
11715             --u2n;
11716           nodes.erase( ++u2n, nodes.end() );
11717         }
11718         // set proxy sub-mesh
11719         uvPtVec.resize( nodes.size() );
11720         u2n = nodes.begin();
11721         BRepAdaptor_Curve2d curve( shr->GeomEdge(), F );
11722         for ( size_t i = 0; i < nodes.size(); ++i, ++u2n )
11723         {
11724           uvPtVec[ i ].node = u2n->second;
11725           uvPtVec[ i ].param = u2n->first;
11726           uvPtVec[ i ].SetUV( curve.Value( u2n->first ).XY() );
11727         }
11728         StdMeshers_FaceSide fSide( uvPtVec, F, shr->GeomEdge(), _mesh );
11729         StdMeshers_ViscousLayers2D::SetProxyMeshOfEdge( fSide );
11730       }
11731
11732       // set proxy mesh of EDGEs with layers
11733       vector< _LayerEdge* > edges;
11734       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
11735       {
11736         _EdgesOnShape& eos = * subEOS[ iS ];
11737         if ( eos.ShapeType() != TopAbs_EDGE ) continue;
11738
11739         const TopoDS_Edge& E = TopoDS::Edge( eos._shape );
11740         data.SortOnEdge( E, eos._edges );
11741
11742         edges.clear();
11743         if ( _EdgesOnShape* eov = data.GetShapeEdges( helper.IthVertex( 0, E, /*CumOri=*/false )))
11744           if ( !eov->_edges.empty() )
11745             edges.push_back( eov->_edges[0] ); // on 1st VERTEX
11746
11747         edges.insert( edges.end(), eos._edges.begin(), eos._edges.end() );
11748
11749         if ( _EdgesOnShape* eov = data.GetShapeEdges( helper.IthVertex( 1, E, /*CumOri=*/false )))
11750           if ( !eov->_edges.empty() )
11751             edges.push_back( eov->_edges[0] ); // on last VERTEX
11752
11753         uvPtVec.resize( edges.size() );
11754         for ( size_t i = 0; i < edges.size(); ++i )
11755         {
11756           uvPtVec[ i ].node = edges[i]->_nodes.back();
11757           uvPtVec[ i ].param = helper.GetNodeU( E, edges[i]->_nodes[0] );
11758           uvPtVec[ i ].SetUV( helper.GetNodeUV( F, edges[i]->_nodes.back() ));
11759         }
11760         if ( edges.empty() )
11761           continue;
11762         BRep_Tool::Range( E, uvPtVec[0].param, uvPtVec.back().param );
11763         StdMeshers_FaceSide fSide( uvPtVec, F, E, _mesh );
11764         StdMeshers_ViscousLayers2D::SetProxyMeshOfEdge( fSide );
11765       }
11766       // temporary clear the FACE sub-mesh from faces made by refine()
11767       vector< const SMDS_MeshElement* > elems;
11768       elems.reserve( smDS->NbElements() + smDS->NbNodes() );
11769       for ( SMDS_ElemIteratorPtr ite = smDS->GetElements(); ite->more(); )
11770         elems.push_back( ite->next() );
11771       for ( SMDS_NodeIteratorPtr ite = smDS->GetNodes(); ite->more(); )
11772         elems.push_back( ite->next() );
11773       smDS->Clear();
11774
11775       // compute the mesh on the FACE
11776       sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
11777       sm->ComputeStateEngine( SMESH_subMesh::COMPUTE_SUBMESH );
11778
11779       // re-fill proxy sub-meshes of the FACE
11780       for ( size_t i = 0 ; i < _sdVec.size(); ++i )
11781         if (( psm = _sdVec[i]._proxyMesh->getFaceSubM( F )))
11782           for ( SMDS_ElemIteratorPtr ite = smDS->GetElements(); ite->more(); )
11783             psm->AddElement( ite->next() );
11784
11785       // re-fill smDS
11786       for ( size_t i = 0; i < elems.size(); ++i )
11787         smDS->AddElement( elems[i] );
11788
11789       if ( sm->GetComputeState() != SMESH_subMesh::COMPUTE_OK )
11790         return error( errMsg );
11791
11792     } // end of re-meshing in case of failed smoothing
11793     else if ( !movedByPeriod )
11794     {
11795       // No wrongly shaped faces remain; final smooth. Set node XYZ.
11796       bool isStructuredFixed = false;
11797       if ( SMESH_2D_Algo* algo = dynamic_cast<SMESH_2D_Algo*>( sm->GetAlgo() ))
11798         isStructuredFixed = algo->FixInternalNodes( *data._proxyMesh, F );
11799       if ( !isStructuredFixed )
11800       {
11801         if ( isConcaveFace ) // fix narrow faces by swapping diagonals
11802           fixBadFaces( F, helper, /*is2D=*/false, ++shriStep );
11803
11804         for ( int st = 3; st; --st )
11805         {
11806           switch( st ) {
11807           case 1: smoothType = _SmoothNode::LAPLACIAN; break;
11808           case 2: smoothType = _SmoothNode::LAPLACIAN; break;
11809           case 3: smoothType = _SmoothNode::ANGULAR; break;
11810           }
11811           dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
11812           for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
11813           {
11814             nodesToSmooth[i].Smooth( nbBad,surface,helper,refSign,
11815                                      smoothType,/*set3D=*/st==1 );
11816           }
11817           dumpFunctionEnd();
11818         }
11819       }
11820       if ( !getMeshDS()->IsEmbeddedMode() )
11821         // Log node movement
11822         for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
11823         {
11824           SMESH_TNodeXYZ p ( nodesToSmooth[i]._node );
11825           getMeshDS()->MoveNode( nodesToSmooth[i]._node, p.X(), p.Y(), p.Z() );
11826         }
11827     }
11828
11829     // Set an event listener to clear FACE sub-mesh together with SOLID sub-mesh
11830     VISCOUS_3D::ToClearSubWithMain( sm, data._solid );
11831     if ( data2 )
11832       VISCOUS_3D::ToClearSubWithMain( sm, data2->_solid );
11833
11834   } // loop on FACES to shrink mesh on
11835
11836
11837   // Replace source nodes by target nodes in shrunk mesh edges
11838
11839   map< int, _Shrinker1D >::iterator e2shr = e2shrMap.begin();
11840   for ( ; e2shr != e2shrMap.end(); ++e2shr )
11841     e2shr->second.SwapSrcTgtNodes( getMeshDS() );
11842
11843   return true;
11844 }
11845
11846 //================================================================================
11847 /*!
11848  * \brief Computes 2d shrink direction and finds nodes limiting shrinking
11849  */
11850 //================================================================================
11851
11852 bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge&            edge,
11853                                            _EdgesOnShape&         eos,
11854                                            SMESH_MesherHelper&    helper,
11855                                            const SMESHDS_SubMesh* /*faceSubMesh*/)
11856 {
11857   const SMDS_MeshNode* srcNode = edge._nodes[0];
11858   const SMDS_MeshNode* tgtNode = edge._nodes.back();
11859
11860   if ( eos.SWOLType() == TopAbs_FACE )
11861   {
11862     if ( tgtNode->GetPosition()->GetDim() != 2 ) // not inflated edge
11863     {
11864       edge._pos.clear();
11865       edge.Set( _LayerEdge::SHRUNK );
11866       return srcNode == tgtNode;
11867     }
11868     gp_XY srcUV ( edge._pos[0].X(), edge._pos[0].Y() );          //helper.GetNodeUV( F, srcNode );
11869     gp_XY tgtUV = edge.LastUV( TopoDS::Face( eos._sWOL ), eos ); //helper.GetNodeUV( F, tgtNode );
11870     gp_Vec2d uvDir( srcUV, tgtUV );
11871     double uvLen = uvDir.Magnitude();
11872     uvDir /= uvLen;
11873     edge._normal.SetCoord( uvDir.X(),uvDir.Y(), 0 );
11874     edge._len = uvLen;
11875
11876     //edge._pos.resize(1);
11877     edge._pos[0].SetCoord( tgtUV.X(), tgtUV.Y(), 0 );
11878
11879     // set UV of source node to target node
11880     SMDS_FacePositionPtr pos = tgtNode->GetPosition();
11881     pos->SetUParameter( srcUV.X() );
11882     pos->SetVParameter( srcUV.Y() );
11883   }
11884   else // _sWOL is TopAbs_EDGE
11885   {
11886     if ( tgtNode->GetPosition()->GetDim() != 1 ) // not inflated edge
11887     {
11888       edge._pos.clear();
11889       edge.Set( _LayerEdge::SHRUNK );
11890       return srcNode == tgtNode;
11891     }
11892     const TopoDS_Edge&    E = TopoDS::Edge( eos._sWOL );
11893     SMESHDS_SubMesh* edgeSM = getMeshDS()->MeshElements( E );
11894     if ( !edgeSM || edgeSM->NbElements() == 0 )
11895       return error(SMESH_Comment("Not meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
11896
11897     const SMDS_MeshNode* n2 = 0;
11898     SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
11899     while ( eIt->more() && !n2 )
11900     {
11901       const SMDS_MeshElement* e = eIt->next();
11902       if ( !edgeSM->Contains(e)) continue;
11903       n2 = e->GetNode( 0 );
11904       if ( n2 == srcNode ) n2 = e->GetNode( 1 );
11905     }
11906     if ( !n2 )
11907       return error(SMESH_Comment("Wrongly meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
11908
11909     if ( n2 == tgtNode       || // for 3D_mesh_GHS3D_01/B1
11910          n2 == edge._nodes[1] ) // bos #20643
11911     {
11912       // shrunk by other SOLID
11913       edge.Set( _LayerEdge::SHRUNK ); // ???
11914       return true;
11915     }
11916
11917     double uSrc = helper.GetNodeU( E, srcNode, n2 );
11918     double uTgt = helper.GetNodeU( E, tgtNode, srcNode );
11919     double u2   = helper.GetNodeU( E, n2,      srcNode );
11920
11921     //edge._pos.clear();
11922
11923     if ( fabs( uSrc-uTgt ) < 0.99 * fabs( uSrc-u2 ))
11924     {
11925       // tgtNode is located so that it does not make faces with wrong orientation
11926       edge.Set( _LayerEdge::SHRUNK );
11927       return true;
11928     }
11929     //edge._pos.resize(1);
11930     edge._pos[0].SetCoord( U_TGT, uTgt );
11931     edge._pos[0].SetCoord( U_SRC, uSrc );
11932     edge._pos[0].SetCoord( LEN_TGT, fabs( uSrc-uTgt ));
11933
11934     edge._simplices.resize( 1 );
11935     edge._simplices[0]._nPrev = n2;
11936
11937     // set U of source node to the target node
11938     SMDS_EdgePositionPtr pos = tgtNode->GetPosition();
11939     pos->SetUParameter( uSrc );
11940   }
11941   return true;
11942 }
11943
11944 //================================================================================
11945 /*!
11946  * \brief Restore position of a sole node of a _LayerEdge based on _noShrinkShapes
11947  */
11948 //================================================================================
11949
11950 void _ViscousBuilder::restoreNoShrink( _LayerEdge& edge ) const
11951 {
11952   if ( edge._nodes.size() == 1 )
11953   {
11954     edge._pos.clear();
11955     edge._len = 0;
11956
11957     const SMDS_MeshNode* srcNode = edge._nodes[0];
11958     TopoDS_Shape S = SMESH_MesherHelper::GetSubShapeByNode( srcNode, getMeshDS() );
11959     if ( S.IsNull() ) return;
11960
11961     gp_Pnt p;
11962
11963     switch ( S.ShapeType() )
11964     {
11965     case TopAbs_EDGE:
11966     {
11967       double f,l;
11968       TopLoc_Location loc;
11969       Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( S ), loc, f, l );
11970       if ( curve.IsNull() ) return;
11971       SMDS_EdgePositionPtr ePos = srcNode->GetPosition();
11972       p = curve->Value( ePos->GetUParameter() );
11973       break;
11974     }
11975     case TopAbs_VERTEX:
11976     {
11977       p = BRep_Tool::Pnt( TopoDS::Vertex( S ));
11978       break;
11979     }
11980     default: return;
11981     }
11982     getMeshDS()->MoveNode( srcNode, p.X(), p.Y(), p.Z() );
11983     dumpMove( srcNode );
11984   }
11985 }
11986
11987 //================================================================================
11988 /*!
11989  * \brief Try to fix triangles with high aspect ratio by swapping diagonals
11990  */
11991 //================================================================================
11992
11993 void _ViscousBuilder::fixBadFaces(const TopoDS_Face&          F,
11994                                   SMESH_MesherHelper&         helper,
11995                                   const bool                  is2D,
11996                                   const int                   step,
11997                                   set<const SMDS_MeshNode*> * involvedNodes)
11998 {
11999   SMESH::Controls::AspectRatio qualifier;
12000   SMESH::Controls::TSequenceOfXYZ points(3), points1(3), points2(3);
12001   const double maxAspectRatio = is2D ? 4. : 2;
12002   _NodeCoordHelper xyz( F, helper, is2D );
12003
12004   // find bad triangles
12005
12006   vector< const SMDS_MeshElement* > badTrias;
12007   vector< double >                  badAspects;
12008   SMESHDS_SubMesh*      sm = helper.GetMeshDS()->MeshElements( F );
12009   SMDS_ElemIteratorPtr fIt = sm->GetElements();
12010   while ( fIt->more() )
12011   {
12012     const SMDS_MeshElement * f = fIt->next();
12013     if ( f->NbCornerNodes() != 3 ) continue;
12014     for ( int iP = 0; iP < 3; ++iP ) points(iP+1) = xyz( f->GetNode(iP));
12015     double aspect = qualifier.GetValue( points );
12016     if ( aspect > maxAspectRatio )
12017     {
12018       badTrias.push_back( f );
12019       badAspects.push_back( aspect );
12020     }
12021   }
12022   if ( step == 1 )
12023   {
12024     dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID());
12025     SMDS_ElemIteratorPtr fIt = sm->GetElements();
12026     while ( fIt->more() )
12027     {
12028       const SMDS_MeshElement * f = fIt->next();
12029       if ( f->NbCornerNodes() == 3 )
12030         dumpChangeNodes( f );
12031     }
12032     dumpFunctionEnd();
12033   }
12034   if ( badTrias.empty() )
12035     return;
12036
12037   // find couples of faces to swap diagonal
12038
12039   typedef pair < const SMDS_MeshElement* , const SMDS_MeshElement* > T2Trias;
12040   vector< T2Trias > triaCouples; 
12041
12042   TIDSortedElemSet involvedFaces, emptySet;
12043   for ( size_t iTia = 0; iTia < badTrias.size(); ++iTia )
12044   {
12045     T2Trias trias    [3];
12046     double  aspRatio [3];
12047     int i1, i2, i3;
12048
12049     if ( !involvedFaces.insert( badTrias[iTia] ).second )
12050       continue;
12051     for ( int iP = 0; iP < 3; ++iP )
12052       points(iP+1) = xyz( badTrias[iTia]->GetNode(iP));
12053
12054     // find triangles adjacent to badTrias[iTia] with better aspect ratio after diag-swaping
12055     int bestCouple = -1;
12056     for ( int iSide = 0; iSide < 3; ++iSide )
12057     {
12058       const SMDS_MeshNode* n1 = badTrias[iTia]->GetNode( iSide );
12059       const SMDS_MeshNode* n2 = badTrias[iTia]->GetNode(( iSide+1 ) % 3 );
12060       trias [iSide].first  = badTrias[iTia];
12061       trias [iSide].second = SMESH_MeshAlgos::FindFaceInSet( n1, n2, emptySet, involvedFaces,
12062                                                              & i1, & i2 );
12063       if (( ! trias[iSide].second ) ||
12064           ( trias[iSide].second->NbCornerNodes() != 3 ) ||
12065           ( ! sm->Contains( trias[iSide].second )))
12066         continue;
12067
12068       // aspect ratio of an adjacent tria
12069       for ( int iP = 0; iP < 3; ++iP )
12070         points2(iP+1) = xyz( trias[iSide].second->GetNode(iP));
12071       double aspectInit = qualifier.GetValue( points2 );
12072
12073       // arrange nodes as after diag-swaping
12074       if ( helper.WrapIndex( i1+1, 3 ) == i2 )
12075         i3 = helper.WrapIndex( i1-1, 3 );
12076       else
12077         i3 = helper.WrapIndex( i1+1, 3 );
12078       points1 = points;
12079       points1( 1+ iSide ) = points2( 1+ i3 );
12080       points2( 1+ i2    ) = points1( 1+ ( iSide+2 ) % 3 );
12081
12082       // aspect ratio after diag-swaping
12083       aspRatio[ iSide ] = qualifier.GetValue( points1 ) + qualifier.GetValue( points2 );
12084       if ( aspRatio[ iSide ] > aspectInit + badAspects[ iTia ] )
12085         continue;
12086
12087       // prevent inversion of a triangle
12088       gp_Vec norm1 = gp_Vec( points1(1), points1(3) ) ^ gp_Vec( points1(1), points1(2) );
12089       gp_Vec norm2 = gp_Vec( points2(1), points2(3) ) ^ gp_Vec( points2(1), points2(2) );
12090       if ( norm1 * norm2 < 0. && norm1.Angle( norm2 ) > 70./180.*M_PI )
12091         continue;
12092
12093       if ( bestCouple < 0 || aspRatio[ bestCouple ] > aspRatio[ iSide ] )
12094         bestCouple = iSide;
12095     }
12096
12097     if ( bestCouple >= 0 )
12098     {
12099       triaCouples.push_back( trias[bestCouple] );
12100       involvedFaces.insert ( trias[bestCouple].second );
12101     }
12102     else
12103     {
12104       involvedFaces.erase( badTrias[iTia] );
12105     }
12106   }
12107   if ( triaCouples.empty() )
12108     return;
12109
12110   // swap diagonals
12111
12112   SMESH_MeshEditor editor( helper.GetMesh() );
12113   dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
12114   for ( size_t i = 0; i < triaCouples.size(); ++i )
12115   {
12116     dumpChangeNodes( triaCouples[i].first );
12117     dumpChangeNodes( triaCouples[i].second );
12118     editor.InverseDiag( triaCouples[i].first, triaCouples[i].second );
12119   }
12120
12121   if ( involvedNodes )
12122     for ( size_t i = 0; i < triaCouples.size(); ++i )
12123     {
12124       involvedNodes->insert( triaCouples[i].first->begin_nodes(),
12125                              triaCouples[i].first->end_nodes() );
12126       involvedNodes->insert( triaCouples[i].second->begin_nodes(),
12127                              triaCouples[i].second->end_nodes() );
12128     }
12129
12130   // just for debug dump resulting triangles
12131   dumpFunction(SMESH_Comment("swapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
12132   for ( size_t i = 0; i < triaCouples.size(); ++i )
12133   {
12134     dumpChangeNodes( triaCouples[i].first );
12135     dumpChangeNodes( triaCouples[i].second );
12136   }
12137 }
12138
12139 //================================================================================
12140 /*!
12141  * \brief Move target node to it's final position on the FACE during shrinking
12142  */
12143 //================================================================================
12144
12145 bool _LayerEdge::SetNewLength2d( Handle(Geom_Surface)& surface,
12146                                  const TopoDS_Face&    F,
12147                                  _EdgesOnShape&        eos,
12148                                  SMESH_MesherHelper&   helper )
12149 {
12150   if ( Is( SHRUNK ))
12151     return false; // already at the target position
12152
12153   SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( _nodes.back() );
12154
12155   if ( eos.SWOLType() == TopAbs_FACE )
12156   {
12157     gp_XY    curUV = helper.GetNodeUV( F, tgtNode );
12158     gp_Pnt2d tgtUV( _pos[0].X(), _pos[0].Y() );
12159     gp_Vec2d uvDir( _normal.X(), _normal.Y() );
12160     const double uvLen = tgtUV.Distance( curUV );
12161     const double kSafe = Max( 0.5, 1. - 0.1 * _simplices.size() );
12162
12163     // Select shrinking step such that not to make faces with wrong orientation.
12164     double stepSize = 1e100;
12165     for ( size_t i = 0; i < _simplices.size(); ++i )
12166     {
12167       if ( !_simplices[i]._nPrev->isMarked() ||
12168            !_simplices[i]._nNext->isMarked() )
12169         continue; // simplex of quadrangle created by addBoundaryElements()
12170
12171       // find intersection of 2 lines: curUV-tgtUV and that connecting simplex nodes
12172       gp_XY uvN1 = helper.GetNodeUV( F, _simplices[i]._nPrev, tgtNode );
12173       gp_XY uvN2 = helper.GetNodeUV( F, _simplices[i]._nNext, tgtNode );
12174       gp_XY dirN = uvN2 - uvN1;
12175       double det = uvDir.Crossed( dirN );
12176       if ( Abs( det )  < std::numeric_limits<double>::min() ) continue;
12177       gp_XY dirN2Cur = curUV - uvN1;
12178       double step = dirN.Crossed( dirN2Cur ) / det;
12179       if ( step > 0 )
12180         stepSize = Min( step, stepSize );
12181     }
12182     gp_Pnt2d newUV;
12183     if ( uvLen <= stepSize )
12184     {
12185       newUV = tgtUV;
12186       Set( SHRUNK );
12187       //_pos.clear();
12188     }
12189     else if ( stepSize > 0 )
12190     {
12191       newUV = curUV + uvDir.XY() * stepSize * kSafe;
12192     }
12193     else
12194     {
12195       return true;
12196     }
12197     SMDS_FacePositionPtr pos = tgtNode->GetPosition();
12198     pos->SetUParameter( newUV.X() );
12199     pos->SetVParameter( newUV.Y() );
12200
12201 #ifdef __myDEBUG
12202     gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
12203     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
12204     dumpMove( tgtNode );
12205 #else
12206     if ( surface.IsNull() ) {}
12207 #endif
12208   }
12209   else // _sWOL is TopAbs_EDGE
12210   {
12211     const TopoDS_Edge&      E = TopoDS::Edge( eos._sWOL );
12212     const SMDS_MeshNode*   n2 = _simplices[0]._nPrev;
12213     SMDS_EdgePositionPtr tgtPos = tgtNode->GetPosition();
12214
12215     const double u2     = helper.GetNodeU( E, n2, tgtNode );
12216     const double uSrc   = _pos[0].Coord( U_SRC );
12217     const double lenTgt = _pos[0].Coord( LEN_TGT );
12218
12219     double newU = _pos[0].Coord( U_TGT );
12220     if ( lenTgt < 0.99 * fabs( uSrc-u2 )) // n2 got out of src-tgt range
12221     {
12222       Set( _LayerEdge::SHRUNK );
12223       //_pos.clear();
12224     }
12225     else
12226     {
12227       newU = 0.1 * tgtPos->GetUParameter() + 0.9 * u2;
12228     }
12229     tgtPos->SetUParameter( newU );
12230 #ifdef __myDEBUG
12231     gp_XY newUV = helper.GetNodeUV( F, tgtNode, _nodes[0]);
12232     gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
12233     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
12234     dumpMove( tgtNode );
12235 #endif
12236   }
12237
12238   return true;
12239 }
12240
12241 //================================================================================
12242 /*!
12243  * \brief Perform smooth on the FACE
12244  *  \retval bool - true if the node has been moved
12245  */
12246 //================================================================================
12247
12248 bool _SmoothNode::Smooth(int&                  nbBad,
12249                          Handle(Geom_Surface)& surface,
12250                          SMESH_MesherHelper&   helper,
12251                          const double          refSign,
12252                          SmoothType            how,
12253                          bool                  set3D)
12254 {
12255   const TopoDS_Face& face = TopoDS::Face( helper.GetSubShape() );
12256
12257   // get uv of surrounding nodes
12258   vector<gp_XY> uv( _simplices.size() );
12259   for ( size_t i = 0; i < _simplices.size(); ++i )
12260     uv[i] = helper.GetNodeUV( face, _simplices[i]._nPrev, _node );
12261
12262   // compute new UV for the node
12263   gp_XY newPos (0,0);
12264   if ( how == TFI && _simplices.size() == 4 )
12265   {
12266     gp_XY corners[4];
12267     for ( size_t i = 0; i < _simplices.size(); ++i )
12268       if ( _simplices[i]._nOpp )
12269         corners[i] = helper.GetNodeUV( face, _simplices[i]._nOpp, _node );
12270       else
12271         throw SALOME_Exception(LOCALIZED("TFI smoothing: _Simplex::_nOpp not set!"));
12272
12273     newPos = helper.calcTFI ( 0.5, 0.5,
12274                               corners[0], corners[1], corners[2], corners[3],
12275                               uv[1], uv[2], uv[3], uv[0] );
12276   }
12277   else if ( how == ANGULAR )
12278   {
12279     newPos = computeAngularPos( uv, helper.GetNodeUV( face, _node ), refSign );
12280   }
12281   else if ( how == CENTROIDAL && _simplices.size() > 3 )
12282   {
12283     // average centers of diagonals wieghted with their reciprocal lengths
12284     if ( _simplices.size() == 4 )
12285     {
12286       double w1 = 1. / ( uv[2]-uv[0] ).SquareModulus();
12287       double w2 = 1. / ( uv[3]-uv[1] ).SquareModulus();
12288       newPos = ( w1 * ( uv[2]+uv[0] ) + w2 * ( uv[3]+uv[1] )) / ( w1+w2 ) / 2;
12289     }
12290     else
12291     {
12292       double sumWeight = 0;
12293       int nb = _simplices.size() == 4 ? 2 : _simplices.size();
12294       for ( int i = 0; i < nb; ++i )
12295       {
12296         int iFrom = i + 2;
12297         int iTo   = i + _simplices.size() - 1;
12298         for ( int j = iFrom; j < iTo; ++j )
12299         {
12300           int i2 = SMESH_MesherHelper::WrapIndex( j, _simplices.size() );
12301           double w = 1. / ( uv[i]-uv[i2] ).SquareModulus();
12302           sumWeight += w;
12303           newPos += w * ( uv[i]+uv[i2] );
12304         }
12305       }
12306       newPos /= 2 * sumWeight; // 2 is to get a middle between uv's
12307     }
12308   }
12309   else
12310   {
12311     // Laplacian smooth
12312     for ( size_t i = 0; i < _simplices.size(); ++i )
12313       newPos += uv[i];
12314     newPos /= _simplices.size();
12315   }
12316
12317   // count quality metrics (orientation) of triangles around the node
12318   int nbOkBefore = 0;
12319   gp_XY tgtUV = helper.GetNodeUV( face, _node );
12320   for ( size_t i = 0; i < _simplices.size(); ++i )
12321     nbOkBefore += _simplices[i].IsForward( tgtUV, _node, face, helper, refSign );
12322
12323   int nbOkAfter = 0;
12324   for ( size_t i = 0; i < _simplices.size(); ++i )
12325     nbOkAfter += _simplices[i].IsForward( newPos, _node, face, helper, refSign );
12326
12327   if ( nbOkAfter < nbOkBefore )
12328   {
12329     nbBad += _simplices.size() - nbOkBefore;
12330     return false;
12331   }
12332
12333   SMDS_FacePositionPtr pos = _node->GetPosition();
12334   pos->SetUParameter( newPos.X() );
12335   pos->SetVParameter( newPos.Y() );
12336
12337 #ifdef __myDEBUG
12338   set3D = true;
12339 #endif
12340   if ( set3D )
12341   {
12342     gp_Pnt p = surface->Value( newPos.X(), newPos.Y() );
12343     const_cast< SMDS_MeshNode* >( _node )->setXYZ( p.X(), p.Y(), p.Z() );
12344     dumpMove( _node );
12345   }
12346
12347   nbBad += _simplices.size() - nbOkAfter;
12348   return ( (tgtUV-newPos).SquareModulus() > 1e-10 );
12349 }
12350
12351 //================================================================================
12352 /*!
12353  * \brief Computes new UV using angle based smoothing technique
12354  */
12355 //================================================================================
12356
12357 gp_XY _SmoothNode::computeAngularPos(vector<gp_XY>& uv,
12358                                      const gp_XY&   uvToFix,
12359                                      const double   refSign)
12360 {
12361   uv.push_back( uv.front() );
12362
12363   vector< gp_XY >  edgeDir ( uv.size() );
12364   vector< double > edgeSize( uv.size() );
12365   for ( size_t i = 1; i < edgeDir.size(); ++i )
12366   {
12367     edgeDir [i-1] = uv[i] - uv[i-1];
12368     edgeSize[i-1] = edgeDir[i-1].Modulus();
12369     if ( edgeSize[i-1] < numeric_limits<double>::min() )
12370       edgeDir[i-1].SetX( 100 );
12371     else
12372       edgeDir[i-1] /= edgeSize[i-1] * refSign;
12373   }
12374   edgeDir.back()  = edgeDir.front();
12375   edgeSize.back() = edgeSize.front();
12376
12377   gp_XY  newPos(0,0);
12378   //int    nbEdges = 0;
12379   double sumSize = 0;
12380   for ( size_t i = 1; i < edgeDir.size(); ++i )
12381   {
12382     if ( edgeDir[i-1].X() > 1. ) continue;
12383     int i1 = i-1;
12384     while ( edgeDir[i].X() > 1. && ++i < edgeDir.size() );
12385     if ( i == edgeDir.size() ) break;
12386     gp_XY p = uv[i];
12387     gp_XY norm1( -edgeDir[i1].Y(), edgeDir[i1].X() );
12388     gp_XY norm2( -edgeDir[i].Y(),  edgeDir[i].X() );
12389     gp_XY bisec = norm1 + norm2;
12390     double bisecSize = bisec.Modulus();
12391     if ( bisecSize < numeric_limits<double>::min() )
12392     {
12393       bisec = -edgeDir[i1] + edgeDir[i];
12394       bisecSize = bisec.Modulus();
12395     }
12396     bisec /= bisecSize;
12397
12398     gp_XY  dirToN  = uvToFix - p;
12399     double distToN = dirToN.Modulus();
12400     if ( bisec * dirToN < 0 )
12401       distToN = -distToN;
12402
12403     newPos += ( p + bisec * distToN ) * ( edgeSize[i1] + edgeSize[i] );
12404     //++nbEdges;
12405     sumSize += edgeSize[i1] + edgeSize[i];
12406   }
12407   newPos /= /*nbEdges * */sumSize;
12408   return newPos;
12409 }
12410
12411 //================================================================================
12412 /*!
12413  * \brief Keep a _LayerEdge inflated along the EDGE
12414  */
12415 //================================================================================
12416
12417 void _Shrinker1D::AddEdge( const _LayerEdge*   e,
12418                            _EdgesOnShape&      eos,
12419                            SMESH_MesherHelper& helper )
12420 {
12421   // init
12422   if ( _nodes.empty() )
12423   {
12424     _edges[0] = _edges[1] = 0;
12425     _done = false;
12426   }
12427   // check _LayerEdge
12428   if ( e == _edges[0] || e == _edges[1] || e->_nodes.size() < 2 )
12429     return;
12430   if ( eos.SWOLType() != TopAbs_EDGE )
12431     throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
12432   if ( _edges[0] && !_geomEdge.IsSame( eos._sWOL ))
12433     throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
12434
12435   // store _LayerEdge
12436   _geomEdge = TopoDS::Edge( eos._sWOL );
12437   double f,l;
12438   BRep_Tool::Range( _geomEdge, f,l );
12439   double u = helper.GetNodeU( _geomEdge, e->_nodes[0], e->_nodes.back());
12440   _edges[ u < 0.5*(f+l) ? 0 : 1 ] = e;
12441
12442   // Check if the nodes are already shrunk by another SOLID
12443
12444   const SMDS_MeshNode* tgtNode0 = TgtNode( 0 );
12445   const SMDS_MeshNode* tgtNode1 = TgtNode( 1 );
12446
12447   _done = (( tgtNode0 && tgtNode0->NbInverseElements( SMDSAbs_Edge ) == 2 ) ||
12448            ( tgtNode1 && tgtNode1->NbInverseElements( SMDSAbs_Edge ) == 2 ));
12449   if ( _done )
12450     _nodes.resize( 1, nullptr );
12451
12452   // Update _nodes
12453
12454   if ( _nodes.empty() )
12455   {
12456     SMESHDS_SubMesh * eSubMesh = helper.GetMeshDS()->MeshElements( _geomEdge );
12457     if ( !eSubMesh || eSubMesh->NbNodes() < 1 )
12458       return;
12459     TopLoc_Location loc;
12460     Handle(Geom_Curve) C = BRep_Tool::Curve( _geomEdge, loc, f,l );
12461     GeomAdaptor_Curve aCurve(C, f,l);
12462     const double totLen = GCPnts_AbscissaPoint::Length(aCurve, f, l);
12463
12464     smIdType nbExpectNodes = eSubMesh->NbNodes();
12465     _initU  .reserve( nbExpectNodes );
12466     _normPar.reserve( nbExpectNodes );
12467     _nodes  .reserve( nbExpectNodes );
12468     SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
12469     while ( nIt->more() )
12470     {
12471       const SMDS_MeshNode* node = nIt->next();
12472
12473       // skip refinement nodes
12474       if ( node->NbInverseElements(SMDSAbs_Edge) == 0 ||
12475            node == tgtNode0 || node == tgtNode1 )
12476         continue;
12477       bool hasMarkedFace = false;
12478       SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
12479       while ( fIt->more() && !hasMarkedFace )
12480         hasMarkedFace = fIt->next()->isMarked();
12481       if ( !hasMarkedFace )
12482         continue;
12483
12484       _nodes.push_back( node );
12485       _initU.push_back( helper.GetNodeU( _geomEdge, node ));
12486       double len = GCPnts_AbscissaPoint::Length(aCurve, f, _initU.back());
12487       _normPar.push_back(  len / totLen );
12488     }
12489   }
12490   else
12491   {
12492     // remove target node of the _LayerEdge from _nodes
12493     size_t nbFound = 0;
12494     for ( size_t i = 0; i < _nodes.size(); ++i )
12495       if ( !_nodes[i] || _nodes[i] == tgtNode0 || _nodes[i] == tgtNode1 )
12496         _nodes[i] = 0, nbFound++;
12497     if ( nbFound == _nodes.size() )
12498       _nodes.clear();
12499   }
12500 }
12501
12502 //================================================================================
12503 /*!
12504  * \brief Move nodes on EDGE from ends where _LayerEdge's are inflated
12505  */
12506 //================================================================================
12507
12508 void _Shrinker1D::Compute(bool set3D, SMESH_MesherHelper& helper)
12509 {
12510   if ( _done || _nodes.empty())
12511     return;
12512   const _LayerEdge* e = _edges[0];
12513   if ( !e ) e = _edges[1];
12514   if ( !e ) return;
12515
12516   _done =  (( !_edges[0] || _edges[0]->Is( _LayerEdge::SHRUNK )) &&
12517             ( !_edges[1] || _edges[1]->Is( _LayerEdge::SHRUNK )));
12518
12519   double f,l;
12520   if ( set3D || _done )
12521   {
12522     dumpFunction(SMESH_Comment("shrink1D_E") << helper.GetMeshDS()->ShapeToIndex( _geomEdge )<<
12523                  "_F" << helper.GetSubShapeID() );
12524     Handle(Geom_Curve) C = BRep_Tool::Curve(_geomEdge, f,l);
12525     GeomAdaptor_Curve aCurve(C, f,l);
12526
12527     if ( _edges[0] )
12528       f = helper.GetNodeU( _geomEdge, _edges[0]->_nodes.back(), _nodes[0] );
12529     if ( _edges[1] )
12530       l = helper.GetNodeU( _geomEdge, _edges[1]->_nodes.back(), _nodes.back() );
12531     double totLen = GCPnts_AbscissaPoint::Length( aCurve, f, l );
12532
12533     for ( size_t i = 0; i < _nodes.size(); ++i )
12534     {
12535       if ( !_nodes[i] ) continue;
12536       double len = totLen * _normPar[i];
12537       GCPnts_AbscissaPoint discret( aCurve, len, f );
12538       if ( !discret.IsDone() )
12539         return throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
12540       double u = discret.Parameter();
12541       SMDS_EdgePositionPtr pos = _nodes[i]->GetPosition();
12542       pos->SetUParameter( u );
12543       gp_Pnt p = C->Value( u );
12544       const_cast< SMDS_MeshNode*>( _nodes[i] )->setXYZ( p.X(), p.Y(), p.Z() );
12545       dumpMove( _nodes[i] );
12546     }
12547     dumpFunctionEnd();
12548   }
12549   else
12550   {
12551     BRep_Tool::Range( _geomEdge, f,l );
12552     if ( _edges[0] )
12553       f = helper.GetNodeU( _geomEdge, _edges[0]->_nodes.back(), _nodes[0] );
12554     if ( _edges[1] )
12555       l = helper.GetNodeU( _geomEdge, _edges[1]->_nodes.back(), _nodes.back() );
12556     
12557     for ( size_t i = 0; i < _nodes.size(); ++i )
12558     {
12559       if ( !_nodes[i] ) continue;
12560       double u = f * ( 1-_normPar[i] ) + l * _normPar[i];
12561       SMDS_EdgePositionPtr pos = _nodes[i]->GetPosition();
12562       pos->SetUParameter( u );
12563     }
12564   }
12565 }
12566
12567 //================================================================================
12568 /*!
12569  * \brief Restore initial parameters of nodes on EDGE
12570  */
12571 //================================================================================
12572
12573 void _Shrinker1D::RestoreParams()
12574 {
12575   if ( _done )
12576     for ( size_t i = 0; i < _nodes.size(); ++i )
12577     {
12578       if ( !_nodes[i] ) continue;
12579       SMDS_EdgePositionPtr pos = _nodes[i]->GetPosition();
12580       pos->SetUParameter( _initU[i] );
12581     }
12582   _done = false;
12583 }
12584
12585 //================================================================================
12586 /*!
12587  * \brief Replace source nodes by target nodes in shrunk mesh edges
12588  */
12589 //================================================================================
12590
12591 void _Shrinker1D::SwapSrcTgtNodes( SMESHDS_Mesh* mesh )
12592 {
12593   const SMDS_MeshNode* nodes[3];
12594   for ( int i = 0; i < 2; ++i )
12595   {
12596     if ( !_edges[i] ) continue;
12597
12598     SMESHDS_SubMesh * eSubMesh = mesh->MeshElements( _geomEdge );
12599     if ( !eSubMesh ) return;
12600     const SMDS_MeshNode* srcNode = _edges[i]->_nodes[0];
12601     const SMDS_MeshNode* tgtNode = _edges[i]->_nodes.back();
12602     const SMDS_MeshNode* scdNode = _edges[i]->_nodes[1];
12603     SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
12604     while ( eIt->more() )
12605     {
12606       const SMDS_MeshElement* e = eIt->next();
12607       if ( !eSubMesh->Contains( e ) || e->GetNodeIndex( scdNode ) >= 0 )
12608           continue;
12609       SMDS_ElemIteratorPtr nIt = e->nodesIterator();
12610       for ( int iN = 0; iN < e->NbNodes(); ++iN )
12611       {
12612         const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
12613         nodes[iN] = ( n == srcNode ? tgtNode : n );
12614       }
12615       mesh->ChangeElementNodes( e, nodes, e->NbNodes() );
12616     }
12617   }
12618 }
12619
12620 //================================================================================
12621 /*!
12622  * \brief Setup quadPoints
12623  */
12624 //================================================================================
12625
12626 _Mapper2D::_Mapper2D( const TParam2ColumnMap & param2ColumnMap, const TNode2Edge& n2eMap )
12627 {
12628   size_t i, iSize = _quadPoints.iSize = param2ColumnMap.size();
12629   size_t j, jSize = _quadPoints.jSize = param2ColumnMap.begin()->second.size();
12630   if ( _quadPoints.iSize < 3 ||
12631        _quadPoints.jSize < 3 )
12632     return;
12633   _quadPoints.uv_grid.resize( iSize * jSize );
12634
12635   // set nodes
12636   i = 0;
12637   for ( auto & u_columnNodes : param2ColumnMap )
12638   {
12639     for ( j = 0; j < u_columnNodes.second.size(); ++j )
12640       _quadPoints.UVPt( i, j ).node = u_columnNodes.second[ j ];
12641     ++i;
12642   }
12643
12644   // compute x parameter on borders
12645   uvPnt( 0, 0       ).x = 0;
12646   uvPnt( 0, jSize-1 ).x = 0;
12647   gp_Pnt p0, pPrev0 = SMESH_NodeXYZ( uvPnt( 0, 0       ).node );
12648   gp_Pnt p1, pPrev1 = SMESH_NodeXYZ( uvPnt( 0, jSize-1 ).node );
12649   for ( i = 1; i < iSize; ++i )
12650   {
12651     p0 = SMESH_NodeXYZ( uvPnt( i, 0       ).node );
12652     p1 = SMESH_NodeXYZ( uvPnt( i, jSize-1 ).node );
12653     uvPnt( i, 0       ).x = uvPnt( i-1, 0       ).x + p0.Distance( pPrev0 );
12654     uvPnt( i, jSize-1 ).x = uvPnt( i-1, jSize-1 ).x + p1.Distance( pPrev1 );
12655     pPrev0 = p0;
12656     pPrev1 = p1;
12657   }
12658   for ( i = 1; i < iSize-1; ++i )
12659   {
12660     uvPnt( i, 0       ).x /= uvPnt( iSize-1, 0       ).x;
12661     uvPnt( i, jSize-1 ).x /= uvPnt( iSize-1, jSize-1 ).x;
12662     uvPnt( i, 0       ).y = 0;
12663     uvPnt( i, jSize-1 ).y = 1;
12664   }
12665
12666   // compute y parameter on borders
12667   uvPnt( 0,       0 ).y = 0;
12668   uvPnt( iSize-1, 0 ).y = 0;
12669   pPrev0 = SMESH_NodeXYZ( uvPnt( 0,       0 ).node );
12670   pPrev1 = SMESH_NodeXYZ( uvPnt( iSize-1, 0 ).node );
12671   for ( j = 1; j < jSize; ++j )
12672   {
12673     p0 = SMESH_NodeXYZ( uvPnt( 0,       j ).node );
12674     p1 = SMESH_NodeXYZ( uvPnt( iSize-1, j ).node );
12675     uvPnt( 0,       j ).y = uvPnt( 0,       j-1 ).y + p0.Distance( pPrev0 );
12676     uvPnt( iSize-1, j ).y = uvPnt( iSize-1, j-1 ).y + p1.Distance( pPrev1 );
12677     pPrev0 = p0;
12678     pPrev1 = p1;
12679   }
12680   for ( j = 1; j < jSize-1; ++j )
12681   {
12682     uvPnt( 0,       j ).y /= uvPnt( 0,       jSize-1 ).y;
12683     uvPnt( iSize-1, j ).y /= uvPnt( iSize-1, jSize-1 ).y;
12684     uvPnt( 0,       j ).x = 0;
12685     uvPnt( iSize-1, j ).x = 1;
12686   }
12687
12688   // compute xy of internal nodes
12689   for ( i = 1; i < iSize-1; ++i )
12690   {
12691     const double x0 = uvPnt( i, 0       ).x;
12692     const double x1 = uvPnt( i, jSize-1 ).x;
12693     for ( j = 1; j < jSize-1; ++j )
12694     {
12695       const double y0 = uvPnt( 0,       j ).y;
12696       const double y1 = uvPnt( iSize-1, j ).y;
12697       double x = (x0 + y0 * (x1 - x0)) / (1 - (y1 - y0) * (x1 - x0));
12698       double y = y0 + x * (y1 - y0);
12699       uvPnt( i, j ).x = x;
12700       uvPnt( i, j ).y = y;
12701     }
12702   }
12703
12704   // replace base nodes with target ones
12705   for ( i = 0; i < iSize; ++i )
12706     for ( j = 0; j < jSize; ++j )
12707     {
12708       auto n2e = n2eMap.find( uvPnt( i, j ).node );
12709       uvPnt( i, j ).node = n2e->second->_nodes.back();
12710     }
12711
12712   return;
12713 }
12714
12715 //================================================================================
12716 /*!
12717  * \brief Compute positions of nodes of 2D structured mesh using TFI
12718  */
12719 //================================================================================
12720
12721 bool _Mapper2D::ComputeNodePositions()
12722 {
12723   if ( _quadPoints.uv_grid.empty() )
12724     return true;
12725
12726   size_t i, iSize = _quadPoints.iSize;
12727   size_t j, jSize = _quadPoints.jSize;
12728
12729   SMESH_NodeXYZ a0 ( uvPnt( 0,       0       ).node );
12730   SMESH_NodeXYZ a1 ( uvPnt( iSize-1, 0       ).node );
12731   SMESH_NodeXYZ a2 ( uvPnt( iSize-1, jSize-1 ).node );
12732   SMESH_NodeXYZ a3 ( uvPnt( 0,       jSize-1 ).node );
12733
12734   for ( i = 1; i < iSize-1; ++i )
12735   {
12736     SMESH_NodeXYZ p0 ( uvPnt( i, 0       ).node );
12737     SMESH_NodeXYZ p2 ( uvPnt( i, jSize-1 ).node );
12738     for ( j = 1; j < jSize-1; ++j )
12739     {
12740       SMESH_NodeXYZ p1 ( uvPnt( iSize-1, j ).node );
12741       SMESH_NodeXYZ p3 ( uvPnt( 0,       j ).node );
12742       double x = uvPnt( i, j ).x;
12743       double y = uvPnt( i, j ).y;
12744
12745       gp_XYZ p = SMESH_MesherHelper::calcTFI( x, y, a0,a1,a2,a3, p0,p1,p2,p3 );
12746       const_cast< SMDS_MeshNode* >( uvPnt( i, j ).node )->setXYZ( p.X(), p.Y(), p.Z() );
12747
12748       dumpMove( uvPnt( i, j ).node );
12749     }
12750   }
12751   return true;
12752 }
12753
12754 //================================================================================
12755 /*!
12756  * \brief Creates 2D and 1D elements on boundaries of new prisms
12757  */
12758 //================================================================================
12759
12760 bool _ViscousBuilder::addBoundaryElements(_SolidData& data)
12761 {
12762   SMESH_MesherHelper helper( *_mesh );
12763
12764   vector< const SMDS_MeshNode* > faceNodes;
12765
12766   //for ( size_t i = 0; i < _sdVec.size(); ++i )
12767   {
12768     //_SolidData& data = _sdVec[i];
12769     TopTools_IndexedMapOfShape geomEdges;
12770     TopExp::MapShapes( data._solid, TopAbs_EDGE, geomEdges );
12771     for ( int iE = 1; iE <= geomEdges.Extent(); ++iE )
12772     {
12773       const TopoDS_Edge& E = TopoDS::Edge( geomEdges(iE));
12774       const TGeomID edgeID = getMeshDS()->ShapeToIndex( E );
12775       if ( data._noShrinkShapes.count( edgeID ))
12776         continue;
12777
12778       // Get _LayerEdge's based on E
12779
12780       map< double, const SMDS_MeshNode* > u2nodes;
12781       if ( !SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), E, /*ignoreMedium=*/false, u2nodes))
12782         continue;
12783
12784       vector< _LayerEdge* > ledges; ledges.reserve( u2nodes.size() );
12785       TNode2Edge & n2eMap = data._n2eMap;
12786       map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
12787       {
12788         //check if 2D elements are needed on E
12789         TNode2Edge::iterator n2e = n2eMap.find( u2n->second );
12790         if ( n2e == n2eMap.end() ) continue; // no layers on vertex
12791         ledges.push_back( n2e->second );
12792         u2n++;
12793         if (( n2e = n2eMap.find( u2n->second )) == n2eMap.end() )
12794           continue; // no layers on E
12795         ledges.push_back( n2eMap[ u2n->second ]);
12796
12797         const SMDS_MeshNode* tgtN0 = ledges[0]->_nodes.back();
12798         const SMDS_MeshNode* tgtN1 = ledges[1]->_nodes.back();
12799         int nbSharedPyram = 0;
12800         SMDS_ElemIteratorPtr vIt = tgtN1->GetInverseElementIterator(SMDSAbs_Volume);
12801         while ( vIt->more() )
12802         {
12803           const SMDS_MeshElement* v = vIt->next();
12804           nbSharedPyram += int( v->GetNodeIndex( tgtN0 ) >= 0 );
12805         }
12806         if ( nbSharedPyram > 1 )
12807           continue; // not free border of the pyramid
12808
12809         faceNodes.clear();
12810         faceNodes.push_back( ledges[0]->_nodes[0] );
12811         faceNodes.push_back( ledges[1]->_nodes[0] );
12812         if ( ledges[0]->_nodes.size() > 1 ) faceNodes.push_back( ledges[0]->_nodes[1] );
12813         if ( ledges[1]->_nodes.size() > 1 ) faceNodes.push_back( ledges[1]->_nodes[1] );
12814
12815         if ( getMeshDS()->FindElement( faceNodes, SMDSAbs_Face, /*noMedium=*/true))
12816           continue; // faces already created
12817       }
12818       for ( ++u2n; u2n != u2nodes.end(); ++u2n )
12819         ledges.push_back( n2eMap[ u2n->second ]);
12820
12821       // Find out orientation and type of face to create
12822
12823       bool reverse = false, isOnFace;
12824       TopoDS_Shape F;
12825
12826       map< TGeomID, TopoDS_Shape >::iterator e2f = data._shrinkShape2Shape.find( edgeID );
12827       if (( isOnFace = ( e2f != data._shrinkShape2Shape.end() )))
12828       {
12829         F = e2f->second.Oriented( TopAbs_FORWARD );
12830         reverse = ( helper.GetSubShapeOri( F, E ) == TopAbs_REVERSED );
12831         if ( helper.GetSubShapeOri( data._solid, F ) == TopAbs_REVERSED )
12832           reverse = !reverse, F.Reverse();
12833         if ( helper.IsReversedSubMesh( TopoDS::Face(F) ))
12834           reverse = !reverse;
12835       }
12836       else if ( !data._ignoreFaceIds.count( e2f->first ))
12837       {
12838         // find FACE with layers sharing E
12839         PShapeIteratorPtr fIt = helper.GetAncestors( E, *_mesh, TopAbs_FACE, &data._solid );
12840         if ( fIt->more() )
12841           F = *( fIt->next() );
12842       }
12843       // Find the sub-mesh to add new faces
12844       SMESHDS_SubMesh* sm = 0;
12845       if ( isOnFace )
12846         sm = getMeshDS()->MeshElements( F );
12847       else
12848         sm = data._proxyMesh->getFaceSubM( TopoDS::Face(F), /*create=*/true );
12849       if ( !sm )
12850         return error("error in addBoundaryElements()", data._index);
12851
12852       // Find a proxy sub-mesh of the FACE of an adjacent SOLID, which will use the new boundary
12853       // faces for 3D meshing (PAL23414)
12854       SMESHDS_SubMesh* adjSM = 0;
12855       if ( isOnFace )
12856       {
12857         const TGeomID   faceID = sm->GetID();
12858         PShapeIteratorPtr soIt = helper.GetAncestors( F, *_mesh, TopAbs_SOLID );
12859         while ( const TopoDS_Shape* solid = soIt->next() )
12860           if ( !solid->IsSame( data._solid ))
12861           {
12862             size_t iData = _solids.FindIndex( *solid ) - 1;
12863             if ( iData < _sdVec.size() &&
12864                  _sdVec[ iData ]._ignoreFaceIds.count( faceID ) &&
12865                  _sdVec[ iData ]._shrinkShape2Shape.count( edgeID ) == 0 )
12866             {
12867               SMESH_ProxyMesh::SubMesh* proxySub =
12868                 _sdVec[ iData ]._proxyMesh->getFaceSubM( TopoDS::Face( F ), /*create=*/false);
12869               if ( proxySub && proxySub->NbElements() > 0 )
12870                 adjSM = proxySub;
12871             }
12872           }
12873       }
12874
12875       // Make faces
12876       const int dj1 = reverse ? 0 : 1;
12877       const int dj2 = reverse ? 1 : 0;
12878       vector< const SMDS_MeshElement*> ff; // new faces row
12879       SMESHDS_Mesh* m = getMeshDS();
12880       for ( size_t j = 1; j < ledges.size(); ++j )
12881       {
12882         vector< const SMDS_MeshNode*>&  nn1 = ledges[j-dj1]->_nodes;
12883         vector< const SMDS_MeshNode*>&  nn2 = ledges[j-dj2]->_nodes;
12884         ff.resize( std::max( nn1.size(), nn2.size() ), NULL );
12885         if ( nn1.size() == nn2.size() )
12886         {
12887           if ( isOnFace )
12888             for ( size_t z = 1; z < nn1.size(); ++z )
12889               sm->AddElement( ff[z-1] = m->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
12890           else
12891             for ( size_t z = 1; z < nn1.size(); ++z )
12892               sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
12893         }
12894         else if ( nn1.size() == 1 )
12895         {
12896           if ( isOnFace )
12897             for ( size_t z = 1; z < nn2.size(); ++z )
12898               sm->AddElement( ff[z-1] = m->AddFace( nn1[0], nn2[z-1], nn2[z] ));
12899           else
12900             for ( size_t z = 1; z < nn2.size(); ++z )
12901               sm->AddElement( new SMDS_FaceOfNodes( nn1[0], nn2[z-1], nn2[z] ));
12902         }
12903         else
12904         {
12905           if ( isOnFace )
12906             for ( size_t z = 1; z < nn1.size(); ++z )
12907               sm->AddElement( ff[z-1] = m->AddFace( nn1[z-1], nn2[0], nn1[z] ));
12908           else
12909             for ( size_t z = 1; z < nn1.size(); ++z )
12910               sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[0], nn2[z] ));
12911         }
12912
12913         if ( adjSM ) // add faces to a proxy SM of the adjacent SOLID
12914         {
12915           for ( size_t z = 0; z < ff.size(); ++z )
12916             if ( ff[ z ])
12917               adjSM->AddElement( ff[ z ]);
12918           ff.clear();
12919         }
12920       }
12921
12922       // Make edges
12923       for ( int isFirst = 0; isFirst < 2; ++isFirst )
12924       {
12925         _LayerEdge* edge = isFirst ? ledges.front() : ledges.back();
12926         _EdgesOnShape* eos = data.GetShapeEdges( edge );
12927         if ( eos && eos->SWOLType() == TopAbs_EDGE )
12928         {
12929           vector< const SMDS_MeshNode*>&  nn = edge->_nodes;
12930           if ( nn.size() < 2 || nn[1]->NbInverseElements( SMDSAbs_Edge ) >= 2 )
12931             continue;
12932           helper.SetSubShape( eos->_sWOL );
12933           helper.SetElementsOnShape( true );
12934           for ( size_t z = 1; z < nn.size(); ++z )
12935             helper.AddEdge( nn[z-1], nn[z] );
12936         }
12937       }
12938
12939     } // loop on EDGE's
12940   } // loop on _SolidData's
12941
12942   return true;
12943 }