Salome HOME
23190: EDF 11636 - Problem of viscous layer
[modules/smesh.git] / src / StdMeshers / StdMeshers_ViscousLayers.cxx
1 // Copyright (C) 2007-2016  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 "SMDS_EdgePosition.hxx"
27 #include "SMDS_FaceOfNodes.hxx"
28 #include "SMDS_FacePosition.hxx"
29 #include "SMDS_MeshNode.hxx"
30 #include "SMDS_SetIterator.hxx"
31 #include "SMESHDS_Group.hxx"
32 #include "SMESHDS_Hypothesis.hxx"
33 #include "SMESH_Algo.hxx"
34 #include "SMESH_ComputeError.hxx"
35 #include "SMESH_ControlsDef.hxx"
36 #include "SMESH_Gen.hxx"
37 #include "SMESH_Group.hxx"
38 #include "SMESH_HypoFilter.hxx"
39 #include "SMESH_Mesh.hxx"
40 #include "SMESH_MeshAlgos.hxx"
41 #include "SMESH_MesherHelper.hxx"
42 #include "SMESH_ProxyMesh.hxx"
43 #include "SMESH_subMesh.hxx"
44 #include "SMESH_subMeshEventListener.hxx"
45 #include "StdMeshers_FaceSide.hxx"
46 #include "StdMeshers_ViscousLayers2D.hxx"
47
48 #include <Adaptor3d_HSurface.hxx>
49 #include <BRepAdaptor_Curve.hxx>
50 #include <BRepAdaptor_Curve2d.hxx>
51 #include <BRepAdaptor_Surface.hxx>
52 #include <BRepLProp_SLProps.hxx>
53 #include <BRepOffsetAPI_MakeOffsetShape.hxx>
54 #include <BRep_Tool.hxx>
55 #include <Bnd_B2d.hxx>
56 #include <Bnd_B3d.hxx>
57 #include <ElCLib.hxx>
58 #include <GCPnts_AbscissaPoint.hxx>
59 #include <GCPnts_TangentialDeflection.hxx>
60 #include <Geom2d_Circle.hxx>
61 #include <Geom2d_Line.hxx>
62 #include <Geom2d_TrimmedCurve.hxx>
63 #include <GeomAdaptor_Curve.hxx>
64 #include <GeomLib.hxx>
65 #include <Geom_Circle.hxx>
66 #include <Geom_Curve.hxx>
67 #include <Geom_Line.hxx>
68 #include <Geom_TrimmedCurve.hxx>
69 #include <Precision.hxx>
70 #include <Standard_ErrorHandler.hxx>
71 #include <Standard_Failure.hxx>
72 #include <TColStd_Array1OfReal.hxx>
73 #include <TopExp.hxx>
74 #include <TopExp_Explorer.hxx>
75 #include <TopTools_IndexedMapOfShape.hxx>
76 #include <TopTools_ListOfShape.hxx>
77 #include <TopTools_MapIteratorOfMapOfShape.hxx>
78 #include <TopTools_MapOfShape.hxx>
79 #include <TopoDS.hxx>
80 #include <TopoDS_Edge.hxx>
81 #include <TopoDS_Face.hxx>
82 #include <TopoDS_Vertex.hxx>
83 #include <gp_Ax1.hxx>
84 #include <gp_Cone.hxx>
85 #include <gp_Sphere.hxx>
86 #include <gp_Vec.hxx>
87 #include <gp_XY.hxx>
88
89 #include <cmath>
90 #include <limits>
91 #include <list>
92 #include <queue>
93 #include <string>
94
95 #ifdef _DEBUG_
96 #define __myDEBUG
97 //#define __NOT_INVALIDATE_BAD_SMOOTH
98 #endif
99
100 #define INCREMENTAL_SMOOTH // smooth only if min angle is too small
101 #define BLOCK_INFLATION // of individual _LayerEdge's
102 #define OLD_NEF_POLYGON
103
104 using namespace std;
105
106 //================================================================================
107 namespace VISCOUS_3D
108 {
109   typedef int TGeomID;
110
111   enum UIndex { U_TGT = 1, U_SRC, LEN_TGT };
112
113   const double theMinSmoothCosin = 0.1;
114   const double theSmoothThickToElemSizeRatio = 0.3;
115   const double theMinSmoothTriaAngle = 30;
116   const double theMinSmoothQuadAngle = 45;
117
118   // what part of thickness is allowed till intersection
119   // (defined by SALOME_TESTS/Grids/smesh/viscous_layers_00/A5)
120   const double theThickToIntersection = 1.5;
121
122   bool needSmoothing( double cosin, double tgtThick, double elemSize )
123   {
124     return cosin * tgtThick > theSmoothThickToElemSizeRatio * elemSize;
125   }
126   double getSmoothingThickness( double cosin, double elemSize )
127   {
128     return theSmoothThickToElemSizeRatio * elemSize / cosin;
129   }
130
131   /*!
132    * \brief SMESH_ProxyMesh computed by _ViscousBuilder for a SOLID.
133    * It is stored in a SMESH_subMesh of the SOLID as SMESH_subMeshEventListenerData
134    */
135   struct _MeshOfSolid : public SMESH_ProxyMesh,
136                         public SMESH_subMeshEventListenerData
137   {
138     bool                  _n2nMapComputed;
139     SMESH_ComputeErrorPtr _warning;
140
141     _MeshOfSolid( SMESH_Mesh* mesh)
142       :SMESH_subMeshEventListenerData( /*isDeletable=*/true),_n2nMapComputed(false)
143     {
144       SMESH_ProxyMesh::setMesh( *mesh );
145     }
146
147     // returns submesh for a geom face
148     SMESH_ProxyMesh::SubMesh* getFaceSubM(const TopoDS_Face& F, bool create=false)
149     {
150       TGeomID i = SMESH_ProxyMesh::shapeIndex(F);
151       return create ? SMESH_ProxyMesh::getProxySubMesh(i) : findProxySubMesh(i);
152     }
153     void setNode2Node(const SMDS_MeshNode*                 srcNode,
154                       const SMDS_MeshNode*                 proxyNode,
155                       const SMESH_ProxyMesh::SubMesh* subMesh)
156     {
157       SMESH_ProxyMesh::setNode2Node( srcNode,proxyNode,subMesh);
158     }
159   };
160   //--------------------------------------------------------------------------------
161   /*!
162    * \brief Listener of events of 3D sub-meshes computed with viscous layers.
163    * It is used to clear an inferior dim sub-meshes modified by viscous layers
164    */
165   class _ShrinkShapeListener : SMESH_subMeshEventListener
166   {
167     _ShrinkShapeListener()
168       : SMESH_subMeshEventListener(/*isDeletable=*/false,
169                                    "StdMeshers_ViscousLayers::_ShrinkShapeListener") {}
170   public:
171     static SMESH_subMeshEventListener* Get() { static _ShrinkShapeListener l; return &l; }
172     virtual void ProcessEvent(const int                       event,
173                               const int                       eventType,
174                               SMESH_subMesh*                  solidSM,
175                               SMESH_subMeshEventListenerData* data,
176                               const SMESH_Hypothesis*         hyp)
177     {
178       if ( SMESH_subMesh::COMPUTE_EVENT == eventType && solidSM->IsEmpty() && data )
179       {
180         SMESH_subMeshEventListener::ProcessEvent(event,eventType,solidSM,data,hyp);
181       }
182     }
183   };
184   //--------------------------------------------------------------------------------
185   /*!
186    * \brief Listener of events of 3D sub-meshes computed with viscous layers.
187    * It is used to store data computed by _ViscousBuilder for a sub-mesh and to
188    * delete the data as soon as it has been used
189    */
190   class _ViscousListener : SMESH_subMeshEventListener
191   {
192     _ViscousListener():
193       SMESH_subMeshEventListener(/*isDeletable=*/false,
194                                  "StdMeshers_ViscousLayers::_ViscousListener") {}
195     static SMESH_subMeshEventListener* Get() { static _ViscousListener l; return &l; }
196   public:
197     virtual void ProcessEvent(const int                       event,
198                               const int                       eventType,
199                               SMESH_subMesh*                  subMesh,
200                               SMESH_subMeshEventListenerData* data,
201                               const SMESH_Hypothesis*         hyp)
202     {
203       if (( SMESH_subMesh::COMPUTE_EVENT       == eventType ) &&
204           ( SMESH_subMesh::CHECK_COMPUTE_STATE != event &&
205             SMESH_subMesh::SUBMESH_COMPUTED    != event ))
206       {
207         // delete SMESH_ProxyMesh containing temporary faces
208         subMesh->DeleteEventListener( this );
209       }
210     }
211     // Finds or creates proxy mesh of the solid
212     static _MeshOfSolid* GetSolidMesh(SMESH_Mesh*         mesh,
213                                       const TopoDS_Shape& solid,
214                                       bool                toCreate=false)
215     {
216       if ( !mesh ) return 0;
217       SMESH_subMesh* sm = mesh->GetSubMesh(solid);
218       _MeshOfSolid* data = (_MeshOfSolid*) sm->GetEventListenerData( Get() );
219       if ( !data && toCreate )
220       {
221         data = new _MeshOfSolid(mesh);
222         data->mySubMeshes.push_back( sm ); // to find SOLID by _MeshOfSolid
223         sm->SetEventListener( Get(), data, sm );
224       }
225       return data;
226     }
227     // Removes proxy mesh of the solid
228     static void RemoveSolidMesh(SMESH_Mesh* mesh, const TopoDS_Shape& solid)
229     {
230       mesh->GetSubMesh(solid)->DeleteEventListener( _ViscousListener::Get() );
231     }
232   };
233   
234   //================================================================================
235   /*!
236    * \brief sets a sub-mesh event listener to clear sub-meshes of sub-shapes of
237    * the main shape when sub-mesh of the main shape is cleared,
238    * for example to clear sub-meshes of FACEs when sub-mesh of a SOLID
239    * is cleared
240    */
241   //================================================================================
242
243   void ToClearSubWithMain( SMESH_subMesh* sub, const TopoDS_Shape& main)
244   {
245     SMESH_subMesh* mainSM = sub->GetFather()->GetSubMesh( main );
246     SMESH_subMeshEventListenerData* data =
247       mainSM->GetEventListenerData( _ShrinkShapeListener::Get());
248     if ( data )
249     {
250       if ( find( data->mySubMeshes.begin(), data->mySubMeshes.end(), sub ) ==
251            data->mySubMeshes.end())
252         data->mySubMeshes.push_back( sub );
253     }
254     else
255     {
256       data = SMESH_subMeshEventListenerData::MakeData( /*dependent=*/sub );
257       sub->SetEventListener( _ShrinkShapeListener::Get(), data, /*whereToListenTo=*/mainSM );
258     }
259   }
260   struct _SolidData;
261   //--------------------------------------------------------------------------------
262   /*!
263    * \brief Simplex (triangle or tetrahedron) based on 1 (tria) or 2 (tet) nodes of
264    * _LayerEdge and 2 nodes of the mesh surface beening smoothed.
265    * The class is used to check validity of face or volumes around a smoothed node;
266    * it stores only 2 nodes as the other nodes are stored by _LayerEdge.
267    */
268   struct _Simplex
269   {
270     const SMDS_MeshNode *_nPrev, *_nNext; // nodes on a smoothed mesh surface
271     const SMDS_MeshNode *_nOpp; // in 2D case, a node opposite to a smoothed node in QUAD
272     _Simplex(const SMDS_MeshNode* nPrev=0,
273              const SMDS_MeshNode* nNext=0,
274              const SMDS_MeshNode* nOpp=0)
275       : _nPrev(nPrev), _nNext(nNext), _nOpp(nOpp) {}
276     bool IsForward(const gp_XYZ* pntSrc, const gp_XYZ* pntTgt, double& vol) const
277     {
278       const double M[3][3] =
279         {{ _nNext->X() - pntSrc->X(), _nNext->Y() - pntSrc->Y(), _nNext->Z() - pntSrc->Z() },
280          { pntTgt->X() - pntSrc->X(), pntTgt->Y() - pntSrc->Y(), pntTgt->Z() - pntSrc->Z() },
281          { _nPrev->X() - pntSrc->X(), _nPrev->Y() - pntSrc->Y(), _nPrev->Z() - pntSrc->Z() }};
282       vol = ( + M[0][0] * M[1][1] * M[2][2]
283               + M[0][1] * M[1][2] * M[2][0]
284               + M[0][2] * M[1][0] * M[2][1]
285               - M[0][0] * M[1][2] * M[2][1]
286               - M[0][1] * M[1][0] * M[2][2]
287               - M[0][2] * M[1][1] * M[2][0]);
288       return vol > 1e-100;
289     }
290     bool IsForward(const SMDS_MeshNode* nSrc, const gp_XYZ& pTgt, double& vol) const
291     {
292       SMESH_TNodeXYZ pSrc( nSrc );
293       return IsForward( &pSrc, &pTgt, vol );
294     }
295     bool IsForward(const gp_XY&         tgtUV,
296                    const SMDS_MeshNode* smoothedNode,
297                    const TopoDS_Face&   face,
298                    SMESH_MesherHelper&  helper,
299                    const double         refSign) const
300     {
301       gp_XY prevUV = helper.GetNodeUV( face, _nPrev, smoothedNode );
302       gp_XY nextUV = helper.GetNodeUV( face, _nNext, smoothedNode );
303       gp_Vec2d v1( tgtUV, prevUV ), v2( tgtUV, nextUV );
304       double d = v1 ^ v2;
305       return d*refSign > 1e-100;
306     }
307     bool IsMinAngleOK( const gp_XYZ& pTgt, double& minAngle ) const
308     {
309       SMESH_TNodeXYZ pPrev( _nPrev ), pNext( _nNext );
310       if ( !_nOpp ) // triangle
311       {
312         gp_Vec tp( pPrev - pTgt ), pn( pNext - pPrev ), nt( pTgt - pNext );
313         double tp2 = tp.SquareMagnitude();
314         double pn2 = pn.SquareMagnitude();
315         double nt2 = nt.SquareMagnitude();
316
317         if ( tp2 < pn2 && tp2 < nt2 )
318           minAngle = ( nt * -pn ) * ( nt * -pn ) / nt2 / pn2;
319         else if ( pn2 < nt2 )
320           minAngle = ( tp * -nt ) * ( tp * -nt ) / tp2 / nt2;
321         else
322           minAngle = ( pn * -tp ) * ( pn * -tp ) / pn2 / tp2;
323
324         static double theMaxCos2 = ( Cos( theMinSmoothTriaAngle * M_PI / 180. ) *
325                                      Cos( theMinSmoothTriaAngle * M_PI / 180. ));
326         return minAngle < theMaxCos2;
327       }
328       else // quadrangle
329       {
330         SMESH_TNodeXYZ pOpp( _nOpp );
331         gp_Vec tp( pPrev - pTgt ), po( pOpp - pPrev ), on( pNext - pOpp), nt( pTgt - pNext );
332         double tp2 = tp.SquareMagnitude();
333         double po2 = po.SquareMagnitude();
334         double on2 = on.SquareMagnitude();
335         double nt2 = nt.SquareMagnitude();
336         minAngle = Max( Max((( tp * -nt ) * ( tp * -nt ) / tp2 / nt2 ),
337                             (( po * -tp ) * ( po * -tp ) / po2 / tp2 )),
338                         Max((( on * -po ) * ( on * -po ) / on2 / po2 ),
339                             (( nt * -on ) * ( nt * -on ) / nt2 / on2 )));
340
341         static double theMaxCos2 = ( Cos( theMinSmoothQuadAngle * M_PI / 180. ) *
342                                      Cos( theMinSmoothQuadAngle * M_PI / 180. ));
343         return minAngle < theMaxCos2;
344       }
345     }
346     bool IsNeighbour(const _Simplex& other) const
347     {
348       return _nPrev == other._nNext || _nNext == other._nPrev;
349     }
350     bool Includes( const SMDS_MeshNode* node ) const { return _nPrev == node || _nNext == node; }
351     static void GetSimplices( const SMDS_MeshNode* node,
352                               vector<_Simplex>&   simplices,
353                               const set<TGeomID>& ingnoreShapes,
354                               const _SolidData*   dataToCheckOri = 0,
355                               const bool          toSort = false);
356     static void SortSimplices(vector<_Simplex>& simplices);
357   };
358   //--------------------------------------------------------------------------------
359   /*!
360    * Structure used to take into account surface curvature while smoothing
361    */
362   struct _Curvature
363   {
364     double   _r; // radius
365     double   _k; // factor to correct node smoothed position
366     double   _h2lenRatio; // avgNormProj / (2*avgDist)
367     gp_Pnt2d _uv; // UV used in putOnOffsetSurface()
368   public:
369     static _Curvature* New( double avgNormProj, double avgDist )
370     {
371       _Curvature* c = 0;
372       if ( fabs( avgNormProj / avgDist ) > 1./200 )
373       {
374         c = new _Curvature;
375         c->_r = avgDist * avgDist / avgNormProj;
376         c->_k = avgDist * avgDist / c->_r / c->_r;
377         //c->_k = avgNormProj / c->_r;
378         c->_k *= ( c->_r < 0 ? 1/1.1 : 1.1 ); // not to be too restrictive
379         c->_h2lenRatio = avgNormProj / ( avgDist + avgDist );
380
381         c->_uv.SetCoord( 0., 0. );
382       }
383       return c;
384     }
385     double lenDelta(double len) const { return _k * ( _r + len ); }
386     double lenDeltaByDist(double dist) const { return dist * _h2lenRatio; }
387   };
388   //--------------------------------------------------------------------------------
389
390   struct _2NearEdges;
391   struct _LayerEdge;
392   struct _EdgesOnShape;
393   struct _Smoother1D;
394   typedef map< const SMDS_MeshNode*, _LayerEdge*, TIDCompare > TNode2Edge;
395
396   //--------------------------------------------------------------------------------
397   /*!
398    * \brief Edge normal to surface, connecting a node on solid surface (_nodes[0])
399    * and a node of the most internal layer (_nodes.back())
400    */
401   struct _LayerEdge
402   {
403     typedef gp_XYZ (_LayerEdge::*PSmooFun)();
404
405     vector< const SMDS_MeshNode*> _nodes;
406
407     gp_XYZ              _normal;    // to boundary of solid
408     vector<gp_XYZ>      _pos;       // points computed during inflation
409     double              _len;       // length achived with the last inflation step
410     double              _maxLen;    // maximal possible length
411     double              _cosin;     // of angle (_normal ^ surface)
412     double              _minAngle;  // of _simplices
413     double              _lenFactor; // to compute _len taking _cosin into account
414     int                 _flags;
415
416     // simplices connected to the source node (_nodes[0]);
417     // used for smoothing and quality check of _LayerEdge's based on the FACE
418     vector<_Simplex>    _simplices;
419     vector<_LayerEdge*> _neibors; // all surrounding _LayerEdge's
420     PSmooFun            _smooFunction; // smoothing function
421     _Curvature*         _curvature;
422     // data for smoothing of _LayerEdge's based on the EDGE
423     _2NearEdges*        _2neibors;
424
425     enum EFlags { TO_SMOOTH       = 1,
426                   MOVED           = 2,   // set by _neibors[i]->SetNewLength()
427                   SMOOTHED        = 4,   // set by this->Smooth()
428                   DIFFICULT       = 8,   // near concave VERTEX
429                   ON_CONCAVE_FACE = 16,
430                   BLOCKED         = 32,  // not to inflate any more
431                   INTERSECTED     = 64,  // close intersection with a face found
432                   NORMAL_UPDATED  = 128,
433                   MARKED          = 256, // local usage
434                   MULTI_NORMAL    = 512, // a normal is invisible by some of surrounding faces
435                   NEAR_BOUNDARY   = 1024,// is near FACE boundary forcing smooth
436                   SMOOTHED_C1     = 2048,// is on _eosC1
437                   DISTORTED       = 4096,// was bad before smoothing
438                   RISKY_SWOL      = 8192 // SWOL is parallel to a source FACE
439     };
440     bool Is   ( EFlags f ) const { return _flags & f; }
441     void Set  ( EFlags f ) { _flags |= f; }
442     void Unset( EFlags f ) { _flags &= ~f; }
443
444     void SetNewLength( double len, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
445     bool SetNewLength2d( Handle(Geom_Surface)& surface,
446                          const TopoDS_Face&    F,
447                          _EdgesOnShape&        eos,
448                          SMESH_MesherHelper&   helper );
449     void SetDataByNeighbors( const SMDS_MeshNode* n1,
450                              const SMDS_MeshNode* n2,
451                              const _EdgesOnShape& eos,
452                              SMESH_MesherHelper&  helper);
453     void Block( _SolidData& data );
454     void InvalidateStep( size_t curStep, const _EdgesOnShape& eos, bool restoreLength=false );
455     void ChooseSmooFunction(const set< TGeomID >& concaveVertices,
456                             const TNode2Edge&     n2eMap);
457     void SmoothPos( const vector< double >& segLen, const double tol );
458     int  Smooth(const int step, const bool isConcaveFace, bool findBest);
459     int  Smooth(const int step, bool findBest, vector< _LayerEdge* >& toSmooth );
460     int  CheckNeiborsOnBoundary(vector< _LayerEdge* >* badNeibors = 0, bool * needSmooth = 0 );
461     void SmoothWoCheck();
462     bool SmoothOnEdge(Handle(ShapeAnalysis_Surface)& surface,
463                       const TopoDS_Face&             F,
464                       SMESH_MesherHelper&            helper);
465     void MoveNearConcaVer( const _EdgesOnShape*    eov,
466                            const _EdgesOnShape*    eos,
467                            const int               step,
468                            vector< _LayerEdge* > & badSmooEdges);
469     bool FindIntersection( SMESH_ElementSearcher&   searcher,
470                            double &                 distance,
471                            const double&            epsilon,
472                            _EdgesOnShape&           eos,
473                            const SMDS_MeshElement** face = 0);
474     bool SegTriaInter( const gp_Ax1&        lastSegment,
475                        const gp_XYZ&        p0,
476                        const gp_XYZ&        p1,
477                        const gp_XYZ&        p2,
478                        double&              dist,
479                        const double&        epsilon) const;
480     bool SegTriaInter( const gp_Ax1&        lastSegment,
481                        const SMDS_MeshNode* n0,
482                        const SMDS_MeshNode* n1,
483                        const SMDS_MeshNode* n2,
484                        double&              dist,
485                        const double&        epsilon) const
486     { return SegTriaInter( lastSegment,
487                            SMESH_TNodeXYZ( n0 ), SMESH_TNodeXYZ( n1 ), SMESH_TNodeXYZ( n2 ),
488                            dist, epsilon );
489     }
490     const gp_XYZ& PrevPos() const { return _pos[ _pos.size() - 2 ]; }
491     const gp_XYZ& PrevCheckPos() const { return _pos[ Is( NORMAL_UPDATED ) ? _pos.size()-2 : 0 ]; }
492     gp_Ax1 LastSegment(double& segLen, _EdgesOnShape& eos) const;
493     gp_XY  LastUV( const TopoDS_Face& F, _EdgesOnShape& eos ) const;
494     bool   IsOnEdge() const { return _2neibors; }
495     gp_XYZ Copy( _LayerEdge& other, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
496     void   SetCosin( double cosin );
497     void   SetNormal( const gp_XYZ& n ) { _normal = n; }
498     int    NbSteps() const { return _pos.size() - 1; } // nb inlation steps
499     bool   IsNeiborOnEdge( const _LayerEdge* edge ) const;
500     void   SetSmooLen( double len ) { // set _len at which smoothing is needed
501       _cosin = len; // as for _LayerEdge's on FACE _cosin is not used
502     }
503     double GetSmooLen() { return _cosin; } // for _LayerEdge's on FACE _cosin is not used
504
505     gp_XYZ smoothLaplacian();
506     gp_XYZ smoothAngular();
507     gp_XYZ smoothLengthWeighted();
508     gp_XYZ smoothCentroidal();
509     gp_XYZ smoothNefPolygon();
510
511     enum { FUN_LAPLACIAN, FUN_LENWEIGHTED, FUN_CENTROIDAL, FUN_NEFPOLY, FUN_ANGULAR, FUN_NB };
512     static const int theNbSmooFuns = FUN_NB;
513     static PSmooFun _funs[theNbSmooFuns];
514     static const char* _funNames[theNbSmooFuns+1];
515     int smooFunID( PSmooFun fun=0) const;
516   };
517   _LayerEdge::PSmooFun _LayerEdge::_funs[theNbSmooFuns] = { &_LayerEdge::smoothLaplacian,
518                                                             &_LayerEdge::smoothLengthWeighted,
519                                                             &_LayerEdge::smoothCentroidal,
520                                                             &_LayerEdge::smoothNefPolygon,
521                                                             &_LayerEdge::smoothAngular };
522   const char* _LayerEdge::_funNames[theNbSmooFuns+1] = { "Laplacian",
523                                                          "LengthWeighted",
524                                                          "Centroidal",
525                                                          "NefPolygon",
526                                                          "Angular",
527                                                          "None"};
528   struct _LayerEdgeCmp
529   {
530     bool operator () (const _LayerEdge* e1, const _LayerEdge* e2) const
531     {
532       const bool cmpNodes = ( e1 && e2 && e1->_nodes.size() && e2->_nodes.size() );
533       return cmpNodes ? ( e1->_nodes[0]->GetID() < e2->_nodes[0]->GetID()) : ( e1 < e2 );
534     }
535   };
536   //--------------------------------------------------------------------------------
537   /*!
538    * A 2D half plane used by _LayerEdge::smoothNefPolygon()
539    */
540   struct _halfPlane
541   {
542     gp_XY _pos, _dir, _inNorm;
543     bool IsOut( const gp_XY p, const double tol ) const
544     {
545       return _inNorm * ( p - _pos ) < -tol;
546     }
547     bool FindIntersection( const _halfPlane& hp, gp_XY & intPnt )
548     {
549       //const double eps = 1e-10;
550       double D = _dir.Crossed( hp._dir );
551       if ( fabs(D) < std::numeric_limits<double>::min())
552         return false;
553       gp_XY vec21 = _pos - hp._pos; 
554       double u = hp._dir.Crossed( vec21 ) / D; 
555       intPnt = _pos + _dir * u;
556       return true;
557     }
558   };
559   //--------------------------------------------------------------------------------
560   /*!
561    * Structure used to smooth a _LayerEdge based on an EDGE.
562    */
563   struct _2NearEdges
564   {
565     double               _wgt  [2]; // weights of _nodes
566     _LayerEdge*          _edges[2];
567
568      // normal to plane passing through _LayerEdge._normal and tangent of EDGE
569     gp_XYZ*              _plnNorm;
570
571     _2NearEdges() { _edges[0]=_edges[1]=0; _plnNorm = 0; }
572     const SMDS_MeshNode* tgtNode(bool is2nd) {
573       return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0;
574     }
575     const SMDS_MeshNode* srcNode(bool is2nd) {
576       return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0;
577     }
578     void reverse() {
579       std::swap( _wgt  [0], _wgt  [1] );
580       std::swap( _edges[0], _edges[1] );
581     }
582     void set( _LayerEdge* e1, _LayerEdge* e2, double w1, double w2 ) {
583       _edges[0] = e1; _edges[1] = e2; _wgt[0] = w1; _wgt[1] = w2;
584     }
585     bool include( const _LayerEdge* e ) {
586       return ( _edges[0] == e || _edges[1] == e );
587     }
588   };
589
590
591   //--------------------------------------------------------------------------------
592   /*!
593    * \brief Layers parameters got by averaging several hypotheses
594    */
595   struct AverageHyp
596   {
597     AverageHyp( const StdMeshers_ViscousLayers* hyp = 0 )
598       :_nbLayers(0), _nbHyps(0), _method(0), _thickness(0), _stretchFactor(0)
599     {
600       Add( hyp );
601     }
602     void Add( const StdMeshers_ViscousLayers* hyp )
603     {
604       if ( hyp )
605       {
606         _nbHyps++;
607         _nbLayers       = hyp->GetNumberLayers();
608         //_thickness     += hyp->GetTotalThickness();
609         _thickness      = Max( _thickness, hyp->GetTotalThickness() );
610         _stretchFactor += hyp->GetStretchFactor();
611         _method         = hyp->GetMethod();
612       }
613     }
614     double GetTotalThickness() const { return _thickness; /*_nbHyps ? _thickness / _nbHyps : 0;*/ }
615     double GetStretchFactor()  const { return _nbHyps ? _stretchFactor / _nbHyps : 0; }
616     int    GetNumberLayers()   const { return _nbLayers; }
617     int    GetMethod()         const { return _method; }
618
619     bool   UseSurfaceNormal()  const
620     { return _method == StdMeshers_ViscousLayers::SURF_OFFSET_SMOOTH; }
621     bool   ToSmooth()          const
622     { return _method == StdMeshers_ViscousLayers::SURF_OFFSET_SMOOTH; }
623     bool   IsOffsetMethod()    const
624     { return _method == StdMeshers_ViscousLayers::FACE_OFFSET; }
625
626   private:
627     int     _nbLayers, _nbHyps, _method;
628     double  _thickness, _stretchFactor;
629   };
630
631   //--------------------------------------------------------------------------------
632   /*!
633    * \brief _LayerEdge's on a shape and other shape data
634    */
635   struct _EdgesOnShape
636   {
637     vector< _LayerEdge* > _edges;
638
639     TopoDS_Shape          _shape;
640     TGeomID               _shapeID;
641     SMESH_subMesh *       _subMesh;
642     // face or edge w/o layer along or near which _edges are inflated
643     TopoDS_Shape          _sWOL;
644     bool                  _isRegularSWOL; // w/o singularities
645     // averaged StdMeshers_ViscousLayers parameters
646     AverageHyp            _hyp;
647     bool                  _toSmooth;
648     _Smoother1D*          _edgeSmoother;
649     vector< _EdgesOnShape* > _eosConcaVer; // edges at concave VERTEXes of a FACE
650     vector< _EdgesOnShape* > _eosC1; // to smooth together several C1 continues shapes
651
652     vector< gp_XYZ >         _faceNormals; // if _shape is FACE
653     vector< _EdgesOnShape* > _faceEOS; // to get _faceNormals of adjacent FACEs
654
655     Handle(ShapeAnalysis_Surface) _offsetSurf;
656     _LayerEdge*                   _edgeForOffset;
657
658     _SolidData*            _data; // parent SOLID
659
660     TopAbs_ShapeEnum ShapeType() const
661     { return _shape.IsNull() ? TopAbs_SHAPE : _shape.ShapeType(); }
662     TopAbs_ShapeEnum SWOLType() const
663     { return _sWOL.IsNull() ? TopAbs_SHAPE : _sWOL.ShapeType(); }
664     bool             HasC1( const _EdgesOnShape* other ) const
665     { return std::find( _eosC1.begin(), _eosC1.end(), other ) != _eosC1.end(); }
666     bool             GetNormal( const SMDS_MeshElement* face, gp_Vec& norm );
667     _SolidData&      GetData() const { return *_data; }
668
669     _EdgesOnShape(): _shapeID(-1), _subMesh(0), _toSmooth(false), _edgeSmoother(0) {}
670   };
671
672   //--------------------------------------------------------------------------------
673   /*!
674    * \brief Convex FACE whose radius of curvature is less than the thickness of 
675    *        layers. It is used to detect distortion of prisms based on a convex
676    *        FACE and to update normals to enable further increasing the thickness
677    */
678   struct _ConvexFace
679   {
680     TopoDS_Face                     _face;
681
682     // edges whose _simplices are used to detect prism distortion
683     vector< _LayerEdge* >           _simplexTestEdges;
684
685     // map a sub-shape to _SolidData::_edgesOnShape
686     map< TGeomID, _EdgesOnShape* >  _subIdToEOS;
687
688     bool                            _normalsFixed;
689
690     bool GetCenterOfCurvature( _LayerEdge*         ledge,
691                                BRepLProp_SLProps&  surfProp,
692                                SMESH_MesherHelper& helper,
693                                gp_Pnt &            center ) const;
694     bool CheckPrisms() const;
695   };
696
697   //--------------------------------------------------------------------------------
698   /*!
699    * \brief Structure holding _LayerEdge's based on EDGEs that will collide
700    *        at inflation up to the full thickness. A detected collision
701    *        is fixed in updateNormals()
702    */
703   struct _CollisionEdges
704   {
705     _LayerEdge*           _edge;
706     vector< _LayerEdge* > _intEdges; // each pair forms an intersected quadrangle
707     const SMDS_MeshNode* nSrc(int i) const { return _intEdges[i]->_nodes[0]; }
708     const SMDS_MeshNode* nTgt(int i) const { return _intEdges[i]->_nodes.back(); }
709   };
710
711   //--------------------------------------------------------------------------------
712   /*!
713    * \brief Data of a SOLID
714    */
715   struct _SolidData
716   {
717     typedef const StdMeshers_ViscousLayers* THyp;
718     TopoDS_Shape                    _solid;
719     TGeomID                         _index; // SOLID id
720     _MeshOfSolid*                   _proxyMesh;
721     list< THyp >                    _hyps;
722     list< TopoDS_Shape >            _hypShapes;
723     map< TGeomID, THyp >            _face2hyp; // filled if _hyps.size() > 1
724     set< TGeomID >                  _reversedFaceIds;
725     set< TGeomID >                  _ignoreFaceIds; // WOL FACEs and FACEs of other SOLIDs
726
727     double                          _stepSize, _stepSizeCoeff, _geomSize;
728     const SMDS_MeshNode*            _stepSizeNodes[2];
729
730     TNode2Edge                      _n2eMap; // nodes and _LayerEdge's based on them
731
732     // map to find _n2eMap of another _SolidData by a shrink shape shared by two _SolidData's
733     map< TGeomID, TNode2Edge* >     _s2neMap;
734     // _LayerEdge's with underlying shapes
735     vector< _EdgesOnShape >         _edgesOnShape;
736
737     // key:   an id of shape (EDGE or VERTEX) shared by a FACE with
738     //        layers and a FACE w/o layers
739     // value: the shape (FACE or EDGE) to shrink mesh on.
740     //       _LayerEdge's basing on nodes on key shape are inflated along the value shape
741     map< TGeomID, TopoDS_Shape >     _shrinkShape2Shape;
742
743     // Convex FACEs whose radius of curvature is less than the thickness of layers
744     map< TGeomID, _ConvexFace >      _convexFaces;
745
746     // shapes (EDGEs and VERTEXes) srink from which is forbidden due to collisions with
747     // the adjacent SOLID
748     set< TGeomID >                   _noShrinkShapes;
749
750     int                              _nbShapesToSmooth;
751
752     //map< TGeomID,Handle(Geom_Curve)> _edge2curve;
753
754     vector< _CollisionEdges >        _collisionEdges;
755     set< TGeomID >                   _concaveFaces;
756
757     double                           _maxThickness; // of all _hyps
758     double                           _minThickness; // of all _hyps
759
760     double                           _epsilon; // precision for SegTriaInter()
761
762     SMESH_MesherHelper*              _helper;
763
764     _SolidData(const TopoDS_Shape& s=TopoDS_Shape(),
765                _MeshOfSolid*       m=0)
766       :_solid(s), _proxyMesh(m), _helper(0) {}
767     ~_SolidData();
768
769     void SortOnEdge( const TopoDS_Edge& E, vector< _LayerEdge* >& edges);
770     void Sort2NeiborsOnEdge( vector< _LayerEdge* >& edges );
771
772     _ConvexFace* GetConvexFace( const TGeomID faceID ) {
773       map< TGeomID, _ConvexFace >::iterator id2face = _convexFaces.find( faceID );
774       return id2face == _convexFaces.end() ? 0 : & id2face->second;
775     }
776     _EdgesOnShape* GetShapeEdges(const TGeomID       shapeID );
777     _EdgesOnShape* GetShapeEdges(const TopoDS_Shape& shape );
778     _EdgesOnShape* GetShapeEdges(const _LayerEdge*   edge )
779     { return GetShapeEdges( edge->_nodes[0]->getshapeId() ); }
780
781     SMESH_MesherHelper& GetHelper() const { return *_helper; }
782
783     void UnmarkEdges() {
784       for ( size_t i = 0; i < _edgesOnShape.size(); ++i )
785         for ( size_t j = 0; j < _edgesOnShape[i]._edges.size(); ++j )
786           _edgesOnShape[i]._edges[j]->Unset( _LayerEdge::MARKED );
787     }
788     void AddShapesToSmooth( const set< _EdgesOnShape* >& shape,
789                             const set< _EdgesOnShape* >* edgesNoAnaSmooth=0 );
790
791     void PrepareEdgesToSmoothOnFace( _EdgesOnShape* eof, bool substituteSrcNodes );
792   };
793   //--------------------------------------------------------------------------------
794   /*!
795    * \brief Offset plane used in getNormalByOffset()
796    */
797   struct _OffsetPlane
798   {
799     gp_Pln _plane;
800     int    _faceIndex;
801     int    _faceIndexNext[2];
802     gp_Lin _lines[2]; // line of intersection with neighbor _OffsetPlane's
803     bool   _isLineOK[2];
804     _OffsetPlane() {
805       _isLineOK[0] = _isLineOK[1] = false; _faceIndexNext[0] = _faceIndexNext[1] = -1;
806     }
807     void   ComputeIntersectionLine( _OffsetPlane& pln );
808     gp_XYZ GetCommonPoint(bool& isFound) const;
809     int    NbLines() const { return _isLineOK[0] + _isLineOK[1]; }
810   };
811   //--------------------------------------------------------------------------------
812   /*!
813    * \brief Container of centers of curvature at nodes on an EDGE bounding _ConvexFace
814    */
815   struct _CentralCurveOnEdge
816   {
817     bool                  _isDegenerated;
818     vector< gp_Pnt >      _curvaCenters;
819     vector< _LayerEdge* > _ledges;
820     vector< gp_XYZ >      _normals; // new normal for each of _ledges
821     vector< double >      _segLength2;
822
823     TopoDS_Edge           _edge;
824     TopoDS_Face           _adjFace;
825     bool                  _adjFaceToSmooth;
826
827     void Append( const gp_Pnt& center, _LayerEdge* ledge )
828     {
829       if ( _curvaCenters.size() > 0 )
830         _segLength2.push_back( center.SquareDistance( _curvaCenters.back() ));
831       _curvaCenters.push_back( center );
832       _ledges.push_back( ledge );
833       _normals.push_back( ledge->_normal );
834     }
835     bool FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal );
836     void SetShapes( const TopoDS_Edge&  edge,
837                     const _ConvexFace&  convFace,
838                     _SolidData&         data,
839                     SMESH_MesherHelper& helper);
840   };
841   //--------------------------------------------------------------------------------
842   /*!
843    * \brief Data of node on a shrinked FACE
844    */
845   struct _SmoothNode
846   {
847     const SMDS_MeshNode*         _node;
848     vector<_Simplex>             _simplices; // for quality check
849
850     enum SmoothType { LAPLACIAN, CENTROIDAL, ANGULAR, TFI };
851
852     bool Smooth(int&                  badNb,
853                 Handle(Geom_Surface)& surface,
854                 SMESH_MesherHelper&   helper,
855                 const double          refSign,
856                 SmoothType            how,
857                 bool                  set3D);
858
859     gp_XY computeAngularPos(vector<gp_XY>& uv,
860                             const gp_XY&   uvToFix,
861                             const double   refSign );
862   };
863   //--------------------------------------------------------------------------------
864   /*!
865    * \brief Builder of viscous layers
866    */
867   class _ViscousBuilder
868   {
869   public:
870     _ViscousBuilder();
871     // does it's job
872     SMESH_ComputeErrorPtr Compute(SMESH_Mesh&         mesh,
873                                   const TopoDS_Shape& shape);
874     // check validity of hypotheses
875     SMESH_ComputeErrorPtr CheckHypotheses( SMESH_Mesh&         mesh,
876                                            const TopoDS_Shape& shape );
877
878     // restore event listeners used to clear an inferior dim sub-mesh modified by viscous layers
879     void RestoreListeners();
880
881     // computes SMESH_ProxyMesh::SubMesh::_n2n;
882     bool MakeN2NMap( _MeshOfSolid* pm );
883
884   private:
885
886     bool findSolidsWithLayers();
887     bool findFacesWithLayers(const bool onlyWith=false);
888     void getIgnoreFaces(const TopoDS_Shape&             solid,
889                         const StdMeshers_ViscousLayers* hyp,
890                         const TopoDS_Shape&             hypShape,
891                         set<TGeomID>&                   ignoreFaces);
892     bool makeLayer(_SolidData& data);
893     void setShapeData( _EdgesOnShape& eos, SMESH_subMesh* sm, _SolidData& data );
894     bool setEdgeData( _LayerEdge& edge, _EdgesOnShape& eos,
895                       SMESH_MesherHelper& helper, _SolidData& data);
896     gp_XYZ getFaceNormal(const SMDS_MeshNode* n,
897                          const TopoDS_Face&   face,
898                          SMESH_MesherHelper&  helper,
899                          bool&                isOK,
900                          bool                 shiftInside=false);
901     bool getFaceNormalAtSingularity(const gp_XY&        uv,
902                                     const TopoDS_Face&  face,
903                                     SMESH_MesherHelper& helper,
904                                     gp_Dir&             normal );
905     gp_XYZ getWeigthedNormal( const _LayerEdge*                edge );
906     gp_XYZ getNormalByOffset( _LayerEdge*                      edge,
907                               std::pair< TopoDS_Face, gp_XYZ > fId2Normal[],
908                               int                              nbFaces );
909     bool findNeiborsOnEdge(const _LayerEdge*     edge,
910                            const SMDS_MeshNode*& n1,
911                            const SMDS_MeshNode*& n2,
912                            _EdgesOnShape&        eos,
913                            _SolidData&           data);
914     void findSimplexTestEdges( _SolidData&                    data,
915                                vector< vector<_LayerEdge*> >& edgesByGeom);
916     void computeGeomSize( _SolidData& data );
917     bool findShapesToSmooth( _SolidData& data);
918     void limitStepSizeByCurvature( _SolidData&  data );
919     void limitStepSize( _SolidData&             data,
920                         const SMDS_MeshElement* face,
921                         const _LayerEdge*       maxCosinEdge );
922     void limitStepSize( _SolidData& data, const double minSize);
923     bool inflate(_SolidData& data);
924     bool smoothAndCheck(_SolidData& data, const int nbSteps, double & distToIntersection);
925     int  invalidateBadSmooth( _SolidData&               data,
926                               SMESH_MesherHelper&       helper,
927                               vector< _LayerEdge* >&    badSmooEdges,
928                               vector< _EdgesOnShape* >& eosC1,
929                               const int                 infStep );
930     void makeOffsetSurface( _EdgesOnShape& eos, SMESH_MesherHelper& );
931     void putOnOffsetSurface( _EdgesOnShape& eos, int infStep, int smooStep=0, bool moveAll=false );
932     void findCollisionEdges( _SolidData& data, SMESH_MesherHelper& helper );
933     bool updateNormals( _SolidData& data, SMESH_MesherHelper& helper, int stepNb, double stepSize );
934     bool updateNormalsOfConvexFaces( _SolidData&         data,
935                                      SMESH_MesherHelper& helper,
936                                      int                 stepNb );
937     void updateNormalsOfC1Vertices( _SolidData& data );
938     bool updateNormalsOfSmoothed( _SolidData&         data,
939                                   SMESH_MesherHelper& helper,
940                                   const int           nbSteps,
941                                   const double        stepSize );
942     bool isNewNormalOk( _SolidData&   data,
943                         _LayerEdge&   edge,
944                         const gp_XYZ& newNormal);
945     bool refine(_SolidData& data);
946     bool shrink();
947     bool prepareEdgeToShrink( _LayerEdge& edge, _EdgesOnShape& eos,
948                               SMESH_MesherHelper& helper,
949                               const SMESHDS_SubMesh* faceSubMesh );
950     void restoreNoShrink( _LayerEdge& edge ) const;
951     void fixBadFaces(const TopoDS_Face&          F,
952                      SMESH_MesherHelper&         helper,
953                      const bool                  is2D,
954                      const int                   step,
955                      set<const SMDS_MeshNode*> * involvedNodes=NULL);
956     bool addBoundaryElements();
957
958     bool error( const string& text, int solidID=-1 );
959     SMESHDS_Mesh* getMeshDS() const { return _mesh->GetMeshDS(); }
960
961     // debug
962     void makeGroupOfLE();
963
964     SMESH_Mesh*           _mesh;
965     SMESH_ComputeErrorPtr _error;
966
967     vector< _SolidData >  _sdVec;
968     int                   _tmpFaceID;
969   };
970   //--------------------------------------------------------------------------------
971   /*!
972    * \brief Shrinker of nodes on the EDGE
973    */
974   class _Shrinker1D
975   {
976     TopoDS_Edge                   _geomEdge;
977     vector<double>                _initU;
978     vector<double>                _normPar;
979     vector<const SMDS_MeshNode*>  _nodes;
980     const _LayerEdge*             _edges[2];
981     bool                          _done;
982   public:
983     void AddEdge( const _LayerEdge* e, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
984     void Compute(bool set3D, SMESH_MesherHelper& helper);
985     void RestoreParams();
986     void SwapSrcTgtNodes(SMESHDS_Mesh* mesh);
987     const TopoDS_Edge& GeomEdge() const { return _geomEdge; }
988     const SMDS_MeshNode* TgtNode( bool is2nd ) const
989     { return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0; }
990     const SMDS_MeshNode* SrcNode( bool is2nd ) const
991     { return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0; }
992   };
993   //--------------------------------------------------------------------------------
994   /*!
995    * \brief Smoother of _LayerEdge's on EDGE.
996    */
997   struct _Smoother1D
998   {
999     struct OffPnt // point of the offsetted EDGE
1000     {
1001       gp_XYZ      _xyz;    // coord of a point inflated from EDGE w/o smooth
1002       double      _len;    // length reached at previous inflation step
1003       _2NearEdges _2edges; // 2 neighbor _LayerEdge's
1004       double Distance( const OffPnt& p ) const { return ( _xyz - p._xyz ).Modulus(); }
1005     };
1006     vector< OffPnt >   _offPoints;
1007     vector< double >   _leParams; // normalized param of _eos._edges on EDGE
1008     Handle(Geom_Curve) _anaCurve; // for analytic smooth
1009     _LayerEdge         _leOnV[2]; // _LayerEdge's holding normal to the EDGE at VERTEXes
1010     size_t             _iSeg[2];  // index of segment where extreme tgt node is projected
1011     _EdgesOnShape&     _eos;
1012
1013     static Handle(Geom_Curve) CurveForSmooth( const TopoDS_Edge&  E,
1014                                               _EdgesOnShape&      eos,
1015                                               SMESH_MesherHelper& helper);
1016
1017     _Smoother1D( Handle(Geom_Curve) curveForSmooth,
1018                  _EdgesOnShape&     eos )
1019       : _anaCurve( curveForSmooth ), _eos( eos )
1020     {
1021     }
1022     bool Perform(_SolidData&                    data,
1023                  Handle(ShapeAnalysis_Surface)& surface,
1024                  const TopoDS_Face&             F,
1025                  SMESH_MesherHelper&            helper )
1026     {
1027       if ( _leParams.empty() || ( !isAnalytic() && _offPoints.empty() ))
1028         prepare( data );
1029
1030       if ( isAnalytic() )
1031         return smoothAnalyticEdge( data, surface, F, helper );
1032       else
1033         return smoothComplexEdge ( data, surface, F, helper );
1034     }
1035     void prepare(_SolidData& data );
1036
1037     bool smoothAnalyticEdge( _SolidData&                    data,
1038                              Handle(ShapeAnalysis_Surface)& surface,
1039                              const TopoDS_Face&             F,
1040                              SMESH_MesherHelper&            helper);
1041
1042     bool smoothComplexEdge( _SolidData&                    data,
1043                             Handle(ShapeAnalysis_Surface)& surface,
1044                             const TopoDS_Face&             F,
1045                             SMESH_MesherHelper&            helper);
1046
1047     void setNormalOnV( const bool          is2nd,
1048                        SMESH_MesherHelper& helper);
1049
1050     _LayerEdge* getLEdgeOnV( bool is2nd )
1051     {
1052       return _eos._edges[ is2nd ? _eos._edges.size()-1 : 0 ]->_2neibors->_edges[ is2nd ];
1053     }
1054     bool isAnalytic() const { return !_anaCurve.IsNull(); }
1055   };
1056   //--------------------------------------------------------------------------------
1057   /*!
1058    * \brief Class of temporary mesh face.
1059    * We can't use SMDS_FaceOfNodes since it's impossible to set it's ID which is
1060    * needed because SMESH_ElementSearcher internaly uses set of elements sorted by ID
1061    */
1062   struct _TmpMeshFace : public SMDS_MeshElement
1063   {
1064     vector<const SMDS_MeshNode* > _nn;
1065     _TmpMeshFace( const vector<const SMDS_MeshNode*>& nodes,
1066                   int id, int faceID=-1, int idInFace=-1):
1067       SMDS_MeshElement(id), _nn(nodes) { setShapeId(faceID); setIdInShape(idInFace); }
1068     virtual const SMDS_MeshNode* GetNode(const int ind) const { return _nn[ind]; }
1069     virtual SMDSAbs_ElementType  GetType() const              { return SMDSAbs_Face; }
1070     virtual vtkIdType GetVtkType() const                      { return -1; }
1071     virtual SMDSAbs_EntityType   GetEntityType() const        { return SMDSEntity_Last; }
1072     virtual SMDSAbs_GeometryType GetGeomType() const
1073     { return _nn.size() == 3 ? SMDSGeom_TRIANGLE : SMDSGeom_QUADRANGLE; }
1074     virtual SMDS_ElemIteratorPtr elementsIterator(SMDSAbs_ElementType) const
1075     { return SMDS_ElemIteratorPtr( new SMDS_NodeVectorElemIterator( _nn.begin(), _nn.end()));}
1076   };
1077   //--------------------------------------------------------------------------------
1078   /*!
1079    * \brief Class of temporary mesh face storing _LayerEdge it's based on
1080    */
1081   struct _TmpMeshFaceOnEdge : public _TmpMeshFace
1082   {
1083     _LayerEdge *_le1, *_le2;
1084     _TmpMeshFaceOnEdge( _LayerEdge* le1, _LayerEdge* le2, int ID ):
1085       _TmpMeshFace( vector<const SMDS_MeshNode*>(4), ID ), _le1(le1), _le2(le2)
1086     {
1087       _nn[0]=_le1->_nodes[0];
1088       _nn[1]=_le1->_nodes.back();
1089       _nn[2]=_le2->_nodes.back();
1090       _nn[3]=_le2->_nodes[0];
1091     }
1092     gp_XYZ GetDir() const // return average direction of _LayerEdge's, normal to EDGE
1093     {
1094       SMESH_TNodeXYZ p0s( _nn[0] );
1095       SMESH_TNodeXYZ p0t( _nn[1] );
1096       SMESH_TNodeXYZ p1t( _nn[2] );
1097       SMESH_TNodeXYZ p1s( _nn[3] );
1098       gp_XYZ  v0 = p0t - p0s;
1099       gp_XYZ  v1 = p1t - p1s;
1100       gp_XYZ v01 = p1s - p0s;
1101       gp_XYZ   n = ( v0 ^ v01 ) + ( v1 ^ v01 );
1102       gp_XYZ   d = v01 ^ n;
1103       d.Normalize();
1104       return d;
1105     }
1106     gp_XYZ GetDir(_LayerEdge* le1, _LayerEdge* le2) // return average direction of _LayerEdge's
1107     {
1108       _nn[0]=le1->_nodes[0];
1109       _nn[1]=le1->_nodes.back();
1110       _nn[2]=le2->_nodes.back();
1111       _nn[3]=le2->_nodes[0];
1112       return GetDir();
1113     }
1114   };
1115   //--------------------------------------------------------------------------------
1116   /*!
1117    * \brief Retriever of node coordinates either directly or from a surface by node UV.
1118    * \warning Location of a surface is ignored
1119    */
1120   struct _NodeCoordHelper
1121   {
1122     SMESH_MesherHelper&        _helper;
1123     const TopoDS_Face&         _face;
1124     Handle(Geom_Surface)       _surface;
1125     gp_XYZ (_NodeCoordHelper::* _fun)(const SMDS_MeshNode* n) const;
1126
1127     _NodeCoordHelper(const TopoDS_Face& F, SMESH_MesherHelper& helper, bool is2D)
1128       : _helper( helper ), _face( F )
1129     {
1130       if ( is2D )
1131       {
1132         TopLoc_Location loc;
1133         _surface = BRep_Tool::Surface( _face, loc );
1134       }
1135       if ( _surface.IsNull() )
1136         _fun = & _NodeCoordHelper::direct;
1137       else
1138         _fun = & _NodeCoordHelper::byUV;
1139     }
1140     gp_XYZ operator()(const SMDS_MeshNode* n) const { return (this->*_fun)( n ); }
1141
1142   private:
1143     gp_XYZ direct(const SMDS_MeshNode* n) const
1144     {
1145       return SMESH_TNodeXYZ( n );
1146     }
1147     gp_XYZ byUV  (const SMDS_MeshNode* n) const
1148     {
1149       gp_XY uv = _helper.GetNodeUV( _face, n );
1150       return _surface->Value( uv.X(), uv.Y() ).XYZ();
1151     }
1152   };
1153
1154   //================================================================================
1155   /*!
1156    * \brief Check angle between vectors 
1157    */
1158   //================================================================================
1159
1160   inline bool isLessAngle( const gp_Vec& v1, const gp_Vec& v2, const double cos )
1161   {
1162     double dot = v1 * v2; // cos * |v1| * |v2|
1163     double l1  = v1.SquareMagnitude();
1164     double l2  = v2.SquareMagnitude();
1165     return (( dot * cos >= 0 ) && 
1166             ( dot * dot ) / l1 / l2 >= ( cos * cos ));
1167   }
1168
1169 } // namespace VISCOUS_3D
1170
1171
1172
1173 //================================================================================
1174 // StdMeshers_ViscousLayers hypothesis
1175 //
1176 StdMeshers_ViscousLayers::StdMeshers_ViscousLayers(int hypId, int studyId, SMESH_Gen* gen)
1177   :SMESH_Hypothesis(hypId, studyId, gen),
1178    _isToIgnoreShapes(1), _nbLayers(1), _thickness(1), _stretchFactor(1),
1179    _method( SURF_OFFSET_SMOOTH )
1180 {
1181   _name = StdMeshers_ViscousLayers::GetHypType();
1182   _param_algo_dim = -3; // auxiliary hyp used by 3D algos
1183 } // --------------------------------------------------------------------------------
1184 void StdMeshers_ViscousLayers::SetBndShapes(const std::vector<int>& faceIds, bool toIgnore)
1185 {
1186   if ( faceIds != _shapeIds )
1187     _shapeIds = faceIds, NotifySubMeshesHypothesisModification();
1188   if ( _isToIgnoreShapes != toIgnore )
1189     _isToIgnoreShapes = toIgnore, NotifySubMeshesHypothesisModification();
1190 } // --------------------------------------------------------------------------------
1191 void StdMeshers_ViscousLayers::SetTotalThickness(double thickness)
1192 {
1193   if ( thickness != _thickness )
1194     _thickness = thickness, NotifySubMeshesHypothesisModification();
1195 } // --------------------------------------------------------------------------------
1196 void StdMeshers_ViscousLayers::SetNumberLayers(int nb)
1197 {
1198   if ( _nbLayers != nb )
1199     _nbLayers = nb, NotifySubMeshesHypothesisModification();
1200 } // --------------------------------------------------------------------------------
1201 void StdMeshers_ViscousLayers::SetStretchFactor(double factor)
1202 {
1203   if ( _stretchFactor != factor )
1204     _stretchFactor = factor, NotifySubMeshesHypothesisModification();
1205 } // --------------------------------------------------------------------------------
1206 void StdMeshers_ViscousLayers::SetMethod( ExtrusionMethod method )
1207 {
1208   if ( _method != method )
1209     _method = method, NotifySubMeshesHypothesisModification();
1210 } // --------------------------------------------------------------------------------
1211 SMESH_ProxyMesh::Ptr
1212 StdMeshers_ViscousLayers::Compute(SMESH_Mesh&         theMesh,
1213                                   const TopoDS_Shape& theShape,
1214                                   const bool          toMakeN2NMap) const
1215 {
1216   using namespace VISCOUS_3D;
1217   _ViscousBuilder bulder;
1218   SMESH_ComputeErrorPtr err = bulder.Compute( theMesh, theShape );
1219   if ( err && !err->IsOK() )
1220     return SMESH_ProxyMesh::Ptr();
1221
1222   vector<SMESH_ProxyMesh::Ptr> components;
1223   TopExp_Explorer exp( theShape, TopAbs_SOLID );
1224   for ( ; exp.More(); exp.Next() )
1225   {
1226     if ( _MeshOfSolid* pm =
1227          _ViscousListener::GetSolidMesh( &theMesh, exp.Current(), /*toCreate=*/false))
1228     {
1229       if ( toMakeN2NMap && !pm->_n2nMapComputed )
1230         if ( !bulder.MakeN2NMap( pm ))
1231           return SMESH_ProxyMesh::Ptr();
1232       components.push_back( SMESH_ProxyMesh::Ptr( pm ));
1233       pm->myIsDeletable = false; // it will de deleted by boost::shared_ptr
1234
1235       if ( pm->_warning && !pm->_warning->IsOK() )
1236       {
1237         SMESH_subMesh* sm = theMesh.GetSubMesh( exp.Current() );
1238         SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1239         if ( !smError || smError->IsOK() )
1240           smError = pm->_warning;
1241       }
1242     }
1243     _ViscousListener::RemoveSolidMesh ( &theMesh, exp.Current() );
1244   }
1245   switch ( components.size() )
1246   {
1247   case 0: break;
1248
1249   case 1: return components[0];
1250
1251   default: return SMESH_ProxyMesh::Ptr( new SMESH_ProxyMesh( components ));
1252   }
1253   return SMESH_ProxyMesh::Ptr();
1254 } // --------------------------------------------------------------------------------
1255 std::ostream & StdMeshers_ViscousLayers::SaveTo(std::ostream & save)
1256 {
1257   save << " " << _nbLayers
1258        << " " << _thickness
1259        << " " << _stretchFactor
1260        << " " << _shapeIds.size();
1261   for ( size_t i = 0; i < _shapeIds.size(); ++i )
1262     save << " " << _shapeIds[i];
1263   save << " " << !_isToIgnoreShapes; // negate to keep the behavior in old studies.
1264   save << " " << _method;
1265   return save;
1266 } // --------------------------------------------------------------------------------
1267 std::istream & StdMeshers_ViscousLayers::LoadFrom(std::istream & load)
1268 {
1269   int nbFaces, faceID, shapeToTreat, method;
1270   load >> _nbLayers >> _thickness >> _stretchFactor >> nbFaces;
1271   while ( (int) _shapeIds.size() < nbFaces && load >> faceID )
1272     _shapeIds.push_back( faceID );
1273   if ( load >> shapeToTreat ) {
1274     _isToIgnoreShapes = !shapeToTreat;
1275     if ( load >> method )
1276       _method = (ExtrusionMethod) method;
1277   }
1278   else {
1279     _isToIgnoreShapes = true; // old behavior
1280   }
1281   return load;
1282 } // --------------------------------------------------------------------------------
1283 bool StdMeshers_ViscousLayers::SetParametersByMesh(const SMESH_Mesh*   theMesh,
1284                                                    const TopoDS_Shape& theShape)
1285 {
1286   // TODO
1287   return false;
1288 } // --------------------------------------------------------------------------------
1289 SMESH_ComputeErrorPtr
1290 StdMeshers_ViscousLayers::CheckHypothesis(SMESH_Mesh&                          theMesh,
1291                                           const TopoDS_Shape&                  theShape,
1292                                           SMESH_Hypothesis::Hypothesis_Status& theStatus)
1293 {
1294   VISCOUS_3D::_ViscousBuilder bulder;
1295   SMESH_ComputeErrorPtr err = bulder.CheckHypotheses( theMesh, theShape );
1296   if ( err && !err->IsOK() )
1297     theStatus = SMESH_Hypothesis::HYP_INCOMPAT_HYPS;
1298   else
1299     theStatus = SMESH_Hypothesis::HYP_OK;
1300
1301   return err;
1302 }
1303 // --------------------------------------------------------------------------------
1304 bool StdMeshers_ViscousLayers::IsShapeWithLayers(int shapeIndex) const
1305 {
1306   bool isIn =
1307     ( std::find( _shapeIds.begin(), _shapeIds.end(), shapeIndex ) != _shapeIds.end() );
1308   return IsToIgnoreShapes() ? !isIn : isIn;
1309 }
1310 // END StdMeshers_ViscousLayers hypothesis
1311 //================================================================================
1312
1313 namespace VISCOUS_3D
1314 {
1315   gp_XYZ getEdgeDir( const TopoDS_Edge& E, const TopoDS_Vertex& fromV )
1316   {
1317     gp_Vec dir;
1318     double f,l;
1319     Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1320     if ( c.IsNull() ) return gp_XYZ( Precision::Infinite(), 1e100, 1e100 );
1321     gp_Pnt p = BRep_Tool::Pnt( fromV );
1322     double distF = p.SquareDistance( c->Value( f ));
1323     double distL = p.SquareDistance( c->Value( l ));
1324     c->D1(( distF < distL ? f : l), p, dir );
1325     if ( distL < distF ) dir.Reverse();
1326     return dir.XYZ();
1327   }
1328   //--------------------------------------------------------------------------------
1329   gp_XYZ getEdgeDir( const TopoDS_Edge& E, const SMDS_MeshNode* atNode,
1330                      SMESH_MesherHelper& helper)
1331   {
1332     gp_Vec dir;
1333     double f,l; gp_Pnt p;
1334     Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1335     if ( c.IsNull() ) return gp_XYZ( Precision::Infinite(), 1e100, 1e100 );
1336     double u = helper.GetNodeU( E, atNode );
1337     c->D1( u, p, dir );
1338     return dir.XYZ();
1339   }
1340   //--------------------------------------------------------------------------------
1341   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1342                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok,
1343                      double* cosin=0);
1344   //--------------------------------------------------------------------------------
1345   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Edge& fromE,
1346                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok)
1347   {
1348     double f,l;
1349     Handle(Geom_Curve) c = BRep_Tool::Curve( fromE, f, l );
1350     if ( c.IsNull() )
1351     {
1352       TopoDS_Vertex v = helper.IthVertex( 0, fromE );
1353       return getFaceDir( F, v, node, helper, ok );
1354     }
1355     gp_XY uv = helper.GetNodeUV( F, node, 0, &ok );
1356     Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
1357     gp_Pnt p; gp_Vec du, dv, norm;
1358     surface->D1( uv.X(),uv.Y(), p, du,dv );
1359     norm = du ^ dv;
1360
1361     double u = helper.GetNodeU( fromE, node, 0, &ok );
1362     c->D1( u, p, du );
1363     TopAbs_Orientation o = helper.GetSubShapeOri( F.Oriented(TopAbs_FORWARD), fromE);
1364     if ( o == TopAbs_REVERSED )
1365       du.Reverse();
1366
1367     gp_Vec dir = norm ^ du;
1368
1369     if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX &&
1370          helper.IsClosedEdge( fromE ))
1371     {
1372       if ( fabs(u-f) < fabs(u-l)) c->D1( l, p, dv );
1373       else                        c->D1( f, p, dv );
1374       if ( o == TopAbs_REVERSED )
1375         dv.Reverse();
1376       gp_Vec dir2 = norm ^ dv;
1377       dir = dir.Normalized() + dir2.Normalized();
1378     }
1379     return dir.XYZ();
1380   }
1381   //--------------------------------------------------------------------------------
1382   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1383                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper,
1384                      bool& ok, double* cosin)
1385   {
1386     TopoDS_Face faceFrw = F;
1387     faceFrw.Orientation( TopAbs_FORWARD );
1388     //double f,l; TopLoc_Location loc;
1389     TopoDS_Edge edges[2]; // sharing a vertex
1390     size_t nbEdges = 0;
1391     {
1392       TopoDS_Vertex VV[2];
1393       TopExp_Explorer exp( faceFrw, TopAbs_EDGE );
1394       for ( ; exp.More() && nbEdges < 2; exp.Next() )
1395       {
1396         const TopoDS_Edge& e = TopoDS::Edge( exp.Current() );
1397         if ( SMESH_Algo::isDegenerated( e )) continue;
1398         TopExp::Vertices( e, VV[0], VV[1], /*CumOri=*/true );
1399         if ( VV[1].IsSame( fromV )) {
1400           nbEdges += edges[ 0 ].IsNull();
1401           edges[ 0 ] = e;
1402         }
1403         else if ( VV[0].IsSame( fromV )) {
1404           nbEdges += edges[ 1 ].IsNull();
1405           edges[ 1 ] = e;
1406         }
1407       }
1408     }
1409     gp_XYZ dir(0,0,0), edgeDir[2];
1410     if ( nbEdges == 2 )
1411     {
1412       // get dirs of edges going fromV
1413       ok = true;
1414       for ( size_t i = 0; i < nbEdges && ok; ++i )
1415       {
1416         edgeDir[i] = getEdgeDir( edges[i], fromV );
1417         double size2 = edgeDir[i].SquareModulus();
1418         if (( ok = size2 > numeric_limits<double>::min() ))
1419           edgeDir[i] /= sqrt( size2 );
1420       }
1421       if ( !ok ) return dir;
1422
1423       // get angle between the 2 edges
1424       gp_Vec faceNormal;
1425       double angle = helper.GetAngle( edges[0], edges[1], faceFrw, fromV, &faceNormal );
1426       if ( Abs( angle ) < 5 * M_PI/180 )
1427       {
1428         dir = ( faceNormal.XYZ() ^ edgeDir[0].Reversed()) + ( faceNormal.XYZ() ^ edgeDir[1] );
1429       }
1430       else
1431       {
1432         dir = edgeDir[0] + edgeDir[1];
1433         if ( angle < 0 )
1434           dir.Reverse();
1435       }
1436       if ( cosin ) {
1437         double angle = gp_Vec( edgeDir[0] ).Angle( dir );
1438         *cosin = Cos( angle );
1439       }
1440     }
1441     else if ( nbEdges == 1 )
1442     {
1443       dir = getFaceDir( faceFrw, edges[ edges[0].IsNull() ], node, helper, ok );
1444       if ( cosin ) *cosin = 1.;
1445     }
1446     else
1447     {
1448       ok = false;
1449     }
1450
1451     return dir;
1452   }
1453
1454   //================================================================================
1455   /*!
1456    * \brief Finds concave VERTEXes of a FACE
1457    */
1458   //================================================================================
1459
1460   bool getConcaveVertices( const TopoDS_Face&  F,
1461                            SMESH_MesherHelper& helper,
1462                            set< TGeomID >*     vertices = 0)
1463   {
1464     // check angles at VERTEXes
1465     TError error;
1466     TSideVector wires = StdMeshers_FaceSide::GetFaceWires( F, *helper.GetMesh(), 0, error );
1467     for ( size_t iW = 0; iW < wires.size(); ++iW )
1468     {
1469       const int nbEdges = wires[iW]->NbEdges();
1470       if ( nbEdges < 2 && SMESH_Algo::isDegenerated( wires[iW]->Edge(0)))
1471         continue;
1472       for ( int iE1 = 0; iE1 < nbEdges; ++iE1 )
1473       {
1474         if ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE1 ))) continue;
1475         int iE2 = ( iE1 + 1 ) % nbEdges;
1476         while ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE2 )))
1477           iE2 = ( iE2 + 1 ) % nbEdges;
1478         TopoDS_Vertex V = wires[iW]->FirstVertex( iE2 );
1479         double angle = helper.GetAngle( wires[iW]->Edge( iE1 ),
1480                                         wires[iW]->Edge( iE2 ), F, V );
1481         if ( angle < -5. * M_PI / 180. )
1482         {
1483           if ( !vertices )
1484             return true;
1485           vertices->insert( helper.GetMeshDS()->ShapeToIndex( V ));
1486         }
1487       }
1488     }
1489     return vertices ? !vertices->empty() : false;
1490   }
1491
1492   //================================================================================
1493   /*!
1494    * \brief Returns true if a FACE is bound by a concave EDGE
1495    */
1496   //================================================================================
1497
1498   bool isConcave( const TopoDS_Face&  F,
1499                   SMESH_MesherHelper& helper,
1500                   set< TGeomID >*     vertices = 0 )
1501   {
1502     bool isConcv = false;
1503     // if ( helper.Count( F, TopAbs_WIRE, /*useMap=*/false) > 1 )
1504     //   return true;
1505     gp_Vec2d drv1, drv2;
1506     gp_Pnt2d p;
1507     TopExp_Explorer eExp( F.Oriented( TopAbs_FORWARD ), TopAbs_EDGE );
1508     for ( ; eExp.More(); eExp.Next() )
1509     {
1510       const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
1511       if ( SMESH_Algo::isDegenerated( E )) continue;
1512       // check if 2D curve is concave
1513       BRepAdaptor_Curve2d curve( E, F );
1514       const int nbIntervals = curve.NbIntervals( GeomAbs_C2 );
1515       TColStd_Array1OfReal intervals(1, nbIntervals + 1 );
1516       curve.Intervals( intervals, GeomAbs_C2 );
1517       bool isConvex = true;
1518       for ( int i = 1; i <= nbIntervals && isConvex; ++i )
1519       {
1520         double u1 = intervals( i );
1521         double u2 = intervals( i+1 );
1522         curve.D2( 0.5*( u1+u2 ), p, drv1, drv2 );
1523         double cross = drv1 ^ drv2;
1524         if ( E.Orientation() == TopAbs_REVERSED )
1525           cross = -cross;
1526         isConvex = ( cross > -1e-9 ); // 0.1 );
1527       }
1528       if ( !isConvex )
1529       {
1530         //cout << "Concave FACE " << helper.GetMeshDS()->ShapeToIndex( F ) << endl;
1531         isConcv = true;
1532         if ( vertices )
1533           break;
1534         else
1535           return true;
1536       }
1537     }
1538
1539     // check angles at VERTEXes
1540     if ( getConcaveVertices( F, helper, vertices ))
1541       isConcv = true;
1542
1543     return isConcv;
1544   }
1545
1546   //================================================================================
1547   /*!
1548    * \brief Computes mimimal distance of face in-FACE nodes from an EDGE
1549    *  \param [in] face - the mesh face to treat
1550    *  \param [in] nodeOnEdge - a node on the EDGE
1551    *  \param [out] faceSize - the computed distance
1552    *  \return bool - true if faceSize computed
1553    */
1554   //================================================================================
1555
1556   bool getDistFromEdge( const SMDS_MeshElement* face,
1557                         const SMDS_MeshNode*    nodeOnEdge,
1558                         double &                faceSize )
1559   {
1560     faceSize = Precision::Infinite();
1561     bool done = false;
1562
1563     int nbN  = face->NbCornerNodes();
1564     int iOnE = face->GetNodeIndex( nodeOnEdge );
1565     int iNext[2] = { SMESH_MesherHelper::WrapIndex( iOnE+1, nbN ),
1566                      SMESH_MesherHelper::WrapIndex( iOnE-1, nbN ) };
1567     const SMDS_MeshNode* nNext[2] = { face->GetNode( iNext[0] ),
1568                                       face->GetNode( iNext[1] ) };
1569     gp_XYZ segVec, segEnd = SMESH_TNodeXYZ( nodeOnEdge ); // segment on EDGE
1570     double segLen = -1.;
1571     // look for two neighbor not in-FACE nodes of face
1572     for ( int i = 0; i < 2; ++i )
1573     {
1574       if ( nNext[i]->GetPosition()->GetDim() != 2 &&
1575            nNext[i]->GetID() < nodeOnEdge->GetID() )
1576       {
1577         // look for an in-FACE node
1578         for ( int iN = 0; iN < nbN; ++iN )
1579         {
1580           if ( iN == iOnE || iN == iNext[i] )
1581             continue;
1582           SMESH_TNodeXYZ pInFace = face->GetNode( iN );
1583           gp_XYZ v = pInFace - segEnd;
1584           if ( segLen < 0 )
1585           {
1586             segVec = SMESH_TNodeXYZ( nNext[i] ) - segEnd;
1587             segLen = segVec.Modulus();
1588           }
1589           double distToSeg = v.Crossed( segVec ).Modulus() / segLen;
1590           faceSize = Min( faceSize, distToSeg );
1591           done = true;
1592         }
1593         segLen = -1;
1594       }
1595     }
1596     return done;
1597   }
1598   //================================================================================
1599   /*!
1600    * \brief Return direction of axis or revolution of a surface
1601    */
1602   //================================================================================
1603
1604   bool getRovolutionAxis( const Adaptor3d_Surface& surface,
1605                           gp_Dir &                 axis )
1606   {
1607     switch ( surface.GetType() ) {
1608     case GeomAbs_Cone:
1609     {
1610       gp_Cone cone = surface.Cone();
1611       axis = cone.Axis().Direction();
1612       break;
1613     }
1614     case GeomAbs_Sphere:
1615     {
1616       gp_Sphere sphere = surface.Sphere();
1617       axis = sphere.Position().Direction();
1618       break;
1619     }
1620     case GeomAbs_SurfaceOfRevolution:
1621     {
1622       axis = surface.AxeOfRevolution().Direction();
1623       break;
1624     }
1625     //case GeomAbs_SurfaceOfExtrusion:
1626     case GeomAbs_OffsetSurface:
1627     {
1628       Handle(Adaptor3d_HSurface) base = surface.BasisSurface();
1629       return getRovolutionAxis( base->Surface(), axis );
1630     }
1631     default: return false;
1632     }
1633     return true;
1634   }
1635
1636   //--------------------------------------------------------------------------------
1637   // DEBUG. Dump intermediate node positions into a python script
1638   // HOWTO use: run python commands written in a console to see
1639   //  construction steps of viscous layers
1640 #ifdef __myDEBUG
1641   ofstream* py;
1642   int       theNbPyFunc;
1643   struct PyDump {
1644     PyDump(SMESH_Mesh& m) {
1645       int tag = 3 + m.GetId();
1646       const char* fname = "/tmp/viscous.py";
1647       cout << "execfile('"<<fname<<"')"<<endl;
1648       py = new ofstream(fname);
1649       *py << "import SMESH" << endl
1650           << "from salome.smesh import smeshBuilder" << endl
1651           << "smesh  = smeshBuilder.New(salome.myStudy)" << endl
1652           << "meshSO = smesh.GetCurrentStudy().FindObjectID('0:1:2:" << tag <<"')" << endl
1653           << "mesh   = smesh.Mesh( meshSO.GetObject() )"<<endl;
1654       theNbPyFunc = 0;
1655     }
1656     void Finish() {
1657       if (py) {
1658         *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Viscous Prisms',"
1659           "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_ElemGeomType,'=',SMESH.Geom_PENTA))"<<endl;
1660         *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Neg Volumes',"
1661           "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_Volume3D,'<',0))"<<endl;
1662       }
1663       delete py; py=0;
1664     }
1665     ~PyDump() { Finish(); cout << "NB FUNCTIONS: " << theNbPyFunc << endl; }
1666   };
1667 #define dumpFunction(f) { _dumpFunction(f, __LINE__);}
1668 #define dumpMove(n)     { _dumpMove(n, __LINE__);}
1669 #define dumpMoveComm(n,txt) { _dumpMove(n, __LINE__, txt);}
1670 #define dumpCmd(txt)    { _dumpCmd(txt, __LINE__);}
1671   void _dumpFunction(const string& fun, int ln)
1672   { if (py) *py<< "def "<<fun<<"(): # "<< ln <<endl; cout<<fun<<"()"<<endl; ++theNbPyFunc; }
1673   void _dumpMove(const SMDS_MeshNode* n, int ln, const char* txt="")
1674   { if (py) *py<< "  mesh.MoveNode( "<<n->GetID()<< ", "<< n->X()
1675                << ", "<<n->Y()<<", "<< n->Z()<< ")\t\t # "<< ln <<" "<< txt << endl; }
1676   void _dumpCmd(const string& txt, int ln)
1677   { if (py) *py<< "  "<<txt<<" # "<< ln <<endl; }
1678   void dumpFunctionEnd()
1679   { if (py) *py<< "  return"<< endl; }
1680   void dumpChangeNodes( const SMDS_MeshElement* f )
1681   { if (py) { *py<< "  mesh.ChangeElemNodes( " << f->GetID()<<", [";
1682       for ( int i=1; i < f->NbNodes(); ++i ) *py << f->GetNode(i-1)->GetID()<<", ";
1683       *py << f->GetNode( f->NbNodes()-1 )->GetID() << " ])"<< endl; }}
1684 #define debugMsg( txt ) { cout << "# "<< txt << " (line: " << __LINE__ << ")" << endl; }
1685
1686 #else
1687
1688   struct PyDump { PyDump(SMESH_Mesh&) {} void Finish() {} };
1689 #define dumpFunction(f) f
1690 #define dumpMove(n)
1691 #define dumpMoveComm(n,txt)
1692 #define dumpCmd(txt)
1693 #define dumpFunctionEnd()
1694 #define dumpChangeNodes(f) { if(f) {} } // prevent "unused variable 'f'" warning
1695 #define debugMsg( txt ) {}
1696
1697 #endif
1698 }
1699
1700 using namespace VISCOUS_3D;
1701
1702 //================================================================================
1703 /*!
1704  * \brief Constructor of _ViscousBuilder
1705  */
1706 //================================================================================
1707
1708 _ViscousBuilder::_ViscousBuilder()
1709 {
1710   _error = SMESH_ComputeError::New(COMPERR_OK);
1711   _tmpFaceID = 0;
1712 }
1713
1714 //================================================================================
1715 /*!
1716  * \brief Stores error description and returns false
1717  */
1718 //================================================================================
1719
1720 bool _ViscousBuilder::error(const string& text, int solidId )
1721 {
1722   const string prefix = string("Viscous layers builder: ");
1723   _error->myName    = COMPERR_ALGO_FAILED;
1724   _error->myComment = prefix + text;
1725   if ( _mesh )
1726   {
1727     SMESH_subMesh* sm = _mesh->GetSubMeshContaining( solidId );
1728     if ( !sm && !_sdVec.empty() )
1729       sm = _mesh->GetSubMeshContaining( solidId = _sdVec[0]._index );
1730     if ( sm && sm->GetSubShape().ShapeType() == TopAbs_SOLID )
1731     {
1732       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1733       if ( smError && smError->myAlgo )
1734         _error->myAlgo = smError->myAlgo;
1735       smError = _error;
1736       sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1737     }
1738     // set KO to all solids
1739     for ( size_t i = 0; i < _sdVec.size(); ++i )
1740     {
1741       if ( _sdVec[i]._index == solidId )
1742         continue;
1743       sm = _mesh->GetSubMesh( _sdVec[i]._solid );
1744       if ( !sm->IsEmpty() )
1745         continue;
1746       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1747       if ( !smError || smError->IsOK() )
1748       {
1749         smError = SMESH_ComputeError::New( COMPERR_ALGO_FAILED, prefix + "failed");
1750         sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1751       }
1752     }
1753   }
1754   makeGroupOfLE(); // debug
1755
1756   return false;
1757 }
1758
1759 //================================================================================
1760 /*!
1761  * \brief At study restoration, restore event listeners used to clear an inferior
1762  *  dim sub-mesh modified by viscous layers
1763  */
1764 //================================================================================
1765
1766 void _ViscousBuilder::RestoreListeners()
1767 {
1768   // TODO
1769 }
1770
1771 //================================================================================
1772 /*!
1773  * \brief computes SMESH_ProxyMesh::SubMesh::_n2n
1774  */
1775 //================================================================================
1776
1777 bool _ViscousBuilder::MakeN2NMap( _MeshOfSolid* pm )
1778 {
1779   SMESH_subMesh* solidSM = pm->mySubMeshes.front();
1780   TopExp_Explorer fExp( solidSM->GetSubShape(), TopAbs_FACE );
1781   for ( ; fExp.More(); fExp.Next() )
1782   {
1783     SMESHDS_SubMesh* srcSmDS = pm->GetMeshDS()->MeshElements( fExp.Current() );
1784     const SMESH_ProxyMesh::SubMesh* prxSmDS = pm->GetProxySubMesh( fExp.Current() );
1785
1786     if ( !srcSmDS || !prxSmDS || !srcSmDS->NbElements() || !prxSmDS->NbElements() )
1787       continue;
1788     if ( srcSmDS->GetElements()->next() == prxSmDS->GetElements()->next())
1789       continue;
1790
1791     if ( srcSmDS->NbElements() != prxSmDS->NbElements() )
1792       return error( "Different nb elements in a source and a proxy sub-mesh", solidSM->GetId());
1793
1794     SMDS_ElemIteratorPtr srcIt = srcSmDS->GetElements();
1795     SMDS_ElemIteratorPtr prxIt = prxSmDS->GetElements();
1796     while( prxIt->more() )
1797     {
1798       const SMDS_MeshElement* fSrc = srcIt->next();
1799       const SMDS_MeshElement* fPrx = prxIt->next();
1800       if ( fSrc->NbNodes() != fPrx->NbNodes())
1801         return error( "Different elements in a source and a proxy sub-mesh", solidSM->GetId());
1802       for ( int i = 0 ; i < fPrx->NbNodes(); ++i )
1803         pm->setNode2Node( fSrc->GetNode(i), fPrx->GetNode(i), prxSmDS );
1804     }
1805   }
1806   pm->_n2nMapComputed = true;
1807   return true;
1808 }
1809
1810 //================================================================================
1811 /*!
1812  * \brief Does its job
1813  */
1814 //================================================================================
1815
1816 SMESH_ComputeErrorPtr _ViscousBuilder::Compute(SMESH_Mesh&         theMesh,
1817                                                const TopoDS_Shape& theShape)
1818 {
1819   // TODO: set priority of solids during Gen::Compute()
1820
1821   _mesh = & theMesh;
1822
1823   // check if proxy mesh already computed
1824   TopExp_Explorer exp( theShape, TopAbs_SOLID );
1825   if ( !exp.More() )
1826     return error("No SOLID's in theShape"), _error;
1827
1828   if ( _ViscousListener::GetSolidMesh( _mesh, exp.Current(), /*toCreate=*/false))
1829     return SMESH_ComputeErrorPtr(); // everything already computed
1830
1831   PyDump debugDump( theMesh );
1832
1833   // TODO: ignore already computed SOLIDs 
1834   if ( !findSolidsWithLayers())
1835     return _error;
1836
1837   if ( !findFacesWithLayers() )
1838     return _error;
1839
1840   for ( size_t i = 0; i < _sdVec.size(); ++i )
1841   {
1842     if ( ! makeLayer(_sdVec[i]) )
1843       return _error;
1844
1845     if ( _sdVec[i]._n2eMap.size() == 0 )
1846       continue;
1847     
1848     if ( ! inflate(_sdVec[i]) )
1849       return _error;
1850
1851     if ( ! refine(_sdVec[i]) )
1852       return _error;
1853   }
1854   if ( !shrink() )
1855     return _error;
1856
1857   addBoundaryElements();
1858
1859   makeGroupOfLE(); // debug
1860   debugDump.Finish();
1861
1862   return _error;
1863 }
1864
1865 //================================================================================
1866 /*!
1867  * \brief Check validity of hypotheses
1868  */
1869 //================================================================================
1870
1871 SMESH_ComputeErrorPtr _ViscousBuilder::CheckHypotheses( SMESH_Mesh&         mesh,
1872                                                         const TopoDS_Shape& shape )
1873 {
1874   _mesh = & mesh;
1875
1876   if ( _ViscousListener::GetSolidMesh( _mesh, shape, /*toCreate=*/false))
1877     return SMESH_ComputeErrorPtr(); // everything already computed
1878
1879
1880   findSolidsWithLayers();
1881   bool ok = findFacesWithLayers( true );
1882
1883   // remove _MeshOfSolid's of _SolidData's
1884   for ( size_t i = 0; i < _sdVec.size(); ++i )
1885     _ViscousListener::RemoveSolidMesh( _mesh, _sdVec[i]._solid );
1886
1887   if ( !ok )
1888     return _error;
1889
1890   return SMESH_ComputeErrorPtr();
1891 }
1892
1893 //================================================================================
1894 /*!
1895  * \brief Finds SOLIDs to compute using viscous layers. Fills _sdVec
1896  */
1897 //================================================================================
1898
1899 bool _ViscousBuilder::findSolidsWithLayers()
1900 {
1901   // get all solids
1902   TopTools_IndexedMapOfShape allSolids;
1903   TopExp::MapShapes( _mesh->GetShapeToMesh(), TopAbs_SOLID, allSolids );
1904   _sdVec.reserve( allSolids.Extent());
1905
1906   SMESH_Gen* gen = _mesh->GetGen();
1907   SMESH_HypoFilter filter;
1908   for ( int i = 1; i <= allSolids.Extent(); ++i )
1909   {
1910     // find StdMeshers_ViscousLayers hyp assigned to the i-th solid
1911     SMESH_Algo* algo = gen->GetAlgo( *_mesh, allSolids(i) );
1912     if ( !algo ) continue;
1913     // TODO: check if algo is hidden
1914     const list <const SMESHDS_Hypothesis *> & allHyps =
1915       algo->GetUsedHypothesis(*_mesh, allSolids(i), /*ignoreAuxiliary=*/false);
1916     _SolidData* soData = 0;
1917     list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
1918     const StdMeshers_ViscousLayers* viscHyp = 0;
1919     for ( ; hyp != allHyps.end(); ++hyp )
1920       if (( viscHyp = dynamic_cast<const StdMeshers_ViscousLayers*>( *hyp )))
1921       {
1922         TopoDS_Shape hypShape;
1923         filter.Init( filter.Is( viscHyp ));
1924         _mesh->GetHypothesis( allSolids(i), filter, true, &hypShape );
1925
1926         if ( !soData )
1927         {
1928           _MeshOfSolid* proxyMesh = _ViscousListener::GetSolidMesh( _mesh,
1929                                                                     allSolids(i),
1930                                                                     /*toCreate=*/true);
1931           _sdVec.push_back( _SolidData( allSolids(i), proxyMesh ));
1932           soData = & _sdVec.back();
1933           soData->_index = getMeshDS()->ShapeToIndex( allSolids(i));
1934           soData->_helper = new SMESH_MesherHelper( *_mesh );
1935           soData->_helper->SetSubShape( allSolids(i) );
1936         }
1937         soData->_hyps.push_back( viscHyp );
1938         soData->_hypShapes.push_back( hypShape );
1939       }
1940   }
1941   if ( _sdVec.empty() )
1942     return error
1943       ( SMESH_Comment(StdMeshers_ViscousLayers::GetHypType()) << " hypothesis not found",0);
1944
1945   return true;
1946 }
1947
1948 //================================================================================
1949 /*!
1950  * \brief 
1951  */
1952 //================================================================================
1953
1954 bool _ViscousBuilder::findFacesWithLayers(const bool onlyWith)
1955 {
1956   SMESH_MesherHelper helper( *_mesh );
1957   TopExp_Explorer exp;
1958   TopTools_IndexedMapOfShape solids;
1959
1960   // collect all faces-to-ignore defined by hyp
1961   for ( size_t i = 0; i < _sdVec.size(); ++i )
1962   {
1963     solids.Add( _sdVec[i]._solid );
1964
1965     // get faces-to-ignore defined by each hyp
1966     typedef const StdMeshers_ViscousLayers* THyp;
1967     typedef std::pair< set<TGeomID>, THyp > TFacesOfHyp;
1968     list< TFacesOfHyp > ignoreFacesOfHyps;
1969     list< THyp >::iterator              hyp = _sdVec[i]._hyps.begin();
1970     list< TopoDS_Shape >::iterator hypShape = _sdVec[i]._hypShapes.begin();
1971     for ( ; hyp != _sdVec[i]._hyps.end(); ++hyp, ++hypShape )
1972     {
1973       ignoreFacesOfHyps.push_back( TFacesOfHyp( set<TGeomID>(), *hyp ));
1974       getIgnoreFaces( _sdVec[i]._solid, *hyp, *hypShape, ignoreFacesOfHyps.back().first );
1975     }
1976
1977     // fill _SolidData::_face2hyp and check compatibility of hypotheses
1978     const int nbHyps = _sdVec[i]._hyps.size();
1979     if ( nbHyps > 1 )
1980     {
1981       // check if two hypotheses define different parameters for the same FACE
1982       list< TFacesOfHyp >::iterator igFacesOfHyp;
1983       for ( exp.Init( _sdVec[i]._solid, TopAbs_FACE ); exp.More(); exp.Next() )
1984       {
1985         const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
1986         THyp hyp = 0;
1987         igFacesOfHyp = ignoreFacesOfHyps.begin();
1988         for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
1989           if ( ! igFacesOfHyp->first.count( faceID ))
1990           {
1991             if ( hyp )
1992               return error(SMESH_Comment("Several hypotheses define "
1993                                          "Viscous Layers on the face #") << faceID );
1994             hyp = igFacesOfHyp->second;
1995           }
1996         if ( hyp )
1997           _sdVec[i]._face2hyp.insert( make_pair( faceID, hyp ));
1998         else
1999           _sdVec[i]._ignoreFaceIds.insert( faceID );
2000       }
2001
2002       // check if two hypotheses define different number of viscous layers for
2003       // adjacent faces of a solid
2004       set< int > nbLayersSet;
2005       igFacesOfHyp = ignoreFacesOfHyps.begin();
2006       for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
2007       {
2008         nbLayersSet.insert( igFacesOfHyp->second->GetNumberLayers() );
2009       }
2010       if ( nbLayersSet.size() > 1 )
2011       {
2012         for ( exp.Init( _sdVec[i]._solid, TopAbs_EDGE ); exp.More(); exp.Next() )
2013         {
2014           PShapeIteratorPtr fIt = helper.GetAncestors( exp.Current(), *_mesh, TopAbs_FACE );
2015           THyp hyp1 = 0, hyp2 = 0;
2016           while( const TopoDS_Shape* face = fIt->next() )
2017           {
2018             const TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
2019             map< TGeomID, THyp >::iterator f2h = _sdVec[i]._face2hyp.find( faceID );
2020             if ( f2h != _sdVec[i]._face2hyp.end() )
2021             {
2022               ( hyp1 ? hyp2 : hyp1 ) = f2h->second;
2023             }
2024           }
2025           if ( hyp1 && hyp2 &&
2026                hyp1->GetNumberLayers() != hyp2->GetNumberLayers() )
2027           {
2028             return error("Two hypotheses define different number of "
2029                          "viscous layers on adjacent faces");
2030           }
2031         }
2032       }
2033     } // if ( nbHyps > 1 )
2034     else
2035     {
2036       _sdVec[i]._ignoreFaceIds.swap( ignoreFacesOfHyps.back().first );
2037     }
2038   } // loop on _sdVec
2039
2040   if ( onlyWith ) // is called to check hypotheses compatibility only
2041     return true;
2042
2043   // fill _SolidData::_reversedFaceIds
2044   for ( size_t i = 0; i < _sdVec.size(); ++i )
2045   {
2046     exp.Init( _sdVec[i]._solid.Oriented( TopAbs_FORWARD ), TopAbs_FACE );
2047     for ( ; exp.More(); exp.Next() )
2048     {
2049       const TopoDS_Face& face = TopoDS::Face( exp.Current() );
2050       const TGeomID faceID = getMeshDS()->ShapeToIndex( face );
2051       if ( //!sdVec[i]._ignoreFaceIds.count( faceID ) &&
2052           helper.NbAncestors( face, *_mesh, TopAbs_SOLID ) > 1 &&
2053           helper.IsReversedSubMesh( face ))
2054       {
2055         _sdVec[i]._reversedFaceIds.insert( faceID );
2056       }
2057     }
2058   }
2059
2060   // Find faces to shrink mesh on (solution 2 in issue 0020832);
2061   TopTools_IndexedMapOfShape shapes;
2062   for ( size_t i = 0; i < _sdVec.size(); ++i )
2063   {
2064     shapes.Clear();
2065     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_EDGE, shapes);
2066     for ( int iE = 1; iE <= shapes.Extent(); ++iE )
2067     {
2068       const TopoDS_Shape& edge = shapes(iE);
2069       // find 2 faces sharing an edge
2070       TopoDS_Shape FF[2];
2071       PShapeIteratorPtr fIt = helper.GetAncestors(edge, *_mesh, TopAbs_FACE);
2072       while ( fIt->more())
2073       {
2074         const TopoDS_Shape* f = fIt->next();
2075         if ( helper.IsSubShape( *f, _sdVec[i]._solid))
2076           FF[ int( !FF[0].IsNull()) ] = *f;
2077       }
2078       if( FF[1].IsNull() ) continue; // seam edge can be shared by 1 FACE only
2079       // check presence of layers on them
2080       int ignore[2];
2081       for ( int j = 0; j < 2; ++j )
2082         ignore[j] = _sdVec[i]._ignoreFaceIds.count ( getMeshDS()->ShapeToIndex( FF[j] ));
2083       if ( ignore[0] == ignore[1] )
2084         continue; // nothing interesting
2085       TopoDS_Shape fWOL = FF[ ignore[0] ? 0 : 1 ];
2086       // check presence of layers on fWOL within an adjacent SOLID
2087       bool collision = false;
2088       PShapeIteratorPtr sIt = helper.GetAncestors( fWOL, *_mesh, TopAbs_SOLID );
2089       while ( const TopoDS_Shape* solid = sIt->next() )
2090         if ( !solid->IsSame( _sdVec[i]._solid ))
2091         {
2092           int iSolid = solids.FindIndex( *solid );
2093           int  iFace = getMeshDS()->ShapeToIndex( fWOL );
2094           if ( iSolid > 0 && !_sdVec[ iSolid-1 ]._ignoreFaceIds.count( iFace ))
2095           {
2096             //_sdVec[i]._noShrinkShapes.insert( iFace );
2097             //fWOL.Nullify();
2098             collision = true;
2099           }
2100         }
2101       // add edge to maps
2102       if ( !fWOL.IsNull())
2103       {
2104         TGeomID edgeInd = getMeshDS()->ShapeToIndex( edge );
2105         _sdVec[i]._shrinkShape2Shape.insert( make_pair( edgeInd, fWOL ));
2106         if ( collision )
2107         {
2108           // _shrinkShape2Shape will be used to temporary inflate _LayerEdge's based
2109           // on the edge but shrink won't be performed
2110           _sdVec[i]._noShrinkShapes.insert( edgeInd );
2111         }
2112       }
2113     }
2114   }
2115   // Exclude from _shrinkShape2Shape FACE's that can't be shrinked since
2116   // the algo of the SOLID sharing the FACE does not support it
2117   set< string > notSupportAlgos; notSupportAlgos.insert("Hexa_3D");
2118   for ( size_t i = 0; i < _sdVec.size(); ++i )
2119   {
2120     map< TGeomID, TopoDS_Shape >::iterator e2f = _sdVec[i]._shrinkShape2Shape.begin();
2121     for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); ++e2f )
2122     {
2123       const TopoDS_Shape& fWOL = e2f->second;
2124       const TGeomID     edgeID = e2f->first;
2125       bool notShrinkFace = false;
2126       PShapeIteratorPtr soIt = helper.GetAncestors(fWOL, *_mesh, TopAbs_SOLID);
2127       while ( soIt->more() )
2128       {
2129         const TopoDS_Shape* solid = soIt->next();
2130         if ( _sdVec[i]._solid.IsSame( *solid )) continue;
2131         SMESH_Algo* algo = _mesh->GetGen()->GetAlgo( *_mesh, *solid );
2132         if ( !algo || !notSupportAlgos.count( algo->GetName() )) continue;
2133         notShrinkFace = true;
2134         size_t iSolid = 0;
2135         for ( ; iSolid < _sdVec.size(); ++iSolid )
2136         {
2137           if ( _sdVec[iSolid]._solid.IsSame( *solid ) ) {
2138             if ( _sdVec[iSolid]._shrinkShape2Shape.count( edgeID ))
2139               notShrinkFace = false;
2140             break;
2141           }
2142         }
2143         if ( notShrinkFace )
2144         {
2145           _sdVec[i]._noShrinkShapes.insert( edgeID );
2146
2147           // add VERTEXes of the edge in _noShrinkShapes
2148           TopoDS_Shape edge = getMeshDS()->IndexToShape( edgeID );
2149           for ( TopoDS_Iterator vIt( edge ); vIt.More(); vIt.Next() )
2150             _sdVec[i]._noShrinkShapes.insert( getMeshDS()->ShapeToIndex( vIt.Value() ));
2151
2152           // check if there is a collision with to-shrink-from EDGEs in iSolid
2153           if ( iSolid == _sdVec.size() )
2154             continue; // no VL in the solid
2155           shapes.Clear();
2156           TopExp::MapShapes( fWOL, TopAbs_EDGE, shapes);
2157           for ( int iE = 1; iE <= shapes.Extent(); ++iE )
2158           {
2159             const TopoDS_Edge& E = TopoDS::Edge( shapes( iE ));
2160             const TGeomID    eID = getMeshDS()->ShapeToIndex( E );
2161             if ( eID == edgeID ||
2162                  !_sdVec[iSolid]._shrinkShape2Shape.count( eID ) ||
2163                  _sdVec[i]._noShrinkShapes.count( eID ))
2164               continue;
2165             for ( int is1st = 0; is1st < 2; ++is1st )
2166             {
2167               TopoDS_Vertex V = helper.IthVertex( is1st, E );
2168               if ( _sdVec[i]._noShrinkShapes.count( getMeshDS()->ShapeToIndex( V ) ))
2169               {
2170                 // _sdVec[i]._noShrinkShapes.insert( eID );
2171                 // V = helper.IthVertex( !is1st, E );
2172                 // _sdVec[i]._noShrinkShapes.insert( getMeshDS()->ShapeToIndex( V ));
2173                 //iE = 0; // re-start the loop on EDGEs of fWOL
2174                 return error("No way to make a conformal mesh with "
2175                              "the given set of faces with layers", _sdVec[i]._index);
2176               }
2177             }
2178           }
2179         }
2180
2181       } // while ( soIt->more() )
2182     } // loop on _sdVec[i]._shrinkShape2Shape
2183   } // loop on _sdVec to fill in _SolidData::_noShrinkShapes
2184
2185   // Find the SHAPE along which to inflate _LayerEdge based on VERTEX
2186
2187   for ( size_t i = 0; i < _sdVec.size(); ++i )
2188   {
2189     shapes.Clear();
2190     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_VERTEX, shapes);
2191     for ( int iV = 1; iV <= shapes.Extent(); ++iV )
2192     {
2193       const TopoDS_Shape& vertex = shapes(iV);
2194       // find faces WOL sharing the vertex
2195       vector< TopoDS_Shape > facesWOL;
2196       size_t totalNbFaces = 0;
2197       PShapeIteratorPtr fIt = helper.GetAncestors(vertex, *_mesh, TopAbs_FACE);
2198       while ( fIt->more())
2199       {
2200         const TopoDS_Shape* f = fIt->next();
2201         if ( helper.IsSubShape( *f, _sdVec[i]._solid ) )
2202         {
2203           totalNbFaces++;
2204           const int fID = getMeshDS()->ShapeToIndex( *f );
2205           if ( _sdVec[i]._ignoreFaceIds.count ( fID ) /*&&
2206                !_sdVec[i]._noShrinkShapes.count( fID )*/)
2207             facesWOL.push_back( *f );
2208         }
2209       }
2210       if ( facesWOL.size() == totalNbFaces || facesWOL.empty() )
2211         continue; // no layers at this vertex or no WOL
2212       TGeomID vInd = getMeshDS()->ShapeToIndex( vertex );
2213       switch ( facesWOL.size() )
2214       {
2215       case 1:
2216       {
2217         helper.SetSubShape( facesWOL[0] );
2218         if ( helper.IsRealSeam( vInd )) // inflate along a seam edge?
2219         {
2220           TopoDS_Shape seamEdge;
2221           PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
2222           while ( eIt->more() && seamEdge.IsNull() )
2223           {
2224             const TopoDS_Shape* e = eIt->next();
2225             if ( helper.IsRealSeam( *e ) )
2226               seamEdge = *e;
2227           }
2228           if ( !seamEdge.IsNull() )
2229           {
2230             _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, seamEdge ));
2231             break;
2232           }
2233         }
2234         _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, facesWOL[0] ));
2235         break;
2236       }
2237       case 2:
2238       {
2239         // find an edge shared by 2 faces
2240         PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
2241         while ( eIt->more())
2242         {
2243           const TopoDS_Shape* e = eIt->next();
2244           if ( helper.IsSubShape( *e, facesWOL[0]) &&
2245                helper.IsSubShape( *e, facesWOL[1]))
2246           {
2247             _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, *e )); break;
2248           }
2249         }
2250         break;
2251       }
2252       default:
2253         return error("Not yet supported case", _sdVec[i]._index);
2254       }
2255     }
2256   }
2257
2258   // add FACEs of other SOLIDs to _ignoreFaceIds
2259   for ( size_t i = 0; i < _sdVec.size(); ++i )
2260   {
2261     shapes.Clear();
2262     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_FACE, shapes);
2263
2264     for ( exp.Init( _mesh->GetShapeToMesh(), TopAbs_FACE ); exp.More(); exp.Next() )
2265     {
2266       if ( !shapes.Contains( exp.Current() ))
2267         _sdVec[i]._ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( exp.Current() ));
2268     }
2269   }
2270
2271   return true;
2272 }
2273
2274 //================================================================================
2275 /*!
2276  * \brief Finds FACEs w/o layers for a given SOLID by an hypothesis
2277  */
2278 //================================================================================
2279
2280 void _ViscousBuilder::getIgnoreFaces(const TopoDS_Shape&             solid,
2281                                      const StdMeshers_ViscousLayers* hyp,
2282                                      const TopoDS_Shape&             hypShape,
2283                                      set<TGeomID>&                   ignoreFaceIds)
2284 {
2285   TopExp_Explorer exp;
2286
2287   vector<TGeomID> ids = hyp->GetBndShapes();
2288   if ( hyp->IsToIgnoreShapes() ) // FACEs to ignore are given
2289   {
2290     for ( size_t ii = 0; ii < ids.size(); ++ii )
2291     {
2292       const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[ii] );
2293       if ( !s.IsNull() && s.ShapeType() == TopAbs_FACE )
2294         ignoreFaceIds.insert( ids[ii] );
2295     }
2296   }
2297   else // FACEs with layers are given
2298   {
2299     exp.Init( solid, TopAbs_FACE );
2300     for ( ; exp.More(); exp.Next() )
2301     {
2302       TGeomID faceInd = getMeshDS()->ShapeToIndex( exp.Current() );
2303       if ( find( ids.begin(), ids.end(), faceInd ) == ids.end() )
2304         ignoreFaceIds.insert( faceInd );
2305     }
2306   }
2307
2308   // ignore internal FACEs if inlets and outlets are specified
2309   if ( hyp->IsToIgnoreShapes() )
2310   {
2311     TopTools_IndexedDataMapOfShapeListOfShape solidsOfFace;
2312     TopExp::MapShapesAndAncestors( hypShape,
2313                                    TopAbs_FACE, TopAbs_SOLID, solidsOfFace);
2314
2315     for ( exp.Init( solid, TopAbs_FACE ); exp.More(); exp.Next() )
2316     {
2317       const TopoDS_Face& face = TopoDS::Face( exp.Current() );
2318       if ( SMESH_MesherHelper::NbAncestors( face, *_mesh, TopAbs_SOLID ) < 2 )
2319         continue;
2320
2321       int nbSolids = solidsOfFace.FindFromKey( face ).Extent();
2322       if ( nbSolids > 1 )
2323         ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( face ));
2324     }
2325   }
2326 }
2327
2328 //================================================================================
2329 /*!
2330  * \brief Create the inner surface of the viscous layer and prepare data for infation
2331  */
2332 //================================================================================
2333
2334 bool _ViscousBuilder::makeLayer(_SolidData& data)
2335 {
2336   // get all sub-shapes to make layers on
2337   set<TGeomID> subIds, faceIds;
2338   subIds = data._noShrinkShapes;
2339   TopExp_Explorer exp( data._solid, TopAbs_FACE );
2340   for ( ; exp.More(); exp.Next() )
2341   {
2342     SMESH_subMesh* fSubM = _mesh->GetSubMesh( exp.Current() );
2343     if ( ! data._ignoreFaceIds.count( fSubM->GetId() ))
2344       faceIds.insert( fSubM->GetId() );
2345   }
2346
2347   // make a map to find new nodes on sub-shapes shared with other SOLID
2348   map< TGeomID, TNode2Edge* >::iterator s2ne;
2349   map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
2350   for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
2351   {
2352     TGeomID shapeInd = s2s->first;
2353     for ( size_t i = 0; i < _sdVec.size(); ++i )
2354     {
2355       if ( _sdVec[i]._index == data._index ) continue;
2356       map< TGeomID, TopoDS_Shape >::iterator s2s2 = _sdVec[i]._shrinkShape2Shape.find( shapeInd );
2357       if ( s2s2 != _sdVec[i]._shrinkShape2Shape.end() &&
2358            *s2s == *s2s2 && !_sdVec[i]._n2eMap.empty() )
2359       {
2360         data._s2neMap.insert( make_pair( shapeInd, &_sdVec[i]._n2eMap ));
2361         break;
2362       }
2363     }
2364   }
2365
2366   // Create temporary faces and _LayerEdge's
2367
2368   dumpFunction(SMESH_Comment("makeLayers_")<<data._index);
2369
2370   data._stepSize = Precision::Infinite();
2371   data._stepSizeNodes[0] = 0;
2372
2373   SMESH_MesherHelper helper( *_mesh );
2374   helper.SetSubShape( data._solid );
2375   helper.SetElementsOnShape( true );
2376
2377   vector< const SMDS_MeshNode*> newNodes; // of a mesh face
2378   TNode2Edge::iterator n2e2;
2379
2380   // collect _LayerEdge's of shapes they are based on
2381   vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
2382   const int nbShapes = getMeshDS()->MaxShapeIndex();
2383   edgesByGeom.resize( nbShapes+1 );
2384
2385   // set data of _EdgesOnShape's
2386   if ( SMESH_subMesh* sm = _mesh->GetSubMesh( data._solid ))
2387   {
2388     SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/false);
2389     while ( smIt->more() )
2390     {
2391       sm = smIt->next();
2392       if ( sm->GetSubShape().ShapeType() == TopAbs_FACE &&
2393            !faceIds.count( sm->GetId() ))
2394         continue;
2395       setShapeData( edgesByGeom[ sm->GetId() ], sm, data );
2396     }
2397   }
2398   // make _LayerEdge's
2399   for ( set<TGeomID>::iterator id = faceIds.begin(); id != faceIds.end(); ++id )
2400   {
2401     const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( *id ));
2402     SMESH_subMesh* sm = _mesh->GetSubMesh( F );
2403     SMESH_ProxyMesh::SubMesh* proxySub =
2404       data._proxyMesh->getFaceSubM( F, /*create=*/true);
2405
2406     SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2407     if ( !smDS ) return error(SMESH_Comment("Not meshed face ") << *id, data._index );
2408
2409     SMDS_ElemIteratorPtr eIt = smDS->GetElements();
2410     while ( eIt->more() )
2411     {
2412       const SMDS_MeshElement* face = eIt->next();
2413       double          faceMaxCosin = -1;
2414       _LayerEdge*     maxCosinEdge = 0;
2415       int             nbDegenNodes = 0;
2416
2417       newNodes.resize( face->NbCornerNodes() );
2418       for ( size_t i = 0 ; i < newNodes.size(); ++i )
2419       {
2420         const SMDS_MeshNode* n = face->GetNode( i );
2421         const int      shapeID = n->getshapeId();
2422         const bool onDegenShap = helper.IsDegenShape( shapeID );
2423         const bool onDegenEdge = ( onDegenShap && n->GetPosition()->GetDim() == 1 );
2424         if ( onDegenShap )
2425         {
2426           if ( onDegenEdge )
2427           {
2428             // substitute n on a degenerated EDGE with a node on a corresponding VERTEX
2429             const TopoDS_Shape& E = getMeshDS()->IndexToShape( shapeID );
2430             TopoDS_Vertex       V = helper.IthVertex( 0, TopoDS::Edge( E ));
2431             if ( const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() )) {
2432               n = vN;
2433               nbDegenNodes++;
2434             }
2435           }
2436           else
2437           {
2438             nbDegenNodes++;
2439           }
2440         }
2441         TNode2Edge::iterator n2e = data._n2eMap.insert( make_pair( n, (_LayerEdge*)0 )).first;
2442         if ( !(*n2e).second )
2443         {
2444           // add a _LayerEdge
2445           _LayerEdge* edge = new _LayerEdge();
2446           edge->_nodes.push_back( n );
2447           n2e->second = edge;
2448           edgesByGeom[ shapeID ]._edges.push_back( edge );
2449           const bool noShrink = data._noShrinkShapes.count( shapeID );
2450
2451           SMESH_TNodeXYZ xyz( n );
2452
2453           // set edge data or find already refined _LayerEdge and get data from it
2454           if (( !noShrink                                                     ) &&
2455               ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE        ) &&
2456               (( s2ne = data._s2neMap.find( shapeID )) != data._s2neMap.end() ) &&
2457               (( n2e2 = (*s2ne).second->find( n )) != s2ne->second->end()     ))
2458           {
2459             _LayerEdge* foundEdge = (*n2e2).second;
2460             gp_XYZ        lastPos = edge->Copy( *foundEdge, edgesByGeom[ shapeID ], helper );
2461             foundEdge->_pos.push_back( lastPos );
2462             // location of the last node is modified and we restore it by foundEdge->_pos.back()
2463             const_cast< SMDS_MeshNode* >
2464               ( edge->_nodes.back() )->setXYZ( xyz.X(), xyz.Y(), xyz.Z() );
2465           }
2466           else
2467           {
2468             if ( !noShrink )
2469             {
2470               edge->_nodes.push_back( helper.AddNode( xyz.X(), xyz.Y(), xyz.Z() ));
2471             }
2472             if ( !setEdgeData( *edge, edgesByGeom[ shapeID ], helper, data ))
2473               return false;
2474
2475             if ( edge->_nodes.size() < 2 )
2476               edge->Block( data );
2477               //data._noShrinkShapes.insert( shapeID );
2478           }
2479           dumpMove(edge->_nodes.back());
2480
2481           if ( edge->_cosin > faceMaxCosin )
2482           {
2483             faceMaxCosin = edge->_cosin;
2484             maxCosinEdge = edge;
2485           }
2486         }
2487         newNodes[ i ] = n2e->second->_nodes.back();
2488
2489         if ( onDegenEdge )
2490           data._n2eMap.insert( make_pair( face->GetNode( i ), n2e->second ));
2491       }
2492       if ( newNodes.size() - nbDegenNodes < 2 )
2493         continue;
2494
2495       // create a temporary face
2496       const SMDS_MeshElement* newFace =
2497         new _TmpMeshFace( newNodes, --_tmpFaceID, face->getshapeId(), face->getIdInShape() );
2498       proxySub->AddElement( newFace );
2499
2500       // compute inflation step size by min size of element on a convex surface
2501       if ( faceMaxCosin > theMinSmoothCosin )
2502         limitStepSize( data, face, maxCosinEdge );
2503
2504     } // loop on 2D elements on a FACE
2505   } // loop on FACEs of a SOLID to create _LayerEdge's
2506
2507
2508   // Set _LayerEdge::_neibors
2509   TNode2Edge::iterator n2e;
2510   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2511   {
2512     _EdgesOnShape& eos = data._edgesOnShape[iS];
2513     for ( size_t i = 0; i < eos._edges.size(); ++i )
2514     {
2515       _LayerEdge* edge = eos._edges[i];
2516       TIDSortedNodeSet nearNodes;
2517       SMDS_ElemIteratorPtr fIt = edge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2518       while ( fIt->more() )
2519       {
2520         const SMDS_MeshElement* f = fIt->next();
2521         if ( !data._ignoreFaceIds.count( f->getshapeId() ))
2522           nearNodes.insert( f->begin_nodes(), f->end_nodes() );
2523       }
2524       nearNodes.erase( edge->_nodes[0] );
2525       edge->_neibors.reserve( nearNodes.size() );
2526       TIDSortedNodeSet::iterator node = nearNodes.begin();
2527       for ( ; node != nearNodes.end(); ++node )
2528         if (( n2e = data._n2eMap.find( *node )) != data._n2eMap.end() )
2529           edge->_neibors.push_back( n2e->second );
2530     }
2531   }
2532
2533   data._epsilon = 1e-7;
2534   if ( data._stepSize < 1. )
2535     data._epsilon *= data._stepSize;
2536
2537   if ( !findShapesToSmooth( data ))
2538     return false;
2539
2540   // limit data._stepSize depending on surface curvature and fill data._convexFaces
2541   limitStepSizeByCurvature( data ); // !!! it must be before node substitution in _Simplex
2542
2543   // Set target nodes into _Simplex and _LayerEdge's to _2NearEdges
2544   const SMDS_MeshNode* nn[2];
2545   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2546   {
2547     _EdgesOnShape& eos = data._edgesOnShape[iS];
2548     for ( size_t i = 0; i < eos._edges.size(); ++i )
2549     {
2550       _LayerEdge* edge = eos._edges[i];
2551       if ( edge->IsOnEdge() )
2552       {
2553         // get neighbor nodes
2554         bool hasData = ( edge->_2neibors->_edges[0] );
2555         if ( hasData ) // _LayerEdge is a copy of another one
2556         {
2557           nn[0] = edge->_2neibors->srcNode(0);
2558           nn[1] = edge->_2neibors->srcNode(1);
2559         }
2560         else if ( !findNeiborsOnEdge( edge, nn[0],nn[1], eos, data ))
2561         {
2562           return false;
2563         }
2564         // set neighbor _LayerEdge's
2565         for ( int j = 0; j < 2; ++j )
2566         {
2567           if (( n2e = data._n2eMap.find( nn[j] )) == data._n2eMap.end() )
2568             return error("_LayerEdge not found by src node", data._index);
2569           edge->_2neibors->_edges[j] = n2e->second;
2570         }
2571         if ( !hasData )
2572           edge->SetDataByNeighbors( nn[0], nn[1], eos, helper );
2573       }
2574
2575       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
2576       {
2577         _Simplex& s = edge->_simplices[j];
2578         s._nNext = data._n2eMap[ s._nNext ]->_nodes.back();
2579         s._nPrev = data._n2eMap[ s._nPrev ]->_nodes.back();
2580       }
2581
2582       // For an _LayerEdge on a degenerated EDGE, copy some data from
2583       // a corresponding _LayerEdge on a VERTEX
2584       // (issue 52453, pb on a downloaded SampleCase2-Tet-netgen-mephisto.hdf)
2585       if ( helper.IsDegenShape( edge->_nodes[0]->getshapeId() ))
2586       {
2587         // Generally we should not get here
2588         if ( eos.ShapeType() != TopAbs_EDGE )
2589           continue;
2590         TopoDS_Vertex V = helper.IthVertex( 0, TopoDS::Edge( eos._shape ));
2591         const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() );
2592         if (( n2e = data._n2eMap.find( vN )) == data._n2eMap.end() )
2593           continue;
2594         const _LayerEdge* vEdge = n2e->second;
2595         edge->_normal    = vEdge->_normal;
2596         edge->_lenFactor = vEdge->_lenFactor;
2597         edge->_cosin     = vEdge->_cosin;
2598       }
2599
2600     } // loop on data._edgesOnShape._edges
2601   } // loop on data._edgesOnShape
2602
2603   // fix _LayerEdge::_2neibors on EDGEs to smooth
2604   // map< TGeomID,Handle(Geom_Curve)>::iterator e2c = data._edge2curve.begin();
2605   // for ( ; e2c != data._edge2curve.end(); ++e2c )
2606   //   if ( !e2c->second.IsNull() )
2607   //   {
2608   //     if ( _EdgesOnShape* eos = data.GetShapeEdges( e2c->first ))
2609   //       data.Sort2NeiborsOnEdge( eos->_edges );
2610   //   }
2611
2612   dumpFunctionEnd();
2613   return true;
2614 }
2615
2616 //================================================================================
2617 /*!
2618  * \brief Compute inflation step size by min size of element on a convex surface
2619  */
2620 //================================================================================
2621
2622 void _ViscousBuilder::limitStepSize( _SolidData&             data,
2623                                      const SMDS_MeshElement* face,
2624                                      const _LayerEdge*       maxCosinEdge )
2625 {
2626   int iN = 0;
2627   double minSize = 10 * data._stepSize;
2628   const int nbNodes = face->NbCornerNodes();
2629   for ( int i = 0; i < nbNodes; ++i )
2630   {
2631     const SMDS_MeshNode* nextN = face->GetNode( SMESH_MesherHelper::WrapIndex( i+1, nbNodes ));
2632     const SMDS_MeshNode*  curN = face->GetNode( i );
2633     if ( nextN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ||
2634          curN-> GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
2635     {
2636       double dist = SMESH_TNodeXYZ( curN ).Distance( nextN );
2637       if ( dist < minSize )
2638         minSize = dist, iN = i;
2639     }
2640   }
2641   double newStep = 0.8 * minSize / maxCosinEdge->_lenFactor;
2642   if ( newStep < data._stepSize )
2643   {
2644     data._stepSize = newStep;
2645     data._stepSizeCoeff = 0.8 / maxCosinEdge->_lenFactor;
2646     data._stepSizeNodes[0] = face->GetNode( iN );
2647     data._stepSizeNodes[1] = face->GetNode( SMESH_MesherHelper::WrapIndex( iN+1, nbNodes ));
2648   }
2649 }
2650
2651 //================================================================================
2652 /*!
2653  * \brief Compute inflation step size by min size of element on a convex surface
2654  */
2655 //================================================================================
2656
2657 void _ViscousBuilder::limitStepSize( _SolidData& data, const double minSize )
2658 {
2659   if ( minSize < data._stepSize )
2660   {
2661     data._stepSize = minSize;
2662     if ( data._stepSizeNodes[0] )
2663     {
2664       double dist =
2665         SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
2666       data._stepSizeCoeff = data._stepSize / dist;
2667     }
2668   }
2669 }
2670
2671 //================================================================================
2672 /*!
2673  * \brief Limit data._stepSize by evaluating curvature of shapes and fill data._convexFaces
2674  */
2675 //================================================================================
2676
2677 void _ViscousBuilder::limitStepSizeByCurvature( _SolidData& data )
2678 {
2679   const int nbTestPnt = 5; // on a FACE sub-shape
2680
2681   BRepLProp_SLProps surfProp( 2, 1e-6 );
2682   SMESH_MesherHelper helper( *_mesh );
2683
2684   data._convexFaces.clear();
2685
2686   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2687   {
2688     _EdgesOnShape& eof = data._edgesOnShape[iS];
2689     if ( eof.ShapeType() != TopAbs_FACE ||
2690          data._ignoreFaceIds.count( eof._shapeID ))
2691       continue;
2692
2693     TopoDS_Face        F = TopoDS::Face( eof._shape );
2694     SMESH_subMesh *   sm = eof._subMesh;
2695     const TGeomID faceID = eof._shapeID;
2696
2697     BRepAdaptor_Surface surface( F, false );
2698     surfProp.SetSurface( surface );
2699
2700     bool isTooCurved = false;
2701
2702     _ConvexFace cnvFace;
2703     const double        oriFactor = ( F.Orientation() == TopAbs_REVERSED ? +1. : -1. );
2704     SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/true);
2705     while ( smIt->more() )
2706     {
2707       sm = smIt->next();
2708       const TGeomID subID = sm->GetId();
2709       // find _LayerEdge's of a sub-shape
2710       _EdgesOnShape* eos;
2711       if (( eos = data.GetShapeEdges( subID )))
2712         cnvFace._subIdToEOS.insert( make_pair( subID, eos ));
2713       else
2714         continue;
2715       // check concavity and curvature and limit data._stepSize
2716       const double minCurvature =
2717         1. / ( eos->_hyp.GetTotalThickness() * ( 1 + theThickToIntersection ));
2718       size_t iStep = Max( 1, eos->_edges.size() / nbTestPnt );
2719       for ( size_t i = 0; i < eos->_edges.size(); i += iStep )
2720       {
2721         gp_XY uv = helper.GetNodeUV( F, eos->_edges[ i ]->_nodes[0] );
2722         surfProp.SetParameters( uv.X(), uv.Y() );
2723         if ( !surfProp.IsCurvatureDefined() )
2724           continue;
2725         if ( surfProp.MaxCurvature() * oriFactor > minCurvature )
2726         {
2727           limitStepSize( data, 0.9 / surfProp.MaxCurvature() * oriFactor );
2728           isTooCurved = true;
2729         }
2730         if ( surfProp.MinCurvature() * oriFactor > minCurvature )
2731         {
2732           limitStepSize( data, 0.9 / surfProp.MinCurvature() * oriFactor );
2733           isTooCurved = true;
2734         }
2735       }
2736     } // loop on sub-shapes of the FACE
2737
2738     if ( !isTooCurved ) continue;
2739
2740     _ConvexFace & convFace =
2741       data._convexFaces.insert( make_pair( faceID, cnvFace )).first->second;
2742
2743     convFace._face = F;
2744     convFace._normalsFixed = false;
2745
2746     // Fill _ConvexFace::_simplexTestEdges. These _LayerEdge's are used to detect
2747     // prism distortion.
2748     map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.find( faceID );
2749     if ( id2eos != convFace._subIdToEOS.end() && !id2eos->second->_edges.empty() )
2750     {
2751       // there are _LayerEdge's on the FACE it-self;
2752       // select _LayerEdge's near EDGEs
2753       _EdgesOnShape& eos = * id2eos->second;
2754       for ( size_t i = 0; i < eos._edges.size(); ++i )
2755       {
2756         _LayerEdge* ledge = eos._edges[ i ];
2757         for ( size_t j = 0; j < ledge->_simplices.size(); ++j )
2758           if ( ledge->_simplices[j]._nNext->GetPosition()->GetDim() < 2 )
2759           {
2760             convFace._simplexTestEdges.push_back( ledge );
2761             break;
2762           }
2763       }
2764     }
2765     else
2766     {
2767       // where there are no _LayerEdge's on a _ConvexFace,
2768       // as e.g. on a fillet surface with no internal nodes - issue 22580,
2769       // so that collision of viscous internal faces is not detected by check of
2770       // intersection of _LayerEdge's with the viscous internal faces.
2771
2772       set< const SMDS_MeshNode* > usedNodes;
2773
2774       // look for _LayerEdge's with null _sWOL
2775       id2eos = convFace._subIdToEOS.begin();
2776       for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
2777       {
2778         _EdgesOnShape& eos = * id2eos->second;
2779         if ( !eos._sWOL.IsNull() )
2780           continue;
2781         for ( size_t i = 0; i < eos._edges.size(); ++i )
2782         {
2783           _LayerEdge* ledge = eos._edges[ i ];
2784           const SMDS_MeshNode* srcNode = ledge->_nodes[0];
2785           if ( !usedNodes.insert( srcNode ).second ) continue;
2786
2787           for ( size_t i = 0; i < ledge->_simplices.size(); ++i )
2788           {
2789             usedNodes.insert( ledge->_simplices[i]._nPrev );
2790             usedNodes.insert( ledge->_simplices[i]._nNext );
2791           }
2792           convFace._simplexTestEdges.push_back( ledge );
2793         }
2794       }
2795     }
2796   } // loop on FACEs of data._solid
2797 }
2798
2799 //================================================================================
2800 /*!
2801  * \brief Detect shapes (and _LayerEdge's on them) to smooth
2802  */
2803 //================================================================================
2804
2805 bool _ViscousBuilder::findShapesToSmooth( _SolidData& data )
2806 {
2807   // define allowed thickness
2808   computeGeomSize( data ); // compute data._geomSize and _LayerEdge::_maxLen
2809
2810   data._maxThickness = 0;
2811   data._minThickness = 1e100;
2812   list< const StdMeshers_ViscousLayers* >::iterator hyp = data._hyps.begin();
2813   for ( ; hyp != data._hyps.end(); ++hyp )
2814   {
2815     data._maxThickness = Max( data._maxThickness, (*hyp)->GetTotalThickness() );
2816     data._minThickness = Min( data._minThickness, (*hyp)->GetTotalThickness() );
2817   }
2818   //const double tgtThick = /*Min( 0.5 * data._geomSize, */data._maxThickness;
2819
2820   // Find shapes needing smoothing; such a shape has _LayerEdge._normal on it's
2821   // boundry inclined to the shape at a sharp angle
2822
2823   //list< TGeomID > shapesToSmooth;
2824   TopTools_MapOfShape edgesOfSmooFaces;
2825
2826   SMESH_MesherHelper helper( *_mesh );
2827   bool ok = true;
2828
2829   vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
2830   data._nbShapesToSmooth = 0;
2831
2832   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check FACEs
2833   {
2834     _EdgesOnShape& eos = edgesByGeom[iS];
2835     eos._toSmooth = false;
2836     if ( eos._edges.empty() || eos.ShapeType() != TopAbs_FACE )
2837       continue;
2838
2839     double tgtThick = eos._hyp.GetTotalThickness();
2840     TopExp_Explorer eExp( edgesByGeom[iS]._shape, TopAbs_EDGE );
2841     for ( ; eExp.More() && !eos._toSmooth; eExp.Next() )
2842     {
2843       TGeomID iE = getMeshDS()->ShapeToIndex( eExp.Current() );
2844       vector<_LayerEdge*>& eE = edgesByGeom[ iE ]._edges;
2845       if ( eE.empty() ) continue;
2846
2847       double faceSize;
2848       for ( size_t i = 0; i < eE.size() && !eos._toSmooth; ++i )
2849         if ( eE[i]->_cosin > theMinSmoothCosin )
2850         {
2851           SMDS_ElemIteratorPtr fIt = eE[i]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2852           while ( fIt->more() && !eos._toSmooth )
2853           {
2854             const SMDS_MeshElement* face = fIt->next();
2855             if ( face->getshapeId() == eos._shapeID &&
2856                  getDistFromEdge( face, eE[i]->_nodes[0], faceSize ))
2857             {
2858               eos._toSmooth = needSmoothing( eE[i]->_cosin, tgtThick, faceSize );
2859             }
2860           }
2861         }
2862     }
2863     if ( eos._toSmooth )
2864     {
2865       for ( eExp.ReInit(); eExp.More(); eExp.Next() )
2866         edgesOfSmooFaces.Add( eExp.Current() );
2867
2868       data.PrepareEdgesToSmoothOnFace( &edgesByGeom[iS], /*substituteSrcNodes=*/false );
2869     }
2870     data._nbShapesToSmooth += eos._toSmooth;
2871
2872   }  // check FACEs
2873
2874   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check EDGEs
2875   {
2876     _EdgesOnShape& eos = edgesByGeom[iS];
2877     eos._edgeSmoother = NULL;
2878     if ( eos._edges.empty() || eos.ShapeType() != TopAbs_EDGE ) continue;
2879     if ( !eos._hyp.ToSmooth() ) continue;
2880
2881     const TopoDS_Edge& E = TopoDS::Edge( edgesByGeom[iS]._shape );
2882     if ( SMESH_Algo::isDegenerated( E ) || !edgesOfSmooFaces.Contains( E ))
2883       continue;
2884
2885     double tgtThick = eos._hyp.GetTotalThickness();
2886     for ( TopoDS_Iterator vIt( E ); vIt.More() && !eos._toSmooth; vIt.Next() )
2887     {
2888       TGeomID iV = getMeshDS()->ShapeToIndex( vIt.Value() );
2889       vector<_LayerEdge*>& eV = edgesByGeom[ iV ]._edges;
2890       if ( eV.empty() ) continue;
2891       gp_Vec  eDir    = getEdgeDir( E, TopoDS::Vertex( vIt.Value() ));
2892       double angle    = eDir.Angle( eV[0]->_normal );
2893       double cosin    = Cos( angle );
2894       double cosinAbs = Abs( cosin );
2895       if ( cosinAbs > theMinSmoothCosin )
2896       {
2897         // always smooth analytic EDGEs
2898         Handle(Geom_Curve) curve = _Smoother1D::CurveForSmooth( E, eos, helper );
2899         eos._toSmooth = ! curve.IsNull();
2900
2901         // compare tgtThick with the length of an end segment
2902         SMDS_ElemIteratorPtr eIt = eV[0]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
2903         while ( eIt->more() && !eos._toSmooth )
2904         {
2905           const SMDS_MeshElement* endSeg = eIt->next();
2906           if ( endSeg->getshapeId() == (int) iS )
2907           {
2908             double segLen =
2909               SMESH_TNodeXYZ( endSeg->GetNode(0) ).Distance( endSeg->GetNode(1 ));
2910             eos._toSmooth = needSmoothing( cosinAbs, tgtThick, segLen );
2911           }
2912         }
2913         if ( eos._toSmooth )
2914         {
2915           eos._edgeSmoother = new _Smoother1D( curve, eos );
2916
2917           for ( size_t i = 0; i < eos._edges.size(); ++i )
2918             eos._edges[i]->Set( _LayerEdge::TO_SMOOTH );
2919         }
2920       }
2921     }
2922     data._nbShapesToSmooth += eos._toSmooth;
2923
2924   } // check EDGEs
2925
2926   // Reset _cosin if no smooth is allowed by the user
2927   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
2928   {
2929     _EdgesOnShape& eos = edgesByGeom[iS];
2930     if ( eos._edges.empty() ) continue;
2931
2932     if ( !eos._hyp.ToSmooth() )
2933       for ( size_t i = 0; i < eos._edges.size(); ++i )
2934         eos._edges[i]->SetCosin( 0 );
2935   }
2936
2937
2938   // Fill _eosC1 to make that C1 FACEs and EGDEs between them to be smoothed as a whole
2939
2940   TopTools_MapOfShape c1VV;
2941
2942   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check FACEs
2943   {
2944     _EdgesOnShape& eos = edgesByGeom[iS];
2945     if ( eos._edges.empty() ||
2946          eos.ShapeType() != TopAbs_FACE ||
2947          !eos._toSmooth )
2948       continue;
2949
2950     // check EDGEs of a FACE
2951     TopTools_MapOfShape checkedEE, allVV;
2952     list< SMESH_subMesh* > smQueue( 1, eos._subMesh ); // sm of FACEs
2953     while ( !smQueue.empty() )
2954     {
2955       SMESH_subMesh* sm = smQueue.front();
2956       smQueue.pop_front();
2957       SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/false);
2958       while ( smIt->more() )
2959       {
2960         sm = smIt->next();
2961         if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
2962           allVV.Add( sm->GetSubShape() );
2963         if ( sm->GetSubShape().ShapeType() != TopAbs_EDGE ||
2964              !checkedEE.Add( sm->GetSubShape() ))
2965           continue;
2966
2967         _EdgesOnShape*      eoe = data.GetShapeEdges( sm->GetId() );
2968         vector<_LayerEdge*>& eE = eoe->_edges;
2969         if ( eE.empty() || !eoe->_sWOL.IsNull() )
2970           continue;
2971
2972         bool isC1 = true; // check continuity along an EDGE
2973         for ( size_t i = 0; i < eE.size() && isC1; ++i )
2974           isC1 = ( Abs( eE[i]->_cosin ) < theMinSmoothCosin );
2975         if ( !isC1 )
2976           continue;
2977
2978         // check that mesh faces are C1 as well
2979         {
2980           gp_XYZ norm1, norm2;
2981           const SMDS_MeshNode*   n = eE[ eE.size() / 2 ]->_nodes[0];
2982           SMDS_ElemIteratorPtr fIt = n->GetInverseElementIterator(SMDSAbs_Face);
2983           if ( !SMESH_MeshAlgos::FaceNormal( fIt->next(), norm1, /*normalized=*/true ))
2984             continue;
2985           while ( fIt->more() && isC1 )
2986             isC1 = ( SMESH_MeshAlgos::FaceNormal( fIt->next(), norm2, /*normalized=*/true ) &&
2987                      Abs( norm1 * norm2 ) >= ( 1. - theMinSmoothCosin ));
2988           if ( !isC1 )
2989             continue;
2990         }
2991
2992         // add the EDGE and an adjacent FACE to _eosC1
2993         PShapeIteratorPtr fIt = helper.GetAncestors( sm->GetSubShape(), *_mesh, TopAbs_FACE );
2994         while ( const TopoDS_Shape* face = fIt->next() )
2995         {
2996           _EdgesOnShape* eof = data.GetShapeEdges( *face );
2997           if ( !eof ) continue; // other solid
2998           if ( !eos.HasC1( eoe ))
2999           {
3000             eos._eosC1.push_back( eoe );
3001             eoe->_toSmooth = false;
3002             data.PrepareEdgesToSmoothOnFace( eoe, /*substituteSrcNodes=*/false );
3003           }
3004           if ( eos._shapeID != eof->_shapeID && !eos.HasC1( eof )) 
3005           {
3006             eos._eosC1.push_back( eof );
3007             eof->_toSmooth = false;
3008             data.PrepareEdgesToSmoothOnFace( eof, /*substituteSrcNodes=*/false );
3009             smQueue.push_back( eof->_subMesh );
3010           }
3011         }
3012       }
3013     }
3014     if ( eos._eosC1.empty() )
3015       continue;
3016
3017     // check VERTEXes of C1 FACEs
3018     TopTools_MapIteratorOfMapOfShape vIt( allVV );
3019     for ( ; vIt.More(); vIt.Next() )
3020     {
3021       _EdgesOnShape* eov = data.GetShapeEdges( vIt.Key() );
3022       if ( !eov || eov->_edges.empty() || !eov->_sWOL.IsNull() )
3023         continue;
3024
3025       bool isC1 = true; // check if all adjacent FACEs are in eos._eosC1
3026       PShapeIteratorPtr fIt = helper.GetAncestors( vIt.Key(), *_mesh, TopAbs_FACE );
3027       while ( const TopoDS_Shape* face = fIt->next() )
3028       {
3029         _EdgesOnShape* eof = data.GetShapeEdges( *face );
3030         if ( !eof ) continue; // other solid
3031         isC1 = ( face->IsSame( eos._shape ) || eos.HasC1( eof ));
3032         if ( !isC1 )
3033           break;
3034       }
3035       if ( isC1 )
3036       {
3037         eos._eosC1.push_back( eov );
3038         data.PrepareEdgesToSmoothOnFace( eov, /*substituteSrcNodes=*/false );
3039         c1VV.Add( eov->_shape );
3040       }
3041     }
3042
3043   } // fill _eosC1 of FACEs
3044
3045
3046   // Find C1 EDGEs
3047
3048   vector< pair< _EdgesOnShape*, gp_XYZ > > dirOfEdges;
3049
3050   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check VERTEXes
3051   {
3052     _EdgesOnShape& eov = edgesByGeom[iS];
3053     if ( eov._edges.empty() ||
3054          eov.ShapeType() != TopAbs_VERTEX ||
3055          c1VV.Contains( eov._shape ))
3056       continue;
3057     const TopoDS_Vertex& V = TopoDS::Vertex( eov._shape );
3058
3059     // get directions of surrounding EDGEs
3060     dirOfEdges.clear();
3061     PShapeIteratorPtr fIt = helper.GetAncestors( eov._shape, *_mesh, TopAbs_EDGE );
3062     while ( const TopoDS_Shape* e = fIt->next() )
3063     {
3064       _EdgesOnShape* eoe = data.GetShapeEdges( *e );
3065       if ( !eoe ) continue; // other solid
3066       gp_XYZ eDir = getEdgeDir( TopoDS::Edge( *e ), V );
3067       if ( !Precision::IsInfinite( eDir.X() ))
3068         dirOfEdges.push_back( make_pair( eoe, eDir.Normalized() ));
3069     }
3070
3071     // find EDGEs with C1 directions
3072     for ( size_t i = 0; i < dirOfEdges.size(); ++i )
3073       for ( size_t j = i+1; j < dirOfEdges.size(); ++j )
3074         if ( dirOfEdges[i].first && dirOfEdges[j].first )
3075         {
3076           double dot = dirOfEdges[i].second * dirOfEdges[j].second;
3077           bool isC1 = ( dot < - ( 1. - theMinSmoothCosin ));
3078           if ( isC1 )
3079           {
3080             double maxEdgeLen = 3 * Min( eov._edges[0]->_maxLen, eov._hyp.GetTotalThickness() );
3081             double eLen1 = SMESH_Algo::EdgeLength( TopoDS::Edge( dirOfEdges[i].first->_shape ));
3082             double eLen2 = SMESH_Algo::EdgeLength( TopoDS::Edge( dirOfEdges[j].first->_shape ));
3083             if ( eLen1 < maxEdgeLen ) eov._eosC1.push_back( dirOfEdges[i].first );
3084             if ( eLen2 < maxEdgeLen ) eov._eosC1.push_back( dirOfEdges[j].first );
3085             dirOfEdges[i].first = 0;
3086             dirOfEdges[j].first = 0;
3087           }
3088         }
3089   } // fill _eosC1 of VERTEXes
3090
3091
3092
3093   return ok;
3094 }
3095
3096 //================================================================================
3097 /*!
3098  * \brief initialize data of _EdgesOnShape
3099  */
3100 //================================================================================
3101
3102 void _ViscousBuilder::setShapeData( _EdgesOnShape& eos,
3103                                     SMESH_subMesh* sm,
3104                                     _SolidData&    data )
3105 {
3106   if ( !eos._shape.IsNull() ||
3107        sm->GetSubShape().ShapeType() == TopAbs_WIRE )
3108     return;
3109
3110   SMESH_MesherHelper helper( *_mesh );
3111
3112   eos._subMesh = sm;
3113   eos._shapeID = sm->GetId();
3114   eos._shape   = sm->GetSubShape();
3115   if ( eos.ShapeType() == TopAbs_FACE )
3116     eos._shape.Orientation( helper.GetSubShapeOri( data._solid, eos._shape ));
3117   eos._toSmooth = false;
3118   eos._data = &data;
3119
3120   // set _SWOL
3121   map< TGeomID, TopoDS_Shape >::const_iterator s2s =
3122     data._shrinkShape2Shape.find( eos._shapeID );
3123   if ( s2s != data._shrinkShape2Shape.end() )
3124     eos._sWOL = s2s->second;
3125
3126   eos._isRegularSWOL = true;
3127   if ( eos.SWOLType() == TopAbs_FACE )
3128   {
3129     const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
3130     Handle(ShapeAnalysis_Surface) surface = helper.GetSurface( F );
3131     eos._isRegularSWOL = ( ! surface->HasSingularities( 1e-7 ));
3132   }
3133
3134   // set _hyp
3135   if ( data._hyps.size() == 1 )
3136   {
3137     eos._hyp = data._hyps.back();
3138   }
3139   else
3140   {
3141     // compute average StdMeshers_ViscousLayers parameters
3142     map< TGeomID, const StdMeshers_ViscousLayers* >::iterator f2hyp;
3143     if ( eos.ShapeType() == TopAbs_FACE )
3144     {
3145       if (( f2hyp = data._face2hyp.find( eos._shapeID )) != data._face2hyp.end() )
3146         eos._hyp = f2hyp->second;
3147     }
3148     else
3149     {
3150       PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
3151       while ( const TopoDS_Shape* face = fIt->next() )
3152       {
3153         TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
3154         if (( f2hyp = data._face2hyp.find( faceID )) != data._face2hyp.end() )
3155           eos._hyp.Add( f2hyp->second );
3156       }
3157     }
3158   }
3159
3160   // set _faceNormals
3161   if ( ! eos._hyp.UseSurfaceNormal() )
3162   {
3163     if ( eos.ShapeType() == TopAbs_FACE ) // get normals to elements on a FACE
3164     {
3165       SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3166       eos._faceNormals.resize( smDS->NbElements() );
3167
3168       SMDS_ElemIteratorPtr eIt = smDS->GetElements();
3169       for ( int iF = 0; eIt->more(); ++iF )
3170       {
3171         const SMDS_MeshElement* face = eIt->next();
3172         if ( !SMESH_MeshAlgos::FaceNormal( face, eos._faceNormals[iF], /*normalized=*/true ))
3173           eos._faceNormals[iF].SetCoord( 0,0,0 );
3174       }
3175
3176       if ( !helper.IsReversedSubMesh( TopoDS::Face( eos._shape )))
3177         for ( size_t iF = 0; iF < eos._faceNormals.size(); ++iF )
3178           eos._faceNormals[iF].Reverse();
3179     }
3180     else // find EOS of adjacent FACEs
3181     {
3182       PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
3183       while ( const TopoDS_Shape* face = fIt->next() )
3184       {
3185         TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
3186         eos._faceEOS.push_back( & data._edgesOnShape[ faceID ]);
3187         if ( eos._faceEOS.back()->_shape.IsNull() )
3188           // avoid using uninitialised _shapeID in GetNormal()
3189           eos._faceEOS.back()->_shapeID = faceID;
3190       }
3191     }
3192   }
3193 }
3194
3195 //================================================================================
3196 /*!
3197  * \brief Returns normal of a face
3198  */
3199 //================================================================================
3200
3201 bool _EdgesOnShape::GetNormal( const SMDS_MeshElement* face, gp_Vec& norm )
3202 {
3203   bool ok = false;
3204   const _EdgesOnShape* eos = 0;
3205
3206   if ( face->getshapeId() == _shapeID )
3207   {
3208     eos = this;
3209   }
3210   else
3211   {
3212     for ( size_t iF = 0; iF < _faceEOS.size() && !eos; ++iF )
3213       if ( face->getshapeId() == _faceEOS[ iF ]->_shapeID )
3214         eos = _faceEOS[ iF ];
3215   }
3216
3217   if (( eos ) &&
3218       ( ok = ( face->getIdInShape() < (int) eos->_faceNormals.size() )))
3219   {
3220     norm = eos->_faceNormals[ face->getIdInShape() ];
3221   }
3222   else if ( !eos )
3223   {
3224     debugMsg( "_EdgesOnShape::Normal() failed for face "<<face->GetID()
3225               << " on _shape #" << _shapeID );
3226   }
3227   return ok;
3228 }
3229
3230
3231 //================================================================================
3232 /*!
3233  * \brief Set data of _LayerEdge needed for smoothing
3234  */
3235 //================================================================================
3236
3237 bool _ViscousBuilder::setEdgeData(_LayerEdge&         edge,
3238                                   _EdgesOnShape&      eos,
3239                                   SMESH_MesherHelper& helper,
3240                                   _SolidData&         data)
3241 {
3242   const SMDS_MeshNode* node = edge._nodes[0]; // source node
3243
3244   edge._len       = 0;
3245   edge._maxLen    = Precision::Infinite();
3246   edge._minAngle  = 0;
3247   edge._2neibors  = 0;
3248   edge._curvature = 0;
3249   edge._flags     = 0;
3250
3251   // --------------------------
3252   // Compute _normal and _cosin
3253   // --------------------------
3254
3255   edge._cosin     = 0;
3256   edge._lenFactor = 1.;
3257   edge._normal.SetCoord(0,0,0);
3258   _Simplex::GetSimplices( node, edge._simplices, data._ignoreFaceIds, &data );
3259
3260   int totalNbFaces = 0;
3261   TopoDS_Face F;
3262   std::pair< TopoDS_Face, gp_XYZ > face2Norm[20];
3263   gp_Vec geomNorm;
3264   bool normOK = true;
3265
3266   const bool onShrinkShape = !eos._sWOL.IsNull();
3267   const bool useGeometry   = (( eos._hyp.UseSurfaceNormal() ) ||
3268                               ( eos.ShapeType() != TopAbs_FACE /*&& !onShrinkShape*/ ));
3269
3270   // get geom FACEs the node lies on
3271   //if ( useGeometry )
3272   {
3273     set<TGeomID> faceIds;
3274     if  ( eos.ShapeType() == TopAbs_FACE )
3275     {
3276       faceIds.insert( eos._shapeID );
3277     }
3278     else
3279     {
3280       SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3281       while ( fIt->more() )
3282         faceIds.insert( fIt->next()->getshapeId() );
3283     }
3284     set<TGeomID>::iterator id = faceIds.begin();
3285     for ( ; id != faceIds.end(); ++id )
3286     {
3287       const TopoDS_Shape& s = getMeshDS()->IndexToShape( *id );
3288       if ( s.IsNull() || s.ShapeType() != TopAbs_FACE || data._ignoreFaceIds.count( *id ))
3289         continue;
3290       F = TopoDS::Face( s );
3291       face2Norm[ totalNbFaces ].first = F;
3292       totalNbFaces++;
3293     }
3294   }
3295
3296   // find _normal
3297   if ( useGeometry )
3298   {
3299     if ( onShrinkShape ) // one of faces the node is on has no layers
3300     {
3301       if ( eos.SWOLType() == TopAbs_EDGE )
3302       {
3303         // inflate from VERTEX along EDGE
3304         edge._normal = getEdgeDir( TopoDS::Edge( eos._sWOL ), TopoDS::Vertex( eos._shape ));
3305       }
3306       else if ( eos.ShapeType() == TopAbs_VERTEX )
3307       {
3308         // inflate from VERTEX along FACE
3309         edge._normal = getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Vertex( eos._shape ),
3310                                    node, helper, normOK, &edge._cosin);
3311       }
3312       else
3313       {
3314         // inflate from EDGE along FACE
3315         edge._normal = getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Edge( eos._shape ),
3316                                    node, helper, normOK);
3317       }
3318     }
3319     else // layers are on all FACEs of SOLID the node is on
3320     {
3321       int nbOkNorms = 0;
3322       for ( int iF = 0; iF < totalNbFaces; ++iF )
3323       {
3324         F = TopoDS::Face( face2Norm[ iF ].first );
3325         geomNorm = getFaceNormal( node, F, helper, normOK );
3326         if ( !normOK ) continue;
3327         nbOkNorms++;
3328
3329         if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3330           geomNorm.Reverse();
3331         face2Norm[ iF ].second = geomNorm.XYZ();
3332         edge._normal += geomNorm.XYZ();
3333       }
3334       if ( nbOkNorms == 0 )
3335         return error(SMESH_Comment("Can't get normal to node ") << node->GetID(), data._index);
3336
3337       if ( edge._normal.Modulus() < 1e-3 && nbOkNorms > 1 )
3338       {
3339         // opposite normals, re-get normals at shifted positions (IPAL 52426)
3340         edge._normal.SetCoord( 0,0,0 );
3341         for ( int iF = 0; iF < totalNbFaces; ++iF )
3342         {
3343           const TopoDS_Face& F = face2Norm[iF].first;
3344           geomNorm = getFaceNormal( node, F, helper, normOK, /*shiftInside=*/true );
3345           if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3346             geomNorm.Reverse();
3347           if ( normOK )
3348             face2Norm[ iF ].second = geomNorm.XYZ();
3349           edge._normal += face2Norm[ iF ].second;
3350         }
3351       }
3352
3353       if ( totalNbFaces >= 3 )
3354       {
3355         edge._normal = getNormalByOffset( &edge, face2Norm, totalNbFaces );
3356       }
3357     }
3358   }
3359   else // !useGeometry - get _normal using surrounding mesh faces
3360   {
3361     edge._normal = getWeigthedNormal( &edge );
3362
3363     // set<TGeomID> faceIds;
3364     //
3365     // SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3366     // while ( fIt->more() )
3367     // {
3368     //   const SMDS_MeshElement* face = fIt->next();
3369     //   if ( eos.GetNormal( face, geomNorm ))
3370     //   {
3371     //     if ( onShrinkShape && !faceIds.insert( face->getshapeId() ).second )
3372     //       continue; // use only one mesh face on FACE
3373     //     edge._normal += geomNorm.XYZ();
3374     //     totalNbFaces++;
3375     //   }
3376     // }
3377   }
3378
3379   // compute _cosin
3380   //if ( eos._hyp.UseSurfaceNormal() )
3381   {
3382     switch ( eos.ShapeType() )
3383     {
3384     case TopAbs_FACE: {
3385       edge._cosin = 0;
3386       break;
3387     }
3388     case TopAbs_EDGE: {
3389       TopoDS_Edge E    = TopoDS::Edge( eos._shape );
3390       gp_Vec inFaceDir = getFaceDir( F, E, node, helper, normOK );
3391       double angle     = inFaceDir.Angle( edge._normal ); // [0,PI]
3392       edge._cosin      = Cos( angle );
3393       break;
3394     }
3395     case TopAbs_VERTEX: {
3396       if ( eos.SWOLType() != TopAbs_FACE ) { // else _cosin is set by getFaceDir()
3397         TopoDS_Vertex V  = TopoDS::Vertex( eos._shape );
3398         gp_Vec inFaceDir = getFaceDir( F, V, node, helper, normOK );
3399         double angle     = inFaceDir.Angle( edge._normal ); // [0,PI]
3400         edge._cosin      = Cos( angle );
3401         if ( totalNbFaces > 2 || helper.IsSeamShape( node->getshapeId() ))
3402           for ( int iF = totalNbFaces-2; iF >=0; --iF )
3403           {
3404             F = face2Norm[ iF ].first;
3405             inFaceDir = getFaceDir( F, V, node, helper, normOK=true );
3406             if ( normOK ) {
3407               double angle = inFaceDir.Angle( edge._normal );
3408               double cosin = Cos( angle );
3409               if ( Abs( cosin ) > edge._cosin )
3410                 edge._cosin = cosin;
3411             }
3412           }
3413       }
3414       break;
3415     }
3416     default:
3417       return error(SMESH_Comment("Invalid shape position of node ")<<node, data._index);
3418     }
3419   }
3420
3421   double normSize = edge._normal.SquareModulus();
3422   if ( normSize < numeric_limits<double>::min() )
3423     return error(SMESH_Comment("Bad normal at node ")<< node->GetID(), data._index );
3424
3425   edge._normal /= sqrt( normSize );
3426
3427   if ( edge.Is( _LayerEdge::MULTI_NORMAL ) && edge._nodes.size() == 2 )
3428   {
3429     getMeshDS()->RemoveFreeNode( edge._nodes.back(), 0, /*fromGroups=*/false );
3430     edge._nodes.resize( 1 );
3431     edge._normal.SetCoord( 0,0,0 );
3432     edge._maxLen = 0;
3433   }
3434
3435   // Set the rest data
3436   // --------------------
3437
3438   edge.SetCosin( edge._cosin ); // to update edge._lenFactor
3439
3440   if ( onShrinkShape )
3441   {
3442     const SMDS_MeshNode* tgtNode = edge._nodes.back();
3443     if ( SMESHDS_SubMesh* sm = getMeshDS()->MeshElements( data._solid ))
3444       sm->RemoveNode( tgtNode , /*isNodeDeleted=*/false );
3445
3446     // set initial position which is parameters on _sWOL in this case
3447     if ( eos.SWOLType() == TopAbs_EDGE )
3448     {
3449       double u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), node, 0, &normOK );
3450       edge._pos.push_back( gp_XYZ( u, 0, 0 ));
3451       if ( edge._nodes.size() > 1 )
3452         getMeshDS()->SetNodeOnEdge( tgtNode, TopoDS::Edge( eos._sWOL ), u );
3453     }
3454     else // eos.SWOLType() == TopAbs_FACE
3455     {
3456       gp_XY uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), node, 0, &normOK );
3457       edge._pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
3458       if ( edge._nodes.size() > 1 )
3459         getMeshDS()->SetNodeOnFace( tgtNode, TopoDS::Face( eos._sWOL ), uv.X(), uv.Y() );
3460     }
3461
3462     if ( edge._nodes.size() > 1 )
3463     {
3464       // check if an angle between a FACE with layers and SWOL is sharp,
3465       // else the edge should not inflate
3466       F.Nullify();
3467       for ( int iF = 0; iF < totalNbFaces  &&  F.IsNull();  ++iF ) // find a FACE with VL
3468         if ( ! helper.IsSubShape( eos._sWOL, face2Norm[iF].first ))
3469           F = face2Norm[iF].first;
3470       if ( !F.IsNull())
3471       {
3472         geomNorm = getFaceNormal( node, F, helper, normOK );
3473         if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3474           geomNorm.Reverse(); // inside the SOLID
3475         if ( geomNorm * edge._normal < -0.001 )
3476         {
3477           getMeshDS()->RemoveFreeNode( tgtNode, 0, /*fromGroups=*/false );
3478           edge._nodes.resize( 1 );
3479         }
3480         else if ( edge._lenFactor > 3 )
3481         {
3482           edge._lenFactor = 2;
3483           edge.Set( _LayerEdge::RISKY_SWOL );
3484         }
3485       }
3486     }
3487   }
3488   else
3489   {
3490     edge._pos.push_back( SMESH_TNodeXYZ( node ));
3491
3492     if ( eos.ShapeType() == TopAbs_FACE )
3493     {
3494       double angle;
3495       for ( size_t i = 0; i < edge._simplices.size(); ++i )
3496       {
3497         edge._simplices[i].IsMinAngleOK( edge._pos.back(), angle );
3498         edge._minAngle = Max( edge._minAngle, angle ); // "angle" is actually cosine
3499       }
3500     }
3501   }
3502
3503   // Set neighbor nodes for a _LayerEdge based on EDGE
3504
3505   if ( eos.ShapeType() == TopAbs_EDGE /*||
3506        ( onShrinkShape && posType == SMDS_TOP_VERTEX && fabs( edge._cosin ) < 1e-10 )*/)
3507   {
3508     edge._2neibors = new _2NearEdges;
3509     // target nodes instead of source ones will be set later
3510   }
3511
3512   return true;
3513 }
3514
3515 //================================================================================
3516 /*!
3517  * \brief Return normal to a FACE at a node
3518  *  \param [in] n - node
3519  *  \param [in] face - FACE
3520  *  \param [in] helper - helper
3521  *  \param [out] isOK - true or false
3522  *  \param [in] shiftInside - to find normal at a position shifted inside the face
3523  *  \return gp_XYZ - normal
3524  */
3525 //================================================================================
3526
3527 gp_XYZ _ViscousBuilder::getFaceNormal(const SMDS_MeshNode* node,
3528                                       const TopoDS_Face&   face,
3529                                       SMESH_MesherHelper&  helper,
3530                                       bool&                isOK,
3531                                       bool                 shiftInside)
3532 {
3533   gp_XY uv;
3534   if ( shiftInside )
3535   {
3536     // get a shifted position
3537     gp_Pnt p = SMESH_TNodeXYZ( node );
3538     gp_XYZ shift( 0,0,0 );
3539     TopoDS_Shape S = helper.GetSubShapeByNode( node, helper.GetMeshDS() );
3540     switch ( S.ShapeType() ) {
3541     case TopAbs_VERTEX:
3542     {
3543       shift = getFaceDir( face, TopoDS::Vertex( S ), node, helper, isOK );
3544       break;
3545     }
3546     case TopAbs_EDGE:
3547     {
3548       shift = getFaceDir( face, TopoDS::Edge( S ), node, helper, isOK );
3549       break;
3550     }
3551     default:
3552       isOK = false;
3553     }
3554     if ( isOK )
3555       shift.Normalize();
3556     p.Translate( shift * 1e-5 );
3557
3558     TopLoc_Location loc;
3559     GeomAPI_ProjectPointOnSurf& projector = helper.GetProjector( face, loc, 1e-7 );
3560
3561     if ( !loc.IsIdentity() ) p.Transform( loc.Transformation().Inverted() );
3562     
3563     projector.Perform( p );
3564     if ( !projector.IsDone() || projector.NbPoints() < 1 )
3565     {
3566       isOK = false;
3567       return p.XYZ();
3568     }
3569     Quantity_Parameter U,V;
3570     projector.LowerDistanceParameters(U,V);
3571     uv.SetCoord( U,V );
3572   }
3573   else
3574   {
3575     uv = helper.GetNodeUV( face, node, 0, &isOK );
3576   }
3577
3578   gp_Dir normal;
3579   isOK = false;
3580
3581   Handle(Geom_Surface) surface = BRep_Tool::Surface( face );
3582
3583   if ( !shiftInside &&
3584        helper.IsDegenShape( node->getshapeId() ) &&
3585        getFaceNormalAtSingularity( uv, face, helper, normal ))
3586   {
3587     isOK = true;
3588     return normal.XYZ();
3589   }
3590
3591   int pointKind = GeomLib::NormEstim( surface, uv, 1e-5, normal );
3592   enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
3593
3594   if ( pointKind == IMPOSSIBLE &&
3595        node->GetPosition()->GetDim() == 2 ) // node inside the FACE
3596   {
3597     // probably NormEstim() failed due to a too high tolerance
3598     pointKind = GeomLib::NormEstim( surface, uv, 1e-20, normal );
3599     isOK = ( pointKind < IMPOSSIBLE );
3600   }
3601   if ( pointKind < IMPOSSIBLE )
3602   {
3603     if ( pointKind != REGULAR &&
3604          !shiftInside &&
3605          node->GetPosition()->GetDim() < 2 ) // FACE boundary
3606     {
3607       gp_XYZ normShift = getFaceNormal( node, face, helper, isOK, /*shiftInside=*/true );
3608       if ( normShift * normal.XYZ() < 0. )
3609         normal = normShift;
3610     }
3611     isOK = true;
3612   }
3613
3614   if ( !isOK ) // hard singularity, to call with shiftInside=true ?
3615   {
3616     const TGeomID faceID = helper.GetMeshDS()->ShapeToIndex( face );
3617
3618     SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3619     while ( fIt->more() )
3620     {
3621       const SMDS_MeshElement* f = fIt->next();
3622       if ( f->getshapeId() == faceID )
3623       {
3624         isOK = SMESH_MeshAlgos::FaceNormal( f, (gp_XYZ&) normal.XYZ(), /*normalized=*/true );
3625         if ( isOK )
3626         {
3627           TopoDS_Face ff = face;
3628           ff.Orientation( TopAbs_FORWARD );
3629           if ( helper.IsReversedSubMesh( ff ))
3630             normal.Reverse();
3631           break;
3632         }
3633       }
3634     }
3635   }
3636   return normal.XYZ();
3637 }
3638
3639 //================================================================================
3640 /*!
3641  * \brief Try to get normal at a singularity of a surface basing on it's nature
3642  */
3643 //================================================================================
3644
3645 bool _ViscousBuilder::getFaceNormalAtSingularity( const gp_XY&        uv,
3646                                                   const TopoDS_Face&  face,
3647                                                   SMESH_MesherHelper& helper,
3648                                                   gp_Dir&             normal )
3649 {
3650   BRepAdaptor_Surface surface( face );
3651   gp_Dir axis;
3652   if ( !getRovolutionAxis( surface, axis ))
3653     return false;
3654
3655   double f,l, d, du, dv;
3656   f = surface.FirstUParameter();
3657   l = surface.LastUParameter();
3658   d = ( uv.X() - f ) / ( l - f );
3659   du = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
3660   f = surface.FirstVParameter();
3661   l = surface.LastVParameter();
3662   d = ( uv.Y() - f ) / ( l - f );
3663   dv = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
3664
3665   gp_Dir refDir;
3666   gp_Pnt2d testUV = uv;
3667   enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
3668   double tol = 1e-5;
3669   Handle(Geom_Surface) geomsurf = surface.Surface().Surface();
3670   for ( int iLoop = 0; true ; ++iLoop )
3671   {
3672     testUV.SetCoord( testUV.X() + du, testUV.Y() + dv );
3673     if ( GeomLib::NormEstim( geomsurf, testUV, tol, refDir ) == REGULAR )
3674       break;
3675     if ( iLoop > 20 )
3676       return false;
3677     tol /= 10.;
3678   }
3679
3680   if ( axis * refDir < 0. )
3681     axis.Reverse();
3682
3683   normal = axis;
3684
3685   return true;
3686 }
3687
3688 //================================================================================
3689 /*!
3690  * \brief Return a normal at a node weighted with angles taken by faces
3691  */
3692 //================================================================================
3693
3694 gp_XYZ _ViscousBuilder::getWeigthedNormal( const _LayerEdge* edge )
3695 {
3696   const SMDS_MeshNode* n = edge->_nodes[0];
3697
3698   gp_XYZ resNorm(0,0,0);
3699   SMESH_TNodeXYZ p0( n ), pP, pN;
3700   for ( size_t i = 0; i < edge->_simplices.size(); ++i )
3701   {
3702     pP.Set( edge->_simplices[i]._nPrev );
3703     pN.Set( edge->_simplices[i]._nNext );
3704     gp_Vec v0P( p0, pP ), v0N( p0, pN ), vPN( pP, pN ), norm = v0P ^ v0N;
3705     double l0P = v0P.SquareMagnitude();
3706     double l0N = v0N.SquareMagnitude();
3707     double lPN = vPN.SquareMagnitude();
3708     if ( l0P < std::numeric_limits<double>::min() ||
3709          l0N < std::numeric_limits<double>::min() ||
3710          lPN < std::numeric_limits<double>::min() )
3711       continue;
3712     double lNorm = norm.SquareMagnitude();
3713     double  sin2 = lNorm / l0P / l0N;
3714     double angle = ACos(( v0P * v0N ) / Sqrt( l0P ) / Sqrt( l0N ));
3715
3716     double weight = sin2 * angle / lPN;
3717     resNorm += weight * norm.XYZ() / Sqrt( lNorm );
3718   }
3719
3720   return resNorm;
3721 }
3722
3723 //================================================================================
3724 /*!
3725  * \brief Return a normal at a node by getting a common point of offset planes
3726  *        defined by the FACE normals
3727  */
3728 //================================================================================
3729
3730 gp_XYZ _ViscousBuilder::getNormalByOffset( _LayerEdge*                      edge,
3731                                            std::pair< TopoDS_Face, gp_XYZ > f2Normal[],
3732                                            int                              nbFaces )
3733 {
3734   SMESH_TNodeXYZ p0 = edge->_nodes[0];
3735
3736   gp_XYZ resNorm(0,0,0);
3737   TopoDS_Shape V = SMESH_MesherHelper::GetSubShapeByNode( p0._node, getMeshDS() );
3738   if ( V.ShapeType() != TopAbs_VERTEX || nbFaces < 3 )
3739   {
3740     for ( int i = 0; i < nbFaces; ++i )
3741       resNorm += f2Normal[i].second;
3742     return resNorm;
3743   }
3744
3745   // prepare _OffsetPlane's
3746   vector< _OffsetPlane > pln( nbFaces );
3747   for ( int i = 0; i < nbFaces; ++i )
3748   {
3749     pln[i]._faceIndex = i;
3750     pln[i]._plane = gp_Pln( p0 + f2Normal[i].second, f2Normal[i].second );
3751   }
3752
3753   // intersect neighboring OffsetPlane's
3754   PShapeIteratorPtr edgeIt = SMESH_MesherHelper::GetAncestors( V, *_mesh, TopAbs_EDGE );
3755   while ( const TopoDS_Shape* edge = edgeIt->next() )
3756   {
3757     int f1 = -1, f2 = -1;
3758     for ( int i = 0; i < nbFaces &&  f2 < 0;  ++i )
3759       if ( SMESH_MesherHelper::IsSubShape( *edge, f2Normal[i].first ))
3760         (( f1 < 0 ) ? f1 : f2 ) = i;
3761
3762     if ( f2 >= 0 )
3763       pln[ f1 ].ComputeIntersectionLine( pln[ f2 ]);
3764   }
3765
3766   // get a common point
3767   gp_XYZ commonPnt( 0, 0, 0 );
3768   int nbPoints = 0;
3769   bool isPointFound;
3770   for ( int i = 0; i < nbFaces; ++i )
3771   {
3772     commonPnt += pln[ i ].GetCommonPoint( isPointFound );
3773     nbPoints  += isPointFound;
3774   }
3775   gp_XYZ wgtNorm = getWeigthedNormal( edge );
3776   if ( nbPoints == 0 )
3777     return wgtNorm;
3778
3779   commonPnt /= nbPoints;
3780   resNorm = commonPnt - p0;
3781
3782   // choose the best among resNorm and wgtNorm
3783   resNorm.Normalize();
3784   wgtNorm.Normalize();
3785   double resMinDot = std::numeric_limits<double>::max();
3786   double wgtMinDot = std::numeric_limits<double>::max();
3787   for ( int i = 0; i < nbFaces; ++i )
3788   {
3789     resMinDot = Min( resMinDot, resNorm * f2Normal[i].second );
3790     wgtMinDot = Min( wgtMinDot, wgtNorm * f2Normal[i].second );
3791   }
3792
3793   if ( Max( resMinDot, wgtMinDot ) < theMinSmoothCosin )
3794   {
3795     edge->Set( _LayerEdge::MULTI_NORMAL );
3796   }
3797
3798   return ( resMinDot > wgtMinDot ) ? resNorm : wgtNorm;
3799 }
3800
3801 //================================================================================
3802 /*!
3803  * \brief Compute line of intersection of 2 planes
3804  */
3805 //================================================================================
3806
3807 void _OffsetPlane::ComputeIntersectionLine( _OffsetPlane& pln )
3808 {
3809   int iNext = bool( _faceIndexNext[0] >= 0 );
3810   _faceIndexNext[ iNext ] = pln._faceIndex;
3811
3812   gp_XYZ n1 = _plane.Axis().Direction().XYZ();
3813   gp_XYZ n2 = pln._plane.Axis().Direction().XYZ();
3814
3815   gp_XYZ lineDir = n1 ^ n2;
3816
3817   double x = Abs( lineDir.X() );
3818   double y = Abs( lineDir.Y() );
3819   double z = Abs( lineDir.Z() );
3820
3821   int cooMax; // max coordinate
3822   if (x > y) {
3823     if (x > z) cooMax = 1;
3824     else       cooMax = 3;
3825   }
3826   else {
3827     if (y > z) cooMax = 2;
3828     else       cooMax = 3;
3829   }
3830
3831   if ( Abs( lineDir.Coord( cooMax )) < 0.05 )
3832     return;
3833
3834   gp_Pnt linePos;
3835   // the constants in the 2 plane equations
3836   double d1 = - ( _plane.Axis().Direction().XYZ()     * _plane.Location().XYZ() );
3837   double d2 = - ( pln._plane.Axis().Direction().XYZ() * pln._plane.Location().XYZ() );
3838
3839   switch ( cooMax ) {
3840   case 1:
3841     linePos.SetX(  0 );
3842     linePos.SetY(( d2*n1.Z() - d1*n2.Z()) / lineDir.X() );
3843     linePos.SetZ(( d1*n2.Y() - d2*n1.Y()) / lineDir.X() );
3844     break;
3845   case 2:
3846     linePos.SetX(( d1*n2.Z() - d2*n1.Z()) / lineDir.Y() );
3847     linePos.SetY(  0 );
3848     linePos.SetZ(( d2*n1.X() - d1*n2.X()) / lineDir.Y() );
3849     break;
3850   case 3:
3851     linePos.SetX(( d2*n1.Y() - d1*n2.Y()) / lineDir.Z() );
3852     linePos.SetY(( d1*n2.X() - d2*n1.X()) / lineDir.Z() );
3853     linePos.SetZ(  0 );
3854   }
3855
3856   gp_Lin& line = _lines[ iNext ];
3857   line.SetDirection( lineDir );
3858   line.SetLocation ( linePos );
3859
3860   _isLineOK[ iNext ] = true;
3861
3862
3863   iNext = bool( pln._faceIndexNext[0] >= 0 );
3864   pln._lines        [ iNext ] = line;
3865   pln._faceIndexNext[ iNext ] = this->_faceIndex;
3866   pln._isLineOK     [ iNext ] = true;
3867 }
3868
3869 //================================================================================
3870 /*!
3871  * \brief Computes intersection point of two _lines
3872  */
3873 //================================================================================
3874
3875 gp_XYZ _OffsetPlane::GetCommonPoint(bool& isFound) const
3876 {
3877   gp_XYZ p( 0,0,0 );
3878   isFound = false;
3879
3880   if ( NbLines() == 2 )
3881   {
3882     gp_Vec lPerp0 = _lines[0].Direction().XYZ() ^ _plane.Axis().Direction().XYZ();
3883     gp_Vec   l0l1 = _lines[1].Location().XYZ() - _lines[0].Location().XYZ();
3884     double  dot01 = lPerp0 * _lines[1].Direction().XYZ();
3885     if ( Abs( dot01 ) > std::numeric_limits<double>::min() )
3886     {
3887       double u1 = - ( lPerp0 * l0l1 ) / dot01;
3888       p = ( _lines[1].Location().XYZ() + _lines[1].Direction().XYZ() * u1 );
3889       isFound = true;
3890     }
3891   }
3892
3893   return p;
3894 }
3895
3896 //================================================================================
3897 /*!
3898  * \brief Find 2 neigbor nodes of a node on EDGE
3899  */
3900 //================================================================================
3901
3902 bool _ViscousBuilder::findNeiborsOnEdge(const _LayerEdge*     edge,
3903                                         const SMDS_MeshNode*& n1,
3904                                         const SMDS_MeshNode*& n2,
3905                                         _EdgesOnShape&        eos,
3906                                         _SolidData&           data)
3907 {
3908   const SMDS_MeshNode* node = edge->_nodes[0];
3909   const int        shapeInd = eos._shapeID;
3910   SMESHDS_SubMesh*   edgeSM = 0;
3911   if ( eos.ShapeType() == TopAbs_EDGE )
3912   {
3913     edgeSM = eos._subMesh->GetSubMeshDS();
3914     if ( !edgeSM || edgeSM->NbElements() == 0 )
3915       return error(SMESH_Comment("Not meshed EDGE ") << shapeInd, data._index);
3916   }
3917   int iN = 0;
3918   n2 = 0;
3919   SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Edge);
3920   while ( eIt->more() && !n2 )
3921   {
3922     const SMDS_MeshElement* e = eIt->next();
3923     const SMDS_MeshNode*   nNeibor = e->GetNode( 0 );
3924     if ( nNeibor == node ) nNeibor = e->GetNode( 1 );
3925     if ( edgeSM )
3926     {
3927       if (!edgeSM->Contains(e)) continue;
3928     }
3929     else
3930     {
3931       TopoDS_Shape s = SMESH_MesherHelper::GetSubShapeByNode( nNeibor, getMeshDS() );
3932       if ( !SMESH_MesherHelper::IsSubShape( s, eos._sWOL )) continue;
3933     }
3934     ( iN++ ? n2 : n1 ) = nNeibor;
3935   }
3936   if ( !n2 )
3937     return error(SMESH_Comment("Wrongly meshed EDGE ") << shapeInd, data._index);
3938   return true;
3939 }
3940
3941 //================================================================================
3942 /*!
3943  * \brief Set _curvature and _2neibors->_plnNorm by 2 neigbor nodes residing the same EDGE
3944  */
3945 //================================================================================
3946
3947 void _LayerEdge::SetDataByNeighbors( const SMDS_MeshNode* n1,
3948                                      const SMDS_MeshNode* n2,
3949                                      const _EdgesOnShape& eos,
3950                                      SMESH_MesherHelper&  helper)
3951 {
3952   if ( eos.ShapeType() != TopAbs_EDGE )
3953     return;
3954
3955   gp_XYZ  pos = SMESH_TNodeXYZ( _nodes[0] );
3956   gp_XYZ vec1 = pos - SMESH_TNodeXYZ( n1 );
3957   gp_XYZ vec2 = pos - SMESH_TNodeXYZ( n2 );
3958
3959   // Set _curvature
3960
3961   double      sumLen = vec1.Modulus() + vec2.Modulus();
3962   _2neibors->_wgt[0] = 1 - vec1.Modulus() / sumLen;
3963   _2neibors->_wgt[1] = 1 - vec2.Modulus() / sumLen;
3964   double avgNormProj = 0.5 * ( _normal * vec1 + _normal * vec2 );
3965   double      avgLen = 0.5 * ( vec1.Modulus() + vec2.Modulus() );
3966   if ( _curvature ) delete _curvature;
3967   _curvature = _Curvature::New( avgNormProj, avgLen );
3968   // if ( _curvature )
3969   //   debugMsg( _nodes[0]->GetID()
3970   //             << " CURV r,k: " << _curvature->_r<<","<<_curvature->_k
3971   //             << " proj = "<<avgNormProj<< " len = " << avgLen << "| lenDelta(0) = "
3972   //             << _curvature->lenDelta(0) );
3973
3974   // Set _plnNorm
3975
3976   if ( eos._sWOL.IsNull() )
3977   {
3978     TopoDS_Edge  E = TopoDS::Edge( eos._shape );
3979     // if ( SMESH_Algo::isDegenerated( E ))
3980     //   return;
3981     gp_XYZ dirE    = getEdgeDir( E, _nodes[0], helper );
3982     gp_XYZ plnNorm = dirE ^ _normal;
3983     double proj0   = plnNorm * vec1;
3984     double proj1   = plnNorm * vec2;
3985     if ( fabs( proj0 ) > 1e-10 || fabs( proj1 ) > 1e-10 )
3986     {
3987       if ( _2neibors->_plnNorm ) delete _2neibors->_plnNorm;
3988       _2neibors->_plnNorm = new gp_XYZ( plnNorm.Normalized() );
3989     }
3990   }
3991 }
3992
3993 //================================================================================
3994 /*!
3995  * \brief Copy data from a _LayerEdge of other SOLID and based on the same node;
3996  * this and other _LayerEdge's are inflated along a FACE or an EDGE
3997  */
3998 //================================================================================
3999
4000 gp_XYZ _LayerEdge::Copy( _LayerEdge&         other,
4001                          _EdgesOnShape&      eos,
4002                          SMESH_MesherHelper& helper )
4003 {
4004   _nodes     = other._nodes;
4005   _normal    = other._normal;
4006   _len       = 0;
4007   _lenFactor = other._lenFactor;
4008   _cosin     = other._cosin;
4009   _2neibors  = other._2neibors;
4010   _curvature = 0; std::swap( _curvature, other._curvature );
4011   _2neibors  = 0; std::swap( _2neibors,  other._2neibors );
4012
4013   gp_XYZ lastPos( 0,0,0 );
4014   if ( eos.SWOLType() == TopAbs_EDGE )
4015   {
4016     double u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), _nodes[0] );
4017     _pos.push_back( gp_XYZ( u, 0, 0));
4018
4019     u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), _nodes.back() );
4020     lastPos.SetX( u );
4021   }
4022   else // TopAbs_FACE
4023   {
4024     gp_XY uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), _nodes[0]);
4025     _pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
4026
4027     uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), _nodes.back() );
4028     lastPos.SetX( uv.X() );
4029     lastPos.SetY( uv.Y() );
4030   }
4031   return lastPos;
4032 }
4033
4034 //================================================================================
4035 /*!
4036  * \brief Set _cosin and _lenFactor
4037  */
4038 //================================================================================
4039
4040 void _LayerEdge::SetCosin( double cosin )
4041 {
4042   _cosin = cosin;
4043   cosin = Abs( _cosin );
4044   //_lenFactor = ( cosin < 1.-1e-12 ) ?  Min( 2., 1./sqrt(1-cosin*cosin )) : 1.0;
4045   _lenFactor = ( cosin < 1.-1e-12 ) ?  1./sqrt(1-cosin*cosin ) : 1.0;
4046 }
4047
4048 //================================================================================
4049 /*!
4050  * \brief Check if another _LayerEdge is a neighbor on EDGE
4051  */
4052 //================================================================================
4053
4054 bool _LayerEdge::IsNeiborOnEdge( const _LayerEdge* edge ) const
4055 {
4056   return (( this->_2neibors && this->_2neibors->include( edge )) ||
4057           ( edge->_2neibors && edge->_2neibors->include( this )));
4058 }
4059
4060 //================================================================================
4061 /*!
4062  * \brief Fills a vector<_Simplex > 
4063  */
4064 //================================================================================
4065
4066 void _Simplex::GetSimplices( const SMDS_MeshNode* node,
4067                              vector<_Simplex>&    simplices,
4068                              const set<TGeomID>&  ingnoreShapes,
4069                              const _SolidData*    dataToCheckOri,
4070                              const bool           toSort)
4071 {
4072   simplices.clear();
4073   SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
4074   while ( fIt->more() )
4075   {
4076     const SMDS_MeshElement* f = fIt->next();
4077     const TGeomID    shapeInd = f->getshapeId();
4078     if ( ingnoreShapes.count( shapeInd )) continue;
4079     const int nbNodes = f->NbCornerNodes();
4080     const int  srcInd = f->GetNodeIndex( node );
4081     const SMDS_MeshNode* nPrev = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd-1, nbNodes ));
4082     const SMDS_MeshNode* nNext = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+1, nbNodes ));
4083     const SMDS_MeshNode* nOpp  = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+2, nbNodes ));
4084     if ( dataToCheckOri && dataToCheckOri->_reversedFaceIds.count( shapeInd ))
4085       std::swap( nPrev, nNext );
4086     simplices.push_back( _Simplex( nPrev, nNext, ( nbNodes == 3 ? 0 : nOpp )));
4087   }
4088
4089   if ( toSort )
4090     SortSimplices( simplices );
4091 }
4092
4093 //================================================================================
4094 /*!
4095  * \brief Set neighbor simplices side by side
4096  */
4097 //================================================================================
4098
4099 void _Simplex::SortSimplices(vector<_Simplex>& simplices)
4100 {
4101   vector<_Simplex> sortedSimplices( simplices.size() );
4102   sortedSimplices[0] = simplices[0];
4103   size_t nbFound = 0;
4104   for ( size_t i = 1; i < simplices.size(); ++i )
4105   {
4106     for ( size_t j = 1; j < simplices.size(); ++j )
4107       if ( sortedSimplices[i-1]._nNext == simplices[j]._nPrev )
4108       {
4109         sortedSimplices[i] = simplices[j];
4110         nbFound++;
4111         break;
4112       }
4113   }
4114   if ( nbFound == simplices.size() - 1 )
4115     simplices.swap( sortedSimplices );
4116 }
4117
4118 //================================================================================
4119 /*!
4120  * \brief DEBUG. Create groups contating temorary data of _LayerEdge's
4121  */
4122 //================================================================================
4123
4124 void _ViscousBuilder::makeGroupOfLE()
4125 {
4126 #ifdef _DEBUG_
4127   for ( size_t i = 0 ; i < _sdVec.size(); ++i )
4128   {
4129     if ( _sdVec[i]._n2eMap.empty() ) continue;
4130
4131     dumpFunction( SMESH_Comment("make_LayerEdge_") << i );
4132     TNode2Edge::iterator n2e;
4133     for ( n2e = _sdVec[i]._n2eMap.begin(); n2e != _sdVec[i]._n2eMap.end(); ++n2e )
4134     {
4135       _LayerEdge* le = n2e->second;
4136       // for ( size_t iN = 1; iN < le->_nodes.size(); ++iN )
4137       //   dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[iN-1]->GetID()
4138       //           << ", " << le->_nodes[iN]->GetID() <<"])");
4139       if ( le ) {
4140         dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[0]->GetID()
4141                 << ", " << le->_nodes.back()->GetID() <<"]) # " << le->_flags );
4142       }
4143     }
4144     dumpFunctionEnd();
4145
4146     dumpFunction( SMESH_Comment("makeNormals") << i );
4147     for ( n2e = _sdVec[i]._n2eMap.begin(); n2e != _sdVec[i]._n2eMap.end(); ++n2e )
4148     {
4149       _LayerEdge* edge = n2e->second;
4150       SMESH_TNodeXYZ nXYZ( edge->_nodes[0] );
4151       nXYZ += edge->_normal * _sdVec[i]._stepSize;
4152       dumpCmd(SMESH_Comment("mesh.AddEdge([ ") << edge->_nodes[0]->GetID()
4153               << ", mesh.AddNode( "<< nXYZ.X()<<","<< nXYZ.Y()<<","<< nXYZ.Z()<<")])");
4154     }
4155     dumpFunctionEnd();
4156
4157     dumpFunction( SMESH_Comment("makeTmpFaces_") << i );
4158     dumpCmd( "faceId1 = mesh.NbElements()" );
4159     TopExp_Explorer fExp( _sdVec[i]._solid, TopAbs_FACE );
4160     for ( ; fExp.More(); fExp.Next() )
4161     {
4162       if ( const SMESHDS_SubMesh* sm = _sdVec[i]._proxyMesh->GetProxySubMesh( fExp.Current() ))
4163       {
4164         if ( sm->NbElements() == 0 ) continue;
4165         SMDS_ElemIteratorPtr fIt = sm->GetElements();
4166         while ( fIt->more())
4167         {
4168           const SMDS_MeshElement* e = fIt->next();
4169           SMESH_Comment cmd("mesh.AddFace([");
4170           for ( int j = 0; j < e->NbCornerNodes(); ++j )
4171             cmd << e->GetNode(j)->GetID() << (j+1 < e->NbCornerNodes() ? ",": "])");
4172           dumpCmd( cmd );
4173         }
4174       }
4175     }
4176     dumpCmd( "faceId2 = mesh.NbElements()" );
4177     dumpCmd( SMESH_Comment( "mesh.MakeGroup( 'tmpFaces_" ) << i << "',"
4178              << "SMESH.FACE, SMESH.FT_RangeOfIds,'=',"
4179              << "'%s-%s' % (faceId1+1, faceId2))");
4180     dumpFunctionEnd();
4181   }
4182 #endif
4183 }
4184
4185 //================================================================================
4186 /*!
4187  * \brief Find maximal _LayerEdge length (layer thickness) limited by geometry
4188  */
4189 //================================================================================
4190
4191 void _ViscousBuilder::computeGeomSize( _SolidData& data )
4192 {
4193   data._geomSize = Precision::Infinite();
4194   double intersecDist;
4195   const SMDS_MeshElement* face;
4196   SMESH_MesherHelper helper( *_mesh );
4197
4198   SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
4199     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
4200                                            data._proxyMesh->GetFaces( data._solid )));
4201
4202   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4203   {
4204     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4205     if ( eos._edges.empty() )
4206       continue;
4207     // get neighbor faces intersection with which should not be considered since
4208     // collisions are avoided by means of smoothing
4209     set< TGeomID > neighborFaces;
4210     if ( eos._hyp.ToSmooth() )
4211     {
4212       SMESH_subMeshIteratorPtr subIt =
4213         eos._subMesh->getDependsOnIterator(/*includeSelf=*/eos.ShapeType() != TopAbs_FACE );
4214       while ( subIt->more() )
4215       {
4216         SMESH_subMesh* sm = subIt->next();
4217         PShapeIteratorPtr fIt = helper.GetAncestors( sm->GetSubShape(), *_mesh, TopAbs_FACE );
4218         while ( const TopoDS_Shape* face = fIt->next() )
4219           neighborFaces.insert( getMeshDS()->ShapeToIndex( *face ));
4220       }
4221     }
4222     // find intersections
4223     double thinkness = eos._hyp.GetTotalThickness();
4224     for ( size_t i = 0; i < eos._edges.size(); ++i )
4225     {
4226       if ( eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
4227       eos._edges[i]->_maxLen = thinkness;
4228       eos._edges[i]->FindIntersection( *searcher, intersecDist, data._epsilon, eos, &face );
4229       if ( intersecDist > 0 && face )
4230       {
4231         data._geomSize = Min( data._geomSize, intersecDist );
4232         if ( !neighborFaces.count( face->getshapeId() ))
4233           eos._edges[i]->_maxLen = Min( thinkness, intersecDist / ( face->GetID() < 0 ? 3. : 2. ));
4234       }
4235     }
4236   }
4237 }
4238
4239 //================================================================================
4240 /*!
4241  * \brief Increase length of _LayerEdge's to reach the required thickness of layers
4242  */
4243 //================================================================================
4244
4245 bool _ViscousBuilder::inflate(_SolidData& data)
4246 {
4247   SMESH_MesherHelper helper( *_mesh );
4248
4249   // Limit inflation step size by geometry size found by itersecting
4250   // normals of _LayerEdge's with mesh faces
4251   if ( data._stepSize > 0.3 * data._geomSize )
4252     limitStepSize( data, 0.3 * data._geomSize );
4253
4254   const double tgtThick = data._maxThickness;
4255   if ( data._stepSize > data._minThickness )
4256     limitStepSize( data, data._minThickness );
4257
4258   if ( data._stepSize < 1. )
4259     data._epsilon = data._stepSize * 1e-7;
4260
4261   debugMsg( "-- geomSize = " << data._geomSize << ", stepSize = " << data._stepSize );
4262
4263   findCollisionEdges( data, helper );
4264
4265   // limit length of _LayerEdge's around MULTI_NORMAL _LayerEdge's
4266   for ( size_t i = 0; i < data._edgesOnShape.size(); ++i )
4267     if ( data._edgesOnShape[i].ShapeType() == TopAbs_VERTEX &&
4268          data._edgesOnShape[i]._edges.size() > 0 &&
4269          data._edgesOnShape[i]._edges[0]->Is( _LayerEdge::MULTI_NORMAL ))
4270       data._edgesOnShape[i]._edges[0]->Block( data );
4271
4272   const double safeFactor = ( 2*data._maxThickness < data._geomSize ) ? 1 : theThickToIntersection;
4273
4274   double avgThick = 0, curThick = 0, distToIntersection = Precision::Infinite();
4275   int nbSteps = 0, nbRepeats = 0;
4276   while ( avgThick < 0.99 )
4277   {
4278     // new target length
4279     double prevThick = curThick;
4280     curThick += data._stepSize;
4281     if ( curThick > tgtThick )
4282     {
4283       curThick = tgtThick + tgtThick*( 1.-avgThick ) * nbRepeats;
4284       nbRepeats++;
4285     }
4286
4287     double stepSize = curThick - prevThick;
4288     updateNormalsOfSmoothed( data, helper, nbSteps, stepSize ); // to ease smoothing
4289
4290     // Elongate _LayerEdge's
4291     dumpFunction(SMESH_Comment("inflate")<<data._index<<"_step"<<nbSteps); // debug
4292     for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4293     {
4294       _EdgesOnShape& eos = data._edgesOnShape[iS];
4295       if ( eos._edges.empty() ) continue;
4296
4297       const double shapeCurThick = Min( curThick, eos._hyp.GetTotalThickness() );
4298       for ( size_t i = 0; i < eos._edges.size(); ++i )
4299       {
4300         eos._edges[i]->SetNewLength( shapeCurThick, eos, helper );
4301       }
4302     }
4303     dumpFunctionEnd();
4304
4305     if ( !updateNormals( data, helper, nbSteps, stepSize )) // to avoid collisions
4306       return false;
4307
4308     // Improve and check quality
4309     if ( !smoothAndCheck( data, nbSteps, distToIntersection ))
4310     {
4311       if ( nbSteps > 0 )
4312       {
4313 #ifdef __NOT_INVALIDATE_BAD_SMOOTH
4314         debugMsg("NOT INVALIDATED STEP!");
4315         return error("Smoothing failed", data._index);
4316 #endif
4317         dumpFunction(SMESH_Comment("invalidate")<<data._index<<"_step"<<nbSteps); // debug
4318         for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4319         {
4320           _EdgesOnShape& eos = data._edgesOnShape[iS];
4321           for ( size_t i = 0; i < eos._edges.size(); ++i )
4322             eos._edges[i]->InvalidateStep( nbSteps+1, eos );
4323         }
4324         dumpFunctionEnd();
4325       }
4326       break; // no more inflating possible
4327     }
4328     nbSteps++;
4329
4330     // Evaluate achieved thickness
4331     avgThick = 0;
4332     int nbActiveEdges = 0;
4333     for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4334     {
4335       _EdgesOnShape& eos = data._edgesOnShape[iS];
4336       if ( eos._edges.empty() ) continue;
4337
4338       const double shapeTgtThick = eos._hyp.GetTotalThickness();
4339       for ( size_t i = 0; i < eos._edges.size(); ++i )
4340       {
4341         avgThick      += Min( 1., eos._edges[i]->_len / shapeTgtThick );
4342         nbActiveEdges += ( ! eos._edges[i]->Is( _LayerEdge::BLOCKED ));
4343       }
4344     }
4345     avgThick /= data._n2eMap.size();
4346     debugMsg( "-- Thickness " << curThick << " ("<< avgThick*100 << "%) reached" );
4347
4348 #ifdef BLOCK_INFLATION
4349     if ( nbActiveEdges == 0 )
4350     {
4351       debugMsg( "-- Stop inflation since all _LayerEdge's BLOCKED " );
4352       break;
4353     }
4354 #else
4355     if ( distToIntersection < tgtThick * avgThick * safeFactor && avgThick < 0.9 )
4356     {
4357       debugMsg( "-- Stop inflation since "
4358                 << " distToIntersection( "<<distToIntersection<<" ) < avgThick( "
4359                 << tgtThick * avgThick << " ) * " << safeFactor );
4360       break;
4361     }
4362 #endif
4363     // new step size
4364     limitStepSize( data, 0.25 * distToIntersection );
4365     if ( data._stepSizeNodes[0] )
4366       data._stepSize = data._stepSizeCoeff *
4367         SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
4368
4369   } // while ( avgThick < 0.99 )
4370
4371   if ( nbSteps == 0 )
4372     return error("failed at the very first inflation step", data._index);
4373
4374   if ( avgThick < 0.99 )
4375   {
4376     if ( !data._proxyMesh->_warning || data._proxyMesh->_warning->IsOK() )
4377     {
4378       data._proxyMesh->_warning.reset
4379         ( new SMESH_ComputeError (COMPERR_WARNING,
4380                                   SMESH_Comment("Thickness ") << tgtThick <<
4381                                   " of viscous layers not reached,"
4382                                   " average reached thickness is " << avgThick*tgtThick));
4383     }
4384   }
4385
4386   // Restore position of src nodes moved by inflation on _noShrinkShapes
4387   dumpFunction(SMESH_Comment("restoNoShrink_So")<<data._index); // debug
4388   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4389   {
4390     _EdgesOnShape& eos = data._edgesOnShape[iS];
4391     if ( !eos._edges.empty() && eos._edges[0]->_nodes.size() == 1 )
4392       for ( size_t i = 0; i < eos._edges.size(); ++i )
4393       {
4394         restoreNoShrink( *eos._edges[ i ] );
4395       }
4396   }
4397   dumpFunctionEnd();
4398
4399   return safeFactor > 0; // == true (avoid warning: unused variable 'safeFactor')
4400 }
4401
4402 //================================================================================
4403 /*!
4404  * \brief Improve quality of layer inner surface and check intersection
4405  */
4406 //================================================================================
4407
4408 bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
4409                                      const int   infStep,
4410                                      double &    distToIntersection)
4411 {
4412   if ( data._nbShapesToSmooth == 0 )
4413     return true; // no shapes needing smoothing
4414
4415   bool moved, improved;
4416   double vol;
4417   vector< _LayerEdge* >    movedEdges, badSmooEdges;
4418   vector< _EdgesOnShape* > eosC1; // C1 continues shapes
4419   vector< bool >           isConcaveFace;
4420
4421   SMESH_MesherHelper helper(*_mesh);
4422   Handle(ShapeAnalysis_Surface) surface;
4423   TopoDS_Face F;
4424
4425   for ( int isFace = 0; isFace < 2; ++isFace ) // smooth on [ EDGEs, FACEs ]
4426   {
4427     const TopAbs_ShapeEnum shapeType = isFace ? TopAbs_FACE : TopAbs_EDGE;
4428
4429     for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4430     {
4431       _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4432       if ( !eos._toSmooth ||
4433            eos.ShapeType() != shapeType ||
4434            eos._edges.empty() )
4435         continue;
4436
4437       // already smoothed?
4438       // bool toSmooth = ( eos._edges[ 0 ]->NbSteps() >= infStep+1 );
4439       // if ( !toSmooth ) continue;
4440
4441       if ( !eos._hyp.ToSmooth() )
4442       {
4443         // smooth disabled by the user; check validy only
4444         if ( !isFace ) continue;
4445         for ( size_t i = 0; i < eos._edges.size(); ++i )
4446         {
4447           _LayerEdge* edge = eos._edges[i];
4448           for ( size_t iF = 0; iF < edge->_simplices.size(); ++iF )
4449             if ( !edge->_simplices[iF].IsForward( edge->_nodes[0], edge->_pos.back(), vol ))
4450             {
4451               debugMsg( "-- Stop inflation. Bad simplex ("
4452                         << " "<< edge->_nodes[0]->GetID()
4453                         << " "<< edge->_nodes.back()->GetID()
4454                         << " "<< edge->_simplices[iF]._nPrev->GetID()
4455                         << " "<< edge->_simplices[iF]._nNext->GetID() << " ) ");
4456               return false;
4457             }
4458         }
4459         continue; // goto the next EDGE or FACE
4460       }
4461
4462       // prepare data
4463       if ( eos.SWOLType() == TopAbs_FACE )
4464       {
4465         if ( !F.IsSame( eos._sWOL )) {
4466           F = TopoDS::Face( eos._sWOL );
4467           helper.SetSubShape( F );
4468           surface = helper.GetSurface( F );
4469         }
4470       }
4471       else
4472       {
4473         F.Nullify(); surface.Nullify();
4474       }
4475       const TGeomID sInd = eos._shapeID;
4476
4477       // perform smoothing
4478
4479       if ( eos.ShapeType() == TopAbs_EDGE )
4480       {
4481         dumpFunction(SMESH_Comment("smooth")<<data._index << "_Ed"<<sInd <<"_InfStep"<<infStep);
4482
4483         if ( !eos._edgeSmoother->Perform( data, surface, F, helper ))
4484         {
4485           // smooth on EDGE's (normally we should not get here)
4486           int step = 0;
4487           do {
4488             moved = false;
4489             for ( size_t i = 0; i < eos._edges.size(); ++i )
4490             {
4491               moved |= eos._edges[i]->SmoothOnEdge( surface, F, helper );
4492             }
4493             dumpCmd( SMESH_Comment("# end step ")<<step);
4494           }
4495           while ( moved && step++ < 5 );
4496         }
4497         dumpFunctionEnd();
4498       }
4499
4500       else // smooth on FACE
4501       {
4502         eosC1.clear();
4503         eosC1.push_back( & eos );
4504         eosC1.insert( eosC1.end(), eos._eosC1.begin(), eos._eosC1.end() );
4505
4506         movedEdges.clear();
4507         isConcaveFace.resize( eosC1.size() );
4508         for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4509         {
4510           isConcaveFace[ iEOS ] = data._concaveFaces.count( eosC1[ iEOS ]->_shapeID  );
4511           vector< _LayerEdge* > & edges = eosC1[ iEOS ]->_edges;
4512           for ( size_t i = 0; i < edges.size(); ++i )
4513             if ( edges[i]->Is( _LayerEdge::MOVED ) ||
4514                  edges[i]->Is( _LayerEdge::NEAR_BOUNDARY ))
4515               movedEdges.push_back( edges[i] );
4516
4517           makeOffsetSurface( *eosC1[ iEOS ], helper );
4518         }
4519
4520         int step = 0, stepLimit = 5, badNb = 0;
4521         while (( ++step <= stepLimit ) || improved )
4522         {
4523           dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
4524                        <<"_InfStep"<<infStep<<"_"<<step); // debug
4525           int oldBadNb = badNb;
4526           badSmooEdges.clear();
4527
4528 #ifdef INCREMENTAL_SMOOTH
4529           bool findBest = false; // ( step == stepLimit );
4530           for ( size_t i = 0; i < movedEdges.size(); ++i )
4531           {
4532             movedEdges[i]->Unset( _LayerEdge::SMOOTHED );
4533             if ( movedEdges[i]->Smooth( step, findBest, movedEdges ) > 0 )
4534               badSmooEdges.push_back( movedEdges[i] );
4535           }
4536 #else
4537           bool findBest = ( step == stepLimit || isConcaveFace[ iEOS ]);
4538           for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4539           {
4540             vector< _LayerEdge* > & edges = eosC1[ iEOS ]->_edges;
4541             for ( size_t i = 0; i < edges.size(); ++i )
4542             {
4543               edges[i]->Unset( _LayerEdge::SMOOTHED );
4544               if ( edges[i]->Smooth( step, findBest, false ) > 0 )
4545                 badSmooEdges.push_back( eos._edges[i] );
4546             }
4547           }
4548 #endif
4549           badNb = badSmooEdges.size();
4550
4551           if ( badNb > 0 )
4552             debugMsg(SMESH_Comment("badNb = ") << badNb );
4553
4554           if ( !badSmooEdges.empty() && step >= stepLimit / 2 )
4555           {
4556             if ( badSmooEdges[0]->Is( _LayerEdge::ON_CONCAVE_FACE ))
4557               stepLimit = 9;
4558
4559             // resolve hard smoothing situation around concave VERTEXes
4560             for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4561             {
4562               vector< _EdgesOnShape* > & eosCoVe = eosC1[ iEOS ]->_eosConcaVer;
4563               for ( size_t i = 0; i < eosCoVe.size(); ++i )
4564                 eosCoVe[i]->_edges[0]->MoveNearConcaVer( eosCoVe[i], eosC1[ iEOS ],
4565                                                          step, badSmooEdges );
4566             }
4567             // look for the best smooth of _LayerEdge's neighboring badSmooEdges
4568             badNb = 0;
4569             for ( size_t i = 0; i < badSmooEdges.size(); ++i )
4570             {
4571               _LayerEdge* ledge = badSmooEdges[i];
4572               for ( size_t iN = 0; iN < ledge->_neibors.size(); ++iN )
4573               {
4574                 ledge->_neibors[iN]->Unset( _LayerEdge::SMOOTHED );
4575                 badNb += ledge->_neibors[iN]->Smooth( step, true, /*findBest=*/true );
4576               }
4577               ledge->Unset( _LayerEdge::SMOOTHED );
4578               badNb += ledge->Smooth( step, true, /*findBest=*/true );
4579             }
4580             debugMsg(SMESH_Comment("badNb = ") << badNb );
4581           }
4582
4583           if ( badNb == oldBadNb  &&
4584                badNb > 0 &&
4585                step < stepLimit ) // smooth w/o chech of validity
4586           {
4587             dumpFunctionEnd();
4588             dumpFunction(SMESH_Comment("smoothWoCheck")<<data._index<<"_Fa"<<sInd
4589                          <<"_InfStep"<<infStep<<"_"<<step); // debug
4590             for ( size_t i = 0; i < movedEdges.size(); ++i )
4591             {
4592               movedEdges[i]->SmoothWoCheck();
4593             }
4594             if ( stepLimit < 9 )
4595               stepLimit++;
4596           }
4597
4598           improved = ( badNb < oldBadNb );
4599
4600           dumpFunctionEnd();
4601
4602           if (( step % 3 == 1 ) || ( badNb > 0 && step >= stepLimit / 2 ))
4603             for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4604             {
4605               putOnOffsetSurface( *eosC1[ iEOS ], infStep, step, /*moveAll=*/step == 1 );
4606             }
4607
4608         } // smoothing steps
4609
4610         // project -- to prevent intersections or fix bad simplices
4611         for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4612         {
4613           if ( ! eosC1[ iEOS ]->_eosConcaVer.empty() || badNb > 0 )
4614             putOnOffsetSurface( *eosC1[ iEOS ], infStep );
4615         }
4616
4617         if ( !badSmooEdges.empty() )
4618         {
4619           badSmooEdges.clear();
4620           for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4621           {
4622             for ( size_t i = 0; i < eosC1[ iEOS ]->_edges.size(); ++i )
4623             {
4624               if ( !eosC1[ iEOS ]->_sWOL.IsNull() ) continue;
4625
4626               _LayerEdge* edge = eosC1[ iEOS ]->_edges[i];
4627               edge->CheckNeiborsOnBoundary( & badSmooEdges );
4628               if ( badNb > 0 )
4629               {
4630                 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
4631                 const gp_XYZ& prevXYZ = edge->PrevCheckPos();
4632                 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
4633                   if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
4634                   {
4635                     debugMsg("Bad simplex ( " << edge->_nodes[0]->GetID()
4636                              << " "<< tgtXYZ._node->GetID()
4637                              << " "<< edge->_simplices[j]._nPrev->GetID()
4638                              << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
4639                     badSmooEdges.push_back( edge );
4640                     break;
4641                   }
4642               }
4643             }
4644           }
4645
4646           // try to fix bad simplices by removing the last inflation step of some _LayerEdge's
4647           badNb = invalidateBadSmooth( data, helper, badSmooEdges, eosC1, infStep );
4648
4649           if ( badNb > 0 )
4650             return false;
4651         }
4652
4653       } // // smooth on FACE's
4654     } // loop on shapes
4655   } // smooth on [ EDGEs, FACEs ]
4656
4657   // Check orientation of simplices of _LayerEdge's on EDGEs and VERTEXes
4658   eosC1.resize(1);
4659   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4660   {
4661     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4662     if ( eos.ShapeType() == TopAbs_FACE ||
4663          eos._edges.empty() ||
4664          !eos._sWOL.IsNull() )
4665       continue;
4666
4667     badSmooEdges.clear();
4668     for ( size_t i = 0; i < eos._edges.size(); ++i )
4669     {
4670       _LayerEdge*      edge = eos._edges[i];
4671       if ( edge->_nodes.size() < 2 ) continue;
4672       SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
4673       const gp_XYZ& prevXYZ = edge->PrevCheckPos();
4674       //const gp_XYZ& prevXYZ = edge->PrevPos();
4675       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
4676         if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
4677         {
4678           debugMsg("Bad simplex on bnd ( " << edge->_nodes[0]->GetID()
4679                    << " "<< tgtXYZ._node->GetID()
4680                    << " "<< edge->_simplices[j]._nPrev->GetID()
4681                    << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
4682           badSmooEdges.push_back( edge );
4683           break;
4684         }
4685     }
4686
4687     // try to fix bad simplices by removing the last inflation step of some _LayerEdge's
4688     eosC1[0] = &eos;
4689     int badNb = invalidateBadSmooth( data, helper, badSmooEdges, eosC1, infStep );
4690     if ( badNb > 0 )
4691       return false;
4692   }
4693
4694
4695   // Check if the last segments of _LayerEdge intersects 2D elements;
4696   // checked elements are either temporary faces or faces on surfaces w/o the layers
4697
4698   SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
4699     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
4700                                            data._proxyMesh->GetFaces( data._solid )) );
4701
4702 #ifdef BLOCK_INFLATION
4703   const bool toBlockInfaltion = true;
4704 #else
4705   const bool toBlockInfaltion = false;
4706 #endif
4707   distToIntersection = Precision::Infinite();
4708   double dist;
4709   const SMDS_MeshElement* intFace = 0;
4710   const SMDS_MeshElement* closestFace = 0;
4711   _LayerEdge* le = 0;
4712   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4713   {
4714     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4715     if ( eos._edges.empty() || !eos._sWOL.IsNull() )
4716       continue;
4717     for ( size_t i = 0; i < eos._edges.size(); ++i )
4718     {
4719       if ( eos._edges[i]->Is( _LayerEdge::INTERSECTED ) ||
4720            eos._edges[i]->Is( _LayerEdge::MULTI_NORMAL ))
4721         continue;
4722       if ( eos._edges[i]->FindIntersection( *searcher, dist, data._epsilon, eos, &intFace ))
4723         return false;
4724       if ( !intFace )
4725       {
4726         SMESH_Comment msg("Invalid? normal at node "); msg << eos._edges[i]->_nodes[0]->GetID();
4727         debugMsg( msg );
4728         continue; 
4729       }
4730
4731       const bool isShorterDist = ( distToIntersection > dist );
4732       if ( toBlockInfaltion || isShorterDist )
4733       {
4734         // ignore intersection of a _LayerEdge based on a _ConvexFace with a face
4735         // lying on this _ConvexFace
4736         if ( _ConvexFace* convFace = data.GetConvexFace( intFace->getshapeId() ))
4737           if ( convFace->_subIdToEOS.count ( eos._shapeID ))
4738             continue;
4739
4740         // ignore intersection of a _LayerEdge based on a FACE with an element on this FACE
4741         // ( avoid limiting the thickness on the case of issue 22576)
4742         if ( intFace->getshapeId() == eos._shapeID  )
4743           continue;
4744
4745         // ignore intersection with intFace of an adjacent FACE
4746         if ( dist > 0 )
4747         {
4748           bool toIgnore = false;
4749           if (  eos._edges[i]->Is( _LayerEdge::TO_SMOOTH ))
4750           {
4751             const TopoDS_Shape& S = getMeshDS()->IndexToShape( intFace->getshapeId() );
4752             if ( !S.IsNull() && S.ShapeType() == TopAbs_FACE )
4753             {
4754               TopExp_Explorer edge( eos._shape, TopAbs_EDGE );
4755               for ( ; !toIgnore && edge.More(); edge.Next() )
4756                 // is adjacent - has a common EDGE
4757                 toIgnore = ( helper.IsSubShape( edge.Current(), S ));
4758
4759               if ( toIgnore ) // check angle between normals
4760               {
4761                 gp_XYZ normal;
4762                 if ( SMESH_MeshAlgos::FaceNormal( intFace, normal, /*normalized=*/true ))
4763                   toIgnore  = ( normal * eos._edges[i]->_normal > -0.5 );
4764               }
4765             }
4766           }
4767           if ( !toIgnore ) // check if the edge is a neighbor of intFace
4768           {
4769             for ( size_t iN = 0; !toIgnore &&  iN < eos._edges[i]->_neibors.size(); ++iN )
4770             {
4771               int nInd = intFace->GetNodeIndex( eos._edges[i]->_neibors[ iN ]->_nodes.back() );
4772               toIgnore = ( nInd >= 0 );
4773             }
4774           }
4775           if ( toIgnore )
4776             continue;
4777         }
4778
4779         // intersection not ignored
4780
4781         if ( toBlockInfaltion &&
4782              dist < ( eos._edges[i]->_len * theThickToIntersection ))
4783         {
4784           eos._edges[i]->Set( _LayerEdge::INTERSECTED ); // not to intersect
4785           eos._edges[i]->Block( data );                  // not to inflate
4786
4787           if ( _EdgesOnShape* eof = data.GetShapeEdges( intFace->getshapeId() ))
4788           {
4789             // block _LayerEdge's, on top of which intFace is
4790             if ( const _TmpMeshFace* f = dynamic_cast< const _TmpMeshFace*>( intFace ))
4791             {
4792               const SMDS_MeshElement* srcFace =
4793                 eof->_subMesh->GetSubMeshDS()->GetElement( f->getIdInShape() );
4794               SMDS_ElemIteratorPtr nIt = srcFace->nodesIterator();
4795               while ( nIt->more() )
4796               {
4797                 const SMDS_MeshNode* srcNode = static_cast<const SMDS_MeshNode*>( nIt->next() );
4798                 TNode2Edge::iterator n2e = data._n2eMap.find( srcNode );
4799                 if ( n2e != data._n2eMap.end() )
4800                   n2e->second->Block( data );
4801               }
4802             }
4803           }
4804         }
4805
4806         if ( isShorterDist )
4807         {
4808           distToIntersection = dist;
4809           le = eos._edges[i];
4810           closestFace = intFace;
4811         }
4812
4813       } // if ( toBlockInfaltion || isShorterDist )
4814     } // loop on eos._edges
4815   } // loop on data._edgesOnShape
4816
4817 #ifdef __myDEBUG
4818   if ( closestFace )
4819   {
4820     SMDS_MeshElement::iterator nIt = closestFace->begin_nodes();
4821     cout << "Shortest distance: _LayerEdge nodes: tgt " << le->_nodes.back()->GetID()
4822          << " src " << le->_nodes[0]->GetID()<< ", intersection with face ("
4823          << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
4824          << ") distance = " << distToIntersection<< endl;
4825   }
4826 #endif
4827
4828   return true;
4829 }
4830
4831 //================================================================================
4832 /*!
4833  * \brief try to fix bad simplices by removing the last inflation step of some _LayerEdge's
4834  *  \param [in,out] badSmooEdges - _LayerEdge's to fix
4835  *  \return int - resulting nb of bad _LayerEdge's
4836  */
4837 //================================================================================
4838
4839 int _ViscousBuilder::invalidateBadSmooth( _SolidData&               data,
4840                                           SMESH_MesherHelper&       helper,
4841                                           vector< _LayerEdge* >&    badSmooEdges,
4842                                           vector< _EdgesOnShape* >& eosC1,
4843                                           const int                 infStep )
4844 {
4845   if ( badSmooEdges.empty() || infStep == 0 ) return 0;
4846
4847   dumpFunction(SMESH_Comment("invalidateBadSmooth")<<"_S"<<eosC1[0]->_shapeID<<"_InfStep"<<infStep);
4848
4849   data.UnmarkEdges();
4850
4851   double vol;
4852   vector< _LayerEdge* > simplexNeibors(2);
4853   for ( size_t i = 0; i < badSmooEdges.size(); ++i )
4854   {
4855     _LayerEdge* edge = badSmooEdges[i];
4856     if ( edge->Is( _LayerEdge::MARKED ))
4857       continue;
4858
4859     // look for _LayerEdge's of bad _simplices
4860     SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
4861     const gp_XYZ* prevXYZ = & edge->PrevCheckPos();
4862     for ( size_t j = 0; j < edge->_simplices.size(); ++j )
4863     {
4864       if ( edge->_simplices[j].IsForward( prevXYZ, &tgtXYZ, vol ))
4865         continue;
4866       simplexNeibors.clear();
4867       for ( size_t iN = 0; iN < edge->_neibors.size() && simplexNeibors.size() < 2; ++iN )
4868         if ( edge->_simplices[j].Includes( edge->_neibors[iN]->_nodes.back() ))
4869           simplexNeibors.push_back( edge->_neibors[iN] );
4870       if ( simplexNeibors.size() < 2 ) continue;
4871
4872       // select a _LayerEdge to invalidate
4873       _LayerEdge* invaE = 0;
4874       double maxVol = 0;
4875       simplexNeibors.push_back( edge );
4876       for ( int iE = 0; iE < 3; ++iE )
4877       {
4878         _LayerEdge* e = simplexNeibors[ iE ];
4879         if ( e->Is( _LayerEdge::MARKED ) ||
4880              //e->Is( _LayerEdge::BLOCKED ) ||
4881              e->NbSteps() < 2 )
4882           continue;
4883         _EdgesOnShape* eos = data.GetShapeEdges( e );
4884         double len = e->_len;
4885         e->InvalidateStep( e->NbSteps(), *eos, /*restoreLength=*/true );
4886         if ( e == edge ) {
4887           tgtXYZ.Set( edge->_nodes.back() );
4888           prevXYZ = & edge->PrevCheckPos();
4889         }
4890         if ( edge->_simplices[j].IsForward( & edge->PrevCheckPos(), &tgtXYZ, vol ) &&
4891              vol > maxVol )
4892         {
4893           invaE = e;
4894           maxVol = vol;
4895         }
4896         e->SetNewLength( len, *eos, helper );
4897         if ( e == edge ) {
4898           tgtXYZ.Set( edge->_nodes.back() );
4899           prevXYZ = & edge->PrevCheckPos();
4900         }
4901       }
4902
4903       // invalidate
4904       if ( invaE )
4905       {
4906         if ( invaE == edge ) {
4907           tgtXYZ.Set( edge->_nodes.back() );
4908           prevXYZ = & edge->PrevCheckPos();
4909         }
4910         _EdgesOnShape* eos = data.GetShapeEdges( invaE );
4911         invaE->InvalidateStep( invaE->NbSteps(), *eos, /*updLen=*/true );
4912         invaE->Block( data );
4913         invaE->Set( _LayerEdge::MARKED );
4914         if ( eos->ShapeType() == TopAbs_VERTEX )
4915         {
4916           // re-smooth on analytical EDGEs
4917           PShapeIteratorPtr eIt = helper.GetAncestors( eos->_shape, *_mesh, TopAbs_EDGE );
4918           while ( const TopoDS_Shape* e = eIt->next() )
4919             if ( _EdgesOnShape* eoe = data.GetShapeEdges( *e ))
4920               if ( eoe->_edgeSmoother && eoe->_edgeSmoother->isAnalytic() )
4921               {
4922                 TopoDS_Face F; Handle(ShapeAnalysis_Surface) surface;
4923                 if ( eoe->SWOLType() == TopAbs_FACE ) {
4924                   F       = TopoDS::Face( eoe->_sWOL );
4925                   surface = helper.GetSurface( F );
4926                 }
4927                 eoe->_edgeSmoother->Perform( data, surface, F, helper );
4928               }
4929         }
4930       }
4931     } // loop on edge->_simplices
4932   } // loop on badSmooEdges
4933
4934
4935   // check result of invalidation
4936
4937   int badNb = 0;
4938   for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4939   {
4940     for ( size_t i = 0; i < eosC1[ iEOS ]->_edges.size(); ++i )
4941     {
4942       if ( !eosC1[ iEOS ]->_sWOL.IsNull() ) continue;
4943       _LayerEdge*      edge = eosC1[ iEOS ]->_edges[i];
4944       SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
4945       const gp_XYZ& prevXYZ = edge->PrevCheckPos();
4946       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
4947         if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
4948         {
4949           ++badNb;
4950           debugMsg("Bad simplex remains ( " << edge->_nodes[0]->GetID()
4951                    << " "<< tgtXYZ._node->GetID()
4952                    << " "<< edge->_simplices[j]._nPrev->GetID()
4953                    << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
4954         }
4955     }
4956   }
4957   dumpFunctionEnd();
4958
4959   return badNb;
4960 }
4961
4962 //================================================================================
4963 /*!
4964  * \brief Create an offset surface
4965  */
4966 //================================================================================
4967
4968 void _ViscousBuilder::makeOffsetSurface( _EdgesOnShape& eos, SMESH_MesherHelper& helper )
4969 {
4970   if ( eos._offsetSurf.IsNull() ||
4971        eos._edgeForOffset == 0 ||
4972        eos._edgeForOffset->Is( _LayerEdge::BLOCKED ))
4973     return;
4974
4975   Handle(ShapeAnalysis_Surface) baseSurface = helper.GetSurface( TopoDS::Face( eos._shape ));
4976
4977   // find offset
4978   gp_Pnt   tgtP = SMESH_TNodeXYZ( eos._edgeForOffset->_nodes.back() );
4979   gp_Pnt2d   uv = baseSurface->ValueOfUV( tgtP, Precision::Confusion() );
4980   double offset = baseSurface->Gap();
4981
4982   eos._offsetSurf.Nullify();
4983
4984   try
4985   {
4986     BRepOffsetAPI_MakeOffsetShape offsetMaker( eos._shape, -offset, Precision::Confusion() );
4987     if ( !offsetMaker.IsDone() ) return;
4988
4989     TopExp_Explorer fExp( offsetMaker.Shape(), TopAbs_FACE );
4990     if ( !fExp.More() ) return;
4991
4992     TopoDS_Face F = TopoDS::Face( fExp.Current() );
4993     Handle(Geom_Surface) surf = BRep_Tool::Surface( F );
4994     if ( surf.IsNull() ) return;
4995
4996     eos._offsetSurf = new ShapeAnalysis_Surface( surf );
4997   }
4998   catch ( Standard_Failure )
4999   {
5000   }
5001 }
5002
5003 //================================================================================
5004 /*!
5005  * \brief Put nodes of a curved FACE to its offset surface
5006  */
5007 //================================================================================
5008
5009 void _ViscousBuilder::putOnOffsetSurface( _EdgesOnShape& eos,
5010                                           int            infStep,
5011                                           int            smooStep,
5012                                           bool           moveAll )
5013 {
5014   if ( eos._offsetSurf.IsNull() ||
5015        eos.ShapeType() != TopAbs_FACE ||
5016        eos._edgeForOffset == 0 ||
5017        eos._edgeForOffset->Is( _LayerEdge::BLOCKED ))
5018     return;
5019
5020   double preci = BRep_Tool::Tolerance( TopoDS::Face( eos._shape )), vol;
5021   for ( size_t i = 0; i < eos._edges.size(); ++i )
5022   {
5023     _LayerEdge* edge = eos._edges[i];
5024     edge->Unset( _LayerEdge::MARKED );
5025     if ( edge->Is( _LayerEdge::BLOCKED ) || !edge->_curvature )
5026       continue;
5027     if ( !moveAll && !edge->Is( _LayerEdge::MOVED ))
5028         continue;
5029
5030     int nbBlockedAround = 0;
5031     for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
5032       nbBlockedAround += edge->_neibors[iN]->Is( _LayerEdge::BLOCKED );
5033     if ( nbBlockedAround > 1 )
5034       continue;
5035
5036     gp_Pnt tgtP = SMESH_TNodeXYZ( edge->_nodes.back() );
5037     gp_Pnt2d uv = eos._offsetSurf->NextValueOfUV( edge->_curvature->_uv, tgtP, preci );
5038     if ( eos._offsetSurf->Gap() > edge->_len ) continue; // NextValueOfUV() bug 
5039     edge->_curvature->_uv = uv;
5040     if ( eos._offsetSurf->Gap() < 10 * preci ) continue; // same pos
5041
5042     gp_XYZ  newP = eos._offsetSurf->Value( uv ).XYZ();
5043     gp_XYZ prevP = edge->PrevCheckPos();
5044     bool      ok = true;
5045     if ( !moveAll )
5046       for ( size_t iS = 0; iS < edge->_simplices.size() && ok; ++iS )
5047       {
5048         ok = edge->_simplices[iS].IsForward( &prevP, &newP, vol );
5049       }
5050     if ( ok )
5051     {
5052       SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( edge->_nodes.back() );
5053       n->setXYZ( newP.X(), newP.Y(), newP.Z());
5054       edge->_pos.back() = newP;
5055
5056       edge->Set( _LayerEdge::MARKED );
5057     }
5058   }
5059
5060 #ifdef _DEBUG_
5061   // dumpMove() for debug
5062   size_t i = 0;
5063   for ( ; i < eos._edges.size(); ++i )
5064     if ( eos._edges[i]->Is( _LayerEdge::MARKED ))
5065       break;
5066   if ( i < eos._edges.size() )
5067   {
5068     dumpFunction(SMESH_Comment("putOnOffsetSurface_F") << eos._shapeID
5069                  << "_InfStep" << infStep << "_" << smooStep );
5070     for ( ; i < eos._edges.size(); ++i )
5071     {
5072       if ( eos._edges[i]->Is( _LayerEdge::MARKED ))
5073         dumpMove( eos._edges[i]->_nodes.back() );
5074     }
5075     dumpFunctionEnd();
5076   }
5077 #endif
5078 }
5079
5080 //================================================================================
5081 /*!
5082  * \brief Return a curve of the EDGE to be used for smoothing and arrange
5083  *        _LayerEdge's to be in a consequent order
5084  */
5085 //================================================================================
5086
5087 Handle(Geom_Curve) _Smoother1D::CurveForSmooth( const TopoDS_Edge&  E,
5088                                                 _EdgesOnShape&      eos,
5089                                                 SMESH_MesherHelper& helper)
5090 {
5091   SMESHDS_SubMesh* smDS = eos._subMesh->GetSubMeshDS();
5092
5093   TopLoc_Location loc; double f,l;
5094
5095   Handle(Geom_Line)   line;
5096   Handle(Geom_Circle) circle;
5097   bool isLine, isCirc;
5098   if ( eos._sWOL.IsNull() ) /////////////////////////////////////////// 3D case
5099   {
5100     // check if the EDGE is a line
5101     Handle(Geom_Curve) curve = BRep_Tool::Curve( E, f, l);
5102     if ( curve->IsKind( STANDARD_TYPE( Geom_TrimmedCurve )))
5103       curve = Handle(Geom_TrimmedCurve)::DownCast( curve )->BasisCurve();
5104
5105     line   = Handle(Geom_Line)::DownCast( curve );
5106     circle = Handle(Geom_Circle)::DownCast( curve );
5107     isLine = (!line.IsNull());
5108     isCirc = (!circle.IsNull());
5109
5110     if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
5111     {
5112       isLine = SMESH_Algo::IsStraight( E );
5113
5114       if ( isLine )
5115         line = new Geom_Line( gp::OX() ); // only type does matter
5116     }
5117     if ( !isLine && !isCirc && eos._edges.size() > 2) // Check if the EDGE is close to a circle
5118     {
5119       // TODO
5120     }
5121   }
5122   else //////////////////////////////////////////////////////////////////////// 2D case
5123   {
5124     if ( !eos._isRegularSWOL ) // 23190
5125       return NULL;
5126
5127     const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
5128
5129     // check if the EDGE is a line
5130     Handle(Geom2d_Curve) curve = BRep_Tool::CurveOnSurface( E, F, f, l );
5131     if ( curve->IsKind( STANDARD_TYPE( Geom2d_TrimmedCurve )))
5132       curve = Handle(Geom2d_TrimmedCurve)::DownCast( curve )->BasisCurve();
5133
5134     Handle(Geom2d_Line)   line2d   = Handle(Geom2d_Line)::DownCast( curve );
5135     Handle(Geom2d_Circle) circle2d = Handle(Geom2d_Circle)::DownCast( curve );
5136     isLine = (!line2d.IsNull());
5137     isCirc = (!circle2d.IsNull());
5138
5139     if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
5140     {
5141       Bnd_B2d bndBox;
5142       SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
5143       while ( nIt->more() )
5144         bndBox.Add( helper.GetNodeUV( F, nIt->next() ));
5145       gp_XY size = bndBox.CornerMax() - bndBox.CornerMin();
5146
5147       const double lineTol = 1e-2 * sqrt( bndBox.SquareExtent() );
5148       for ( int i = 0; i < 2 && !isLine; ++i )
5149         isLine = ( size.Coord( i+1 ) <= lineTol );
5150     }
5151     if ( !isLine && !isCirc && eos._edges.size() > 2 ) // Check if the EDGE is close to a circle
5152     {
5153       // TODO
5154     }
5155     if ( isLine )
5156     {
5157       line = new Geom_Line( gp::OX() ); // only type does matter
5158     }
5159     else if ( isCirc )
5160     {
5161       gp_Pnt2d p = circle2d->Location();
5162       gp_Ax2 ax( gp_Pnt( p.X(), p.Y(), 0), gp::DX());
5163       circle = new Geom_Circle( ax, 1.); // only center position does matter
5164     }
5165   }
5166
5167   if ( isLine )
5168     return line;
5169   if ( isCirc )
5170     return circle;
5171
5172   return Handle(Geom_Curve)();
5173 }
5174
5175 //================================================================================
5176 /*!
5177  * \brief smooth _LayerEdge's on a staight EDGE or circular EDGE
5178  */
5179 //================================================================================
5180
5181 bool _Smoother1D::smoothAnalyticEdge( _SolidData&                    data,
5182                                       Handle(ShapeAnalysis_Surface)& surface,
5183                                       const TopoDS_Face&             F,
5184                                       SMESH_MesherHelper&            helper)
5185 {
5186   if ( !isAnalytic() ) return false;
5187
5188   const size_t iFrom = 0, iTo = _eos._edges.size();
5189
5190   if ( _anaCurve->IsKind( STANDARD_TYPE( Geom_Line )))
5191   {
5192     if ( F.IsNull() ) // 3D
5193     {
5194       SMESH_TNodeXYZ p0   ( _eos._edges[iFrom]->_2neibors->tgtNode(0) );
5195       SMESH_TNodeXYZ p1   ( _eos._edges[iTo-1]->_2neibors->tgtNode(1) );
5196       SMESH_TNodeXYZ pSrc0( _eos._edges[iFrom]->_2neibors->srcNode(0) );
5197       SMESH_TNodeXYZ pSrc1( _eos._edges[iTo-1]->_2neibors->srcNode(1) );
5198       gp_XYZ newPos;
5199       for ( size_t i = iFrom; i < iTo; ++i )
5200       {
5201         if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5202
5203         _LayerEdge*       edge = _eos._edges[i];
5204         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edge->_nodes.back() );
5205         newPos = p0 * ( 1. - _leParams[i] ) + p1 * _leParams[i];
5206
5207         if ( _eos._edges[i]->Is( _LayerEdge::NORMAL_UPDATED ))
5208         {
5209           gp_XYZ curPos  = SMESH_TNodeXYZ ( tgtNode );
5210           gp_XYZ lineDir = pSrc1 - pSrc0;
5211           double   shift = ( lineDir * ( newPos - pSrc0 ) -
5212                              lineDir * ( curPos - pSrc0 ));
5213           newPos = curPos + lineDir * shift / lineDir.SquareModulus();
5214         }
5215         edge->_pos.back() = newPos;
5216         tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5217         dumpMove( tgtNode );
5218       }
5219     }
5220     else
5221     {
5222       _LayerEdge* e0 = getLEdgeOnV( 0 );
5223       _LayerEdge* e1 = getLEdgeOnV( 1 );
5224       gp_XY uv0 = e0->LastUV( F, *data.GetShapeEdges( e0 ));
5225       gp_XY uv1 = e1->LastUV( F, *data.GetShapeEdges( e1 ));
5226       if ( e0->_nodes.back() == e1->_nodes.back() ) // closed edge
5227       {
5228         int iPeriodic = helper.GetPeriodicIndex();
5229         if ( iPeriodic == 1 || iPeriodic == 2 )
5230         {
5231           uv1.SetCoord( iPeriodic, helper.GetOtherParam( uv1.Coord( iPeriodic )));
5232           if ( uv0.Coord( iPeriodic ) > uv1.Coord( iPeriodic ))
5233             std::swap( uv0, uv1 );
5234         }
5235       }
5236       const gp_XY rangeUV = uv1 - uv0;
5237       for ( size_t i = iFrom; i < iTo; ++i )
5238       {
5239         if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5240         gp_XY newUV = uv0 + _leParams[i] * rangeUV;
5241         _eos._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
5242
5243         gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
5244         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5245         tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5246         dumpMove( tgtNode );
5247
5248         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
5249         pos->SetUParameter( newUV.X() );
5250         pos->SetVParameter( newUV.Y() );
5251       }
5252     }
5253     return true;
5254   }
5255
5256   if ( _anaCurve->IsKind( STANDARD_TYPE( Geom_Circle )))
5257   {
5258     Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast( _anaCurve );
5259     gp_Pnt center3D = circle->Location();
5260
5261     if ( F.IsNull() ) // 3D
5262     {
5263       if ( getLEdgeOnV( 0 )->_nodes.back() == getLEdgeOnV( 1 )->_nodes.back() )
5264         return true; // closed EDGE - nothing to do
5265
5266       // circle is a real curve of EDGE
5267       gp_Circ circ = circle->Circ();
5268
5269       // new center is shifted along its axis
5270       const gp_Dir& axis = circ.Axis().Direction();
5271       _LayerEdge*     e0 = getLEdgeOnV(0);
5272       _LayerEdge*     e1 = getLEdgeOnV(1);
5273       SMESH_TNodeXYZ  p0 = e0->_nodes.back();
5274       SMESH_TNodeXYZ  p1 = e1->_nodes.back();
5275       double      shift1 = axis.XYZ() * ( p0 - center3D.XYZ() );
5276       double      shift2 = axis.XYZ() * ( p1 - center3D.XYZ() );
5277       gp_Pnt   newCenter = center3D.XYZ() + axis.XYZ() * 0.5 * ( shift1 + shift2 );
5278
5279       double newRadius = 0.5 * ( newCenter.Distance( p0 ) + newCenter.Distance( p1 ));
5280
5281       gp_Ax2  newAxis( newCenter, axis, gp_Vec( newCenter, p0 ));
5282       gp_Circ newCirc( newAxis, newRadius );
5283       gp_Vec  vecC1  ( newCenter, p1 );
5284
5285       double uLast = newAxis.XDirection().AngleWithRef( vecC1, newAxis.Direction() ); // -PI - +PI
5286       if ( uLast < 0 )
5287         uLast += 2 * M_PI;
5288       
5289       for ( size_t i = iFrom; i < iTo; ++i )
5290       {
5291         if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5292         double u = uLast * _leParams[i];
5293         gp_Pnt p = ElCLib::Value( u, newCirc );
5294         _eos._edges[i]->_pos.back() = p.XYZ();
5295
5296         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5297         tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
5298         dumpMove( tgtNode );
5299       }
5300       return true;
5301     }
5302     else // 2D
5303     {
5304       const gp_XY center( center3D.X(), center3D.Y() );
5305
5306       _LayerEdge* e0 = getLEdgeOnV(0);
5307       _LayerEdge* eM = _eos._edges[ 0 ];
5308       _LayerEdge* e1 = getLEdgeOnV(1);
5309       gp_XY      uv0 = e0->LastUV( F, *data.GetShapeEdges( e0 ) );
5310       gp_XY      uvM = eM->LastUV( F, *data.GetShapeEdges( eM ) );
5311       gp_XY      uv1 = e1->LastUV( F, *data.GetShapeEdges( e1 ) );
5312       gp_Vec2d vec0( center, uv0 );
5313       gp_Vec2d vecM( center, uvM );
5314       gp_Vec2d vec1( center, uv1 );
5315       double uLast = vec0.Angle( vec1 ); // -PI - +PI
5316       double uMidl = vec0.Angle( vecM );
5317       if ( uLast * uMidl <= 0. )
5318         uLast += ( uMidl > 0 ? +2. : -2. ) * M_PI;
5319       const double radius = 0.5 * ( vec0.Magnitude() + vec1.Magnitude() );
5320
5321       gp_Ax2d   axis( center, vec0 );
5322       gp_Circ2d circ( axis, radius );
5323       for ( size_t i = iFrom; i < iTo; ++i )
5324       {
5325         if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5326         double    newU = uLast * _leParams[i];
5327         gp_Pnt2d newUV = ElCLib::Value( newU, circ );
5328         _eos._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
5329
5330         gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
5331         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5332         tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5333         dumpMove( tgtNode );
5334
5335         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
5336         pos->SetUParameter( newUV.X() );
5337         pos->SetVParameter( newUV.Y() );
5338       }
5339     }
5340     return true;
5341   }
5342
5343   return false;
5344 }
5345
5346 //================================================================================
5347 /*!
5348  * \brief smooth _LayerEdge's on a an EDGE
5349  */
5350 //================================================================================
5351
5352 bool _Smoother1D::smoothComplexEdge( _SolidData&                    data,
5353                                      Handle(ShapeAnalysis_Surface)& surface,
5354                                      const TopoDS_Face&             F,
5355                                      SMESH_MesherHelper&            helper)
5356 {
5357   if ( _offPoints.empty() )
5358     return false;
5359
5360   // move _offPoints to a new position
5361
5362   _LayerEdge* e[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
5363   if ( e[0]->Is( _LayerEdge::NORMAL_UPDATED )) setNormalOnV( 0, helper );
5364   if ( e[1]->Is( _LayerEdge::NORMAL_UPDATED )) setNormalOnV( 1, helper );
5365   _leOnV[0]._len = e[0]->_len;
5366   _leOnV[1]._len = e[1]->_len;
5367   for ( size_t i = 0; i < _offPoints.size(); i++ )
5368   {
5369     _LayerEdge*  e0 = _offPoints[i]._2edges._edges[0];
5370     _LayerEdge*  e1 = _offPoints[i]._2edges._edges[1];
5371     const double w0 = _offPoints[i]._2edges._wgt[0];
5372     const double w1 = _offPoints[i]._2edges._wgt[1];
5373     gp_XYZ  avgNorm = ( e0->_normal    * w0 + e1->_normal    * w1 ).Normalized();
5374     double  avgLen  = ( e0->_len       * w0 + e1->_len       * w1 );
5375     double  avgFact = ( e0->_lenFactor * w0 + e1->_lenFactor * w1 );
5376
5377     _offPoints[i]._xyz += avgNorm * ( avgLen - _offPoints[i]._len ) * avgFact;
5378     _offPoints[i]._len  = avgLen;
5379   }
5380
5381   double fTol;
5382   if ( !surface.IsNull() ) // project _offPoints to the FACE
5383   {
5384     fTol = 100 * BRep_Tool::Tolerance( F );
5385     //const double segLen = _offPoints[0].Distance( _offPoints[1] );
5386
5387     gp_Pnt2d uv = surface->ValueOfUV( _offPoints[0]._xyz, fTol );
5388     //if ( surface->Gap() < 0.5 * segLen )
5389       _offPoints[0]._xyz = surface->Value( uv ).XYZ();
5390
5391     for ( size_t i = 1; i < _offPoints.size(); ++i )
5392     {
5393       uv = surface->NextValueOfUV( uv, _offPoints[i]._xyz, fTol );
5394       //if ( surface->Gap() < 0.5 * segLen )
5395         _offPoints[i]._xyz = surface->Value( uv ).XYZ();
5396     }
5397   }
5398
5399   // project tgt nodes of extreme _LayerEdge's to the offset segments
5400
5401   gp_Pnt pExtreme[2], pProj[2];
5402   for ( int is2nd = 0; is2nd < 2; ++is2nd )
5403   {
5404     pExtreme[ is2nd ] = SMESH_TNodeXYZ( e[is2nd]->_nodes.back() );
5405     int  i = _iSeg[ is2nd ];
5406     int di = is2nd ? -1 : +1;
5407     bool projected = false;
5408     double uOnSeg, uOnSegDiff, uOnSegBestDiff = Precision::Infinite();
5409     do {
5410       gp_Vec v0p( _offPoints[i]._xyz, pExtreme[ is2nd ]    );
5411       gp_Vec v01( _offPoints[i]._xyz, _offPoints[i+1]._xyz );
5412       uOnSeg     = ( v0p * v01 ) / v01.SquareMagnitude();
5413       uOnSegDiff = Abs( uOnSeg - 0.5 );
5414       projected  = ( uOnSegDiff <= 0.5 );
5415       if ( uOnSegDiff < uOnSegBestDiff )
5416       {
5417         _iSeg[ is2nd ] = i;
5418         pProj[ is2nd ] = _offPoints[i]._xyz + ( v01 * uOnSeg ).XYZ();
5419         uOnSegBestDiff = uOnSegDiff;
5420       }
5421       i += di;
5422     }
5423     while ( !projected &&
5424             i >= 0 && i+1 < (int)_offPoints.size() );
5425
5426     if ( !projected )
5427     {
5428       if (( is2nd && _iSeg[1] != _offPoints.size()-2 ) || ( !is2nd && _iSeg[0] != 0 ))
5429       {
5430         _iSeg[0] = 0;
5431         _iSeg[1] = _offPoints.size()-2;
5432         debugMsg( "smoothComplexEdge() failed to project nodes of extreme _LayerEdge's" );
5433         return false;
5434       }
5435     }
5436   }
5437   if ( _iSeg[0] > _iSeg[1] )
5438   {
5439     debugMsg( "smoothComplexEdge() incorrectly projected nodes of extreme _LayerEdge's" );
5440     return false;
5441   }
5442
5443   // compute normalized length of the offset segments located between the projections
5444
5445   size_t iSeg = 0, nbSeg = _iSeg[1] - _iSeg[0] + 1;
5446   vector< double > len( nbSeg + 1 );
5447   len[ iSeg++ ] = 0;
5448   len[ iSeg++ ] = pProj[ 0 ].Distance( _offPoints[ _iSeg[0]+1 ]._xyz );
5449   for ( size_t i = _iSeg[0]+1; i <= _iSeg[1]; ++i, ++iSeg )
5450   {
5451     len[ iSeg ] = len[ iSeg-1 ] + _offPoints[i].Distance( _offPoints[i+1] );
5452   }
5453   len[ nbSeg ] -= pProj[ 1 ].Distance( _offPoints[ _iSeg[1]+1 ]._xyz );
5454
5455   double d0 = pProj[0].Distance( pExtreme[0]);
5456   double d1 = pProj[1].Distance( pExtreme[1]);
5457   double fullLen = len.back() - d0 - d1;
5458   for ( iSeg = 0; iSeg < len.size(); ++iSeg )
5459     len[iSeg] = ( len[iSeg] - d0 ) / fullLen;
5460
5461   // temporary replace extreme _offPoints by pExtreme
5462   gp_XYZ op[2] = { _offPoints[ _iSeg[0]   ]._xyz,
5463                    _offPoints[ _iSeg[1]+1 ]._xyz };
5464   _offPoints[ _iSeg[0]   ]._xyz = pExtreme[0].XYZ();
5465   _offPoints[ _iSeg[1]+ 1]._xyz = pExtreme[1].XYZ();
5466
5467   // distribute tgt nodes of _LayerEdge's between the projections
5468
5469   iSeg = 0;
5470   for ( size_t i = 0; i < _eos._edges.size(); ++i )
5471   {
5472     if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5473     while ( iSeg+2 < len.size() && _leParams[i] > len[ iSeg+1 ] )
5474       iSeg++;
5475     double r = ( _leParams[i] - len[ iSeg ]) / ( len[ iSeg+1 ] - len[ iSeg ]);
5476     gp_XYZ p = ( _offPoints[ iSeg + _iSeg[0]     ]._xyz * ( 1 - r ) +
5477                  _offPoints[ iSeg + _iSeg[0] + 1 ]._xyz * r );
5478
5479     if ( surface.IsNull() )
5480     {
5481       _eos._edges[i]->_pos.back() = p;
5482     }
5483     else // project a new node position to a FACE
5484     {
5485       gp_Pnt2d uv ( _eos._edges[i]->_pos.back().X(), _eos._edges[i]->_pos.back().Y() );
5486       gp_Pnt2d uv2( surface->NextValueOfUV( uv, p, fTol ));
5487
5488       p = surface->Value( uv2 ).XYZ();
5489       _eos._edges[i]->_pos.back().SetCoord( uv2.X(), uv2.Y(), 0 );
5490     }
5491     SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5492     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
5493     dumpMove( tgtNode );
5494   }
5495
5496   _offPoints[ _iSeg[0]   ]._xyz = op[0];
5497   _offPoints[ _iSeg[1]+1 ]._xyz = op[1];
5498
5499   return true;
5500 }
5501
5502 //================================================================================
5503 /*!
5504  * \brief Prepare for smoothing
5505  */
5506 //================================================================================
5507
5508 void _Smoother1D::prepare(_SolidData& data)
5509 {
5510   // sort _LayerEdge's by position on the EDGE
5511   const TopoDS_Edge& E = TopoDS::Edge( _eos._shape );
5512   data.SortOnEdge( E, _eos._edges );
5513
5514   // compute normalized param of _eos._edges on EDGE
5515   _leParams.resize( _eos._edges.size() + 1 );
5516   {
5517     double curLen, prevLen = _leParams[0] = 1.0;
5518     gp_Pnt pPrev = SMESH_TNodeXYZ( getLEdgeOnV( 0 )->_nodes[0] );
5519     _leParams[0] = 0;
5520     for ( size_t i = 0; i < _eos._edges.size(); ++i )
5521     {
5522       gp_Pnt p = SMESH_TNodeXYZ( _eos._edges[i]->_nodes[0] );
5523       //curLen = prevLen * _eos._edges[i]->_2neibors->_wgt[1] / _eos._edges[i]->_2neibors->_wgt[0];
5524       curLen = p.Distance( pPrev );
5525       _leParams[i+1] = _leParams[i] + curLen;
5526       prevLen = curLen;
5527       pPrev = p;
5528     }
5529     double fullLen = _leParams.back() + pPrev.Distance( SMESH_TNodeXYZ( getLEdgeOnV(1)->_nodes[0]));
5530     for ( size_t i = 0; i < _leParams.size(); ++i )
5531       _leParams[i] = _leParams[i+1] / fullLen;
5532   }
5533
5534   if ( isAnalytic() )
5535     return;
5536
5537   // divide E to have offset segments with low deflection
5538   BRepAdaptor_Curve c3dAdaptor( E );
5539   const double curDeflect = 0.1; //0.3; // 0.01; // Curvature deflection
5540   const double angDeflect = 0.1; //0.2; // 0.09; // Angular deflection
5541   GCPnts_TangentialDeflection discret(c3dAdaptor, angDeflect, curDeflect);
5542   if ( discret.NbPoints() <= 2 )
5543   {
5544     _anaCurve = new Geom_Line( gp::OX() ); // only type does matter
5545     return;
5546   }
5547
5548   const double edgeLen = SMESH_Algo::EdgeLength( E );
5549   const double u0      = c3dAdaptor.FirstParameter();
5550   _offPoints.resize( discret.NbPoints() );
5551   for ( size_t i = 0; i < _offPoints.size(); i++ )
5552   {
5553     _offPoints[i]._xyz = discret.Value( i+1 ).XYZ();
5554     // use OffPnt::_len to  TEMPORARY  store normalized param of an offset point
5555     double u = discret.Parameter( i+1 );
5556     _offPoints[i]._len = GCPnts_AbscissaPoint::Length( c3dAdaptor, u0, u ) / edgeLen;
5557   }
5558
5559   _LayerEdge* leOnV[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
5560
5561   // set _2edges
5562   _offPoints    [0]._2edges.set( &_leOnV[0], &_leOnV[0], 0.5, 0.5 );
5563   _offPoints.back()._2edges.set( &_leOnV[1], &_leOnV[1], 0.5, 0.5 );
5564   _2NearEdges tmp2edges;
5565   tmp2edges._edges[1] = _eos._edges[0];
5566   _leOnV[0]._2neibors = & tmp2edges;
5567   _leOnV[0]._nodes    = leOnV[0]->_nodes;
5568   _leOnV[1]._nodes    = leOnV[1]->_nodes;
5569   _LayerEdge* eNext, *ePrev = & _leOnV[0];
5570   for ( size_t iLE = 0, i = 1; i < _offPoints.size()-1; i++ )
5571   {
5572     // find _LayerEdge's located before and after an offset point
5573     // (_eos._edges[ iLE ] is next after ePrev)
5574     while ( iLE < _eos._edges.size() && _offPoints[i]._len > _leParams[ iLE ] )
5575       ePrev = _eos._edges[ iLE++ ];
5576     eNext = ePrev->_2neibors->_edges[1];
5577
5578     gp_Pnt p0 = SMESH_TNodeXYZ( ePrev->_nodes[0] );
5579     gp_Pnt p1 = SMESH_TNodeXYZ( eNext->_nodes[0] );
5580     double  r = p0.Distance( _offPoints[i]._xyz ) / p0.Distance( p1 );
5581     _offPoints[i]._2edges.set( ePrev, eNext, 1-r, r );
5582   }
5583
5584   int iLBO = _offPoints.size() - 2; // last but one
5585   _offPoints[iLBO]._2edges._edges[1] = & _leOnV[1];
5586
5587   // {
5588   //   TopoDS_Face face[2]; // FACEs sharing the EDGE
5589   //   PShapeIteratorPtr fIt = helper.GetAncestors( _eos._shape, *helper.GetMesh(), TopAbs_FACE );
5590   //   while ( const TopoDS_Shape* F = fIt->next() )
5591   //   {
5592   //     TGeomID fID = helper.GetMeshDS()->ShapeToIndex( *F );
5593   //     if ( ! data._ignoreFaceIds.count( fID ))
5594   //       face[ !face[0].IsNull() ] = *F;
5595   //   }
5596   //   if ( face[0].IsNull() ) return;
5597   //   if ( face[1].IsNull() ) face[1] = face[0];
5598   // }
5599
5600
5601   // set _normal of _leOnV[0] and _leOnV[1] to be normal to the EDGE
5602
5603   setNormalOnV( 0, data.GetHelper() );
5604   setNormalOnV( 1, data.GetHelper() );
5605   _leOnV[ 0 ]._len = 0;
5606   _leOnV[ 1 ]._len = 0;
5607   _leOnV[ 0 ]._lenFactor = _offPoints[1   ]._2edges._edges[1]->_lenFactor;
5608   _leOnV[ 1 ]._lenFactor = _offPoints[iLBO]._2edges._edges[0]->_lenFactor;
5609
5610   _iSeg[0] = 0;
5611   _iSeg[1] = _offPoints.size()-2;
5612
5613   // initialize OffPnt::_len
5614   for ( size_t i = 0; i < _offPoints.size(); ++i )
5615     _offPoints[i]._len = 0;
5616
5617   if ( _eos._edges[0]->NbSteps() > 1 ) // already inflated several times, init _xyz
5618   {
5619     _leOnV[0]._len = leOnV[0]->_len;
5620     _leOnV[1]._len = leOnV[1]->_len;
5621     for ( size_t i = 0; i < _offPoints.size(); i++ )
5622     {
5623       _LayerEdge*  e0 = _offPoints[i]._2edges._edges[0];
5624       _LayerEdge*  e1 = _offPoints[i]._2edges._edges[1];
5625       const double w0 = _offPoints[i]._2edges._wgt[0];
5626       const double w1 = _offPoints[i]._2edges._wgt[1];
5627       double  avgLen  = ( e0->_len * w0 + e1->_len * w1 );
5628       gp_XYZ  avgXYZ  = ( SMESH_TNodeXYZ( e0->_nodes.back() ) * w0 +
5629                           SMESH_TNodeXYZ( e1->_nodes.back() ) * w1 );
5630       _offPoints[i]._xyz = avgXYZ;
5631       _offPoints[i]._len = avgLen;
5632     }
5633   }
5634 }
5635
5636 //================================================================================
5637 /*!
5638  * \brief set _normal of _leOnV[is2nd] to be normal to the EDGE
5639  */
5640 //================================================================================
5641
5642 void _Smoother1D::setNormalOnV( const bool          is2nd,
5643                                 SMESH_MesherHelper& helper)
5644 {
5645   _LayerEdge*    leOnV = getLEdgeOnV( is2nd );
5646   const TopoDS_Edge& E = TopoDS::Edge( _eos._shape );
5647   TopoDS_Shape       V = helper.GetSubShapeByNode( leOnV->_nodes[0], helper.GetMeshDS() );
5648   gp_XYZ          eDir = getEdgeDir( E, TopoDS::Vertex( V ));
5649   gp_XYZ         cross = leOnV->_normal ^ eDir;
5650   gp_XYZ          norm = eDir ^ cross;
5651   double          size = norm.Modulus();
5652
5653   _leOnV[ is2nd ]._normal = norm / size;
5654 }
5655
5656 //================================================================================
5657 /*!
5658  * \brief Sort _LayerEdge's by a parameter on a given EDGE
5659  */
5660 //================================================================================
5661
5662 void _SolidData::SortOnEdge( const TopoDS_Edge&     E,
5663                              vector< _LayerEdge* >& edges)
5664 {
5665   map< double, _LayerEdge* > u2edge;
5666   for ( size_t i = 0; i < edges.size(); ++i )
5667     u2edge.insert( u2edge.end(),
5668                    make_pair( _helper->GetNodeU( E, edges[i]->_nodes[0] ), edges[i] ));
5669
5670   ASSERT( u2edge.size() == edges.size() );
5671   map< double, _LayerEdge* >::iterator u2e = u2edge.begin();
5672   for ( size_t i = 0; i < edges.size(); ++i, ++u2e )
5673     edges[i] = u2e->second;
5674
5675   Sort2NeiborsOnEdge( edges );
5676 }
5677
5678 //================================================================================
5679 /*!
5680  * \brief Set _2neibors according to the order of _LayerEdge on EDGE
5681  */
5682 //================================================================================
5683
5684 void _SolidData::Sort2NeiborsOnEdge( vector< _LayerEdge* >& edges )
5685 {
5686   if ( edges.size() < 2 || !edges[0]->_2neibors ) return;
5687
5688   for ( size_t i = 0; i < edges.size()-1; ++i )
5689     if ( edges[i]->_2neibors->tgtNode(1) != edges[i+1]->_nodes.back() )
5690       edges[i]->_2neibors->reverse();
5691
5692   const size_t iLast = edges.size() - 1;
5693   if ( edges.size() > 1 &&
5694        edges[iLast]->_2neibors->tgtNode(0) != edges[iLast-1]->_nodes.back() )
5695     edges[iLast]->_2neibors->reverse();
5696 }
5697
5698 //================================================================================
5699 /*!
5700  * \brief Return _EdgesOnShape* corresponding to the shape
5701  */
5702 //================================================================================
5703
5704 _EdgesOnShape* _SolidData::GetShapeEdges(const TGeomID shapeID )
5705 {
5706   if ( shapeID < (int)_edgesOnShape.size() &&
5707        _edgesOnShape[ shapeID ]._shapeID == shapeID )
5708     return _edgesOnShape[ shapeID ]._subMesh ? & _edgesOnShape[ shapeID ] : 0;
5709
5710   for ( size_t i = 0; i < _edgesOnShape.size(); ++i )
5711     if ( _edgesOnShape[i]._shapeID == shapeID )
5712       return _edgesOnShape[i]._subMesh ? & _edgesOnShape[i] : 0;
5713
5714   return 0;
5715 }
5716
5717 //================================================================================
5718 /*!
5719  * \brief Return _EdgesOnShape* corresponding to the shape
5720  */
5721 //================================================================================
5722
5723 _EdgesOnShape* _SolidData::GetShapeEdges(const TopoDS_Shape& shape )
5724 {
5725   SMESHDS_Mesh* meshDS = _proxyMesh->GetMesh()->GetMeshDS();
5726   return GetShapeEdges( meshDS->ShapeToIndex( shape ));
5727 }
5728
5729 //================================================================================
5730 /*!
5731  * \brief Prepare data of the _LayerEdge for smoothing on FACE
5732  */
5733 //================================================================================
5734
5735 void _SolidData::PrepareEdgesToSmoothOnFace( _EdgesOnShape* eos, bool substituteSrcNodes )
5736 {
5737   SMESH_MesherHelper helper( *_proxyMesh->GetMesh() );
5738
5739   set< TGeomID > vertices;
5740   TopoDS_Face F;
5741   if ( eos->ShapeType() == TopAbs_FACE )
5742   {
5743     // check FACE concavity and get concave VERTEXes
5744     F = TopoDS::Face( eos->_shape );
5745     if ( isConcave( F, helper, &vertices ))
5746       _concaveFaces.insert( eos->_shapeID );
5747
5748     // set eos._eosConcaVer
5749     eos->_eosConcaVer.clear();
5750     eos->_eosConcaVer.reserve( vertices.size() );
5751     for ( set< TGeomID >::iterator v = vertices.begin(); v != vertices.end(); ++v )
5752     {
5753       _EdgesOnShape* eov = GetShapeEdges( *v );
5754       if ( eov && eov->_edges.size() == 1 )
5755       {
5756         eos->_eosConcaVer.push_back( eov );
5757         for ( size_t i = 0; i < eov->_edges[0]->_neibors.size(); ++i )
5758           eov->_edges[0]->_neibors[i]->Set( _LayerEdge::DIFFICULT );
5759       }
5760     }
5761
5762     // SetSmooLen() to _LayerEdge's on FACE
5763     for ( size_t i = 0; i < eos->_edges.size(); ++i )
5764     {
5765       eos->_edges[i]->SetSmooLen( Precision::Infinite() );
5766     }
5767     SMESH_subMeshIteratorPtr smIt = eos->_subMesh->getDependsOnIterator(/*includeSelf=*/false);
5768     while ( smIt->more() ) // loop on sub-shapes of the FACE
5769     {
5770       _EdgesOnShape* eoe = GetShapeEdges( smIt->next()->GetId() );
5771       if ( !eoe ) continue;
5772
5773       vector<_LayerEdge*>& eE = eoe->_edges;
5774       for ( size_t iE = 0; iE < eE.size(); ++iE ) // loop on _LayerEdge's on EDGE or VERTEX
5775       {
5776         if ( eE[iE]->_cosin <= theMinSmoothCosin )
5777           continue;
5778
5779         SMDS_ElemIteratorPtr segIt = eE[iE]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
5780         while ( segIt->more() )
5781         {
5782           const SMDS_MeshElement* seg = segIt->next();
5783           if ( !eos->_subMesh->DependsOn( seg->getshapeId() ))
5784             continue;
5785           if ( seg->GetNode(0) != eE[iE]->_nodes[0] )
5786             continue; // not to check a seg twice
5787           for ( size_t iN = 0; iN < eE[iE]->_neibors.size(); ++iN )
5788           {
5789             _LayerEdge* eN = eE[iE]->_neibors[iN];
5790             if ( eN->_nodes[0]->getshapeId() != eos->_shapeID )
5791               continue;
5792             double dist    = SMESH_MeshAlgos::GetDistance( seg, SMESH_TNodeXYZ( eN->_nodes[0] ));
5793             double smooLen = getSmoothingThickness( eE[iE]->_cosin, dist );
5794             eN->SetSmooLen( Min( smooLen, eN->GetSmooLen() ));
5795             eN->Set( _LayerEdge::NEAR_BOUNDARY );
5796           }
5797         }
5798       }
5799     }
5800   } // if ( eos->ShapeType() == TopAbs_FACE )
5801
5802   for ( size_t i = 0; i < eos->_edges.size(); ++i )
5803   {
5804     eos->_edges[i]->_smooFunction = 0;
5805     eos->_edges[i]->Set( _LayerEdge::TO_SMOOTH );
5806   }
5807   bool isCurved = false;
5808   for ( size_t i = 0; i < eos->_edges.size(); ++i )
5809   {
5810     _LayerEdge* edge = eos->_edges[i];
5811
5812     // get simplices sorted
5813     _Simplex::SortSimplices( edge->_simplices );
5814
5815     // smoothing function
5816     edge->ChooseSmooFunction( vertices, _n2eMap );
5817
5818     // set _curvature
5819     double avgNormProj = 0, avgLen = 0;
5820     for ( size_t iS = 0; iS < edge->_simplices.size(); ++iS )
5821     {
5822       _Simplex& s = edge->_simplices[iS];
5823
5824       gp_XYZ  vec = edge->_pos.back() - SMESH_TNodeXYZ( s._nPrev );
5825       avgNormProj += edge->_normal * vec;
5826       avgLen      += vec.Modulus();
5827       if ( substituteSrcNodes )
5828       {
5829         s._nNext = _n2eMap[ s._nNext ]->_nodes.back();
5830         s._nPrev = _n2eMap[ s._nPrev ]->_nodes.back();
5831       }
5832     }
5833     avgNormProj /= edge->_simplices.size();
5834     avgLen      /= edge->_simplices.size();
5835     if (( edge->_curvature = _Curvature::New( avgNormProj, avgLen )))
5836     {
5837       isCurved = true;
5838       SMDS_FacePosition* fPos = dynamic_cast<SMDS_FacePosition*>( edge->_nodes[0]->GetPosition() );
5839       if ( !fPos )
5840         for ( size_t iS = 0; iS < edge->_simplices.size()  &&  !fPos; ++iS )
5841           fPos = dynamic_cast<SMDS_FacePosition*>( edge->_simplices[iS]._nPrev->GetPosition() );
5842       if ( fPos )
5843         edge->_curvature->_uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
5844     }
5845   }
5846
5847   // prepare for putOnOffsetSurface()
5848   if (( eos->ShapeType() == TopAbs_FACE ) &&
5849       ( isCurved || !eos->_eosConcaVer.empty() ))
5850   {
5851     eos->_offsetSurf = helper.GetSurface( TopoDS::Face( eos->_shape ));
5852     eos->_edgeForOffset = 0;
5853
5854     double maxCosin = -1;
5855     for ( TopExp_Explorer eExp( eos->_shape, TopAbs_EDGE ); eExp.More(); eExp.Next() )
5856     {
5857       _EdgesOnShape* eoe = GetShapeEdges( eExp.Current() );
5858       if ( !eoe || eoe->_edges.empty() ) continue;
5859
5860       vector<_LayerEdge*>& eE = eoe->_edges;
5861       _LayerEdge* e = eE[ eE.size() / 2 ];
5862       if ( e->_cosin > maxCosin )
5863       {
5864         eos->_edgeForOffset = e;
5865         maxCosin = e->_cosin;
5866       }
5867     }
5868   }
5869 }
5870
5871 //================================================================================
5872 /*!
5873  * \brief Add faces for smoothing
5874  */
5875 //================================================================================
5876
5877 void _SolidData::AddShapesToSmooth( const set< _EdgesOnShape* >& eosToSmooth,
5878                                     const set< _EdgesOnShape* >* edgesNoAnaSmooth )
5879 {
5880   set< _EdgesOnShape * >::const_iterator eos = eosToSmooth.begin();
5881   for ( ; eos != eosToSmooth.end(); ++eos )
5882   {
5883     if ( !*eos || (*eos)->_toSmooth ) continue;
5884
5885     (*eos)->_toSmooth = true;
5886
5887     if ( (*eos)->ShapeType() == TopAbs_FACE )
5888     {
5889       PrepareEdgesToSmoothOnFace( *eos, /*substituteSrcNodes=*/false );
5890       (*eos)->_toSmooth = true;
5891     }
5892   }
5893
5894   // avoid _Smoother1D::smoothAnalyticEdge() of edgesNoAnaSmooth
5895   if ( edgesNoAnaSmooth )
5896     for ( eos = edgesNoAnaSmooth->begin(); eos != edgesNoAnaSmooth->end(); ++eos )
5897     {
5898       if ( (*eos)->_edgeSmoother )
5899         (*eos)->_edgeSmoother->_anaCurve.Nullify();
5900     }
5901 }
5902
5903 //================================================================================
5904 /*!
5905  * \brief Fill data._collisionEdges
5906  */
5907 //================================================================================
5908
5909 void _ViscousBuilder::findCollisionEdges( _SolidData& data, SMESH_MesherHelper& helper )
5910 {
5911   data._collisionEdges.clear();
5912
5913   // set the full thickness of the layers to LEs
5914   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
5915   {
5916     _EdgesOnShape& eos = data._edgesOnShape[iS];
5917     if ( eos._edges.empty() ) continue;
5918     if ( eos.ShapeType() != TopAbs_EDGE && eos.ShapeType() != TopAbs_VERTEX ) continue;
5919
5920     for ( size_t i = 0; i < eos._edges.size(); ++i )
5921     {
5922       if ( eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5923       double maxLen = eos._edges[i]->_maxLen;
5924       eos._edges[i]->_maxLen = Precision::Infinite(); // avoid blocking
5925       eos._edges[i]->SetNewLength( 1.5 * maxLen, eos, helper );
5926       eos._edges[i]->_maxLen = maxLen;
5927     }
5928   }
5929
5930   // make temporary quadrangles got by extrusion of
5931   // mesh edges along _LayerEdge._normal's
5932
5933   vector< const SMDS_MeshElement* > tmpFaces;
5934
5935   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
5936   {
5937     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
5938     if ( eos.ShapeType() != TopAbs_EDGE )
5939       continue;
5940     if ( eos._edges.empty() )
5941     {
5942       _LayerEdge* edge[2] = { 0, 0 }; // LE of 2 VERTEX'es
5943       SMESH_subMeshIteratorPtr smIt = eos._subMesh->getDependsOnIterator(/*includeSelf=*/false);
5944       while ( smIt->more() )
5945         if ( _EdgesOnShape* eov = data.GetShapeEdges( smIt->next()->GetId() ))
5946           if ( eov->_edges.size() == 1 )
5947             edge[ bool( edge[0]) ] = eov->_edges[0];
5948
5949       if ( edge[1] )
5950       {
5951         _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge[0], edge[1], --_tmpFaceID );
5952         tmpFaces.push_back( f );
5953       }
5954     }
5955     for ( size_t i = 0; i < eos._edges.size(); ++i )
5956     {
5957       _LayerEdge* edge = eos._edges[i];
5958       for ( int j = 0; j < 2; ++j ) // loop on _2NearEdges
5959       {
5960         const SMDS_MeshNode* src2 = edge->_2neibors->srcNode(j);
5961         if ( src2->GetPosition()->GetDim() > 0 &&
5962              src2->GetID() < edge->_nodes[0]->GetID() )
5963           continue; // avoid using same segment twice
5964
5965         // a _LayerEdge containg tgt2
5966         _LayerEdge* neiborEdge = edge->_2neibors->_edges[j];
5967
5968         _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge, neiborEdge, --_tmpFaceID );
5969         tmpFaces.push_back( f );
5970       }
5971     }
5972   }
5973
5974   // Find _LayerEdge's intersecting tmpFaces.
5975
5976   SMDS_ElemIteratorPtr fIt( new SMDS_ElementVectorIterator( tmpFaces.begin(),
5977                                                             tmpFaces.end()));
5978   SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
5979     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(), fIt ));
5980
5981   double dist1, dist2, segLen, eps;
5982   _CollisionEdges collEdges;
5983   vector< const SMDS_MeshElement* > suspectFaces;
5984   const double angle30 = Cos( 30. * M_PI / 180. );
5985
5986   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
5987   {
5988     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
5989     if ( eos.ShapeType() == TopAbs_FACE || !eos._sWOL.IsNull() )
5990       continue;
5991     // find sub-shapes whose VL can influence VL on eos
5992     set< TGeomID > neighborShapes;
5993     PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
5994     while ( const TopoDS_Shape* face = fIt->next() )
5995     {
5996       TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
5997       if ( _EdgesOnShape* eof = data.GetShapeEdges( faceID ))
5998       {
5999         SMESH_subMeshIteratorPtr subIt = eof->_subMesh->getDependsOnIterator(/*includeSelf=*/false);
6000         while ( subIt->more() )
6001           neighborShapes.insert( subIt->next()->GetId() );
6002       }
6003     }
6004     if ( eos.ShapeType() == TopAbs_VERTEX )
6005     {
6006       PShapeIteratorPtr eIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_EDGE );
6007       while ( const TopoDS_Shape* edge = eIt->next() )
6008         neighborShapes.erase( getMeshDS()->ShapeToIndex( *edge ));
6009     }
6010     // find intersecting _LayerEdge's
6011     for ( size_t i = 0; i < eos._edges.size(); ++i )
6012     {
6013       _LayerEdge*   edge = eos._edges[i];
6014       gp_Ax1 lastSegment = edge->LastSegment( segLen, eos );
6015       eps     = 0.5 * edge->_len;
6016       segLen *= 1.2;
6017
6018       gp_Vec eSegDir0, eSegDir1;
6019       if ( edge->IsOnEdge() )
6020       {
6021         SMESH_TNodeXYZ eP( edge->_nodes[0] );
6022         eSegDir0 = SMESH_TNodeXYZ( edge->_2neibors->srcNode(0) ) - eP;
6023         eSegDir1 = SMESH_TNodeXYZ( edge->_2neibors->srcNode(1) ) - eP;
6024       }
6025       suspectFaces.clear();
6026       searcher->GetElementsInSphere( SMESH_TNodeXYZ( edge->_nodes.back()), edge->_len,
6027                                      SMDSAbs_Face, suspectFaces );
6028       collEdges._intEdges.clear();
6029       for ( size_t j = 0 ; j < suspectFaces.size(); ++j )
6030       {
6031         const _TmpMeshFaceOnEdge* f = (const _TmpMeshFaceOnEdge*) suspectFaces[j];
6032         if ( f->_le1 == edge || f->_le2 == edge ) continue;
6033         if ( !neighborShapes.count( f->_le1->_nodes[0]->getshapeId() )) continue;
6034         if ( !neighborShapes.count( f->_le2->_nodes[0]->getshapeId() )) continue;
6035         if ( edge->IsOnEdge() ) {
6036           if ( edge->_2neibors->include( f->_le1 ) ||
6037                edge->_2neibors->include( f->_le2 )) continue;
6038         }
6039         else {
6040           if (( f->_le1->IsOnEdge() && f->_le1->_2neibors->include( edge )) ||
6041               ( f->_le2->IsOnEdge() && f->_le2->_2neibors->include( edge )))  continue;
6042         }
6043         dist1 = dist2 = Precision::Infinite();
6044         if ( !edge->SegTriaInter( lastSegment, f->_nn[0], f->_nn[1], f->_nn[2], dist1, eps ))
6045           dist1 = Precision::Infinite();
6046         if ( !edge->SegTriaInter( lastSegment, f->_nn[3], f->_nn[2], f->_nn[0], dist2, eps ))
6047           dist2 = Precision::Infinite();
6048         if (( dist1 > segLen ) && ( dist2 > segLen ))
6049           continue;
6050
6051         if ( edge->IsOnEdge() )
6052         {
6053           // skip perpendicular EDGEs
6054           gp_Vec fSegDir  = SMESH_TNodeXYZ( f->_nn[0] ) - SMESH_TNodeXYZ( f->_nn[3] );
6055           bool isParallel = ( isLessAngle( eSegDir0, fSegDir, angle30 ) ||
6056                               isLessAngle( eSegDir1, fSegDir, angle30 ) ||
6057                               isLessAngle( eSegDir0, fSegDir.Reversed(), angle30 ) ||
6058                               isLessAngle( eSegDir1, fSegDir.Reversed(), angle30 ));
6059           if ( !isParallel )
6060             continue;
6061         }
6062
6063         // either limit inflation of edges or remember them for updating _normal
6064         // double dot = edge->_normal * f->GetDir();
6065         // if ( dot > 0.1 )
6066         {
6067           collEdges._intEdges.push_back( f->_le1 );
6068           collEdges._intEdges.push_back( f->_le2 );
6069         }
6070         // else
6071         // {
6072         //   double shortLen = 0.75 * ( Min( dist1, dist2 ) / edge->_lenFactor );
6073         //   edge->_maxLen = Min( shortLen, edge->_maxLen );
6074         // }
6075       }
6076
6077       if ( !collEdges._intEdges.empty() )
6078       {
6079         collEdges._edge = edge;
6080         data._collisionEdges.push_back( collEdges );
6081       }
6082     }
6083   }
6084
6085   for ( size_t i = 0 ; i < tmpFaces.size(); ++i )
6086     delete tmpFaces[i];
6087
6088   // restore the zero thickness
6089   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6090   {
6091     _EdgesOnShape& eos = data._edgesOnShape[iS];
6092     if ( eos._edges.empty() ) continue;
6093     if ( eos.ShapeType() != TopAbs_EDGE && eos.ShapeType() != TopAbs_VERTEX ) continue;
6094
6095     for ( size_t i = 0; i < eos._edges.size(); ++i )
6096     {
6097       eos._edges[i]->InvalidateStep( 1, eos );
6098       eos._edges[i]->_len = 0;
6099     }
6100   }
6101 }
6102
6103 //================================================================================
6104 /*!
6105  * \brief Modify normals of _LayerEdge's on EDGE's to avoid intersection with
6106  * _LayerEdge's on neighbor EDGE's
6107  */
6108 //================================================================================
6109
6110 bool _ViscousBuilder::updateNormals( _SolidData&         data,
6111                                      SMESH_MesherHelper& helper,
6112                                      int                 stepNb,
6113                                      double              stepSize)
6114 {
6115   updateNormalsOfC1Vertices( data );
6116
6117   if ( stepNb > 0 && !updateNormalsOfConvexFaces( data, helper, stepNb ))
6118     return false;
6119
6120   // map to store new _normal and _cosin for each intersected edge
6121   map< _LayerEdge*, _LayerEdge, _LayerEdgeCmp >           edge2newEdge;
6122   map< _LayerEdge*, _LayerEdge, _LayerEdgeCmp >::iterator e2neIt;
6123   _LayerEdge zeroEdge;
6124   zeroEdge._normal.SetCoord( 0,0,0 );
6125   zeroEdge._maxLen = Precision::Infinite();
6126   zeroEdge._nodes.resize(1); // to init _TmpMeshFaceOnEdge
6127
6128   set< _EdgesOnShape* > shapesToSmooth, edgesNoAnaSmooth;
6129
6130   double segLen, dist1, dist2;
6131   vector< pair< _LayerEdge*, double > > intEdgesDist;
6132   _TmpMeshFaceOnEdge quad( &zeroEdge, &zeroEdge, 0 );
6133
6134   for ( int iter = 0; iter < 5; ++iter )
6135   {
6136     edge2newEdge.clear();
6137
6138     for ( size_t iE = 0; iE < data._collisionEdges.size(); ++iE )
6139     {
6140       _CollisionEdges& ce = data._collisionEdges[iE];
6141       _LayerEdge*   edge1 = ce._edge;
6142       if ( !edge1 || edge1->Is( _LayerEdge::BLOCKED )) continue;
6143       _EdgesOnShape* eos1 = data.GetShapeEdges( edge1 );
6144       if ( !eos1 ) continue;
6145
6146       // detect intersections
6147       gp_Ax1 lastSeg = edge1->LastSegment( segLen, *eos1 );
6148       double testLen = 1.5 * edge1->_maxLen; //2 + edge1->_len * edge1->_lenFactor;
6149       double     eps = 0.5 * edge1->_len;
6150       intEdgesDist.clear();
6151       double minIntDist = Precision::Infinite();
6152       for ( size_t i = 0; i < ce._intEdges.size(); i += 2 )
6153       {
6154         if ( ce._intEdges[i  ]->Is( _LayerEdge::BLOCKED ) ||
6155              ce._intEdges[i+1]->Is( _LayerEdge::BLOCKED ))
6156           continue;
6157         double dot  = edge1->_normal * quad.GetDir( ce._intEdges[i], ce._intEdges[i+1] );
6158         double fact = ( 1.1 + dot * dot );
6159         SMESH_TNodeXYZ pSrc0( ce.nSrc(i) ), pSrc1( ce.nSrc(i+1) );
6160         SMESH_TNodeXYZ pTgt0( ce.nTgt(i) ), pTgt1( ce.nTgt(i+1) );
6161         gp_XYZ pLast0 = pSrc0 + ( pTgt0 - pSrc0 ) * fact;
6162         gp_XYZ pLast1 = pSrc1 + ( pTgt1 - pSrc1 ) * fact;
6163         dist1 = dist2 = Precision::Infinite();
6164         if ( !edge1->SegTriaInter( lastSeg, pSrc0, pTgt0, pSrc1, dist1, eps ) &&
6165              !edge1->SegTriaInter( lastSeg, pSrc1, pTgt1, pTgt0, dist2, eps ))
6166           continue;
6167         if (( dist1 > testLen || dist1 < 0 ) &&
6168             ( dist2 > testLen || dist2 < 0 ))
6169           continue;
6170
6171         // choose a closest edge
6172         gp_Pnt intP( lastSeg.Location().XYZ() +
6173                      lastSeg.Direction().XYZ() * ( Min( dist1, dist2 ) + segLen ));
6174         double d1 = intP.SquareDistance( pSrc0 );
6175         double d2 = intP.SquareDistance( pSrc1 );
6176         int iClose = i + ( d2 < d1 );
6177         _LayerEdge* edge2 = ce._intEdges[iClose];
6178         edge2->Unset( _LayerEdge::MARKED );
6179
6180         // choose a closest edge among neighbors
6181         gp_Pnt srcP( SMESH_TNodeXYZ( edge1->_nodes[0] ));
6182         d1 = srcP.SquareDistance( SMESH_TNodeXYZ( edge2->_nodes[0] ));
6183         for ( size_t j = 0; j < intEdgesDist.size(); ++j )
6184         {
6185           _LayerEdge * edgeJ = intEdgesDist[j].first;
6186           if ( edge2->IsNeiborOnEdge( edgeJ ))
6187           {
6188             d2 = srcP.SquareDistance( SMESH_TNodeXYZ( edgeJ->_nodes[0] ));
6189             ( d1 < d2 ? edgeJ : edge2 )->Set( _LayerEdge::MARKED );
6190           }
6191         }
6192         intEdgesDist.push_back( make_pair( edge2, Min( dist1, dist2 )));
6193         // if ( Abs( d2 - d1 ) / Max( d2, d1 ) < 0.5 )
6194         // {
6195         //   iClose = i + !( d2 < d1 );
6196         //   intEdges.push_back( ce._intEdges[iClose] );
6197         //   ce._intEdges[iClose]->Unset( _LayerEdge::MARKED );
6198         // }
6199         minIntDist = Min( edge1->_len * edge1->_lenFactor - segLen + dist1, minIntDist );
6200         minIntDist = Min( edge1->_len * edge1->_lenFactor - segLen + dist2, minIntDist );
6201       }
6202
6203       //ce._edge = 0;
6204
6205       // compute new _normals
6206       for ( size_t i = 0; i < intEdgesDist.size(); ++i )
6207       {
6208         _LayerEdge* edge2    = intEdgesDist[i].first;
6209         double       distWgt = edge1->_len / intEdgesDist[i].second;
6210         if ( edge2->Is( _LayerEdge::MARKED )) continue;
6211         edge2->Set( _LayerEdge::MARKED );
6212
6213         // get a new normal
6214         gp_XYZ dir1 = edge1->_normal, dir2 = edge2->_normal;
6215
6216         double cos1 = Abs( edge1->_cosin ), cos2 = Abs( edge2->_cosin );
6217         double wgt1 = ( cos1 + 0.001 ) / ( cos1 + cos2 + 0.002 );
6218         double wgt2 = ( cos2 + 0.001 ) / ( cos1 + cos2 + 0.002 );
6219         // double cos1 = Abs( edge1->_cosin ),        cos2 = Abs( edge2->_cosin );
6220         // double sgn1 = 0.1 * ( 1 + edge1->_cosin ), sgn2 = 0.1 * ( 1 + edge2->_cosin );
6221         // double wgt1 = ( cos1 + sgn1 ) / ( cos1 + cos2 + sgn1 + sgn2 );
6222         // double wgt2 = ( cos2 + sgn2 ) / ( cos1 + cos2 + sgn1 + sgn2 );
6223         gp_XYZ newNormal = wgt1 * dir1 + wgt2 * dir2;
6224         newNormal.Normalize();
6225
6226         // get new cosin
6227         double newCos;
6228         double sgn1 = edge1->_cosin / cos1, sgn2 = edge2->_cosin / cos2;
6229         if ( cos1 < theMinSmoothCosin )
6230         {
6231           newCos = cos2 * sgn1;
6232         }
6233         else if ( cos2 > theMinSmoothCosin ) // both cos1 and cos2 > theMinSmoothCosin
6234         {
6235           newCos = ( wgt1 * cos1 + wgt2 * cos2 ) * edge1->_cosin / cos1;
6236         }
6237         else
6238         {
6239           newCos = edge1->_cosin;
6240         }
6241
6242         e2neIt = edge2newEdge.insert( make_pair( edge1, zeroEdge )).first;
6243         e2neIt->second._normal += distWgt * newNormal;
6244         e2neIt->second._cosin   = newCos;
6245         e2neIt->second._maxLen  = 0.7 * minIntDist / edge1->_lenFactor;
6246         if ( iter > 0 && sgn1 * sgn2 < 0 && edge1->_cosin < 0 )
6247           e2neIt->second._normal += dir2;
6248         e2neIt = edge2newEdge.insert( make_pair( edge2, zeroEdge )).first;
6249         e2neIt->second._normal += distWgt * newNormal;
6250         e2neIt->second._cosin   = edge2->_cosin;
6251         if ( iter > 0 && sgn1 * sgn2 < 0 && edge2->_cosin < 0 )
6252           e2neIt->second._normal += dir1;
6253       }
6254     }
6255
6256     if ( edge2newEdge.empty() )
6257       break; //return true;
6258
6259     dumpFunction(SMESH_Comment("updateNormals")<< data._index << "_" << stepNb << "_it" << iter);
6260
6261     // Update data of edges depending on a new _normal
6262
6263     data.UnmarkEdges();
6264     for ( e2neIt = edge2newEdge.begin(); e2neIt != edge2newEdge.end(); ++e2neIt )
6265     {
6266       _LayerEdge*    edge = e2neIt->first;
6267       _LayerEdge& newEdge = e2neIt->second;
6268       _EdgesOnShape*  eos = data.GetShapeEdges( edge );
6269
6270       // Check if a new _normal is OK:
6271       newEdge._normal.Normalize();
6272       if ( !isNewNormalOk( data, *edge, newEdge._normal ))
6273       {
6274         if ( newEdge._maxLen < edge->_len && iter > 0 ) // limit _maxLen
6275         {
6276           edge->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true  );
6277           edge->_maxLen = newEdge._maxLen;
6278           edge->SetNewLength( newEdge._maxLen, *eos, helper );
6279         }
6280         continue; // the new _normal is bad
6281       }
6282       // the new _normal is OK
6283
6284       // find shapes that need smoothing due to change of _normal
6285       if ( edge->_cosin   < theMinSmoothCosin &&
6286            newEdge._cosin > theMinSmoothCosin )
6287       {
6288         if ( eos->_sWOL.IsNull() )
6289         {
6290           SMDS_ElemIteratorPtr fIt = edge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
6291           while ( fIt->more() )
6292             shapesToSmooth.insert( data.GetShapeEdges( fIt->next()->getshapeId() ));
6293         }
6294         else // edge inflates along a FACE
6295         {
6296           TopoDS_Shape V = helper.GetSubShapeByNode( edge->_nodes[0], getMeshDS() );
6297           PShapeIteratorPtr eIt = helper.GetAncestors( V, *_mesh, TopAbs_EDGE );
6298           while ( const TopoDS_Shape* E = eIt->next() )
6299           {
6300             if ( !helper.IsSubShape( *E, /*FACE=*/eos->_sWOL ))
6301               continue;
6302             gp_Vec edgeDir = getEdgeDir( TopoDS::Edge( *E ), TopoDS::Vertex( V ));
6303             double   angle = edgeDir.Angle( newEdge._normal ); // [0,PI]
6304             if ( angle < M_PI / 2 )
6305               shapesToSmooth.insert( data.GetShapeEdges( *E ));
6306           }
6307         }
6308       }
6309
6310       double len = edge->_len;
6311       edge->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true  );
6312       edge->SetNormal( newEdge._normal );
6313       edge->SetCosin( newEdge._cosin );
6314       edge->SetNewLength( len, *eos, helper );
6315       edge->Set( _LayerEdge::MARKED );
6316       edge->Set( _LayerEdge::NORMAL_UPDATED );
6317       edgesNoAnaSmooth.insert( eos );
6318     }
6319
6320     // Update normals and other dependent data of not intersecting _LayerEdge's
6321     // neighboring the intersecting ones
6322
6323     for ( e2neIt = edge2newEdge.begin(); e2neIt != edge2newEdge.end(); ++e2neIt )
6324     {
6325       _LayerEdge*   edge1 = e2neIt->first;
6326       _EdgesOnShape* eos1 = data.GetShapeEdges( edge1 );
6327       if ( !edge1->Is( _LayerEdge::MARKED ))
6328         continue;
6329
6330       if ( edge1->IsOnEdge() )
6331       {
6332         const SMDS_MeshNode * n1 = edge1->_2neibors->srcNode(0);
6333         const SMDS_MeshNode * n2 = edge1->_2neibors->srcNode(1);
6334         edge1->SetDataByNeighbors( n1, n2, *eos1, helper );
6335       }
6336
6337       if ( !edge1->_2neibors )
6338         continue;
6339       for ( int j = 0; j < 2; ++j ) // loop on 2 neighbors
6340       {
6341         _LayerEdge* neighbor = edge1->_2neibors->_edges[j];
6342         if ( neighbor->Is( _LayerEdge::MARKED ) /*edge2newEdge.count ( neighbor )*/)
6343           continue; // j-th neighbor is also intersected
6344         _LayerEdge* prevEdge = edge1;
6345         const int nbSteps = 10;
6346         for ( int step = nbSteps; step; --step ) // step from edge1 in j-th direction
6347         {
6348           if ( neighbor->Is( _LayerEdge::BLOCKED ) ||
6349                neighbor->Is( _LayerEdge::MARKED ))
6350             break;
6351           _EdgesOnShape* eos = data.GetShapeEdges( neighbor );
6352           if ( !eos ) continue;
6353           _LayerEdge* nextEdge = neighbor;
6354           if ( neighbor->_2neibors )
6355           {
6356             int iNext = 0;
6357             nextEdge = neighbor->_2neibors->_edges[iNext];
6358             if ( nextEdge == prevEdge )
6359               nextEdge = neighbor->_2neibors->_edges[ ++iNext ];
6360           }
6361           double r = double(step-1)/nbSteps;
6362           if ( !nextEdge->_2neibors )
6363             r = Min( r, 0.5 );
6364
6365           gp_XYZ newNorm = prevEdge->_normal * r + nextEdge->_normal * (1-r);
6366           newNorm.Normalize();
6367           if ( !isNewNormalOk( data, *neighbor, newNorm ))
6368             break;
6369
6370           double len = neighbor->_len;
6371           neighbor->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true  );
6372           neighbor->SetNormal( newNorm );
6373           neighbor->SetCosin( prevEdge->_cosin * r + nextEdge->_cosin * (1-r) );
6374           if ( neighbor->_2neibors )
6375             neighbor->SetDataByNeighbors( prevEdge->_nodes[0], nextEdge->_nodes[0], *eos, helper );
6376           neighbor->SetNewLength( len, *eos, helper );
6377           neighbor->Set( _LayerEdge::MARKED );
6378           neighbor->Set( _LayerEdge::NORMAL_UPDATED );
6379           edgesNoAnaSmooth.insert( eos );
6380
6381           if ( !neighbor->_2neibors )
6382             break; // neighbor is on VERTEX
6383
6384           // goto the next neighbor
6385           prevEdge = neighbor;
6386           neighbor = nextEdge;
6387         }
6388       }
6389     }
6390     dumpFunctionEnd();
6391   } // iterations
6392
6393   data.AddShapesToSmooth( shapesToSmooth, &edgesNoAnaSmooth );
6394
6395   return true;
6396 }
6397
6398 //================================================================================
6399 /*!
6400  * \brief Check if a new normal is OK
6401  */
6402 //================================================================================
6403
6404 bool _ViscousBuilder::isNewNormalOk( _SolidData&   data,
6405                                      _LayerEdge&   edge,
6406                                      const gp_XYZ& newNormal)
6407 {
6408   // check a min angle between the newNormal and surrounding faces
6409   vector<_Simplex> simplices;
6410   SMESH_TNodeXYZ n0( edge._nodes[0] ), n1, n2;
6411   _Simplex::GetSimplices( n0._node, simplices, data._ignoreFaceIds, &data );
6412   double newMinDot = 1, curMinDot = 1;
6413   for ( size_t i = 0; i < simplices.size(); ++i )
6414   {
6415     n1.Set( simplices[i]._nPrev );
6416     n2.Set( simplices[i]._nNext );
6417     gp_XYZ normFace = ( n1 - n0 ) ^ ( n2 - n0 );
6418     double normLen2 = normFace.SquareModulus();
6419     if ( normLen2 < std::numeric_limits<double>::min() )
6420       continue;
6421     normFace /= Sqrt( normLen2 );
6422     newMinDot = Min( newNormal    * normFace, newMinDot );
6423     curMinDot = Min( edge._normal * normFace, curMinDot );
6424   }
6425   if ( newMinDot < 0.5 )
6426   {
6427     return ( newMinDot >= curMinDot * 0.9 );
6428     //return ( newMinDot >= ( curMinDot * ( 0.8 + 0.1 * edge.NbSteps() )));
6429     // double initMinDot2 = 1. - edge._cosin * edge._cosin;
6430     // return ( newMinDot * newMinDot ) >= ( 0.8 * initMinDot2 );
6431   }
6432   return true;
6433 }
6434
6435 //================================================================================
6436 /*!
6437  * \brief Modify normals of _LayerEdge's on FACE to reflex smoothing
6438  */
6439 //================================================================================
6440
6441 bool _ViscousBuilder::updateNormalsOfSmoothed( _SolidData&         data,
6442                                                SMESH_MesherHelper& helper,
6443                                                const int           nbSteps,
6444                                                const double        stepSize )
6445 {
6446   if ( data._nbShapesToSmooth == 0 || nbSteps == 0 )
6447     return true; // no shapes needing smoothing
6448
6449   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6450   {
6451     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
6452     if ( //!eos._toSmooth ||  _eosC1 have _toSmooth == false
6453          !eos._hyp.ToSmooth() ||
6454          eos.ShapeType() != TopAbs_FACE ||
6455          eos._edges.empty() )
6456       continue;
6457
6458     bool toSmooth = ( eos._edges[ 0 ]->NbSteps() >= nbSteps+1 );
6459     if ( !toSmooth ) continue;
6460
6461     for ( size_t i = 0; i < eos._edges.size(); ++i )
6462     {
6463       _LayerEdge* edge = eos._edges[i];
6464       if ( !edge->Is( _LayerEdge::SMOOTHED ))
6465         continue;
6466       if ( edge->Is( _LayerEdge::DIFFICULT ) && nbSteps != 1 )
6467         continue;
6468
6469       const gp_XYZ& pPrev = edge->PrevPos();
6470       const gp_XYZ& pLast = edge->_pos.back();
6471       gp_XYZ      stepVec = pLast - pPrev;
6472       double realStepSize = stepVec.Modulus();
6473       if ( realStepSize < numeric_limits<double>::min() )
6474         continue;
6475
6476       edge->_lenFactor = realStepSize / stepSize;
6477       edge->_normal    = stepVec / realStepSize;
6478       edge->Set( _LayerEdge::NORMAL_UPDATED );
6479     }
6480   }
6481
6482   return true;
6483 }
6484
6485 //================================================================================
6486 /*!
6487  * \brief Modify normals of _LayerEdge's on C1 VERTEXes
6488  */
6489 //================================================================================
6490
6491 void _ViscousBuilder::updateNormalsOfC1Vertices( _SolidData& data )
6492 {
6493   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6494   {
6495     _EdgesOnShape& eov = data._edgesOnShape[ iS ];
6496     if ( eov._eosC1.empty() ||
6497          eov.ShapeType() != TopAbs_VERTEX ||
6498          eov._edges.empty() )
6499       continue;
6500
6501     gp_XYZ newNorm   = eov._edges[0]->_normal;
6502     double curThick  = eov._edges[0]->_len * eov._edges[0]->_lenFactor;
6503     bool normChanged = false;
6504
6505     for ( size_t i = 0; i < eov._eosC1.size(); ++i )
6506     {
6507       _EdgesOnShape*   eoe = eov._eosC1[i];
6508       const TopoDS_Edge& e = TopoDS::Edge( eoe->_shape );
6509       const double    eLen = SMESH_Algo::EdgeLength( e );
6510       TopoDS_Shape    oppV = SMESH_MesherHelper::IthVertex( 0, e );
6511       if ( oppV.IsSame( eov._shape ))
6512         oppV = SMESH_MesherHelper::IthVertex( 1, e );
6513       _EdgesOnShape* eovOpp = data.GetShapeEdges( oppV );
6514       if ( !eovOpp || eovOpp->_edges.empty() ) continue;
6515
6516       double curThickOpp = eovOpp->_edges[0]->_len * eovOpp->_edges[0]->_lenFactor;
6517       if ( curThickOpp + curThick < eLen )
6518         continue;
6519
6520       double wgt = 2. * curThick / eLen;
6521       newNorm += wgt * eovOpp->_edges[0]->_normal;
6522       normChanged = true;
6523     }
6524     if ( normChanged )
6525     {
6526       eov._edges[0]->SetNormal( newNorm.Normalized() );
6527       eov._edges[0]->Set( _LayerEdge::NORMAL_UPDATED );
6528     }
6529   }
6530 }
6531
6532 //================================================================================
6533 /*!
6534  * \brief Modify normals of _LayerEdge's on _ConvexFace's
6535  */
6536 //================================================================================
6537
6538 bool _ViscousBuilder::updateNormalsOfConvexFaces( _SolidData&         data,
6539                                                   SMESH_MesherHelper& helper,
6540                                                   int                 stepNb )
6541 {
6542   SMESHDS_Mesh* meshDS = helper.GetMeshDS();
6543   bool isOK;
6544
6545   map< TGeomID, _ConvexFace >::iterator id2face = data._convexFaces.begin();
6546   for ( ; id2face != data._convexFaces.end(); ++id2face )
6547   {
6548     _ConvexFace & convFace = (*id2face).second;
6549     if ( convFace._normalsFixed )
6550       continue; // already fixed
6551     if ( convFace.CheckPrisms() )
6552       continue; // nothing to fix
6553
6554     convFace._normalsFixed = true;
6555
6556     BRepAdaptor_Surface surface ( convFace._face, false );
6557     BRepLProp_SLProps   surfProp( surface, 2, 1e-6 );
6558
6559     // check if the convex FACE is of spherical shape
6560
6561     Bnd_B3d centersBox; // bbox of centers of curvature of _LayerEdge's on VERTEXes
6562     Bnd_B3d nodesBox;
6563     gp_Pnt  center;
6564
6565     map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.begin();
6566     for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
6567     {
6568       _EdgesOnShape& eos = *(id2eos->second);
6569       if ( eos.ShapeType() == TopAbs_VERTEX )
6570       {
6571         _LayerEdge* ledge = eos._edges[ 0 ];
6572         if ( convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
6573           centersBox.Add( center );
6574       }
6575       for ( size_t i = 0; i < eos._edges.size(); ++i )
6576         nodesBox.Add( SMESH_TNodeXYZ( eos._edges[ i ]->_nodes[0] ));
6577     }
6578     if ( centersBox.IsVoid() )
6579     {
6580       debugMsg( "Error: centersBox.IsVoid()" );
6581       return false;
6582     }
6583     const bool isSpherical =
6584       ( centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
6585
6586     int nbEdges = helper.Count( convFace._face, TopAbs_EDGE, /*ignoreSame=*/false );
6587     vector < _CentralCurveOnEdge > centerCurves( nbEdges );
6588
6589     if ( isSpherical )
6590     {
6591       // set _LayerEdge::_normal as average of all normals
6592
6593       // WARNING: different density of nodes on EDGEs is not taken into account that
6594       // can lead to an improper new normal
6595
6596       gp_XYZ avgNormal( 0,0,0 );
6597       nbEdges = 0;
6598       id2eos = convFace._subIdToEOS.begin();
6599       for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
6600       {
6601         _EdgesOnShape& eos = *(id2eos->second);
6602         // set data of _CentralCurveOnEdge
6603         if ( eos.ShapeType() == TopAbs_EDGE )
6604         {
6605           _CentralCurveOnEdge& ceCurve = centerCurves[ nbEdges++ ];
6606           ceCurve.SetShapes( TopoDS::Edge( eos._shape ), convFace, data, helper );
6607           if ( !eos._sWOL.IsNull() )
6608             ceCurve._adjFace.Nullify();
6609           else
6610             ceCurve._ledges.insert( ceCurve._ledges.end(),
6611                                     eos._edges.begin(), eos._edges.end());
6612         }
6613         // summarize normals
6614         for ( size_t i = 0; i < eos._edges.size(); ++i )
6615           avgNormal += eos._edges[ i ]->_normal;
6616       }
6617       double normSize = avgNormal.SquareModulus();
6618       if ( normSize < 1e-200 )
6619       {
6620         debugMsg( "updateNormalsOfConvexFaces(): zero avgNormal" );
6621         return false;
6622       }
6623       avgNormal /= Sqrt( normSize );
6624
6625       // compute new _LayerEdge::_cosin on EDGEs
6626       double avgCosin = 0;
6627       int     nbCosin = 0;
6628       gp_Vec inFaceDir;
6629       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
6630       {
6631         _CentralCurveOnEdge& ceCurve = centerCurves[ iE ];
6632         if ( ceCurve._adjFace.IsNull() )
6633           continue;
6634         for ( size_t iLE = 0; iLE < ceCurve._ledges.size(); ++iLE )
6635         {
6636           const SMDS_MeshNode* node = ceCurve._ledges[ iLE ]->_nodes[0];
6637           inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
6638           if ( isOK )
6639           {
6640             double angle = inFaceDir.Angle( avgNormal ); // [0,PI]
6641             ceCurve._ledges[ iLE ]->_cosin = Cos( angle );
6642             avgCosin += ceCurve._ledges[ iLE ]->_cosin;
6643             nbCosin++;
6644           }
6645         }
6646       }
6647       if ( nbCosin > 0 )
6648         avgCosin /= nbCosin;
6649
6650       // set _LayerEdge::_normal = avgNormal
6651       id2eos = convFace._subIdToEOS.begin();
6652       for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
6653       {
6654         _EdgesOnShape& eos = *(id2eos->second);
6655         if ( eos.ShapeType() != TopAbs_EDGE )
6656           for ( size_t i = 0; i < eos._edges.size(); ++i )
6657             eos._edges[ i ]->_cosin = avgCosin;
6658
6659         for ( size_t i = 0; i < eos._edges.size(); ++i )
6660         {
6661           eos._edges[ i ]->SetNormal( avgNormal );
6662           eos._edges[ i ]->Set( _LayerEdge::NORMAL_UPDATED );
6663         }
6664       }
6665     }
6666     else // if ( isSpherical )
6667     {
6668       // We suppose that centers of curvature at all points of the FACE
6669       // lie on some curve, let's call it "central curve". For all _LayerEdge's
6670       // having a common center of curvature we define the same new normal
6671       // as a sum of normals of _LayerEdge's on EDGEs among them.
6672
6673       // get all centers of curvature for each EDGE
6674
6675       helper.SetSubShape( convFace._face );
6676       _LayerEdge* vertexLEdges[2], **edgeLEdge, **edgeLEdgeEnd;
6677
6678       TopExp_Explorer edgeExp( convFace._face, TopAbs_EDGE );
6679       for ( int iE = 0; edgeExp.More(); edgeExp.Next(), ++iE )
6680       {
6681         const TopoDS_Edge& edge = TopoDS::Edge( edgeExp.Current() );
6682
6683         // set adjacent FACE
6684         centerCurves[ iE ].SetShapes( edge, convFace, data, helper );
6685
6686         // get _LayerEdge's of the EDGE
6687         TGeomID edgeID = meshDS->ShapeToIndex( edge );
6688         _EdgesOnShape* eos = data.GetShapeEdges( edgeID );
6689         if ( !eos || eos->_edges.empty() )
6690         {
6691           // no _LayerEdge's on EDGE, use _LayerEdge's on VERTEXes
6692           for ( int iV = 0; iV < 2; ++iV )
6693           {
6694             TopoDS_Vertex v = helper.IthVertex( iV, edge );
6695             TGeomID     vID = meshDS->ShapeToIndex( v );
6696             eos = data.GetShapeEdges( vID );
6697             vertexLEdges[ iV ] = eos->_edges[ 0 ];
6698           }
6699           edgeLEdge    = &vertexLEdges[0];
6700           edgeLEdgeEnd = edgeLEdge + 2;
6701
6702           centerCurves[ iE ]._adjFace.Nullify();
6703         }
6704         else
6705         {
6706           if ( ! eos->_toSmooth )
6707             data.SortOnEdge( edge, eos->_edges );
6708           edgeLEdge    = &eos->_edges[ 0 ];
6709           edgeLEdgeEnd = edgeLEdge + eos->_edges.size();
6710           vertexLEdges[0] = eos->_edges.front()->_2neibors->_edges[0];
6711           vertexLEdges[1] = eos->_edges.back() ->_2neibors->_edges[1];
6712
6713           if ( ! eos->_sWOL.IsNull() )
6714             centerCurves[ iE ]._adjFace.Nullify();
6715         }
6716
6717         // Get curvature centers
6718
6719         centersBox.Clear();
6720
6721         if ( edgeLEdge[0]->IsOnEdge() &&
6722              convFace.GetCenterOfCurvature( vertexLEdges[0], surfProp, helper, center ))
6723         { // 1st VERTEX
6724           centerCurves[ iE ].Append( center, vertexLEdges[0] );
6725           centersBox.Add( center );
6726         }
6727         for ( ; edgeLEdge < edgeLEdgeEnd; ++edgeLEdge )
6728           if ( convFace.GetCenterOfCurvature( *edgeLEdge, surfProp, helper, center ))
6729           { // EDGE or VERTEXes
6730             centerCurves[ iE ].Append( center, *edgeLEdge );
6731             centersBox.Add( center );
6732           }
6733         if ( edgeLEdge[-1]->IsOnEdge() &&
6734              convFace.GetCenterOfCurvature( vertexLEdges[1], surfProp, helper, center ))
6735         { // 2nd VERTEX
6736           centerCurves[ iE ].Append( center, vertexLEdges[1] );
6737           centersBox.Add( center );
6738         }
6739         centerCurves[ iE ]._isDegenerated =
6740           ( centersBox.IsVoid() || centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
6741
6742       } // loop on EDGES of convFace._face to set up data of centerCurves
6743
6744       // Compute new normals for _LayerEdge's on EDGEs
6745
6746       double avgCosin = 0;
6747       int     nbCosin = 0;
6748       gp_Vec inFaceDir;
6749       for ( size_t iE1 = 0; iE1 < centerCurves.size(); ++iE1 )
6750       {
6751         _CentralCurveOnEdge& ceCurve = centerCurves[ iE1 ];
6752         if ( ceCurve._isDegenerated )
6753           continue;
6754         const vector< gp_Pnt >& centers = ceCurve._curvaCenters;
6755         vector< gp_XYZ > &   newNormals = ceCurve._normals;
6756         for ( size_t iC1 = 0; iC1 < centers.size(); ++iC1 )
6757         {
6758           isOK = false;
6759           for ( size_t iE2 = 0; iE2 < centerCurves.size() && !isOK; ++iE2 )
6760           {
6761             if ( iE1 != iE2 )
6762               isOK = centerCurves[ iE2 ].FindNewNormal( centers[ iC1 ], newNormals[ iC1 ]);
6763           }
6764           if ( isOK && !ceCurve._adjFace.IsNull() )
6765           {
6766             // compute new _LayerEdge::_cosin
6767             const SMDS_MeshNode* node = ceCurve._ledges[ iC1 ]->_nodes[0];
6768             inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
6769             if ( isOK )
6770             {
6771               double angle = inFaceDir.Angle( newNormals[ iC1 ] ); // [0,PI]
6772               ceCurve._ledges[ iC1 ]->_cosin = Cos( angle );
6773               avgCosin += ceCurve._ledges[ iC1 ]->_cosin;
6774               nbCosin++;
6775             }
6776           }
6777         }
6778       }
6779       // set new normals to _LayerEdge's of NOT degenerated central curves
6780       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
6781       {
6782         if ( centerCurves[ iE ]._isDegenerated )
6783           continue;
6784         for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
6785         {
6786           centerCurves[ iE ]._ledges[ iLE ]->SetNormal( centerCurves[ iE ]._normals[ iLE ]);
6787           centerCurves[ iE ]._ledges[ iLE ]->Set( _LayerEdge::NORMAL_UPDATED );
6788         }
6789       }
6790       // set new normals to _LayerEdge's of     degenerated central curves
6791       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
6792       {
6793         if ( !centerCurves[ iE ]._isDegenerated ||
6794              centerCurves[ iE ]._ledges.size() < 3 )
6795           continue;
6796         // new normal is an average of new normals at VERTEXes that
6797         // was computed on non-degenerated _CentralCurveOnEdge's
6798         gp_XYZ newNorm = ( centerCurves[ iE ]._ledges.front()->_normal +
6799                            centerCurves[ iE ]._ledges.back ()->_normal );
6800         double sz = newNorm.Modulus();
6801         if ( sz < 1e-200 )
6802           continue;
6803         newNorm /= sz;
6804         double newCosin = ( 0.5 * centerCurves[ iE ]._ledges.front()->_cosin +
6805                             0.5 * centerCurves[ iE ]._ledges.back ()->_cosin );
6806         for ( size_t iLE = 1, nb = centerCurves[ iE ]._ledges.size() - 1; iLE < nb; ++iLE )
6807         {
6808           centerCurves[ iE ]._ledges[ iLE ]->SetNormal( newNorm );
6809           centerCurves[ iE ]._ledges[ iLE ]->_cosin   = newCosin;
6810           centerCurves[ iE ]._ledges[ iLE ]->Set( _LayerEdge::NORMAL_UPDATED );
6811         }
6812       }
6813
6814       // Find new normals for _LayerEdge's based on FACE
6815
6816       if ( nbCosin > 0 )
6817         avgCosin /= nbCosin;
6818       const TGeomID faceID = meshDS->ShapeToIndex( convFace._face );
6819       map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.find( faceID );
6820       if ( id2eos != convFace._subIdToEOS.end() )
6821       {
6822         int iE = 0;
6823         gp_XYZ newNorm;
6824         _EdgesOnShape& eos = * ( id2eos->second );
6825         for ( size_t i = 0; i < eos._edges.size(); ++i )
6826         {
6827           _LayerEdge* ledge = eos._edges[ i ];
6828           if ( !convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
6829             continue;
6830           for ( size_t i = 0; i < centerCurves.size(); ++i, ++iE )
6831           {
6832             iE = iE % centerCurves.size();
6833             if ( centerCurves[ iE ]._isDegenerated )
6834               continue;
6835             newNorm.SetCoord( 0,0,0 );
6836             if ( centerCurves[ iE ].FindNewNormal( center, newNorm ))
6837             {
6838               ledge->SetNormal( newNorm );
6839               ledge->_cosin  = avgCosin;
6840               ledge->Set( _LayerEdge::NORMAL_UPDATED );
6841               break;
6842             }
6843           }
6844         }
6845       }
6846
6847     } // not a quasi-spherical FACE
6848
6849     // Update _LayerEdge's data according to a new normal
6850
6851     dumpFunction(SMESH_Comment("updateNormalsOfConvexFaces")<<data._index
6852                  <<"_F"<<meshDS->ShapeToIndex( convFace._face ));
6853
6854     id2eos = convFace._subIdToEOS.begin();
6855     for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
6856     {
6857       _EdgesOnShape& eos = * ( id2eos->second );
6858       for ( size_t i = 0; i < eos._edges.size(); ++i )
6859       {
6860         _LayerEdge* & ledge = eos._edges[ i ];
6861         double len = ledge->_len;
6862         ledge->InvalidateStep( stepNb + 1, eos, /*restoreLength=*/true );
6863         ledge->SetCosin( ledge->_cosin );
6864         ledge->SetNewLength( len, eos, helper );
6865       }
6866       if ( eos.ShapeType() != TopAbs_FACE )
6867         for ( size_t i = 0; i < eos._edges.size(); ++i )
6868         {
6869           _LayerEdge* ledge = eos._edges[ i ];
6870           for ( size_t iN = 0; iN < ledge->_neibors.size(); ++iN )
6871           {
6872             _LayerEdge* neibor = ledge->_neibors[iN];
6873             if ( neibor->_nodes[0]->GetPosition()->GetDim() == 2 )
6874             {
6875               neibor->Set( _LayerEdge::NEAR_BOUNDARY );
6876               neibor->Set( _LayerEdge::MOVED );
6877               neibor->SetSmooLen( neibor->_len );
6878             }
6879           }
6880         }
6881     } // loop on sub-shapes of convFace._face
6882
6883     // Find FACEs adjacent to convFace._face that got necessity to smooth
6884     // as a result of normals modification
6885
6886     set< _EdgesOnShape* > adjFacesToSmooth;
6887     for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
6888     {
6889       if ( centerCurves[ iE ]._adjFace.IsNull() ||
6890            centerCurves[ iE ]._adjFaceToSmooth )
6891         continue;
6892       for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
6893       {
6894         if ( centerCurves[ iE ]._ledges[ iLE ]->_cosin > theMinSmoothCosin )
6895         {
6896           adjFacesToSmooth.insert( data.GetShapeEdges( centerCurves[ iE ]._adjFace ));
6897           break;
6898         }
6899       }
6900     }
6901     data.AddShapesToSmooth( adjFacesToSmooth );
6902
6903     dumpFunctionEnd();
6904
6905
6906   } // loop on data._convexFaces
6907
6908   return true;
6909 }
6910
6911 //================================================================================
6912 /*!
6913  * \brief Finds a center of curvature of a surface at a _LayerEdge
6914  */
6915 //================================================================================
6916
6917 bool _ConvexFace::GetCenterOfCurvature( _LayerEdge*         ledge,
6918                                         BRepLProp_SLProps&  surfProp,
6919                                         SMESH_MesherHelper& helper,
6920                                         gp_Pnt &            center ) const
6921 {
6922   gp_XY uv = helper.GetNodeUV( _face, ledge->_nodes[0] );
6923   surfProp.SetParameters( uv.X(), uv.Y() );
6924   if ( !surfProp.IsCurvatureDefined() )
6925     return false;
6926
6927   const double oriFactor = ( _face.Orientation() == TopAbs_REVERSED ? +1. : -1. );
6928   double surfCurvatureMax = surfProp.MaxCurvature() * oriFactor;
6929   double surfCurvatureMin = surfProp.MinCurvature() * oriFactor;
6930   if ( surfCurvatureMin > surfCurvatureMax )
6931     center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMin * oriFactor );
6932   else
6933     center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMax * oriFactor );
6934
6935   return true;
6936 }
6937
6938 //================================================================================
6939 /*!
6940  * \brief Check that prisms are not distorted
6941  */
6942 //================================================================================
6943
6944 bool _ConvexFace::CheckPrisms() const
6945 {
6946   double vol = 0;
6947   for ( size_t i = 0; i < _simplexTestEdges.size(); ++i )
6948   {
6949     const _LayerEdge* edge = _simplexTestEdges[i];
6950     SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
6951     for ( size_t j = 0; j < edge->_simplices.size(); ++j )
6952       if ( !edge->_simplices[j].IsForward( edge->_nodes[0], tgtXYZ, vol ))
6953       {
6954         debugMsg( "Bad simplex of _simplexTestEdges ("
6955                   << " "<< edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
6956                   << " "<< edge->_simplices[j]._nPrev->GetID()
6957                   << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
6958         return false;
6959       }
6960   }
6961   return true;
6962 }
6963
6964 //================================================================================
6965 /*!
6966  * \brief Try to compute a new normal by interpolating normals of _LayerEdge's
6967  *        stored in this _CentralCurveOnEdge.
6968  *  \param [in] center - curvature center of a point of another _CentralCurveOnEdge.
6969  *  \param [in,out] newNormal - current normal at this point, to be redefined
6970  *  \return bool - true if succeeded.
6971  */
6972 //================================================================================
6973
6974 bool _CentralCurveOnEdge::FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal )
6975 {
6976   if ( this->_isDegenerated )
6977     return false;
6978
6979   // find two centers the given one lies between
6980
6981   for ( size_t i = 0, nb = _curvaCenters.size()-1;  i < nb;  ++i )
6982   {
6983     double sl2 = 1.001 * _segLength2[ i ];
6984
6985     double d1 = center.SquareDistance( _curvaCenters[ i ]);
6986     if ( d1 > sl2 )
6987       continue;
6988     
6989     double d2 = center.SquareDistance( _curvaCenters[ i+1 ]);
6990     if ( d2 > sl2 || d2 + d1 < 1e-100 )
6991       continue;
6992
6993     d1 = Sqrt( d1 );
6994     d2 = Sqrt( d2 );
6995     double r = d1 / ( d1 + d2 );
6996     gp_XYZ norm = (( 1. - r ) * _ledges[ i   ]->_normal +
6997                    (      r ) * _ledges[ i+1 ]->_normal );
6998     norm.Normalize();
6999
7000     newNormal += norm;
7001     double sz = newNormal.Modulus();
7002     if ( sz < 1e-200 )
7003       break;
7004     newNormal /= sz;
7005     return true;
7006   }
7007   return false;
7008 }
7009
7010 //================================================================================
7011 /*!
7012  * \brief Set shape members
7013  */
7014 //================================================================================
7015
7016 void _CentralCurveOnEdge::SetShapes( const TopoDS_Edge&  edge,
7017                                      const _ConvexFace&  convFace,
7018                                      _SolidData&         data,
7019                                      SMESH_MesherHelper& helper)
7020 {
7021   _edge = edge;
7022
7023   PShapeIteratorPtr fIt = helper.GetAncestors( edge, *helper.GetMesh(), TopAbs_FACE );
7024   while ( const TopoDS_Shape* F = fIt->next())
7025     if ( !convFace._face.IsSame( *F ))
7026     {
7027       _adjFace = TopoDS::Face( *F );
7028       _adjFaceToSmooth = false;
7029       // _adjFace already in a smoothing queue ?
7030       if ( _EdgesOnShape* eos = data.GetShapeEdges( _adjFace ))
7031         _adjFaceToSmooth = eos->_toSmooth;
7032       break;
7033     }
7034 }
7035
7036 //================================================================================
7037 /*!
7038  * \brief Looks for intersection of it's last segment with faces
7039  *  \param distance - returns shortest distance from the last node to intersection
7040  */
7041 //================================================================================
7042
7043 bool _LayerEdge::FindIntersection( SMESH_ElementSearcher&   searcher,
7044                                    double &                 distance,
7045                                    const double&            epsilon,
7046                                    _EdgesOnShape&           eos,
7047                                    const SMDS_MeshElement** intFace)
7048 {
7049   vector< const SMDS_MeshElement* > suspectFaces;
7050   double segLen;
7051   gp_Ax1 lastSegment = LastSegment( segLen, eos );
7052   searcher.GetElementsNearLine( lastSegment, SMDSAbs_Face, suspectFaces );
7053
7054   bool segmentIntersected = false;
7055   distance = Precision::Infinite();
7056   int iFace = -1; // intersected face
7057   for ( size_t j = 0 ; j < suspectFaces.size() /*&& !segmentIntersected*/; ++j )
7058   {
7059     const SMDS_MeshElement* face = suspectFaces[j];
7060     if ( face->GetNodeIndex( _nodes.back() ) >= 0 ||
7061          face->GetNodeIndex( _nodes[0]     ) >= 0 )
7062       continue; // face sharing _LayerEdge node
7063     const int nbNodes = face->NbCornerNodes();
7064     bool intFound = false;
7065     double dist;
7066     SMDS_MeshElement::iterator nIt = face->begin_nodes();
7067     if ( nbNodes == 3 )
7068     {
7069       intFound = SegTriaInter( lastSegment, *nIt++, *nIt++, *nIt++, dist, epsilon );
7070     }
7071     else
7072     {
7073       const SMDS_MeshNode* tria[3];
7074       tria[0] = *nIt++;
7075       tria[1] = *nIt++;
7076       for ( int n2 = 2; n2 < nbNodes && !intFound; ++n2 )
7077       {
7078         tria[2] = *nIt++;
7079         intFound = SegTriaInter(lastSegment, tria[0], tria[1], tria[2], dist, epsilon );
7080         tria[1] = tria[2];
7081       }
7082     }
7083     if ( intFound )
7084     {
7085       if ( dist < segLen*(1.01) && dist > -(_len*_lenFactor-segLen) )
7086         segmentIntersected = true;
7087       if ( distance > dist )
7088         distance = dist, iFace = j;
7089     }
7090   }
7091   if ( intFace ) *intFace = ( iFace != -1 ) ? suspectFaces[iFace] : 0;
7092
7093   distance -= segLen;
7094
7095   if ( segmentIntersected )
7096   {
7097 #ifdef __myDEBUG
7098     SMDS_MeshElement::iterator nIt = suspectFaces[iFace]->begin_nodes();
7099     gp_XYZ intP( lastSegment.Location().XYZ() + lastSegment.Direction().XYZ() * ( distance+segLen ));
7100     cout << "nodes: tgt " << _nodes.back()->GetID() << " src " << _nodes[0]->GetID()
7101          << ", intersection with face ("
7102          << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
7103          << ") at point (" << intP.X() << ", " << intP.Y() << ", " << intP.Z()
7104          << ") distance = " << distance << endl;
7105 #endif
7106   }
7107
7108   return segmentIntersected;
7109 }
7110
7111 //================================================================================
7112 /*!
7113  * \brief Returns size and direction of the last segment
7114  */
7115 //================================================================================
7116
7117 gp_Ax1 _LayerEdge::LastSegment(double& segLen, _EdgesOnShape& eos) const
7118 {
7119   // find two non-coincident positions
7120   gp_XYZ orig = _pos.back();
7121   gp_XYZ vec;
7122   int iPrev = _pos.size() - 2;
7123   //const double tol = ( _len > 0 ) ? 0.3*_len : 1e-100; // adjusted for IPAL52478 + PAL22576
7124   const double tol = ( _len > 0 ) ? ( 1e-6 * _len ) : 1e-100;
7125   while ( iPrev >= 0 )
7126   {
7127     vec = orig - _pos[iPrev];
7128     if ( vec.SquareModulus() > tol*tol )
7129       break;
7130     else
7131       iPrev--;
7132   }
7133
7134   // make gp_Ax1
7135   gp_Ax1 segDir;
7136   if ( iPrev < 0 )
7137   {
7138     segDir.SetLocation( SMESH_TNodeXYZ( _nodes[0] ));
7139     segDir.SetDirection( _normal );
7140     segLen = 0;
7141   }
7142   else
7143   {
7144     gp_Pnt pPrev = _pos[ iPrev ];
7145     if ( !eos._sWOL.IsNull() )
7146     {
7147       TopLoc_Location loc;
7148       if ( eos.SWOLType() == TopAbs_EDGE )
7149       {
7150         double f,l;
7151         Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eos._sWOL ), loc, f,l);
7152         pPrev = curve->Value( pPrev.X() ).Transformed( loc );
7153       }
7154       else
7155       {
7156         Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face( eos._sWOL ), loc );
7157         pPrev = surface->Value( pPrev.X(), pPrev.Y() ).Transformed( loc );
7158       }
7159       vec = SMESH_TNodeXYZ( _nodes.back() ) - pPrev.XYZ();
7160     }
7161     segDir.SetLocation( pPrev );
7162     segDir.SetDirection( vec );
7163     segLen = vec.Modulus();
7164   }
7165
7166   return segDir;
7167 }
7168
7169 //================================================================================
7170 /*!
7171  * \brief Return the last position of the target node on a FACE. 
7172  *  \param [in] F - the FACE this _LayerEdge is inflated along
7173  *  \return gp_XY - result UV
7174  */
7175 //================================================================================
7176
7177 gp_XY _LayerEdge::LastUV( const TopoDS_Face& F, _EdgesOnShape& eos ) const
7178 {
7179   if ( F.IsSame( eos._sWOL )) // F is my FACE
7180     return gp_XY( _pos.back().X(), _pos.back().Y() );
7181
7182   if ( eos.SWOLType() != TopAbs_EDGE ) // wrong call
7183     return gp_XY( 1e100, 1e100 );
7184
7185   // _sWOL is EDGE of F; _pos.back().X() is the last U on the EDGE
7186   double f, l, u = _pos.back().X();
7187   Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( TopoDS::Edge(eos._sWOL), F, f,l);
7188   if ( !C2d.IsNull() && f <= u && u <= l )
7189     return C2d->Value( u ).XY();
7190
7191   return gp_XY( 1e100, 1e100 );
7192 }
7193
7194 //================================================================================
7195 /*!
7196  * \brief Test intersection of the last segment with a given triangle
7197  *   using Moller-Trumbore algorithm
7198  * Intersection is detected if distance to intersection is less than _LayerEdge._len
7199  */
7200 //================================================================================
7201
7202 bool _LayerEdge::SegTriaInter( const gp_Ax1& lastSegment,
7203                                const gp_XYZ& vert0,
7204                                const gp_XYZ& vert1,
7205                                const gp_XYZ& vert2,
7206                                double&       t,
7207                                const double& EPSILON) const
7208 {
7209   const gp_Pnt& orig = lastSegment.Location();
7210   const gp_Dir& dir  = lastSegment.Direction();
7211
7212   /* calculate distance from vert0 to ray origin */
7213   gp_XYZ tvec = orig.XYZ() - vert0;
7214
7215   //if ( tvec * dir > EPSILON )
7216     // intersected face is at back side of the temporary face this _LayerEdge belongs to
7217     //return false;
7218
7219   gp_XYZ edge1 = vert1 - vert0;
7220   gp_XYZ edge2 = vert2 - vert0;
7221
7222   /* begin calculating determinant - also used to calculate U parameter */
7223   gp_XYZ pvec = dir.XYZ() ^ edge2;
7224
7225   /* if determinant is near zero, ray lies in plane of triangle */
7226   double det = edge1 * pvec;
7227
7228   const double ANGL_EPSILON = 1e-12;
7229   if ( det > -ANGL_EPSILON && det < ANGL_EPSILON )
7230     return false;
7231
7232   /* calculate U parameter and test bounds */
7233   double u = ( tvec * pvec ) / det;
7234   //if (u < 0.0 || u > 1.0)
7235   if ( u < -EPSILON || u > 1.0 + EPSILON )
7236     return false;
7237
7238   /* prepare to test V parameter */
7239   gp_XYZ qvec = tvec ^ edge1;
7240
7241   /* calculate V parameter and test bounds */
7242   double v = (dir.XYZ() * qvec) / det;
7243   //if ( v < 0.0 || u + v > 1.0 )
7244   if ( v < -EPSILON || u + v > 1.0 + EPSILON )
7245     return false;
7246
7247   /* calculate t, ray intersects triangle */
7248   t = (edge2 * qvec) / det;
7249
7250   //return true;
7251   return t > 0.;
7252 }
7253
7254 //================================================================================
7255 /*!
7256  * \brief _LayerEdge, located at a concave VERTEX of a FACE, moves target nodes of
7257  *        neighbor _LayerEdge's by it's own inflation vector.
7258  *  \param [in] eov - EOS of the VERTEX
7259  *  \param [in] eos - EOS of the FACE
7260  *  \param [in] step - inflation step
7261  *  \param [in,out] badSmooEdges - not untangled _LayerEdge's
7262  */
7263 //================================================================================
7264
7265 void _LayerEdge::MoveNearConcaVer( const _EdgesOnShape*    eov,
7266                                    const _EdgesOnShape*    eos,
7267                                    const int               step,
7268                                    vector< _LayerEdge* > & badSmooEdges )
7269 {
7270   // check if any of _neibors is in badSmooEdges
7271   if ( std::find_first_of( _neibors.begin(), _neibors.end(),
7272                            badSmooEdges.begin(), badSmooEdges.end() ) == _neibors.end() )
7273     return;
7274
7275   // get all edges to move
7276
7277   set< _LayerEdge* > edges;
7278
7279   // find a distance between _LayerEdge on VERTEX and its neighbors
7280   gp_XYZ  curPosV = SMESH_TNodeXYZ( _nodes.back() );
7281   double dist2 = 0;
7282   for ( size_t i = 0; i < _neibors.size(); ++i )
7283   {
7284     _LayerEdge* nEdge = _neibors[i];
7285     if ( nEdge->_nodes[0]->getshapeId() == eos->_shapeID )
7286     {
7287       edges.insert( nEdge );
7288       dist2 = Max( dist2, ( curPosV - nEdge->_pos.back() ).SquareModulus() );
7289     }
7290   }
7291   // add _LayerEdge's close to curPosV
7292   size_t nbE;
7293   do {
7294     nbE = edges.size();
7295     for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
7296     {
7297       _LayerEdge* edgeF = *e;
7298       for ( size_t i = 0; i < edgeF->_neibors.size(); ++i )
7299       {
7300         _LayerEdge* nEdge = edgeF->_neibors[i];
7301         if ( nEdge->_nodes[0]->getshapeId() == eos->_shapeID &&
7302              dist2 > ( curPosV - nEdge->_pos.back() ).SquareModulus() )
7303           edges.insert( nEdge );
7304       }
7305     }
7306   }
7307   while ( nbE < edges.size() );
7308
7309   // move the target node of the got edges
7310
7311   gp_XYZ prevPosV = PrevPos();
7312   if ( eov->SWOLType() == TopAbs_EDGE )
7313   {
7314     BRepAdaptor_Curve curve ( TopoDS::Edge( eov->_sWOL ));
7315     prevPosV = curve.Value( prevPosV.X() ).XYZ();
7316   }
7317   else if ( eov->SWOLType() == TopAbs_FACE )
7318   {
7319     BRepAdaptor_Surface surface( TopoDS::Face( eov->_sWOL ));
7320     prevPosV = surface.Value( prevPosV.X(), prevPosV.Y() ).XYZ();
7321   }
7322
7323   SMDS_FacePosition* fPos;
7324   //double r = 1. - Min( 0.9, step / 10. );
7325   for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
7326   {
7327     _LayerEdge*       edgeF = *e;
7328     const gp_XYZ     prevVF = edgeF->PrevPos() - prevPosV;
7329     const gp_XYZ    newPosF = curPosV + prevVF;
7330     SMDS_MeshNode* tgtNodeF = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
7331     tgtNodeF->setXYZ( newPosF.X(), newPosF.Y(), newPosF.Z() );
7332     edgeF->_pos.back() = newPosF;
7333     dumpMoveComm( tgtNodeF, "MoveNearConcaVer" ); // debug
7334
7335     // set _curvature to make edgeF updated by putOnOffsetSurface()
7336     if ( !edgeF->_curvature )
7337       if (( fPos = dynamic_cast<SMDS_FacePosition*>( edgeF->_nodes[0]->GetPosition() )))
7338       {
7339         edgeF->_curvature = new _Curvature;
7340         edgeF->_curvature->_r = 0;
7341         edgeF->_curvature->_k = 0;
7342         edgeF->_curvature->_h2lenRatio = 0;
7343         edgeF->_curvature->_uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
7344       }
7345   }
7346   // gp_XYZ inflationVec( SMESH_TNodeXYZ( _nodes.back() ) -
7347   //                      SMESH_TNodeXYZ( _nodes[0]    ));
7348   // for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
7349   // {
7350   //   _LayerEdge*      edgeF = *e;
7351   //   gp_XYZ          newPos = SMESH_TNodeXYZ( edgeF->_nodes[0] ) + inflationVec;
7352   //   SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
7353   //   tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7354   //   edgeF->_pos.back() = newPosF;
7355   //   dumpMoveComm( tgtNode, "MoveNearConcaVer" ); // debug
7356   // }
7357
7358   // smooth _LayerEdge's around moved nodes
7359   //size_t nbBadBefore = badSmooEdges.size();
7360   for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
7361   {
7362     _LayerEdge* edgeF = *e;
7363     for ( size_t j = 0; j < edgeF->_neibors.size(); ++j )
7364       if ( edgeF->_neibors[j]->_nodes[0]->getshapeId() == eos->_shapeID )
7365         //&& !edges.count( edgeF->_neibors[j] ))
7366       {
7367         _LayerEdge* edgeFN = edgeF->_neibors[j];
7368         edgeFN->Unset( SMOOTHED );
7369         int nbBad = edgeFN->Smooth( step, /*isConcaFace=*/true, /*findBest=*/true );
7370         // if ( nbBad > 0 )
7371         // {
7372         //   gp_XYZ         newPos = SMESH_TNodeXYZ( edgeFN->_nodes[0] ) + inflationVec;
7373         //   const gp_XYZ& prevPos = edgeFN->_pos[ edgeFN->_pos.size()-2 ];
7374         //   int        nbBadAfter = edgeFN->_simplices.size();
7375         //   double vol;
7376         //   for ( size_t iS = 0; iS < edgeFN->_simplices.size(); ++iS )
7377         //   {
7378         //     nbBadAfter -= edgeFN->_simplices[iS].IsForward( &prevPos, &newPos, vol );
7379         //   }
7380         //   if ( nbBadAfter <= nbBad )
7381         //   {
7382         //     SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeFN->_nodes.back() );
7383         //     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7384         //     edgeF->_pos.back() = newPosF;
7385         //     dumpMoveComm( tgtNode, "MoveNearConcaVer 2" ); // debug
7386         //     nbBad = nbBadAfter;
7387         //   }
7388         // }
7389         if ( nbBad > 0 )
7390           badSmooEdges.push_back( edgeFN );
7391       }
7392   }
7393     // move a bit not smoothed around moved nodes
7394   //   for ( size_t i = nbBadBefore; i < badSmooEdges.size(); ++i )
7395   //   {
7396   //   _LayerEdge*      edgeF = badSmooEdges[i];
7397   //   SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
7398   //   gp_XYZ         newPos1 = SMESH_TNodeXYZ( edgeF->_nodes[0] ) + inflationVec;
7399   //   gp_XYZ         newPos2 = 0.5 * ( newPos1 + SMESH_TNodeXYZ( tgtNode ));
7400   //   tgtNode->setXYZ( newPos2.X(), newPos2.Y(), newPos2.Z() );
7401   //   edgeF->_pos.back() = newPosF;
7402   //   dumpMoveComm( tgtNode, "MoveNearConcaVer 2" ); // debug
7403   // }
7404 }
7405
7406 //================================================================================
7407 /*!
7408  * \brief Perform smooth of _LayerEdge's based on EDGE's
7409  *  \retval bool - true if node has been moved
7410  */
7411 //================================================================================
7412
7413 bool _LayerEdge::SmoothOnEdge(Handle(ShapeAnalysis_Surface)& surface,
7414                               const TopoDS_Face&             F,
7415                               SMESH_MesherHelper&            helper)
7416 {
7417   ASSERT( IsOnEdge() );
7418
7419   SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
7420   SMESH_TNodeXYZ oldPos( tgtNode );
7421   double dist01, distNewOld;
7422   
7423   SMESH_TNodeXYZ p0( _2neibors->tgtNode(0));
7424   SMESH_TNodeXYZ p1( _2neibors->tgtNode(1));
7425   dist01 = p0.Distance( _2neibors->tgtNode(1) );
7426
7427   gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
7428   double lenDelta = 0;
7429   if ( _curvature )
7430   {
7431     //lenDelta = _curvature->lenDelta( _len );
7432     lenDelta = _curvature->lenDeltaByDist( dist01 );
7433     newPos.ChangeCoord() += _normal * lenDelta;
7434   }
7435
7436   distNewOld = newPos.Distance( oldPos );
7437
7438   if ( F.IsNull() )
7439   {
7440     if ( _2neibors->_plnNorm )
7441     {
7442       // put newPos on the plane defined by source node and _plnNorm
7443       gp_XYZ new2src = SMESH_TNodeXYZ( _nodes[0] ) - newPos.XYZ();
7444       double new2srcProj = (*_2neibors->_plnNorm) * new2src;
7445       newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
7446     }
7447     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7448     _pos.back() = newPos.XYZ();
7449   }
7450   else
7451   {
7452     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7453     gp_XY uv( Precision::Infinite(), 0 );
7454     helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
7455     _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
7456
7457     newPos = surface->Value( uv );
7458     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7459   }
7460
7461   // commented for IPAL0052478
7462   // if ( _curvature && lenDelta < 0 )
7463   // {
7464   //   gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
7465   //   _len -= prevPos.Distance( oldPos );
7466   //   _len += prevPos.Distance( newPos );
7467   // }
7468   bool moved = distNewOld > dist01/50;
7469   //if ( moved )
7470   dumpMove( tgtNode ); // debug
7471
7472   return moved;
7473 }
7474
7475 //================================================================================
7476 /*!
7477  * \brief Perform 3D smooth of nodes inflated from FACE. No check of validity
7478  */
7479 //================================================================================
7480
7481 void _LayerEdge::SmoothWoCheck()
7482 {
7483   if ( Is( DIFFICULT ))
7484     return;
7485
7486   bool moved = Is( SMOOTHED );
7487   for ( size_t i = 0; i < _neibors.size()  &&  !moved; ++i )
7488     moved = _neibors[i]->Is( SMOOTHED );
7489   if ( !moved )
7490     return;
7491
7492   gp_XYZ newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
7493
7494   SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
7495   n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
7496   _pos.back() = newPos;
7497
7498   dumpMoveComm( n, SMESH_Comment("No check - ") << _funNames[ smooFunID() ]);
7499 }
7500
7501 //================================================================================
7502 /*!
7503  * \brief Checks validity of _neibors on EDGEs and VERTEXes
7504  */
7505 //================================================================================
7506
7507 int _LayerEdge::CheckNeiborsOnBoundary( vector< _LayerEdge* >* badNeibors, bool * needSmooth )
7508 {
7509   if ( ! Is( NEAR_BOUNDARY ))
7510     return 0;
7511
7512   int nbBad = 0;
7513   double vol;
7514   for ( size_t iN = 0; iN < _neibors.size(); ++iN )
7515   {
7516     _LayerEdge* eN = _neibors[iN];
7517     if ( eN->_nodes[0]->getshapeId() == _nodes[0]->getshapeId() )
7518       continue;
7519     if ( needSmooth )
7520       *needSmooth |= ( eN->Is( _LayerEdge::BLOCKED ) || eN->Is( _LayerEdge::NORMAL_UPDATED ));
7521
7522     SMESH_TNodeXYZ curPosN ( eN->_nodes.back() );
7523     SMESH_TNodeXYZ prevPosN( eN->_nodes[0] );
7524     for ( size_t i = 0; i < eN->_simplices.size(); ++i )
7525       if ( eN->_nodes.size() > 1 &&
7526            eN->_simplices[i].Includes( _nodes.back() ) &&
7527            !eN->_simplices[i].IsForward( &prevPosN, &curPosN, vol ))
7528       {
7529         ++nbBad;
7530         if ( badNeibors )
7531         {
7532           badNeibors->push_back( eN );
7533           debugMsg("Bad boundary simplex ( "
7534                    << " "<< eN->_nodes[0]->GetID()
7535                    << " "<< eN->_nodes.back()->GetID()
7536                    << " "<< eN->_simplices[i]._nPrev->GetID()
7537                    << " "<< eN->_simplices[i]._nNext->GetID() << " )" );
7538         }
7539         else
7540         {
7541           break;
7542         }
7543       }
7544   }
7545   return nbBad;
7546 }
7547
7548 //================================================================================
7549 /*!
7550  * \brief Perform 'smart' 3D smooth of nodes inflated from FACE
7551  *  \retval int - nb of bad simplices around this _LayerEdge
7552  */
7553 //================================================================================
7554
7555 int _LayerEdge::Smooth(const int step, bool findBest, vector< _LayerEdge* >& toSmooth )
7556 {
7557   if ( !Is( MOVED ) || Is( SMOOTHED ))
7558     return 0; // shape of simplices not changed
7559   if ( _simplices.size() < 2 )
7560     return 0; // _LayerEdge inflated along EDGE or FACE
7561
7562   if ( Is( DIFFICULT )) // || Is( ON_CONCAVE_FACE )
7563     findBest = true;
7564
7565   const gp_XYZ& curPos  = _pos.back();
7566   const gp_XYZ& prevPos = PrevCheckPos();
7567
7568   // quality metrics (orientation) of tetras around _tgtNode
7569   int nbOkBefore = 0;
7570   double vol, minVolBefore = 1e100;
7571   for ( size_t i = 0; i < _simplices.size(); ++i )
7572   {
7573     nbOkBefore += _simplices[i].IsForward( &prevPos, &curPos, vol );
7574     minVolBefore = Min( minVolBefore, vol );
7575   }
7576   int nbBad = _simplices.size() - nbOkBefore;
7577
7578   bool bndNeedSmooth = false;
7579   if ( nbBad == 0 )
7580     nbBad = CheckNeiborsOnBoundary( 0, & bndNeedSmooth );
7581   if ( nbBad > 0 )
7582     Set( DISTORTED );
7583
7584   // evaluate min angle
7585   if ( nbBad == 0 && !findBest && !bndNeedSmooth )
7586   {
7587     size_t nbGoodAngles = _simplices.size();
7588     double angle;
7589     for ( size_t i = 0; i < _simplices.size(); ++i )
7590     {
7591       if ( !_simplices[i].IsMinAngleOK( curPos, angle ) && angle > _minAngle )
7592         --nbGoodAngles;
7593     }
7594     if ( nbGoodAngles == _simplices.size() )
7595     {
7596       Unset( MOVED );
7597       return 0;
7598     }
7599   }
7600   if ( Is( ON_CONCAVE_FACE ))
7601     findBest = true;
7602
7603   if ( step % 2 == 0 )
7604     findBest = false;
7605
7606   if ( Is( ON_CONCAVE_FACE ) && !findBest ) // alternate FUN_CENTROIDAL and FUN_LAPLACIAN
7607   {
7608     if ( _smooFunction == _funs[ FUN_LAPLACIAN ] )
7609       _smooFunction = _funs[ FUN_CENTROIDAL ];
7610     else
7611       _smooFunction = _funs[ FUN_LAPLACIAN ];
7612   }
7613
7614   // compute new position for the last _pos using different _funs
7615   gp_XYZ newPos;
7616   bool moved = false;
7617   for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
7618   {
7619     if ( iFun < 0 )
7620       newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
7621     else if ( _funs[ iFun ] == _smooFunction )
7622       continue; // _smooFunction again
7623     else if ( step > 1 )
7624       newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
7625     else
7626       break; // let "easy" functions improve elements around distorted ones
7627
7628     if ( _curvature )
7629     {
7630       double delta  = _curvature->lenDelta( _len );
7631       if ( delta > 0 )
7632         newPos += _normal * delta;
7633       else
7634       {
7635         double segLen = _normal * ( newPos - prevPos );
7636         if ( segLen + delta > 0 )
7637           newPos += _normal * delta;
7638       }
7639       // double segLenChange = _normal * ( curPos - newPos );
7640       // newPos += 0.5 * _normal * segLenChange;
7641     }
7642
7643     int nbOkAfter = 0;
7644     double minVolAfter = 1e100;
7645     for ( size_t i = 0; i < _simplices.size(); ++i )
7646     {
7647       nbOkAfter += _simplices[i].IsForward( &prevPos, &newPos, vol );
7648       minVolAfter = Min( minVolAfter, vol );
7649     }
7650     // get worse?
7651     if ( nbOkAfter < nbOkBefore )
7652       continue;
7653
7654     if (( findBest ) &&
7655         ( nbOkAfter == nbOkBefore ) &&
7656         ( minVolAfter <= minVolBefore ))
7657       continue;
7658
7659     nbBad        = _simplices.size() - nbOkAfter;
7660     minVolBefore = minVolAfter;
7661     nbOkBefore   = nbOkAfter;
7662     moved        = true;
7663
7664     SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
7665     n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
7666     _pos.back() = newPos;
7667
7668     dumpMoveComm( n, SMESH_Comment( _funNames[ iFun < 0 ? smooFunID() : iFun ] )
7669                   << (nbBad ? " --BAD" : ""));
7670
7671     if ( iFun > -1 )
7672     {
7673       continue; // look for a better function
7674     }
7675
7676     if ( !findBest )
7677       break;
7678
7679   } // loop on smoothing functions
7680
7681   if ( moved ) // notify _neibors
7682   {
7683     Set( SMOOTHED );
7684     for ( size_t i = 0; i < _neibors.size(); ++i )
7685       if ( !_neibors[i]->Is( MOVED ))
7686       {
7687         _neibors[i]->Set( MOVED );
7688         toSmooth.push_back( _neibors[i] );
7689       }
7690   }
7691
7692   return nbBad;
7693 }
7694
7695 //================================================================================
7696 /*!
7697  * \brief Perform 'smart' 3D smooth of nodes inflated from FACE
7698  *  \retval int - nb of bad simplices around this _LayerEdge
7699  */
7700 //================================================================================
7701
7702 int _LayerEdge::Smooth(const int step, const bool isConcaveFace, bool findBest )
7703 {
7704   if ( !_smooFunction )
7705     return 0; // _LayerEdge inflated along EDGE or FACE
7706   if ( Is( BLOCKED ))
7707     return 0; // not inflated
7708
7709   const gp_XYZ& curPos  = _pos.back();
7710   const gp_XYZ& prevPos = PrevCheckPos();
7711
7712   // quality metrics (orientation) of tetras around _tgtNode
7713   int nbOkBefore = 0;
7714   double vol, minVolBefore = 1e100;
7715   for ( size_t i = 0; i < _simplices.size(); ++i )
7716   {
7717     nbOkBefore += _simplices[i].IsForward( &prevPos, &curPos, vol );
7718     minVolBefore = Min( minVolBefore, vol );
7719   }
7720   int nbBad = _simplices.size() - nbOkBefore;
7721
7722   if ( isConcaveFace ) // alternate FUN_CENTROIDAL and FUN_LAPLACIAN
7723   {
7724     if      ( _smooFunction == _funs[ FUN_CENTROIDAL ] && step % 2 )
7725       _smooFunction = _funs[ FUN_LAPLACIAN ];
7726     else if ( _smooFunction == _funs[ FUN_LAPLACIAN ] && !( step % 2 ))
7727       _smooFunction = _funs[ FUN_CENTROIDAL ];
7728   }
7729
7730   // compute new position for the last _pos using different _funs
7731   gp_XYZ newPos;
7732   for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
7733   {
7734     if ( iFun < 0 )
7735       newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
7736     else if ( _funs[ iFun ] == _smooFunction )
7737       continue; // _smooFunction again
7738     else if ( step > 1 )
7739       newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
7740     else
7741       break; // let "easy" functions improve elements around distorted ones
7742
7743     if ( _curvature )
7744     {
7745       double delta  = _curvature->lenDelta( _len );
7746       if ( delta > 0 )
7747         newPos += _normal * delta;
7748       else
7749       {
7750         double segLen = _normal * ( newPos - prevPos );
7751         if ( segLen + delta > 0 )
7752           newPos += _normal * delta;
7753       }
7754       // double segLenChange = _normal * ( curPos - newPos );
7755       // newPos += 0.5 * _normal * segLenChange;
7756     }
7757
7758     int nbOkAfter = 0;
7759     double minVolAfter = 1e100;
7760     for ( size_t i = 0; i < _simplices.size(); ++i )
7761     {
7762       nbOkAfter += _simplices[i].IsForward( &prevPos, &newPos, vol );
7763       minVolAfter = Min( minVolAfter, vol );
7764     }
7765     // get worse?
7766     if ( nbOkAfter < nbOkBefore )
7767       continue;
7768     if (( isConcaveFace || findBest ) &&
7769         ( nbOkAfter == nbOkBefore ) &&
7770         ( minVolAfter <= minVolBefore )
7771         )
7772       continue;
7773
7774     nbBad        = _simplices.size() - nbOkAfter;
7775     minVolBefore = minVolAfter;
7776     nbOkBefore   = nbOkAfter;
7777
7778     SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
7779     n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
7780     _pos.back() = newPos;
7781
7782     dumpMoveComm( n, SMESH_Comment( _funNames[ iFun < 0 ? smooFunID() : iFun ] )
7783                   << ( nbBad ? "--BAD" : ""));
7784
7785     // commented for IPAL0052478
7786     // _len -= prevPos.Distance(SMESH_TNodeXYZ( n ));
7787     // _len += prevPos.Distance(newPos);
7788
7789     if ( iFun > -1 ) // findBest || the chosen _fun makes worse
7790     {
7791       //_smooFunction = _funs[ iFun ];
7792       // cout << "# " << _funNames[ iFun ] << "\t N:" << _nodes.back()->GetID()
7793       // << "\t nbBad: " << _simplices.size() - nbOkAfter
7794       // << " minVol: " << minVolAfter
7795       // << " " << newPos.X() << " " << newPos.Y() << " " << newPos.Z()
7796       // << endl;
7797       continue; // look for a better function
7798     }
7799
7800     if ( !findBest )
7801       break;
7802
7803   } // loop on smoothing functions
7804
7805   return nbBad;
7806 }
7807
7808 //================================================================================
7809 /*!
7810  * \brief Chooses a smoothing technic giving a position most close to an initial one.
7811  *        For a correct result, _simplices must contain nodes lying on geometry.
7812  */
7813 //================================================================================
7814
7815 void _LayerEdge::ChooseSmooFunction( const set< TGeomID >& concaveVertices,
7816                                      const TNode2Edge&     n2eMap)
7817 {
7818   if ( _smooFunction ) return;
7819
7820   // use smoothNefPolygon() near concaveVertices
7821   if ( !concaveVertices.empty() )
7822   {
7823     _smooFunction = _funs[ FUN_CENTROIDAL ];
7824
7825     Set( ON_CONCAVE_FACE );
7826
7827     for ( size_t i = 0; i < _simplices.size(); ++i )
7828     {
7829       if ( concaveVertices.count( _simplices[i]._nPrev->getshapeId() ))
7830       {
7831         _smooFunction = _funs[ FUN_NEFPOLY ];
7832
7833         // set FUN_CENTROIDAL to neighbor edges
7834         for ( i = 0; i < _neibors.size(); ++i )
7835         {
7836           if ( _neibors[i]->_nodes[0]->GetPosition()->GetDim() == 2 )
7837           {
7838             _neibors[i]->_smooFunction = _funs[ FUN_CENTROIDAL ];
7839           }
7840         }
7841         return;
7842       }
7843     }
7844
7845     // // this coice is done only if ( !concaveVertices.empty() ) for Grids/smesh/bugs_19/X1
7846     // // where the nodes are smoothed too far along a sphere thus creating
7847     // // inverted _simplices
7848     // double dist[theNbSmooFuns];
7849     // //double coef[theNbSmooFuns] = { 1., 1.2, 1.4, 1.4 };
7850     // double coef[theNbSmooFuns] = { 1., 1., 1., 1. };
7851
7852     // double minDist = Precision::Infinite();
7853     // gp_Pnt p = SMESH_TNodeXYZ( _nodes[0] );
7854     // for ( int i = 0; i < FUN_NEFPOLY; ++i )
7855     // {
7856     //   gp_Pnt newP = (this->*_funs[i])();
7857     //   dist[i] = p.SquareDistance( newP );
7858     //   if ( dist[i]*coef[i] < minDist )
7859     //   {
7860     //     _smooFunction = _funs[i];
7861     //     minDist = dist[i]*coef[i];
7862     //   }
7863     // }
7864   }
7865   else
7866   {
7867     _smooFunction = _funs[ FUN_LAPLACIAN ];
7868   }
7869   // int minDim = 3;
7870   // for ( size_t i = 0; i < _simplices.size(); ++i )
7871   //   minDim = Min( minDim, _simplices[i]._nPrev->GetPosition()->GetDim() );
7872   // if ( minDim == 0 )
7873   //   _smooFunction = _funs[ FUN_CENTROIDAL ];
7874   // else if ( minDim == 1 )
7875   //   _smooFunction = _funs[ FUN_CENTROIDAL ];
7876
7877
7878   // int iMin;
7879   // for ( int i = 0; i < FUN_NB; ++i )
7880   // {
7881   //   //cout << dist[i] << " ";
7882   //   if ( _smooFunction == _funs[i] ) {
7883   //     iMin = i;
7884   //     //debugMsg( fNames[i] );
7885   //     break;
7886   //   }
7887   // }
7888   // cout << _funNames[ iMin ] << "\t N:" << _nodes.back()->GetID() << endl;
7889 }
7890
7891 //================================================================================
7892 /*!
7893  * \brief Returns a name of _SmooFunction
7894  */
7895 //================================================================================
7896
7897 int _LayerEdge::smooFunID( _LayerEdge::PSmooFun fun) const
7898 {
7899   if ( !fun )
7900     fun = _smooFunction;
7901   for ( int i = 0; i < theNbSmooFuns; ++i )
7902     if ( fun == _funs[i] )
7903       return i;
7904
7905   return theNbSmooFuns;
7906 }
7907
7908 //================================================================================
7909 /*!
7910  * \brief Computes a new node position using Laplacian smoothing
7911  */
7912 //================================================================================
7913
7914 gp_XYZ _LayerEdge::smoothLaplacian()
7915 {
7916   gp_XYZ newPos (0,0,0);
7917   for ( size_t i = 0; i < _simplices.size(); ++i )
7918     newPos += SMESH_TNodeXYZ( _simplices[i]._nPrev );
7919   newPos /= _simplices.size();
7920
7921   return newPos;
7922 }
7923
7924 //================================================================================
7925 /*!
7926  * \brief Computes a new node position using angular-based smoothing
7927  */
7928 //================================================================================
7929
7930 gp_XYZ _LayerEdge::smoothAngular()
7931 {
7932   vector< gp_Vec > edgeDir;  edgeDir. reserve( _simplices.size() + 1 );
7933   vector< double > edgeSize; edgeSize.reserve( _simplices.size()     );
7934   vector< gp_XYZ > points;   points.  reserve( _simplices.size() + 1 );
7935
7936   gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
7937   gp_XYZ pN( 0,0,0 );
7938   for ( size_t i = 0; i < _simplices.size(); ++i )
7939   {
7940     gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
7941     edgeDir.push_back( p - pPrev );
7942     edgeSize.push_back( edgeDir.back().Magnitude() );
7943     if ( edgeSize.back() < numeric_limits<double>::min() )
7944     {
7945       edgeDir.pop_back();
7946       edgeSize.pop_back();
7947     }
7948     else
7949     {
7950       edgeDir.back() /= edgeSize.back();
7951       points.push_back( p );
7952       pN += p;
7953     }
7954     pPrev = p;
7955   }
7956   edgeDir.push_back ( edgeDir[0] );
7957   edgeSize.push_back( edgeSize[0] );
7958   pN /= points.size();
7959
7960   gp_XYZ newPos(0,0,0);
7961   double sumSize = 0;
7962   for ( size_t i = 0; i < points.size(); ++i )
7963   {
7964     gp_Vec toN    = pN - points[i];
7965     double toNLen = toN.Magnitude();
7966     if ( toNLen < numeric_limits<double>::min() )
7967     {
7968       newPos += pN;
7969       continue;
7970     }
7971     gp_Vec bisec    = edgeDir[i] + edgeDir[i+1];
7972     double bisecLen = bisec.SquareMagnitude();
7973     if ( bisecLen < numeric_limits<double>::min() )
7974     {
7975       gp_Vec norm = edgeDir[i] ^ toN;
7976       bisec = norm ^ edgeDir[i];
7977       bisecLen = bisec.SquareMagnitude();
7978     }
7979     bisecLen = Sqrt( bisecLen );
7980     bisec /= bisecLen;
7981
7982 #if 1
7983     gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * bisecLen;
7984     sumSize += bisecLen;
7985 #else
7986     gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * ( edgeSize[i] + edgeSize[i+1] );
7987     sumSize += ( edgeSize[i] + edgeSize[i+1] );
7988 #endif
7989     newPos += pNew;
7990   }
7991   newPos /= sumSize;
7992
7993   // project newPos to an average plane
7994
7995   gp_XYZ norm(0,0,0); // plane normal
7996   points.push_back( points[0] );
7997   for ( size_t i = 1; i < points.size(); ++i )
7998   {
7999     gp_XYZ vec1 = points[ i-1 ] - pN;
8000     gp_XYZ vec2 = points[ i   ] - pN;
8001     gp_XYZ cross = vec1 ^ vec2;
8002     try {
8003       cross.Normalize();
8004       if ( cross * norm < numeric_limits<double>::min() )
8005         norm += cross.Reversed();
8006       else
8007         norm += cross;
8008     }
8009     catch (Standard_Failure) { // if |cross| == 0.
8010     }
8011   }
8012   gp_XYZ vec = newPos - pN;
8013   double r   = ( norm * vec ) / norm.SquareModulus();  // param [0,1] on norm
8014   newPos     = newPos - r * norm;
8015
8016   return newPos;
8017 }
8018
8019 //================================================================================
8020 /*!
8021  * \brief Computes a new node position using weigthed node positions
8022  */
8023 //================================================================================
8024
8025 gp_XYZ _LayerEdge::smoothLengthWeighted()
8026 {
8027   vector< double > edgeSize; edgeSize.reserve( _simplices.size() + 1);
8028   vector< gp_XYZ > points;   points.  reserve( _simplices.size() );
8029
8030   gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
8031   for ( size_t i = 0; i < _simplices.size(); ++i )
8032   {
8033     gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
8034     edgeSize.push_back( ( p - pPrev ).Modulus() );
8035     if ( edgeSize.back() < numeric_limits<double>::min() )
8036     {
8037       edgeSize.pop_back();
8038     }
8039     else
8040     {
8041       points.push_back( p );
8042     }
8043     pPrev = p;
8044   }
8045   edgeSize.push_back( edgeSize[0] );
8046
8047   gp_XYZ newPos(0,0,0);
8048   double sumSize = 0;
8049   for ( size_t i = 0; i < points.size(); ++i )
8050   {
8051     newPos += points[i] * ( edgeSize[i] + edgeSize[i+1] );
8052     sumSize += edgeSize[i] + edgeSize[i+1];
8053   }
8054   newPos /= sumSize;
8055   return newPos;
8056 }
8057
8058 //================================================================================
8059 /*!
8060  * \brief Computes a new node position using angular-based smoothing
8061  */
8062 //================================================================================
8063
8064 gp_XYZ _LayerEdge::smoothCentroidal()
8065 {
8066   gp_XYZ newPos(0,0,0);
8067   gp_XYZ pN = SMESH_TNodeXYZ( _nodes.back() );
8068   double sumSize = 0;
8069   for ( size_t i = 0; i < _simplices.size(); ++i )
8070   {
8071     gp_XYZ p1 = SMESH_TNodeXYZ( _simplices[i]._nPrev );
8072     gp_XYZ p2 = SMESH_TNodeXYZ( _simplices[i]._nNext );
8073     gp_XYZ gc = ( pN + p1 + p2 ) / 3.;
8074     double size = (( p1 - pN ) ^ ( p2 - pN )).Modulus();
8075
8076     sumSize += size;
8077     newPos += gc * size;
8078   }
8079   newPos /= sumSize;
8080
8081   return newPos;
8082 }
8083
8084 //================================================================================
8085 /*!
8086  * \brief Computes a new node position located inside a Nef polygon
8087  */
8088 //================================================================================
8089
8090 gp_XYZ _LayerEdge::smoothNefPolygon()
8091 #ifdef OLD_NEF_POLYGON
8092 {
8093   gp_XYZ newPos(0,0,0);
8094
8095   // get a plane to seach a solution on
8096
8097   vector< gp_XYZ > vecs( _simplices.size() + 1 );
8098   size_t i;
8099   const double tol = numeric_limits<double>::min();
8100   gp_XYZ center(0,0,0);
8101   for ( i = 0; i < _simplices.size(); ++i )
8102   {
8103     vecs[i] = ( SMESH_TNodeXYZ( _simplices[i]._nNext ) -
8104                 SMESH_TNodeXYZ( _simplices[i]._nPrev ));
8105     center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
8106   }
8107   vecs.back() = vecs[0];
8108   center /= _simplices.size();
8109
8110   gp_XYZ zAxis(0,0,0);
8111   for ( i = 0; i < _simplices.size(); ++i )
8112     zAxis += vecs[i] ^ vecs[i+1];
8113
8114   gp_XYZ yAxis;
8115   for ( i = 0; i < _simplices.size(); ++i )
8116   {
8117     yAxis = vecs[i];
8118     if ( yAxis.SquareModulus() > tol )
8119       break;
8120   }
8121   gp_XYZ xAxis = yAxis ^ zAxis;
8122   // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
8123   // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
8124   //                             p0.Distance( _simplices[2]._nPrev ));
8125   // gp_XYZ center = smoothLaplacian();
8126   // gp_XYZ xAxis, yAxis, zAxis;
8127   // for ( i = 0; i < _simplices.size(); ++i )
8128   // {
8129   //   xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8130   //   if ( xAxis.SquareModulus() > tol*tol )
8131   //     break;
8132   // }
8133   // for ( i = 1; i < _simplices.size(); ++i )
8134   // {
8135   //   yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8136   //   zAxis = xAxis ^ yAxis;
8137   //   if ( zAxis.SquareModulus() > tol*tol )
8138   //     break;
8139   // }
8140   // if ( i == _simplices.size() ) return newPos;
8141
8142   yAxis = zAxis ^ xAxis;
8143   xAxis /= xAxis.Modulus();
8144   yAxis /= yAxis.Modulus();
8145
8146   // get half-planes of _simplices
8147
8148   vector< _halfPlane > halfPlns( _simplices.size() );
8149   int nbHP = 0;
8150   for ( size_t i = 0; i < _simplices.size(); ++i )
8151   {
8152     gp_XYZ OP1 = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8153     gp_XYZ OP2 = SMESH_TNodeXYZ( _simplices[i]._nNext ) - center;
8154     gp_XY  p1( OP1 * xAxis, OP1 * yAxis );
8155     gp_XY  p2( OP2 * xAxis, OP2 * yAxis );
8156     gp_XY  vec12 = p2 - p1;
8157     double dist12 = vec12.Modulus();
8158     if ( dist12 < tol )
8159       continue;
8160     vec12 /= dist12;
8161     halfPlns[ nbHP ]._pos = p1;
8162     halfPlns[ nbHP ]._dir = vec12;
8163     halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
8164     ++nbHP;
8165   }
8166
8167   // intersect boundaries of half-planes, define state of intersection points
8168   // in relation to all half-planes and calculate internal point of a 2D polygon
8169
8170   double sumLen = 0;
8171   gp_XY newPos2D (0,0);
8172
8173   enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
8174   typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
8175   TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
8176
8177   vector< vector< TIntPntState > > allIntPnts( nbHP );
8178   for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
8179   {
8180     vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
8181     if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
8182
8183     int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
8184     int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
8185
8186     int nbNotOut = 0;
8187     const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
8188
8189     for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
8190     {
8191       if ( iHP1 == iHP2 ) continue;
8192
8193       TIntPntState & ips1 = intPnts1[ iHP2 ];
8194       if ( ips1.second == UNDEF )
8195       {
8196         // find an intersection point of boundaries of iHP1 and iHP2
8197
8198         if ( iHP2 == iPrev ) // intersection with neighbors is known
8199           ips1.first = halfPlns[ iHP1 ]._pos;
8200         else if ( iHP2 == iNext )
8201           ips1.first = halfPlns[ iHP2 ]._pos;
8202         else if ( !halfPlns[ iHP1 ].FindIntersection( halfPlns[ iHP2 ], ips1.first ))
8203           ips1.second = NO_INT;
8204
8205         // classify the found intersection point
8206         if ( ips1.second != NO_INT )
8207         {
8208           ips1.second = NOT_OUT;
8209           for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
8210             if ( i != iHP1 && i != iHP2 &&
8211                  halfPlns[ i ].IsOut( ips1.first, tol ))
8212               ips1.second = IS_OUT;
8213         }
8214         vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
8215         if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
8216         TIntPntState & ips2 = intPnts2[ iHP1 ];
8217         ips2 = ips1;
8218       }
8219       if ( ips1.second == NOT_OUT )
8220       {
8221         ++nbNotOut;
8222         segEnds[ bool(segEnds[0]) ] = & ips1.first;
8223       }
8224     }
8225
8226     // find a NOT_OUT segment of boundary which is located between
8227     // two NOT_OUT int points
8228
8229     if ( nbNotOut < 2 )
8230       continue; // no such a segment
8231
8232     if ( nbNotOut > 2 )
8233     {
8234       // sort points along the boundary
8235       map< double, TIntPntState* > ipsByParam;
8236       for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
8237       {
8238         TIntPntState & ips1 = intPnts1[ iHP2 ];
8239         if ( ips1.second != NO_INT )
8240         {
8241           gp_XY     op = ips1.first - halfPlns[ iHP1 ]._pos;
8242           double param = op * halfPlns[ iHP1 ]._dir;
8243           ipsByParam.insert( make_pair( param, & ips1 ));
8244         }
8245       }
8246       // look for two neighboring NOT_OUT points
8247       nbNotOut = 0;
8248       map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
8249       for ( ; u2ips != ipsByParam.end(); ++u2ips )
8250       {
8251         TIntPntState & ips1 = *(u2ips->second);
8252         if ( ips1.second == NOT_OUT )
8253           segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
8254         else if ( nbNotOut >= 2 )
8255           break;
8256         else
8257           nbNotOut = 0;
8258       }
8259     }
8260
8261     if ( nbNotOut >= 2 )
8262     {
8263       double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
8264       sumLen += len;
8265
8266       newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
8267     }
8268   }
8269
8270   if ( sumLen > 0 )
8271   {
8272     newPos2D /= sumLen;
8273     newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
8274   }
8275   else
8276   {
8277     newPos = center;
8278   }
8279
8280   return newPos;
8281 }
8282 #else // OLD_NEF_POLYGON
8283 { ////////////////////////////////// NEW
8284   gp_XYZ newPos(0,0,0);
8285
8286   // get a plane to seach a solution on
8287
8288   size_t i;
8289   gp_XYZ center(0,0,0);
8290   for ( i = 0; i < _simplices.size(); ++i )
8291     center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
8292   center /= _simplices.size();
8293
8294   vector< gp_XYZ > vecs( _simplices.size() + 1 );
8295   for ( i = 0; i < _simplices.size(); ++i )
8296     vecs[i] = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8297   vecs.back() = vecs[0];
8298
8299   const double tol = numeric_limits<double>::min();
8300   gp_XYZ zAxis(0,0,0);
8301   for ( i = 0; i < _simplices.size(); ++i )
8302   {
8303     gp_XYZ cross = vecs[i] ^ vecs[i+1];
8304     try {
8305       cross.Normalize();
8306       if ( cross * zAxis < tol )
8307         zAxis += cross.Reversed();
8308       else
8309         zAxis += cross;
8310     }
8311     catch (Standard_Failure) { // if |cross| == 0.
8312     }
8313   }
8314
8315   gp_XYZ yAxis;
8316   for ( i = 0; i < _simplices.size(); ++i )
8317   {
8318     yAxis = vecs[i];
8319     if ( yAxis.SquareModulus() > tol )
8320       break;
8321   }
8322   gp_XYZ xAxis = yAxis ^ zAxis;
8323   // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
8324   // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
8325   //                             p0.Distance( _simplices[2]._nPrev ));
8326   // gp_XYZ center = smoothLaplacian();
8327   // gp_XYZ xAxis, yAxis, zAxis;
8328   // for ( i = 0; i < _simplices.size(); ++i )
8329   // {
8330   //   xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8331   //   if ( xAxis.SquareModulus() > tol*tol )
8332   //     break;
8333   // }
8334   // for ( i = 1; i < _simplices.size(); ++i )
8335   // {
8336   //   yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8337   //   zAxis = xAxis ^ yAxis;
8338   //   if ( zAxis.SquareModulus() > tol*tol )
8339   //     break;
8340   // }
8341   // if ( i == _simplices.size() ) return newPos;
8342
8343   yAxis = zAxis ^ xAxis;
8344   xAxis /= xAxis.Modulus();
8345   yAxis /= yAxis.Modulus();
8346
8347   // get half-planes of _simplices
8348
8349   vector< _halfPlane > halfPlns( _simplices.size() );
8350   int nbHP = 0;
8351   for ( size_t i = 0; i < _simplices.size(); ++i )
8352   {
8353     const gp_XYZ& OP1 = vecs[ i   ];
8354     const gp_XYZ& OP2 = vecs[ i+1 ];
8355     gp_XY  p1( OP1 * xAxis, OP1 * yAxis );
8356     gp_XY  p2( OP2 * xAxis, OP2 * yAxis );
8357     gp_XY  vec12 = p2 - p1;
8358     double dist12 = vec12.Modulus();
8359     if ( dist12 < tol )
8360       continue;
8361     vec12 /= dist12;
8362     halfPlns[ nbHP ]._pos = p1;
8363     halfPlns[ nbHP ]._dir = vec12;
8364     halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
8365     ++nbHP;
8366   }
8367
8368   // intersect boundaries of half-planes, define state of intersection points
8369   // in relation to all half-planes and calculate internal point of a 2D polygon
8370
8371   double sumLen = 0;
8372   gp_XY newPos2D (0,0);
8373
8374   enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
8375   typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
8376   TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
8377
8378   vector< vector< TIntPntState > > allIntPnts( nbHP );
8379   for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
8380   {
8381     vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
8382     if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
8383
8384     int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
8385     int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
8386
8387     int nbNotOut = 0;
8388     const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
8389
8390     for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
8391     {
8392       if ( iHP1 == iHP2 ) continue;
8393
8394       TIntPntState & ips1 = intPnts1[ iHP2 ];
8395       if ( ips1.second == UNDEF )
8396       {
8397         // find an intersection point of boundaries of iHP1 and iHP2
8398
8399         if ( iHP2 == iPrev ) // intersection with neighbors is known
8400           ips1.first = halfPlns[ iHP1 ]._pos;
8401         else if ( iHP2 == iNext )
8402           ips1.first = halfPlns[ iHP2 ]._pos;
8403         else if ( !halfPlns[ iHP1 ].FindIntersection( halfPlns[ iHP2 ], ips1.first ))
8404           ips1.second = NO_INT;
8405
8406         // classify the found intersection point
8407         if ( ips1.second != NO_INT )
8408         {
8409           ips1.second = NOT_OUT;
8410           for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
8411             if ( i != iHP1 && i != iHP2 &&
8412                  halfPlns[ i ].IsOut( ips1.first, tol ))
8413               ips1.second = IS_OUT;
8414         }
8415         vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
8416         if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
8417         TIntPntState & ips2 = intPnts2[ iHP1 ];
8418         ips2 = ips1;
8419       }
8420       if ( ips1.second == NOT_OUT )
8421       {
8422         ++nbNotOut;
8423         segEnds[ bool(segEnds[0]) ] = & ips1.first;
8424       }
8425     }
8426
8427     // find a NOT_OUT segment of boundary which is located between
8428     // two NOT_OUT int points
8429
8430     if ( nbNotOut < 2 )
8431       continue; // no such a segment
8432
8433     if ( nbNotOut > 2 )
8434     {
8435       // sort points along the boundary
8436       map< double, TIntPntState* > ipsByParam;
8437       for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
8438       {
8439         TIntPntState & ips1 = intPnts1[ iHP2 ];
8440         if ( ips1.second != NO_INT )
8441         {
8442           gp_XY     op = ips1.first - halfPlns[ iHP1 ]._pos;
8443           double param = op * halfPlns[ iHP1 ]._dir;
8444           ipsByParam.insert( make_pair( param, & ips1 ));
8445         }
8446       }
8447       // look for two neighboring NOT_OUT points
8448       nbNotOut = 0;
8449       map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
8450       for ( ; u2ips != ipsByParam.end(); ++u2ips )
8451       {
8452         TIntPntState & ips1 = *(u2ips->second);
8453         if ( ips1.second == NOT_OUT )
8454           segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
8455         else if ( nbNotOut >= 2 )
8456           break;
8457         else
8458           nbNotOut = 0;
8459       }
8460     }
8461
8462     if ( nbNotOut >= 2 )
8463     {
8464       double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
8465       sumLen += len;
8466
8467       newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
8468     }
8469   }
8470
8471   if ( sumLen > 0 )
8472   {
8473     newPos2D /= sumLen;
8474     newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
8475   }
8476   else
8477   {
8478     newPos = center;
8479   }
8480
8481   return newPos;
8482 }
8483 #endif // OLD_NEF_POLYGON
8484
8485 //================================================================================
8486 /*!
8487  * \brief Add a new segment to _LayerEdge during inflation
8488  */
8489 //================================================================================
8490
8491 void _LayerEdge::SetNewLength( double len, _EdgesOnShape& eos, SMESH_MesherHelper& helper )
8492 {
8493   if ( Is( BLOCKED ))
8494     return;
8495
8496   if ( len > _maxLen )
8497   {
8498     len = _maxLen;
8499     Block( eos.GetData() );
8500   }
8501   const double lenDelta = len - _len;
8502   if ( lenDelta < len * 1e-3  )
8503   {
8504     Block( eos.GetData() );
8505     return;
8506   }
8507
8508   SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
8509   gp_XYZ oldXYZ = SMESH_TNodeXYZ( n );
8510   gp_XYZ newXYZ;
8511   if ( eos._hyp.IsOffsetMethod() )
8512   {
8513     newXYZ = oldXYZ;
8514     gp_Vec faceNorm;
8515     SMDS_ElemIteratorPtr faceIt = _nodes[0]->GetInverseElementIterator( SMDSAbs_Face );
8516     while ( faceIt->more() )
8517     {
8518       const SMDS_MeshElement* face = faceIt->next();
8519       if ( !eos.GetNormal( face, faceNorm ))
8520         continue;
8521
8522       // translate plane of a face
8523       gp_XYZ baryCenter = oldXYZ + faceNorm.XYZ() * lenDelta;
8524
8525       // find point of intersection of the face plane located at baryCenter
8526       // and _normal located at newXYZ
8527       double d    = -( faceNorm.XYZ() * baryCenter ); // d of plane equation ax+by+cz+d=0
8528       double dot  = ( faceNorm.XYZ() * _normal );
8529       if ( dot < std::numeric_limits<double>::min() )
8530         dot = lenDelta * 1e-3;
8531       double step = -( faceNorm.XYZ() * newXYZ + d ) / dot;
8532       newXYZ += step * _normal;
8533     }
8534   }
8535   else
8536   {
8537     newXYZ = oldXYZ + _normal * lenDelta * _lenFactor;
8538   }
8539
8540   n->setXYZ( newXYZ.X(), newXYZ.Y(), newXYZ.Z() );
8541   _pos.push_back( newXYZ );
8542
8543   if ( !eos._sWOL.IsNull() )
8544   {
8545     double distXYZ[4];
8546     bool uvOK = false;
8547     if ( eos.SWOLType() == TopAbs_EDGE )
8548     {
8549       double u = Precision::Infinite(); // to force projection w/o distance check
8550       uvOK = helper.CheckNodeU( TopoDS::Edge( eos._sWOL ), n, u,
8551                                 /*tol=*/2*lenDelta, /*force=*/true, distXYZ );
8552       _pos.back().SetCoord( u, 0, 0 );
8553       if ( _nodes.size() > 1 && uvOK )
8554       {
8555         SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
8556         pos->SetUParameter( u );
8557       }
8558     }
8559     else //  TopAbs_FACE
8560     {
8561       gp_XY uv( Precision::Infinite(), 0 );
8562       uvOK = helper.CheckNodeUV( TopoDS::Face( eos._sWOL ), n, uv,
8563                                  /*tol=*/2*lenDelta, /*force=*/true, distXYZ );
8564       _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
8565       if ( _nodes.size() > 1 && uvOK )
8566       {
8567         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
8568         pos->SetUParameter( uv.X() );
8569         pos->SetVParameter( uv.Y() );
8570       }
8571     }
8572     if ( uvOK )
8573     {
8574       n->setXYZ( distXYZ[1], distXYZ[2], distXYZ[3]);
8575     }
8576     else
8577     {
8578       n->setXYZ( oldXYZ.X(), oldXYZ.Y(), oldXYZ.Z() );
8579       _pos.pop_back();
8580       Block( eos.GetData() );
8581       return;
8582     }
8583   }
8584
8585   _len = len;
8586
8587   // notify _neibors
8588   if ( eos.ShapeType() != TopAbs_FACE )
8589   {
8590     for ( size_t i = 0; i < _neibors.size(); ++i )
8591       //if (  _len > _neibors[i]->GetSmooLen() )
8592         _neibors[i]->Set( MOVED );
8593
8594     Set( MOVED );
8595   }
8596   dumpMove( n ); //debug
8597 }
8598
8599 //================================================================================
8600 /*!
8601  * \brief Set BLOCKED flag and propagate limited _maxLen to _neibors
8602  */
8603 //================================================================================
8604
8605 void _LayerEdge::Block( _SolidData& data )
8606 {
8607   if ( Is( BLOCKED )) return;
8608   Set( BLOCKED );
8609
8610   _maxLen = _len;
8611   std::queue<_LayerEdge*> queue;
8612   queue.push( this );
8613
8614   gp_Pnt pSrc, pTgt, pSrcN, pTgtN;
8615   while ( !queue.empty() )
8616   {
8617     _LayerEdge* edge = queue.front(); queue.pop();
8618     pSrc = SMESH_TNodeXYZ( edge->_nodes[0] );
8619     pTgt = SMESH_TNodeXYZ( edge->_nodes.back() );
8620     for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
8621     {
8622       _LayerEdge* neibor = edge->_neibors[iN];
8623       if ( neibor->Is( BLOCKED ) ||
8624            neibor->_maxLen < edge->_maxLen )
8625         continue;
8626       pSrcN = SMESH_TNodeXYZ( neibor->_nodes[0] );
8627       pTgtN = SMESH_TNodeXYZ( neibor->_nodes.back() );
8628       double minDist = pSrc.SquareDistance( pSrcN );
8629       minDist   = Min( pTgt.SquareDistance( pTgtN ), minDist );
8630       minDist   = Min( pSrc.SquareDistance( pTgtN ), minDist );
8631       minDist   = Min( pTgt.SquareDistance( pSrcN ), minDist );
8632       double newMaxLen = edge->_maxLen + 0.5 * Sqrt( minDist );
8633       if ( neibor->_maxLen > newMaxLen )
8634       {
8635         neibor->_maxLen = newMaxLen;
8636         if ( neibor->_maxLen < neibor->_len )
8637         {
8638           _EdgesOnShape* eos = data.GetShapeEdges( neibor );
8639           neibor->InvalidateStep( neibor->NbSteps(), *eos, /*restoreLength=*/true );
8640           neibor->SetNewLength( neibor->_maxLen, *eos, data.GetHelper() );
8641         }
8642         queue.push( neibor );
8643       }
8644     }
8645   }
8646 }
8647
8648 //================================================================================
8649 /*!
8650  * \brief Remove last inflation step
8651  */
8652 //================================================================================
8653
8654 void _LayerEdge::InvalidateStep( size_t curStep, const _EdgesOnShape& eos, bool restoreLength )
8655 {
8656   if ( _pos.size() > curStep && _nodes.size() > 1 )
8657   {
8658     _pos.resize( curStep );
8659
8660     gp_Pnt      nXYZ = _pos.back();
8661     SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
8662     SMESH_TNodeXYZ curXYZ( n );
8663     if ( !eos._sWOL.IsNull() )
8664     {
8665       TopLoc_Location loc;
8666       if ( eos.SWOLType() == TopAbs_EDGE )
8667       {
8668         SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
8669         pos->SetUParameter( nXYZ.X() );
8670         double f,l;
8671         Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eos._sWOL ), loc, f,l);
8672         nXYZ = curve->Value( nXYZ.X() ).Transformed( loc );
8673       }
8674       else
8675       {
8676         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
8677         pos->SetUParameter( nXYZ.X() );
8678         pos->SetVParameter( nXYZ.Y() );
8679         Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(eos._sWOL), loc );
8680         nXYZ = surface->Value( nXYZ.X(), nXYZ.Y() ).Transformed( loc );
8681       }
8682     }
8683     n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
8684     dumpMove( n );
8685
8686     if ( restoreLength )
8687     {
8688       _len -= ( nXYZ.XYZ() - curXYZ ).Modulus() / _lenFactor;
8689     }
8690   }
8691 }
8692
8693 //================================================================================
8694 /*!
8695  * \brief Smooth a path formed by _pos of a _LayerEdge smoothed on FACE
8696  */
8697 //================================================================================
8698
8699 void _LayerEdge::SmoothPos( const vector< double >& segLen, const double tol )
8700 {
8701   //return;
8702   if ( Is( NORMAL_UPDATED ) || _pos.size() <= 2 )
8703     return;
8704
8705   // find the 1st smoothed _pos
8706   int iSmoothed = 0;
8707   for ( size_t i = 1; i < _pos.size() && !iSmoothed; ++i )
8708   {
8709     double normDist = ( _pos[i] - _pos[0] ).Crossed( _normal ).SquareModulus();
8710     if ( normDist > tol * tol )
8711       iSmoothed = i;
8712   }
8713   if ( !iSmoothed ) return;
8714
8715   if ( 1 || Is( DISTORTED ))
8716   {
8717     // if ( segLen[ iSmoothed ] / segLen.back() < 0.5 )
8718     //   return;
8719     for ( size_t i = Max( 1, iSmoothed-1 ); i < _pos.size()-1; ++i )
8720     {
8721       gp_XYZ midPos = 0.5 * ( _pos[i-1] + _pos[i+1] );
8722       gp_XYZ newPos = 0.5 * ( midPos + _pos[i] );
8723       _pos[i] = newPos;
8724       double midLen = 0.5 * ( segLen[i-1] + segLen[i+1] );
8725       double newLen = 0.5 * ( midLen + segLen[i] );
8726       const_cast< double& >( segLen[i] ) = newLen;
8727     }
8728   }
8729   else
8730   {
8731     for ( size_t i = 1; i < _pos.size()-1; ++i )
8732     {
8733       if ((int) i < iSmoothed  &&  ( segLen[i] / segLen.back() < 0.5 ))
8734         continue;
8735
8736       double     wgt = segLen[i] / segLen.back();
8737       gp_XYZ normPos = _pos[0] + _normal * wgt * _len;
8738       gp_XYZ tgtPos  = ( 1 - wgt ) * _pos[0] +  wgt * _pos.back();
8739       gp_XYZ newPos  = ( 1 - wgt ) * normPos +  wgt * tgtPos;
8740       _pos[i] = newPos;
8741     }
8742   }
8743 }
8744
8745 //================================================================================
8746 /*!
8747  * \brief Create layers of prisms
8748  */
8749 //================================================================================
8750
8751 bool _ViscousBuilder::refine(_SolidData& data)
8752 {
8753   SMESH_MesherHelper& helper = data.GetHelper();
8754   helper.SetElementsOnShape(false);
8755
8756   Handle(Geom_Curve) curve;
8757   Handle(ShapeAnalysis_Surface) surface;
8758   TopoDS_Edge geomEdge;
8759   TopoDS_Face geomFace;
8760   TopLoc_Location loc;
8761   double f,l, u;
8762   gp_XY uv;
8763   vector< gp_XYZ > pos3D;
8764   bool isOnEdge;
8765   TGeomID prevBaseId = -1;
8766   TNode2Edge* n2eMap = 0;
8767   TNode2Edge::iterator n2e;
8768
8769   // Create intermediate nodes on each _LayerEdge
8770
8771   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
8772   {
8773     _EdgesOnShape& eos = data._edgesOnShape[iS];
8774     if ( eos._edges.empty() ) continue;
8775
8776     if ( eos._edges[0]->_nodes.size() < 2 )
8777       continue; // on _noShrinkShapes
8778
8779     // get data of a shrink shape
8780     isOnEdge = false;
8781     geomEdge.Nullify(); geomFace.Nullify();
8782     curve.Nullify(); surface.Nullify();
8783     if ( !eos._sWOL.IsNull() )
8784     {
8785       isOnEdge = ( eos.SWOLType() == TopAbs_EDGE );
8786       if ( isOnEdge )
8787       {
8788         geomEdge = TopoDS::Edge( eos._sWOL );
8789         curve    = BRep_Tool::Curve( geomEdge, loc, f,l);
8790       }
8791       else
8792       {
8793         geomFace = TopoDS::Face( eos._sWOL );
8794         surface  = helper.GetSurface( geomFace );
8795       }
8796     }
8797     else if ( eos.ShapeType() == TopAbs_FACE && eos._toSmooth )
8798     {
8799       geomFace = TopoDS::Face( eos._shape );
8800       surface  = helper.GetSurface( geomFace );
8801       // propagate _toSmooth back to _eosC1, which was unset in findShapesToSmooth()
8802       for ( size_t i = 0; i < eos._eosC1.size(); ++i )
8803       {
8804         eos._eosC1[ i ]->_toSmooth = true;
8805         for ( size_t j = 0; j < eos._eosC1[i]->_edges.size(); ++j )
8806           eos._eosC1[i]->_edges[j]->Set( _LayerEdge::SMOOTHED_C1 );
8807       }
8808     }
8809
8810     vector< double > segLen;
8811     for ( size_t i = 0; i < eos._edges.size(); ++i )
8812     {
8813       _LayerEdge& edge = *eos._edges[i];
8814       if ( edge._pos.size() < 2 )
8815         continue;
8816
8817       // get accumulated length of segments
8818       segLen.resize( edge._pos.size() );
8819       segLen[0] = 0.0;
8820       if ( eos._sWOL.IsNull() )
8821       {
8822         bool useNormal = true;
8823         bool   usePos  = false;
8824         bool smoothed  = false;
8825         const double preci = 0.1 * edge._len;
8826         if ( eos._toSmooth )
8827         {
8828           gp_Pnt tgtExpected = edge._pos[0] + edge._normal * edge._len;
8829           smoothed = tgtExpected.SquareDistance( edge._pos.back() ) > preci * preci;
8830         }
8831         if ( smoothed )
8832         {
8833           if ( !surface.IsNull() &&
8834                !data._convexFaces.count( eos._shapeID )) // edge smoothed on FACE
8835           {
8836             useNormal = usePos = false;
8837             gp_Pnt2d uv = helper.GetNodeUV( geomFace, edge._nodes[0] );
8838             for ( size_t j = 1; j < edge._pos.size() && !useNormal; ++j )
8839             {
8840               uv = surface->NextValueOfUV( uv, edge._pos[j], preci );
8841               if ( surface->Gap() < 2. * edge._len )
8842                 segLen[j] = surface->Gap();
8843               else
8844                 useNormal = true;
8845             }
8846           }
8847         }
8848         else
8849         {
8850           useNormal = usePos = false;
8851           edge._pos[1] = edge._pos.back();
8852           edge._pos.resize( 2 );
8853           segLen.resize( 2 );
8854           segLen[ 1 ] = edge._len;
8855         }
8856         if ( useNormal && edge.Is( _LayerEdge::NORMAL_UPDATED ))
8857         {
8858           useNormal = usePos = false;
8859           _LayerEdge tmpEdge; // get original _normal
8860           tmpEdge._nodes.push_back( edge._nodes[0] );
8861           if ( !setEdgeData( tmpEdge, eos, helper, data ))
8862             usePos = true;
8863           else
8864             for ( size_t j = 1; j < edge._pos.size(); ++j )
8865               segLen[j] = ( edge._pos[j] - edge._pos[0] ) * tmpEdge._normal;
8866         }
8867         if ( useNormal )
8868         {
8869           for ( size_t j = 1; j < edge._pos.size(); ++j )
8870             segLen[j] = ( edge._pos[j] - edge._pos[0] ) * edge._normal;
8871         }
8872         if ( usePos )
8873         {
8874           for ( size_t j = 1; j < edge._pos.size(); ++j )
8875             segLen[j] = segLen[j-1] + ( edge._pos[j-1] - edge._pos[j] ).Modulus();
8876         }
8877         else
8878         {
8879           bool swapped = ( edge._pos.size() > 2 );
8880           while ( swapped )
8881           {
8882             swapped = false;
8883             for ( size_t j = 1; j < edge._pos.size(); ++j )
8884               if ( segLen[j] < segLen[j-1] )
8885               {
8886                 std::swap( segLen[j], segLen[j-1] );
8887                 std::swap( edge._pos[j], edge._pos[j-1] );
8888                 swapped = true;
8889               }
8890           }
8891         }
8892         // smooth a path formed by edge._pos
8893         if (( smoothed ) &&
8894             ( eos.ShapeType() == TopAbs_FACE || edge.Is( _LayerEdge::SMOOTHED_C1 )))
8895           edge.SmoothPos( segLen, preci );
8896       }
8897       else if ( eos._isRegularSWOL ) // usual SWOL
8898       {
8899         for ( size_t j = 1; j < edge._pos.size(); ++j )
8900           segLen[j] = segLen[j-1] + (edge._pos[j-1] - edge._pos[j] ).Modulus();
8901       }
8902       else if ( !surface.IsNull() ) // SWOL surface with singularities
8903       {
8904         pos3D.resize( edge._pos.size() );
8905         for ( size_t j = 0; j < edge._pos.size(); ++j )
8906           pos3D[j] = surface->Value( edge._pos[j].X(), edge._pos[j].Y() ).XYZ();
8907
8908         for ( size_t j = 1; j < edge._pos.size(); ++j )
8909           segLen[j] = segLen[j-1] + ( pos3D[j-1] - pos3D[j] ).Modulus();
8910       }
8911
8912       // allocate memory for new nodes if it is not yet refined
8913       const SMDS_MeshNode* tgtNode = edge._nodes.back();
8914       if ( edge._nodes.size() == 2 )
8915       {
8916         edge._nodes.resize( eos._hyp.GetNumberLayers() + 1, 0 );
8917         edge._nodes[1] = 0;
8918         edge._nodes.back() = tgtNode;
8919       }
8920       // restore shapePos of the last node by already treated _LayerEdge of another _SolidData
8921       const TGeomID baseShapeId = edge._nodes[0]->getshapeId();
8922       if ( baseShapeId != prevBaseId )
8923       {
8924         map< TGeomID, TNode2Edge* >::iterator s2ne = data._s2neMap.find( baseShapeId );
8925         n2eMap = ( s2ne == data._s2neMap.end() ) ? 0 : s2ne->second;
8926         prevBaseId = baseShapeId;
8927       }
8928       _LayerEdge* edgeOnSameNode = 0;
8929       bool        useExistingPos = false;
8930       if ( n2eMap && (( n2e = n2eMap->find( edge._nodes[0] )) != n2eMap->end() ))
8931       {
8932         edgeOnSameNode = n2e->second;
8933         useExistingPos = ( edgeOnSameNode->_len < edge._len );
8934         const gp_XYZ& otherTgtPos = edgeOnSameNode->_pos.back();
8935         SMDS_PositionPtr  lastPos = tgtNode->GetPosition();
8936         if ( isOnEdge )
8937         {
8938           SMDS_EdgePosition* epos = static_cast<SMDS_EdgePosition*>( lastPos );
8939           epos->SetUParameter( otherTgtPos.X() );
8940         }
8941         else
8942         {
8943           SMDS_FacePosition* fpos = static_cast<SMDS_FacePosition*>( lastPos );
8944           fpos->SetUParameter( otherTgtPos.X() );
8945           fpos->SetVParameter( otherTgtPos.Y() );
8946         }
8947       }
8948       // calculate height of the first layer
8949       double h0;
8950       const double T = segLen.back(); //data._hyp.GetTotalThickness();
8951       const double f = eos._hyp.GetStretchFactor();
8952       const int    N = eos._hyp.GetNumberLayers();
8953       const double fPowN = pow( f, N );
8954       if ( fPowN - 1 <= numeric_limits<double>::min() )
8955         h0 = T / N;
8956       else
8957         h0 = T * ( f - 1 )/( fPowN - 1 );
8958
8959       const double zeroLen = std::numeric_limits<double>::min();
8960
8961       // create intermediate nodes
8962       double hSum = 0, hi = h0/f;
8963       size_t iSeg = 1;
8964       for ( size_t iStep = 1; iStep < edge._nodes.size(); ++iStep )
8965       {
8966         // compute an intermediate position
8967         hi *= f;
8968         hSum += hi;
8969         while ( hSum > segLen[iSeg] && iSeg < segLen.size()-1 )
8970           ++iSeg;
8971         int iPrevSeg = iSeg-1;
8972         while ( fabs( segLen[iPrevSeg] - segLen[iSeg]) <= zeroLen && iPrevSeg > 0 )
8973           --iPrevSeg;
8974         double   r = ( segLen[iSeg] - hSum ) / ( segLen[iSeg] - segLen[iPrevSeg] );
8975         gp_Pnt pos = r * edge._pos[iPrevSeg] + (1-r) * edge._pos[iSeg];
8976
8977         SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >( edge._nodes[ iStep ]);
8978         if ( !eos._sWOL.IsNull() )
8979         {
8980           // compute XYZ by parameters <pos>
8981           if ( isOnEdge )
8982           {
8983             u = pos.X();
8984             if ( !node )
8985               pos = curve->Value( u ).Transformed(loc);
8986           }
8987           else if ( eos._isRegularSWOL )
8988           {
8989             uv.SetCoord( pos.X(), pos.Y() );
8990             if ( !node )
8991               pos = surface->Value( pos.X(), pos.Y() );
8992           }
8993           else
8994           {
8995             uv.SetCoord( pos.X(), pos.Y() );
8996             gp_Pnt p = r * pos3D[ iPrevSeg ] + (1-r) * pos3D[ iSeg ];
8997             uv = surface->NextValueOfUV( uv, p, BRep_Tool::Tolerance( geomFace )).XY();
8998             if ( !node )
8999               pos = surface->Value( uv );
9000           }
9001         }
9002         // create or update the node
9003         if ( !node )
9004         {
9005           node = helper.AddNode( pos.X(), pos.Y(), pos.Z());
9006           if ( !eos._sWOL.IsNull() )
9007           {
9008             if ( isOnEdge )
9009               getMeshDS()->SetNodeOnEdge( node, geomEdge, u );
9010             else
9011               getMeshDS()->SetNodeOnFace( node, geomFace, uv.X(), uv.Y() );
9012           }
9013           else
9014           {
9015             getMeshDS()->SetNodeInVolume( node, helper.GetSubShapeID() );
9016           }
9017         }
9018         else
9019         {
9020           if ( !eos._sWOL.IsNull() )
9021           {
9022             // make average pos from new and current parameters
9023             if ( isOnEdge )
9024             {
9025               //u = 0.5 * ( u + helper.GetNodeU( geomEdge, node ));
9026               if ( useExistingPos )
9027                 u = helper.GetNodeU( geomEdge, node );
9028               pos = curve->Value( u ).Transformed(loc);
9029
9030               SMDS_EdgePosition* epos = static_cast<SMDS_EdgePosition*>( node->GetPosition() );
9031               epos->SetUParameter( u );
9032             }
9033             else
9034             {
9035               //uv = 0.5 * ( uv + helper.GetNodeUV( geomFace, node ));
9036               if ( useExistingPos )
9037                 uv = helper.GetNodeUV( geomFace, node );
9038               pos = surface->Value( uv );
9039
9040               SMDS_FacePosition* fpos = static_cast<SMDS_FacePosition*>( node->GetPosition() );
9041               fpos->SetUParameter( uv.X() );
9042               fpos->SetVParameter( uv.Y() );
9043             }
9044           }
9045           node->setXYZ( pos.X(), pos.Y(), pos.Z() );
9046         }
9047       } // loop on edge._nodes
9048
9049       if ( !eos._sWOL.IsNull() ) // prepare for shrink()
9050       {
9051         if ( isOnEdge )
9052           edge._pos.back().SetCoord( u, 0,0);
9053         else
9054           edge._pos.back().SetCoord( uv.X(), uv.Y() ,0);
9055
9056         if ( edgeOnSameNode )
9057           edgeOnSameNode->_pos.back() = edge._pos.back();
9058       }
9059
9060     } // loop on eos._edges to create nodes
9061
9062
9063     if ( !getMeshDS()->IsEmbeddedMode() )
9064       // Log node movement
9065       for ( size_t i = 0; i < eos._edges.size(); ++i )
9066       {
9067         SMESH_TNodeXYZ p ( eos._edges[i]->_nodes.back() );
9068         getMeshDS()->MoveNode( p._node, p.X(), p.Y(), p.Z() );
9069       }
9070   }
9071
9072
9073   // Create volumes
9074
9075   helper.SetElementsOnShape(true);
9076
9077   vector< vector<const SMDS_MeshNode*>* > nnVec;
9078   set< vector<const SMDS_MeshNode*>* >    nnSet;
9079   set< int >                       degenEdgeInd;
9080   vector<const SMDS_MeshElement*>     degenVols;
9081   vector<int>                       isRiskySWOL;
9082
9083   TopExp_Explorer exp( data._solid, TopAbs_FACE );
9084   for ( ; exp.More(); exp.Next() )
9085   {
9086     const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
9087     if ( data._ignoreFaceIds.count( faceID ))
9088       continue;
9089     const bool isReversedFace = data._reversedFaceIds.count( faceID );
9090     SMESHDS_SubMesh*    fSubM = getMeshDS()->MeshElements( exp.Current() );
9091     SMDS_ElemIteratorPtr  fIt = fSubM->GetElements();
9092     while ( fIt->more() )
9093     {
9094       const SMDS_MeshElement* face = fIt->next();
9095       const int            nbNodes = face->NbCornerNodes();
9096       nnVec.resize( nbNodes );
9097       nnSet.clear();
9098       degenEdgeInd.clear();
9099       isRiskySWOL.resize( nbNodes );
9100       size_t maxZ = 0, minZ = std::numeric_limits<size_t>::max();
9101       SMDS_NodeIteratorPtr nIt = face->nodeIterator();
9102       for ( int iN = 0; iN < nbNodes; ++iN )
9103       {
9104         const SMDS_MeshNode* n = nIt->next();
9105         _LayerEdge*       edge = data._n2eMap[ n ];
9106         const int i = isReversedFace ? nbNodes-1-iN : iN;
9107         nnVec[ i ] = & edge->_nodes;
9108         maxZ = std::max( maxZ, nnVec[ i ]->size() );
9109         minZ = std::min( minZ, nnVec[ i ]->size() );
9110         //isRiskySWOL[ i ] = edge->Is( _LayerEdge::RISKY_SWOL );
9111
9112         if ( helper.HasDegeneratedEdges() )
9113           nnSet.insert( nnVec[ i ]);
9114       }
9115
9116       if ( maxZ == 0 )
9117         continue;
9118       if ( 0 < nnSet.size() && nnSet.size() < 3 )
9119         continue;
9120
9121       switch ( nbNodes )
9122       {
9123       case 3: // TRIA
9124       {
9125         // PENTA
9126         for ( size_t iZ = 1; iZ < minZ; ++iZ )
9127           helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
9128                             (*nnVec[0])[iZ],   (*nnVec[1])[iZ],   (*nnVec[2])[iZ]);
9129
9130         for ( size_t iZ = minZ; iZ < maxZ; ++iZ )
9131         {
9132           for ( int iN = 0; iN < nbNodes; ++iN )
9133             if ( nnVec[ iN ]->size() < iZ+1 )
9134               degenEdgeInd.insert( iN );
9135
9136           if ( degenEdgeInd.size() == 1 )  // PYRAM
9137           {
9138             int i2 = *degenEdgeInd.begin();
9139             int i0 = helper.WrapIndex( i2 - 1, nbNodes );
9140             int i1 = helper.WrapIndex( i2 + 1, nbNodes );
9141             helper.AddVolume( (*nnVec[i0])[iZ-1], (*nnVec[i1])[iZ-1],
9142                               (*nnVec[i1])[iZ  ], (*nnVec[i0])[iZ  ], (*nnVec[i2]).back());
9143           }
9144           else  // TETRA
9145           {
9146             int i3 = !degenEdgeInd.count(0) ? 0 : !degenEdgeInd.count(1) ? 1 : 2;
9147             helper.AddVolume( (*nnVec[  0 ])[ i3 == 0 ? iZ-1 : nnVec[0]->size()-1 ],
9148                               (*nnVec[  1 ])[ i3 == 1 ? iZ-1 : nnVec[1]->size()-1 ],
9149                               (*nnVec[  2 ])[ i3 == 2 ? iZ-1 : nnVec[2]->size()-1 ],
9150                               (*nnVec[ i3 ])[ iZ ]);
9151           }
9152         }
9153         break; // TRIA
9154       }
9155       case 4: // QUAD
9156       {
9157         // HEX
9158         for ( size_t iZ = 1; iZ < minZ; ++iZ )
9159           helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
9160                             (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
9161                             (*nnVec[0])[iZ],   (*nnVec[1])[iZ],
9162                             (*nnVec[2])[iZ],   (*nnVec[3])[iZ]);
9163
9164         for ( size_t iZ = minZ; iZ < maxZ; ++iZ )
9165         {
9166           for ( int iN = 0; iN < nbNodes; ++iN )
9167             if ( nnVec[ iN ]->size() < iZ+1 )
9168               degenEdgeInd.insert( iN );
9169
9170           switch ( degenEdgeInd.size() )
9171           {
9172           case 2: // PENTA
9173           {
9174             int i2 = *degenEdgeInd.begin();
9175             int i3 = *degenEdgeInd.rbegin();
9176             bool ok = ( i3 - i2 == 1 );
9177             if ( i2 == 0 && i3 == 3 ) { i2 = 3; i3 = 0; ok = true; }
9178             int i0 = helper.WrapIndex( i3 + 1, nbNodes );
9179             int i1 = helper.WrapIndex( i0 + 1, nbNodes );
9180
9181             const SMDS_MeshElement* vol =
9182               helper.AddVolume( nnVec[i3]->back(), (*nnVec[i0])[iZ], (*nnVec[i0])[iZ-1],
9183                                 nnVec[i2]->back(), (*nnVec[i1])[iZ], (*nnVec[i1])[iZ-1]);
9184             if ( !ok && vol )
9185               degenVols.push_back( vol );
9186           }
9187           break;
9188
9189           default: // degen HEX
9190           {
9191             const SMDS_MeshElement* vol =
9192               helper.AddVolume( nnVec[0]->size() > iZ-1 ? (*nnVec[0])[iZ-1] : nnVec[0]->back(),
9193                                 nnVec[1]->size() > iZ-1 ? (*nnVec[1])[iZ-1] : nnVec[1]->back(),
9194                                 nnVec[2]->size() > iZ-1 ? (*nnVec[2])[iZ-1] : nnVec[2]->back(),
9195                                 nnVec[3]->size() > iZ-1 ? (*nnVec[3])[iZ-1] : nnVec[3]->back(),
9196                                 nnVec[0]->size() > iZ   ? (*nnVec[0])[iZ]   : nnVec[0]->back(),
9197                                 nnVec[1]->size() > iZ   ? (*nnVec[1])[iZ]   : nnVec[1]->back(),
9198                                 nnVec[2]->size() > iZ   ? (*nnVec[2])[iZ]   : nnVec[2]->back(),
9199                                 nnVec[3]->size() > iZ   ? (*nnVec[3])[iZ]   : nnVec[3]->back());
9200             degenVols.push_back( vol );
9201           }
9202           }
9203         }
9204         break; // HEX
9205       }
9206       default:
9207         return error("Not supported type of element", data._index);
9208
9209       } // switch ( nbNodes )
9210     } // while ( fIt->more() )
9211   } // loop on FACEs
9212
9213   if ( !degenVols.empty() )
9214   {
9215     SMESH_ComputeErrorPtr& err = _mesh->GetSubMesh( data._solid )->GetComputeError();
9216     if ( !err || err->IsOK() )
9217     {
9218       err.reset( new SMESH_ComputeError( COMPERR_WARNING,
9219                                          "Degenerated volumes created" ));
9220       err->myBadElements.insert( err->myBadElements.end(),
9221                                  degenVols.begin(),degenVols.end() );
9222     }
9223   }
9224
9225   return true;
9226 }
9227
9228 //================================================================================
9229 /*!
9230  * \brief Shrink 2D mesh on faces to let space for inflated layers
9231  */
9232 //================================================================================
9233
9234 bool _ViscousBuilder::shrink()
9235 {
9236   // make map of (ids of FACEs to shrink mesh on) to (_SolidData containing _LayerEdge's
9237   // inflated along FACE or EDGE)
9238   map< TGeomID, _SolidData* > f2sdMap;
9239   for ( size_t i = 0 ; i < _sdVec.size(); ++i )
9240   {
9241     _SolidData& data = _sdVec[i];
9242     TopTools_MapOfShape FFMap;
9243     map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
9244     for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
9245       if ( s2s->second.ShapeType() == TopAbs_FACE )
9246       {
9247         f2sdMap.insert( make_pair( getMeshDS()->ShapeToIndex( s2s->second ), &data ));
9248
9249         if ( FFMap.Add( (*s2s).second ))
9250           // Put mesh faces on the shrinked FACE to the proxy sub-mesh to avoid
9251           // usage of mesh faces made in addBoundaryElements() by the 3D algo or
9252           // by StdMeshers_QuadToTriaAdaptor
9253           if ( SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( s2s->second ))
9254           {
9255             SMESH_ProxyMesh::SubMesh* proxySub =
9256               data._proxyMesh->getFaceSubM( TopoDS::Face( s2s->second ), /*create=*/true);
9257             SMDS_ElemIteratorPtr fIt = smDS->GetElements();
9258             while ( fIt->more() )
9259               proxySub->AddElement( fIt->next() );
9260             // as a result 3D algo will use elements from proxySub and not from smDS
9261           }
9262       }
9263   }
9264
9265   SMESH_MesherHelper helper( *_mesh );
9266   helper.ToFixNodeParameters( true );
9267
9268   // EDGE's to shrink
9269   map< TGeomID, _Shrinker1D > e2shrMap;
9270   vector< _EdgesOnShape* > subEOS;
9271   vector< _LayerEdge* > lEdges;
9272
9273   // loop on FACES to srink mesh on
9274   map< TGeomID, _SolidData* >::iterator f2sd = f2sdMap.begin();
9275   for ( ; f2sd != f2sdMap.end(); ++f2sd )
9276   {
9277     _SolidData&      data = *f2sd->second;
9278     const TopoDS_Face&  F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
9279     SMESH_subMesh*     sm = _mesh->GetSubMesh( F );
9280     SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
9281
9282     Handle(Geom_Surface) surface = BRep_Tool::Surface(F);
9283
9284     helper.SetSubShape(F);
9285
9286     // ===========================
9287     // Prepare data for shrinking
9288     // ===========================
9289
9290     // Collect nodes to smooth, as src nodes are not yet replaced by tgt ones
9291     // and hence all nodes on a FACE connected to 2d elements are to be smoothed
9292     vector < const SMDS_MeshNode* > smoothNodes;
9293     {
9294       SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
9295       while ( nIt->more() )
9296       {
9297         const SMDS_MeshNode* n = nIt->next();
9298         if ( n->NbInverseElements( SMDSAbs_Face ) > 0 )
9299           smoothNodes.push_back( n );
9300       }
9301     }
9302     // Find out face orientation
9303     double refSign = 1;
9304     const set<TGeomID> ignoreShapes;
9305     bool isOkUV;
9306     if ( !smoothNodes.empty() )
9307     {
9308       vector<_Simplex> simplices;
9309       _Simplex::GetSimplices( smoothNodes[0], simplices, ignoreShapes );
9310       helper.GetNodeUV( F, simplices[0]._nPrev, 0, &isOkUV ); // fix UV of silpmex nodes
9311       helper.GetNodeUV( F, simplices[0]._nNext, 0, &isOkUV );
9312       gp_XY uv = helper.GetNodeUV( F, smoothNodes[0], 0, &isOkUV );
9313       if ( !simplices[0].IsForward(uv, smoothNodes[0], F, helper,refSign) )
9314         refSign = -1;
9315     }
9316
9317     // Find _LayerEdge's inflated along F
9318     subEOS.clear();
9319     lEdges.clear();
9320     {
9321       SMESH_subMeshIteratorPtr subIt = sm->getDependsOnIterator(/*includeSelf=*/false,
9322                                                                 /*complexFirst=*/true); //!!!
9323       while ( subIt->more() )
9324       {
9325         const TGeomID subID = subIt->next()->GetId();
9326         if ( data._noShrinkShapes.count( subID ))
9327           continue;
9328         _EdgesOnShape* eos = data.GetShapeEdges( subID );
9329         if ( !eos || eos->_sWOL.IsNull() ) continue;
9330
9331         subEOS.push_back( eos );
9332
9333         for ( size_t i = 0; i < eos->_edges.size(); ++i )
9334         {
9335           lEdges.push_back( eos->_edges[ i ] );
9336           prepareEdgeToShrink( *eos->_edges[ i ], *eos, helper, smDS );
9337         }
9338       }
9339     }
9340
9341     dumpFunction(SMESH_Comment("beforeShrinkFace")<<f2sd->first); // debug
9342     SMDS_ElemIteratorPtr fIt = smDS->GetElements();
9343     while ( fIt->more() )
9344       if ( const SMDS_MeshElement* f = fIt->next() )
9345         dumpChangeNodes( f );
9346     dumpFunctionEnd();
9347
9348     // Replace source nodes by target nodes in mesh faces to shrink
9349     dumpFunction(SMESH_Comment("replNodesOnFace")<<f2sd->first); // debug
9350     const SMDS_MeshNode* nodes[20];
9351     for ( size_t iS = 0; iS < subEOS.size(); ++iS )
9352     {
9353       _EdgesOnShape& eos = * subEOS[ iS ];
9354       for ( size_t i = 0; i < eos._edges.size(); ++i )
9355       {
9356         _LayerEdge& edge = *eos._edges[i];
9357         const SMDS_MeshNode* srcNode = edge._nodes[0];
9358         const SMDS_MeshNode* tgtNode = edge._nodes.back();
9359         SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
9360         while ( fIt->more() )
9361         {
9362           const SMDS_MeshElement* f = fIt->next();
9363           if ( !smDS->Contains( f ))
9364             continue;
9365           SMDS_NodeIteratorPtr nIt = f->nodeIterator();
9366           for ( int iN = 0; nIt->more(); ++iN )
9367           {
9368             const SMDS_MeshNode* n = nIt->next();
9369             nodes[iN] = ( n == srcNode ? tgtNode : n );
9370           }
9371           helper.GetMeshDS()->ChangeElementNodes( f, nodes, f->NbNodes() );
9372           dumpChangeNodes( f );
9373         }
9374       }
9375     }
9376     dumpFunctionEnd();
9377
9378     // find out if a FACE is concave
9379     const bool isConcaveFace = isConcave( F, helper );
9380
9381     // Create _SmoothNode's on face F
9382     vector< _SmoothNode > nodesToSmooth( smoothNodes.size() );
9383     {
9384       dumpFunction(SMESH_Comment("fixUVOnFace")<<f2sd->first); // debug
9385       const bool sortSimplices = isConcaveFace;
9386       for ( size_t i = 0; i < smoothNodes.size(); ++i )
9387       {
9388         const SMDS_MeshNode* n = smoothNodes[i];
9389         nodesToSmooth[ i ]._node = n;
9390         // src nodes must be replaced by tgt nodes to have tgt nodes in _simplices
9391         _Simplex::GetSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes, 0, sortSimplices);
9392         // fix up incorrect uv of nodes on the FACE
9393         helper.GetNodeUV( F, n, 0, &isOkUV);
9394         dumpMove( n );
9395       }
9396       dumpFunctionEnd();
9397     }
9398     //if ( nodesToSmooth.empty() ) continue;
9399
9400     // Find EDGE's to shrink and set simpices to LayerEdge's
9401     set< _Shrinker1D* > eShri1D;
9402     {
9403       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
9404       {
9405         _EdgesOnShape& eos = * subEOS[ iS ];
9406         if ( eos.SWOLType() == TopAbs_EDGE )
9407         {
9408           SMESH_subMesh* edgeSM = _mesh->GetSubMesh( eos._sWOL );
9409           _Shrinker1D& srinker  = e2shrMap[ edgeSM->GetId() ];
9410           eShri1D.insert( & srinker );
9411           srinker.AddEdge( eos._edges[0], eos, helper );
9412           VISCOUS_3D::ToClearSubWithMain( edgeSM, data._solid );
9413           // restore params of nodes on EGDE if the EDGE has been already
9414           // srinked while srinking other FACE
9415           srinker.RestoreParams();
9416         }
9417         for ( size_t i = 0; i < eos._edges.size(); ++i )
9418         {
9419           _LayerEdge& edge = * eos._edges[i];
9420           _Simplex::GetSimplices( /*tgtNode=*/edge._nodes.back(), edge._simplices, ignoreShapes );
9421         }
9422       }
9423     }
9424
9425     bool toFixTria = false; // to improve quality of trias by diagonal swap
9426     if ( isConcaveFace )
9427     {
9428       const bool hasTria = _mesh->NbTriangles(), hasQuad = _mesh->NbQuadrangles();
9429       if ( hasTria != hasQuad ) {
9430         toFixTria = hasTria;
9431       }
9432       else {
9433         set<int> nbNodesSet;
9434         SMDS_ElemIteratorPtr fIt = smDS->GetElements();
9435         while ( fIt->more() && nbNodesSet.size() < 2 )
9436           nbNodesSet.insert( fIt->next()->NbCornerNodes() );
9437         toFixTria = ( *nbNodesSet.begin() == 3 );
9438       }
9439     }
9440
9441     // ==================
9442     // Perform shrinking
9443     // ==================
9444
9445     bool shrinked = true;
9446     int badNb, shriStep=0, smooStep=0;
9447     _SmoothNode::SmoothType smoothType
9448       = isConcaveFace ? _SmoothNode::ANGULAR : _SmoothNode::LAPLACIAN;
9449     SMESH_Comment errMsg;
9450     while ( shrinked )
9451     {
9452       shriStep++;
9453       // Move boundary nodes (actually just set new UV)
9454       // -----------------------------------------------
9455       dumpFunction(SMESH_Comment("moveBoundaryOnF")<<f2sd->first<<"_st"<<shriStep ); // debug
9456       shrinked = false;
9457       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
9458       {
9459         _EdgesOnShape& eos = * subEOS[ iS ];
9460         for ( size_t i = 0; i < eos._edges.size(); ++i )
9461         {
9462           shrinked |= eos._edges[i]->SetNewLength2d( surface, F, eos, helper );
9463         }
9464       }
9465       dumpFunctionEnd();
9466
9467       // Move nodes on EDGE's
9468       // (XYZ is set as soon as a needed length reached in SetNewLength2d())
9469       set< _Shrinker1D* >::iterator shr = eShri1D.begin();
9470       for ( ; shr != eShri1D.end(); ++shr )
9471         (*shr)->Compute( /*set3D=*/false, helper );
9472
9473       // Smoothing in 2D
9474       // -----------------
9475       int nbNoImpSteps = 0;
9476       bool       moved = true;
9477       badNb = 1;
9478       while (( nbNoImpSteps < 5 && badNb > 0) && moved)
9479       {
9480         dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
9481
9482         int oldBadNb = badNb;
9483         badNb = 0;
9484         moved = false;
9485         // '% 5' minimizes NB FUNCTIONS on viscous_layers_00/B2 case
9486         _SmoothNode::SmoothType smooTy = ( smooStep % 5 ) ? smoothType : _SmoothNode::LAPLACIAN;
9487         for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
9488         {
9489           moved |= nodesToSmooth[i].Smooth( badNb, surface, helper, refSign,
9490                                             smooTy, /*set3D=*/isConcaveFace);
9491         }
9492         if ( badNb < oldBadNb )
9493           nbNoImpSteps = 0;
9494         else
9495           nbNoImpSteps++;
9496
9497         dumpFunctionEnd();
9498       }
9499
9500       errMsg.clear();
9501       if ( badNb > 0 )
9502         errMsg << "Can't shrink 2D mesh on face " << f2sd->first;
9503       if ( shriStep > 200 )
9504         errMsg << "Infinite loop at shrinking 2D mesh on face " << f2sd->first;
9505       if ( !errMsg.empty() )
9506         break;
9507
9508       // Fix narrow triangles by swapping diagonals
9509       // ---------------------------------------
9510       if ( toFixTria )
9511       {
9512         set<const SMDS_MeshNode*> usedNodes;
9513         fixBadFaces( F, helper, /*is2D=*/true, shriStep, & usedNodes); // swap diagonals
9514
9515         // update working data
9516         set<const SMDS_MeshNode*>::iterator n;
9517         for ( size_t i = 0; i < nodesToSmooth.size() && !usedNodes.empty(); ++i )
9518         {
9519           n = usedNodes.find( nodesToSmooth[ i ]._node );
9520           if ( n != usedNodes.end())
9521           {
9522             _Simplex::GetSimplices( nodesToSmooth[ i ]._node,
9523                                     nodesToSmooth[ i ]._simplices,
9524                                     ignoreShapes, NULL,
9525                                     /*sortSimplices=*/ smoothType == _SmoothNode::ANGULAR );
9526             usedNodes.erase( n );
9527           }
9528         }
9529         for ( size_t i = 0; i < lEdges.size() && !usedNodes.empty(); ++i )
9530         {
9531           n = usedNodes.find( /*tgtNode=*/ lEdges[i]->_nodes.back() );
9532           if ( n != usedNodes.end())
9533           {
9534             _Simplex::GetSimplices( lEdges[i]->_nodes.back(),
9535                                     lEdges[i]->_simplices,
9536                                     ignoreShapes );
9537             usedNodes.erase( n );
9538           }
9539         }
9540       }
9541       // TODO: check effect of this additional smooth
9542       // additional laplacian smooth to increase allowed shrink step
9543       // for ( int st = 1; st; --st )
9544       // {
9545       //   dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
9546       //   for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
9547       //   {
9548       //     nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,
9549       //                              _SmoothNode::LAPLACIAN,/*set3D=*/false);
9550       //   }
9551       // }
9552
9553     } // while ( shrinked )
9554
9555     if ( !errMsg.empty() ) // Try to re-compute the shrink FACE
9556     {
9557       // remove faces
9558       SMESHDS_SubMesh* psm = data._proxyMesh->getFaceSubM( F );
9559       {
9560         vector< const SMDS_MeshElement* > facesToRm;
9561         if ( psm )
9562         {
9563           facesToRm.reserve( psm->NbElements() );
9564           for ( SMDS_ElemIteratorPtr ite = psm->GetElements(); ite->more(); )
9565             facesToRm.push_back( ite->next() );
9566
9567           for ( size_t i = 0 ; i < _sdVec.size(); ++i )
9568             if (( psm = _sdVec[i]._proxyMesh->getFaceSubM( F )))
9569               psm->Clear();
9570         }
9571         for ( size_t i = 0; i < facesToRm.size(); ++i )
9572           getMeshDS()->RemoveFreeElement( facesToRm[i], smDS, /*fromGroups=*/false );
9573       }
9574       // remove nodes
9575       {
9576         TIDSortedNodeSet nodesToKeep; // nodes of _LayerEdge to keep
9577         for ( size_t iS = 0; iS < subEOS.size(); ++iS ) {
9578           for ( size_t i = 0; i < subEOS[iS]->_edges.size(); ++i )
9579             nodesToKeep.insert( ++( subEOS[iS]->_edges[i]->_nodes.begin() ),
9580                                 subEOS[iS]->_edges[i]->_nodes.end() );
9581         }
9582         SMDS_NodeIteratorPtr itn = smDS->GetNodes();
9583         while ( itn->more() ) {
9584           const SMDS_MeshNode* n = itn->next();
9585           if ( !nodesToKeep.count( n ))
9586             getMeshDS()->RemoveFreeNode( n, smDS, /*fromGroups=*/false );
9587         }
9588       }
9589       // restore position and UV of target nodes
9590       gp_Pnt p;
9591       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
9592         for ( size_t i = 0; i < subEOS[iS]->_edges.size(); ++i )
9593         {
9594           _LayerEdge*       edge = subEOS[iS]->_edges[i];
9595           SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( edge->_nodes.back() );
9596           if ( edge->_pos.empty() ) continue;
9597           if ( subEOS[iS]->SWOLType() == TopAbs_FACE )
9598           {
9599             SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
9600             pos->SetUParameter( edge->_pos[0].X() );
9601             pos->SetVParameter( edge->_pos[0].Y() );
9602             p = surface->Value( edge->_pos[0].X(), edge->_pos[0].Y() );
9603           }
9604           else
9605           {
9606             SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
9607             pos->SetUParameter( edge->_pos[0].Coord( U_TGT ));
9608             p = BRepAdaptor_Curve( TopoDS::Edge( subEOS[iS]->_sWOL )).Value( pos->GetUParameter() );
9609           }
9610           tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
9611           dumpMove( tgtNode );
9612         }
9613       // shrink EDGE sub-meshes and set proxy sub-meshes
9614       UVPtStructVec uvPtVec;
9615       set< _Shrinker1D* >::iterator shrIt = eShri1D.begin();
9616       for ( shrIt = eShri1D.begin(); shrIt != eShri1D.end(); ++shrIt )
9617       {
9618         _Shrinker1D* shr = (*shrIt);
9619         shr->Compute( /*set3D=*/true, helper );
9620
9621         // set proxy mesh of EDGEs w/o layers
9622         map< double, const SMDS_MeshNode* > nodes;
9623         SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), shr->GeomEdge(),/*skipMedium=*/true, nodes);
9624         // remove refinement nodes
9625         const SMDS_MeshNode* sn0 = shr->SrcNode(0), *sn1 = shr->SrcNode(1);
9626         const SMDS_MeshNode* tn0 = shr->TgtNode(0), *tn1 = shr->TgtNode(1);
9627         map< double, const SMDS_MeshNode* >::iterator u2n = nodes.begin();
9628         if ( u2n->second == sn0 || u2n->second == sn1 )
9629         {
9630           while ( u2n->second != tn0 && u2n->second != tn1 )
9631             ++u2n;
9632           nodes.erase( nodes.begin(), u2n );
9633         }
9634         u2n = --nodes.end();
9635         if ( u2n->second == sn0 || u2n->second == sn1 )
9636         {
9637           while ( u2n->second != tn0 && u2n->second != tn1 )
9638             --u2n;
9639           nodes.erase( ++u2n, nodes.end() );
9640         }
9641         // set proxy sub-mesh
9642         uvPtVec.resize( nodes.size() );
9643         u2n = nodes.begin();
9644         BRepAdaptor_Curve2d curve( shr->GeomEdge(), F );
9645         for ( size_t i = 0; i < nodes.size(); ++i, ++u2n )
9646         {
9647           uvPtVec[ i ].node = u2n->second;
9648           uvPtVec[ i ].param = u2n->first;
9649           uvPtVec[ i ].SetUV( curve.Value( u2n->first ).XY() );
9650         }
9651         StdMeshers_FaceSide fSide( uvPtVec, F, shr->GeomEdge(), _mesh );
9652         StdMeshers_ViscousLayers2D::SetProxyMeshOfEdge( fSide );
9653       }
9654
9655       // set proxy mesh of EDGEs with layers
9656       vector< _LayerEdge* > edges;
9657       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
9658       {
9659         _EdgesOnShape& eos = * subEOS[ iS ];
9660         if ( eos.ShapeType() != TopAbs_EDGE ) continue;
9661
9662         const TopoDS_Edge& E = TopoDS::Edge( eos._shape );
9663         data.SortOnEdge( E, eos._edges );
9664
9665         edges.clear();
9666         if ( _EdgesOnShape* eov = data.GetShapeEdges( helper.IthVertex( 0, E, /*CumOri=*/false )))
9667           if ( !eov->_edges.empty() )
9668             edges.push_back( eov->_edges[0] ); // on 1st VERTEX
9669
9670         edges.insert( edges.end(), eos._edges.begin(), eos._edges.end() );
9671
9672         if ( _EdgesOnShape* eov = data.GetShapeEdges( helper.IthVertex( 1, E, /*CumOri=*/false )))
9673           if ( !eov->_edges.empty() )
9674             edges.push_back( eov->_edges[0] ); // on last VERTEX
9675
9676         uvPtVec.resize( edges.size() );
9677         for ( size_t i = 0; i < edges.size(); ++i )
9678         {
9679           uvPtVec[ i ].node = edges[i]->_nodes.back();
9680           uvPtVec[ i ].param = helper.GetNodeU( E, edges[i]->_nodes[0] );
9681           uvPtVec[ i ].SetUV( helper.GetNodeUV( F, edges[i]->_nodes.back() ));
9682         }
9683         BRep_Tool::Range( E, uvPtVec[0].param, uvPtVec.back().param );
9684         StdMeshers_FaceSide fSide( uvPtVec, F, E, _mesh );
9685         StdMeshers_ViscousLayers2D::SetProxyMeshOfEdge( fSide );
9686       }
9687       // temporary clear the FACE sub-mesh from faces made by refine()
9688       vector< const SMDS_MeshElement* > elems;
9689       elems.reserve( smDS->NbElements() + smDS->NbNodes() );
9690       for ( SMDS_ElemIteratorPtr ite = smDS->GetElements(); ite->more(); )
9691         elems.push_back( ite->next() );
9692       for ( SMDS_NodeIteratorPtr ite = smDS->GetNodes(); ite->more(); )
9693         elems.push_back( ite->next() );
9694       smDS->Clear();
9695
9696       // compute the mesh on the FACE
9697       sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
9698       sm->ComputeStateEngine( SMESH_subMesh::COMPUTE_SUBMESH );
9699
9700       // re-fill proxy sub-meshes of the FACE
9701       for ( size_t i = 0 ; i < _sdVec.size(); ++i )
9702         if (( psm = _sdVec[i]._proxyMesh->getFaceSubM( F )))
9703           for ( SMDS_ElemIteratorPtr ite = smDS->GetElements(); ite->more(); )
9704             psm->AddElement( ite->next() );
9705
9706       // re-fill smDS
9707       for ( size_t i = 0; i < elems.size(); ++i )
9708         smDS->AddElement( elems[i] );
9709
9710       if ( sm->GetComputeState() != SMESH_subMesh::COMPUTE_OK )
9711         return error( errMsg );
9712
9713     } // end of re-meshing in case of failed smoothing
9714     else
9715     {
9716       // No wrongly shaped faces remain; final smooth. Set node XYZ.
9717       bool isStructuredFixed = false;
9718       if ( SMESH_2D_Algo* algo = dynamic_cast<SMESH_2D_Algo*>( sm->GetAlgo() ))
9719         isStructuredFixed = algo->FixInternalNodes( *data._proxyMesh, F );
9720       if ( !isStructuredFixed )
9721       {
9722         if ( isConcaveFace ) // fix narrow faces by swapping diagonals
9723           fixBadFaces( F, helper, /*is2D=*/false, ++shriStep );
9724
9725         for ( int st = 3; st; --st )
9726         {
9727           switch( st ) {
9728           case 1: smoothType = _SmoothNode::LAPLACIAN; break;
9729           case 2: smoothType = _SmoothNode::LAPLACIAN; break;
9730           case 3: smoothType = _SmoothNode::ANGULAR; break;
9731           }
9732           dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
9733           for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
9734           {
9735             nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,
9736                                      smoothType,/*set3D=*/st==1 );
9737           }
9738           dumpFunctionEnd();
9739         }
9740       }
9741       if ( !getMeshDS()->IsEmbeddedMode() )
9742         // Log node movement
9743         for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
9744         {
9745           SMESH_TNodeXYZ p ( nodesToSmooth[i]._node );
9746           getMeshDS()->MoveNode( nodesToSmooth[i]._node, p.X(), p.Y(), p.Z() );
9747         }
9748     }
9749
9750     // Set an event listener to clear FACE sub-mesh together with SOLID sub-mesh
9751     VISCOUS_3D::ToClearSubWithMain( sm, data._solid );
9752
9753   } // loop on FACES to srink mesh on
9754
9755
9756   // Replace source nodes by target nodes in shrinked mesh edges
9757
9758   map< int, _Shrinker1D >::iterator e2shr = e2shrMap.begin();
9759   for ( ; e2shr != e2shrMap.end(); ++e2shr )
9760     e2shr->second.SwapSrcTgtNodes( getMeshDS() );
9761
9762   return true;
9763 }
9764
9765 //================================================================================
9766 /*!
9767  * \brief Computes 2d shrink direction and finds nodes limiting shrinking
9768  */
9769 //================================================================================
9770
9771 bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge&            edge,
9772                                            _EdgesOnShape&         eos,
9773                                            SMESH_MesherHelper&    helper,
9774                                            const SMESHDS_SubMesh* faceSubMesh)
9775 {
9776   const SMDS_MeshNode* srcNode = edge._nodes[0];
9777   const SMDS_MeshNode* tgtNode = edge._nodes.back();
9778
9779   if ( eos.SWOLType() == TopAbs_FACE )
9780   {
9781     if ( tgtNode->GetPosition()->GetDim() != 2 ) // not inflated edge
9782     {
9783       edge._pos.clear();
9784       return srcNode == tgtNode;
9785     }
9786     gp_XY srcUV ( edge._pos[0].X(), edge._pos[0].Y() );          //helper.GetNodeUV( F, srcNode );
9787     gp_XY tgtUV = edge.LastUV( TopoDS::Face( eos._sWOL ), eos ); //helper.GetNodeUV( F, tgtNode );
9788     gp_Vec2d uvDir( srcUV, tgtUV );
9789     double uvLen = uvDir.Magnitude();
9790     uvDir /= uvLen;
9791     edge._normal.SetCoord( uvDir.X(),uvDir.Y(), 0 );
9792     edge._len = uvLen;
9793
9794     edge._pos.resize(1);
9795     edge._pos[0].SetCoord( tgtUV.X(), tgtUV.Y(), 0 );
9796
9797     // set UV of source node to target node
9798     SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
9799     pos->SetUParameter( srcUV.X() );
9800     pos->SetVParameter( srcUV.Y() );
9801   }
9802   else // _sWOL is TopAbs_EDGE
9803   {
9804     if ( tgtNode->GetPosition()->GetDim() != 1 ) // not inflated edge
9805     {
9806       edge._pos.clear();
9807       return srcNode == tgtNode;
9808     }
9809     const TopoDS_Edge&    E = TopoDS::Edge( eos._sWOL );
9810     SMESHDS_SubMesh* edgeSM = getMeshDS()->MeshElements( E );
9811     if ( !edgeSM || edgeSM->NbElements() == 0 )
9812       return error(SMESH_Comment("Not meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
9813
9814     const SMDS_MeshNode* n2 = 0;
9815     SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
9816     while ( eIt->more() && !n2 )
9817     {
9818       const SMDS_MeshElement* e = eIt->next();
9819       if ( !edgeSM->Contains(e)) continue;
9820       n2 = e->GetNode( 0 );
9821       if ( n2 == srcNode ) n2 = e->GetNode( 1 );
9822     }
9823     if ( !n2 )
9824       return error(SMESH_Comment("Wrongly meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
9825
9826     double uSrc = helper.GetNodeU( E, srcNode, n2 );
9827     double uTgt = helper.GetNodeU( E, tgtNode, srcNode );
9828     double u2   = helper.GetNodeU( E, n2, srcNode );
9829
9830     edge._pos.clear();
9831
9832     if ( fabs( uSrc-uTgt ) < 0.99 * fabs( uSrc-u2 ))
9833     {
9834       // tgtNode is located so that it does not make faces with wrong orientation
9835       return true;
9836     }
9837     edge._pos.resize(1);
9838     edge._pos[0].SetCoord( U_TGT, uTgt );
9839     edge._pos[0].SetCoord( U_SRC, uSrc );
9840     edge._pos[0].SetCoord( LEN_TGT, fabs( uSrc-uTgt ));
9841
9842     edge._simplices.resize( 1 );
9843     edge._simplices[0]._nPrev = n2;
9844
9845     // set U of source node to the target node
9846     SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
9847     pos->SetUParameter( uSrc );
9848   }
9849   return true;
9850 }
9851
9852 //================================================================================
9853 /*!
9854  * \brief Restore position of a sole node of a _LayerEdge based on _noShrinkShapes
9855  */
9856 //================================================================================
9857
9858 void _ViscousBuilder::restoreNoShrink( _LayerEdge& edge ) const
9859 {
9860   if ( edge._nodes.size() == 1 )
9861   {
9862     edge._pos.clear();
9863     edge._len = 0;
9864
9865     const SMDS_MeshNode* srcNode = edge._nodes[0];
9866     TopoDS_Shape S = SMESH_MesherHelper::GetSubShapeByNode( srcNode, getMeshDS() );
9867     if ( S.IsNull() ) return;
9868
9869     gp_Pnt p;
9870
9871     switch ( S.ShapeType() )
9872     {
9873     case TopAbs_EDGE:
9874     {
9875       double f,l;
9876       TopLoc_Location loc;
9877       Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( S ), loc, f, l );
9878       if ( curve.IsNull() ) return;
9879       SMDS_EdgePosition* ePos = static_cast<SMDS_EdgePosition*>( srcNode->GetPosition() );
9880       p = curve->Value( ePos->GetUParameter() );
9881       break;
9882     }
9883     case TopAbs_VERTEX:
9884     {
9885       p = BRep_Tool::Pnt( TopoDS::Vertex( S ));
9886       break;
9887     }
9888     default: return;
9889     }
9890     getMeshDS()->MoveNode( srcNode, p.X(), p.Y(), p.Z() );
9891     dumpMove( srcNode );
9892   }
9893 }
9894
9895 //================================================================================
9896 /*!
9897  * \brief Try to fix triangles with high aspect ratio by swaping diagonals
9898  */
9899 //================================================================================
9900
9901 void _ViscousBuilder::fixBadFaces(const TopoDS_Face&          F,
9902                                   SMESH_MesherHelper&         helper,
9903                                   const bool                  is2D,
9904                                   const int                   step,
9905                                   set<const SMDS_MeshNode*> * involvedNodes)
9906 {
9907   SMESH::Controls::AspectRatio qualifier;
9908   SMESH::Controls::TSequenceOfXYZ points(3), points1(3), points2(3);
9909   const double maxAspectRatio = is2D ? 4. : 2;
9910   _NodeCoordHelper xyz( F, helper, is2D );
9911
9912   // find bad triangles
9913
9914   vector< const SMDS_MeshElement* > badTrias;
9915   vector< double >                  badAspects;
9916   SMESHDS_SubMesh*      sm = helper.GetMeshDS()->MeshElements( F );
9917   SMDS_ElemIteratorPtr fIt = sm->GetElements();
9918   while ( fIt->more() )
9919   {
9920     const SMDS_MeshElement * f = fIt->next();
9921     if ( f->NbCornerNodes() != 3 ) continue;
9922     for ( int iP = 0; iP < 3; ++iP ) points(iP+1) = xyz( f->GetNode(iP));
9923     double aspect = qualifier.GetValue( points );
9924     if ( aspect > maxAspectRatio )
9925     {
9926       badTrias.push_back( f );
9927       badAspects.push_back( aspect );
9928     }
9929   }
9930   if ( step == 1 )
9931   {
9932     dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID());
9933     SMDS_ElemIteratorPtr fIt = sm->GetElements();
9934     while ( fIt->more() )
9935     {
9936       const SMDS_MeshElement * f = fIt->next();
9937       if ( f->NbCornerNodes() == 3 )
9938         dumpChangeNodes( f );
9939     }
9940     dumpFunctionEnd();
9941   }
9942   if ( badTrias.empty() )
9943     return;
9944
9945   // find couples of faces to swap diagonal
9946
9947   typedef pair < const SMDS_MeshElement* , const SMDS_MeshElement* > T2Trias;
9948   vector< T2Trias > triaCouples; 
9949
9950   TIDSortedElemSet involvedFaces, emptySet;
9951   for ( size_t iTia = 0; iTia < badTrias.size(); ++iTia )
9952   {
9953     T2Trias trias    [3];
9954     double  aspRatio [3];
9955     int i1, i2, i3;
9956
9957     if ( !involvedFaces.insert( badTrias[iTia] ).second )
9958       continue;
9959     for ( int iP = 0; iP < 3; ++iP )
9960       points(iP+1) = xyz( badTrias[iTia]->GetNode(iP));
9961
9962     // find triangles adjacent to badTrias[iTia] with better aspect ratio after diag-swaping
9963     int bestCouple = -1;
9964     for ( int iSide = 0; iSide < 3; ++iSide )
9965     {
9966       const SMDS_MeshNode* n1 = badTrias[iTia]->GetNode( iSide );
9967       const SMDS_MeshNode* n2 = badTrias[iTia]->GetNode(( iSide+1 ) % 3 );
9968       trias [iSide].first  = badTrias[iTia];
9969       trias [iSide].second = SMESH_MeshAlgos::FindFaceInSet( n1, n2, emptySet, involvedFaces,
9970                                                              & i1, & i2 );
9971       if (( ! trias[iSide].second ) ||
9972           ( trias[iSide].second->NbCornerNodes() != 3 ) ||
9973           ( ! sm->Contains( trias[iSide].second )))
9974         continue;
9975
9976       // aspect ratio of an adjacent tria
9977       for ( int iP = 0; iP < 3; ++iP )
9978         points2(iP+1) = xyz( trias[iSide].second->GetNode(iP));
9979       double aspectInit = qualifier.GetValue( points2 );
9980
9981       // arrange nodes as after diag-swaping
9982       if ( helper.WrapIndex( i1+1, 3 ) == i2 )
9983         i3 = helper.WrapIndex( i1-1, 3 );
9984       else
9985         i3 = helper.WrapIndex( i1+1, 3 );
9986       points1 = points;
9987       points1( 1+ iSide ) = points2( 1+ i3 );
9988       points2( 1+ i2    ) = points1( 1+ ( iSide+2 ) % 3 );
9989
9990       // aspect ratio after diag-swaping
9991       aspRatio[ iSide ] = qualifier.GetValue( points1 ) + qualifier.GetValue( points2 );
9992       if ( aspRatio[ iSide ] > aspectInit + badAspects[ iTia ] )
9993         continue;
9994
9995       // prevent inversion of a triangle
9996       gp_Vec norm1 = gp_Vec( points1(1), points1(3) ) ^ gp_Vec( points1(1), points1(2) );
9997       gp_Vec norm2 = gp_Vec( points2(1), points2(3) ) ^ gp_Vec( points2(1), points2(2) );
9998       if ( norm1 * norm2 < 0. && norm1.Angle( norm2 ) > 70./180.*M_PI )
9999         continue;
10000
10001       if ( bestCouple < 0 || aspRatio[ bestCouple ] > aspRatio[ iSide ] )
10002         bestCouple = iSide;
10003     }
10004
10005     if ( bestCouple >= 0 )
10006     {
10007       triaCouples.push_back( trias[bestCouple] );
10008       involvedFaces.insert ( trias[bestCouple].second );
10009     }
10010     else
10011     {
10012       involvedFaces.erase( badTrias[iTia] );
10013     }
10014   }
10015   if ( triaCouples.empty() )
10016     return;
10017
10018   // swap diagonals
10019
10020   SMESH_MeshEditor editor( helper.GetMesh() );
10021   dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
10022   for ( size_t i = 0; i < triaCouples.size(); ++i )
10023   {
10024     dumpChangeNodes( triaCouples[i].first );
10025     dumpChangeNodes( triaCouples[i].second );
10026     editor.InverseDiag( triaCouples[i].first, triaCouples[i].second );
10027   }
10028
10029   if ( involvedNodes )
10030     for ( size_t i = 0; i < triaCouples.size(); ++i )
10031     {
10032       involvedNodes->insert( triaCouples[i].first->begin_nodes(),
10033                              triaCouples[i].first->end_nodes() );
10034       involvedNodes->insert( triaCouples[i].second->begin_nodes(),
10035                              triaCouples[i].second->end_nodes() );
10036     }
10037
10038   // just for debug dump resulting triangles
10039   dumpFunction(SMESH_Comment("swapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
10040   for ( size_t i = 0; i < triaCouples.size(); ++i )
10041   {
10042     dumpChangeNodes( triaCouples[i].first );
10043     dumpChangeNodes( triaCouples[i].second );
10044   }
10045 }
10046
10047 //================================================================================
10048 /*!
10049  * \brief Move target node to it's final position on the FACE during shrinking
10050  */
10051 //================================================================================
10052
10053 bool _LayerEdge::SetNewLength2d( Handle(Geom_Surface)& surface,
10054                                  const TopoDS_Face&    F,
10055                                  _EdgesOnShape&        eos,
10056                                  SMESH_MesherHelper&   helper )
10057 {
10058   if ( _pos.empty() )
10059     return false; // already at the target position
10060
10061   SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( _nodes.back() );
10062
10063   if ( eos.SWOLType() == TopAbs_FACE )
10064   {
10065     gp_XY    curUV = helper.GetNodeUV( F, tgtNode );
10066     gp_Pnt2d tgtUV( _pos[0].X(), _pos[0].Y() );
10067     gp_Vec2d uvDir( _normal.X(), _normal.Y() );
10068     const double uvLen = tgtUV.Distance( curUV );
10069     const double kSafe = Max( 0.5, 1. - 0.1 * _simplices.size() );
10070
10071     // Select shrinking step such that not to make faces with wrong orientation.
10072     double stepSize = 1e100;
10073     for ( size_t i = 0; i < _simplices.size(); ++i )
10074     {
10075       // find intersection of 2 lines: curUV-tgtUV and that connecting simplex nodes
10076       gp_XY uvN1 = helper.GetNodeUV( F, _simplices[i]._nPrev );
10077       gp_XY uvN2 = helper.GetNodeUV( F, _simplices[i]._nNext );
10078       gp_XY dirN = uvN2 - uvN1;
10079       double det = uvDir.Crossed( dirN );
10080       if ( Abs( det )  < std::numeric_limits<double>::min() ) continue;
10081       gp_XY dirN2Cur = curUV - uvN1;
10082       double step = dirN.Crossed( dirN2Cur ) / det;
10083       if ( step > 0 )
10084         stepSize = Min( step, stepSize );
10085     }
10086     gp_Pnt2d newUV;
10087     if ( uvLen <= stepSize )
10088     {
10089       newUV = tgtUV;
10090       _pos.clear();
10091     }
10092     else if ( stepSize > 0 )
10093     {
10094       newUV = curUV + uvDir.XY() * stepSize * kSafe;
10095     }
10096     else
10097     {
10098       return true;
10099     }
10100     SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
10101     pos->SetUParameter( newUV.X() );
10102     pos->SetVParameter( newUV.Y() );
10103
10104 #ifdef __myDEBUG
10105     gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
10106     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
10107     dumpMove( tgtNode );
10108 #endif
10109   }
10110   else // _sWOL is TopAbs_EDGE
10111   {
10112     const TopoDS_Edge&      E = TopoDS::Edge( eos._sWOL );
10113     const SMDS_MeshNode*   n2 = _simplices[0]._nPrev;
10114     SMDS_EdgePosition* tgtPos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
10115
10116     const double u2     = helper.GetNodeU( E, n2, tgtNode );
10117     const double uSrc   = _pos[0].Coord( U_SRC );
10118     const double lenTgt = _pos[0].Coord( LEN_TGT );
10119
10120     double newU = _pos[0].Coord( U_TGT );
10121     if ( lenTgt < 0.99 * fabs( uSrc-u2 )) // n2 got out of src-tgt range
10122     {
10123       _pos.clear();
10124     }
10125     else
10126     {
10127       newU = 0.1 * tgtPos->GetUParameter() + 0.9 * u2;
10128     }
10129     tgtPos->SetUParameter( newU );
10130 #ifdef __myDEBUG
10131     gp_XY newUV = helper.GetNodeUV( F, tgtNode, _nodes[0]);
10132     gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
10133     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
10134     dumpMove( tgtNode );
10135 #endif
10136   }
10137
10138   return true;
10139 }
10140
10141 //================================================================================
10142 /*!
10143  * \brief Perform smooth on the FACE
10144  *  \retval bool - true if the node has been moved
10145  */
10146 //================================================================================
10147
10148 bool _SmoothNode::Smooth(int&                  badNb,
10149                          Handle(Geom_Surface)& surface,
10150                          SMESH_MesherHelper&   helper,
10151                          const double          refSign,
10152                          SmoothType            how,
10153                          bool                  set3D)
10154 {
10155   const TopoDS_Face& face = TopoDS::Face( helper.GetSubShape() );
10156
10157   // get uv of surrounding nodes
10158   vector<gp_XY> uv( _simplices.size() );
10159   for ( size_t i = 0; i < _simplices.size(); ++i )
10160     uv[i] = helper.GetNodeUV( face, _simplices[i]._nPrev, _node );
10161
10162   // compute new UV for the node
10163   gp_XY newPos (0,0);
10164   if ( how == TFI && _simplices.size() == 4 )
10165   {
10166     gp_XY corners[4];
10167     for ( size_t i = 0; i < _simplices.size(); ++i )
10168       if ( _simplices[i]._nOpp )
10169         corners[i] = helper.GetNodeUV( face, _simplices[i]._nOpp, _node );
10170       else
10171         throw SALOME_Exception(LOCALIZED("TFI smoothing: _Simplex::_nOpp not set!"));
10172
10173     newPos = helper.calcTFI ( 0.5, 0.5,
10174                               corners[0], corners[1], corners[2], corners[3],
10175                               uv[1], uv[2], uv[3], uv[0] );
10176   }
10177   else if ( how == ANGULAR )
10178   {
10179     newPos = computeAngularPos( uv, helper.GetNodeUV( face, _node ), refSign );
10180   }
10181   else if ( how == CENTROIDAL && _simplices.size() > 3 )
10182   {
10183     // average centers of diagonals wieghted with their reciprocal lengths
10184     if ( _simplices.size() == 4 )
10185     {
10186       double w1 = 1. / ( uv[2]-uv[0] ).SquareModulus();
10187       double w2 = 1. / ( uv[3]-uv[1] ).SquareModulus();
10188       newPos = ( w1 * ( uv[2]+uv[0] ) + w2 * ( uv[3]+uv[1] )) / ( w1+w2 ) / 2;
10189     }
10190     else
10191     {
10192       double sumWeight = 0;
10193       int nb = _simplices.size() == 4 ? 2 : _simplices.size();
10194       for ( int i = 0; i < nb; ++i )
10195       {
10196         int iFrom = i + 2;
10197         int iTo   = i + _simplices.size() - 1;
10198         for ( int j = iFrom; j < iTo; ++j )
10199         {
10200           int i2 = SMESH_MesherHelper::WrapIndex( j, _simplices.size() );
10201           double w = 1. / ( uv[i]-uv[i2] ).SquareModulus();
10202           sumWeight += w;
10203           newPos += w * ( uv[i]+uv[i2] );
10204         }
10205       }
10206       newPos /= 2 * sumWeight; // 2 is to get a middle between uv's
10207     }
10208   }
10209   else
10210   {
10211     // Laplacian smooth
10212     for ( size_t i = 0; i < _simplices.size(); ++i )
10213       newPos += uv[i];
10214     newPos /= _simplices.size();
10215   }
10216
10217   // count quality metrics (orientation) of triangles around the node
10218   int nbOkBefore = 0;
10219   gp_XY tgtUV = helper.GetNodeUV( face, _node );
10220   for ( size_t i = 0; i < _simplices.size(); ++i )
10221     nbOkBefore += _simplices[i].IsForward( tgtUV, _node, face, helper, refSign );
10222
10223   int nbOkAfter = 0;
10224   for ( size_t i = 0; i < _simplices.size(); ++i )
10225     nbOkAfter += _simplices[i].IsForward( newPos, _node, face, helper, refSign );
10226
10227   if ( nbOkAfter < nbOkBefore )
10228   {
10229     badNb += _simplices.size() - nbOkBefore;
10230     return false;
10231   }
10232
10233   SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( _node->GetPosition() );
10234   pos->SetUParameter( newPos.X() );
10235   pos->SetVParameter( newPos.Y() );
10236
10237 #ifdef __myDEBUG
10238   set3D = true;
10239 #endif
10240   if ( set3D )
10241   {
10242     gp_Pnt p = surface->Value( newPos.X(), newPos.Y() );
10243     const_cast< SMDS_MeshNode* >( _node )->setXYZ( p.X(), p.Y(), p.Z() );
10244     dumpMove( _node );
10245   }
10246
10247   badNb += _simplices.size() - nbOkAfter;
10248   return ( (tgtUV-newPos).SquareModulus() > 1e-10 );
10249 }
10250
10251 //================================================================================
10252 /*!
10253  * \brief Computes new UV using angle based smoothing technic
10254  */
10255 //================================================================================
10256
10257 gp_XY _SmoothNode::computeAngularPos(vector<gp_XY>& uv,
10258                                      const gp_XY&   uvToFix,
10259                                      const double   refSign)
10260 {
10261   uv.push_back( uv.front() );
10262
10263   vector< gp_XY >  edgeDir ( uv.size() );
10264   vector< double > edgeSize( uv.size() );
10265   for ( size_t i = 1; i < edgeDir.size(); ++i )
10266   {
10267     edgeDir [i-1] = uv[i] - uv[i-1];
10268     edgeSize[i-1] = edgeDir[i-1].Modulus();
10269     if ( edgeSize[i-1] < numeric_limits<double>::min() )
10270       edgeDir[i-1].SetX( 100 );
10271     else
10272       edgeDir[i-1] /= edgeSize[i-1] * refSign;
10273   }
10274   edgeDir.back()  = edgeDir.front();
10275   edgeSize.back() = edgeSize.front();
10276
10277   gp_XY  newPos(0,0);
10278   //int    nbEdges = 0;
10279   double sumSize = 0;
10280   for ( size_t i = 1; i < edgeDir.size(); ++i )
10281   {
10282     if ( edgeDir[i-1].X() > 1. ) continue;
10283     int i1 = i-1;
10284     while ( edgeDir[i].X() > 1. && ++i < edgeDir.size() );
10285     if ( i == edgeDir.size() ) break;
10286     gp_XY p = uv[i];
10287     gp_XY norm1( -edgeDir[i1].Y(), edgeDir[i1].X() );
10288     gp_XY norm2( -edgeDir[i].Y(),  edgeDir[i].X() );
10289     gp_XY bisec = norm1 + norm2;
10290     double bisecSize = bisec.Modulus();
10291     if ( bisecSize < numeric_limits<double>::min() )
10292     {
10293       bisec = -edgeDir[i1] + edgeDir[i];
10294       bisecSize = bisec.Modulus();
10295     }
10296     bisec /= bisecSize;
10297
10298     gp_XY  dirToN  = uvToFix - p;
10299     double distToN = dirToN.Modulus();
10300     if ( bisec * dirToN < 0 )
10301       distToN = -distToN;
10302
10303     newPos += ( p + bisec * distToN ) * ( edgeSize[i1] + edgeSize[i] );
10304     //++nbEdges;
10305     sumSize += edgeSize[i1] + edgeSize[i];
10306   }
10307   newPos /= /*nbEdges * */sumSize;
10308   return newPos;
10309 }
10310
10311 //================================================================================
10312 /*!
10313  * \brief Delete _SolidData
10314  */
10315 //================================================================================
10316
10317 _SolidData::~_SolidData()
10318 {
10319   TNode2Edge::iterator n2e = _n2eMap.begin();
10320   for ( ; n2e != _n2eMap.end(); ++n2e )
10321   {
10322     _LayerEdge* & e = n2e->second;
10323     if ( e )
10324     {
10325       delete e->_curvature;
10326       if ( e->_2neibors )
10327         delete e->_2neibors->_plnNorm;
10328       delete e->_2neibors;
10329     }
10330     delete e;
10331     e = 0;
10332   }
10333   _n2eMap.clear();
10334
10335   delete _helper;
10336   _helper = 0;
10337 }
10338
10339 //================================================================================
10340 /*!
10341  * \brief Keep a _LayerEdge inflated along the EDGE
10342  */
10343 //================================================================================
10344
10345 void _Shrinker1D::AddEdge( const _LayerEdge*   e,
10346                            _EdgesOnShape&      eos,
10347                            SMESH_MesherHelper& helper )
10348 {
10349   // init
10350   if ( _nodes.empty() )
10351   {
10352     _edges[0] = _edges[1] = 0;
10353     _done = false;
10354   }
10355   // check _LayerEdge
10356   if ( e == _edges[0] || e == _edges[1] )
10357     return;
10358   if ( eos.SWOLType() != TopAbs_EDGE )
10359     throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
10360   if ( _edges[0] && !_geomEdge.IsSame( eos._sWOL ))
10361     throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
10362
10363   // store _LayerEdge
10364   _geomEdge = TopoDS::Edge( eos._sWOL );
10365   double f,l;
10366   BRep_Tool::Range( _geomEdge, f,l );
10367   double u = helper.GetNodeU( _geomEdge, e->_nodes[0], e->_nodes.back());
10368   _edges[ u < 0.5*(f+l) ? 0 : 1 ] = e;
10369
10370   // Update _nodes
10371
10372   const SMDS_MeshNode* tgtNode0 = TgtNode( 0 );
10373   const SMDS_MeshNode* tgtNode1 = TgtNode( 1 );
10374
10375   if ( _nodes.empty() )
10376   {
10377     SMESHDS_SubMesh * eSubMesh = helper.GetMeshDS()->MeshElements( _geomEdge );
10378     if ( !eSubMesh || eSubMesh->NbNodes() < 1 )
10379       return;
10380     TopLoc_Location loc;
10381     Handle(Geom_Curve) C = BRep_Tool::Curve( _geomEdge, loc, f,l );
10382     GeomAdaptor_Curve aCurve(C, f,l);
10383     const double totLen = GCPnts_AbscissaPoint::Length(aCurve, f, l);
10384
10385     int nbExpectNodes = eSubMesh->NbNodes();
10386     _initU  .reserve( nbExpectNodes );
10387     _normPar.reserve( nbExpectNodes );
10388     _nodes  .reserve( nbExpectNodes );
10389     SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
10390     while ( nIt->more() )
10391     {
10392       const SMDS_MeshNode* node = nIt->next();
10393       if ( node->NbInverseElements(SMDSAbs_Edge) == 0 ||
10394            node == tgtNode0 || node == tgtNode1 )
10395         continue; // refinement nodes
10396       _nodes.push_back( node );
10397       _initU.push_back( helper.GetNodeU( _geomEdge, node ));
10398       double len = GCPnts_AbscissaPoint::Length(aCurve, f, _initU.back());
10399       _normPar.push_back(  len / totLen );
10400     }
10401   }
10402   else
10403   {
10404     // remove target node of the _LayerEdge from _nodes
10405     size_t nbFound = 0;
10406     for ( size_t i = 0; i < _nodes.size(); ++i )
10407       if ( !_nodes[i] || _nodes[i] == tgtNode0 || _nodes[i] == tgtNode1 )
10408         _nodes[i] = 0, nbFound++;
10409     if ( nbFound == _nodes.size() )
10410       _nodes.clear();
10411   }
10412 }
10413
10414 //================================================================================
10415 /*!
10416  * \brief Move nodes on EDGE from ends where _LayerEdge's are inflated
10417  */
10418 //================================================================================
10419
10420 void _Shrinker1D::Compute(bool set3D, SMESH_MesherHelper& helper)
10421 {
10422   if ( _done || _nodes.empty())
10423     return;
10424   const _LayerEdge* e = _edges[0];
10425   if ( !e ) e = _edges[1];
10426   if ( !e ) return;
10427
10428   _done =  (( !_edges[0] || _edges[0]->_pos.empty() ) &&
10429             ( !_edges[1] || _edges[1]->_pos.empty() ));
10430
10431   double f,l;
10432   if ( set3D || _done )
10433   {
10434     Handle(Geom_Curve) C = BRep_Tool::Curve(_geomEdge, f,l);
10435     GeomAdaptor_Curve aCurve(C, f,l);
10436
10437     if ( _edges[0] )
10438       f = helper.GetNodeU( _geomEdge, _edges[0]->_nodes.back(), _nodes[0] );
10439     if ( _edges[1] )
10440       l = helper.GetNodeU( _geomEdge, _edges[1]->_nodes.back(), _nodes.back() );
10441     double totLen = GCPnts_AbscissaPoint::Length( aCurve, f, l );
10442
10443     for ( size_t i = 0; i < _nodes.size(); ++i )
10444     {
10445       if ( !_nodes[i] ) continue;
10446       double len = totLen * _normPar[i];
10447       GCPnts_AbscissaPoint discret( aCurve, len, f );
10448       if ( !discret.IsDone() )
10449         return throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
10450       double u = discret.Parameter();
10451       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
10452       pos->SetUParameter( u );
10453       gp_Pnt p = C->Value( u );
10454       const_cast< SMDS_MeshNode*>( _nodes[i] )->setXYZ( p.X(), p.Y(), p.Z() );
10455     }
10456   }
10457   else
10458   {
10459     BRep_Tool::Range( _geomEdge, f,l );
10460     if ( _edges[0] )
10461       f = helper.GetNodeU( _geomEdge, _edges[0]->_nodes.back(), _nodes[0] );
10462     if ( _edges[1] )
10463       l = helper.GetNodeU( _geomEdge, _edges[1]->_nodes.back(), _nodes.back() );
10464     
10465     for ( size_t i = 0; i < _nodes.size(); ++i )
10466     {
10467       if ( !_nodes[i] ) continue;
10468       double u = f * ( 1-_normPar[i] ) + l * _normPar[i];
10469       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
10470       pos->SetUParameter( u );
10471     }
10472   }
10473 }
10474
10475 //================================================================================
10476 /*!
10477  * \brief Restore initial parameters of nodes on EDGE
10478  */
10479 //================================================================================
10480
10481 void _Shrinker1D::RestoreParams()
10482 {
10483   if ( _done )
10484     for ( size_t i = 0; i < _nodes.size(); ++i )
10485     {
10486       if ( !_nodes[i] ) continue;
10487       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
10488       pos->SetUParameter( _initU[i] );
10489     }
10490   _done = false;
10491 }
10492
10493 //================================================================================
10494 /*!
10495  * \brief Replace source nodes by target nodes in shrinked mesh edges
10496  */
10497 //================================================================================
10498
10499 void _Shrinker1D::SwapSrcTgtNodes( SMESHDS_Mesh* mesh )
10500 {
10501   const SMDS_MeshNode* nodes[3];
10502   for ( int i = 0; i < 2; ++i )
10503   {
10504     if ( !_edges[i] ) continue;
10505
10506     SMESHDS_SubMesh * eSubMesh = mesh->MeshElements( _geomEdge );
10507     if ( !eSubMesh ) return;
10508     const SMDS_MeshNode* srcNode = _edges[i]->_nodes[0];
10509     const SMDS_MeshNode* tgtNode = _edges[i]->_nodes.back();
10510     SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
10511     while ( eIt->more() )
10512     {
10513       const SMDS_MeshElement* e = eIt->next();
10514       if ( !eSubMesh->Contains( e ))
10515           continue;
10516       SMDS_ElemIteratorPtr nIt = e->nodesIterator();
10517       for ( int iN = 0; iN < e->NbNodes(); ++iN )
10518       {
10519         const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
10520         nodes[iN] = ( n == srcNode ? tgtNode : n );
10521       }
10522       mesh->ChangeElementNodes( e, nodes, e->NbNodes() );
10523     }
10524   }
10525 }
10526
10527 //================================================================================
10528 /*!
10529  * \brief Creates 2D and 1D elements on boundaries of new prisms
10530  */
10531 //================================================================================
10532
10533 bool _ViscousBuilder::addBoundaryElements()
10534 {
10535   SMESH_MesherHelper helper( *_mesh );
10536
10537   vector< const SMDS_MeshNode* > faceNodes;
10538
10539   for ( size_t i = 0; i < _sdVec.size(); ++i )
10540   {
10541     _SolidData& data = _sdVec[i];
10542     TopTools_IndexedMapOfShape geomEdges;
10543     TopExp::MapShapes( data._solid, TopAbs_EDGE, geomEdges );
10544     for ( int iE = 1; iE <= geomEdges.Extent(); ++iE )
10545     {
10546       const TopoDS_Edge& E = TopoDS::Edge( geomEdges(iE));
10547       if ( data._noShrinkShapes.count( getMeshDS()->ShapeToIndex( E )))
10548         continue;
10549
10550       // Get _LayerEdge's based on E
10551
10552       map< double, const SMDS_MeshNode* > u2nodes;
10553       if ( !SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), E, /*ignoreMedium=*/false, u2nodes))
10554         continue;
10555
10556       vector< _LayerEdge* > ledges; ledges.reserve( u2nodes.size() );
10557       TNode2Edge & n2eMap = data._n2eMap;
10558       map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
10559       {
10560         //check if 2D elements are needed on E
10561         TNode2Edge::iterator n2e = n2eMap.find( u2n->second );
10562         if ( n2e == n2eMap.end() ) continue; // no layers on vertex
10563         ledges.push_back( n2e->second );
10564         u2n++;
10565         if (( n2e = n2eMap.find( u2n->second )) == n2eMap.end() )
10566           continue; // no layers on E
10567         ledges.push_back( n2eMap[ u2n->second ]);
10568
10569         const SMDS_MeshNode* tgtN0 = ledges[0]->_nodes.back();
10570         const SMDS_MeshNode* tgtN1 = ledges[1]->_nodes.back();
10571         int nbSharedPyram = 0;
10572         SMDS_ElemIteratorPtr vIt = tgtN0->GetInverseElementIterator(SMDSAbs_Volume);
10573         while ( vIt->more() )
10574         {
10575           const SMDS_MeshElement* v = vIt->next();
10576           nbSharedPyram += int( v->GetNodeIndex( tgtN1 ) >= 0 );
10577         }
10578         if ( nbSharedPyram > 1 )
10579           continue; // not free border of the pyramid
10580
10581         faceNodes.clear();
10582         faceNodes.push_back( ledges[0]->_nodes[0] );
10583         faceNodes.push_back( ledges[1]->_nodes[0] );
10584         if ( ledges[0]->_nodes.size() > 1 ) faceNodes.push_back( ledges[0]->_nodes[1] );
10585         if ( ledges[1]->_nodes.size() > 1 ) faceNodes.push_back( ledges[1]->_nodes[1] );
10586
10587         if ( getMeshDS()->FindElement( faceNodes, SMDSAbs_Face, /*noMedium=*/true))
10588           continue; // faces already created
10589       }
10590       for ( ++u2n; u2n != u2nodes.end(); ++u2n )
10591         ledges.push_back( n2eMap[ u2n->second ]);
10592
10593       // Find out orientation and type of face to create
10594
10595       bool reverse = false, isOnFace;
10596       
10597       map< TGeomID, TopoDS_Shape >::iterator e2f =
10598         data._shrinkShape2Shape.find( getMeshDS()->ShapeToIndex( E ));
10599       TopoDS_Shape F;
10600       if (( isOnFace = ( e2f != data._shrinkShape2Shape.end() )))
10601       {
10602         F = e2f->second.Oriented( TopAbs_FORWARD );
10603         reverse = ( helper.GetSubShapeOri( F, E ) == TopAbs_REVERSED );
10604         if ( helper.GetSubShapeOri( data._solid, F ) == TopAbs_REVERSED )
10605           reverse = !reverse, F.Reverse();
10606         if ( helper.IsReversedSubMesh( TopoDS::Face(F) ))
10607           reverse = !reverse;
10608       }
10609       else
10610       {
10611         // find FACE with layers sharing E
10612         PShapeIteratorPtr fIt = helper.GetAncestors( E, *_mesh, TopAbs_FACE );
10613         while ( fIt->more() && F.IsNull() )
10614         {
10615           const TopoDS_Shape* pF = fIt->next();
10616           if ( helper.IsSubShape( *pF, data._solid) &&
10617                !data._ignoreFaceIds.count( e2f->first ))
10618             F = *pF;
10619         }
10620       }
10621       // Find the sub-mesh to add new faces
10622       SMESHDS_SubMesh* sm = 0;
10623       if ( isOnFace )
10624         sm = getMeshDS()->MeshElements( F );
10625       else
10626         sm = data._proxyMesh->getFaceSubM( TopoDS::Face(F), /*create=*/true );
10627       if ( !sm )
10628         return error("error in addBoundaryElements()", data._index);
10629
10630       // Make faces
10631       const int dj1 = reverse ? 0 : 1;
10632       const int dj2 = reverse ? 1 : 0;
10633       for ( size_t j = 1; j < ledges.size(); ++j )
10634       {
10635         vector< const SMDS_MeshNode*>&  nn1 = ledges[j-dj1]->_nodes;
10636         vector< const SMDS_MeshNode*>&  nn2 = ledges[j-dj2]->_nodes;
10637         if ( nn1.size() == nn2.size() )
10638         {
10639           if ( isOnFace )
10640             for ( size_t z = 1; z < nn1.size(); ++z )
10641               sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
10642           else
10643             for ( size_t z = 1; z < nn1.size(); ++z )
10644               sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
10645         }
10646         else if ( nn1.size() == 1 )
10647         {
10648           if ( isOnFace )
10649             for ( size_t z = 1; z < nn2.size(); ++z )
10650               sm->AddElement( getMeshDS()->AddFace( nn1[0], nn2[z-1], nn2[z] ));
10651           else
10652             for ( size_t z = 1; z < nn2.size(); ++z )
10653               sm->AddElement( new SMDS_FaceOfNodes( nn1[0], nn2[z-1], nn2[z] ));
10654         }
10655         else
10656         {
10657           if ( isOnFace )
10658             for ( size_t z = 1; z < nn1.size(); ++z )
10659               sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[0], nn1[z] ));
10660           else
10661             for ( size_t z = 1; z < nn1.size(); ++z )
10662               sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[0], nn2[z] ));
10663         }
10664       }
10665
10666       // Make edges
10667       for ( int isFirst = 0; isFirst < 2; ++isFirst )
10668       {
10669         _LayerEdge* edge = isFirst ? ledges.front() : ledges.back();
10670         _EdgesOnShape* eos = data.GetShapeEdges( edge );
10671         if ( eos && eos->SWOLType() == TopAbs_EDGE )
10672         {
10673           vector< const SMDS_MeshNode*>&  nn = edge->_nodes;
10674           if ( nn.size() < 2 || nn[1]->GetInverseElementIterator( SMDSAbs_Edge )->more() )
10675             continue;
10676           helper.SetSubShape( eos->_sWOL );
10677           helper.SetElementsOnShape( true );
10678           for ( size_t z = 1; z < nn.size(); ++z )
10679             helper.AddEdge( nn[z-1], nn[z] );
10680         }
10681       }
10682
10683     } // loop on EDGE's
10684   } // loop on _SolidData's
10685
10686   return true;
10687 }