Salome HOME
a6530b9244a5782abe3a820e82075e2aab951077
[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 "SMESHDS_Mesh.hxx"
34 #include "SMESH_Algo.hxx"
35 #include "SMESH_ComputeError.hxx"
36 #include "SMESH_ControlsDef.hxx"
37 #include "SMESH_Gen.hxx"
38 #include "SMESH_Group.hxx"
39 #include "SMESH_HypoFilter.hxx"
40 #include "SMESH_Mesh.hxx"
41 #include "SMESH_MeshAlgos.hxx"
42 #include "SMESH_MesherHelper.hxx"
43 #include "SMESH_ProxyMesh.hxx"
44 #include "SMESH_subMesh.hxx"
45 #include "SMESH_subMeshEventListener.hxx"
46 #include "StdMeshers_FaceSide.hxx"
47 #include "StdMeshers_ViscousLayers2D.hxx"
48
49 #include <Adaptor3d_HSurface.hxx>
50 #include <BRepAdaptor_Curve.hxx>
51 #include <BRepAdaptor_Curve2d.hxx>
52 #include <BRepAdaptor_Surface.hxx>
53 //#include <BRepLProp_CLProps.hxx>
54 #include <BRepLProp_SLProps.hxx>
55 #include <BRepOffsetAPI_MakeOffsetShape.hxx>
56 #include <BRep_Tool.hxx>
57 #include <Bnd_B2d.hxx>
58 #include <Bnd_B3d.hxx>
59 #include <ElCLib.hxx>
60 #include <GCPnts_AbscissaPoint.hxx>
61 #include <GCPnts_TangentialDeflection.hxx>
62 #include <Geom2d_Circle.hxx>
63 #include <Geom2d_Line.hxx>
64 #include <Geom2d_TrimmedCurve.hxx>
65 #include <GeomAdaptor_Curve.hxx>
66 #include <GeomLib.hxx>
67 #include <Geom_Circle.hxx>
68 #include <Geom_Curve.hxx>
69 #include <Geom_Line.hxx>
70 #include <Geom_TrimmedCurve.hxx>
71 #include <Precision.hxx>
72 #include <Standard_ErrorHandler.hxx>
73 #include <Standard_Failure.hxx>
74 #include <TColStd_Array1OfReal.hxx>
75 #include <TopExp.hxx>
76 #include <TopExp_Explorer.hxx>
77 #include <TopTools_IndexedMapOfShape.hxx>
78 #include <TopTools_ListOfShape.hxx>
79 #include <TopTools_MapIteratorOfMapOfShape.hxx>
80 #include <TopTools_MapOfShape.hxx>
81 #include <TopoDS.hxx>
82 #include <TopoDS_Edge.hxx>
83 #include <TopoDS_Face.hxx>
84 #include <TopoDS_Vertex.hxx>
85 #include <gp_Ax1.hxx>
86 #include <gp_Cone.hxx>
87 #include <gp_Sphere.hxx>
88 #include <gp_Vec.hxx>
89 #include <gp_XY.hxx>
90
91 #include <cmath>
92 #include <limits>
93 #include <list>
94 #include <queue>
95 #include <string>
96
97 #ifdef _DEBUG_
98 //#define __myDEBUG
99 //#define __NOT_INVALIDATE_BAD_SMOOTH
100 //#define __NODES_AT_POS
101 #endif
102
103 #define INCREMENTAL_SMOOTH // smooth only if min angle is too small
104 #define BLOCK_INFLATION // of individual _LayerEdge's
105 #define OLD_NEF_POLYGON
106
107 using namespace std;
108
109 //================================================================================
110 namespace VISCOUS_3D
111 {
112   typedef int TGeomID;
113
114   enum UIndex { U_TGT = 1, U_SRC, LEN_TGT };
115
116   const double theMinSmoothCosin = 0.1;
117   const double theSmoothThickToElemSizeRatio = 0.3;
118   const double theMinSmoothTriaAngle = 30;
119   const double theMinSmoothQuadAngle = 45;
120
121   // what part of thickness is allowed till intersection
122   // (defined by SALOME_TESTS/Grids/smesh/viscous_layers_00/A5)
123   const double theThickToIntersection = 1.5;
124
125   bool needSmoothing( double cosin, double tgtThick, double elemSize )
126   {
127     return cosin * tgtThick > theSmoothThickToElemSizeRatio * elemSize;
128   }
129   double getSmoothingThickness( double cosin, double elemSize )
130   {
131     return theSmoothThickToElemSizeRatio * elemSize / cosin;
132   }
133
134   /*!
135    * \brief SMESH_ProxyMesh computed by _ViscousBuilder for a SOLID.
136    * It is stored in a SMESH_subMesh of the SOLID as SMESH_subMeshEventListenerData
137    */
138   struct _MeshOfSolid : public SMESH_ProxyMesh,
139                         public SMESH_subMeshEventListenerData
140   {
141     bool                  _n2nMapComputed;
142     SMESH_ComputeErrorPtr _warning;
143
144     _MeshOfSolid( SMESH_Mesh* mesh)
145       :SMESH_subMeshEventListenerData( /*isDeletable=*/true),_n2nMapComputed(false)
146     {
147       SMESH_ProxyMesh::setMesh( *mesh );
148     }
149
150     // returns submesh for a geom face
151     SMESH_ProxyMesh::SubMesh* getFaceSubM(const TopoDS_Face& F, bool create=false)
152     {
153       TGeomID i = SMESH_ProxyMesh::shapeIndex(F);
154       return create ? SMESH_ProxyMesh::getProxySubMesh(i) : findProxySubMesh(i);
155     }
156     void setNode2Node(const SMDS_MeshNode*                 srcNode,
157                       const SMDS_MeshNode*                 proxyNode,
158                       const SMESH_ProxyMesh::SubMesh* subMesh)
159     {
160       SMESH_ProxyMesh::setNode2Node( srcNode,proxyNode,subMesh);
161     }
162   };
163   //--------------------------------------------------------------------------------
164   /*!
165    * \brief Listener of events of 3D sub-meshes computed with viscous layers.
166    * It is used to clear an inferior dim sub-meshes modified by viscous layers
167    */
168   class _ShrinkShapeListener : SMESH_subMeshEventListener
169   {
170     _ShrinkShapeListener()
171       : SMESH_subMeshEventListener(/*isDeletable=*/false,
172                                    "StdMeshers_ViscousLayers::_ShrinkShapeListener") {}
173   public:
174     static SMESH_subMeshEventListener* Get() { static _ShrinkShapeListener l; return &l; }
175     virtual void ProcessEvent(const int                       event,
176                               const int                       eventType,
177                               SMESH_subMesh*                  solidSM,
178                               SMESH_subMeshEventListenerData* data,
179                               const SMESH_Hypothesis*         hyp)
180     {
181       if ( SMESH_subMesh::COMPUTE_EVENT == eventType && solidSM->IsEmpty() && data )
182       {
183         SMESH_subMeshEventListener::ProcessEvent(event,eventType,solidSM,data,hyp);
184       }
185     }
186   };
187   //--------------------------------------------------------------------------------
188   /*!
189    * \brief Listener of events of 3D sub-meshes computed with viscous layers.
190    * It is used to store data computed by _ViscousBuilder for a sub-mesh and to
191    * delete the data as soon as it has been used
192    */
193   class _ViscousListener : SMESH_subMeshEventListener
194   {
195     _ViscousListener():
196       SMESH_subMeshEventListener(/*isDeletable=*/false,
197                                  "StdMeshers_ViscousLayers::_ViscousListener") {}
198     static SMESH_subMeshEventListener* Get() { static _ViscousListener l; return &l; }
199   public:
200     virtual void ProcessEvent(const int                       event,
201                               const int                       eventType,
202                               SMESH_subMesh*                  subMesh,
203                               SMESH_subMeshEventListenerData* data,
204                               const SMESH_Hypothesis*         hyp)
205     {
206       if (( SMESH_subMesh::COMPUTE_EVENT       == eventType ) &&
207           ( SMESH_subMesh::CHECK_COMPUTE_STATE != event &&
208             SMESH_subMesh::SUBMESH_COMPUTED    != event ))
209       {
210         // delete SMESH_ProxyMesh containing temporary faces
211         subMesh->DeleteEventListener( this );
212       }
213     }
214     // Finds or creates proxy mesh of the solid
215     static _MeshOfSolid* GetSolidMesh(SMESH_Mesh*         mesh,
216                                       const TopoDS_Shape& solid,
217                                       bool                toCreate=false)
218     {
219       if ( !mesh ) return 0;
220       SMESH_subMesh* sm = mesh->GetSubMesh(solid);
221       _MeshOfSolid* data = (_MeshOfSolid*) sm->GetEventListenerData( Get() );
222       if ( !data && toCreate )
223       {
224         data = new _MeshOfSolid(mesh);
225         data->mySubMeshes.push_back( sm ); // to find SOLID by _MeshOfSolid
226         sm->SetEventListener( Get(), data, sm );
227       }
228       return data;
229     }
230     // Removes proxy mesh of the solid
231     static void RemoveSolidMesh(SMESH_Mesh* mesh, const TopoDS_Shape& solid)
232     {
233       mesh->GetSubMesh(solid)->DeleteEventListener( _ViscousListener::Get() );
234     }
235   };
236   
237   //================================================================================
238   /*!
239    * \brief sets a sub-mesh event listener to clear sub-meshes of sub-shapes of
240    * the main shape when sub-mesh of the main shape is cleared,
241    * for example to clear sub-meshes of FACEs when sub-mesh of a SOLID
242    * is cleared
243    */
244   //================================================================================
245
246   void ToClearSubWithMain( SMESH_subMesh* sub, const TopoDS_Shape& main)
247   {
248     SMESH_subMesh* mainSM = sub->GetFather()->GetSubMesh( main );
249     SMESH_subMeshEventListenerData* data =
250       mainSM->GetEventListenerData( _ShrinkShapeListener::Get());
251     if ( data )
252     {
253       if ( find( data->mySubMeshes.begin(), data->mySubMeshes.end(), sub ) ==
254            data->mySubMeshes.end())
255         data->mySubMeshes.push_back( sub );
256     }
257     else
258     {
259       data = SMESH_subMeshEventListenerData::MakeData( /*dependent=*/sub );
260       sub->SetEventListener( _ShrinkShapeListener::Get(), data, /*whereToListenTo=*/mainSM );
261     }
262   }
263   struct _SolidData;
264   //--------------------------------------------------------------------------------
265   /*!
266    * \brief Simplex (triangle or tetrahedron) based on 1 (tria) or 2 (tet) nodes of
267    * _LayerEdge and 2 nodes of the mesh surface beening smoothed.
268    * The class is used to check validity of face or volumes around a smoothed node;
269    * it stores only 2 nodes as the other nodes are stored by _LayerEdge.
270    */
271   struct _Simplex
272   {
273     const SMDS_MeshNode *_nPrev, *_nNext; // nodes on a smoothed mesh surface
274     const SMDS_MeshNode *_nOpp; // in 2D case, a node opposite to a smoothed node in QUAD
275     _Simplex(const SMDS_MeshNode* nPrev=0,
276              const SMDS_MeshNode* nNext=0,
277              const SMDS_MeshNode* nOpp=0)
278       : _nPrev(nPrev), _nNext(nNext), _nOpp(nOpp) {}
279     bool IsForward(const gp_XYZ* pntSrc, const gp_XYZ* pntTgt, double& vol) const
280     {
281       const double M[3][3] =
282         {{ _nNext->X() - pntSrc->X(), _nNext->Y() - pntSrc->Y(), _nNext->Z() - pntSrc->Z() },
283          { pntTgt->X() - pntSrc->X(), pntTgt->Y() - pntSrc->Y(), pntTgt->Z() - pntSrc->Z() },
284          { _nPrev->X() - pntSrc->X(), _nPrev->Y() - pntSrc->Y(), _nPrev->Z() - pntSrc->Z() }};
285       vol = ( + M[0][0] * M[1][1] * M[2][2]
286               + M[0][1] * M[1][2] * M[2][0]
287               + M[0][2] * M[1][0] * M[2][1]
288               - M[0][0] * M[1][2] * M[2][1]
289               - M[0][1] * M[1][0] * M[2][2]
290               - M[0][2] * M[1][1] * M[2][0]);
291       return vol > 1e-100;
292     }
293     bool IsForward(const SMDS_MeshNode* nSrc, const gp_XYZ& pTgt, double& vol) const
294     {
295       SMESH_TNodeXYZ pSrc( nSrc );
296       return IsForward( &pSrc, &pTgt, vol );
297     }
298     bool IsForward(const gp_XY&         tgtUV,
299                    const SMDS_MeshNode* smoothedNode,
300                    const TopoDS_Face&   face,
301                    SMESH_MesherHelper&  helper,
302                    const double         refSign) const
303     {
304       gp_XY prevUV = helper.GetNodeUV( face, _nPrev, smoothedNode );
305       gp_XY nextUV = helper.GetNodeUV( face, _nNext, smoothedNode );
306       gp_Vec2d v1( tgtUV, prevUV ), v2( tgtUV, nextUV );
307       double d = v1 ^ v2;
308       return d*refSign > 1e-100;
309     }
310     bool IsMinAngleOK( const gp_XYZ& pTgt, double& minAngle ) const
311     {
312       SMESH_TNodeXYZ pPrev( _nPrev ), pNext( _nNext );
313       if ( !_nOpp ) // triangle
314       {
315         gp_Vec tp( pPrev - pTgt ), pn( pNext - pPrev ), nt( pTgt - pNext );
316         double tp2 = tp.SquareMagnitude();
317         double pn2 = pn.SquareMagnitude();
318         double nt2 = nt.SquareMagnitude();
319
320         if ( tp2 < pn2 && tp2 < nt2 )
321           minAngle = ( nt * -pn ) * ( nt * -pn ) / nt2 / pn2;
322         else if ( pn2 < nt2 )
323           minAngle = ( tp * -nt ) * ( tp * -nt ) / tp2 / nt2;
324         else
325           minAngle = ( pn * -tp ) * ( pn * -tp ) / pn2 / tp2;
326
327         static double theMaxCos2 = ( Cos( theMinSmoothTriaAngle * M_PI / 180. ) *
328                                      Cos( theMinSmoothTriaAngle * M_PI / 180. ));
329         return minAngle < theMaxCos2;
330       }
331       else // quadrangle
332       {
333         SMESH_TNodeXYZ pOpp( _nOpp );
334         gp_Vec tp( pPrev - pTgt ), po( pOpp - pPrev ), on( pNext - pOpp), nt( pTgt - pNext );
335         double tp2 = tp.SquareMagnitude();
336         double po2 = po.SquareMagnitude();
337         double on2 = on.SquareMagnitude();
338         double nt2 = nt.SquareMagnitude();
339         minAngle = Max( Max((( tp * -nt ) * ( tp * -nt ) / tp2 / nt2 ),
340                             (( po * -tp ) * ( po * -tp ) / po2 / tp2 )),
341                         Max((( on * -po ) * ( on * -po ) / on2 / po2 ),
342                             (( nt * -on ) * ( nt * -on ) / nt2 / on2 )));
343
344         static double theMaxCos2 = ( Cos( theMinSmoothQuadAngle * M_PI / 180. ) *
345                                      Cos( theMinSmoothQuadAngle * M_PI / 180. ));
346         return minAngle < theMaxCos2;
347       }
348     }
349     bool IsNeighbour(const _Simplex& other) const
350     {
351       return _nPrev == other._nNext || _nNext == other._nPrev;
352     }
353     bool Includes( const SMDS_MeshNode* node ) const { return _nPrev == node || _nNext == node; }
354     static void GetSimplices( const SMDS_MeshNode* node,
355                               vector<_Simplex>&   simplices,
356                               const set<TGeomID>& ingnoreShapes,
357                               const _SolidData*   dataToCheckOri = 0,
358                               const bool          toSort = false);
359     static void SortSimplices(vector<_Simplex>& simplices);
360   };
361   //--------------------------------------------------------------------------------
362   /*!
363    * Structure used to take into account surface curvature while smoothing
364    */
365   struct _Curvature
366   {
367     double   _r; // radius
368     double   _k; // factor to correct node smoothed position
369     double   _h2lenRatio; // avgNormProj / (2*avgDist)
370     gp_Pnt2d _uv; // UV used in putOnOffsetSurface()
371   public:
372     static _Curvature* New( double avgNormProj, double avgDist )
373     {
374       _Curvature* c = 0;
375       if ( fabs( avgNormProj / avgDist ) > 1./200 )
376       {
377         c = new _Curvature;
378         c->_r = avgDist * avgDist / avgNormProj;
379         c->_k = avgDist * avgDist / c->_r / c->_r;
380         //c->_k = avgNormProj / c->_r;
381         c->_k *= ( c->_r < 0 ? 1/1.1 : 1.1 ); // not to be too restrictive
382         c->_h2lenRatio = avgNormProj / ( avgDist + avgDist );
383
384         c->_uv.SetCoord( 0., 0. );
385       }
386       return c;
387     }
388     double lenDelta(double len) const { return _k * ( _r + len ); }
389     double lenDeltaByDist(double dist) const { return dist * _h2lenRatio; }
390   };
391   //--------------------------------------------------------------------------------
392
393   struct _2NearEdges;
394   struct _LayerEdge;
395   struct _EdgesOnShape;
396   struct _Smoother1D;
397   typedef map< const SMDS_MeshNode*, _LayerEdge*, TIDCompare > TNode2Edge;
398
399   //--------------------------------------------------------------------------------
400   /*!
401    * \brief Edge normal to surface, connecting a node on solid surface (_nodes[0])
402    * and a node of the most internal layer (_nodes.back())
403    */
404   struct _LayerEdge
405   {
406     typedef gp_XYZ (_LayerEdge::*PSmooFun)();
407
408     vector< const SMDS_MeshNode*> _nodes;
409
410     gp_XYZ              _normal;    // to boundary of solid
411     vector<gp_XYZ>      _pos;       // points computed during inflation
412     double              _len;       // length achieved with the last inflation step
413     double              _maxLen;    // maximal possible length
414     double              _cosin;     // of angle (_normal ^ surface)
415     double              _minAngle;  // of _simplices
416     double              _lenFactor; // to compute _len taking _cosin into account
417     int                 _flags;
418
419     // simplices connected to the source node (_nodes[0]);
420     // used for smoothing and quality check of _LayerEdge's based on the FACE
421     vector<_Simplex>    _simplices;
422     vector<_LayerEdge*> _neibors; // all surrounding _LayerEdge's
423     PSmooFun            _smooFunction; // smoothing function
424     _Curvature*         _curvature;
425     // data for smoothing of _LayerEdge's based on the EDGE
426     _2NearEdges*        _2neibors;
427
428     enum EFlags { TO_SMOOTH       = 0x0000001,
429                   MOVED           = 0x0000002, // set by _neibors[i]->SetNewLength()
430                   SMOOTHED        = 0x0000004, // set by this->Smooth()
431                   DIFFICULT       = 0x0000008, // near concave VERTEX
432                   ON_CONCAVE_FACE = 0x0000010,
433                   BLOCKED         = 0x0000020, // not to inflate any more
434                   INTERSECTED     = 0x0000040, // close intersection with a face found
435                   NORMAL_UPDATED  = 0x0000080,
436                   MARKED          = 0x0000100, // local usage
437                   MULTI_NORMAL    = 0x0000200, // a normal is invisible by some of surrounding faces
438                   NEAR_BOUNDARY   = 0x0000400, // is near FACE boundary forcing smooth
439                   SMOOTHED_C1     = 0x0000800, // is on _eosC1
440                   DISTORTED       = 0x0001000, // was bad before smoothing
441                   RISKY_SWOL      = 0x0002000, // SWOL is parallel to a source FACE
442                   SHRUNK          = 0x0004000, // target node reached a tgt position while shrink()
443                   UNUSED_FLAG     = 0x0100000  // to add use flags after
444     };
445     bool Is   ( int flag ) const { return _flags & flag; }
446     void Set  ( int flag ) { _flags |= flag; }
447     void Unset( int flag ) { _flags &= ~flag; }
448     std::string DumpFlags() const; // debug
449
450     void SetNewLength( double len, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
451     bool SetNewLength2d( Handle(Geom_Surface)& surface,
452                          const TopoDS_Face&    F,
453                          _EdgesOnShape&        eos,
454                          SMESH_MesherHelper&   helper );
455     void SetDataByNeighbors( const SMDS_MeshNode* n1,
456                              const SMDS_MeshNode* n2,
457                              const _EdgesOnShape& eos,
458                              SMESH_MesherHelper&  helper);
459     void Block( _SolidData& data );
460     void InvalidateStep( size_t curStep, const _EdgesOnShape& eos, bool restoreLength=false );
461     void ChooseSmooFunction(const set< TGeomID >& concaveVertices,
462                             const TNode2Edge&     n2eMap);
463     void SmoothPos( const vector< double >& segLen, const double tol );
464     int  GetSmoothedPos( const double tol );
465     int  Smooth(const int step, const bool isConcaveFace, bool findBest);
466     int  Smooth(const int step, bool findBest, vector< _LayerEdge* >& toSmooth );
467     int  CheckNeiborsOnBoundary(vector< _LayerEdge* >* badNeibors = 0, bool * needSmooth = 0 );
468     void SmoothWoCheck();
469     bool SmoothOnEdge(Handle(ShapeAnalysis_Surface)& surface,
470                       const TopoDS_Face&             F,
471                       SMESH_MesherHelper&            helper);
472     void MoveNearConcaVer( const _EdgesOnShape*    eov,
473                            const _EdgesOnShape*    eos,
474                            const int               step,
475                            vector< _LayerEdge* > & badSmooEdges);
476     bool FindIntersection( SMESH_ElementSearcher&   searcher,
477                            double &                 distance,
478                            const double&            epsilon,
479                            _EdgesOnShape&           eos,
480                            const SMDS_MeshElement** face = 0);
481     bool SegTriaInter( const gp_Ax1&        lastSegment,
482                        const gp_XYZ&        p0,
483                        const gp_XYZ&        p1,
484                        const gp_XYZ&        p2,
485                        double&              dist,
486                        const double&        epsilon) const;
487     bool SegTriaInter( const gp_Ax1&        lastSegment,
488                        const SMDS_MeshNode* n0,
489                        const SMDS_MeshNode* n1,
490                        const SMDS_MeshNode* n2,
491                        double&              dist,
492                        const double&        epsilon) const
493     { return SegTriaInter( lastSegment,
494                            SMESH_TNodeXYZ( n0 ), SMESH_TNodeXYZ( n1 ), SMESH_TNodeXYZ( n2 ),
495                            dist, epsilon );
496     }
497     const gp_XYZ& PrevPos() const { return _pos[ _pos.size() - 2 ]; }
498     gp_XYZ PrevCheckPos( _EdgesOnShape* eos=0 ) const;
499     gp_Ax1 LastSegment(double& segLen, _EdgesOnShape& eos) const;
500     gp_XY  LastUV( const TopoDS_Face& F, _EdgesOnShape& eos ) const;
501     bool   IsOnEdge() const { return _2neibors; }
502     gp_XYZ Copy( _LayerEdge& other, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
503     void   SetCosin( double cosin );
504     void   SetNormal( const gp_XYZ& n ) { _normal = n; }
505     int    NbSteps() const { return _pos.size() - 1; } // nb inlation steps
506     bool   IsNeiborOnEdge( const _LayerEdge* edge ) const;
507     void   SetSmooLen( double len ) { // set _len at which smoothing is needed
508       _cosin = len; // as for _LayerEdge's on FACE _cosin is not used
509     }
510     double GetSmooLen() { return _cosin; } // for _LayerEdge's on FACE _cosin is not used
511
512     gp_XYZ smoothLaplacian();
513     gp_XYZ smoothAngular();
514     gp_XYZ smoothLengthWeighted();
515     gp_XYZ smoothCentroidal();
516     gp_XYZ smoothNefPolygon();
517
518     enum { FUN_LAPLACIAN, FUN_LENWEIGHTED, FUN_CENTROIDAL, FUN_NEFPOLY, FUN_ANGULAR, FUN_NB };
519     static const int theNbSmooFuns = FUN_NB;
520     static PSmooFun _funs[theNbSmooFuns];
521     static const char* _funNames[theNbSmooFuns+1];
522     int smooFunID( PSmooFun fun=0) const;
523   };
524   _LayerEdge::PSmooFun _LayerEdge::_funs[theNbSmooFuns] = { &_LayerEdge::smoothLaplacian,
525                                                             &_LayerEdge::smoothLengthWeighted,
526                                                             &_LayerEdge::smoothCentroidal,
527                                                             &_LayerEdge::smoothNefPolygon,
528                                                             &_LayerEdge::smoothAngular };
529   const char* _LayerEdge::_funNames[theNbSmooFuns+1] = { "Laplacian",
530                                                          "LengthWeighted",
531                                                          "Centroidal",
532                                                          "NefPolygon",
533                                                          "Angular",
534                                                          "None"};
535   struct _LayerEdgeCmp
536   {
537     bool operator () (const _LayerEdge* e1, const _LayerEdge* e2) const
538     {
539       const bool cmpNodes = ( e1 && e2 && e1->_nodes.size() && e2->_nodes.size() );
540       return cmpNodes ? ( e1->_nodes[0]->GetID() < e2->_nodes[0]->GetID()) : ( e1 < e2 );
541     }
542   };
543   //--------------------------------------------------------------------------------
544   /*!
545    * A 2D half plane used by _LayerEdge::smoothNefPolygon()
546    */
547   struct _halfPlane
548   {
549     gp_XY _pos, _dir, _inNorm;
550     bool IsOut( const gp_XY p, const double tol ) const
551     {
552       return _inNorm * ( p - _pos ) < -tol;
553     }
554     bool FindIntersection( const _halfPlane& hp, gp_XY & intPnt )
555     {
556       //const double eps = 1e-10;
557       double D = _dir.Crossed( hp._dir );
558       if ( fabs(D) < std::numeric_limits<double>::min())
559         return false;
560       gp_XY vec21 = _pos - hp._pos; 
561       double u = hp._dir.Crossed( vec21 ) / D; 
562       intPnt = _pos + _dir * u;
563       return true;
564     }
565   };
566   //--------------------------------------------------------------------------------
567   /*!
568    * Structure used to smooth a _LayerEdge based on an EDGE.
569    */
570   struct _2NearEdges
571   {
572     double               _wgt  [2]; // weights of _nodes
573     _LayerEdge*          _edges[2];
574
575      // normal to plane passing through _LayerEdge._normal and tangent of EDGE
576     gp_XYZ*              _plnNorm;
577
578     _2NearEdges() { _edges[0]=_edges[1]=0; _plnNorm = 0; }
579     const SMDS_MeshNode* tgtNode(bool is2nd) {
580       return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0;
581     }
582     const SMDS_MeshNode* srcNode(bool is2nd) {
583       return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0;
584     }
585     void reverse() {
586       std::swap( _wgt  [0], _wgt  [1] );
587       std::swap( _edges[0], _edges[1] );
588     }
589     void set( _LayerEdge* e1, _LayerEdge* e2, double w1, double w2 ) {
590       _edges[0] = e1; _edges[1] = e2; _wgt[0] = w1; _wgt[1] = w2;
591     }
592     bool include( const _LayerEdge* e ) {
593       return ( _edges[0] == e || _edges[1] == e );
594     }
595   };
596
597
598   //--------------------------------------------------------------------------------
599   /*!
600    * \brief Layers parameters got by averaging several hypotheses
601    */
602   struct AverageHyp
603   {
604     AverageHyp( const StdMeshers_ViscousLayers* hyp = 0 )
605       :_nbLayers(0), _nbHyps(0), _method(0), _thickness(0), _stretchFactor(0)
606     {
607       Add( hyp );
608     }
609     void Add( const StdMeshers_ViscousLayers* hyp )
610     {
611       if ( hyp )
612       {
613         _nbHyps++;
614         _nbLayers       = hyp->GetNumberLayers();
615         //_thickness     += hyp->GetTotalThickness();
616         _thickness      = Max( _thickness, hyp->GetTotalThickness() );
617         _stretchFactor += hyp->GetStretchFactor();
618         _method         = hyp->GetMethod();
619       }
620     }
621     double GetTotalThickness() const { return _thickness; /*_nbHyps ? _thickness / _nbHyps : 0;*/ }
622     double GetStretchFactor()  const { return _nbHyps ? _stretchFactor / _nbHyps : 0; }
623     int    GetNumberLayers()   const { return _nbLayers; }
624     int    GetMethod()         const { return _method; }
625
626     bool   UseSurfaceNormal()  const
627     { return _method == StdMeshers_ViscousLayers::SURF_OFFSET_SMOOTH; }
628     bool   ToSmooth()          const
629     { return _method == StdMeshers_ViscousLayers::SURF_OFFSET_SMOOTH; }
630     bool   IsOffsetMethod()    const
631     { return _method == StdMeshers_ViscousLayers::FACE_OFFSET; }
632
633   private:
634     int     _nbLayers, _nbHyps, _method;
635     double  _thickness, _stretchFactor;
636   };
637
638   //--------------------------------------------------------------------------------
639   /*!
640    * \brief _LayerEdge's on a shape and other shape data
641    */
642   struct _EdgesOnShape
643   {
644     vector< _LayerEdge* > _edges;
645
646     TopoDS_Shape          _shape;
647     TGeomID               _shapeID;
648     SMESH_subMesh *       _subMesh;
649     // face or edge w/o layer along or near which _edges are inflated
650     TopoDS_Shape          _sWOL;
651     bool                  _isRegularSWOL; // w/o singularities
652     // averaged StdMeshers_ViscousLayers parameters
653     AverageHyp            _hyp;
654     bool                  _toSmooth;
655     _Smoother1D*          _edgeSmoother;
656     vector< _EdgesOnShape* > _eosConcaVer; // edges at concave VERTEXes of a FACE
657     vector< _EdgesOnShape* > _eosC1; // to smooth together several C1 continues shapes
658
659     vector< gp_XYZ >         _faceNormals; // if _shape is FACE
660     vector< _EdgesOnShape* > _faceEOS; // to get _faceNormals of adjacent FACEs
661
662     Handle(ShapeAnalysis_Surface) _offsetSurf;
663     _LayerEdge*                   _edgeForOffset;
664
665     _SolidData*            _data; // parent SOLID
666
667     TopAbs_ShapeEnum ShapeType() const
668     { return _shape.IsNull() ? TopAbs_SHAPE : _shape.ShapeType(); }
669     TopAbs_ShapeEnum SWOLType() const
670     { return _sWOL.IsNull() ? TopAbs_SHAPE : _sWOL.ShapeType(); }
671     bool             HasC1( const _EdgesOnShape* other ) const
672     { return std::find( _eosC1.begin(), _eosC1.end(), other ) != _eosC1.end(); }
673     bool             GetNormal( const SMDS_MeshElement* face, gp_Vec& norm );
674     _SolidData&      GetData() const { return *_data; }
675
676     _EdgesOnShape(): _shapeID(-1), _subMesh(0), _toSmooth(false), _edgeSmoother(0) {}
677   };
678
679   //--------------------------------------------------------------------------------
680   /*!
681    * \brief Convex FACE whose radius of curvature is less than the thickness of 
682    *        layers. It is used to detect distortion of prisms based on a convex
683    *        FACE and to update normals to enable further increasing the thickness
684    */
685   struct _ConvexFace
686   {
687     TopoDS_Face                     _face;
688
689     // edges whose _simplices are used to detect prism distortion
690     vector< _LayerEdge* >           _simplexTestEdges;
691
692     // map a sub-shape to _SolidData::_edgesOnShape
693     map< TGeomID, _EdgesOnShape* >  _subIdToEOS;
694
695     bool                            _normalsFixed;
696
697     bool GetCenterOfCurvature( _LayerEdge*         ledge,
698                                BRepLProp_SLProps&  surfProp,
699                                SMESH_MesherHelper& helper,
700                                gp_Pnt &            center ) const;
701     bool CheckPrisms() const;
702   };
703
704   //--------------------------------------------------------------------------------
705   /*!
706    * \brief Structure holding _LayerEdge's based on EDGEs that will collide
707    *        at inflation up to the full thickness. A detected collision
708    *        is fixed in updateNormals()
709    */
710   struct _CollisionEdges
711   {
712     _LayerEdge*           _edge;
713     vector< _LayerEdge* > _intEdges; // each pair forms an intersected quadrangle
714     const SMDS_MeshNode* nSrc(int i) const { return _intEdges[i]->_nodes[0]; }
715     const SMDS_MeshNode* nTgt(int i) const { return _intEdges[i]->_nodes.back(); }
716   };
717
718   //--------------------------------------------------------------------------------
719   /*!
720    * \brief Data of a SOLID
721    */
722   struct _SolidData
723   {
724     typedef const StdMeshers_ViscousLayers* THyp;
725     TopoDS_Shape                    _solid;
726     TopTools_MapOfShape             _before; // SOLIDs to be computed before _solid
727     TGeomID                         _index; // SOLID id
728     _MeshOfSolid*                   _proxyMesh;
729     list< THyp >                    _hyps;
730     list< TopoDS_Shape >            _hypShapes;
731     map< TGeomID, THyp >            _face2hyp; // filled if _hyps.size() > 1
732     set< TGeomID >                  _reversedFaceIds;
733     set< TGeomID >                  _ignoreFaceIds; // WOL FACEs and FACEs of other SOLIDs
734
735     double                          _stepSize, _stepSizeCoeff, _geomSize;
736     const SMDS_MeshNode*            _stepSizeNodes[2];
737
738     TNode2Edge                      _n2eMap; // nodes and _LayerEdge's based on them
739
740     // map to find _n2eMap of another _SolidData by a shrink shape shared by two _SolidData's
741     map< TGeomID, TNode2Edge* >     _s2neMap;
742     // _LayerEdge's with underlying shapes
743     vector< _EdgesOnShape >         _edgesOnShape;
744
745     // key:   an id of shape (EDGE or VERTEX) shared by a FACE with
746     //        layers and a FACE w/o layers
747     // value: the shape (FACE or EDGE) to shrink mesh on.
748     //       _LayerEdge's basing on nodes on key shape are inflated along the value shape
749     map< TGeomID, TopoDS_Shape >     _shrinkShape2Shape;
750
751     // Convex FACEs whose radius of curvature is less than the thickness of layers
752     map< TGeomID, _ConvexFace >      _convexFaces;
753
754     // shapes (EDGEs and VERTEXes) srink from which is forbidden due to collisions with
755     // the adjacent SOLID
756     set< TGeomID >                   _noShrinkShapes;
757
758     int                              _nbShapesToSmooth;
759
760     //map< TGeomID,Handle(Geom_Curve)> _edge2curve;
761
762     vector< _CollisionEdges >        _collisionEdges;
763     set< TGeomID >                   _concaveFaces;
764
765     double                           _maxThickness; // of all _hyps
766     double                           _minThickness; // of all _hyps
767
768     double                           _epsilon; // precision for SegTriaInter()
769
770     SMESH_MesherHelper*              _helper;
771
772     _SolidData(const TopoDS_Shape& s=TopoDS_Shape(),
773                _MeshOfSolid*       m=0)
774       :_solid(s), _proxyMesh(m), _helper(0) {}
775     ~_SolidData();
776
777     void SortOnEdge( const TopoDS_Edge& E, vector< _LayerEdge* >& edges);
778     void Sort2NeiborsOnEdge( vector< _LayerEdge* >& edges );
779
780     _ConvexFace* GetConvexFace( const TGeomID faceID ) {
781       map< TGeomID, _ConvexFace >::iterator id2face = _convexFaces.find( faceID );
782       return id2face == _convexFaces.end() ? 0 : & id2face->second;
783     }
784     _EdgesOnShape* GetShapeEdges(const TGeomID       shapeID );
785     _EdgesOnShape* GetShapeEdges(const TopoDS_Shape& shape );
786     _EdgesOnShape* GetShapeEdges(const _LayerEdge*   edge )
787     { return GetShapeEdges( edge->_nodes[0]->getshapeId() ); }
788
789     SMESH_MesherHelper& GetHelper() const { return *_helper; }
790
791     void UnmarkEdges( int flag = _LayerEdge::MARKED ) {
792       for ( size_t i = 0; i < _edgesOnShape.size(); ++i )
793         for ( size_t j = 0; j < _edgesOnShape[i]._edges.size(); ++j )
794           _edgesOnShape[i]._edges[j]->Unset( flag );
795     }
796     void AddShapesToSmooth( const set< _EdgesOnShape* >& shape,
797                             const set< _EdgesOnShape* >* edgesNoAnaSmooth=0 );
798
799     void PrepareEdgesToSmoothOnFace( _EdgesOnShape* eof, bool substituteSrcNodes );
800   };
801   //--------------------------------------------------------------------------------
802   /*!
803    * \brief Offset plane used in getNormalByOffset()
804    */
805   struct _OffsetPlane
806   {
807     gp_Pln _plane;
808     int    _faceIndex;
809     int    _faceIndexNext[2];
810     gp_Lin _lines[2]; // line of intersection with neighbor _OffsetPlane's
811     bool   _isLineOK[2];
812     _OffsetPlane() {
813       _isLineOK[0] = _isLineOK[1] = false; _faceIndexNext[0] = _faceIndexNext[1] = -1;
814     }
815     void   ComputeIntersectionLine( _OffsetPlane&        pln, 
816                                     const TopoDS_Edge&   E,
817                                     const TopoDS_Vertex& V );
818     gp_XYZ GetCommonPoint(bool& isFound, const TopoDS_Vertex& V) const;
819     int    NbLines() const { return _isLineOK[0] + _isLineOK[1]; }
820   };
821   //--------------------------------------------------------------------------------
822   /*!
823    * \brief Container of centers of curvature at nodes on an EDGE bounding _ConvexFace
824    */
825   struct _CentralCurveOnEdge
826   {
827     bool                  _isDegenerated;
828     vector< gp_Pnt >      _curvaCenters;
829     vector< _LayerEdge* > _ledges;
830     vector< gp_XYZ >      _normals; // new normal for each of _ledges
831     vector< double >      _segLength2;
832
833     TopoDS_Edge           _edge;
834     TopoDS_Face           _adjFace;
835     bool                  _adjFaceToSmooth;
836
837     void Append( const gp_Pnt& center, _LayerEdge* ledge )
838     {
839       if ( _curvaCenters.size() > 0 )
840         _segLength2.push_back( center.SquareDistance( _curvaCenters.back() ));
841       _curvaCenters.push_back( center );
842       _ledges.push_back( ledge );
843       _normals.push_back( ledge->_normal );
844     }
845     bool FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal );
846     void SetShapes( const TopoDS_Edge&  edge,
847                     const _ConvexFace&  convFace,
848                     _SolidData&         data,
849                     SMESH_MesherHelper& helper);
850   };
851   //--------------------------------------------------------------------------------
852   /*!
853    * \brief Data of node on a shrinked FACE
854    */
855   struct _SmoothNode
856   {
857     const SMDS_MeshNode*         _node;
858     vector<_Simplex>             _simplices; // for quality check
859
860     enum SmoothType { LAPLACIAN, CENTROIDAL, ANGULAR, TFI };
861
862     bool Smooth(int&                  badNb,
863                 Handle(Geom_Surface)& surface,
864                 SMESH_MesherHelper&   helper,
865                 const double          refSign,
866                 SmoothType            how,
867                 bool                  set3D);
868
869     gp_XY computeAngularPos(vector<gp_XY>& uv,
870                             const gp_XY&   uvToFix,
871                             const double   refSign );
872   };
873   //--------------------------------------------------------------------------------
874   /*!
875    * \brief Builder of viscous layers
876    */
877   class _ViscousBuilder
878   {
879   public:
880     _ViscousBuilder();
881     // does it's job
882     SMESH_ComputeErrorPtr Compute(SMESH_Mesh&         mesh,
883                                   const TopoDS_Shape& shape);
884     // check validity of hypotheses
885     SMESH_ComputeErrorPtr CheckHypotheses( SMESH_Mesh&         mesh,
886                                            const TopoDS_Shape& shape );
887
888     // restore event listeners used to clear an inferior dim sub-mesh modified by viscous layers
889     void RestoreListeners();
890
891     // computes SMESH_ProxyMesh::SubMesh::_n2n;
892     bool MakeN2NMap( _MeshOfSolid* pm );
893
894   private:
895
896     bool findSolidsWithLayers();
897     bool setBefore( _SolidData& solidBefore, _SolidData& solidAfter );
898     bool findFacesWithLayers(const bool onlyWith=false);
899     void getIgnoreFaces(const TopoDS_Shape&             solid,
900                         const StdMeshers_ViscousLayers* hyp,
901                         const TopoDS_Shape&             hypShape,
902                         set<TGeomID>&                   ignoreFaces);
903     bool makeLayer(_SolidData& data);
904     void setShapeData( _EdgesOnShape& eos, SMESH_subMesh* sm, _SolidData& data );
905     bool setEdgeData( _LayerEdge& edge, _EdgesOnShape& eos,
906                       SMESH_MesherHelper& helper, _SolidData& data);
907     gp_XYZ getFaceNormal(const SMDS_MeshNode* n,
908                          const TopoDS_Face&   face,
909                          SMESH_MesherHelper&  helper,
910                          bool&                isOK,
911                          bool                 shiftInside=false);
912     bool getFaceNormalAtSingularity(const gp_XY&        uv,
913                                     const TopoDS_Face&  face,
914                                     SMESH_MesherHelper& helper,
915                                     gp_Dir&             normal );
916     gp_XYZ getWeigthedNormal( const _LayerEdge*                edge );
917     gp_XYZ getNormalByOffset( _LayerEdge*                      edge,
918                               std::pair< TopoDS_Face, gp_XYZ > fId2Normal[],
919                               int                              nbFaces,
920                               bool                             lastNoOffset = false);
921     bool findNeiborsOnEdge(const _LayerEdge*     edge,
922                            const SMDS_MeshNode*& n1,
923                            const SMDS_MeshNode*& n2,
924                            _EdgesOnShape&        eos,
925                            _SolidData&           data);
926     void findSimplexTestEdges( _SolidData&                    data,
927                                vector< vector<_LayerEdge*> >& edgesByGeom);
928     void computeGeomSize( _SolidData& data );
929     bool findShapesToSmooth( _SolidData& data);
930     void limitStepSizeByCurvature( _SolidData&  data );
931     void limitStepSize( _SolidData&             data,
932                         const SMDS_MeshElement* face,
933                         const _LayerEdge*       maxCosinEdge );
934     void limitStepSize( _SolidData& data, const double minSize);
935     bool inflate(_SolidData& data);
936     bool smoothAndCheck(_SolidData& data, const int nbSteps, double & distToIntersection);
937     int  invalidateBadSmooth( _SolidData&               data,
938                               SMESH_MesherHelper&       helper,
939                               vector< _LayerEdge* >&    badSmooEdges,
940                               vector< _EdgesOnShape* >& eosC1,
941                               const int                 infStep );
942     void makeOffsetSurface( _EdgesOnShape& eos, SMESH_MesherHelper& );
943     void putOnOffsetSurface( _EdgesOnShape& eos, int infStep,
944                              vector< _EdgesOnShape* >& eosC1,
945                              int smooStep=0, bool moveAll=false );
946     void findCollisionEdges( _SolidData& data, SMESH_MesherHelper& helper );
947     void limitMaxLenByCurvature( _SolidData& data, SMESH_MesherHelper& helper );
948     void limitMaxLenByCurvature( _LayerEdge* e1, _LayerEdge* e2,
949                                  _EdgesOnShape& eos1, _EdgesOnShape& eos2,
950                                  SMESH_MesherHelper& helper );
951     bool updateNormals( _SolidData& data, SMESH_MesherHelper& helper, int stepNb, double stepSize );
952     bool updateNormalsOfConvexFaces( _SolidData&         data,
953                                      SMESH_MesherHelper& helper,
954                                      int                 stepNb );
955     void updateNormalsOfC1Vertices( _SolidData& data );
956     bool updateNormalsOfSmoothed( _SolidData&         data,
957                                   SMESH_MesherHelper& helper,
958                                   const int           nbSteps,
959                                   const double        stepSize );
960     bool isNewNormalOk( _SolidData&   data,
961                         _LayerEdge&   edge,
962                         const gp_XYZ& newNormal);
963     bool refine(_SolidData& data);
964     bool shrink(_SolidData& data);
965     bool prepareEdgeToShrink( _LayerEdge& edge, _EdgesOnShape& eos,
966                               SMESH_MesherHelper& helper,
967                               const SMESHDS_SubMesh* faceSubMesh );
968     void restoreNoShrink( _LayerEdge& edge ) const;
969     void fixBadFaces(const TopoDS_Face&          F,
970                      SMESH_MesherHelper&         helper,
971                      const bool                  is2D,
972                      const int                   step,
973                      set<const SMDS_MeshNode*> * involvedNodes=NULL);
974     bool addBoundaryElements(_SolidData& data);
975
976     bool error( const string& text, int solidID=-1 );
977     SMESHDS_Mesh* getMeshDS() const { return _mesh->GetMeshDS(); }
978
979     // debug
980     void makeGroupOfLE();
981
982     SMESH_Mesh*                _mesh;
983     SMESH_ComputeErrorPtr      _error;
984
985     vector<                    _SolidData >  _sdVec;
986     TopTools_IndexedMapOfShape _solids; // to find _SolidData by a solid
987     TopTools_MapOfShape        _shrinkedFaces;
988
989     int                        _tmpFaceID;
990   };
991   //--------------------------------------------------------------------------------
992   /*!
993    * \brief Shrinker of nodes on the EDGE
994    */
995   class _Shrinker1D
996   {
997     TopoDS_Edge                   _geomEdge;
998     vector<double>                _initU;
999     vector<double>                _normPar;
1000     vector<const SMDS_MeshNode*>  _nodes;
1001     const _LayerEdge*             _edges[2];
1002     bool                          _done;
1003   public:
1004     void AddEdge( const _LayerEdge* e, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
1005     void Compute(bool set3D, SMESH_MesherHelper& helper);
1006     void RestoreParams();
1007     void SwapSrcTgtNodes(SMESHDS_Mesh* mesh);
1008     const TopoDS_Edge& GeomEdge() const { return _geomEdge; }
1009     const SMDS_MeshNode* TgtNode( bool is2nd ) const
1010     { return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0; }
1011     const SMDS_MeshNode* SrcNode( bool is2nd ) const
1012     { return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0; }
1013   };
1014   //--------------------------------------------------------------------------------
1015   /*!
1016    * \brief Smoother of _LayerEdge's on EDGE.
1017    */
1018   struct _Smoother1D
1019   {
1020     struct OffPnt // point of the offsetted EDGE
1021     {
1022       gp_XYZ      _xyz;    // coord of a point inflated from EDGE w/o smooth
1023       double      _len;    // length reached at previous inflation step
1024       double      _param;  // on EDGE
1025       _2NearEdges _2edges; // 2 neighbor _LayerEdge's
1026       gp_XYZ      _edgeDir;// EDGE tangent at _param
1027       double Distance( const OffPnt& p ) const { return ( _xyz - p._xyz ).Modulus(); }
1028     };
1029     vector< OffPnt >   _offPoints;
1030     vector< double >   _leParams; // normalized param of _eos._edges on EDGE
1031     Handle(Geom_Curve) _anaCurve; // for analytic smooth
1032     _LayerEdge         _leOnV[2]; // _LayerEdge's holding normal to the EDGE at VERTEXes
1033     gp_XYZ             _edgeDir[2]; // tangent at VERTEXes
1034     size_t             _iSeg[2];  // index of segment where extreme tgt node is projected
1035     _EdgesOnShape&     _eos;
1036     double             _curveLen; // length of the EDGE
1037
1038     static Handle(Geom_Curve) CurveForSmooth( const TopoDS_Edge&  E,
1039                                               _EdgesOnShape&      eos,
1040                                               SMESH_MesherHelper& helper);
1041
1042     _Smoother1D( Handle(Geom_Curve) curveForSmooth,
1043                  _EdgesOnShape&     eos )
1044       : _anaCurve( curveForSmooth ), _eos( eos )
1045     {
1046     }
1047     bool Perform(_SolidData&                    data,
1048                  Handle(ShapeAnalysis_Surface)& surface,
1049                  const TopoDS_Face&             F,
1050                  SMESH_MesherHelper&            helper )
1051     {
1052       if ( _leParams.empty() || ( !isAnalytic() && _offPoints.empty() ))
1053         prepare( data );
1054
1055       if ( isAnalytic() )
1056         return smoothAnalyticEdge( data, surface, F, helper );
1057       else
1058         return smoothComplexEdge ( data, surface, F, helper );
1059     }
1060     void prepare(_SolidData& data );
1061
1062     bool smoothAnalyticEdge( _SolidData&                    data,
1063                              Handle(ShapeAnalysis_Surface)& surface,
1064                              const TopoDS_Face&             F,
1065                              SMESH_MesherHelper&            helper);
1066
1067     bool smoothComplexEdge( _SolidData&                    data,
1068                             Handle(ShapeAnalysis_Surface)& surface,
1069                             const TopoDS_Face&             F,
1070                             SMESH_MesherHelper&            helper);
1071
1072     gp_XYZ getNormalNormal( const gp_XYZ & normal,
1073                             const gp_XYZ&  edgeDir);
1074
1075     _LayerEdge* getLEdgeOnV( bool is2nd )
1076     {
1077       return _eos._edges[ is2nd ? _eos._edges.size()-1 : 0 ]->_2neibors->_edges[ is2nd ];
1078     }
1079     bool isAnalytic() const { return !_anaCurve.IsNull(); }
1080   };
1081   //--------------------------------------------------------------------------------
1082   /*!
1083    * \brief Class of temporary mesh face.
1084    * We can't use SMDS_FaceOfNodes since it's impossible to set it's ID which is
1085    * needed because SMESH_ElementSearcher internaly uses set of elements sorted by ID
1086    */
1087   struct _TmpMeshFace : public SMDS_MeshElement
1088   {
1089     vector<const SMDS_MeshNode* > _nn;
1090     _TmpMeshFace( const vector<const SMDS_MeshNode*>& nodes,
1091                   int id, int faceID=-1, int idInFace=-1):
1092       SMDS_MeshElement(id), _nn(nodes) { setShapeId(faceID); setIdInShape(idInFace); }
1093     virtual const SMDS_MeshNode* GetNode(const int ind) const { return _nn[ind]; }
1094     virtual SMDSAbs_ElementType  GetType() const              { return SMDSAbs_Face; }
1095     virtual vtkIdType GetVtkType() const                      { return -1; }
1096     virtual SMDSAbs_EntityType   GetEntityType() const        { return SMDSEntity_Last; }
1097     virtual SMDSAbs_GeometryType GetGeomType() const
1098     { return _nn.size() == 3 ? SMDSGeom_TRIANGLE : SMDSGeom_QUADRANGLE; }
1099     virtual SMDS_ElemIteratorPtr elementsIterator(SMDSAbs_ElementType) const
1100     { return SMDS_ElemIteratorPtr( new SMDS_NodeVectorElemIterator( _nn.begin(), _nn.end()));}
1101   };
1102   //--------------------------------------------------------------------------------
1103   /*!
1104    * \brief Class of temporary mesh face storing _LayerEdge it's based on
1105    */
1106   struct _TmpMeshFaceOnEdge : public _TmpMeshFace
1107   {
1108     _LayerEdge *_le1, *_le2;
1109     _TmpMeshFaceOnEdge( _LayerEdge* le1, _LayerEdge* le2, int ID ):
1110       _TmpMeshFace( vector<const SMDS_MeshNode*>(4), ID ), _le1(le1), _le2(le2)
1111     {
1112       _nn[0]=_le1->_nodes[0];
1113       _nn[1]=_le1->_nodes.back();
1114       _nn[2]=_le2->_nodes.back();
1115       _nn[3]=_le2->_nodes[0];
1116     }
1117     gp_XYZ GetDir() const // return average direction of _LayerEdge's, normal to EDGE
1118     {
1119       SMESH_TNodeXYZ p0s( _nn[0] );
1120       SMESH_TNodeXYZ p0t( _nn[1] );
1121       SMESH_TNodeXYZ p1t( _nn[2] );
1122       SMESH_TNodeXYZ p1s( _nn[3] );
1123       gp_XYZ  v0 = p0t - p0s;
1124       gp_XYZ  v1 = p1t - p1s;
1125       gp_XYZ v01 = p1s - p0s;
1126       gp_XYZ   n = ( v0 ^ v01 ) + ( v1 ^ v01 );
1127       gp_XYZ   d = v01 ^ n;
1128       d.Normalize();
1129       return d;
1130     }
1131     gp_XYZ GetDir(_LayerEdge* le1, _LayerEdge* le2) // return average direction of _LayerEdge's
1132     {
1133       _nn[0]=le1->_nodes[0];
1134       _nn[1]=le1->_nodes.back();
1135       _nn[2]=le2->_nodes.back();
1136       _nn[3]=le2->_nodes[0];
1137       return GetDir();
1138     }
1139   };
1140   //--------------------------------------------------------------------------------
1141   /*!
1142    * \brief Retriever of node coordinates either directly or from a surface by node UV.
1143    * \warning Location of a surface is ignored
1144    */
1145   struct _NodeCoordHelper
1146   {
1147     SMESH_MesherHelper&        _helper;
1148     const TopoDS_Face&         _face;
1149     Handle(Geom_Surface)       _surface;
1150     gp_XYZ (_NodeCoordHelper::* _fun)(const SMDS_MeshNode* n) const;
1151
1152     _NodeCoordHelper(const TopoDS_Face& F, SMESH_MesherHelper& helper, bool is2D)
1153       : _helper( helper ), _face( F )
1154     {
1155       if ( is2D )
1156       {
1157         TopLoc_Location loc;
1158         _surface = BRep_Tool::Surface( _face, loc );
1159       }
1160       if ( _surface.IsNull() )
1161         _fun = & _NodeCoordHelper::direct;
1162       else
1163         _fun = & _NodeCoordHelper::byUV;
1164     }
1165     gp_XYZ operator()(const SMDS_MeshNode* n) const { return (this->*_fun)( n ); }
1166
1167   private:
1168     gp_XYZ direct(const SMDS_MeshNode* n) const
1169     {
1170       return SMESH_TNodeXYZ( n );
1171     }
1172     gp_XYZ byUV  (const SMDS_MeshNode* n) const
1173     {
1174       gp_XY uv = _helper.GetNodeUV( _face, n );
1175       return _surface->Value( uv.X(), uv.Y() ).XYZ();
1176     }
1177   };
1178
1179   //================================================================================
1180   /*!
1181    * \brief Check angle between vectors 
1182    */
1183   //================================================================================
1184
1185   inline bool isLessAngle( const gp_Vec& v1, const gp_Vec& v2, const double cos )
1186   {
1187     double dot = v1 * v2; // cos * |v1| * |v2|
1188     double l1  = v1.SquareMagnitude();
1189     double l2  = v2.SquareMagnitude();
1190     return (( dot * cos >= 0 ) && 
1191             ( dot * dot ) / l1 / l2 >= ( cos * cos ));
1192   }
1193
1194 } // namespace VISCOUS_3D
1195
1196
1197
1198 //================================================================================
1199 // StdMeshers_ViscousLayers hypothesis
1200 //
1201 StdMeshers_ViscousLayers::StdMeshers_ViscousLayers(int hypId, int studyId, SMESH_Gen* gen)
1202   :SMESH_Hypothesis(hypId, studyId, gen),
1203    _isToIgnoreShapes(1), _nbLayers(1), _thickness(1), _stretchFactor(1),
1204    _method( SURF_OFFSET_SMOOTH )
1205 {
1206   _name = StdMeshers_ViscousLayers::GetHypType();
1207   _param_algo_dim = -3; // auxiliary hyp used by 3D algos
1208 } // --------------------------------------------------------------------------------
1209 void StdMeshers_ViscousLayers::SetBndShapes(const std::vector<int>& faceIds, bool toIgnore)
1210 {
1211   if ( faceIds != _shapeIds )
1212     _shapeIds = faceIds, NotifySubMeshesHypothesisModification();
1213   if ( _isToIgnoreShapes != toIgnore )
1214     _isToIgnoreShapes = toIgnore, NotifySubMeshesHypothesisModification();
1215 } // --------------------------------------------------------------------------------
1216 void StdMeshers_ViscousLayers::SetTotalThickness(double thickness)
1217 {
1218   if ( thickness != _thickness )
1219     _thickness = thickness, NotifySubMeshesHypothesisModification();
1220 } // --------------------------------------------------------------------------------
1221 void StdMeshers_ViscousLayers::SetNumberLayers(int nb)
1222 {
1223   if ( _nbLayers != nb )
1224     _nbLayers = nb, NotifySubMeshesHypothesisModification();
1225 } // --------------------------------------------------------------------------------
1226 void StdMeshers_ViscousLayers::SetStretchFactor(double factor)
1227 {
1228   if ( _stretchFactor != factor )
1229     _stretchFactor = factor, NotifySubMeshesHypothesisModification();
1230 } // --------------------------------------------------------------------------------
1231 void StdMeshers_ViscousLayers::SetMethod( ExtrusionMethod method )
1232 {
1233   if ( _method != method )
1234     _method = method, NotifySubMeshesHypothesisModification();
1235 } // --------------------------------------------------------------------------------
1236 SMESH_ProxyMesh::Ptr
1237 StdMeshers_ViscousLayers::Compute(SMESH_Mesh&         theMesh,
1238                                   const TopoDS_Shape& theShape,
1239                                   const bool          toMakeN2NMap) const
1240 {
1241   using namespace VISCOUS_3D;
1242   _ViscousBuilder builder;
1243   SMESH_ComputeErrorPtr err = builder.Compute( theMesh, theShape );
1244   if ( err && !err->IsOK() )
1245     return SMESH_ProxyMesh::Ptr();
1246
1247   vector<SMESH_ProxyMesh::Ptr> components;
1248   TopExp_Explorer exp( theShape, TopAbs_SOLID );
1249   for ( ; exp.More(); exp.Next() )
1250   {
1251     if ( _MeshOfSolid* pm =
1252          _ViscousListener::GetSolidMesh( &theMesh, exp.Current(), /*toCreate=*/false))
1253     {
1254       if ( toMakeN2NMap && !pm->_n2nMapComputed )
1255         if ( !builder.MakeN2NMap( pm ))
1256           return SMESH_ProxyMesh::Ptr();
1257       components.push_back( SMESH_ProxyMesh::Ptr( pm ));
1258       pm->myIsDeletable = false; // it will de deleted by boost::shared_ptr
1259
1260       if ( pm->_warning && !pm->_warning->IsOK() )
1261       {
1262         SMESH_subMesh* sm = theMesh.GetSubMesh( exp.Current() );
1263         SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1264         if ( !smError || smError->IsOK() )
1265           smError = pm->_warning;
1266       }
1267     }
1268     _ViscousListener::RemoveSolidMesh ( &theMesh, exp.Current() );
1269   }
1270   switch ( components.size() )
1271   {
1272   case 0: break;
1273
1274   case 1: return components[0];
1275
1276   default: return SMESH_ProxyMesh::Ptr( new SMESH_ProxyMesh( components ));
1277   }
1278   return SMESH_ProxyMesh::Ptr();
1279 } // --------------------------------------------------------------------------------
1280 std::ostream & StdMeshers_ViscousLayers::SaveTo(std::ostream & save)
1281 {
1282   save << " " << _nbLayers
1283        << " " << _thickness
1284        << " " << _stretchFactor
1285        << " " << _shapeIds.size();
1286   for ( size_t i = 0; i < _shapeIds.size(); ++i )
1287     save << " " << _shapeIds[i];
1288   save << " " << !_isToIgnoreShapes; // negate to keep the behavior in old studies.
1289   save << " " << _method;
1290   return save;
1291 } // --------------------------------------------------------------------------------
1292 std::istream & StdMeshers_ViscousLayers::LoadFrom(std::istream & load)
1293 {
1294   int nbFaces, faceID, shapeToTreat, method;
1295   load >> _nbLayers >> _thickness >> _stretchFactor >> nbFaces;
1296   while ( (int) _shapeIds.size() < nbFaces && load >> faceID )
1297     _shapeIds.push_back( faceID );
1298   if ( load >> shapeToTreat ) {
1299     _isToIgnoreShapes = !shapeToTreat;
1300     if ( load >> method )
1301       _method = (ExtrusionMethod) method;
1302   }
1303   else {
1304     _isToIgnoreShapes = true; // old behavior
1305   }
1306   return load;
1307 } // --------------------------------------------------------------------------------
1308 bool StdMeshers_ViscousLayers::SetParametersByMesh(const SMESH_Mesh*   theMesh,
1309                                                    const TopoDS_Shape& theShape)
1310 {
1311   // TODO
1312   return false;
1313 } // --------------------------------------------------------------------------------
1314 SMESH_ComputeErrorPtr
1315 StdMeshers_ViscousLayers::CheckHypothesis(SMESH_Mesh&                          theMesh,
1316                                           const TopoDS_Shape&                  theShape,
1317                                           SMESH_Hypothesis::Hypothesis_Status& theStatus)
1318 {
1319   VISCOUS_3D::_ViscousBuilder builder;
1320   SMESH_ComputeErrorPtr err = builder.CheckHypotheses( theMesh, theShape );
1321   if ( err && !err->IsOK() )
1322     theStatus = SMESH_Hypothesis::HYP_INCOMPAT_HYPS;
1323   else
1324     theStatus = SMESH_Hypothesis::HYP_OK;
1325
1326   return err;
1327 }
1328 // --------------------------------------------------------------------------------
1329 bool StdMeshers_ViscousLayers::IsShapeWithLayers(int shapeIndex) const
1330 {
1331   bool isIn =
1332     ( std::find( _shapeIds.begin(), _shapeIds.end(), shapeIndex ) != _shapeIds.end() );
1333   return IsToIgnoreShapes() ? !isIn : isIn;
1334 }
1335 // END StdMeshers_ViscousLayers hypothesis
1336 //================================================================================
1337
1338 namespace VISCOUS_3D
1339 {
1340   gp_XYZ getEdgeDir( const TopoDS_Edge& E, const TopoDS_Vertex& fromV )
1341   {
1342     gp_Vec dir;
1343     double f,l;
1344     Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1345     if ( c.IsNull() ) return gp_XYZ( Precision::Infinite(), 1e100, 1e100 );
1346     gp_Pnt p = BRep_Tool::Pnt( fromV );
1347     double distF = p.SquareDistance( c->Value( f ));
1348     double distL = p.SquareDistance( c->Value( l ));
1349     c->D1(( distF < distL ? f : l), p, dir );
1350     if ( distL < distF ) dir.Reverse();
1351     return dir.XYZ();
1352   }
1353   //--------------------------------------------------------------------------------
1354   gp_XYZ getEdgeDir( const TopoDS_Edge& E, const SMDS_MeshNode* atNode,
1355                      SMESH_MesherHelper& helper)
1356   {
1357     gp_Vec dir;
1358     double f,l; gp_Pnt p;
1359     Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1360     if ( c.IsNull() ) return gp_XYZ( Precision::Infinite(), 1e100, 1e100 );
1361     double u = helper.GetNodeU( E, atNode );
1362     c->D1( u, p, dir );
1363     return dir.XYZ();
1364   }
1365   //--------------------------------------------------------------------------------
1366   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1367                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok,
1368                      double* cosin=0);
1369   //--------------------------------------------------------------------------------
1370   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Edge& fromE,
1371                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok)
1372   {
1373     double f,l;
1374     Handle(Geom_Curve) c = BRep_Tool::Curve( fromE, f, l );
1375     if ( c.IsNull() )
1376     {
1377       TopoDS_Vertex v = helper.IthVertex( 0, fromE );
1378       return getFaceDir( F, v, node, helper, ok );
1379     }
1380     gp_XY uv = helper.GetNodeUV( F, node, 0, &ok );
1381     Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
1382     gp_Pnt p; gp_Vec du, dv, norm;
1383     surface->D1( uv.X(),uv.Y(), p, du,dv );
1384     norm = du ^ dv;
1385
1386     double u = helper.GetNodeU( fromE, node, 0, &ok );
1387     c->D1( u, p, du );
1388     TopAbs_Orientation o = helper.GetSubShapeOri( F.Oriented(TopAbs_FORWARD), fromE);
1389     if ( o == TopAbs_REVERSED )
1390       du.Reverse();
1391
1392     gp_Vec dir = norm ^ du;
1393
1394     if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX &&
1395          helper.IsClosedEdge( fromE ))
1396     {
1397       if ( fabs(u-f) < fabs(u-l)) c->D1( l, p, dv );
1398       else                        c->D1( f, p, dv );
1399       if ( o == TopAbs_REVERSED )
1400         dv.Reverse();
1401       gp_Vec dir2 = norm ^ dv;
1402       dir = dir.Normalized() + dir2.Normalized();
1403     }
1404     return dir.XYZ();
1405   }
1406   //--------------------------------------------------------------------------------
1407   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1408                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper,
1409                      bool& ok, double* cosin)
1410   {
1411     TopoDS_Face faceFrw = F;
1412     faceFrw.Orientation( TopAbs_FORWARD );
1413     //double f,l; TopLoc_Location loc;
1414     TopoDS_Edge edges[2]; // sharing a vertex
1415     size_t nbEdges = 0;
1416     {
1417       TopoDS_Vertex VV[2];
1418       TopExp_Explorer exp( faceFrw, TopAbs_EDGE );
1419       for ( ; exp.More() && nbEdges < 2; exp.Next() )
1420       {
1421         const TopoDS_Edge& e = TopoDS::Edge( exp.Current() );
1422         if ( SMESH_Algo::isDegenerated( e )) continue;
1423         TopExp::Vertices( e, VV[0], VV[1], /*CumOri=*/true );
1424         if ( VV[1].IsSame( fromV )) {
1425           nbEdges += edges[ 0 ].IsNull();
1426           edges[ 0 ] = e;
1427         }
1428         else if ( VV[0].IsSame( fromV )) {
1429           nbEdges += edges[ 1 ].IsNull();
1430           edges[ 1 ] = e;
1431         }
1432       }
1433     }
1434     gp_XYZ dir(0,0,0), edgeDir[2];
1435     if ( nbEdges == 2 )
1436     {
1437       // get dirs of edges going fromV
1438       ok = true;
1439       for ( size_t i = 0; i < nbEdges && ok; ++i )
1440       {
1441         edgeDir[i] = getEdgeDir( edges[i], fromV );
1442         double size2 = edgeDir[i].SquareModulus();
1443         if (( ok = size2 > numeric_limits<double>::min() ))
1444           edgeDir[i] /= sqrt( size2 );
1445       }
1446       if ( !ok ) return dir;
1447
1448       // get angle between the 2 edges
1449       gp_Vec faceNormal;
1450       double angle = helper.GetAngle( edges[0], edges[1], faceFrw, fromV, &faceNormal );
1451       if ( Abs( angle ) < 5 * M_PI/180 )
1452       {
1453         dir = ( faceNormal.XYZ() ^ edgeDir[0].Reversed()) + ( faceNormal.XYZ() ^ edgeDir[1] );
1454       }
1455       else
1456       {
1457         dir = edgeDir[0] + edgeDir[1];
1458         if ( angle < 0 )
1459           dir.Reverse();
1460       }
1461       if ( cosin ) {
1462         double angle = gp_Vec( edgeDir[0] ).Angle( dir );
1463         *cosin = Cos( angle );
1464       }
1465     }
1466     else if ( nbEdges == 1 )
1467     {
1468       dir = getFaceDir( faceFrw, edges[ edges[0].IsNull() ], node, helper, ok );
1469       if ( cosin ) *cosin = 1.;
1470     }
1471     else
1472     {
1473       ok = false;
1474     }
1475
1476     return dir;
1477   }
1478
1479   //================================================================================
1480   /*!
1481    * \brief Finds concave VERTEXes of a FACE
1482    */
1483   //================================================================================
1484
1485   bool getConcaveVertices( const TopoDS_Face&  F,
1486                            SMESH_MesherHelper& helper,
1487                            set< TGeomID >*     vertices = 0)
1488   {
1489     // check angles at VERTEXes
1490     TError error;
1491     TSideVector wires = StdMeshers_FaceSide::GetFaceWires( F, *helper.GetMesh(), 0, error );
1492     for ( size_t iW = 0; iW < wires.size(); ++iW )
1493     {
1494       const int nbEdges = wires[iW]->NbEdges();
1495       if ( nbEdges < 2 && SMESH_Algo::isDegenerated( wires[iW]->Edge(0)))
1496         continue;
1497       for ( int iE1 = 0; iE1 < nbEdges; ++iE1 )
1498       {
1499         if ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE1 ))) continue;
1500         int iE2 = ( iE1 + 1 ) % nbEdges;
1501         while ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE2 )))
1502           iE2 = ( iE2 + 1 ) % nbEdges;
1503         TopoDS_Vertex V = wires[iW]->FirstVertex( iE2 );
1504         double angle = helper.GetAngle( wires[iW]->Edge( iE1 ),
1505                                         wires[iW]->Edge( iE2 ), F, V );
1506         if ( angle < -5. * M_PI / 180. )
1507         {
1508           if ( !vertices )
1509             return true;
1510           vertices->insert( helper.GetMeshDS()->ShapeToIndex( V ));
1511         }
1512       }
1513     }
1514     return vertices ? !vertices->empty() : false;
1515   }
1516
1517   //================================================================================
1518   /*!
1519    * \brief Returns true if a FACE is bound by a concave EDGE
1520    */
1521   //================================================================================
1522
1523   bool isConcave( const TopoDS_Face&  F,
1524                   SMESH_MesherHelper& helper,
1525                   set< TGeomID >*     vertices = 0 )
1526   {
1527     bool isConcv = false;
1528     // if ( helper.Count( F, TopAbs_WIRE, /*useMap=*/false) > 1 )
1529     //   return true;
1530     gp_Vec2d drv1, drv2;
1531     gp_Pnt2d p;
1532     TopExp_Explorer eExp( F.Oriented( TopAbs_FORWARD ), TopAbs_EDGE );
1533     for ( ; eExp.More(); eExp.Next() )
1534     {
1535       const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
1536       if ( SMESH_Algo::isDegenerated( E )) continue;
1537       // check if 2D curve is concave
1538       BRepAdaptor_Curve2d curve( E, F );
1539       const int nbIntervals = curve.NbIntervals( GeomAbs_C2 );
1540       TColStd_Array1OfReal intervals(1, nbIntervals + 1 );
1541       curve.Intervals( intervals, GeomAbs_C2 );
1542       bool isConvex = true;
1543       for ( int i = 1; i <= nbIntervals && isConvex; ++i )
1544       {
1545         double u1 = intervals( i );
1546         double u2 = intervals( i+1 );
1547         curve.D2( 0.5*( u1+u2 ), p, drv1, drv2 );
1548         double cross = drv1 ^ drv2;
1549         if ( E.Orientation() == TopAbs_REVERSED )
1550           cross = -cross;
1551         isConvex = ( cross > -1e-9 ); // 0.1 );
1552       }
1553       if ( !isConvex )
1554       {
1555         //cout << "Concave FACE " << helper.GetMeshDS()->ShapeToIndex( F ) << endl;
1556         isConcv = true;
1557         if ( vertices )
1558           break;
1559         else
1560           return true;
1561       }
1562     }
1563
1564     // check angles at VERTEXes
1565     if ( getConcaveVertices( F, helper, vertices ))
1566       isConcv = true;
1567
1568     return isConcv;
1569   }
1570
1571   //================================================================================
1572   /*!
1573    * \brief Computes mimimal distance of face in-FACE nodes from an EDGE
1574    *  \param [in] face - the mesh face to treat
1575    *  \param [in] nodeOnEdge - a node on the EDGE
1576    *  \param [out] faceSize - the computed distance
1577    *  \return bool - true if faceSize computed
1578    */
1579   //================================================================================
1580
1581   bool getDistFromEdge( const SMDS_MeshElement* face,
1582                         const SMDS_MeshNode*    nodeOnEdge,
1583                         double &                faceSize )
1584   {
1585     faceSize = Precision::Infinite();
1586     bool done = false;
1587
1588     int nbN  = face->NbCornerNodes();
1589     int iOnE = face->GetNodeIndex( nodeOnEdge );
1590     int iNext[2] = { SMESH_MesherHelper::WrapIndex( iOnE+1, nbN ),
1591                      SMESH_MesherHelper::WrapIndex( iOnE-1, nbN ) };
1592     const SMDS_MeshNode* nNext[2] = { face->GetNode( iNext[0] ),
1593                                       face->GetNode( iNext[1] ) };
1594     gp_XYZ segVec, segEnd = SMESH_TNodeXYZ( nodeOnEdge ); // segment on EDGE
1595     double segLen = -1.;
1596     // look for two neighbor not in-FACE nodes of face
1597     for ( int i = 0; i < 2; ++i )
1598     {
1599       if ( nNext[i]->GetPosition()->GetDim() != 2 &&
1600            nNext[i]->GetID() < nodeOnEdge->GetID() )
1601       {
1602         // look for an in-FACE node
1603         for ( int iN = 0; iN < nbN; ++iN )
1604         {
1605           if ( iN == iOnE || iN == iNext[i] )
1606             continue;
1607           SMESH_TNodeXYZ pInFace = face->GetNode( iN );
1608           gp_XYZ v = pInFace - segEnd;
1609           if ( segLen < 0 )
1610           {
1611             segVec = SMESH_TNodeXYZ( nNext[i] ) - segEnd;
1612             segLen = segVec.Modulus();
1613           }
1614           double distToSeg = v.Crossed( segVec ).Modulus() / segLen;
1615           faceSize = Min( faceSize, distToSeg );
1616           done = true;
1617         }
1618         segLen = -1;
1619       }
1620     }
1621     return done;
1622   }
1623   //================================================================================
1624   /*!
1625    * \brief Return direction of axis or revolution of a surface
1626    */
1627   //================================================================================
1628
1629   bool getRovolutionAxis( const Adaptor3d_Surface& surface,
1630                           gp_Dir &                 axis )
1631   {
1632     switch ( surface.GetType() ) {
1633     case GeomAbs_Cone:
1634     {
1635       gp_Cone cone = surface.Cone();
1636       axis = cone.Axis().Direction();
1637       break;
1638     }
1639     case GeomAbs_Sphere:
1640     {
1641       gp_Sphere sphere = surface.Sphere();
1642       axis = sphere.Position().Direction();
1643       break;
1644     }
1645     case GeomAbs_SurfaceOfRevolution:
1646     {
1647       axis = surface.AxeOfRevolution().Direction();
1648       break;
1649     }
1650     //case GeomAbs_SurfaceOfExtrusion:
1651     case GeomAbs_OffsetSurface:
1652     {
1653       Handle(Adaptor3d_HSurface) base = surface.BasisSurface();
1654       return getRovolutionAxis( base->Surface(), axis );
1655     }
1656     default: return false;
1657     }
1658     return true;
1659   }
1660
1661   //--------------------------------------------------------------------------------
1662   // DEBUG. Dump intermediate node positions into a python script
1663   // HOWTO use: run python commands written in a console to see
1664   //  construction steps of viscous layers
1665 #ifdef __myDEBUG
1666   ofstream* py;
1667   int       theNbPyFunc;
1668   struct PyDump {
1669     PyDump(SMESH_Mesh& m) {
1670       int tag = 3 + m.GetId();
1671       const char* fname = "/tmp/viscous.py";
1672       cout << "execfile('"<<fname<<"')"<<endl;
1673       py = new ofstream(fname);
1674       *py << "import SMESH" << endl
1675           << "from salome.smesh import smeshBuilder" << endl
1676           << "smesh  = smeshBuilder.New(salome.myStudy)" << endl
1677           << "meshSO = smesh.GetCurrentStudy().FindObjectID('0:1:2:" << tag <<"')" << endl
1678           << "mesh   = smesh.Mesh( meshSO.GetObject() )"<<endl;
1679       theNbPyFunc = 0;
1680     }
1681     void Finish() {
1682       if (py) {
1683         *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Viscous Prisms',"
1684           "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_ElemGeomType,'=',SMESH.Geom_PENTA))"<<endl;
1685         *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Neg Volumes',"
1686           "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_Volume3D,'<',0))"<<endl;
1687       }
1688       delete py; py=0;
1689     }
1690     ~PyDump() { Finish(); cout << "NB FUNCTIONS: " << theNbPyFunc << endl; }
1691   };
1692 #define dumpFunction(f) { _dumpFunction(f, __LINE__);}
1693 #define dumpMove(n)     { _dumpMove(n, __LINE__);}
1694 #define dumpMoveComm(n,txt) { _dumpMove(n, __LINE__, txt);}
1695 #define dumpCmd(txt)    { _dumpCmd(txt, __LINE__);}
1696   void _dumpFunction(const string& fun, int ln)
1697   { if (py) *py<< "def "<<fun<<"(): # "<< ln <<endl; cout<<fun<<"()"<<endl; ++theNbPyFunc; }
1698   void _dumpMove(const SMDS_MeshNode* n, int ln, const char* txt="")
1699   { if (py) *py<< "  mesh.MoveNode( "<<n->GetID()<< ", "<< n->X()
1700                << ", "<<n->Y()<<", "<< n->Z()<< ")\t\t # "<< ln <<" "<< txt << endl; }
1701   void _dumpCmd(const string& txt, int ln)
1702   { if (py) *py<< "  "<<txt<<" # "<< ln <<endl; }
1703   void dumpFunctionEnd()
1704   { if (py) *py<< "  return"<< endl; }
1705   void dumpChangeNodes( const SMDS_MeshElement* f )
1706   { if (py) { *py<< "  mesh.ChangeElemNodes( " << f->GetID()<<", [";
1707       for ( int i=1; i < f->NbNodes(); ++i ) *py << f->GetNode(i-1)->GetID()<<", ";
1708       *py << f->GetNode( f->NbNodes()-1 )->GetID() << " ])"<< endl; }}
1709 #define debugMsg( txt ) { cout << "# "<< txt << " (line: " << __LINE__ << ")" << endl; }
1710
1711 #else
1712
1713   struct PyDump { PyDump(SMESH_Mesh&) {} void Finish() {} };
1714 #define dumpFunction(f) f
1715 #define dumpMove(n)
1716 #define dumpMoveComm(n,txt)
1717 #define dumpCmd(txt)
1718 #define dumpFunctionEnd()
1719 #define dumpChangeNodes(f) { if(f) {} } // prevent "unused variable 'f'" warning
1720 #define debugMsg( txt ) {}
1721
1722 #endif
1723 }
1724
1725 using namespace VISCOUS_3D;
1726
1727 //================================================================================
1728 /*!
1729  * \brief Constructor of _ViscousBuilder
1730  */
1731 //================================================================================
1732
1733 _ViscousBuilder::_ViscousBuilder()
1734 {
1735   _error = SMESH_ComputeError::New(COMPERR_OK);
1736   _tmpFaceID = 0;
1737 }
1738
1739 //================================================================================
1740 /*!
1741  * \brief Stores error description and returns false
1742  */
1743 //================================================================================
1744
1745 bool _ViscousBuilder::error(const string& text, int solidId )
1746 {
1747   const string prefix = string("Viscous layers builder: ");
1748   _error->myName    = COMPERR_ALGO_FAILED;
1749   _error->myComment = prefix + text;
1750   if ( _mesh )
1751   {
1752     SMESH_subMesh* sm = _mesh->GetSubMeshContaining( solidId );
1753     if ( !sm && !_sdVec.empty() )
1754       sm = _mesh->GetSubMeshContaining( solidId = _sdVec[0]._index );
1755     if ( sm && sm->GetSubShape().ShapeType() == TopAbs_SOLID )
1756     {
1757       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1758       if ( smError && smError->myAlgo )
1759         _error->myAlgo = smError->myAlgo;
1760       smError = _error;
1761       sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1762     }
1763     // set KO to all solids
1764     for ( size_t i = 0; i < _sdVec.size(); ++i )
1765     {
1766       if ( _sdVec[i]._index == solidId )
1767         continue;
1768       sm = _mesh->GetSubMesh( _sdVec[i]._solid );
1769       if ( !sm->IsEmpty() )
1770         continue;
1771       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1772       if ( !smError || smError->IsOK() )
1773       {
1774         smError = SMESH_ComputeError::New( COMPERR_ALGO_FAILED, prefix + "failed");
1775         sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1776       }
1777     }
1778   }
1779   makeGroupOfLE(); // debug
1780
1781   return false;
1782 }
1783
1784 //================================================================================
1785 /*!
1786  * \brief At study restoration, restore event listeners used to clear an inferior
1787  *  dim sub-mesh modified by viscous layers
1788  */
1789 //================================================================================
1790
1791 void _ViscousBuilder::RestoreListeners()
1792 {
1793   // TODO
1794 }
1795
1796 //================================================================================
1797 /*!
1798  * \brief computes SMESH_ProxyMesh::SubMesh::_n2n
1799  */
1800 //================================================================================
1801
1802 bool _ViscousBuilder::MakeN2NMap( _MeshOfSolid* pm )
1803 {
1804   SMESH_subMesh* solidSM = pm->mySubMeshes.front();
1805   TopExp_Explorer fExp( solidSM->GetSubShape(), TopAbs_FACE );
1806   for ( ; fExp.More(); fExp.Next() )
1807   {
1808     SMESHDS_SubMesh* srcSmDS = pm->GetMeshDS()->MeshElements( fExp.Current() );
1809     const SMESH_ProxyMesh::SubMesh* prxSmDS = pm->GetProxySubMesh( fExp.Current() );
1810
1811     if ( !srcSmDS || !prxSmDS || !srcSmDS->NbElements() || !prxSmDS->NbElements() )
1812       continue;
1813     if ( srcSmDS->GetElements()->next() == prxSmDS->GetElements()->next())
1814       continue;
1815
1816     if ( srcSmDS->NbElements() != prxSmDS->NbElements() )
1817       return error( "Different nb elements in a source and a proxy sub-mesh", solidSM->GetId());
1818
1819     SMDS_ElemIteratorPtr srcIt = srcSmDS->GetElements();
1820     SMDS_ElemIteratorPtr prxIt = prxSmDS->GetElements();
1821     while( prxIt->more() )
1822     {
1823       const SMDS_MeshElement* fSrc = srcIt->next();
1824       const SMDS_MeshElement* fPrx = prxIt->next();
1825       if ( fSrc->NbNodes() != fPrx->NbNodes())
1826         return error( "Different elements in a source and a proxy sub-mesh", solidSM->GetId());
1827       for ( int i = 0 ; i < fPrx->NbNodes(); ++i )
1828         pm->setNode2Node( fSrc->GetNode(i), fPrx->GetNode(i), prxSmDS );
1829     }
1830   }
1831   pm->_n2nMapComputed = true;
1832   return true;
1833 }
1834
1835 //================================================================================
1836 /*!
1837  * \brief Does its job
1838  */
1839 //================================================================================
1840
1841 SMESH_ComputeErrorPtr _ViscousBuilder::Compute(SMESH_Mesh&         theMesh,
1842                                                const TopoDS_Shape& theShape)
1843 {
1844   _mesh = & theMesh;
1845
1846   // check if proxy mesh already computed
1847   TopExp_Explorer exp( theShape, TopAbs_SOLID );
1848   if ( !exp.More() )
1849     return error("No SOLID's in theShape"), _error;
1850
1851   if ( _ViscousListener::GetSolidMesh( _mesh, exp.Current(), /*toCreate=*/false))
1852     return SMESH_ComputeErrorPtr(); // everything already computed
1853
1854   PyDump debugDump( theMesh );
1855
1856   // TODO: ignore already computed SOLIDs 
1857   if ( !findSolidsWithLayers())
1858     return _error;
1859
1860   if ( !findFacesWithLayers() )
1861     return _error;
1862
1863   for ( size_t i = 0; i < _sdVec.size(); ++i )
1864   {
1865     size_t iSD = 0;
1866     for ( iSD = 0; iSD < _sdVec.size(); ++iSD ) // find next SOLID to compute
1867       if ( _sdVec[iSD]._before.IsEmpty() &&
1868            !_sdVec[iSD]._solid.IsNull() &&
1869            _sdVec[iSD]._n2eMap.empty() )
1870         break;
1871
1872     if ( ! makeLayer(_sdVec[iSD]) )   // create _LayerEdge's
1873       return _error;
1874
1875     if ( _sdVec[iSD]._n2eMap.size() == 0 ) // no layers in a SOLID
1876     {
1877       _sdVec[iSD]._solid.Nullify();
1878       continue;
1879     }
1880
1881     if ( ! inflate(_sdVec[iSD]) )     // increase length of _LayerEdge's
1882       return _error;
1883
1884     if ( ! refine(_sdVec[iSD]) )      // create nodes and prisms
1885       return _error;
1886
1887     if ( ! shrink(_sdVec[iSD]) )      // shrink 2D mesh on FACEs w/o layer
1888       return _error;
1889
1890     addBoundaryElements(_sdVec[iSD]); // create quadrangles on prism bare sides
1891
1892     const TopoDS_Shape& solid = _sdVec[iSD]._solid;
1893     for ( iSD = 0; iSD < _sdVec.size(); ++iSD )
1894       _sdVec[iSD]._before.Remove( solid );
1895   }
1896
1897   makeGroupOfLE(); // debug
1898   debugDump.Finish();
1899
1900   return _error;
1901 }
1902
1903 //================================================================================
1904 /*!
1905  * \brief Check validity of hypotheses
1906  */
1907 //================================================================================
1908
1909 SMESH_ComputeErrorPtr _ViscousBuilder::CheckHypotheses( SMESH_Mesh&         mesh,
1910                                                         const TopoDS_Shape& shape )
1911 {
1912   _mesh = & mesh;
1913
1914   if ( _ViscousListener::GetSolidMesh( _mesh, shape, /*toCreate=*/false))
1915     return SMESH_ComputeErrorPtr(); // everything already computed
1916
1917
1918   findSolidsWithLayers();
1919   bool ok = findFacesWithLayers( true );
1920
1921   // remove _MeshOfSolid's of _SolidData's
1922   for ( size_t i = 0; i < _sdVec.size(); ++i )
1923     _ViscousListener::RemoveSolidMesh( _mesh, _sdVec[i]._solid );
1924
1925   if ( !ok )
1926     return _error;
1927
1928   return SMESH_ComputeErrorPtr();
1929 }
1930
1931 //================================================================================
1932 /*!
1933  * \brief Finds SOLIDs to compute using viscous layers. Fills _sdVec
1934  */
1935 //================================================================================
1936
1937 bool _ViscousBuilder::findSolidsWithLayers()
1938 {
1939   // get all solids
1940   TopTools_IndexedMapOfShape allSolids;
1941   TopExp::MapShapes( _mesh->GetShapeToMesh(), TopAbs_SOLID, allSolids );
1942   _sdVec.reserve( allSolids.Extent());
1943
1944   SMESH_HypoFilter filter;
1945   for ( int i = 1; i <= allSolids.Extent(); ++i )
1946   {
1947     // find StdMeshers_ViscousLayers hyp assigned to the i-th solid
1948     SMESH_subMesh* sm = _mesh->GetSubMesh( allSolids(i) );
1949     if ( sm->GetSubMeshDS() && sm->GetSubMeshDS()->NbElements() > 0 )
1950       continue; // solid is already meshed
1951     SMESH_Algo* algo = sm->GetAlgo();
1952     if ( !algo ) continue;
1953     // TODO: check if algo is hidden
1954     const list <const SMESHDS_Hypothesis *> & allHyps =
1955       algo->GetUsedHypothesis(*_mesh, allSolids(i), /*ignoreAuxiliary=*/false);
1956     _SolidData* soData = 0;
1957     list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
1958     const StdMeshers_ViscousLayers* viscHyp = 0;
1959     for ( ; hyp != allHyps.end(); ++hyp )
1960       if (( viscHyp = dynamic_cast<const StdMeshers_ViscousLayers*>( *hyp )))
1961       {
1962         TopoDS_Shape hypShape;
1963         filter.Init( filter.Is( viscHyp ));
1964         _mesh->GetHypothesis( allSolids(i), filter, true, &hypShape );
1965
1966         if ( !soData )
1967         {
1968           _MeshOfSolid* proxyMesh = _ViscousListener::GetSolidMesh( _mesh,
1969                                                                     allSolids(i),
1970                                                                     /*toCreate=*/true);
1971           _sdVec.push_back( _SolidData( allSolids(i), proxyMesh ));
1972           soData = & _sdVec.back();
1973           soData->_index = getMeshDS()->ShapeToIndex( allSolids(i));
1974           soData->_helper = new SMESH_MesherHelper( *_mesh );
1975           soData->_helper->SetSubShape( allSolids(i) );
1976           _solids.Add( allSolids(i) );
1977         }
1978         soData->_hyps.push_back( viscHyp );
1979         soData->_hypShapes.push_back( hypShape );
1980       }
1981   }
1982   if ( _sdVec.empty() )
1983     return error
1984       ( SMESH_Comment(StdMeshers_ViscousLayers::GetHypType()) << " hypothesis not found",0);
1985
1986   return true;
1987 }
1988
1989 //================================================================================
1990 /*!
1991  * \brief Set a _SolidData to be computed before another
1992  */
1993 //================================================================================
1994
1995 bool _ViscousBuilder::setBefore( _SolidData& solidBefore, _SolidData& solidAfter )
1996 {
1997   // check possibility to set this order; get all solids before solidBefore
1998   TopTools_IndexedMapOfShape allSolidsBefore;
1999   allSolidsBefore.Add( solidBefore._solid );
2000   for ( int i = 1; i <= allSolidsBefore.Extent(); ++i )
2001   {
2002     int iSD = _solids.FindIndex( allSolidsBefore(i) );
2003     if ( iSD )
2004     {
2005       TopTools_MapIteratorOfMapOfShape soIt( _sdVec[ iSD-1 ]._before );
2006       for ( ; soIt.More(); soIt.Next() )
2007         allSolidsBefore.Add( soIt.Value() );
2008     }
2009   }
2010   if ( allSolidsBefore.Contains( solidAfter._solid ))
2011     return false;
2012
2013   for ( int i = 1; i <= allSolidsBefore.Extent(); ++i )
2014     solidAfter._before.Add( allSolidsBefore(i) );
2015
2016   return true;
2017 }
2018
2019 //================================================================================
2020 /*!
2021  * \brief
2022  */
2023 //================================================================================
2024
2025 bool _ViscousBuilder::findFacesWithLayers(const bool onlyWith)
2026 {
2027   SMESH_MesherHelper helper( *_mesh );
2028   TopExp_Explorer exp;
2029
2030   // collect all faces-to-ignore defined by hyp
2031   for ( size_t i = 0; i < _sdVec.size(); ++i )
2032   {
2033     // get faces-to-ignore defined by each hyp
2034     typedef const StdMeshers_ViscousLayers* THyp;
2035     typedef std::pair< set<TGeomID>, THyp > TFacesOfHyp;
2036     list< TFacesOfHyp > ignoreFacesOfHyps;
2037     list< THyp >::iterator              hyp = _sdVec[i]._hyps.begin();
2038     list< TopoDS_Shape >::iterator hypShape = _sdVec[i]._hypShapes.begin();
2039     for ( ; hyp != _sdVec[i]._hyps.end(); ++hyp, ++hypShape )
2040     {
2041       ignoreFacesOfHyps.push_back( TFacesOfHyp( set<TGeomID>(), *hyp ));
2042       getIgnoreFaces( _sdVec[i]._solid, *hyp, *hypShape, ignoreFacesOfHyps.back().first );
2043     }
2044
2045     // fill _SolidData::_face2hyp and check compatibility of hypotheses
2046     const int nbHyps = _sdVec[i]._hyps.size();
2047     if ( nbHyps > 1 )
2048     {
2049       // check if two hypotheses define different parameters for the same FACE
2050       list< TFacesOfHyp >::iterator igFacesOfHyp;
2051       for ( exp.Init( _sdVec[i]._solid, TopAbs_FACE ); exp.More(); exp.Next() )
2052       {
2053         const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
2054         THyp hyp = 0;
2055         igFacesOfHyp = ignoreFacesOfHyps.begin();
2056         for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
2057           if ( ! igFacesOfHyp->first.count( faceID ))
2058           {
2059             if ( hyp )
2060               return error(SMESH_Comment("Several hypotheses define "
2061                                          "Viscous Layers on the face #") << faceID );
2062             hyp = igFacesOfHyp->second;
2063           }
2064         if ( hyp )
2065           _sdVec[i]._face2hyp.insert( make_pair( faceID, hyp ));
2066         else
2067           _sdVec[i]._ignoreFaceIds.insert( faceID );
2068       }
2069
2070       // check if two hypotheses define different number of viscous layers for
2071       // adjacent faces of a solid
2072       set< int > nbLayersSet;
2073       igFacesOfHyp = ignoreFacesOfHyps.begin();
2074       for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
2075       {
2076         nbLayersSet.insert( igFacesOfHyp->second->GetNumberLayers() );
2077       }
2078       if ( nbLayersSet.size() > 1 )
2079       {
2080         for ( exp.Init( _sdVec[i]._solid, TopAbs_EDGE ); exp.More(); exp.Next() )
2081         {
2082           PShapeIteratorPtr fIt = helper.GetAncestors( exp.Current(), *_mesh, TopAbs_FACE );
2083           THyp hyp1 = 0, hyp2 = 0;
2084           while( const TopoDS_Shape* face = fIt->next() )
2085           {
2086             const TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
2087             map< TGeomID, THyp >::iterator f2h = _sdVec[i]._face2hyp.find( faceID );
2088             if ( f2h != _sdVec[i]._face2hyp.end() )
2089             {
2090               ( hyp1 ? hyp2 : hyp1 ) = f2h->second;
2091             }
2092           }
2093           if ( hyp1 && hyp2 &&
2094                hyp1->GetNumberLayers() != hyp2->GetNumberLayers() )
2095           {
2096             return error("Two hypotheses define different number of "
2097                          "viscous layers on adjacent faces");
2098           }
2099         }
2100       }
2101     } // if ( nbHyps > 1 )
2102     else
2103     {
2104       _sdVec[i]._ignoreFaceIds.swap( ignoreFacesOfHyps.back().first );
2105     }
2106   } // loop on _sdVec
2107
2108   if ( onlyWith ) // is called to check hypotheses compatibility only
2109     return true;
2110
2111   // fill _SolidData::_reversedFaceIds
2112   for ( size_t i = 0; i < _sdVec.size(); ++i )
2113   {
2114     exp.Init( _sdVec[i]._solid.Oriented( TopAbs_FORWARD ), TopAbs_FACE );
2115     for ( ; exp.More(); exp.Next() )
2116     {
2117       const TopoDS_Face& face = TopoDS::Face( exp.Current() );
2118       const TGeomID faceID = getMeshDS()->ShapeToIndex( face );
2119       if ( //!sdVec[i]._ignoreFaceIds.count( faceID ) &&
2120           helper.NbAncestors( face, *_mesh, TopAbs_SOLID ) > 1 &&
2121           helper.IsReversedSubMesh( face ))
2122       {
2123         _sdVec[i]._reversedFaceIds.insert( faceID );
2124       }
2125     }
2126   }
2127
2128   // Find FACEs to shrink mesh on (solution 2 in issue 0020832): fill in _shrinkShape2Shape
2129   TopTools_IndexedMapOfShape shapes;
2130   std::string structAlgoName = "Hexa_3D";
2131   for ( size_t i = 0; i < _sdVec.size(); ++i )
2132   {
2133     shapes.Clear();
2134     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_EDGE, shapes);
2135     for ( int iE = 1; iE <= shapes.Extent(); ++iE )
2136     {
2137       const TopoDS_Shape& edge = shapes(iE);
2138       // find 2 FACEs sharing an EDGE
2139       TopoDS_Shape FF[2];
2140       PShapeIteratorPtr fIt = helper.GetAncestors(edge, *_mesh, TopAbs_FACE, &_sdVec[i]._solid);
2141       while ( fIt->more())
2142       {
2143         const TopoDS_Shape* f = fIt->next();
2144         FF[ int( !FF[0].IsNull()) ] = *f;
2145       }
2146       if( FF[1].IsNull() ) continue; // seam edge can be shared by 1 FACE only
2147
2148       // check presence of layers on them
2149       int ignore[2];
2150       for ( int j = 0; j < 2; ++j )
2151         ignore[j] = _sdVec[i]._ignoreFaceIds.count( getMeshDS()->ShapeToIndex( FF[j] ));
2152       if ( ignore[0] == ignore[1] )
2153         continue; // nothing interesting
2154       TopoDS_Shape fWOL = FF[ ignore[0] ? 0 : 1 ];
2155
2156       // add EDGE to maps
2157       if ( !fWOL.IsNull())
2158       {
2159         TGeomID edgeInd = getMeshDS()->ShapeToIndex( edge );
2160         _sdVec[i]._shrinkShape2Shape.insert( make_pair( edgeInd, fWOL ));
2161       }
2162     }
2163   }
2164
2165   // Find the SHAPE along which to inflate _LayerEdge based on VERTEX
2166
2167   for ( size_t i = 0; i < _sdVec.size(); ++i )
2168   {
2169     shapes.Clear();
2170     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_VERTEX, shapes);
2171     for ( int iV = 1; iV <= shapes.Extent(); ++iV )
2172     {
2173       const TopoDS_Shape& vertex = shapes(iV);
2174       // find faces WOL sharing the vertex
2175       vector< TopoDS_Shape > facesWOL;
2176       size_t totalNbFaces = 0;
2177       PShapeIteratorPtr fIt = helper.GetAncestors(vertex, *_mesh, TopAbs_FACE, &_sdVec[i]._solid );
2178       while ( fIt->more())
2179       {
2180         const TopoDS_Shape* f = fIt->next();
2181         totalNbFaces++;
2182         const int fID = getMeshDS()->ShapeToIndex( *f );
2183         if ( _sdVec[i]._ignoreFaceIds.count ( fID ) /*&& !_sdVec[i]._noShrinkShapes.count( fID )*/)
2184           facesWOL.push_back( *f );
2185       }
2186       if ( facesWOL.size() == totalNbFaces || facesWOL.empty() )
2187         continue; // no layers at this vertex or no WOL
2188       TGeomID vInd = getMeshDS()->ShapeToIndex( vertex );
2189       switch ( facesWOL.size() )
2190       {
2191       case 1:
2192       {
2193         helper.SetSubShape( facesWOL[0] );
2194         if ( helper.IsRealSeam( vInd )) // inflate along a seam edge?
2195         {
2196           TopoDS_Shape seamEdge;
2197           PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
2198           while ( eIt->more() && seamEdge.IsNull() )
2199           {
2200             const TopoDS_Shape* e = eIt->next();
2201             if ( helper.IsRealSeam( *e ) )
2202               seamEdge = *e;
2203           }
2204           if ( !seamEdge.IsNull() )
2205           {
2206             _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, seamEdge ));
2207             break;
2208           }
2209         }
2210         _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, facesWOL[0] ));
2211         break;
2212       }
2213       case 2:
2214       {
2215         // find an edge shared by 2 faces
2216         PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
2217         while ( eIt->more())
2218         {
2219           const TopoDS_Shape* e = eIt->next();
2220           if ( helper.IsSubShape( *e, facesWOL[0]) &&
2221                helper.IsSubShape( *e, facesWOL[1]))
2222           {
2223             _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, *e )); break;
2224           }
2225         }
2226         break;
2227       }
2228       default:
2229         return error("Not yet supported case", _sdVec[i]._index);
2230       }
2231     }
2232   }
2233
2234   // Add to _noShrinkShapes sub-shapes of FACE's that can't be shrinked since
2235   // the algo of the SOLID sharing the FACE does not support it or for other reasons
2236   set< string > notSupportAlgos; notSupportAlgos.insert( structAlgoName );
2237   for ( size_t i = 0; i < _sdVec.size(); ++i )
2238   {
2239     map< TGeomID, TopoDS_Shape >::iterator e2f = _sdVec[i]._shrinkShape2Shape.begin();
2240     for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); ++e2f )
2241     {
2242       const TopoDS_Shape& fWOL = e2f->second;
2243       const TGeomID     edgeID = e2f->first;
2244       TGeomID           faceID = getMeshDS()->ShapeToIndex( fWOL );
2245       TopoDS_Shape        edge = getMeshDS()->IndexToShape( edgeID );
2246       if ( edge.ShapeType() != TopAbs_EDGE )
2247         continue; // shrink shape is VERTEX
2248
2249       TopoDS_Shape solid;
2250       PShapeIteratorPtr soIt = helper.GetAncestors(fWOL, *_mesh, TopAbs_SOLID);
2251       while ( soIt->more() && solid.IsNull() )
2252       {
2253         const TopoDS_Shape* so = soIt->next();
2254         if ( !so->IsSame( _sdVec[i]._solid ))
2255           solid = *so;
2256       }
2257       if ( solid.IsNull() )
2258         continue;
2259
2260       bool noShrinkE = false;
2261       SMESH_Algo*  algo = _mesh->GetSubMesh( solid )->GetAlgo();
2262       bool isStructured = ( algo && algo->GetName() == structAlgoName );
2263       size_t     iSolid = _solids.FindIndex( solid ) - 1;
2264       if ( iSolid < _sdVec.size() && _sdVec[ iSolid ]._ignoreFaceIds.count( faceID ))
2265       {
2266         // the adjacent SOLID has NO layers on fWOL;
2267         // shrink allowed if
2268         // - there are layers on the EDGE in the adjacent SOLID
2269         // - there are NO layers in the adjacent SOLID && algo is unstructured and computed later
2270         bool hasWLAdj = (_sdVec[iSolid]._shrinkShape2Shape.count( edgeID ));
2271         bool shrinkAllowed = (( hasWLAdj ) ||
2272                               ( !isStructured && setBefore( _sdVec[ i ], _sdVec[ iSolid ] )));
2273         noShrinkE = !shrinkAllowed;
2274       }
2275       else if ( iSolid < _sdVec.size() )
2276       {
2277         // the adjacent SOLID has layers on fWOL;
2278         // check if SOLID's mesh is unstructured and then try to set it
2279         // to be computed after the i-th solid
2280         if ( isStructured || !setBefore( _sdVec[ i ], _sdVec[ iSolid ] ))
2281           noShrinkE = true; // don't shrink fWOL
2282       }
2283       else
2284       {
2285         // the adjacent SOLID has NO layers at all
2286         noShrinkE = isStructured;
2287       }
2288
2289       if ( noShrinkE )
2290       {
2291         _sdVec[i]._noShrinkShapes.insert( edgeID );
2292
2293         // check if there is a collision with to-shrink-from EDGEs in iSolid
2294         // if ( iSolid < _sdVec.size() )
2295         // {
2296         //   shapes.Clear();
2297         //   TopExp::MapShapes( fWOL, TopAbs_EDGE, shapes);
2298         //   for ( int iE = 1; iE <= shapes.Extent(); ++iE )
2299         //   {
2300         //     const TopoDS_Edge& E = TopoDS::Edge( shapes( iE ));
2301         //     const TGeomID    eID = getMeshDS()->ShapeToIndex( E );
2302         //     if ( eID == edgeID ||
2303         //          !_sdVec[iSolid]._shrinkShape2Shape.count( eID ) ||
2304         //          _sdVec[i]._noShrinkShapes.count( eID ))
2305         //       continue;
2306         //     for ( int is1st = 0; is1st < 2; ++is1st )
2307         //     {
2308         //       TopoDS_Vertex V = helper.IthVertex( is1st, E );
2309         //       if ( _sdVec[i]._noShrinkShapes.count( getMeshDS()->ShapeToIndex( V ) ))
2310         //       {
2311         //         return error("No way to make a conformal mesh with "
2312         //                      "the given set of faces with layers", _sdVec[i]._index);
2313         //       }
2314         //     }
2315         //   }
2316         // }
2317       }
2318
2319       // add VERTEXes of the edge in _noShrinkShapes, which is necessary if
2320       // _shrinkShape2Shape is different in the adjacent SOLID
2321       for ( TopoDS_Iterator vIt( edge ); vIt.More(); vIt.Next() )
2322       {
2323         TGeomID vID = getMeshDS()->ShapeToIndex( vIt.Value() );
2324         bool noShrinkV = false;
2325
2326         if ( iSolid < _sdVec.size() )
2327         {
2328           if ( _sdVec[ iSolid ]._ignoreFaceIds.count( faceID ))
2329           {
2330             map< TGeomID, TopoDS_Shape >::iterator i2S, i2SAdj;
2331             i2S    = _sdVec[i     ]._shrinkShape2Shape.find( vID );
2332             i2SAdj = _sdVec[iSolid]._shrinkShape2Shape.find( vID );
2333             if ( i2SAdj == _sdVec[iSolid]._shrinkShape2Shape.end() )
2334               noShrinkV = ( i2S->second.ShapeType() == TopAbs_EDGE || isStructured );
2335             else
2336               noShrinkV = ( ! i2S->second.IsSame( i2SAdj->second ));
2337           }
2338           else
2339           {
2340             noShrinkV = noShrinkE;
2341           }
2342         }
2343         else
2344         {
2345           // the adjacent SOLID has NO layers at all
2346           noShrinkV = ( isStructured ||
2347                         _sdVec[i]._shrinkShape2Shape[ vID ].ShapeType() == TopAbs_EDGE );
2348         }
2349         if ( noShrinkV )
2350           _sdVec[i]._noShrinkShapes.insert( vID );
2351       }
2352
2353     } // loop on _sdVec[i]._shrinkShape2Shape
2354   } // loop on _sdVec to fill in _SolidData::_noShrinkShapes
2355
2356
2357     // add FACEs of other SOLIDs to _ignoreFaceIds
2358   for ( size_t i = 0; i < _sdVec.size(); ++i )
2359   {
2360     shapes.Clear();
2361     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_FACE, shapes);
2362
2363     for ( exp.Init( _mesh->GetShapeToMesh(), TopAbs_FACE ); exp.More(); exp.Next() )
2364     {
2365       if ( !shapes.Contains( exp.Current() ))
2366         _sdVec[i]._ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( exp.Current() ));
2367     }
2368   }
2369
2370   return true;
2371 }
2372
2373 //================================================================================
2374 /*!
2375  * \brief Finds FACEs w/o layers for a given SOLID by an hypothesis
2376  */
2377 //================================================================================
2378
2379 void _ViscousBuilder::getIgnoreFaces(const TopoDS_Shape&             solid,
2380                                      const StdMeshers_ViscousLayers* hyp,
2381                                      const TopoDS_Shape&             hypShape,
2382                                      set<TGeomID>&                   ignoreFaceIds)
2383 {
2384   TopExp_Explorer exp;
2385
2386   vector<TGeomID> ids = hyp->GetBndShapes();
2387   if ( hyp->IsToIgnoreShapes() ) // FACEs to ignore are given
2388   {
2389     for ( size_t ii = 0; ii < ids.size(); ++ii )
2390     {
2391       const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[ii] );
2392       if ( !s.IsNull() && s.ShapeType() == TopAbs_FACE )
2393         ignoreFaceIds.insert( ids[ii] );
2394     }
2395   }
2396   else // FACEs with layers are given
2397   {
2398     exp.Init( solid, TopAbs_FACE );
2399     for ( ; exp.More(); exp.Next() )
2400     {
2401       TGeomID faceInd = getMeshDS()->ShapeToIndex( exp.Current() );
2402       if ( find( ids.begin(), ids.end(), faceInd ) == ids.end() )
2403         ignoreFaceIds.insert( faceInd );
2404     }
2405   }
2406
2407   // ignore internal FACEs if inlets and outlets are specified
2408   if ( hyp->IsToIgnoreShapes() )
2409   {
2410     TopTools_IndexedDataMapOfShapeListOfShape solidsOfFace;
2411     TopExp::MapShapesAndAncestors( hypShape,
2412                                    TopAbs_FACE, TopAbs_SOLID, solidsOfFace);
2413
2414     for ( exp.Init( solid, TopAbs_FACE ); exp.More(); exp.Next() )
2415     {
2416       const TopoDS_Face& face = TopoDS::Face( exp.Current() );
2417       if ( SMESH_MesherHelper::NbAncestors( face, *_mesh, TopAbs_SOLID ) < 2 )
2418         continue;
2419
2420       int nbSolids = solidsOfFace.FindFromKey( face ).Extent();
2421       if ( nbSolids > 1 )
2422         ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( face ));
2423     }
2424   }
2425 }
2426
2427 //================================================================================
2428 /*!
2429  * \brief Create the inner surface of the viscous layer and prepare data for infation
2430  */
2431 //================================================================================
2432
2433 bool _ViscousBuilder::makeLayer(_SolidData& data)
2434 {
2435   // get all sub-shapes to make layers on
2436   set<TGeomID> subIds, faceIds;
2437   subIds = data._noShrinkShapes;
2438   TopExp_Explorer exp( data._solid, TopAbs_FACE );
2439   for ( ; exp.More(); exp.Next() )
2440   {
2441     SMESH_subMesh* fSubM = _mesh->GetSubMesh( exp.Current() );
2442     if ( ! data._ignoreFaceIds.count( fSubM->GetId() ))
2443       faceIds.insert( fSubM->GetId() );
2444   }
2445
2446   // make a map to find new nodes on sub-shapes shared with other SOLID
2447   map< TGeomID, TNode2Edge* >::iterator s2ne;
2448   map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
2449   for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
2450   {
2451     TGeomID shapeInd = s2s->first;
2452     for ( size_t i = 0; i < _sdVec.size(); ++i )
2453     {
2454       if ( _sdVec[i]._index == data._index ) continue;
2455       map< TGeomID, TopoDS_Shape >::iterator s2s2 = _sdVec[i]._shrinkShape2Shape.find( shapeInd );
2456       if ( s2s2 != _sdVec[i]._shrinkShape2Shape.end() &&
2457            *s2s == *s2s2 && !_sdVec[i]._n2eMap.empty() )
2458       {
2459         data._s2neMap.insert( make_pair( shapeInd, &_sdVec[i]._n2eMap ));
2460         break;
2461       }
2462     }
2463   }
2464
2465   // Create temporary faces and _LayerEdge's
2466
2467   dumpFunction(SMESH_Comment("makeLayers_")<<data._index);
2468
2469   data._stepSize = Precision::Infinite();
2470   data._stepSizeNodes[0] = 0;
2471
2472   SMESH_MesherHelper helper( *_mesh );
2473   helper.SetSubShape( data._solid );
2474   helper.SetElementsOnShape( true );
2475
2476   vector< const SMDS_MeshNode*> newNodes; // of a mesh face
2477   TNode2Edge::iterator n2e2;
2478
2479   // collect _LayerEdge's of shapes they are based on
2480   vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
2481   const int nbShapes = getMeshDS()->MaxShapeIndex();
2482   edgesByGeom.resize( nbShapes+1 );
2483
2484   // set data of _EdgesOnShape's
2485   if ( SMESH_subMesh* sm = _mesh->GetSubMesh( data._solid ))
2486   {
2487     SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/false);
2488     while ( smIt->more() )
2489     {
2490       sm = smIt->next();
2491       if ( sm->GetSubShape().ShapeType() == TopAbs_FACE &&
2492            !faceIds.count( sm->GetId() ))
2493         continue;
2494       setShapeData( edgesByGeom[ sm->GetId() ], sm, data );
2495     }
2496   }
2497   // make _LayerEdge's
2498   for ( set<TGeomID>::iterator id = faceIds.begin(); id != faceIds.end(); ++id )
2499   {
2500     const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( *id ));
2501     SMESH_subMesh* sm = _mesh->GetSubMesh( F );
2502     SMESH_ProxyMesh::SubMesh* proxySub =
2503       data._proxyMesh->getFaceSubM( F, /*create=*/true);
2504
2505     SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2506     if ( !smDS ) return error(SMESH_Comment("Not meshed face ") << *id, data._index );
2507
2508     SMDS_ElemIteratorPtr eIt = smDS->GetElements();
2509     while ( eIt->more() )
2510     {
2511       const SMDS_MeshElement* face = eIt->next();
2512       double          faceMaxCosin = -1;
2513       _LayerEdge*     maxCosinEdge = 0;
2514       int             nbDegenNodes = 0;
2515
2516       newNodes.resize( face->NbCornerNodes() );
2517       for ( size_t i = 0 ; i < newNodes.size(); ++i )
2518       {
2519         const SMDS_MeshNode* n = face->GetNode( i );
2520         const int      shapeID = n->getshapeId();
2521         const bool onDegenShap = helper.IsDegenShape( shapeID );
2522         const bool onDegenEdge = ( onDegenShap && n->GetPosition()->GetDim() == 1 );
2523         if ( onDegenShap )
2524         {
2525           if ( onDegenEdge )
2526           {
2527             // substitute n on a degenerated EDGE with a node on a corresponding VERTEX
2528             const TopoDS_Shape& E = getMeshDS()->IndexToShape( shapeID );
2529             TopoDS_Vertex       V = helper.IthVertex( 0, TopoDS::Edge( E ));
2530             if ( const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() )) {
2531               n = vN;
2532               nbDegenNodes++;
2533             }
2534           }
2535           else
2536           {
2537             nbDegenNodes++;
2538           }
2539         }
2540         TNode2Edge::iterator n2e = data._n2eMap.insert( make_pair( n, (_LayerEdge*)0 )).first;
2541         if ( !(*n2e).second )
2542         {
2543           // add a _LayerEdge
2544           _LayerEdge* edge = new _LayerEdge();
2545           edge->_nodes.push_back( n );
2546           n2e->second = edge;
2547           edgesByGeom[ shapeID ]._edges.push_back( edge );
2548           const bool noShrink = data._noShrinkShapes.count( shapeID );
2549
2550           SMESH_TNodeXYZ xyz( n );
2551
2552           // set edge data or find already refined _LayerEdge and get data from it
2553           if (( !noShrink                                                     ) &&
2554               ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE        ) &&
2555               (( s2ne = data._s2neMap.find( shapeID )) != data._s2neMap.end() ) &&
2556               (( n2e2 = (*s2ne).second->find( n )) != s2ne->second->end()     ))
2557           {
2558             _LayerEdge* foundEdge = (*n2e2).second;
2559             gp_XYZ        lastPos = edge->Copy( *foundEdge, edgesByGeom[ shapeID ], helper );
2560             foundEdge->_pos.push_back( lastPos );
2561             // location of the last node is modified and we restore it by foundEdge->_pos.back()
2562             const_cast< SMDS_MeshNode* >
2563               ( edge->_nodes.back() )->setXYZ( xyz.X(), xyz.Y(), xyz.Z() );
2564           }
2565           else
2566           {
2567             if ( !noShrink )
2568             {
2569               edge->_nodes.push_back( helper.AddNode( xyz.X(), xyz.Y(), xyz.Z() ));
2570             }
2571             if ( !setEdgeData( *edge, edgesByGeom[ shapeID ], helper, data ))
2572               return false;
2573
2574             if ( edge->_nodes.size() < 2 )
2575               edge->Block( data );
2576               //data._noShrinkShapes.insert( shapeID );
2577           }
2578           dumpMove(edge->_nodes.back());
2579
2580           if ( edge->_cosin > faceMaxCosin )
2581           {
2582             faceMaxCosin = edge->_cosin;
2583             maxCosinEdge = edge;
2584           }
2585         }
2586         newNodes[ i ] = n2e->second->_nodes.back();
2587
2588         if ( onDegenEdge )
2589           data._n2eMap.insert( make_pair( face->GetNode( i ), n2e->second ));
2590       }
2591       if ( newNodes.size() - nbDegenNodes < 2 )
2592         continue;
2593
2594       // create a temporary face
2595       const SMDS_MeshElement* newFace =
2596         new _TmpMeshFace( newNodes, --_tmpFaceID, face->getshapeId(), face->getIdInShape() );
2597       proxySub->AddElement( newFace );
2598
2599       // compute inflation step size by min size of element on a convex surface
2600       if ( faceMaxCosin > theMinSmoothCosin )
2601         limitStepSize( data, face, maxCosinEdge );
2602
2603     } // loop on 2D elements on a FACE
2604   } // loop on FACEs of a SOLID to create _LayerEdge's
2605
2606
2607   // Set _LayerEdge::_neibors
2608   TNode2Edge::iterator n2e;
2609   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2610   {
2611     _EdgesOnShape& eos = data._edgesOnShape[iS];
2612     for ( size_t i = 0; i < eos._edges.size(); ++i )
2613     {
2614       _LayerEdge* edge = eos._edges[i];
2615       TIDSortedNodeSet nearNodes;
2616       SMDS_ElemIteratorPtr fIt = edge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2617       while ( fIt->more() )
2618       {
2619         const SMDS_MeshElement* f = fIt->next();
2620         if ( !data._ignoreFaceIds.count( f->getshapeId() ))
2621           nearNodes.insert( f->begin_nodes(), f->end_nodes() );
2622       }
2623       nearNodes.erase( edge->_nodes[0] );
2624       edge->_neibors.reserve( nearNodes.size() );
2625       TIDSortedNodeSet::iterator node = nearNodes.begin();
2626       for ( ; node != nearNodes.end(); ++node )
2627         if (( n2e = data._n2eMap.find( *node )) != data._n2eMap.end() )
2628           edge->_neibors.push_back( n2e->second );
2629     }
2630   }
2631
2632   data._epsilon = 1e-7;
2633   if ( data._stepSize < 1. )
2634     data._epsilon *= data._stepSize;
2635
2636   if ( !findShapesToSmooth( data )) // _LayerEdge::_maxLen is computed here
2637     return false;
2638
2639   // limit data._stepSize depending on surface curvature and fill data._convexFaces
2640   limitStepSizeByCurvature( data ); // !!! it must be before node substitution in _Simplex
2641
2642   // Set target nodes into _Simplex and _LayerEdge's to _2NearEdges
2643   const SMDS_MeshNode* nn[2];
2644   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2645   {
2646     _EdgesOnShape& eos = data._edgesOnShape[iS];
2647     for ( size_t i = 0; i < eos._edges.size(); ++i )
2648     {
2649       _LayerEdge* edge = eos._edges[i];
2650       if ( edge->IsOnEdge() )
2651       {
2652         // get neighbor nodes
2653         bool hasData = ( edge->_2neibors->_edges[0] );
2654         if ( hasData ) // _LayerEdge is a copy of another one
2655         {
2656           nn[0] = edge->_2neibors->srcNode(0);
2657           nn[1] = edge->_2neibors->srcNode(1);
2658         }
2659         else if ( !findNeiborsOnEdge( edge, nn[0],nn[1], eos, data ))
2660         {
2661           return false;
2662         }
2663         // set neighbor _LayerEdge's
2664         for ( int j = 0; j < 2; ++j )
2665         {
2666           if (( n2e = data._n2eMap.find( nn[j] )) == data._n2eMap.end() )
2667             return error("_LayerEdge not found by src node", data._index);
2668           edge->_2neibors->_edges[j] = n2e->second;
2669         }
2670         if ( !hasData )
2671           edge->SetDataByNeighbors( nn[0], nn[1], eos, helper );
2672       }
2673
2674       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
2675       {
2676         _Simplex& s = edge->_simplices[j];
2677         s._nNext = data._n2eMap[ s._nNext ]->_nodes.back();
2678         s._nPrev = data._n2eMap[ s._nPrev ]->_nodes.back();
2679       }
2680
2681       // For an _LayerEdge on a degenerated EDGE, copy some data from
2682       // a corresponding _LayerEdge on a VERTEX
2683       // (issue 52453, pb on a downloaded SampleCase2-Tet-netgen-mephisto.hdf)
2684       if ( helper.IsDegenShape( edge->_nodes[0]->getshapeId() ))
2685       {
2686         // Generally we should not get here
2687         if ( eos.ShapeType() != TopAbs_EDGE )
2688           continue;
2689         TopoDS_Vertex V = helper.IthVertex( 0, TopoDS::Edge( eos._shape ));
2690         const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() );
2691         if (( n2e = data._n2eMap.find( vN )) == data._n2eMap.end() )
2692           continue;
2693         const _LayerEdge* vEdge = n2e->second;
2694         edge->_normal    = vEdge->_normal;
2695         edge->_lenFactor = vEdge->_lenFactor;
2696         edge->_cosin     = vEdge->_cosin;
2697       }
2698
2699     } // loop on data._edgesOnShape._edges
2700   } // loop on data._edgesOnShape
2701
2702   // fix _LayerEdge::_2neibors on EDGEs to smooth
2703   // map< TGeomID,Handle(Geom_Curve)>::iterator e2c = data._edge2curve.begin();
2704   // for ( ; e2c != data._edge2curve.end(); ++e2c )
2705   //   if ( !e2c->second.IsNull() )
2706   //   {
2707   //     if ( _EdgesOnShape* eos = data.GetShapeEdges( e2c->first ))
2708   //       data.Sort2NeiborsOnEdge( eos->_edges );
2709   //   }
2710
2711   dumpFunctionEnd();
2712   return true;
2713 }
2714
2715 //================================================================================
2716 /*!
2717  * \brief Compute inflation step size by min size of element on a convex surface
2718  */
2719 //================================================================================
2720
2721 void _ViscousBuilder::limitStepSize( _SolidData&             data,
2722                                      const SMDS_MeshElement* face,
2723                                      const _LayerEdge*       maxCosinEdge )
2724 {
2725   int iN = 0;
2726   double minSize = 10 * data._stepSize;
2727   const int nbNodes = face->NbCornerNodes();
2728   for ( int i = 0; i < nbNodes; ++i )
2729   {
2730     const SMDS_MeshNode* nextN = face->GetNode( SMESH_MesherHelper::WrapIndex( i+1, nbNodes ));
2731     const SMDS_MeshNode*  curN = face->GetNode( i );
2732     if ( nextN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ||
2733          curN-> GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
2734     {
2735       double dist = SMESH_TNodeXYZ( curN ).Distance( nextN );
2736       if ( dist < minSize )
2737         minSize = dist, iN = i;
2738     }
2739   }
2740   double newStep = 0.8 * minSize / maxCosinEdge->_lenFactor;
2741   if ( newStep < data._stepSize )
2742   {
2743     data._stepSize = newStep;
2744     data._stepSizeCoeff = 0.8 / maxCosinEdge->_lenFactor;
2745     data._stepSizeNodes[0] = face->GetNode( iN );
2746     data._stepSizeNodes[1] = face->GetNode( SMESH_MesherHelper::WrapIndex( iN+1, nbNodes ));
2747   }
2748 }
2749
2750 //================================================================================
2751 /*!
2752  * \brief Compute inflation step size by min size of element on a convex surface
2753  */
2754 //================================================================================
2755
2756 void _ViscousBuilder::limitStepSize( _SolidData& data, const double minSize )
2757 {
2758   if ( minSize < data._stepSize )
2759   {
2760     data._stepSize = minSize;
2761     if ( data._stepSizeNodes[0] )
2762     {
2763       double dist =
2764         SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
2765       data._stepSizeCoeff = data._stepSize / dist;
2766     }
2767   }
2768 }
2769
2770 //================================================================================
2771 /*!
2772  * \brief Limit data._stepSize by evaluating curvature of shapes and fill data._convexFaces
2773  */
2774 //================================================================================
2775
2776 void _ViscousBuilder::limitStepSizeByCurvature( _SolidData& data )
2777 {
2778   SMESH_MesherHelper helper( *_mesh );
2779
2780   const int nbTestPnt = 5; // on a FACE sub-shape
2781
2782   BRepLProp_SLProps surfProp( 2, 1e-6 );
2783   data._convexFaces.clear();
2784
2785   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2786   {
2787     _EdgesOnShape& eof = data._edgesOnShape[iS];
2788     if ( eof.ShapeType() != TopAbs_FACE ||
2789          data._ignoreFaceIds.count( eof._shapeID ))
2790       continue;
2791
2792     TopoDS_Face        F = TopoDS::Face( eof._shape );
2793     SMESH_subMesh *   sm = eof._subMesh;
2794     const TGeomID faceID = eof._shapeID;
2795
2796     BRepAdaptor_Surface surface( F, false );
2797     surfProp.SetSurface( surface );
2798
2799     bool isTooCurved = false;
2800
2801     _ConvexFace cnvFace;
2802     const double        oriFactor = ( F.Orientation() == TopAbs_REVERSED ? +1. : -1. );
2803     SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/true);
2804     while ( smIt->more() )
2805     {
2806       sm = smIt->next();
2807       const TGeomID subID = sm->GetId();
2808       // find _LayerEdge's of a sub-shape
2809       _EdgesOnShape* eos;
2810       if (( eos = data.GetShapeEdges( subID )))
2811         cnvFace._subIdToEOS.insert( make_pair( subID, eos ));
2812       else
2813         continue;
2814       // check concavity and curvature and limit data._stepSize
2815       const double minCurvature =
2816         1. / ( eos->_hyp.GetTotalThickness() * ( 1 + theThickToIntersection ));
2817       size_t iStep = Max( 1, eos->_edges.size() / nbTestPnt );
2818       for ( size_t i = 0; i < eos->_edges.size(); i += iStep )
2819       {
2820         gp_XY uv = helper.GetNodeUV( F, eos->_edges[ i ]->_nodes[0] );
2821         surfProp.SetParameters( uv.X(), uv.Y() );
2822         if ( !surfProp.IsCurvatureDefined() )
2823           continue;
2824         if ( surfProp.MaxCurvature() * oriFactor > minCurvature )
2825         {
2826           limitStepSize( data, 0.9 / surfProp.MaxCurvature() * oriFactor );
2827           isTooCurved = true;
2828         }
2829         if ( surfProp.MinCurvature() * oriFactor > minCurvature )
2830         {
2831           limitStepSize( data, 0.9 / surfProp.MinCurvature() * oriFactor );
2832           isTooCurved = true;
2833         }
2834       }
2835     } // loop on sub-shapes of the FACE
2836
2837     if ( !isTooCurved ) continue;
2838
2839     _ConvexFace & convFace =
2840       data._convexFaces.insert( make_pair( faceID, cnvFace )).first->second;
2841
2842     convFace._face = F;
2843     convFace._normalsFixed = false;
2844
2845     // skip a closed surface (data._convexFaces is useful anyway)
2846     bool isClosedF = false;
2847     helper.SetSubShape( F );
2848     if ( helper.HasRealSeam() )
2849     {
2850       // in the closed surface there must be a closed EDGE
2851       for ( TopExp_Explorer eIt( F, TopAbs_EDGE ); eIt.More() && !isClosedF; eIt.Next() )
2852         isClosedF = helper.IsClosedEdge( TopoDS::Edge( eIt.Current() ));
2853     }
2854     if ( isClosedF )
2855     {
2856       // limit _LayerEdge::_maxLen on the FACE
2857       const double minCurvature =
2858         1. / ( eof._hyp.GetTotalThickness() * ( 1 + theThickToIntersection ));
2859       map< TGeomID, _EdgesOnShape* >::iterator id2eos = cnvFace._subIdToEOS.find( faceID );
2860       if ( id2eos != cnvFace._subIdToEOS.end() )
2861       {
2862         _EdgesOnShape& eos = * id2eos->second;
2863         for ( size_t i = 0; i < eos._edges.size(); ++i )
2864         {
2865           _LayerEdge* ledge = eos._edges[ i ];
2866           gp_XY uv = helper.GetNodeUV( F, ledge->_nodes[0] );
2867           surfProp.SetParameters( uv.X(), uv.Y() );
2868           if ( !surfProp.IsCurvatureDefined() )
2869             continue;
2870
2871           if ( surfProp.MaxCurvature() * oriFactor > minCurvature )
2872             ledge->_maxLen = Min( ledge->_maxLen, 1. / surfProp.MaxCurvature() * oriFactor );
2873
2874           if ( surfProp.MinCurvature() * oriFactor > minCurvature )
2875             ledge->_maxLen = Min( ledge->_maxLen, 1. / surfProp.MinCurvature() * oriFactor );
2876         }
2877       }
2878       continue;
2879     }
2880
2881     // Fill _ConvexFace::_simplexTestEdges. These _LayerEdge's are used to detect
2882     // prism distortion.
2883     map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.find( faceID );
2884     if ( id2eos != convFace._subIdToEOS.end() && !id2eos->second->_edges.empty() )
2885     {
2886       // there are _LayerEdge's on the FACE it-self;
2887       // select _LayerEdge's near EDGEs
2888       _EdgesOnShape& eos = * id2eos->second;
2889       for ( size_t i = 0; i < eos._edges.size(); ++i )
2890       {
2891         _LayerEdge* ledge = eos._edges[ i ];
2892         for ( size_t j = 0; j < ledge->_simplices.size(); ++j )
2893           if ( ledge->_simplices[j]._nNext->GetPosition()->GetDim() < 2 )
2894           {
2895             convFace._simplexTestEdges.push_back( ledge );
2896             break;
2897           }
2898       }
2899     }
2900     else
2901     {
2902       // where there are no _LayerEdge's on a _ConvexFace,
2903       // as e.g. on a fillet surface with no internal nodes - issue 22580,
2904       // so that collision of viscous internal faces is not detected by check of
2905       // intersection of _LayerEdge's with the viscous internal faces.
2906
2907       set< const SMDS_MeshNode* > usedNodes;
2908
2909       // look for _LayerEdge's with null _sWOL
2910       id2eos = convFace._subIdToEOS.begin();
2911       for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
2912       {
2913         _EdgesOnShape& eos = * id2eos->second;
2914         if ( !eos._sWOL.IsNull() )
2915           continue;
2916         for ( size_t i = 0; i < eos._edges.size(); ++i )
2917         {
2918           _LayerEdge* ledge = eos._edges[ i ];
2919           const SMDS_MeshNode* srcNode = ledge->_nodes[0];
2920           if ( !usedNodes.insert( srcNode ).second ) continue;
2921
2922           for ( size_t i = 0; i < ledge->_simplices.size(); ++i )
2923           {
2924             usedNodes.insert( ledge->_simplices[i]._nPrev );
2925             usedNodes.insert( ledge->_simplices[i]._nNext );
2926           }
2927           convFace._simplexTestEdges.push_back( ledge );
2928         }
2929       }
2930     }
2931   } // loop on FACEs of data._solid
2932 }
2933
2934 //================================================================================
2935 /*!
2936  * \brief Detect shapes (and _LayerEdge's on them) to smooth
2937  */
2938 //================================================================================
2939
2940 bool _ViscousBuilder::findShapesToSmooth( _SolidData& data )
2941 {
2942   // define allowed thickness
2943   computeGeomSize( data ); // compute data._geomSize and _LayerEdge::_maxLen
2944
2945   data._maxThickness = 0;
2946   data._minThickness = 1e100;
2947   list< const StdMeshers_ViscousLayers* >::iterator hyp = data._hyps.begin();
2948   for ( ; hyp != data._hyps.end(); ++hyp )
2949   {
2950     data._maxThickness = Max( data._maxThickness, (*hyp)->GetTotalThickness() );
2951     data._minThickness = Min( data._minThickness, (*hyp)->GetTotalThickness() );
2952   }
2953   //const double tgtThick = /*Min( 0.5 * data._geomSize, */data._maxThickness;
2954
2955   // Find shapes needing smoothing; such a shape has _LayerEdge._normal on it's
2956   // boundary inclined to the shape at a sharp angle
2957
2958   //list< TGeomID > shapesToSmooth;
2959   TopTools_MapOfShape edgesOfSmooFaces;
2960
2961   SMESH_MesherHelper helper( *_mesh );
2962   bool ok = true;
2963
2964   vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
2965   data._nbShapesToSmooth = 0;
2966
2967   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check FACEs
2968   {
2969     _EdgesOnShape& eos = edgesByGeom[iS];
2970     eos._toSmooth = false;
2971     if ( eos._edges.empty() || eos.ShapeType() != TopAbs_FACE )
2972       continue;
2973
2974     double tgtThick = eos._hyp.GetTotalThickness();
2975     TopExp_Explorer eExp( edgesByGeom[iS]._shape, TopAbs_EDGE );
2976     for ( ; eExp.More() && !eos._toSmooth; eExp.Next() )
2977     {
2978       TGeomID iE = getMeshDS()->ShapeToIndex( eExp.Current() );
2979       vector<_LayerEdge*>& eE = edgesByGeom[ iE ]._edges;
2980       if ( eE.empty() ) continue;
2981
2982       double faceSize;
2983       for ( size_t i = 0; i < eE.size() && !eos._toSmooth; ++i )
2984         if ( eE[i]->_cosin > theMinSmoothCosin )
2985         {
2986           SMDS_ElemIteratorPtr fIt = eE[i]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2987           while ( fIt->more() && !eos._toSmooth )
2988           {
2989             const SMDS_MeshElement* face = fIt->next();
2990             if ( face->getshapeId() == eos._shapeID &&
2991                  getDistFromEdge( face, eE[i]->_nodes[0], faceSize ))
2992             {
2993               eos._toSmooth = needSmoothing( eE[i]->_cosin, tgtThick, faceSize );
2994             }
2995           }
2996         }
2997     }
2998     if ( eos._toSmooth )
2999     {
3000       for ( eExp.ReInit(); eExp.More(); eExp.Next() )
3001         edgesOfSmooFaces.Add( eExp.Current() );
3002
3003       data.PrepareEdgesToSmoothOnFace( &edgesByGeom[iS], /*substituteSrcNodes=*/false );
3004     }
3005     data._nbShapesToSmooth += eos._toSmooth;
3006
3007   }  // check FACEs
3008
3009   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check EDGEs
3010   {
3011     _EdgesOnShape& eos = edgesByGeom[iS];
3012     eos._edgeSmoother = NULL;
3013     if ( eos._edges.empty() || eos.ShapeType() != TopAbs_EDGE ) continue;
3014     if ( !eos._hyp.ToSmooth() ) continue;
3015
3016     const TopoDS_Edge& E = TopoDS::Edge( edgesByGeom[iS]._shape );
3017     if ( SMESH_Algo::isDegenerated( E ) || !edgesOfSmooFaces.Contains( E ))
3018       continue;
3019
3020     double tgtThick = eos._hyp.GetTotalThickness();
3021     for ( TopoDS_Iterator vIt( E ); vIt.More() && !eos._toSmooth; vIt.Next() )
3022     {
3023       TGeomID iV = getMeshDS()->ShapeToIndex( vIt.Value() );
3024       vector<_LayerEdge*>& eV = edgesByGeom[ iV ]._edges;
3025       if ( eV.empty() || eV[0]->Is( _LayerEdge::MULTI_NORMAL )) continue;
3026       gp_Vec  eDir    = getEdgeDir( E, TopoDS::Vertex( vIt.Value() ));
3027       double angle    = eDir.Angle( eV[0]->_normal );
3028       double cosin    = Cos( angle );
3029       double cosinAbs = Abs( cosin );
3030       if ( cosinAbs > theMinSmoothCosin )
3031       {
3032         // always smooth analytic EDGEs
3033         Handle(Geom_Curve) curve = _Smoother1D::CurveForSmooth( E, eos, helper );
3034         eos._toSmooth = ! curve.IsNull();
3035
3036         // compare tgtThick with the length of an end segment
3037         SMDS_ElemIteratorPtr eIt = eV[0]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
3038         while ( eIt->more() && !eos._toSmooth )
3039         {
3040           const SMDS_MeshElement* endSeg = eIt->next();
3041           if ( endSeg->getshapeId() == (int) iS )
3042           {
3043             double segLen =
3044               SMESH_TNodeXYZ( endSeg->GetNode(0) ).Distance( endSeg->GetNode(1 ));
3045             eos._toSmooth = needSmoothing( cosinAbs, tgtThick, segLen );
3046           }
3047         }
3048         if ( eos._toSmooth )
3049         {
3050           eos._edgeSmoother = new _Smoother1D( curve, eos );
3051
3052           for ( size_t i = 0; i < eos._edges.size(); ++i )
3053             eos._edges[i]->Set( _LayerEdge::TO_SMOOTH );
3054         }
3055       }
3056     }
3057     data._nbShapesToSmooth += eos._toSmooth;
3058
3059   } // check EDGEs
3060
3061   // Reset _cosin if no smooth is allowed by the user
3062   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
3063   {
3064     _EdgesOnShape& eos = edgesByGeom[iS];
3065     if ( eos._edges.empty() ) continue;
3066
3067     if ( !eos._hyp.ToSmooth() )
3068       for ( size_t i = 0; i < eos._edges.size(); ++i )
3069         eos._edges[i]->SetCosin( 0 );
3070   }
3071
3072
3073   // Fill _eosC1 to make that C1 FACEs and EGDEs between them to be smoothed as a whole
3074
3075   TopTools_MapOfShape c1VV;
3076
3077   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check FACEs
3078   {
3079     _EdgesOnShape& eos = edgesByGeom[iS];
3080     if ( eos._edges.empty() ||
3081          eos.ShapeType() != TopAbs_FACE ||
3082          !eos._toSmooth )
3083       continue;
3084
3085     // check EDGEs of a FACE
3086     TopTools_MapOfShape checkedEE, allVV;
3087     list< SMESH_subMesh* > smQueue( 1, eos._subMesh ); // sm of FACEs
3088     while ( !smQueue.empty() )
3089     {
3090       SMESH_subMesh* sm = smQueue.front();
3091       smQueue.pop_front();
3092       SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/false);
3093       while ( smIt->more() )
3094       {
3095         sm = smIt->next();
3096         if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
3097           allVV.Add( sm->GetSubShape() );
3098         if ( sm->GetSubShape().ShapeType() != TopAbs_EDGE ||
3099              !checkedEE.Add( sm->GetSubShape() ))
3100           continue;
3101
3102         _EdgesOnShape*      eoe = data.GetShapeEdges( sm->GetId() );
3103         vector<_LayerEdge*>& eE = eoe->_edges;
3104         if ( eE.empty() || !eoe->_sWOL.IsNull() )
3105           continue;
3106
3107         bool isC1 = true; // check continuity along an EDGE
3108         for ( size_t i = 0; i < eE.size() && isC1; ++i )
3109           isC1 = ( Abs( eE[i]->_cosin ) < theMinSmoothCosin );
3110         if ( !isC1 )
3111           continue;
3112
3113         // check that mesh faces are C1 as well
3114         {
3115           gp_XYZ norm1, norm2;
3116           const SMDS_MeshNode*   n = eE[ eE.size() / 2 ]->_nodes[0];
3117           SMDS_ElemIteratorPtr fIt = n->GetInverseElementIterator(SMDSAbs_Face);
3118           if ( !SMESH_MeshAlgos::FaceNormal( fIt->next(), norm1, /*normalized=*/true ))
3119             continue;
3120           while ( fIt->more() && isC1 )
3121             isC1 = ( SMESH_MeshAlgos::FaceNormal( fIt->next(), norm2, /*normalized=*/true ) &&
3122                      Abs( norm1 * norm2 ) >= ( 1. - theMinSmoothCosin ));
3123           if ( !isC1 )
3124             continue;
3125         }
3126
3127         // add the EDGE and an adjacent FACE to _eosC1
3128         PShapeIteratorPtr fIt = helper.GetAncestors( sm->GetSubShape(), *_mesh, TopAbs_FACE );
3129         while ( const TopoDS_Shape* face = fIt->next() )
3130         {
3131           _EdgesOnShape* eof = data.GetShapeEdges( *face );
3132           if ( !eof ) continue; // other solid
3133           if ( !eos.HasC1( eoe ))
3134           {
3135             eos._eosC1.push_back( eoe );
3136             eoe->_toSmooth = false;
3137             data.PrepareEdgesToSmoothOnFace( eoe, /*substituteSrcNodes=*/false );
3138           }
3139           if ( eos._shapeID != eof->_shapeID && !eos.HasC1( eof )) 
3140           {
3141             eos._eosC1.push_back( eof );
3142             eof->_toSmooth = false;
3143             data.PrepareEdgesToSmoothOnFace( eof, /*substituteSrcNodes=*/false );
3144             smQueue.push_back( eof->_subMesh );
3145           }
3146         }
3147       }
3148     }
3149     if ( eos._eosC1.empty() )
3150       continue;
3151
3152     // check VERTEXes of C1 FACEs
3153     TopTools_MapIteratorOfMapOfShape vIt( allVV );
3154     for ( ; vIt.More(); vIt.Next() )
3155     {
3156       _EdgesOnShape* eov = data.GetShapeEdges( vIt.Key() );
3157       if ( !eov || eov->_edges.empty() || !eov->_sWOL.IsNull() )
3158         continue;
3159
3160       bool isC1 = true; // check if all adjacent FACEs are in eos._eosC1
3161       PShapeIteratorPtr fIt = helper.GetAncestors( vIt.Key(), *_mesh, TopAbs_FACE );
3162       while ( const TopoDS_Shape* face = fIt->next() )
3163       {
3164         _EdgesOnShape* eof = data.GetShapeEdges( *face );
3165         if ( !eof ) continue; // other solid
3166         isC1 = ( face->IsSame( eos._shape ) || eos.HasC1( eof ));
3167         if ( !isC1 )
3168           break;
3169       }
3170       if ( isC1 )
3171       {
3172         eos._eosC1.push_back( eov );
3173         data.PrepareEdgesToSmoothOnFace( eov, /*substituteSrcNodes=*/false );
3174         c1VV.Add( eov->_shape );
3175       }
3176     }
3177
3178   } // fill _eosC1 of FACEs
3179
3180
3181   // Find C1 EDGEs
3182
3183   vector< pair< _EdgesOnShape*, gp_XYZ > > dirOfEdges;
3184
3185   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check VERTEXes
3186   {
3187     _EdgesOnShape& eov = edgesByGeom[iS];
3188     if ( eov._edges.empty() ||
3189          eov.ShapeType() != TopAbs_VERTEX ||
3190          c1VV.Contains( eov._shape ))
3191       continue;
3192     const TopoDS_Vertex& V = TopoDS::Vertex( eov._shape );
3193
3194     // get directions of surrounding EDGEs
3195     dirOfEdges.clear();
3196     PShapeIteratorPtr fIt = helper.GetAncestors( eov._shape, *_mesh, TopAbs_EDGE );
3197     while ( const TopoDS_Shape* e = fIt->next() )
3198     {
3199       _EdgesOnShape* eoe = data.GetShapeEdges( *e );
3200       if ( !eoe ) continue; // other solid
3201       gp_XYZ eDir = getEdgeDir( TopoDS::Edge( *e ), V );
3202       if ( !Precision::IsInfinite( eDir.X() ))
3203         dirOfEdges.push_back( make_pair( eoe, eDir.Normalized() ));
3204     }
3205
3206     // find EDGEs with C1 directions
3207     for ( size_t i = 0; i < dirOfEdges.size(); ++i )
3208       for ( size_t j = i+1; j < dirOfEdges.size(); ++j )
3209         if ( dirOfEdges[i].first && dirOfEdges[j].first )
3210         {
3211           double dot = dirOfEdges[i].second * dirOfEdges[j].second;
3212           bool isC1 = ( dot < - ( 1. - theMinSmoothCosin ));
3213           if ( isC1 )
3214           {
3215             double maxEdgeLen = 3 * Min( eov._edges[0]->_maxLen, eov._hyp.GetTotalThickness() );
3216             double eLen1 = SMESH_Algo::EdgeLength( TopoDS::Edge( dirOfEdges[i].first->_shape ));
3217             double eLen2 = SMESH_Algo::EdgeLength( TopoDS::Edge( dirOfEdges[j].first->_shape ));
3218             if ( eLen1 < maxEdgeLen ) eov._eosC1.push_back( dirOfEdges[i].first );
3219             if ( eLen2 < maxEdgeLen ) eov._eosC1.push_back( dirOfEdges[j].first );
3220             dirOfEdges[i].first = 0;
3221             dirOfEdges[j].first = 0;
3222           }
3223         }
3224   } // fill _eosC1 of VERTEXes
3225
3226
3227
3228   return ok;
3229 }
3230
3231 //================================================================================
3232 /*!
3233  * \brief initialize data of _EdgesOnShape
3234  */
3235 //================================================================================
3236
3237 void _ViscousBuilder::setShapeData( _EdgesOnShape& eos,
3238                                     SMESH_subMesh* sm,
3239                                     _SolidData&    data )
3240 {
3241   if ( !eos._shape.IsNull() ||
3242        sm->GetSubShape().ShapeType() == TopAbs_WIRE )
3243     return;
3244
3245   SMESH_MesherHelper helper( *_mesh );
3246
3247   eos._subMesh = sm;
3248   eos._shapeID = sm->GetId();
3249   eos._shape   = sm->GetSubShape();
3250   if ( eos.ShapeType() == TopAbs_FACE )
3251     eos._shape.Orientation( helper.GetSubShapeOri( data._solid, eos._shape ));
3252   eos._toSmooth = false;
3253   eos._data = &data;
3254
3255   // set _SWOL
3256   map< TGeomID, TopoDS_Shape >::const_iterator s2s =
3257     data._shrinkShape2Shape.find( eos._shapeID );
3258   if ( s2s != data._shrinkShape2Shape.end() )
3259     eos._sWOL = s2s->second;
3260
3261   eos._isRegularSWOL = true;
3262   if ( eos.SWOLType() == TopAbs_FACE )
3263   {
3264     const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
3265     Handle(ShapeAnalysis_Surface) surface = helper.GetSurface( F );
3266     eos._isRegularSWOL = ( ! surface->HasSingularities( 1e-7 ));
3267   }
3268
3269   // set _hyp
3270   if ( data._hyps.size() == 1 )
3271   {
3272     eos._hyp = data._hyps.back();
3273   }
3274   else
3275   {
3276     // compute average StdMeshers_ViscousLayers parameters
3277     map< TGeomID, const StdMeshers_ViscousLayers* >::iterator f2hyp;
3278     if ( eos.ShapeType() == TopAbs_FACE )
3279     {
3280       if (( f2hyp = data._face2hyp.find( eos._shapeID )) != data._face2hyp.end() )
3281         eos._hyp = f2hyp->second;
3282     }
3283     else
3284     {
3285       PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
3286       while ( const TopoDS_Shape* face = fIt->next() )
3287       {
3288         TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
3289         if (( f2hyp = data._face2hyp.find( faceID )) != data._face2hyp.end() )
3290           eos._hyp.Add( f2hyp->second );
3291       }
3292     }
3293   }
3294
3295   // set _faceNormals
3296   if ( ! eos._hyp.UseSurfaceNormal() )
3297   {
3298     if ( eos.ShapeType() == TopAbs_FACE ) // get normals to elements on a FACE
3299     {
3300       SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3301       eos._faceNormals.resize( smDS->NbElements() );
3302
3303       SMDS_ElemIteratorPtr eIt = smDS->GetElements();
3304       for ( int iF = 0; eIt->more(); ++iF )
3305       {
3306         const SMDS_MeshElement* face = eIt->next();
3307         if ( !SMESH_MeshAlgos::FaceNormal( face, eos._faceNormals[iF], /*normalized=*/true ))
3308           eos._faceNormals[iF].SetCoord( 0,0,0 );
3309       }
3310
3311       if ( !helper.IsReversedSubMesh( TopoDS::Face( eos._shape )))
3312         for ( size_t iF = 0; iF < eos._faceNormals.size(); ++iF )
3313           eos._faceNormals[iF].Reverse();
3314     }
3315     else // find EOS of adjacent FACEs
3316     {
3317       PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
3318       while ( const TopoDS_Shape* face = fIt->next() )
3319       {
3320         TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
3321         eos._faceEOS.push_back( & data._edgesOnShape[ faceID ]);
3322         if ( eos._faceEOS.back()->_shape.IsNull() )
3323           // avoid using uninitialised _shapeID in GetNormal()
3324           eos._faceEOS.back()->_shapeID = faceID;
3325       }
3326     }
3327   }
3328 }
3329
3330 //================================================================================
3331 /*!
3332  * \brief Returns normal of a face
3333  */
3334 //================================================================================
3335
3336 bool _EdgesOnShape::GetNormal( const SMDS_MeshElement* face, gp_Vec& norm )
3337 {
3338   bool ok = false;
3339   const _EdgesOnShape* eos = 0;
3340
3341   if ( face->getshapeId() == _shapeID )
3342   {
3343     eos = this;
3344   }
3345   else
3346   {
3347     for ( size_t iF = 0; iF < _faceEOS.size() && !eos; ++iF )
3348       if ( face->getshapeId() == _faceEOS[ iF ]->_shapeID )
3349         eos = _faceEOS[ iF ];
3350   }
3351
3352   if (( eos ) &&
3353       ( ok = ( face->getIdInShape() < (int) eos->_faceNormals.size() )))
3354   {
3355     norm = eos->_faceNormals[ face->getIdInShape() ];
3356   }
3357   else if ( !eos )
3358   {
3359     debugMsg( "_EdgesOnShape::Normal() failed for face "<<face->GetID()
3360               << " on _shape #" << _shapeID );
3361   }
3362   return ok;
3363 }
3364
3365
3366 //================================================================================
3367 /*!
3368  * \brief Set data of _LayerEdge needed for smoothing
3369  */
3370 //================================================================================
3371
3372 bool _ViscousBuilder::setEdgeData(_LayerEdge&         edge,
3373                                   _EdgesOnShape&      eos,
3374                                   SMESH_MesherHelper& helper,
3375                                   _SolidData&         data)
3376 {
3377   const SMDS_MeshNode* node = edge._nodes[0]; // source node
3378
3379   edge._len       = 0;
3380   edge._maxLen    = Precision::Infinite();
3381   edge._minAngle  = 0;
3382   edge._2neibors  = 0;
3383   edge._curvature = 0;
3384   edge._flags     = 0;
3385
3386   // --------------------------
3387   // Compute _normal and _cosin
3388   // --------------------------
3389
3390   edge._cosin     = 0;
3391   edge._lenFactor = 1.;
3392   edge._normal.SetCoord(0,0,0);
3393   _Simplex::GetSimplices( node, edge._simplices, data._ignoreFaceIds, &data );
3394
3395   int totalNbFaces = 0;
3396   TopoDS_Face F;
3397   std::pair< TopoDS_Face, gp_XYZ > face2Norm[20];
3398   gp_Vec geomNorm;
3399   bool normOK = true;
3400
3401   const bool onShrinkShape = !eos._sWOL.IsNull();
3402   const bool useGeometry   = (( eos._hyp.UseSurfaceNormal() ) ||
3403                               ( eos.ShapeType() != TopAbs_FACE /*&& !onShrinkShape*/ ));
3404
3405   // get geom FACEs the node lies on
3406   //if ( useGeometry )
3407   {
3408     set<TGeomID> faceIds;
3409     if  ( eos.ShapeType() == TopAbs_FACE )
3410     {
3411       faceIds.insert( eos._shapeID );
3412     }
3413     else
3414     {
3415       SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3416       while ( fIt->more() )
3417         faceIds.insert( fIt->next()->getshapeId() );
3418     }
3419     set<TGeomID>::iterator id = faceIds.begin();
3420     for ( ; id != faceIds.end(); ++id )
3421     {
3422       const TopoDS_Shape& s = getMeshDS()->IndexToShape( *id );
3423       if ( s.IsNull() || s.ShapeType() != TopAbs_FACE || data._ignoreFaceIds.count( *id ))
3424         continue;
3425       F = TopoDS::Face( s );
3426       face2Norm[ totalNbFaces ].first = F;
3427       totalNbFaces++;
3428     }
3429   }
3430
3431   // find _normal
3432   if ( useGeometry )
3433   {
3434     bool fromVonF = ( eos.ShapeType() == TopAbs_VERTEX &&
3435                       eos.SWOLType()  == TopAbs_FACE  &&
3436                       totalNbFaces > 1 );
3437
3438     if ( onShrinkShape && !fromVonF ) // one of faces the node is on has no layers
3439     {
3440       if ( eos.SWOLType() == TopAbs_EDGE )
3441       {
3442         // inflate from VERTEX along EDGE
3443         edge._normal = getEdgeDir( TopoDS::Edge( eos._sWOL ), TopoDS::Vertex( eos._shape ));
3444       }
3445       else if ( eos.ShapeType() == TopAbs_VERTEX )
3446       {
3447         // inflate from VERTEX along FACE
3448         edge._normal = getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Vertex( eos._shape ),
3449                                    node, helper, normOK, &edge._cosin);
3450       }
3451       else
3452       {
3453         // inflate from EDGE along FACE
3454         edge._normal = getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Edge( eos._shape ),
3455                                    node, helper, normOK);
3456       }
3457     }
3458     else // layers are on all FACEs of SOLID the node is on (or fromVonF)
3459     {
3460       if ( fromVonF )
3461         face2Norm[ totalNbFaces++ ].first = TopoDS::Face( eos._sWOL );
3462
3463       int nbOkNorms = 0;
3464       for ( int iF = totalNbFaces - 1; iF >= 0; --iF )
3465       {
3466         F = face2Norm[ iF ].first;
3467         geomNorm = getFaceNormal( node, F, helper, normOK );
3468         if ( !normOK ) continue;
3469         nbOkNorms++;
3470
3471         if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3472           geomNorm.Reverse();
3473         face2Norm[ iF ].second = geomNorm.XYZ();
3474         edge._normal += geomNorm.XYZ();
3475       }
3476       if ( nbOkNorms == 0 )
3477         return error(SMESH_Comment("Can't get normal to node ") << node->GetID(), data._index);
3478
3479       if ( totalNbFaces >= 3 )
3480       {
3481         edge._normal = getNormalByOffset( &edge, face2Norm, totalNbFaces, fromVonF );
3482       }
3483
3484       if ( edge._normal.Modulus() < 1e-3 && nbOkNorms > 1 )
3485       {
3486         // opposite normals, re-get normals at shifted positions (IPAL 52426)
3487         edge._normal.SetCoord( 0,0,0 );
3488         for ( int iF = 0; iF < totalNbFaces - fromVonF; ++iF )
3489         {
3490           const TopoDS_Face& F = face2Norm[iF].first;
3491           geomNorm = getFaceNormal( node, F, helper, normOK, /*shiftInside=*/true );
3492           if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3493             geomNorm.Reverse();
3494           if ( normOK )
3495             face2Norm[ iF ].second = geomNorm.XYZ();
3496           edge._normal += face2Norm[ iF ].second;
3497         }
3498       }
3499     }
3500   }
3501   else // !useGeometry - get _normal using surrounding mesh faces
3502   {
3503     edge._normal = getWeigthedNormal( &edge );
3504
3505     // set<TGeomID> faceIds;
3506     //
3507     // SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3508     // while ( fIt->more() )
3509     // {
3510     //   const SMDS_MeshElement* face = fIt->next();
3511     //   if ( eos.GetNormal( face, geomNorm ))
3512     //   {
3513     //     if ( onShrinkShape && !faceIds.insert( face->getshapeId() ).second )
3514     //       continue; // use only one mesh face on FACE
3515     //     edge._normal += geomNorm.XYZ();
3516     //     totalNbFaces++;
3517     //   }
3518     // }
3519   }
3520
3521   // compute _cosin
3522   //if ( eos._hyp.UseSurfaceNormal() )
3523   {
3524     switch ( eos.ShapeType() )
3525     {
3526     case TopAbs_FACE: {
3527       edge._cosin = 0;
3528       break;
3529     }
3530     case TopAbs_EDGE: {
3531       TopoDS_Edge E    = TopoDS::Edge( eos._shape );
3532       gp_Vec inFaceDir = getFaceDir( F, E, node, helper, normOK );
3533       double angle     = inFaceDir.Angle( edge._normal ); // [0,PI]
3534       edge._cosin      = Cos( angle );
3535       break;
3536     }
3537     case TopAbs_VERTEX: {
3538       //if ( eos.SWOLType() != TopAbs_FACE ) // else _cosin is set by getFaceDir()
3539       {
3540         TopoDS_Vertex V  = TopoDS::Vertex( eos._shape );
3541         gp_Vec inFaceDir = getFaceDir( F, V, node, helper, normOK );
3542         double angle     = inFaceDir.Angle( edge._normal ); // [0,PI]
3543         edge._cosin      = Cos( angle );
3544         if ( totalNbFaces > 2 || helper.IsSeamShape( node->getshapeId() ))
3545           for ( int iF = totalNbFaces-2; iF >=0; --iF )
3546           {
3547             F = face2Norm[ iF ].first;
3548             inFaceDir = getFaceDir( F, V, node, helper, normOK=true );
3549             if ( normOK ) {
3550               double angle = inFaceDir.Angle( edge._normal );
3551               double cosin = Cos( angle );
3552               if ( Abs( cosin ) > Abs( edge._cosin ))
3553                 edge._cosin = cosin;
3554             }
3555           }
3556       }
3557       break;
3558     }
3559     default:
3560       return error(SMESH_Comment("Invalid shape position of node ")<<node, data._index);
3561     }
3562   }
3563
3564   double normSize = edge._normal.SquareModulus();
3565   if ( normSize < numeric_limits<double>::min() )
3566     return error(SMESH_Comment("Bad normal at node ")<< node->GetID(), data._index );
3567
3568   edge._normal /= sqrt( normSize );
3569
3570   if ( edge.Is( _LayerEdge::MULTI_NORMAL ) && edge._nodes.size() == 2 )
3571   {
3572     getMeshDS()->RemoveFreeNode( edge._nodes.back(), 0, /*fromGroups=*/false );
3573     edge._nodes.resize( 1 );
3574     edge._normal.SetCoord( 0,0,0 );
3575     edge._maxLen = 0;
3576   }
3577
3578   // Set the rest data
3579   // --------------------
3580
3581   edge.SetCosin( edge._cosin ); // to update edge._lenFactor
3582
3583   if ( onShrinkShape )
3584   {
3585     const SMDS_MeshNode* tgtNode = edge._nodes.back();
3586     if ( SMESHDS_SubMesh* sm = getMeshDS()->MeshElements( data._solid ))
3587       sm->RemoveNode( tgtNode , /*isNodeDeleted=*/false );
3588
3589     // set initial position which is parameters on _sWOL in this case
3590     if ( eos.SWOLType() == TopAbs_EDGE )
3591     {
3592       double u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), node, 0, &normOK );
3593       edge._pos.push_back( gp_XYZ( u, 0, 0 ));
3594       if ( edge._nodes.size() > 1 )
3595         getMeshDS()->SetNodeOnEdge( tgtNode, TopoDS::Edge( eos._sWOL ), u );
3596     }
3597     else // eos.SWOLType() == TopAbs_FACE
3598     {
3599       gp_XY uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), node, 0, &normOK );
3600       edge._pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
3601       if ( edge._nodes.size() > 1 )
3602         getMeshDS()->SetNodeOnFace( tgtNode, TopoDS::Face( eos._sWOL ), uv.X(), uv.Y() );
3603     }
3604
3605     if ( edge._nodes.size() > 1 )
3606     {
3607       // check if an angle between a FACE with layers and SWOL is sharp,
3608       // else the edge should not inflate
3609       F.Nullify();
3610       for ( int iF = 0; iF < totalNbFaces  &&  F.IsNull();  ++iF ) // find a FACE with VL
3611         if ( ! helper.IsSubShape( eos._sWOL, face2Norm[iF].first ))
3612           F = face2Norm[iF].first;
3613       if ( !F.IsNull())
3614       {
3615         geomNorm = getFaceNormal( node, F, helper, normOK );
3616         if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3617           geomNorm.Reverse(); // inside the SOLID
3618         if ( geomNorm * edge._normal < -0.001 )
3619         {
3620           getMeshDS()->RemoveFreeNode( tgtNode, 0, /*fromGroups=*/false );
3621           edge._nodes.resize( 1 );
3622         }
3623         else if ( edge._lenFactor > 3 )
3624         {
3625           edge._lenFactor = 2;
3626           edge.Set( _LayerEdge::RISKY_SWOL );
3627         }
3628       }
3629     }
3630   }
3631   else
3632   {
3633     edge._pos.push_back( SMESH_TNodeXYZ( node ));
3634
3635     if ( eos.ShapeType() == TopAbs_FACE )
3636     {
3637       double angle;
3638       for ( size_t i = 0; i < edge._simplices.size(); ++i )
3639       {
3640         edge._simplices[i].IsMinAngleOK( edge._pos.back(), angle );
3641         edge._minAngle = Max( edge._minAngle, angle ); // "angle" is actually cosine
3642       }
3643     }
3644   }
3645
3646   // Set neighbor nodes for a _LayerEdge based on EDGE
3647
3648   if ( eos.ShapeType() == TopAbs_EDGE /*||
3649        ( onShrinkShape && posType == SMDS_TOP_VERTEX && fabs( edge._cosin ) < 1e-10 )*/)
3650   {
3651     edge._2neibors = new _2NearEdges;
3652     // target nodes instead of source ones will be set later
3653   }
3654
3655   return true;
3656 }
3657
3658 //================================================================================
3659 /*!
3660  * \brief Return normal to a FACE at a node
3661  *  \param [in] n - node
3662  *  \param [in] face - FACE
3663  *  \param [in] helper - helper
3664  *  \param [out] isOK - true or false
3665  *  \param [in] shiftInside - to find normal at a position shifted inside the face
3666  *  \return gp_XYZ - normal
3667  */
3668 //================================================================================
3669
3670 gp_XYZ _ViscousBuilder::getFaceNormal(const SMDS_MeshNode* node,
3671                                       const TopoDS_Face&   face,
3672                                       SMESH_MesherHelper&  helper,
3673                                       bool&                isOK,
3674                                       bool                 shiftInside)
3675 {
3676   gp_XY uv;
3677   if ( shiftInside )
3678   {
3679     // get a shifted position
3680     gp_Pnt p = SMESH_TNodeXYZ( node );
3681     gp_XYZ shift( 0,0,0 );
3682     TopoDS_Shape S = helper.GetSubShapeByNode( node, helper.GetMeshDS() );
3683     switch ( S.ShapeType() ) {
3684     case TopAbs_VERTEX:
3685     {
3686       shift = getFaceDir( face, TopoDS::Vertex( S ), node, helper, isOK );
3687       break;
3688     }
3689     case TopAbs_EDGE:
3690     {
3691       shift = getFaceDir( face, TopoDS::Edge( S ), node, helper, isOK );
3692       break;
3693     }
3694     default:
3695       isOK = false;
3696     }
3697     if ( isOK )
3698       shift.Normalize();
3699     p.Translate( shift * 1e-5 );
3700
3701     TopLoc_Location loc;
3702     GeomAPI_ProjectPointOnSurf& projector = helper.GetProjector( face, loc, 1e-7 );
3703
3704     if ( !loc.IsIdentity() ) p.Transform( loc.Transformation().Inverted() );
3705     
3706     projector.Perform( p );
3707     if ( !projector.IsDone() || projector.NbPoints() < 1 )
3708     {
3709       isOK = false;
3710       return p.XYZ();
3711     }
3712     Quantity_Parameter U,V;
3713     projector.LowerDistanceParameters(U,V);
3714     uv.SetCoord( U,V );
3715   }
3716   else
3717   {
3718     uv = helper.GetNodeUV( face, node, 0, &isOK );
3719   }
3720
3721   gp_Dir normal;
3722   isOK = false;
3723
3724   Handle(Geom_Surface) surface = BRep_Tool::Surface( face );
3725
3726   if ( !shiftInside &&
3727        helper.IsDegenShape( node->getshapeId() ) &&
3728        getFaceNormalAtSingularity( uv, face, helper, normal ))
3729   {
3730     isOK = true;
3731     return normal.XYZ();
3732   }
3733
3734   int pointKind = GeomLib::NormEstim( surface, uv, 1e-5, normal );
3735   enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
3736
3737   if ( pointKind == IMPOSSIBLE &&
3738        node->GetPosition()->GetDim() == 2 ) // node inside the FACE
3739   {
3740     // probably NormEstim() failed due to a too high tolerance
3741     pointKind = GeomLib::NormEstim( surface, uv, 1e-20, normal );
3742     isOK = ( pointKind < IMPOSSIBLE );
3743   }
3744   if ( pointKind < IMPOSSIBLE )
3745   {
3746     if ( pointKind != REGULAR &&
3747          !shiftInside &&
3748          node->GetPosition()->GetDim() < 2 ) // FACE boundary
3749     {
3750       gp_XYZ normShift = getFaceNormal( node, face, helper, isOK, /*shiftInside=*/true );
3751       if ( normShift * normal.XYZ() < 0. )
3752         normal = normShift;
3753     }
3754     isOK = true;
3755   }
3756
3757   if ( !isOK ) // hard singularity, to call with shiftInside=true ?
3758   {
3759     const TGeomID faceID = helper.GetMeshDS()->ShapeToIndex( face );
3760
3761     SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3762     while ( fIt->more() )
3763     {
3764       const SMDS_MeshElement* f = fIt->next();
3765       if ( f->getshapeId() == faceID )
3766       {
3767         isOK = SMESH_MeshAlgos::FaceNormal( f, (gp_XYZ&) normal.XYZ(), /*normalized=*/true );
3768         if ( isOK )
3769         {
3770           TopoDS_Face ff = face;
3771           ff.Orientation( TopAbs_FORWARD );
3772           if ( helper.IsReversedSubMesh( ff ))
3773             normal.Reverse();
3774           break;
3775         }
3776       }
3777     }
3778   }
3779   return normal.XYZ();
3780 }
3781
3782 //================================================================================
3783 /*!
3784  * \brief Try to get normal at a singularity of a surface basing on it's nature
3785  */
3786 //================================================================================
3787
3788 bool _ViscousBuilder::getFaceNormalAtSingularity( const gp_XY&        uv,
3789                                                   const TopoDS_Face&  face,
3790                                                   SMESH_MesherHelper& helper,
3791                                                   gp_Dir&             normal )
3792 {
3793   BRepAdaptor_Surface surface( face );
3794   gp_Dir axis;
3795   if ( !getRovolutionAxis( surface, axis ))
3796     return false;
3797
3798   double f,l, d, du, dv;
3799   f = surface.FirstUParameter();
3800   l = surface.LastUParameter();
3801   d = ( uv.X() - f ) / ( l - f );
3802   du = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
3803   f = surface.FirstVParameter();
3804   l = surface.LastVParameter();
3805   d = ( uv.Y() - f ) / ( l - f );
3806   dv = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
3807
3808   gp_Dir refDir;
3809   gp_Pnt2d testUV = uv;
3810   enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
3811   double tol = 1e-5;
3812   Handle(Geom_Surface) geomsurf = surface.Surface().Surface();
3813   for ( int iLoop = 0; true ; ++iLoop )
3814   {
3815     testUV.SetCoord( testUV.X() + du, testUV.Y() + dv );
3816     if ( GeomLib::NormEstim( geomsurf, testUV, tol, refDir ) == REGULAR )
3817       break;
3818     if ( iLoop > 20 )
3819       return false;
3820     tol /= 10.;
3821   }
3822
3823   if ( axis * refDir < 0. )
3824     axis.Reverse();
3825
3826   normal = axis;
3827
3828   return true;
3829 }
3830
3831 //================================================================================
3832 /*!
3833  * \brief Return a normal at a node weighted with angles taken by faces
3834  */
3835 //================================================================================
3836
3837 gp_XYZ _ViscousBuilder::getWeigthedNormal( const _LayerEdge* edge )
3838 {
3839   const SMDS_MeshNode* n = edge->_nodes[0];
3840
3841   gp_XYZ resNorm(0,0,0);
3842   SMESH_TNodeXYZ p0( n ), pP, pN;
3843   for ( size_t i = 0; i < edge->_simplices.size(); ++i )
3844   {
3845     pP.Set( edge->_simplices[i]._nPrev );
3846     pN.Set( edge->_simplices[i]._nNext );
3847     gp_Vec v0P( p0, pP ), v0N( p0, pN ), vPN( pP, pN ), norm = v0P ^ v0N;
3848     double l0P = v0P.SquareMagnitude();
3849     double l0N = v0N.SquareMagnitude();
3850     double lPN = vPN.SquareMagnitude();
3851     if ( l0P < std::numeric_limits<double>::min() ||
3852          l0N < std::numeric_limits<double>::min() ||
3853          lPN < std::numeric_limits<double>::min() )
3854       continue;
3855     double lNorm = norm.SquareMagnitude();
3856     double  sin2 = lNorm / l0P / l0N;
3857     double angle = ACos(( v0P * v0N ) / Sqrt( l0P ) / Sqrt( l0N ));
3858
3859     double weight = sin2 * angle / lPN;
3860     resNorm += weight * norm.XYZ() / Sqrt( lNorm );
3861   }
3862
3863   return resNorm;
3864 }
3865
3866 //================================================================================
3867 /*!
3868  * \brief Return a normal at a node by getting a common point of offset planes
3869  *        defined by the FACE normals
3870  */
3871 //================================================================================
3872
3873 gp_XYZ _ViscousBuilder::getNormalByOffset( _LayerEdge*                      edge,
3874                                            std::pair< TopoDS_Face, gp_XYZ > f2Normal[],
3875                                            int                              nbFaces,
3876                                            bool                             lastNoOffset)
3877 {
3878   SMESH_TNodeXYZ p0 = edge->_nodes[0];
3879
3880   gp_XYZ resNorm(0,0,0);
3881   TopoDS_Shape V = SMESH_MesherHelper::GetSubShapeByNode( p0._node, getMeshDS() );
3882   if ( V.ShapeType() != TopAbs_VERTEX || nbFaces < 3 )
3883   {
3884     for ( int i = 0; i < nbFaces; ++i )
3885       resNorm += f2Normal[i].second;
3886     return resNorm;
3887   }
3888
3889   // prepare _OffsetPlane's
3890   vector< _OffsetPlane > pln( nbFaces );
3891   for ( int i = 0; i < nbFaces - lastNoOffset; ++i )
3892   {
3893     pln[i]._faceIndex = i;
3894     pln[i]._plane = gp_Pln( p0 + f2Normal[i].second, f2Normal[i].second );
3895   }
3896   if ( lastNoOffset )
3897   {
3898     pln[ nbFaces - 1 ]._faceIndex = nbFaces - 1;
3899     pln[ nbFaces - 1 ]._plane = gp_Pln( p0, f2Normal[ nbFaces - 1 ].second );
3900   }
3901
3902   // intersect neighboring OffsetPlane's
3903   PShapeIteratorPtr edgeIt = SMESH_MesherHelper::GetAncestors( V, *_mesh, TopAbs_EDGE );
3904   while ( const TopoDS_Shape* edge = edgeIt->next() )
3905   {
3906     int f1 = -1, f2 = -1;
3907     for ( int i = 0; i < nbFaces &&  f2 < 0;  ++i )
3908       if ( SMESH_MesherHelper::IsSubShape( *edge, f2Normal[i].first ))
3909         (( f1 < 0 ) ? f1 : f2 ) = i;
3910
3911     if ( f2 >= 0 )
3912       pln[ f1 ].ComputeIntersectionLine( pln[ f2 ], TopoDS::Edge( *edge ), TopoDS::Vertex( V ));
3913   }
3914
3915   // get a common point
3916   gp_XYZ commonPnt( 0, 0, 0 );
3917   int nbPoints = 0;
3918   bool isPointFound;
3919   for ( int i = 0; i < nbFaces; ++i )
3920   {
3921     commonPnt += pln[ i ].GetCommonPoint( isPointFound, TopoDS::Vertex( V ));
3922     nbPoints  += isPointFound;
3923   }
3924   gp_XYZ wgtNorm = getWeigthedNormal( edge );
3925   if ( nbPoints == 0 )
3926     return wgtNorm;
3927
3928   commonPnt /= nbPoints;
3929   resNorm = commonPnt - p0;
3930   if ( lastNoOffset )
3931     return resNorm;
3932
3933   // choose the best among resNorm and wgtNorm
3934   resNorm.Normalize();
3935   wgtNorm.Normalize();
3936   double resMinDot = std::numeric_limits<double>::max();
3937   double wgtMinDot = std::numeric_limits<double>::max();
3938   for ( int i = 0; i < nbFaces - lastNoOffset; ++i )
3939   {
3940     resMinDot = Min( resMinDot, resNorm * f2Normal[i].second );
3941     wgtMinDot = Min( wgtMinDot, wgtNorm * f2Normal[i].second );
3942   }
3943
3944   if ( Max( resMinDot, wgtMinDot ) < theMinSmoothCosin )
3945   {
3946     edge->Set( _LayerEdge::MULTI_NORMAL );
3947   }
3948
3949   return ( resMinDot > wgtMinDot ) ? resNorm : wgtNorm;
3950 }
3951
3952 //================================================================================
3953 /*!
3954  * \brief Compute line of intersection of 2 planes
3955  */
3956 //================================================================================
3957
3958 void _OffsetPlane::ComputeIntersectionLine( _OffsetPlane&        pln,
3959                                             const TopoDS_Edge&   E,
3960                                             const TopoDS_Vertex& V )
3961 {
3962   int iNext = bool( _faceIndexNext[0] >= 0 );
3963   _faceIndexNext[ iNext ] = pln._faceIndex;
3964
3965   gp_XYZ n1 = _plane.Axis().Direction().XYZ();
3966   gp_XYZ n2 = pln._plane.Axis().Direction().XYZ();
3967
3968   gp_XYZ lineDir = n1 ^ n2;
3969
3970   double x = Abs( lineDir.X() );
3971   double y = Abs( lineDir.Y() );
3972   double z = Abs( lineDir.Z() );
3973
3974   int cooMax; // max coordinate
3975   if (x > y) {
3976     if (x > z) cooMax = 1;
3977     else       cooMax = 3;
3978   }
3979   else {
3980     if (y > z) cooMax = 2;
3981     else       cooMax = 3;
3982   }
3983
3984   gp_Pnt linePos;
3985   if ( Abs( lineDir.Coord( cooMax )) < 0.05 )
3986   {
3987     // parallel planes - intersection is an offset of the common EDGE
3988     gp_Pnt p = BRep_Tool::Pnt( V );
3989     linePos  = 0.5 * (( p.XYZ() + n1 ) + ( p.XYZ() + n2 ));
3990     lineDir  = getEdgeDir( E, V );
3991   }
3992   else
3993   {
3994     // the constants in the 2 plane equations
3995     double d1 = - ( _plane.Axis().Direction().XYZ()     * _plane.Location().XYZ() );
3996     double d2 = - ( pln._plane.Axis().Direction().XYZ() * pln._plane.Location().XYZ() );
3997
3998     switch ( cooMax ) {
3999     case 1:
4000       linePos.SetX(  0 );
4001       linePos.SetY(( d2*n1.Z() - d1*n2.Z()) / lineDir.X() );
4002       linePos.SetZ(( d1*n2.Y() - d2*n1.Y()) / lineDir.X() );
4003       break;
4004     case 2:
4005       linePos.SetX(( d1*n2.Z() - d2*n1.Z()) / lineDir.Y() );
4006       linePos.SetY(  0 );
4007       linePos.SetZ(( d2*n1.X() - d1*n2.X()) / lineDir.Y() );
4008       break;
4009     case 3:
4010       linePos.SetX(( d2*n1.Y() - d1*n2.Y()) / lineDir.Z() );
4011       linePos.SetY(( d1*n2.X() - d2*n1.X()) / lineDir.Z() );
4012       linePos.SetZ(  0 );
4013     }
4014   }
4015   gp_Lin& line = _lines[ iNext ];
4016   line.SetDirection( lineDir );
4017   line.SetLocation ( linePos );
4018
4019   _isLineOK[ iNext ] = true;
4020
4021
4022   iNext = bool( pln._faceIndexNext[0] >= 0 );
4023   pln._lines        [ iNext ] = line;
4024   pln._faceIndexNext[ iNext ] = this->_faceIndex;
4025   pln._isLineOK     [ iNext ] = true;
4026 }
4027
4028 //================================================================================
4029 /*!
4030  * \brief Computes intersection point of two _lines
4031  */
4032 //================================================================================
4033
4034 gp_XYZ _OffsetPlane::GetCommonPoint(bool&                 isFound,
4035                                     const TopoDS_Vertex & V) const
4036 {
4037   gp_XYZ p( 0,0,0 );
4038   isFound = false;
4039
4040   if ( NbLines() == 2 )
4041   {
4042     gp_Vec lPerp0 = _lines[0].Direction().XYZ() ^ _plane.Axis().Direction().XYZ();
4043     double  dot01 = lPerp0 * _lines[1].Direction().XYZ();
4044     if ( Abs( dot01 ) > 0.05 )
4045     {
4046       gp_Vec l0l1 = _lines[1].Location().XYZ() - _lines[0].Location().XYZ();
4047       double   u1 = - ( lPerp0 * l0l1 ) / dot01;
4048       p = ( _lines[1].Location().XYZ() + _lines[1].Direction().XYZ() * u1 );
4049       isFound = true;
4050     }
4051     else
4052     {
4053       gp_Pnt  pV ( BRep_Tool::Pnt( V ));
4054       gp_Vec  lv0( _lines[0].Location(), pV    ),  lv1(_lines[1].Location(), pV     );
4055       double dot0( lv0 * _lines[0].Direction() ), dot1( lv1 * _lines[1].Direction() );
4056       p += 0.5 * ( _lines[0].Location().XYZ() + _lines[0].Direction().XYZ() * dot0 );
4057       p += 0.5 * ( _lines[1].Location().XYZ() + _lines[1].Direction().XYZ() * dot1 );
4058       isFound = true;
4059     }
4060   }
4061
4062   return p;
4063 }
4064
4065 //================================================================================
4066 /*!
4067  * \brief Find 2 neigbor nodes of a node on EDGE
4068  */
4069 //================================================================================
4070
4071 bool _ViscousBuilder::findNeiborsOnEdge(const _LayerEdge*     edge,
4072                                         const SMDS_MeshNode*& n1,
4073                                         const SMDS_MeshNode*& n2,
4074                                         _EdgesOnShape&        eos,
4075                                         _SolidData&           data)
4076 {
4077   const SMDS_MeshNode* node = edge->_nodes[0];
4078   const int        shapeInd = eos._shapeID;
4079   SMESHDS_SubMesh*   edgeSM = 0;
4080   if ( eos.ShapeType() == TopAbs_EDGE )
4081   {
4082     edgeSM = eos._subMesh->GetSubMeshDS();
4083     if ( !edgeSM || edgeSM->NbElements() == 0 )
4084       return error(SMESH_Comment("Not meshed EDGE ") << shapeInd, data._index);
4085   }
4086   int iN = 0;
4087   n2 = 0;
4088   SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Edge);
4089   while ( eIt->more() && !n2 )
4090   {
4091     const SMDS_MeshElement* e = eIt->next();
4092     const SMDS_MeshNode*   nNeibor = e->GetNode( 0 );
4093     if ( nNeibor == node ) nNeibor = e->GetNode( 1 );
4094     if ( edgeSM )
4095     {
4096       if (!edgeSM->Contains(e)) continue;
4097     }
4098     else
4099     {
4100       TopoDS_Shape s = SMESH_MesherHelper::GetSubShapeByNode( nNeibor, getMeshDS() );
4101       if ( !SMESH_MesherHelper::IsSubShape( s, eos._sWOL )) continue;
4102     }
4103     ( iN++ ? n2 : n1 ) = nNeibor;
4104   }
4105   if ( !n2 )
4106     return error(SMESH_Comment("Wrongly meshed EDGE ") << shapeInd, data._index);
4107   return true;
4108 }
4109
4110 //================================================================================
4111 /*!
4112  * \brief Set _curvature and _2neibors->_plnNorm by 2 neigbor nodes residing the same EDGE
4113  */
4114 //================================================================================
4115
4116 void _LayerEdge::SetDataByNeighbors( const SMDS_MeshNode* n1,
4117                                      const SMDS_MeshNode* n2,
4118                                      const _EdgesOnShape& eos,
4119                                      SMESH_MesherHelper&  helper)
4120 {
4121   if ( eos.ShapeType() != TopAbs_EDGE )
4122     return;
4123
4124   gp_XYZ  pos = SMESH_TNodeXYZ( _nodes[0] );
4125   gp_XYZ vec1 = pos - SMESH_TNodeXYZ( n1 );
4126   gp_XYZ vec2 = pos - SMESH_TNodeXYZ( n2 );
4127
4128   // Set _curvature
4129
4130   double      sumLen = vec1.Modulus() + vec2.Modulus();
4131   _2neibors->_wgt[0] = 1 - vec1.Modulus() / sumLen;
4132   _2neibors->_wgt[1] = 1 - vec2.Modulus() / sumLen;
4133   double avgNormProj = 0.5 * ( _normal * vec1 + _normal * vec2 );
4134   double      avgLen = 0.5 * ( vec1.Modulus() + vec2.Modulus() );
4135   if ( _curvature ) delete _curvature;
4136   _curvature = _Curvature::New( avgNormProj, avgLen );
4137   // if ( _curvature )
4138   //   debugMsg( _nodes[0]->GetID()
4139   //             << " CURV r,k: " << _curvature->_r<<","<<_curvature->_k
4140   //             << " proj = "<<avgNormProj<< " len = " << avgLen << "| lenDelta(0) = "
4141   //             << _curvature->lenDelta(0) );
4142
4143   // Set _plnNorm
4144
4145   if ( eos._sWOL.IsNull() )
4146   {
4147     TopoDS_Edge  E = TopoDS::Edge( eos._shape );
4148     // if ( SMESH_Algo::isDegenerated( E ))
4149     //   return;
4150     gp_XYZ dirE    = getEdgeDir( E, _nodes[0], helper );
4151     gp_XYZ plnNorm = dirE ^ _normal;
4152     double proj0   = plnNorm * vec1;
4153     double proj1   = plnNorm * vec2;
4154     if ( fabs( proj0 ) > 1e-10 || fabs( proj1 ) > 1e-10 )
4155     {
4156       if ( _2neibors->_plnNorm ) delete _2neibors->_plnNorm;
4157       _2neibors->_plnNorm = new gp_XYZ( plnNorm.Normalized() );
4158     }
4159   }
4160 }
4161
4162 //================================================================================
4163 /*!
4164  * \brief Copy data from a _LayerEdge of other SOLID and based on the same node;
4165  * this and the other _LayerEdge are inflated along a FACE or an EDGE
4166  */
4167 //================================================================================
4168
4169 gp_XYZ _LayerEdge::Copy( _LayerEdge&         other,
4170                          _EdgesOnShape&      eos,
4171                          SMESH_MesherHelper& helper )
4172 {
4173   _nodes     = other._nodes;
4174   _normal    = other._normal;
4175   _len       = 0;
4176   _lenFactor = other._lenFactor;
4177   _cosin     = other._cosin;
4178   _2neibors  = other._2neibors;
4179   _curvature = 0; std::swap( _curvature, other._curvature );
4180   _2neibors  = 0; std::swap( _2neibors,  other._2neibors );
4181
4182   gp_XYZ lastPos( 0,0,0 );
4183   if ( eos.SWOLType() == TopAbs_EDGE )
4184   {
4185     double u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), _nodes[0] );
4186     _pos.push_back( gp_XYZ( u, 0, 0));
4187
4188     u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), _nodes.back() );
4189     lastPos.SetX( u );
4190   }
4191   else // TopAbs_FACE
4192   {
4193     gp_XY uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), _nodes[0]);
4194     _pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
4195
4196     uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), _nodes.back() );
4197     lastPos.SetX( uv.X() );
4198     lastPos.SetY( uv.Y() );
4199   }
4200   return lastPos;
4201 }
4202
4203 //================================================================================
4204 /*!
4205  * \brief Set _cosin and _lenFactor
4206  */
4207 //================================================================================
4208
4209 void _LayerEdge::SetCosin( double cosin )
4210 {
4211   _cosin = cosin;
4212   cosin = Abs( _cosin );
4213   //_lenFactor = ( cosin < 1.-1e-12 ) ?  Min( 2., 1./sqrt(1-cosin*cosin )) : 1.0;
4214   _lenFactor = ( cosin < 1.-1e-12 ) ?  1./sqrt(1-cosin*cosin ) : 1.0;
4215 }
4216
4217 //================================================================================
4218 /*!
4219  * \brief Check if another _LayerEdge is a neighbor on EDGE
4220  */
4221 //================================================================================
4222
4223 bool _LayerEdge::IsNeiborOnEdge( const _LayerEdge* edge ) const
4224 {
4225   return (( this->_2neibors && this->_2neibors->include( edge )) ||
4226           ( edge->_2neibors && edge->_2neibors->include( this )));
4227 }
4228
4229 //================================================================================
4230 /*!
4231  * \brief Fills a vector<_Simplex > 
4232  */
4233 //================================================================================
4234
4235 void _Simplex::GetSimplices( const SMDS_MeshNode* node,
4236                              vector<_Simplex>&    simplices,
4237                              const set<TGeomID>&  ingnoreShapes,
4238                              const _SolidData*    dataToCheckOri,
4239                              const bool           toSort)
4240 {
4241   simplices.clear();
4242   SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
4243   while ( fIt->more() )
4244   {
4245     const SMDS_MeshElement* f = fIt->next();
4246     const TGeomID    shapeInd = f->getshapeId();
4247     if ( ingnoreShapes.count( shapeInd )) continue;
4248     const int nbNodes = f->NbCornerNodes();
4249     const int  srcInd = f->GetNodeIndex( node );
4250     const SMDS_MeshNode* nPrev = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd-1, nbNodes ));
4251     const SMDS_MeshNode* nNext = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+1, nbNodes ));
4252     const SMDS_MeshNode* nOpp  = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+2, nbNodes ));
4253     if ( dataToCheckOri && dataToCheckOri->_reversedFaceIds.count( shapeInd ))
4254       std::swap( nPrev, nNext );
4255     simplices.push_back( _Simplex( nPrev, nNext, ( nbNodes == 3 ? 0 : nOpp )));
4256   }
4257
4258   if ( toSort )
4259     SortSimplices( simplices );
4260 }
4261
4262 //================================================================================
4263 /*!
4264  * \brief Set neighbor simplices side by side
4265  */
4266 //================================================================================
4267
4268 void _Simplex::SortSimplices(vector<_Simplex>& simplices)
4269 {
4270   vector<_Simplex> sortedSimplices( simplices.size() );
4271   sortedSimplices[0] = simplices[0];
4272   size_t nbFound = 0;
4273   for ( size_t i = 1; i < simplices.size(); ++i )
4274   {
4275     for ( size_t j = 1; j < simplices.size(); ++j )
4276       if ( sortedSimplices[i-1]._nNext == simplices[j]._nPrev )
4277       {
4278         sortedSimplices[i] = simplices[j];
4279         nbFound++;
4280         break;
4281       }
4282   }
4283   if ( nbFound == simplices.size() - 1 )
4284     simplices.swap( sortedSimplices );
4285 }
4286
4287 //================================================================================
4288 /*!
4289  * \brief DEBUG. Create groups contating temorary data of _LayerEdge's
4290  */
4291 //================================================================================
4292
4293 void _ViscousBuilder::makeGroupOfLE()
4294 {
4295 #ifdef _DEBUG_
4296   for ( size_t i = 0 ; i < _sdVec.size(); ++i )
4297   {
4298     if ( _sdVec[i]._n2eMap.empty() ) continue;
4299
4300     dumpFunction( SMESH_Comment("make_LayerEdge_") << i );
4301     TNode2Edge::iterator n2e;
4302     for ( n2e = _sdVec[i]._n2eMap.begin(); n2e != _sdVec[i]._n2eMap.end(); ++n2e )
4303     {
4304       _LayerEdge* le = n2e->second;
4305       // for ( size_t iN = 1; iN < le->_nodes.size(); ++iN )
4306       //   dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[iN-1]->GetID()
4307       //           << ", " << le->_nodes[iN]->GetID() <<"])");
4308       if ( le ) {
4309         dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[0]->GetID()
4310                 << ", " << le->_nodes.back()->GetID() <<"]) # " << le->_flags );
4311       }
4312     }
4313     dumpFunctionEnd();
4314
4315     dumpFunction( SMESH_Comment("makeNormals") << i );
4316     for ( n2e = _sdVec[i]._n2eMap.begin(); n2e != _sdVec[i]._n2eMap.end(); ++n2e )
4317     {
4318       _LayerEdge* edge = n2e->second;
4319       SMESH_TNodeXYZ nXYZ( edge->_nodes[0] );
4320       nXYZ += edge->_normal * _sdVec[i]._stepSize;
4321       dumpCmd(SMESH_Comment("mesh.AddEdge([ ") << edge->_nodes[0]->GetID()
4322               << ", mesh.AddNode( "<< nXYZ.X()<<","<< nXYZ.Y()<<","<< nXYZ.Z()<<")])");
4323     }
4324     dumpFunctionEnd();
4325
4326     dumpFunction( SMESH_Comment("makeTmpFaces_") << i );
4327     dumpCmd( "faceId1 = mesh.NbElements()" );
4328     TopExp_Explorer fExp( _sdVec[i]._solid, TopAbs_FACE );
4329     for ( ; fExp.More(); fExp.Next() )
4330     {
4331       if ( const SMESHDS_SubMesh* sm = _sdVec[i]._proxyMesh->GetProxySubMesh( fExp.Current() ))
4332       {
4333         if ( sm->NbElements() == 0 ) continue;
4334         SMDS_ElemIteratorPtr fIt = sm->GetElements();
4335         while ( fIt->more())
4336         {
4337           const SMDS_MeshElement* e = fIt->next();
4338           SMESH_Comment cmd("mesh.AddFace([");
4339           for ( int j = 0; j < e->NbCornerNodes(); ++j )
4340             cmd << e->GetNode(j)->GetID() << (j+1 < e->NbCornerNodes() ? ",": "])");
4341           dumpCmd( cmd );
4342         }
4343       }
4344     }
4345     dumpCmd( "faceId2 = mesh.NbElements()" );
4346     dumpCmd( SMESH_Comment( "mesh.MakeGroup( 'tmpFaces_" ) << i << "',"
4347              << "SMESH.FACE, SMESH.FT_RangeOfIds,'=',"
4348              << "'%s-%s' % (faceId1+1, faceId2))");
4349     dumpFunctionEnd();
4350   }
4351 #endif
4352 }
4353
4354 //================================================================================
4355 /*!
4356  * \brief Find maximal _LayerEdge length (layer thickness) limited by geometry
4357  */
4358 //================================================================================
4359
4360 void _ViscousBuilder::computeGeomSize( _SolidData& data )
4361 {
4362   data._geomSize = Precision::Infinite();
4363   double intersecDist;
4364   const SMDS_MeshElement* face;
4365   SMESH_MesherHelper helper( *_mesh );
4366
4367   SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
4368     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
4369                                            data._proxyMesh->GetFaces( data._solid )));
4370
4371   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4372   {
4373     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4374     if ( eos._edges.empty() )
4375       continue;
4376     // get neighbor faces intersection with which should not be considered since
4377     // collisions are avoided by means of smoothing
4378     set< TGeomID > neighborFaces;
4379     if ( eos._hyp.ToSmooth() )
4380     {
4381       SMESH_subMeshIteratorPtr subIt =
4382         eos._subMesh->getDependsOnIterator(/*includeSelf=*/eos.ShapeType() != TopAbs_FACE );
4383       while ( subIt->more() )
4384       {
4385         SMESH_subMesh* sm = subIt->next();
4386         PShapeIteratorPtr fIt = helper.GetAncestors( sm->GetSubShape(), *_mesh, TopAbs_FACE );
4387         while ( const TopoDS_Shape* face = fIt->next() )
4388           neighborFaces.insert( getMeshDS()->ShapeToIndex( *face ));
4389       }
4390     }
4391     // find intersections
4392     double thinkness = eos._hyp.GetTotalThickness();
4393     for ( size_t i = 0; i < eos._edges.size(); ++i )
4394     {
4395       if ( eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
4396       eos._edges[i]->_maxLen = thinkness;
4397       eos._edges[i]->FindIntersection( *searcher, intersecDist, data._epsilon, eos, &face );
4398       if ( intersecDist > 0 && face )
4399       {
4400         data._geomSize = Min( data._geomSize, intersecDist );
4401         if ( !neighborFaces.count( face->getshapeId() ))
4402           eos._edges[i]->_maxLen = Min( thinkness, intersecDist / ( face->GetID() < 0 ? 3. : 2. ));
4403       }
4404     }
4405   }
4406 }
4407
4408 //================================================================================
4409 /*!
4410  * \brief Increase length of _LayerEdge's to reach the required thickness of layers
4411  */
4412 //================================================================================
4413
4414 bool _ViscousBuilder::inflate(_SolidData& data)
4415 {
4416   SMESH_MesherHelper helper( *_mesh );
4417
4418   // Limit inflation step size by geometry size found by itersecting
4419   // normals of _LayerEdge's with mesh faces
4420   if ( data._stepSize > 0.3 * data._geomSize )
4421     limitStepSize( data, 0.3 * data._geomSize );
4422
4423   const double tgtThick = data._maxThickness;
4424   if ( data._stepSize > data._minThickness )
4425     limitStepSize( data, data._minThickness );
4426
4427   if ( data._stepSize < 1. )
4428     data._epsilon = data._stepSize * 1e-7;
4429
4430   debugMsg( "-- geomSize = " << data._geomSize << ", stepSize = " << data._stepSize );
4431
4432   findCollisionEdges( data, helper );
4433
4434   limitMaxLenByCurvature( data, helper );
4435
4436   // limit length of _LayerEdge's around MULTI_NORMAL _LayerEdge's
4437   for ( size_t i = 0; i < data._edgesOnShape.size(); ++i )
4438     if ( data._edgesOnShape[i].ShapeType() == TopAbs_VERTEX &&
4439          data._edgesOnShape[i]._edges.size() > 0 &&
4440          data._edgesOnShape[i]._edges[0]->Is( _LayerEdge::MULTI_NORMAL ))
4441     {
4442       data._edgesOnShape[i]._edges[0]->Unset( _LayerEdge::BLOCKED );
4443       data._edgesOnShape[i]._edges[0]->Block( data );
4444     }
4445
4446   const double safeFactor = ( 2*data._maxThickness < data._geomSize ) ? 1 : theThickToIntersection;
4447
4448   double avgThick = 0, curThick = 0, distToIntersection = Precision::Infinite();
4449   int nbSteps = 0, nbRepeats = 0;
4450   while ( avgThick < 0.99 )
4451   {
4452     // new target length
4453     double prevThick = curThick;
4454     curThick += data._stepSize;
4455     if ( curThick > tgtThick )
4456     {
4457       curThick = tgtThick + tgtThick*( 1.-avgThick ) * nbRepeats;
4458       nbRepeats++;
4459     }
4460
4461     double stepSize = curThick - prevThick;
4462     updateNormalsOfSmoothed( data, helper, nbSteps, stepSize ); // to ease smoothing
4463
4464     // Elongate _LayerEdge's
4465     dumpFunction(SMESH_Comment("inflate")<<data._index<<"_step"<<nbSteps); // debug
4466     for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4467     {
4468       _EdgesOnShape& eos = data._edgesOnShape[iS];
4469       if ( eos._edges.empty() ) continue;
4470
4471       const double shapeCurThick = Min( curThick, eos._hyp.GetTotalThickness() );
4472       for ( size_t i = 0; i < eos._edges.size(); ++i )
4473       {
4474         eos._edges[i]->SetNewLength( shapeCurThick, eos, helper );
4475       }
4476     }
4477     dumpFunctionEnd();
4478
4479     if ( !updateNormals( data, helper, nbSteps, stepSize )) // to avoid collisions
4480       return false;
4481
4482     // Improve and check quality
4483     if ( !smoothAndCheck( data, nbSteps, distToIntersection ))
4484     {
4485       if ( nbSteps > 0 )
4486       {
4487 #ifdef __NOT_INVALIDATE_BAD_SMOOTH
4488         debugMsg("NOT INVALIDATED STEP!");
4489         return error("Smoothing failed", data._index);
4490 #endif
4491         dumpFunction(SMESH_Comment("invalidate")<<data._index<<"_step"<<nbSteps); // debug
4492         for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4493         {
4494           _EdgesOnShape& eos = data._edgesOnShape[iS];
4495           for ( size_t i = 0; i < eos._edges.size(); ++i )
4496             eos._edges[i]->InvalidateStep( nbSteps+1, eos );
4497         }
4498         dumpFunctionEnd();
4499       }
4500       break; // no more inflating possible
4501     }
4502     nbSteps++;
4503
4504     // Evaluate achieved thickness
4505     avgThick = 0;
4506     int nbActiveEdges = 0;
4507     for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4508     {
4509       _EdgesOnShape& eos = data._edgesOnShape[iS];
4510       if ( eos._edges.empty() ) continue;
4511
4512       const double shapeTgtThick = eos._hyp.GetTotalThickness();
4513       for ( size_t i = 0; i < eos._edges.size(); ++i )
4514       {
4515         if ( eos._edges[i]->_nodes.size() > 1 )
4516           avgThick    += Min( 1., eos._edges[i]->_len / shapeTgtThick );
4517         else
4518           avgThick    += shapeTgtThick;
4519         nbActiveEdges += ( ! eos._edges[i]->Is( _LayerEdge::BLOCKED ));
4520       }
4521     }
4522     avgThick /= data._n2eMap.size();
4523     debugMsg( "-- Thickness " << curThick << " ("<< avgThick*100 << "%) reached" );
4524
4525 #ifdef BLOCK_INFLATION
4526     if ( nbActiveEdges == 0 )
4527     {
4528       debugMsg( "-- Stop inflation since all _LayerEdge's BLOCKED " );
4529       break;
4530     }
4531 #else
4532     if ( distToIntersection < tgtThick * avgThick * safeFactor && avgThick < 0.9 )
4533     {
4534       debugMsg( "-- Stop inflation since "
4535                 << " distToIntersection( "<<distToIntersection<<" ) < avgThick( "
4536                 << tgtThick * avgThick << " ) * " << safeFactor );
4537       break;
4538     }
4539 #endif
4540     // new step size
4541     limitStepSize( data, 0.25 * distToIntersection );
4542     if ( data._stepSizeNodes[0] )
4543       data._stepSize = data._stepSizeCoeff *
4544         SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
4545
4546   } // while ( avgThick < 0.99 )
4547
4548   if ( nbSteps == 0 )
4549     return error("failed at the very first inflation step", data._index);
4550
4551   if ( avgThick < 0.99 )
4552   {
4553     if ( !data._proxyMesh->_warning || data._proxyMesh->_warning->IsOK() )
4554     {
4555       data._proxyMesh->_warning.reset
4556         ( new SMESH_ComputeError (COMPERR_WARNING,
4557                                   SMESH_Comment("Thickness ") << tgtThick <<
4558                                   " of viscous layers not reached,"
4559                                   " average reached thickness is " << avgThick*tgtThick));
4560     }
4561   }
4562
4563   // Restore position of src nodes moved by inflation on _noShrinkShapes
4564   dumpFunction(SMESH_Comment("restoNoShrink_So")<<data._index); // debug
4565   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4566   {
4567     _EdgesOnShape& eos = data._edgesOnShape[iS];
4568     if ( !eos._edges.empty() && eos._edges[0]->_nodes.size() == 1 )
4569       for ( size_t i = 0; i < eos._edges.size(); ++i )
4570       {
4571         restoreNoShrink( *eos._edges[ i ] );
4572       }
4573   }
4574   dumpFunctionEnd();
4575
4576   return safeFactor > 0; // == true (avoid warning: unused variable 'safeFactor')
4577 }
4578
4579 //================================================================================
4580 /*!
4581  * \brief Improve quality of layer inner surface and check intersection
4582  */
4583 //================================================================================
4584
4585 bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
4586                                      const int   infStep,
4587                                      double &    distToIntersection)
4588 {
4589   if ( data._nbShapesToSmooth == 0 )
4590     return true; // no shapes needing smoothing
4591
4592   bool moved, improved;
4593   double vol;
4594   vector< _LayerEdge* >    movedEdges, badEdges;
4595   vector< _EdgesOnShape* > eosC1; // C1 continues shapes
4596   vector< bool >           isConcaveFace;
4597
4598   SMESH_MesherHelper helper(*_mesh);
4599   Handle(ShapeAnalysis_Surface) surface;
4600   TopoDS_Face F;
4601
4602   for ( int isFace = 0; isFace < 2; ++isFace ) // smooth on [ EDGEs, FACEs ]
4603   {
4604     const TopAbs_ShapeEnum shapeType = isFace ? TopAbs_FACE : TopAbs_EDGE;
4605
4606     for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4607     {
4608       _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4609       if ( !eos._toSmooth ||
4610            eos.ShapeType() != shapeType ||
4611            eos._edges.empty() )
4612         continue;
4613
4614       // already smoothed?
4615       // bool toSmooth = ( eos._edges[ 0 ]->NbSteps() >= infStep+1 );
4616       // if ( !toSmooth ) continue;
4617
4618       if ( !eos._hyp.ToSmooth() )
4619       {
4620         // smooth disabled by the user; check validy only
4621         if ( !isFace ) continue;
4622         badEdges.clear();
4623         for ( size_t i = 0; i < eos._edges.size(); ++i )
4624         {
4625           _LayerEdge* edge = eos._edges[i];
4626           for ( size_t iF = 0; iF < edge->_simplices.size(); ++iF )
4627             if ( !edge->_simplices[iF].IsForward( edge->_nodes[0], edge->_pos.back(), vol ))
4628             {
4629               // debugMsg( "-- Stop inflation. Bad simplex ("
4630               //           << " "<< edge->_nodes[0]->GetID()
4631               //           << " "<< edge->_nodes.back()->GetID()
4632               //           << " "<< edge->_simplices[iF]._nPrev->GetID()
4633               //           << " "<< edge->_simplices[iF]._nNext->GetID() << " ) ");
4634               // return false;
4635               badEdges.push_back( edge );
4636             }
4637         }
4638         if ( !badEdges.empty() )
4639         {
4640           eosC1.resize(1);
4641           eosC1[0] = &eos;
4642           int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4643           if ( nbBad > 0 )
4644             return false;
4645         }
4646         continue; // goto the next EDGE or FACE
4647       }
4648
4649       // prepare data
4650       if ( eos.SWOLType() == TopAbs_FACE )
4651       {
4652         if ( !F.IsSame( eos._sWOL )) {
4653           F = TopoDS::Face( eos._sWOL );
4654           helper.SetSubShape( F );
4655           surface = helper.GetSurface( F );
4656         }
4657       }
4658       else
4659       {
4660         F.Nullify(); surface.Nullify();
4661       }
4662       const TGeomID sInd = eos._shapeID;
4663
4664       // perform smoothing
4665
4666       if ( eos.ShapeType() == TopAbs_EDGE )
4667       {
4668         dumpFunction(SMESH_Comment("smooth")<<data._index << "_Ed"<<sInd <<"_InfStep"<<infStep);
4669
4670         if ( !eos._edgeSmoother->Perform( data, surface, F, helper ))
4671         {
4672           // smooth on EDGE's (normally we should not get here)
4673           int step = 0;
4674           do {
4675             moved = false;
4676             for ( size_t i = 0; i < eos._edges.size(); ++i )
4677             {
4678               moved |= eos._edges[i]->SmoothOnEdge( surface, F, helper );
4679             }
4680             dumpCmd( SMESH_Comment("# end step ")<<step);
4681           }
4682           while ( moved && step++ < 5 );
4683         }
4684         dumpFunctionEnd();
4685       }
4686
4687       else // smooth on FACE
4688       {
4689         eosC1.clear();
4690         eosC1.push_back( & eos );
4691         eosC1.insert( eosC1.end(), eos._eosC1.begin(), eos._eosC1.end() );
4692
4693         movedEdges.clear();
4694         isConcaveFace.resize( eosC1.size() );
4695         for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4696         {
4697           isConcaveFace[ iEOS ] = data._concaveFaces.count( eosC1[ iEOS ]->_shapeID  );
4698           vector< _LayerEdge* > & edges = eosC1[ iEOS ]->_edges;
4699           for ( size_t i = 0; i < edges.size(); ++i )
4700             if ( edges[i]->Is( _LayerEdge::MOVED ) ||
4701                  edges[i]->Is( _LayerEdge::NEAR_BOUNDARY ))
4702               movedEdges.push_back( edges[i] );
4703
4704           makeOffsetSurface( *eosC1[ iEOS ], helper );
4705         }
4706
4707         int step = 0, stepLimit = 5, nbBad = 0;
4708         while (( ++step <= stepLimit ) || improved )
4709         {
4710           dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
4711                        <<"_InfStep"<<infStep<<"_"<<step); // debug
4712           int oldBadNb = nbBad;
4713           badEdges.clear();
4714
4715 #ifdef INCREMENTAL_SMOOTH
4716           bool findBest = false; // ( step == stepLimit );
4717           for ( size_t i = 0; i < movedEdges.size(); ++i )
4718           {
4719             movedEdges[i]->Unset( _LayerEdge::SMOOTHED );
4720             if ( movedEdges[i]->Smooth( step, findBest, movedEdges ) > 0 )
4721               badEdges.push_back( movedEdges[i] );
4722           }
4723 #else
4724           bool findBest = ( step == stepLimit || isConcaveFace[ iEOS ]);
4725           for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4726           {
4727             vector< _LayerEdge* > & edges = eosC1[ iEOS ]->_edges;
4728             for ( size_t i = 0; i < edges.size(); ++i )
4729             {
4730               edges[i]->Unset( _LayerEdge::SMOOTHED );
4731               if ( edges[i]->Smooth( step, findBest, false ) > 0 )
4732                 badEdges.push_back( eos._edges[i] );
4733             }
4734           }
4735 #endif
4736           nbBad = badEdges.size();
4737
4738           if ( nbBad > 0 )
4739             debugMsg(SMESH_Comment("nbBad = ") << nbBad );
4740
4741           if ( !badEdges.empty() && step >= stepLimit / 2 )
4742           {
4743             if ( badEdges[0]->Is( _LayerEdge::ON_CONCAVE_FACE ))
4744               stepLimit = 9;
4745
4746             // resolve hard smoothing situation around concave VERTEXes
4747             for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4748             {
4749               vector< _EdgesOnShape* > & eosCoVe = eosC1[ iEOS ]->_eosConcaVer;
4750               for ( size_t i = 0; i < eosCoVe.size(); ++i )
4751                 eosCoVe[i]->_edges[0]->MoveNearConcaVer( eosCoVe[i], eosC1[ iEOS ],
4752                                                          step, badEdges );
4753             }
4754             // look for the best smooth of _LayerEdge's neighboring badEdges
4755             nbBad = 0;
4756             for ( size_t i = 0; i < badEdges.size(); ++i )
4757             {
4758               _LayerEdge* ledge = badEdges[i];
4759               for ( size_t iN = 0; iN < ledge->_neibors.size(); ++iN )
4760               {
4761                 ledge->_neibors[iN]->Unset( _LayerEdge::SMOOTHED );
4762                 nbBad += ledge->_neibors[iN]->Smooth( step, true, /*findBest=*/true );
4763               }
4764               ledge->Unset( _LayerEdge::SMOOTHED );
4765               nbBad += ledge->Smooth( step, true, /*findBest=*/true );
4766             }
4767             debugMsg(SMESH_Comment("nbBad = ") << nbBad );
4768           }
4769
4770           if ( nbBad == oldBadNb  &&
4771                nbBad > 0 &&
4772                step < stepLimit ) // smooth w/o chech of validity
4773           {
4774             dumpFunctionEnd();
4775             dumpFunction(SMESH_Comment("smoothWoCheck")<<data._index<<"_Fa"<<sInd
4776                          <<"_InfStep"<<infStep<<"_"<<step); // debug
4777             for ( size_t i = 0; i < movedEdges.size(); ++i )
4778             {
4779               movedEdges[i]->SmoothWoCheck();
4780             }
4781             if ( stepLimit < 9 )
4782               stepLimit++;
4783           }
4784
4785           improved = ( nbBad < oldBadNb );
4786
4787           dumpFunctionEnd();
4788
4789           if (( step % 3 == 1 ) || ( nbBad > 0 && step >= stepLimit / 2 ))
4790             for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4791             {
4792               putOnOffsetSurface( *eosC1[ iEOS ], infStep, eosC1, step, /*moveAll=*/step == 1 );
4793             }
4794
4795         } // smoothing steps
4796
4797         // project -- to prevent intersections or fix bad simplices
4798         for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4799         {
4800           if ( ! eosC1[ iEOS ]->_eosConcaVer.empty() || nbBad > 0 )
4801             putOnOffsetSurface( *eosC1[ iEOS ], infStep, eosC1 );
4802         }
4803
4804         //if ( !badEdges.empty() )
4805         {
4806           badEdges.clear();
4807           for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4808           {
4809             for ( size_t i = 0; i < eosC1[ iEOS ]->_edges.size(); ++i )
4810             {
4811               if ( !eosC1[ iEOS ]->_sWOL.IsNull() ) continue;
4812
4813               _LayerEdge* edge = eosC1[ iEOS ]->_edges[i];
4814               edge->CheckNeiborsOnBoundary( & badEdges );
4815               if (( nbBad > 0 ) ||
4816                   ( edge->Is( _LayerEdge::BLOCKED ) && edge->Is( _LayerEdge::NEAR_BOUNDARY )))
4817               {
4818                 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
4819                 gp_XYZ        prevXYZ = edge->PrevCheckPos();
4820                 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
4821                   if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
4822                   {
4823                     debugMsg("Bad simplex ( " << edge->_nodes[0]->GetID()
4824                              << " "<< tgtXYZ._node->GetID()
4825                              << " "<< edge->_simplices[j]._nPrev->GetID()
4826                              << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
4827                     badEdges.push_back( edge );
4828                     break;
4829                   }
4830               }
4831             }
4832           }
4833
4834           // try to fix bad simplices by removing the last inflation step of some _LayerEdge's
4835           nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4836
4837           if ( nbBad > 0 )
4838             return false;
4839         }
4840
4841       } // // smooth on FACE's
4842     } // loop on shapes
4843   } // smooth on [ EDGEs, FACEs ]
4844
4845   // Check orientation of simplices of _LayerEdge's on EDGEs and VERTEXes
4846   eosC1.resize(1);
4847   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4848   {
4849     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4850     if ( eos.ShapeType() == TopAbs_FACE ||
4851          eos._edges.empty() ||
4852          !eos._sWOL.IsNull() )
4853       continue;
4854
4855     badEdges.clear();
4856     for ( size_t i = 0; i < eos._edges.size(); ++i )
4857     {
4858       _LayerEdge*      edge = eos._edges[i];
4859       if ( edge->_nodes.size() < 2 ) continue;
4860       SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
4861       gp_XYZ        prevXYZ = edge->PrevCheckPos( &eos );
4862       //const gp_XYZ& prevXYZ = edge->PrevPos();
4863       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
4864         if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
4865         {
4866           debugMsg("Bad simplex on bnd ( " << edge->_nodes[0]->GetID()
4867                    << " "<< tgtXYZ._node->GetID()
4868                    << " "<< edge->_simplices[j]._nPrev->GetID()
4869                    << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
4870           badEdges.push_back( edge );
4871           break;
4872         }
4873     }
4874
4875     // try to fix bad simplices by removing the last inflation step of some _LayerEdge's
4876     eosC1[0] = &eos;
4877     int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4878     if ( nbBad > 0 )
4879       return false;
4880   }
4881
4882
4883   // Check if the last segments of _LayerEdge intersects 2D elements;
4884   // checked elements are either temporary faces or faces on surfaces w/o the layers
4885
4886   SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
4887     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
4888                                            data._proxyMesh->GetFaces( data._solid )) );
4889
4890 #ifdef BLOCK_INFLATION
4891   const bool toBlockInfaltion = true;
4892 #else
4893   const bool toBlockInfaltion = false;
4894 #endif
4895   distToIntersection = Precision::Infinite();
4896   double dist;
4897   const SMDS_MeshElement* intFace = 0;
4898   const SMDS_MeshElement* closestFace = 0;
4899   _LayerEdge* le = 0;
4900   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4901   {
4902     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4903     if ( eos._edges.empty() || !eos._sWOL.IsNull() )
4904       continue;
4905     for ( size_t i = 0; i < eos._edges.size(); ++i )
4906     {
4907       if ( eos._edges[i]->Is( _LayerEdge::INTERSECTED ) ||
4908            eos._edges[i]->Is( _LayerEdge::MULTI_NORMAL ))
4909         continue;
4910       if ( eos._edges[i]->FindIntersection( *searcher, dist, data._epsilon, eos, &intFace ))
4911       {
4912         return false;
4913         // commented due to "Illegal hash-positionPosition" error in NETGEN
4914         // on Debian60 on viscous_layers_01/B2 case
4915         // Collision; try to deflate _LayerEdge's causing it
4916         // badEdges.clear();
4917         // badEdges.push_back( eos._edges[i] );
4918         // eosC1[0] = & eos;
4919         // int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4920         // if ( nbBad > 0 )
4921         //   return false;
4922
4923         // badEdges.clear();
4924         // if ( _EdgesOnShape* eof = data.GetShapeEdges( intFace->getshapeId() ))
4925         // {
4926         //   if ( const _TmpMeshFace* f = dynamic_cast< const _TmpMeshFace*>( intFace ))
4927         //   {
4928         //     const SMDS_MeshElement* srcFace =
4929         //       eof->_subMesh->GetSubMeshDS()->GetElement( f->getIdInShape() );
4930         //     SMDS_ElemIteratorPtr nIt = srcFace->nodesIterator();
4931         //     while ( nIt->more() )
4932         //     {
4933         //       const SMDS_MeshNode* srcNode = static_cast<const SMDS_MeshNode*>( nIt->next() );
4934         //       TNode2Edge::iterator n2e = data._n2eMap.find( srcNode );
4935         //       if ( n2e != data._n2eMap.end() )
4936         //         badEdges.push_back( n2e->second );
4937         //     }
4938         //     eosC1[0] = eof;
4939         //     nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4940         //     if ( nbBad > 0 )
4941         //       return false;
4942         //   }
4943         // }
4944         // if ( eos._edges[i]->FindIntersection( *searcher, dist, data._epsilon, eos, &intFace ))
4945         //   return false;
4946         // else
4947         //   continue;
4948       }
4949       if ( !intFace )
4950       {
4951         SMESH_Comment msg("Invalid? normal at node "); msg << eos._edges[i]->_nodes[0]->GetID();
4952         debugMsg( msg );
4953         continue;
4954       }
4955
4956       const bool isShorterDist = ( distToIntersection > dist );
4957       if ( toBlockInfaltion || isShorterDist )
4958       {
4959         // ignore intersection of a _LayerEdge based on a _ConvexFace with a face
4960         // lying on this _ConvexFace
4961         if ( _ConvexFace* convFace = data.GetConvexFace( intFace->getshapeId() ))
4962           if ( convFace->_subIdToEOS.count ( eos._shapeID ))
4963             continue;
4964
4965         // ignore intersection of a _LayerEdge based on a FACE with an element on this FACE
4966         // ( avoid limiting the thickness on the case of issue 22576)
4967         if ( intFace->getshapeId() == eos._shapeID  )
4968           continue;
4969
4970         // ignore intersection with intFace of an adjacent FACE
4971         if ( dist > 0 )
4972         {
4973           bool toIgnore = false;
4974           if (  eos._edges[i]->Is( _LayerEdge::TO_SMOOTH ))
4975           {
4976             const TopoDS_Shape& S = getMeshDS()->IndexToShape( intFace->getshapeId() );
4977             if ( !S.IsNull() && S.ShapeType() == TopAbs_FACE )
4978             {
4979               TopExp_Explorer edge( eos._shape, TopAbs_EDGE );
4980               for ( ; !toIgnore && edge.More(); edge.Next() )
4981                 // is adjacent - has a common EDGE
4982                 toIgnore = ( helper.IsSubShape( edge.Current(), S ));
4983
4984               if ( toIgnore ) // check angle between normals
4985               {
4986                 gp_XYZ normal;
4987                 if ( SMESH_MeshAlgos::FaceNormal( intFace, normal, /*normalized=*/true ))
4988                   toIgnore  = ( normal * eos._edges[i]->_normal > -0.5 );
4989               }
4990             }
4991           }
4992           if ( !toIgnore ) // check if the edge is a neighbor of intFace
4993           {
4994             for ( size_t iN = 0; !toIgnore &&  iN < eos._edges[i]->_neibors.size(); ++iN )
4995             {
4996               int nInd = intFace->GetNodeIndex( eos._edges[i]->_neibors[ iN ]->_nodes.back() );
4997               toIgnore = ( nInd >= 0 );
4998             }
4999           }
5000           if ( toIgnore )
5001             continue;
5002         }
5003
5004         // intersection not ignored
5005
5006         if ( toBlockInfaltion &&
5007              dist < ( eos._edges[i]->_len * theThickToIntersection ))
5008         {
5009           eos._edges[i]->Set( _LayerEdge::INTERSECTED ); // not to intersect
5010           eos._edges[i]->Block( data );                  // not to inflate
5011
5012           if ( _EdgesOnShape* eof = data.GetShapeEdges( intFace->getshapeId() ))
5013           {
5014             // block _LayerEdge's, on top of which intFace is
5015             if ( const _TmpMeshFace* f = dynamic_cast< const _TmpMeshFace*>( intFace ))
5016             {
5017               const SMDS_MeshElement* srcFace =
5018                 eof->_subMesh->GetSubMeshDS()->GetElement( f->getIdInShape() );
5019               SMDS_ElemIteratorPtr nIt = srcFace->nodesIterator();
5020               while ( nIt->more() )
5021               {
5022                 const SMDS_MeshNode* srcNode = static_cast<const SMDS_MeshNode*>( nIt->next() );
5023                 TNode2Edge::iterator n2e = data._n2eMap.find( srcNode );
5024                 if ( n2e != data._n2eMap.end() )
5025                   n2e->second->Block( data );
5026               }
5027             }
5028           }
5029         }
5030
5031         if ( isShorterDist )
5032         {
5033           distToIntersection = dist;
5034           le = eos._edges[i];
5035           closestFace = intFace;
5036         }
5037
5038       } // if ( toBlockInfaltion || isShorterDist )
5039     } // loop on eos._edges
5040   } // loop on data._edgesOnShape
5041
5042   if ( closestFace && le )
5043   {
5044 #ifdef __myDEBUG
5045     SMDS_MeshElement::iterator nIt = closestFace->begin_nodes();
5046     cout << "Shortest distance: _LayerEdge nodes: tgt " << le->_nodes.back()->GetID()
5047          << " src " << le->_nodes[0]->GetID()<< ", intersection with face ("
5048          << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
5049          << ") distance = " << distToIntersection<< endl;
5050 #endif
5051   }
5052
5053   return true;
5054 }
5055
5056 //================================================================================
5057 /*!
5058  * \brief try to fix bad simplices by removing the last inflation step of some _LayerEdge's
5059  *  \param [in,out] badSmooEdges - _LayerEdge's to fix
5060  *  \return int - resulting nb of bad _LayerEdge's
5061  */
5062 //================================================================================
5063
5064 int _ViscousBuilder::invalidateBadSmooth( _SolidData&               data,
5065                                           SMESH_MesherHelper&       helper,
5066                                           vector< _LayerEdge* >&    badSmooEdges,
5067                                           vector< _EdgesOnShape* >& eosC1,
5068                                           const int                 infStep )
5069 {
5070   if ( badSmooEdges.empty() || infStep == 0 ) return 0;
5071
5072   dumpFunction(SMESH_Comment("invalidateBadSmooth")<<"_S"<<eosC1[0]->_shapeID<<"_InfStep"<<infStep);
5073
5074   enum {
5075     INVALIDATED   = _LayerEdge::UNUSED_FLAG,
5076     TO_INVALIDATE = _LayerEdge::UNUSED_FLAG * 2,
5077     ADDED         = _LayerEdge::UNUSED_FLAG * 4
5078   };
5079   data.UnmarkEdges( TO_INVALIDATE & INVALIDATED & ADDED );
5080
5081   double vol;
5082   bool haveInvalidated = true;
5083   while ( haveInvalidated )
5084   {
5085     haveInvalidated = false;
5086     for ( size_t i = 0; i < badSmooEdges.size(); ++i )
5087     {
5088       _LayerEdge*   edge = badSmooEdges[i];
5089       _EdgesOnShape* eos = data.GetShapeEdges( edge );
5090       edge->Set( ADDED );
5091       bool invalidated = false;
5092       if ( edge->Is( TO_INVALIDATE ) && edge->NbSteps() > 1 )
5093       {
5094         edge->InvalidateStep( edge->NbSteps(), *eos, /*restoreLength=*/true );
5095         edge->Block( data );
5096         edge->Set( INVALIDATED );
5097         edge->Unset( TO_INVALIDATE );
5098         invalidated = true;
5099         haveInvalidated = true;
5100       }
5101
5102       // look for _LayerEdge's of bad _simplices
5103       int nbBad = 0;
5104       SMESH_TNodeXYZ tgtXYZ  = edge->_nodes.back();
5105       gp_XYZ        prevXYZ1 = edge->PrevCheckPos( eos );
5106       //const gp_XYZ& prevXYZ2 = edge->PrevPos();
5107       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5108       {
5109         if (( edge->_simplices[j].IsForward( &prevXYZ1, &tgtXYZ, vol ))/* &&
5110             ( &prevXYZ1 == &prevXYZ2 || edge->_simplices[j].IsForward( &prevXYZ2, &tgtXYZ, vol ))*/)
5111           continue;
5112
5113         bool isBad = true;
5114         _LayerEdge* ee[2] = { 0,0 };
5115         for ( size_t iN = 0; iN < edge->_neibors.size() &&   !ee[1]  ; ++iN )
5116           if ( edge->_simplices[j].Includes( edge->_neibors[iN]->_nodes.back() ))
5117             ee[ ee[0] != 0 ] = edge->_neibors[iN];
5118
5119         int maxNbSteps = Max( ee[0]->NbSteps(), ee[1]->NbSteps() );
5120         while ( maxNbSteps > edge->NbSteps() && isBad )
5121         {
5122           --maxNbSteps;
5123           for ( int iE = 0; iE < 2; ++iE )
5124           {
5125             if ( ee[ iE ]->NbSteps() > maxNbSteps &&
5126                  ee[ iE ]->NbSteps() > 1 )
5127             {
5128               _EdgesOnShape* eos = data.GetShapeEdges( ee[ iE ] );
5129               ee[ iE ]->InvalidateStep( ee[ iE ]->NbSteps(), *eos, /*restoreLength=*/true );
5130               ee[ iE ]->Block( data );
5131               ee[ iE ]->Set( INVALIDATED );
5132               haveInvalidated = true;
5133             }
5134           }
5135           if (( edge->_simplices[j].IsForward( &prevXYZ1, &tgtXYZ, vol )) /*&&
5136               ( &prevXYZ1 == &prevXYZ2 || edge->_simplices[j].IsForward( &prevXYZ2, &tgtXYZ, vol ))*/)
5137             isBad = false;
5138         }
5139         nbBad += isBad;
5140         if ( !ee[0]->Is( ADDED )) badSmooEdges.push_back( ee[0] );
5141         if ( !ee[1]->Is( ADDED )) badSmooEdges.push_back( ee[1] );
5142         ee[0]->Set( ADDED );
5143         ee[1]->Set( ADDED );
5144         if ( isBad )
5145         {
5146           ee[0]->Set( TO_INVALIDATE );
5147           ee[1]->Set( TO_INVALIDATE );
5148         }
5149       }
5150
5151       if ( !invalidated &&  nbBad > 0  &&  edge->NbSteps() > 1 )
5152       {
5153         _EdgesOnShape* eos = data.GetShapeEdges( edge );
5154         edge->InvalidateStep( edge->NbSteps(), *eos, /*restoreLength=*/true );
5155         edge->Block( data );
5156         edge->Set( INVALIDATED );
5157         edge->Unset( TO_INVALIDATE );
5158         haveInvalidated = true;
5159       }
5160     } // loop on badSmooEdges
5161   } // while ( haveInvalidated )
5162
5163   // re-smooth on analytical EDGEs
5164   for ( size_t i = 0; i < badSmooEdges.size(); ++i )
5165   {
5166     _LayerEdge* edge = badSmooEdges[i];
5167     if ( !edge->Is( INVALIDATED )) continue;
5168
5169     _EdgesOnShape* eos = data.GetShapeEdges( edge );
5170     if ( eos->ShapeType() == TopAbs_VERTEX )
5171     {
5172       PShapeIteratorPtr eIt = helper.GetAncestors( eos->_shape, *_mesh, TopAbs_EDGE );
5173       while ( const TopoDS_Shape* e = eIt->next() )
5174         if ( _EdgesOnShape* eoe = data.GetShapeEdges( *e ))
5175           if ( eoe->_edgeSmoother && eoe->_edgeSmoother->isAnalytic() )
5176           {
5177             // TopoDS_Face F; Handle(ShapeAnalysis_Surface) surface;
5178             // if ( eoe->SWOLType() == TopAbs_FACE ) {
5179             //   F       = TopoDS::Face( eoe->_sWOL );
5180             //   surface = helper.GetSurface( F );
5181             // }
5182             // eoe->_edgeSmoother->Perform( data, surface, F, helper );
5183             eoe->_edgeSmoother->_anaCurve.Nullify();
5184           }
5185     }
5186   }
5187
5188
5189   // check result of invalidation
5190
5191   int nbBad = 0;
5192   for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
5193   {
5194     for ( size_t i = 0; i < eosC1[ iEOS ]->_edges.size(); ++i )
5195     {
5196       if ( !eosC1[ iEOS ]->_sWOL.IsNull() ) continue;
5197       _LayerEdge*      edge = eosC1[ iEOS ]->_edges[i];
5198       SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
5199       gp_XYZ        prevXYZ = edge->PrevCheckPos( eosC1[ iEOS ]);
5200       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5201         if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
5202         {
5203           ++nbBad;
5204           debugMsg("Bad simplex remains ( " << edge->_nodes[0]->GetID()
5205                    << " "<< tgtXYZ._node->GetID()
5206                    << " "<< edge->_simplices[j]._nPrev->GetID()
5207                    << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
5208         }
5209     }
5210   }
5211   dumpFunctionEnd();
5212
5213   return nbBad;
5214 }
5215
5216 //================================================================================
5217 /*!
5218  * \brief Create an offset surface
5219  */
5220 //================================================================================
5221
5222 void _ViscousBuilder::makeOffsetSurface( _EdgesOnShape& eos, SMESH_MesherHelper& helper )
5223 {
5224   if ( eos._offsetSurf.IsNull() ||
5225        eos._edgeForOffset == 0 ||
5226        eos._edgeForOffset->Is( _LayerEdge::BLOCKED ))
5227     return;
5228
5229   Handle(ShapeAnalysis_Surface) baseSurface = helper.GetSurface( TopoDS::Face( eos._shape ));
5230
5231   // find offset
5232   gp_Pnt   tgtP = SMESH_TNodeXYZ( eos._edgeForOffset->_nodes.back() );
5233   /*gp_Pnt2d uv=*/baseSurface->ValueOfUV( tgtP, Precision::Confusion() );
5234   double offset = baseSurface->Gap();
5235
5236   eos._offsetSurf.Nullify();
5237
5238   try
5239   {
5240     BRepOffsetAPI_MakeOffsetShape offsetMaker( eos._shape, -offset, Precision::Confusion() );
5241     if ( !offsetMaker.IsDone() ) return;
5242
5243     TopExp_Explorer fExp( offsetMaker.Shape(), TopAbs_FACE );
5244     if ( !fExp.More() ) return;
5245
5246     TopoDS_Face F = TopoDS::Face( fExp.Current() );
5247     Handle(Geom_Surface) surf = BRep_Tool::Surface( F );
5248     if ( surf.IsNull() ) return;
5249
5250     eos._offsetSurf = new ShapeAnalysis_Surface( surf );
5251   }
5252   catch ( Standard_Failure )
5253   {
5254   }
5255 }
5256
5257 //================================================================================
5258 /*!
5259  * \brief Put nodes of a curved FACE to its offset surface
5260  */
5261 //================================================================================
5262
5263 void _ViscousBuilder::putOnOffsetSurface( _EdgesOnShape&            eos,
5264                                           int                       infStep,
5265                                           vector< _EdgesOnShape* >& eosC1,
5266                                           int                       smooStep,
5267                                           bool                      moveAll )
5268 {
5269   _EdgesOnShape * eof = & eos;
5270   if ( eos.ShapeType() != TopAbs_FACE ) // eos is a boundary of C1 FACE, look for the FACE eos
5271   {
5272     eof = 0;
5273     for ( size_t i = 0; i < eosC1.size() && !eof; ++i )
5274     {
5275       if ( eosC1[i]->_offsetSurf.IsNull() ||
5276            eosC1[i]->ShapeType() != TopAbs_FACE ||
5277            eosC1[i]->_edgeForOffset == 0 ||
5278            eosC1[i]->_edgeForOffset->Is( _LayerEdge::BLOCKED ))
5279         continue;
5280       if ( SMESH_MesherHelper::IsSubShape( eos._shape, eosC1[i]->_shape ))
5281         eof = eosC1[i];
5282     }
5283   }
5284   if ( !eof ||
5285        eof->_offsetSurf.IsNull() ||
5286        eof->ShapeType() != TopAbs_FACE ||
5287        eof->_edgeForOffset == 0 ||
5288        eof->_edgeForOffset->Is( _LayerEdge::BLOCKED ))
5289     return;
5290
5291   double preci = BRep_Tool::Tolerance( TopoDS::Face( eof->_shape )), vol;
5292   for ( size_t i = 0; i < eos._edges.size(); ++i )
5293   {
5294     _LayerEdge* edge = eos._edges[i];
5295     edge->Unset( _LayerEdge::MARKED );
5296     if ( edge->Is( _LayerEdge::BLOCKED ) || !edge->_curvature )
5297       continue;
5298     if ( !moveAll && !edge->Is( _LayerEdge::MOVED ))
5299         continue;
5300
5301     int nbBlockedAround = 0;
5302     for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
5303       nbBlockedAround += edge->_neibors[iN]->Is( _LayerEdge::BLOCKED );
5304     if ( nbBlockedAround > 1 )
5305       continue;
5306
5307     gp_Pnt tgtP = SMESH_TNodeXYZ( edge->_nodes.back() );
5308     gp_Pnt2d uv = eof->_offsetSurf->NextValueOfUV( edge->_curvature->_uv, tgtP, preci );
5309     if ( eof->_offsetSurf->Gap() > edge->_len ) continue; // NextValueOfUV() bug 
5310     edge->_curvature->_uv = uv;
5311     if ( eof->_offsetSurf->Gap() < 10 * preci ) continue; // same pos
5312
5313     gp_XYZ  newP = eof->_offsetSurf->Value( uv ).XYZ();
5314     gp_XYZ prevP = edge->PrevCheckPos();
5315     bool      ok = true;
5316     if ( !moveAll )
5317       for ( size_t iS = 0; iS < edge->_simplices.size() && ok; ++iS )
5318       {
5319         ok = edge->_simplices[iS].IsForward( &prevP, &newP, vol );
5320       }
5321     if ( ok )
5322     {
5323       SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( edge->_nodes.back() );
5324       n->setXYZ( newP.X(), newP.Y(), newP.Z());
5325       edge->_pos.back() = newP;
5326
5327       edge->Set( _LayerEdge::MARKED );
5328     }
5329   }
5330
5331 #ifdef _DEBUG_
5332   // dumpMove() for debug
5333   size_t i = 0;
5334   for ( ; i < eos._edges.size(); ++i )
5335     if ( eos._edges[i]->Is( _LayerEdge::MARKED ))
5336       break;
5337   if ( i < eos._edges.size() )
5338   {
5339     dumpFunction(SMESH_Comment("putOnOffsetSurface_F") << eos._shapeID
5340                  << "_InfStep" << infStep << "_" << smooStep );
5341     for ( ; i < eos._edges.size(); ++i )
5342     {
5343       if ( eos._edges[i]->Is( _LayerEdge::MARKED ))
5344         dumpMove( eos._edges[i]->_nodes.back() );
5345     }
5346     dumpFunctionEnd();
5347   }
5348 #endif
5349 }
5350
5351 //================================================================================
5352 /*!
5353  * \brief Return a curve of the EDGE to be used for smoothing and arrange
5354  *        _LayerEdge's to be in a consequent order
5355  */
5356 //================================================================================
5357
5358 Handle(Geom_Curve) _Smoother1D::CurveForSmooth( const TopoDS_Edge&  E,
5359                                                 _EdgesOnShape&      eos,
5360                                                 SMESH_MesherHelper& helper)
5361 {
5362   SMESHDS_SubMesh* smDS = eos._subMesh->GetSubMeshDS();
5363
5364   TopLoc_Location loc; double f,l;
5365
5366   Handle(Geom_Line)   line;
5367   Handle(Geom_Circle) circle;
5368   bool isLine, isCirc;
5369   if ( eos._sWOL.IsNull() ) /////////////////////////////////////////// 3D case
5370   {
5371     // check if the EDGE is a line
5372     Handle(Geom_Curve) curve = BRep_Tool::Curve( E, f, l);
5373     if ( curve->IsKind( STANDARD_TYPE( Geom_TrimmedCurve )))
5374       curve = Handle(Geom_TrimmedCurve)::DownCast( curve )->BasisCurve();
5375
5376     line   = Handle(Geom_Line)::DownCast( curve );
5377     circle = Handle(Geom_Circle)::DownCast( curve );
5378     isLine = (!line.IsNull());
5379     isCirc = (!circle.IsNull());
5380
5381     if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
5382     {
5383       isLine = SMESH_Algo::IsStraight( E );
5384
5385       if ( isLine )
5386         line = new Geom_Line( gp::OX() ); // only type does matter
5387     }
5388     if ( !isLine && !isCirc && eos._edges.size() > 2) // Check if the EDGE is close to a circle
5389     {
5390       // TODO
5391     }
5392   }
5393   else //////////////////////////////////////////////////////////////////////// 2D case
5394   {
5395     if ( !eos._isRegularSWOL ) // 23190
5396       return NULL;
5397
5398     const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
5399
5400     // check if the EDGE is a line
5401     Handle(Geom2d_Curve) curve = BRep_Tool::CurveOnSurface( E, F, f, l );
5402     if ( curve->IsKind( STANDARD_TYPE( Geom2d_TrimmedCurve )))
5403       curve = Handle(Geom2d_TrimmedCurve)::DownCast( curve )->BasisCurve();
5404
5405     Handle(Geom2d_Line)   line2d   = Handle(Geom2d_Line)::DownCast( curve );
5406     Handle(Geom2d_Circle) circle2d = Handle(Geom2d_Circle)::DownCast( curve );
5407     isLine = (!line2d.IsNull());
5408     isCirc = (!circle2d.IsNull());
5409
5410     if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
5411     {
5412       Bnd_B2d bndBox;
5413       SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
5414       while ( nIt->more() )
5415         bndBox.Add( helper.GetNodeUV( F, nIt->next() ));
5416       gp_XY size = bndBox.CornerMax() - bndBox.CornerMin();
5417
5418       const double lineTol = 1e-2 * sqrt( bndBox.SquareExtent() );
5419       for ( int i = 0; i < 2 && !isLine; ++i )
5420         isLine = ( size.Coord( i+1 ) <= lineTol );
5421     }
5422     if ( !isLine && !isCirc && eos._edges.size() > 2 ) // Check if the EDGE is close to a circle
5423     {
5424       // TODO
5425     }
5426     if ( isLine )
5427     {
5428       line = new Geom_Line( gp::OX() ); // only type does matter
5429     }
5430     else if ( isCirc )
5431     {
5432       gp_Pnt2d p = circle2d->Location();
5433       gp_Ax2 ax( gp_Pnt( p.X(), p.Y(), 0), gp::DX());
5434       circle = new Geom_Circle( ax, 1.); // only center position does matter
5435     }
5436   }
5437
5438   if ( isLine )
5439     return line;
5440   if ( isCirc )
5441     return circle;
5442
5443   return Handle(Geom_Curve)();
5444 }
5445
5446 //================================================================================
5447 /*!
5448  * \brief smooth _LayerEdge's on a staight EDGE or circular EDGE
5449  */
5450 //================================================================================
5451
5452 bool _Smoother1D::smoothAnalyticEdge( _SolidData&                    data,
5453                                       Handle(ShapeAnalysis_Surface)& surface,
5454                                       const TopoDS_Face&             F,
5455                                       SMESH_MesherHelper&            helper)
5456 {
5457   if ( !isAnalytic() ) return false;
5458
5459   const size_t iFrom = 0, iTo = _eos._edges.size();
5460
5461   if ( _anaCurve->IsKind( STANDARD_TYPE( Geom_Line )))
5462   {
5463     if ( F.IsNull() ) // 3D
5464     {
5465       SMESH_TNodeXYZ p0   ( _eos._edges[iFrom]->_2neibors->tgtNode(0) );
5466       SMESH_TNodeXYZ p1   ( _eos._edges[iTo-1]->_2neibors->tgtNode(1) );
5467       SMESH_TNodeXYZ pSrc0( _eos._edges[iFrom]->_2neibors->srcNode(0) );
5468       SMESH_TNodeXYZ pSrc1( _eos._edges[iTo-1]->_2neibors->srcNode(1) );
5469       gp_XYZ newPos, lineDir = pSrc1 - pSrc0;
5470       _LayerEdge* vLE0 = _eos._edges[iFrom]->_2neibors->_edges[0];
5471       _LayerEdge* vLE1 = _eos._edges[iTo-1]->_2neibors->_edges[1];
5472       bool shiftOnly = ( vLE0->Is( _LayerEdge::NORMAL_UPDATED ) ||
5473                          vLE0->Is( _LayerEdge::BLOCKED ) ||
5474                          vLE1->Is( _LayerEdge::NORMAL_UPDATED ) ||
5475                          vLE1->Is( _LayerEdge::BLOCKED ));
5476       for ( size_t i = iFrom; i < iTo; ++i )
5477       {
5478         _LayerEdge*       edge = _eos._edges[i];
5479         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edge->_nodes.back() );
5480         newPos = p0 * ( 1. - _leParams[i] ) + p1 * _leParams[i];
5481
5482         if ( shiftOnly || edge->Is( _LayerEdge::NORMAL_UPDATED ))
5483         {
5484           gp_XYZ curPos = SMESH_TNodeXYZ ( tgtNode );
5485           double  shift = ( lineDir * ( newPos - pSrc0 ) -
5486                             lineDir * ( curPos - pSrc0 ));
5487           newPos = curPos + lineDir * shift / lineDir.SquareModulus();
5488         }
5489         if ( edge->Is( _LayerEdge::BLOCKED ))
5490         {
5491           SMESH_TNodeXYZ pSrc( edge->_nodes[0] );
5492           double curThick = pSrc.SquareDistance( tgtNode );
5493           double newThink = ( pSrc - newPos ).SquareModulus();
5494           if ( newThink > curThick )
5495             continue;
5496         }
5497         edge->_pos.back() = newPos;
5498         tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5499         dumpMove( tgtNode );
5500       }
5501     }
5502     else // 2D
5503     {
5504       _LayerEdge* e0 = getLEdgeOnV( 0 );
5505       _LayerEdge* e1 = getLEdgeOnV( 1 );
5506       gp_XY uv0 = e0->LastUV( F, *data.GetShapeEdges( e0 ));
5507       gp_XY uv1 = e1->LastUV( F, *data.GetShapeEdges( e1 ));
5508       if ( e0->_nodes.back() == e1->_nodes.back() ) // closed edge
5509       {
5510         int iPeriodic = helper.GetPeriodicIndex();
5511         if ( iPeriodic == 1 || iPeriodic == 2 )
5512         {
5513           uv1.SetCoord( iPeriodic, helper.GetOtherParam( uv1.Coord( iPeriodic )));
5514           if ( uv0.Coord( iPeriodic ) > uv1.Coord( iPeriodic ))
5515             std::swap( uv0, uv1 );
5516         }
5517       }
5518       const gp_XY rangeUV = uv1 - uv0;
5519       for ( size_t i = iFrom; i < iTo; ++i )
5520       {
5521         if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5522         gp_XY newUV = uv0 + _leParams[i] * rangeUV;
5523         _eos._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
5524
5525         gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
5526         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5527         tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5528         dumpMove( tgtNode );
5529
5530         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
5531         pos->SetUParameter( newUV.X() );
5532         pos->SetVParameter( newUV.Y() );
5533       }
5534     }
5535     return true;
5536   }
5537
5538   if ( _anaCurve->IsKind( STANDARD_TYPE( Geom_Circle )))
5539   {
5540     Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast( _anaCurve );
5541     gp_Pnt center3D = circle->Location();
5542
5543     if ( F.IsNull() ) // 3D
5544     {
5545       if ( getLEdgeOnV( 0 )->_nodes.back() == getLEdgeOnV( 1 )->_nodes.back() )
5546         return true; // closed EDGE - nothing to do
5547
5548       // circle is a real curve of EDGE
5549       gp_Circ circ = circle->Circ();
5550
5551       // new center is shifted along its axis
5552       const gp_Dir& axis = circ.Axis().Direction();
5553       _LayerEdge*     e0 = getLEdgeOnV(0);
5554       _LayerEdge*     e1 = getLEdgeOnV(1);
5555       SMESH_TNodeXYZ  p0 = e0->_nodes.back();
5556       SMESH_TNodeXYZ  p1 = e1->_nodes.back();
5557       double      shift1 = axis.XYZ() * ( p0 - center3D.XYZ() );
5558       double      shift2 = axis.XYZ() * ( p1 - center3D.XYZ() );
5559       gp_Pnt   newCenter = center3D.XYZ() + axis.XYZ() * 0.5 * ( shift1 + shift2 );
5560
5561       double newRadius = 0.5 * ( newCenter.Distance( p0 ) + newCenter.Distance( p1 ));
5562
5563       gp_Ax2  newAxis( newCenter, axis, gp_Vec( newCenter, p0 ));
5564       gp_Circ newCirc( newAxis, newRadius );
5565       gp_Vec  vecC1  ( newCenter, p1 );
5566
5567       double uLast = newAxis.XDirection().AngleWithRef( vecC1, newAxis.Direction() ); // -PI - +PI
5568       if ( uLast < 0 )
5569         uLast += 2 * M_PI;
5570       
5571       for ( size_t i = iFrom; i < iTo; ++i )
5572       {
5573         if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5574         double u = uLast * _leParams[i];
5575         gp_Pnt p = ElCLib::Value( u, newCirc );
5576         _eos._edges[i]->_pos.back() = p.XYZ();
5577
5578         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5579         tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
5580         dumpMove( tgtNode );
5581       }
5582       return true;
5583     }
5584     else // 2D
5585     {
5586       const gp_XY center( center3D.X(), center3D.Y() );
5587
5588       _LayerEdge* e0 = getLEdgeOnV(0);
5589       _LayerEdge* eM = _eos._edges[ 0 ];
5590       _LayerEdge* e1 = getLEdgeOnV(1);
5591       gp_XY      uv0 = e0->LastUV( F, *data.GetShapeEdges( e0 ) );
5592       gp_XY      uvM = eM->LastUV( F, *data.GetShapeEdges( eM ) );
5593       gp_XY      uv1 = e1->LastUV( F, *data.GetShapeEdges( e1 ) );
5594       gp_Vec2d vec0( center, uv0 );
5595       gp_Vec2d vecM( center, uvM );
5596       gp_Vec2d vec1( center, uv1 );
5597       double uLast = vec0.Angle( vec1 ); // -PI - +PI
5598       double uMidl = vec0.Angle( vecM );
5599       if ( uLast * uMidl <= 0. )
5600         uLast += ( uMidl > 0 ? +2. : -2. ) * M_PI;
5601       const double radius = 0.5 * ( vec0.Magnitude() + vec1.Magnitude() );
5602
5603       gp_Ax2d   axis( center, vec0 );
5604       gp_Circ2d circ( axis, radius );
5605       for ( size_t i = iFrom; i < iTo; ++i )
5606       {
5607         if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5608         double    newU = uLast * _leParams[i];
5609         gp_Pnt2d newUV = ElCLib::Value( newU, circ );
5610         _eos._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
5611
5612         gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
5613         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5614         tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5615         dumpMove( tgtNode );
5616
5617         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
5618         pos->SetUParameter( newUV.X() );
5619         pos->SetVParameter( newUV.Y() );
5620       }
5621     }
5622     return true;
5623   }
5624
5625   return false;
5626 }
5627
5628 //================================================================================
5629 /*!
5630  * \brief smooth _LayerEdge's on a an EDGE
5631  */
5632 //================================================================================
5633
5634 bool _Smoother1D::smoothComplexEdge( _SolidData&                    data,
5635                                      Handle(ShapeAnalysis_Surface)& surface,
5636                                      const TopoDS_Face&             F,
5637                                      SMESH_MesherHelper&            helper)
5638 {
5639   if ( _offPoints.empty() )
5640     return false;
5641
5642   // move _offPoints along normals of _LayerEdge's
5643
5644   _LayerEdge* e[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
5645   if ( e[0]->Is( _LayerEdge::NORMAL_UPDATED ))
5646     _leOnV[0]._normal = getNormalNormal( e[0]->_normal, _edgeDir[0] );
5647   if ( e[1]->Is( _LayerEdge::NORMAL_UPDATED )) 
5648     _leOnV[1]._normal = getNormalNormal( e[1]->_normal, _edgeDir[1] );
5649   _leOnV[0]._len = e[0]->_len;
5650   _leOnV[1]._len = e[1]->_len;
5651   for ( size_t i = 0; i < _offPoints.size(); i++ )
5652   {
5653     _LayerEdge*  e0 = _offPoints[i]._2edges._edges[0];
5654     _LayerEdge*  e1 = _offPoints[i]._2edges._edges[1];
5655     const double w0 = _offPoints[i]._2edges._wgt[0];
5656     const double w1 = _offPoints[i]._2edges._wgt[1];
5657     gp_XYZ  avgNorm = ( e0->_normal    * w0 + e1->_normal    * w1 ).Normalized();
5658     double  avgLen  = ( e0->_len       * w0 + e1->_len       * w1 );
5659     double  avgFact = ( e0->_lenFactor * w0 + e1->_lenFactor * w1 );
5660     if ( e0->Is( _LayerEdge::NORMAL_UPDATED ) ||
5661          e1->Is( _LayerEdge::NORMAL_UPDATED ))
5662       avgNorm = getNormalNormal( avgNorm, _offPoints[i]._edgeDir );
5663
5664     _offPoints[i]._xyz += avgNorm * ( avgLen - _offPoints[i]._len ) * avgFact;
5665     _offPoints[i]._len  = avgLen;
5666   }
5667
5668   double fTol = 0;
5669   if ( !surface.IsNull() ) // project _offPoints to the FACE
5670   {
5671     fTol = 100 * BRep_Tool::Tolerance( F );
5672     //const double segLen = _offPoints[0].Distance( _offPoints[1] );
5673
5674     gp_Pnt2d uv = surface->ValueOfUV( _offPoints[0]._xyz, fTol );
5675     //if ( surface->Gap() < 0.5 * segLen )
5676       _offPoints[0]._xyz = surface->Value( uv ).XYZ();
5677
5678     for ( size_t i = 1; i < _offPoints.size(); ++i )
5679     {
5680       uv = surface->NextValueOfUV( uv, _offPoints[i]._xyz, fTol );
5681       //if ( surface->Gap() < 0.5 * segLen )
5682         _offPoints[i]._xyz = surface->Value( uv ).XYZ();
5683     }
5684   }
5685
5686   // project tgt nodes of extreme _LayerEdge's to the offset segments
5687
5688   if ( e[0]->Is( _LayerEdge::NORMAL_UPDATED )) _iSeg[0] = 0;
5689   if ( e[1]->Is( _LayerEdge::NORMAL_UPDATED )) _iSeg[1] = _offPoints.size()-2;
5690
5691   gp_Pnt pExtreme[2], pProj[2];
5692   for ( int is2nd = 0; is2nd < 2; ++is2nd )
5693   {
5694     pExtreme[ is2nd ] = SMESH_TNodeXYZ( e[is2nd]->_nodes.back() );
5695     int  i = _iSeg[ is2nd ];
5696     int di = is2nd ? -1 : +1;
5697     bool projected = false;
5698     double uOnSeg, distMin = Precision::Infinite(), dist, distPrev = 0;
5699     int nbWorse = 0;
5700     do {
5701       gp_Vec v0p( _offPoints[i]._xyz, pExtreme[ is2nd ]    );
5702       gp_Vec v01( _offPoints[i]._xyz, _offPoints[i+1]._xyz );
5703       uOnSeg     = ( v0p * v01 ) / v01.SquareMagnitude();  // param [0,1] along v01
5704       projected  = ( Abs( uOnSeg - 0.5 ) <= 0.5 );
5705       dist       =  pExtreme[ is2nd ].SquareDistance( _offPoints[ i + ( uOnSeg > 0.5 )]._xyz );
5706       if ( dist < distMin || projected )
5707       {
5708         _iSeg[ is2nd ] = i;
5709         pProj[ is2nd ] = _offPoints[i]._xyz + ( v01 * uOnSeg ).XYZ();
5710         distMin = dist;
5711       }
5712       else if ( dist > distPrev )
5713       {
5714         if ( ++nbWorse > 3 ) // avoid projection to the middle of a closed EDGE
5715           break;
5716       }
5717       distPrev = dist;
5718       i += di;
5719     }
5720     while ( !projected &&
5721             i >= 0 && i+1 < (int)_offPoints.size() );
5722
5723     if ( !projected )
5724     {
5725       if (( is2nd && _iSeg[1] != _offPoints.size()-2 ) || ( !is2nd && _iSeg[0] != 0 ))
5726       {
5727         _iSeg[0] = 0;
5728         _iSeg[1] = _offPoints.size()-2;
5729         debugMsg( "smoothComplexEdge() failed to project nodes of extreme _LayerEdge's" );
5730         return false;
5731       }
5732     }
5733   }
5734   if ( _iSeg[0] > _iSeg[1] )
5735   {
5736     debugMsg( "smoothComplexEdge() incorrectly projected nodes of extreme _LayerEdge's" );
5737     return false;
5738   }
5739
5740   // adjust length of extreme LE (test viscous_layers_01/B7)
5741   gp_Vec vDiv0( pExtreme[0], pProj[0] );
5742   gp_Vec vDiv1( pExtreme[1], pProj[1] );
5743   double d0 = vDiv0.Magnitude();
5744   double d1 = vDiv1.Magnitude();
5745   if ( e[0]->_normal * vDiv0.XYZ() < 0 ) e[0]->_len += d0;
5746   else                                   e[0]->_len -= d0;
5747   if ( e[1]->_normal * vDiv1.XYZ() < 0 ) e[1]->_len += d1;
5748   else                                   e[1]->_len -= d1;
5749
5750   // compute normalized length of the offset segments located between the projections
5751
5752   size_t iSeg = 0, nbSeg = _iSeg[1] - _iSeg[0] + 1;
5753   vector< double > len( nbSeg + 1 );
5754   len[ iSeg++ ] = 0;
5755   len[ iSeg++ ] = pProj[ 0 ].Distance( _offPoints[ _iSeg[0]+1 ]._xyz )/* * e[0]->_lenFactor*/;
5756   for ( size_t i = _iSeg[0]+1; i <= _iSeg[1]; ++i, ++iSeg )
5757   {
5758     len[ iSeg ] = len[ iSeg-1 ] + _offPoints[i].Distance( _offPoints[i+1] );
5759   }
5760   len[ nbSeg ] -= pProj[ 1 ].Distance( _offPoints[ _iSeg[1]+1 ]._xyz )/* * e[1]->_lenFactor*/;
5761
5762   // d0 *= e[0]->_lenFactor;
5763   // d1 *= e[1]->_lenFactor;
5764   double fullLen = len.back() - d0 - d1;
5765   for ( iSeg = 0; iSeg < len.size(); ++iSeg )
5766     len[iSeg] = ( len[iSeg] - d0 ) / fullLen;
5767
5768   // temporary replace extreme _offPoints by pExtreme
5769   gp_XYZ op[2] = { _offPoints[ _iSeg[0]   ]._xyz,
5770                    _offPoints[ _iSeg[1]+1 ]._xyz };
5771   _offPoints[ _iSeg[0]   ]._xyz = pExtreme[0].XYZ();
5772   _offPoints[ _iSeg[1]+ 1]._xyz = pExtreme[1].XYZ();
5773
5774   // distribute tgt nodes of _LayerEdge's between the projections
5775
5776   iSeg = 0;
5777   for ( size_t i = 0; i < _eos._edges.size(); ++i )
5778   {
5779     if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5780     while ( iSeg+2 < len.size() && _leParams[i] > len[ iSeg+1 ] )
5781       iSeg++;
5782     double r = ( _leParams[i] - len[ iSeg ]) / ( len[ iSeg+1 ] - len[ iSeg ]);
5783     gp_XYZ p = ( _offPoints[ iSeg + _iSeg[0]     ]._xyz * ( 1 - r ) +
5784                  _offPoints[ iSeg + _iSeg[0] + 1 ]._xyz * r );
5785
5786     if ( surface.IsNull() )
5787     {
5788       _eos._edges[i]->_pos.back() = p;
5789     }
5790     else // project a new node position to a FACE
5791     {
5792       gp_Pnt2d uv ( _eos._edges[i]->_pos.back().X(), _eos._edges[i]->_pos.back().Y() );
5793       gp_Pnt2d uv2( surface->NextValueOfUV( uv, p, fTol ));
5794
5795       p = surface->Value( uv2 ).XYZ();
5796       _eos._edges[i]->_pos.back().SetCoord( uv2.X(), uv2.Y(), 0 );
5797     }
5798     SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5799     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
5800     dumpMove( tgtNode );
5801   }
5802
5803   _offPoints[ _iSeg[0]   ]._xyz = op[0];
5804   _offPoints[ _iSeg[1]+1 ]._xyz = op[1];
5805
5806   return true;
5807 }
5808
5809 //================================================================================
5810 /*!
5811  * \brief Prepare for smoothing
5812  */
5813 //================================================================================
5814
5815 void _Smoother1D::prepare(_SolidData& data)
5816 {
5817   const TopoDS_Edge& E = TopoDS::Edge( _eos._shape );
5818   _curveLen = SMESH_Algo::EdgeLength( E );
5819
5820   // sort _LayerEdge's by position on the EDGE
5821   data.SortOnEdge( E, _eos._edges );
5822
5823   // compute normalized param of _eos._edges on EDGE
5824   _leParams.resize( _eos._edges.size() + 1 );
5825   {
5826     double curLen;
5827     gp_Pnt pPrev = SMESH_TNodeXYZ( getLEdgeOnV( 0 )->_nodes[0] );
5828     _leParams[0] = 0;
5829     for ( size_t i = 0; i < _eos._edges.size(); ++i )
5830     {
5831       gp_Pnt p       = SMESH_TNodeXYZ( _eos._edges[i]->_nodes[0] );
5832       curLen         = p.Distance( pPrev );
5833       _leParams[i+1] = _leParams[i] + curLen;
5834       pPrev          = p;
5835     }
5836     double fullLen = _leParams.back() + pPrev.Distance( SMESH_TNodeXYZ( getLEdgeOnV(1)->_nodes[0]));
5837     for ( size_t i = 0; i < _leParams.size()-1; ++i )
5838       _leParams[i] = _leParams[i+1] / fullLen;
5839   }
5840
5841   if ( isAnalytic() )
5842     return;
5843
5844   // divide E to have offset segments with low deflection
5845   BRepAdaptor_Curve c3dAdaptor( E );
5846   const double curDeflect = 0.1; //0.3; // 0.01; // Curvature deflection
5847   const double angDeflect = 0.1; //0.2; // 0.09; // Angular deflection
5848   GCPnts_TangentialDeflection discret(c3dAdaptor, angDeflect, curDeflect);
5849   if ( discret.NbPoints() <= 2 )
5850   {
5851     _anaCurve = new Geom_Line( gp::OX() ); // only type does matter
5852     return;
5853   }
5854
5855   const double u0 = c3dAdaptor.FirstParameter();
5856   gp_Pnt p; gp_Vec tangent;
5857   _offPoints.resize( discret.NbPoints() );
5858   for ( size_t i = 0; i < _offPoints.size(); i++ )
5859   {
5860     double u = discret.Parameter( i+1 );
5861     c3dAdaptor.D1( u, p, tangent );
5862     _offPoints[i]._xyz     = p.XYZ();
5863     _offPoints[i]._edgeDir = tangent.XYZ();
5864     _offPoints[i]._param = GCPnts_AbscissaPoint::Length( c3dAdaptor, u0, u ) / _curveLen;
5865   }
5866
5867   _LayerEdge* leOnV[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
5868
5869   // set _2edges
5870   _offPoints    [0]._2edges.set( &_leOnV[0], &_leOnV[0], 0.5, 0.5 );
5871   _offPoints.back()._2edges.set( &_leOnV[1], &_leOnV[1], 0.5, 0.5 );
5872   _2NearEdges tmp2edges;
5873   tmp2edges._edges[1] = _eos._edges[0];
5874   _leOnV[0]._2neibors = & tmp2edges;
5875   _leOnV[0]._nodes    = leOnV[0]->_nodes;
5876   _leOnV[1]._nodes    = leOnV[1]->_nodes;
5877   _LayerEdge* eNext, *ePrev = & _leOnV[0];
5878   for ( size_t iLE = 0, i = 1; i < _offPoints.size()-1; i++ )
5879   {
5880     // find _LayerEdge's located before and after an offset point
5881     // (_eos._edges[ iLE ] is next after ePrev)
5882     while ( iLE < _eos._edges.size() && _offPoints[i]._param > _leParams[ iLE ] )
5883       ePrev = _eos._edges[ iLE++ ];
5884     eNext = ePrev->_2neibors->_edges[1];
5885
5886     gp_Pnt p0 = SMESH_TNodeXYZ( ePrev->_nodes[0] );
5887     gp_Pnt p1 = SMESH_TNodeXYZ( eNext->_nodes[0] );
5888     double  r = p0.Distance( _offPoints[i]._xyz ) / p0.Distance( p1 );
5889     _offPoints[i]._2edges.set( ePrev, eNext, 1-r, r );
5890   }
5891
5892   // replace _LayerEdge's on VERTEX by _leOnV in _offPoints._2edges
5893   for ( size_t i = 0; i < _offPoints.size(); i++ )
5894     if ( _offPoints[i]._2edges._edges[0] == leOnV[0] )
5895       _offPoints[i]._2edges._edges[0] = & _leOnV[0];
5896     else break;
5897   for ( size_t i = _offPoints.size()-1; i > 0; i-- )
5898     if ( _offPoints[i]._2edges._edges[1] == leOnV[1] )
5899       _offPoints[i]._2edges._edges[1] = & _leOnV[1];
5900     else break;
5901
5902   // set _normal of _leOnV[0] and _leOnV[1] to be normal to the EDGE
5903
5904   int iLBO = _offPoints.size() - 2; // last but one
5905
5906   _edgeDir[0] = getEdgeDir( E, leOnV[0]->_nodes[0], data.GetHelper() );
5907   _edgeDir[1] = getEdgeDir( E, leOnV[1]->_nodes[0], data.GetHelper() );
5908
5909   _leOnV[ 0 ]._normal = getNormalNormal( leOnV[0]->_normal, _edgeDir[0] );
5910   _leOnV[ 1 ]._normal = getNormalNormal( leOnV[1]->_normal, _edgeDir[1] );
5911   _leOnV[ 0 ]._len = 0;
5912   _leOnV[ 1 ]._len = 0;
5913   _leOnV[ 0 ]._lenFactor = _offPoints[1   ]._2edges._edges[1]->_lenFactor;
5914   _leOnV[ 1 ]._lenFactor = _offPoints[iLBO]._2edges._edges[0]->_lenFactor;
5915
5916   _iSeg[0] = 0;
5917   _iSeg[1] = _offPoints.size()-2;
5918
5919   // initialize OffPnt::_len
5920   for ( size_t i = 0; i < _offPoints.size(); ++i )
5921     _offPoints[i]._len = 0;
5922
5923   if ( _eos._edges[0]->NbSteps() > 1 ) // already inflated several times, init _xyz
5924   {
5925     _leOnV[0]._len = leOnV[0]->_len;
5926     _leOnV[1]._len = leOnV[1]->_len;
5927     for ( size_t i = 0; i < _offPoints.size(); i++ )
5928     {
5929       _LayerEdge*  e0 = _offPoints[i]._2edges._edges[0];
5930       _LayerEdge*  e1 = _offPoints[i]._2edges._edges[1];
5931       const double w0 = _offPoints[i]._2edges._wgt[0];
5932       const double w1 = _offPoints[i]._2edges._wgt[1];
5933       double  avgLen  = ( e0->_len * w0 + e1->_len * w1 );
5934       gp_XYZ  avgXYZ  = ( SMESH_TNodeXYZ( e0->_nodes.back() ) * w0 +
5935                           SMESH_TNodeXYZ( e1->_nodes.back() ) * w1 );
5936       _offPoints[i]._xyz = avgXYZ;
5937       _offPoints[i]._len = avgLen;
5938     }
5939   }
5940 }
5941
5942 //================================================================================
5943 /*!
5944  * \brief set _normal of _leOnV[is2nd] to be normal to the EDGE
5945  */
5946 //================================================================================
5947
5948 gp_XYZ _Smoother1D::getNormalNormal( const gp_XYZ & normal,
5949                                      const gp_XYZ&  edgeDir)
5950 {
5951   gp_XYZ cross = normal ^ edgeDir;
5952   gp_XYZ  norm = edgeDir ^ cross;
5953   double  size = norm.Modulus();
5954
5955   return norm / size;
5956 }
5957
5958 //================================================================================
5959 /*!
5960  * \brief Sort _LayerEdge's by a parameter on a given EDGE
5961  */
5962 //================================================================================
5963
5964 void _SolidData::SortOnEdge( const TopoDS_Edge&     E,
5965                              vector< _LayerEdge* >& edges)
5966 {
5967   map< double, _LayerEdge* > u2edge;
5968   for ( size_t i = 0; i < edges.size(); ++i )
5969     u2edge.insert( u2edge.end(),
5970                    make_pair( _helper->GetNodeU( E, edges[i]->_nodes[0] ), edges[i] ));
5971
5972   ASSERT( u2edge.size() == edges.size() );
5973   map< double, _LayerEdge* >::iterator u2e = u2edge.begin();
5974   for ( size_t i = 0; i < edges.size(); ++i, ++u2e )
5975     edges[i] = u2e->second;
5976
5977   Sort2NeiborsOnEdge( edges );
5978 }
5979
5980 //================================================================================
5981 /*!
5982  * \brief Set _2neibors according to the order of _LayerEdge on EDGE
5983  */
5984 //================================================================================
5985
5986 void _SolidData::Sort2NeiborsOnEdge( vector< _LayerEdge* >& edges )
5987 {
5988   if ( edges.size() < 2 || !edges[0]->_2neibors ) return;
5989
5990   for ( size_t i = 0; i < edges.size()-1; ++i )
5991     if ( edges[i]->_2neibors->tgtNode(1) != edges[i+1]->_nodes.back() )
5992       edges[i]->_2neibors->reverse();
5993
5994   const size_t iLast = edges.size() - 1;
5995   if ( edges.size() > 1 &&
5996        edges[iLast]->_2neibors->tgtNode(0) != edges[iLast-1]->_nodes.back() )
5997     edges[iLast]->_2neibors->reverse();
5998 }
5999
6000 //================================================================================
6001 /*!
6002  * \brief Return _EdgesOnShape* corresponding to the shape
6003  */
6004 //================================================================================
6005
6006 _EdgesOnShape* _SolidData::GetShapeEdges(const TGeomID shapeID )
6007 {
6008   if ( shapeID < (int)_edgesOnShape.size() &&
6009        _edgesOnShape[ shapeID ]._shapeID == shapeID )
6010     return _edgesOnShape[ shapeID ]._subMesh ? & _edgesOnShape[ shapeID ] : 0;
6011
6012   for ( size_t i = 0; i < _edgesOnShape.size(); ++i )
6013     if ( _edgesOnShape[i]._shapeID == shapeID )
6014       return _edgesOnShape[i]._subMesh ? & _edgesOnShape[i] : 0;
6015
6016   return 0;
6017 }
6018
6019 //================================================================================
6020 /*!
6021  * \brief Return _EdgesOnShape* corresponding to the shape
6022  */
6023 //================================================================================
6024
6025 _EdgesOnShape* _SolidData::GetShapeEdges(const TopoDS_Shape& shape )
6026 {
6027   SMESHDS_Mesh* meshDS = _proxyMesh->GetMesh()->GetMeshDS();
6028   return GetShapeEdges( meshDS->ShapeToIndex( shape ));
6029 }
6030
6031 //================================================================================
6032 /*!
6033  * \brief Prepare data of the _LayerEdge for smoothing on FACE
6034  */
6035 //================================================================================
6036
6037 void _SolidData::PrepareEdgesToSmoothOnFace( _EdgesOnShape* eos, bool substituteSrcNodes )
6038 {
6039   SMESH_MesherHelper helper( *_proxyMesh->GetMesh() );
6040
6041   set< TGeomID > vertices;
6042   TopoDS_Face F;
6043   if ( eos->ShapeType() == TopAbs_FACE )
6044   {
6045     // check FACE concavity and get concave VERTEXes
6046     F = TopoDS::Face( eos->_shape );
6047     if ( isConcave( F, helper, &vertices ))
6048       _concaveFaces.insert( eos->_shapeID );
6049
6050     // set eos._eosConcaVer
6051     eos->_eosConcaVer.clear();
6052     eos->_eosConcaVer.reserve( vertices.size() );
6053     for ( set< TGeomID >::iterator v = vertices.begin(); v != vertices.end(); ++v )
6054     {
6055       _EdgesOnShape* eov = GetShapeEdges( *v );
6056       if ( eov && eov->_edges.size() == 1 )
6057       {
6058         eos->_eosConcaVer.push_back( eov );
6059         for ( size_t i = 0; i < eov->_edges[0]->_neibors.size(); ++i )
6060           eov->_edges[0]->_neibors[i]->Set( _LayerEdge::DIFFICULT );
6061       }
6062     }
6063
6064     // SetSmooLen() to _LayerEdge's on FACE
6065     for ( size_t i = 0; i < eos->_edges.size(); ++i )
6066     {
6067       eos->_edges[i]->SetSmooLen( Precision::Infinite() );
6068     }
6069     SMESH_subMeshIteratorPtr smIt = eos->_subMesh->getDependsOnIterator(/*includeSelf=*/false);
6070     while ( smIt->more() ) // loop on sub-shapes of the FACE
6071     {
6072       _EdgesOnShape* eoe = GetShapeEdges( smIt->next()->GetId() );
6073       if ( !eoe ) continue;
6074
6075       vector<_LayerEdge*>& eE = eoe->_edges;
6076       for ( size_t iE = 0; iE < eE.size(); ++iE ) // loop on _LayerEdge's on EDGE or VERTEX
6077       {
6078         if ( eE[iE]->_cosin <= theMinSmoothCosin )
6079           continue;
6080
6081         SMDS_ElemIteratorPtr segIt = eE[iE]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
6082         while ( segIt->more() )
6083         {
6084           const SMDS_MeshElement* seg = segIt->next();
6085           if ( !eos->_subMesh->DependsOn( seg->getshapeId() ))
6086             continue;
6087           if ( seg->GetNode(0) != eE[iE]->_nodes[0] )
6088             continue; // not to check a seg twice
6089           for ( size_t iN = 0; iN < eE[iE]->_neibors.size(); ++iN )
6090           {
6091             _LayerEdge* eN = eE[iE]->_neibors[iN];
6092             if ( eN->_nodes[0]->getshapeId() != eos->_shapeID )
6093               continue;
6094             double dist    = SMESH_MeshAlgos::GetDistance( seg, SMESH_TNodeXYZ( eN->_nodes[0] ));
6095             double smooLen = getSmoothingThickness( eE[iE]->_cosin, dist );
6096             eN->SetSmooLen( Min( smooLen, eN->GetSmooLen() ));
6097             eN->Set( _LayerEdge::NEAR_BOUNDARY );
6098           }
6099         }
6100       }
6101     }
6102   } // if ( eos->ShapeType() == TopAbs_FACE )
6103
6104   for ( size_t i = 0; i < eos->_edges.size(); ++i )
6105   {
6106     eos->_edges[i]->_smooFunction = 0;
6107     eos->_edges[i]->Set( _LayerEdge::TO_SMOOTH );
6108   }
6109   bool isCurved = false;
6110   for ( size_t i = 0; i < eos->_edges.size(); ++i )
6111   {
6112     _LayerEdge* edge = eos->_edges[i];
6113
6114     // get simplices sorted
6115     _Simplex::SortSimplices( edge->_simplices );
6116
6117     // smoothing function
6118     edge->ChooseSmooFunction( vertices, _n2eMap );
6119
6120     // set _curvature
6121     double avgNormProj = 0, avgLen = 0;
6122     for ( size_t iS = 0; iS < edge->_simplices.size(); ++iS )
6123     {
6124       _Simplex& s = edge->_simplices[iS];
6125
6126       gp_XYZ  vec = edge->_pos.back() - SMESH_TNodeXYZ( s._nPrev );
6127       avgNormProj += edge->_normal * vec;
6128       avgLen      += vec.Modulus();
6129       if ( substituteSrcNodes )
6130       {
6131         s._nNext = _n2eMap[ s._nNext ]->_nodes.back();
6132         s._nPrev = _n2eMap[ s._nPrev ]->_nodes.back();
6133       }
6134     }
6135     avgNormProj /= edge->_simplices.size();
6136     avgLen      /= edge->_simplices.size();
6137     if (( edge->_curvature = _Curvature::New( avgNormProj, avgLen )))
6138     {
6139       isCurved = true;
6140       SMDS_FacePosition* fPos = dynamic_cast<SMDS_FacePosition*>( edge->_nodes[0]->GetPosition() );
6141       if ( !fPos )
6142         for ( size_t iS = 0; iS < edge->_simplices.size()  &&  !fPos; ++iS )
6143           fPos = dynamic_cast<SMDS_FacePosition*>( edge->_simplices[iS]._nPrev->GetPosition() );
6144       if ( fPos )
6145         edge->_curvature->_uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
6146     }
6147   }
6148
6149   // prepare for putOnOffsetSurface()
6150   if (( eos->ShapeType() == TopAbs_FACE ) &&
6151       ( isCurved || !eos->_eosConcaVer.empty() ))
6152   {
6153     eos->_offsetSurf = helper.GetSurface( TopoDS::Face( eos->_shape ));
6154     eos->_edgeForOffset = 0;
6155
6156     double maxCosin = -1;
6157     for ( TopExp_Explorer eExp( eos->_shape, TopAbs_EDGE ); eExp.More(); eExp.Next() )
6158     {
6159       _EdgesOnShape* eoe = GetShapeEdges( eExp.Current() );
6160       if ( !eoe || eoe->_edges.empty() ) continue;
6161
6162       vector<_LayerEdge*>& eE = eoe->_edges;
6163       _LayerEdge* e = eE[ eE.size() / 2 ];
6164       if ( e->_cosin > maxCosin )
6165       {
6166         eos->_edgeForOffset = e;
6167         maxCosin = e->_cosin;
6168       }
6169     }
6170   }
6171 }
6172
6173 //================================================================================
6174 /*!
6175  * \brief Add faces for smoothing
6176  */
6177 //================================================================================
6178
6179 void _SolidData::AddShapesToSmooth( const set< _EdgesOnShape* >& eosToSmooth,
6180                                     const set< _EdgesOnShape* >* edgesNoAnaSmooth )
6181 {
6182   set< _EdgesOnShape * >::const_iterator eos = eosToSmooth.begin();
6183   for ( ; eos != eosToSmooth.end(); ++eos )
6184   {
6185     if ( !*eos || (*eos)->_toSmooth ) continue;
6186
6187     (*eos)->_toSmooth = true;
6188
6189     if ( (*eos)->ShapeType() == TopAbs_FACE )
6190     {
6191       PrepareEdgesToSmoothOnFace( *eos, /*substituteSrcNodes=*/false );
6192       (*eos)->_toSmooth = true;
6193     }
6194   }
6195
6196   // avoid _Smoother1D::smoothAnalyticEdge() of edgesNoAnaSmooth
6197   if ( edgesNoAnaSmooth )
6198     for ( eos = edgesNoAnaSmooth->begin(); eos != edgesNoAnaSmooth->end(); ++eos )
6199     {
6200       if ( (*eos)->_edgeSmoother )
6201         (*eos)->_edgeSmoother->_anaCurve.Nullify();
6202     }
6203 }
6204
6205 //================================================================================
6206 /*!
6207  * \brief Limit _LayerEdge::_maxLen according to local curvature
6208  */
6209 //================================================================================
6210
6211 void _ViscousBuilder::limitMaxLenByCurvature( _SolidData& data, SMESH_MesherHelper& helper )
6212 {
6213   // find intersection of neighbor _LayerEdge's to limit _maxLen
6214   // according to local curvature (IPAL52648)
6215
6216   // This method must be called after findCollisionEdges() where _LayerEdge's
6217   // get _lenFactor initialized in the case of eos._hyp.IsOffsetMethod()
6218
6219   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6220   {
6221     _EdgesOnShape& eosI = data._edgesOnShape[iS];
6222     if ( eosI._edges.empty() ) continue;
6223     if ( !eosI._hyp.ToSmooth() )
6224     {
6225       for ( size_t i = 0; i < eosI._edges.size(); ++i )
6226       {
6227         _LayerEdge* eI = eosI._edges[i];
6228         for ( size_t iN = 0; iN < eI->_neibors.size(); ++iN )
6229         {
6230           _LayerEdge* eN = eI->_neibors[iN];
6231           if ( eI->_nodes[0]->GetID() < eN->_nodes[0]->GetID() ) // treat this pair once
6232           {
6233             _EdgesOnShape* eosN = data.GetShapeEdges( eN );
6234             limitMaxLenByCurvature( eI, eN, eosI, *eosN, helper );
6235           }
6236         }
6237       }
6238     }
6239     else if ( eosI.ShapeType() == TopAbs_EDGE )
6240     {
6241       const TopoDS_Edge& E = TopoDS::Edge( eosI._shape );
6242       if ( SMESH_Algo::IsStraight( E, /*degenResult=*/true )) continue;
6243
6244       _LayerEdge* e0 = eosI._edges[0];
6245       for ( size_t i = 1; i < eosI._edges.size(); ++i )
6246       {
6247         _LayerEdge* eI = eosI._edges[i];
6248         limitMaxLenByCurvature( eI, e0, eosI, eosI, helper );
6249         e0 = eI;
6250       }
6251     }
6252   }
6253 }
6254
6255 //================================================================================
6256 /*!
6257  * \brief Limit _LayerEdge::_maxLen according to local curvature
6258  */
6259 //================================================================================
6260
6261 void _ViscousBuilder::limitMaxLenByCurvature( _LayerEdge*         e1,
6262                                               _LayerEdge*         e2,
6263                                               _EdgesOnShape&      eos1,
6264                                               _EdgesOnShape&      eos2,
6265                                               SMESH_MesherHelper& helper )
6266 {
6267   gp_XYZ plnNorm = e1->_normal ^ e2->_normal;
6268   double norSize = plnNorm.SquareModulus();
6269   if ( norSize < std::numeric_limits<double>::min() )
6270     return; // parallel normals
6271
6272   // find closest points of skew _LayerEdge's
6273   SMESH_TNodeXYZ src1( e1->_nodes[0] ), src2( e2->_nodes[0] );
6274   gp_XYZ dir12 = src2 - src1;
6275   gp_XYZ perp1 = e1->_normal ^ plnNorm;
6276   gp_XYZ perp2 = e2->_normal ^ plnNorm;
6277   double  dot1 = perp2 * e1->_normal;
6278   double  dot2 = perp1 * e2->_normal;
6279   double    u1 =   ( perp2 * dir12 ) / dot1;
6280   double    u2 = - ( perp1 * dir12 ) / dot2;
6281   if ( u1 > 0 && u2 > 0 )
6282   {
6283     double ovl = ( u1 * e1->_normal * dir12 -
6284                    u2 * e2->_normal * dir12 ) / dir12.SquareModulus();
6285     if ( ovl > theSmoothThickToElemSizeRatio )
6286     {    
6287       e1->_maxLen = Min( e1->_maxLen, 0.75 * u1 / e1->_lenFactor );
6288       e2->_maxLen = Min( e2->_maxLen, 0.75 * u2 / e2->_lenFactor );
6289     }
6290   }
6291 }
6292
6293 //================================================================================
6294 /*!
6295  * \brief Fill data._collisionEdges
6296  */
6297 //================================================================================
6298
6299 void _ViscousBuilder::findCollisionEdges( _SolidData& data, SMESH_MesherHelper& helper )
6300 {
6301   data._collisionEdges.clear();
6302
6303   // set the full thickness of the layers to LEs
6304   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6305   {
6306     _EdgesOnShape& eos = data._edgesOnShape[iS];
6307     if ( eos._edges.empty() ) continue;
6308     if ( eos.ShapeType() != TopAbs_EDGE && eos.ShapeType() != TopAbs_VERTEX ) continue;
6309
6310     for ( size_t i = 0; i < eos._edges.size(); ++i )
6311     {
6312       if ( eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
6313       double maxLen = eos._edges[i]->_maxLen;
6314       eos._edges[i]->_maxLen = Precision::Infinite(); // avoid blocking
6315       eos._edges[i]->SetNewLength( 1.5 * maxLen, eos, helper );
6316       eos._edges[i]->_maxLen = maxLen;
6317     }
6318   }
6319
6320   // make temporary quadrangles got by extrusion of
6321   // mesh edges along _LayerEdge._normal's
6322
6323   vector< const SMDS_MeshElement* > tmpFaces;
6324
6325   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6326   {
6327     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
6328     if ( eos.ShapeType() != TopAbs_EDGE )
6329       continue;
6330     if ( eos._edges.empty() )
6331     {
6332       _LayerEdge* edge[2] = { 0, 0 }; // LE of 2 VERTEX'es
6333       SMESH_subMeshIteratorPtr smIt = eos._subMesh->getDependsOnIterator(/*includeSelf=*/false);
6334       while ( smIt->more() )
6335         if ( _EdgesOnShape* eov = data.GetShapeEdges( smIt->next()->GetId() ))
6336           if ( eov->_edges.size() == 1 )
6337             edge[ bool( edge[0]) ] = eov->_edges[0];
6338
6339       if ( edge[1] )
6340       {
6341         _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge[0], edge[1], --_tmpFaceID );
6342         tmpFaces.push_back( f );
6343       }
6344     }
6345     for ( size_t i = 0; i < eos._edges.size(); ++i )
6346     {
6347       _LayerEdge* edge = eos._edges[i];
6348       for ( int j = 0; j < 2; ++j ) // loop on _2NearEdges
6349       {
6350         const SMDS_MeshNode* src2 = edge->_2neibors->srcNode(j);
6351         if ( src2->GetPosition()->GetDim() > 0 &&
6352              src2->GetID() < edge->_nodes[0]->GetID() )
6353           continue; // avoid using same segment twice
6354
6355         // a _LayerEdge containg tgt2
6356         _LayerEdge* neiborEdge = edge->_2neibors->_edges[j];
6357
6358         _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge, neiborEdge, --_tmpFaceID );
6359         tmpFaces.push_back( f );
6360       }
6361     }
6362   }
6363
6364   // Find _LayerEdge's intersecting tmpFaces.
6365
6366   SMDS_ElemIteratorPtr fIt( new SMDS_ElementVectorIterator( tmpFaces.begin(),
6367                                                             tmpFaces.end()));
6368   SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
6369     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(), fIt ));
6370
6371   double dist1, dist2, segLen, eps = 0.5;
6372   _CollisionEdges collEdges;
6373   vector< const SMDS_MeshElement* > suspectFaces;
6374   const double angle45 = Cos( 45. * M_PI / 180. );
6375
6376   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6377   {
6378     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
6379     if ( eos.ShapeType() == TopAbs_FACE || !eos._sWOL.IsNull() )
6380       continue;
6381     // find sub-shapes whose VL can influence VL on eos
6382     set< TGeomID > neighborShapes;
6383     PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
6384     while ( const TopoDS_Shape* face = fIt->next() )
6385     {
6386       TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
6387       if ( _EdgesOnShape* eof = data.GetShapeEdges( faceID ))
6388       {
6389         SMESH_subMeshIteratorPtr subIt = eof->_subMesh->getDependsOnIterator(/*includeSelf=*/false);
6390         while ( subIt->more() )
6391           neighborShapes.insert( subIt->next()->GetId() );
6392       }
6393     }
6394     if ( eos.ShapeType() == TopAbs_VERTEX )
6395     {
6396       PShapeIteratorPtr eIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_EDGE );
6397       while ( const TopoDS_Shape* edge = eIt->next() )
6398         neighborShapes.erase( getMeshDS()->ShapeToIndex( *edge ));
6399     }
6400     // find intersecting _LayerEdge's
6401     for ( size_t i = 0; i < eos._edges.size(); ++i )
6402     {
6403       if ( eos._edges[i]->Is( _LayerEdge::MULTI_NORMAL )) continue;
6404       _LayerEdge*   edge = eos._edges[i];
6405       gp_Ax1 lastSegment = edge->LastSegment( segLen, eos );
6406       segLen *= 1.2;
6407
6408       gp_Vec eSegDir0, eSegDir1;
6409       if ( edge->IsOnEdge() )
6410       {
6411         SMESH_TNodeXYZ eP( edge->_nodes[0] );
6412         eSegDir0 = SMESH_TNodeXYZ( edge->_2neibors->srcNode(0) ) - eP;
6413         eSegDir1 = SMESH_TNodeXYZ( edge->_2neibors->srcNode(1) ) - eP;
6414       }
6415       suspectFaces.clear();
6416       searcher->GetElementsInSphere( SMESH_TNodeXYZ( edge->_nodes.back()), edge->_len * 2,
6417                                      SMDSAbs_Face, suspectFaces );
6418       collEdges._intEdges.clear();
6419       for ( size_t j = 0 ; j < suspectFaces.size(); ++j )
6420       {
6421         const _TmpMeshFaceOnEdge* f = (const _TmpMeshFaceOnEdge*) suspectFaces[j];
6422         if ( f->_le1 == edge || f->_le2 == edge ) continue;
6423         if ( !neighborShapes.count( f->_le1->_nodes[0]->getshapeId() )) continue;
6424         if ( !neighborShapes.count( f->_le2->_nodes[0]->getshapeId() )) continue;
6425         if ( edge->IsOnEdge() ) {
6426           if ( edge->_2neibors->include( f->_le1 ) ||
6427                edge->_2neibors->include( f->_le2 )) continue;
6428         }
6429         else {
6430           if (( f->_le1->IsOnEdge() && f->_le1->_2neibors->include( edge )) ||
6431               ( f->_le2->IsOnEdge() && f->_le2->_2neibors->include( edge )))  continue;
6432         }
6433         dist1 = dist2 = Precision::Infinite();
6434         if ( !edge->SegTriaInter( lastSegment, f->_nn[0], f->_nn[1], f->_nn[2], dist1, eps ))
6435           dist1 = Precision::Infinite();
6436         if ( !edge->SegTriaInter( lastSegment, f->_nn[3], f->_nn[2], f->_nn[0], dist2, eps ))
6437           dist2 = Precision::Infinite();
6438         if (( dist1 > segLen ) && ( dist2 > segLen ))
6439           continue;
6440
6441         if ( edge->IsOnEdge() )
6442         {
6443           // skip perpendicular EDGEs
6444           gp_Vec fSegDir  = SMESH_TNodeXYZ( f->_nn[0] ) - SMESH_TNodeXYZ( f->_nn[3] );
6445           bool isParallel = ( isLessAngle( eSegDir0, fSegDir, angle45 ) ||
6446                               isLessAngle( eSegDir1, fSegDir, angle45 ) ||
6447                               isLessAngle( eSegDir0, fSegDir.Reversed(), angle45 ) ||
6448                               isLessAngle( eSegDir1, fSegDir.Reversed(), angle45 ));
6449           if ( !isParallel )
6450             continue;
6451         }
6452
6453         // either limit inflation of edges or remember them for updating _normal
6454         // double dot = edge->_normal * f->GetDir();
6455         // if ( dot > 0.1 )
6456         {
6457           collEdges._intEdges.push_back( f->_le1 );
6458           collEdges._intEdges.push_back( f->_le2 );
6459         }
6460         // else
6461         // {
6462         //   double shortLen = 0.75 * ( Min( dist1, dist2 ) / edge->_lenFactor );
6463         //   edge->_maxLen = Min( shortLen, edge->_maxLen );
6464         // }
6465       }
6466
6467       if ( !collEdges._intEdges.empty() )
6468       {
6469         collEdges._edge = edge;
6470         data._collisionEdges.push_back( collEdges );
6471       }
6472     }
6473   }
6474
6475   for ( size_t i = 0 ; i < tmpFaces.size(); ++i )
6476     delete tmpFaces[i];
6477
6478   // restore the zero thickness
6479   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6480   {
6481     _EdgesOnShape& eos = data._edgesOnShape[iS];
6482     if ( eos._edges.empty() ) continue;
6483     if ( eos.ShapeType() != TopAbs_EDGE && eos.ShapeType() != TopAbs_VERTEX ) continue;
6484
6485     for ( size_t i = 0; i < eos._edges.size(); ++i )
6486     {
6487       eos._edges[i]->InvalidateStep( 1, eos );
6488       eos._edges[i]->_len = 0;
6489     }
6490   }
6491 }
6492
6493 //================================================================================
6494 /*!
6495  * \brief Modify normals of _LayerEdge's on EDGE's to avoid intersection with
6496  * _LayerEdge's on neighbor EDGE's
6497  */
6498 //================================================================================
6499
6500 bool _ViscousBuilder::updateNormals( _SolidData&         data,
6501                                      SMESH_MesherHelper& helper,
6502                                      int                 stepNb,
6503                                      double              stepSize)
6504 {
6505   updateNormalsOfC1Vertices( data );
6506
6507   if ( stepNb > 0 && !updateNormalsOfConvexFaces( data, helper, stepNb ))
6508     return false;
6509
6510   // map to store new _normal and _cosin for each intersected edge
6511   map< _LayerEdge*, _LayerEdge, _LayerEdgeCmp >           edge2newEdge;
6512   map< _LayerEdge*, _LayerEdge, _LayerEdgeCmp >::iterator e2neIt;
6513   _LayerEdge zeroEdge;
6514   zeroEdge._normal.SetCoord( 0,0,0 );
6515   zeroEdge._maxLen = Precision::Infinite();
6516   zeroEdge._nodes.resize(1); // to init _TmpMeshFaceOnEdge
6517
6518   set< _EdgesOnShape* > shapesToSmooth, edgesNoAnaSmooth;
6519
6520   double segLen, dist1, dist2, dist;
6521   vector< pair< _LayerEdge*, double > > intEdgesDist;
6522   _TmpMeshFaceOnEdge quad( &zeroEdge, &zeroEdge, 0 );
6523
6524   for ( int iter = 0; iter < 5; ++iter )
6525   {
6526     edge2newEdge.clear();
6527
6528     for ( size_t iE = 0; iE < data._collisionEdges.size(); ++iE )
6529     {
6530       _CollisionEdges& ce = data._collisionEdges[iE];
6531       _LayerEdge*   edge1 = ce._edge;
6532       if ( !edge1 /*|| edge1->Is( _LayerEdge::BLOCKED )*/) continue;
6533       _EdgesOnShape* eos1 = data.GetShapeEdges( edge1 );
6534       if ( !eos1 ) continue;
6535
6536       // detect intersections
6537       gp_Ax1 lastSeg = edge1->LastSegment( segLen, *eos1 );
6538       double testLen = 1.5 * edge1->_maxLen * edge1->_lenFactor;
6539       double     eps = 0.5;
6540       intEdgesDist.clear();
6541       double minIntDist = Precision::Infinite();
6542       for ( size_t i = 0; i < ce._intEdges.size(); i += 2 )
6543       {
6544         if ( edge1->Is( _LayerEdge::BLOCKED ) &&
6545              ce._intEdges[i  ]->Is( _LayerEdge::BLOCKED ) &&
6546              ce._intEdges[i+1]->Is( _LayerEdge::BLOCKED ))
6547           continue;
6548         double dot  = edge1->_normal * quad.GetDir( ce._intEdges[i], ce._intEdges[i+1] );
6549         double fact = ( 1.1 + dot * dot );
6550         SMESH_TNodeXYZ pSrc0( ce.nSrc(i) ), pSrc1( ce.nSrc(i+1) );
6551         SMESH_TNodeXYZ pTgt0( ce.nTgt(i) ), pTgt1( ce.nTgt(i+1) );
6552         gp_XYZ pLast0 = pSrc0 + ( pTgt0 - pSrc0 ) * fact;
6553         gp_XYZ pLast1 = pSrc1 + ( pTgt1 - pSrc1 ) * fact;
6554         dist1 = dist2 = Precision::Infinite();
6555         if ( !edge1->SegTriaInter( lastSeg, pSrc0, pLast0, pSrc1,  dist1, eps ) &&
6556              !edge1->SegTriaInter( lastSeg, pSrc1, pLast1, pLast0, dist2, eps ))
6557           continue;
6558         dist = dist1;
6559         if ( dist > testLen || dist <= 0 )
6560         {
6561           dist = dist2;
6562           if ( dist > testLen || dist <= 0 )
6563             continue;
6564         }
6565         // choose a closest edge
6566         gp_Pnt intP( lastSeg.Location().XYZ() + lastSeg.Direction().XYZ() * ( dist + segLen ));
6567         double d1 = intP.SquareDistance( pSrc0 );
6568         double d2 = intP.SquareDistance( pSrc1 );
6569         int iClose = i + ( d2 < d1 );
6570         _LayerEdge* edge2 = ce._intEdges[iClose];
6571         edge2->Unset( _LayerEdge::MARKED );
6572
6573         // choose a closest edge among neighbors
6574         gp_Pnt srcP( SMESH_TNodeXYZ( edge1->_nodes[0] ));
6575         d1 = srcP.SquareDistance( SMESH_TNodeXYZ( edge2->_nodes[0] ));
6576         for ( size_t j = 0; j < intEdgesDist.size(); ++j )
6577         {
6578           _LayerEdge * edgeJ = intEdgesDist[j].first;
6579           if ( edge2->IsNeiborOnEdge( edgeJ ))
6580           {
6581             d2 = srcP.SquareDistance( SMESH_TNodeXYZ( edgeJ->_nodes[0] ));
6582             ( d1 < d2 ? edgeJ : edge2 )->Set( _LayerEdge::MARKED );
6583           }
6584         }
6585         intEdgesDist.push_back( make_pair( edge2, dist ));
6586         // if ( Abs( d2 - d1 ) / Max( d2, d1 ) < 0.5 )
6587         // {
6588         //   iClose = i + !( d2 < d1 );
6589         //   intEdges.push_back( ce._intEdges[iClose] );
6590         //   ce._intEdges[iClose]->Unset( _LayerEdge::MARKED );
6591         // }
6592         minIntDist = Min( edge1->_len * edge1->_lenFactor - segLen + dist, minIntDist );
6593       }
6594
6595       //ce._edge = 0;
6596
6597       // compute new _normals
6598       for ( size_t i = 0; i < intEdgesDist.size(); ++i )
6599       {
6600         _LayerEdge* edge2    = intEdgesDist[i].first;
6601         double       distWgt = edge1->_len / intEdgesDist[i].second;
6602         // if ( edge1->Is( _LayerEdge::BLOCKED ) &&
6603         //      edge2->Is( _LayerEdge::BLOCKED )) continue;        
6604         if ( edge2->Is( _LayerEdge::MARKED )) continue;
6605         edge2->Set( _LayerEdge::MARKED );
6606
6607         // get a new normal
6608         gp_XYZ dir1 = edge1->_normal, dir2 = edge2->_normal;
6609
6610         double cos1 = Abs( edge1->_cosin ), cos2 = Abs( edge2->_cosin );
6611         double wgt1 = ( cos1 + 0.001 ) / ( cos1 + cos2 + 0.002 );
6612         double wgt2 = ( cos2 + 0.001 ) / ( cos1 + cos2 + 0.002 );
6613         // double cos1 = Abs( edge1->_cosin ),        cos2 = Abs( edge2->_cosin );
6614         // double sgn1 = 0.1 * ( 1 + edge1->_cosin ), sgn2 = 0.1 * ( 1 + edge2->_cosin );
6615         // double wgt1 = ( cos1 + sgn1 ) / ( cos1 + cos2 + sgn1 + sgn2 );
6616         // double wgt2 = ( cos2 + sgn2 ) / ( cos1 + cos2 + sgn1 + sgn2 );
6617         gp_XYZ newNormal = wgt1 * dir1 + wgt2 * dir2;
6618         newNormal.Normalize();
6619
6620         // get new cosin
6621         double newCos;
6622         double sgn1 = edge1->_cosin / cos1, sgn2 = edge2->_cosin / cos2;
6623         if ( cos1 < theMinSmoothCosin )
6624         {
6625           newCos = cos2 * sgn1;
6626         }
6627         else if ( cos2 > theMinSmoothCosin ) // both cos1 and cos2 > theMinSmoothCosin
6628         {
6629           newCos = ( wgt1 * cos1 + wgt2 * cos2 ) * edge1->_cosin / cos1;
6630         }
6631         else
6632         {
6633           newCos = edge1->_cosin;
6634         }
6635
6636         e2neIt = edge2newEdge.insert( make_pair( edge1, zeroEdge )).first;
6637         e2neIt->second._normal += distWgt * newNormal;
6638         e2neIt->second._cosin   = newCos;
6639         e2neIt->second._maxLen  = 0.7 * minIntDist / edge1->_lenFactor;
6640         if ( iter > 0 && sgn1 * sgn2 < 0 && edge1->_cosin < 0 )
6641           e2neIt->second._normal += dir2;
6642         e2neIt = edge2newEdge.insert( make_pair( edge2, zeroEdge )).first;
6643         e2neIt->second._normal += distWgt * newNormal;
6644         e2neIt->second._cosin   = edge2->_cosin;
6645         if ( iter > 0 && sgn1 * sgn2 < 0 && edge2->_cosin < 0 )
6646           e2neIt->second._normal += dir1;
6647       }
6648     }
6649
6650     if ( edge2newEdge.empty() )
6651       break; //return true;
6652
6653     dumpFunction(SMESH_Comment("updateNormals")<< data._index << "_" << stepNb << "_it" << iter);
6654
6655     // Update data of edges depending on a new _normal
6656
6657     data.UnmarkEdges();
6658     for ( e2neIt = edge2newEdge.begin(); e2neIt != edge2newEdge.end(); ++e2neIt )
6659     {
6660       _LayerEdge*    edge = e2neIt->first;
6661       if ( edge->Is( _LayerEdge::BLOCKED )) continue;
6662       _LayerEdge& newEdge = e2neIt->second;
6663       _EdgesOnShape*  eos = data.GetShapeEdges( edge );
6664
6665       // Check if a new _normal is OK:
6666       newEdge._normal.Normalize();
6667       if ( !isNewNormalOk( data, *edge, newEdge._normal ))
6668       {
6669         if ( newEdge._maxLen < edge->_len && iter > 0 ) // limit _maxLen
6670         {
6671           edge->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true  );
6672           edge->_maxLen = newEdge._maxLen;
6673           edge->SetNewLength( newEdge._maxLen, *eos, helper );
6674         }
6675         continue; // the new _normal is bad
6676       }
6677       // the new _normal is OK
6678
6679       // find shapes that need smoothing due to change of _normal
6680       if ( edge->_cosin   < theMinSmoothCosin &&
6681            newEdge._cosin > theMinSmoothCosin )
6682       {
6683         if ( eos->_sWOL.IsNull() )
6684         {
6685           SMDS_ElemIteratorPtr fIt = edge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
6686           while ( fIt->more() )
6687             shapesToSmooth.insert( data.GetShapeEdges( fIt->next()->getshapeId() ));
6688         }
6689         else // edge inflates along a FACE
6690         {
6691           TopoDS_Shape V = helper.GetSubShapeByNode( edge->_nodes[0], getMeshDS() );
6692           PShapeIteratorPtr eIt = helper.GetAncestors( V, *_mesh, TopAbs_EDGE, &eos->_sWOL );
6693           while ( const TopoDS_Shape* E = eIt->next() )
6694           {
6695             gp_Vec edgeDir = getEdgeDir( TopoDS::Edge( *E ), TopoDS::Vertex( V ));
6696             double   angle = edgeDir.Angle( newEdge._normal ); // [0,PI]
6697             if ( angle < M_PI / 2 )
6698               shapesToSmooth.insert( data.GetShapeEdges( *E ));
6699           }
6700         }
6701       }
6702
6703       double len = edge->_len;
6704       edge->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true  );
6705       edge->SetNormal( newEdge._normal );
6706       edge->SetCosin( newEdge._cosin );
6707       edge->SetNewLength( len, *eos, helper );
6708       edge->Set( _LayerEdge::MARKED );
6709       edge->Set( _LayerEdge::NORMAL_UPDATED );
6710       edgesNoAnaSmooth.insert( eos );
6711     }
6712
6713     // Update normals and other dependent data of not intersecting _LayerEdge's
6714     // neighboring the intersecting ones
6715
6716     for ( e2neIt = edge2newEdge.begin(); e2neIt != edge2newEdge.end(); ++e2neIt )
6717     {
6718       _LayerEdge*   edge1 = e2neIt->first;
6719       _EdgesOnShape* eos1 = data.GetShapeEdges( edge1 );
6720       if ( !edge1->Is( _LayerEdge::MARKED ))
6721         continue;
6722
6723       if ( edge1->IsOnEdge() )
6724       {
6725         const SMDS_MeshNode * n1 = edge1->_2neibors->srcNode(0);
6726         const SMDS_MeshNode * n2 = edge1->_2neibors->srcNode(1);
6727         edge1->SetDataByNeighbors( n1, n2, *eos1, helper );
6728       }
6729
6730       if ( !edge1->_2neibors || !eos1->_sWOL.IsNull() )
6731         continue;
6732       for ( int j = 0; j < 2; ++j ) // loop on 2 neighbors
6733       {
6734         _LayerEdge* neighbor = edge1->_2neibors->_edges[j];
6735         if ( neighbor->Is( _LayerEdge::MARKED ) /*edge2newEdge.count ( neighbor )*/)
6736           continue; // j-th neighbor is also intersected
6737         _LayerEdge* prevEdge = edge1;
6738         const int nbSteps = 10;
6739         for ( int step = nbSteps; step; --step ) // step from edge1 in j-th direction
6740         {
6741           if ( neighbor->Is( _LayerEdge::BLOCKED ) ||
6742                neighbor->Is( _LayerEdge::MARKED ))
6743             break;
6744           _EdgesOnShape* eos = data.GetShapeEdges( neighbor );
6745           if ( !eos ) continue;
6746           _LayerEdge* nextEdge = neighbor;
6747           if ( neighbor->_2neibors )
6748           {
6749             int iNext = 0;
6750             nextEdge = neighbor->_2neibors->_edges[iNext];
6751             if ( nextEdge == prevEdge )
6752               nextEdge = neighbor->_2neibors->_edges[ ++iNext ];
6753           }
6754           double r = double(step-1)/nbSteps/(iter+1);
6755           if ( !nextEdge->_2neibors )
6756             r = Min( r, 0.5 );
6757
6758           gp_XYZ newNorm = prevEdge->_normal * r + nextEdge->_normal * (1-r);
6759           newNorm.Normalize();
6760           if ( !isNewNormalOk( data, *neighbor, newNorm ))
6761             break;
6762
6763           double len = neighbor->_len;
6764           neighbor->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true  );
6765           neighbor->SetNormal( newNorm );
6766           neighbor->SetCosin( prevEdge->_cosin * r + nextEdge->_cosin * (1-r) );
6767           if ( neighbor->_2neibors )
6768             neighbor->SetDataByNeighbors( prevEdge->_nodes[0], nextEdge->_nodes[0], *eos, helper );
6769           neighbor->SetNewLength( len, *eos, helper );
6770           neighbor->Set( _LayerEdge::MARKED );
6771           neighbor->Set( _LayerEdge::NORMAL_UPDATED );
6772           edgesNoAnaSmooth.insert( eos );
6773
6774           if ( !neighbor->_2neibors )
6775             break; // neighbor is on VERTEX
6776
6777           // goto the next neighbor
6778           prevEdge = neighbor;
6779           neighbor = nextEdge;
6780         }
6781       }
6782     }
6783     dumpFunctionEnd();
6784   } // iterations
6785
6786   data.AddShapesToSmooth( shapesToSmooth, &edgesNoAnaSmooth );
6787
6788   return true;
6789 }
6790
6791 //================================================================================
6792 /*!
6793  * \brief Check if a new normal is OK
6794  */
6795 //================================================================================
6796
6797 bool _ViscousBuilder::isNewNormalOk( _SolidData&   data,
6798                                      _LayerEdge&   edge,
6799                                      const gp_XYZ& newNormal)
6800 {
6801   // check a min angle between the newNormal and surrounding faces
6802   vector<_Simplex> simplices;
6803   SMESH_TNodeXYZ n0( edge._nodes[0] ), n1, n2;
6804   _Simplex::GetSimplices( n0._node, simplices, data._ignoreFaceIds, &data );
6805   double newMinDot = 1, curMinDot = 1;
6806   for ( size_t i = 0; i < simplices.size(); ++i )
6807   {
6808     n1.Set( simplices[i]._nPrev );
6809     n2.Set( simplices[i]._nNext );
6810     gp_XYZ normFace = ( n1 - n0 ) ^ ( n2 - n0 );
6811     double normLen2 = normFace.SquareModulus();
6812     if ( normLen2 < std::numeric_limits<double>::min() )
6813       continue;
6814     normFace /= Sqrt( normLen2 );
6815     newMinDot = Min( newNormal    * normFace, newMinDot );
6816     curMinDot = Min( edge._normal * normFace, curMinDot );
6817   }
6818   bool ok = true;
6819   if ( newMinDot < 0.5 )
6820   {
6821     ok = ( newMinDot >= curMinDot * 0.9 );
6822     //return ( newMinDot >= ( curMinDot * ( 0.8 + 0.1 * edge.NbSteps() )));
6823     // double initMinDot2 = 1. - edge._cosin * edge._cosin;
6824     // return ( newMinDot * newMinDot ) >= ( 0.8 * initMinDot2 );
6825   }
6826
6827   return ok;
6828 }
6829
6830 //================================================================================
6831 /*!
6832  * \brief Modify normals of _LayerEdge's on FACE to reflex smoothing
6833  */
6834 //================================================================================
6835
6836 bool _ViscousBuilder::updateNormalsOfSmoothed( _SolidData&         data,
6837                                                SMESH_MesherHelper& helper,
6838                                                const int           nbSteps,
6839                                                const double        stepSize )
6840 {
6841   if ( data._nbShapesToSmooth == 0 || nbSteps == 0 )
6842     return true; // no shapes needing smoothing
6843
6844   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6845   {
6846     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
6847     if ( //!eos._toSmooth ||  _eosC1 have _toSmooth == false
6848          !eos._hyp.ToSmooth() ||
6849          eos.ShapeType() != TopAbs_FACE ||
6850          eos._edges.empty() )
6851       continue;
6852
6853     bool toSmooth = ( eos._edges[ 0 ]->NbSteps() >= nbSteps+1 );
6854     if ( !toSmooth ) continue;
6855
6856     for ( size_t i = 0; i < eos._edges.size(); ++i )
6857     {
6858       _LayerEdge* edge = eos._edges[i];
6859       if ( !edge->Is( _LayerEdge::SMOOTHED ))
6860         continue;
6861       if ( edge->Is( _LayerEdge::DIFFICULT ) && nbSteps != 1 )
6862         continue;
6863
6864       const gp_XYZ& pPrev = edge->PrevPos();
6865       const gp_XYZ& pLast = edge->_pos.back();
6866       gp_XYZ      stepVec = pLast - pPrev;
6867       double realStepSize = stepVec.Modulus();
6868       if ( realStepSize < numeric_limits<double>::min() )
6869         continue;
6870
6871       edge->_lenFactor = realStepSize / stepSize;
6872       edge->_normal    = stepVec / realStepSize;
6873       edge->Set( _LayerEdge::NORMAL_UPDATED );
6874     }
6875   }
6876
6877   return true;
6878 }
6879
6880 //================================================================================
6881 /*!
6882  * \brief Modify normals of _LayerEdge's on C1 VERTEXes
6883  */
6884 //================================================================================
6885
6886 void _ViscousBuilder::updateNormalsOfC1Vertices( _SolidData& data )
6887 {
6888   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6889   {
6890     _EdgesOnShape& eov = data._edgesOnShape[ iS ];
6891     if ( eov._eosC1.empty() ||
6892          eov.ShapeType() != TopAbs_VERTEX ||
6893          eov._edges.empty() )
6894       continue;
6895
6896     gp_XYZ newNorm   = eov._edges[0]->_normal;
6897     double curThick  = eov._edges[0]->_len * eov._edges[0]->_lenFactor;
6898     bool normChanged = false;
6899
6900     for ( size_t i = 0; i < eov._eosC1.size(); ++i )
6901     {
6902       _EdgesOnShape*   eoe = eov._eosC1[i];
6903       const TopoDS_Edge& e = TopoDS::Edge( eoe->_shape );
6904       const double    eLen = SMESH_Algo::EdgeLength( e );
6905       TopoDS_Shape    oppV = SMESH_MesherHelper::IthVertex( 0, e );
6906       if ( oppV.IsSame( eov._shape ))
6907         oppV = SMESH_MesherHelper::IthVertex( 1, e );
6908       _EdgesOnShape* eovOpp = data.GetShapeEdges( oppV );
6909       if ( !eovOpp || eovOpp->_edges.empty() ) continue;
6910       if ( eov._edges[0]->Is( _LayerEdge::BLOCKED )) continue;
6911
6912       double curThickOpp = eovOpp->_edges[0]->_len * eovOpp->_edges[0]->_lenFactor;
6913       if ( curThickOpp + curThick < eLen )
6914         continue;
6915
6916       double wgt = 2. * curThick / eLen;
6917       newNorm += wgt * eovOpp->_edges[0]->_normal;
6918       normChanged = true;
6919     }
6920     if ( normChanged )
6921     {
6922       eov._edges[0]->SetNormal( newNorm.Normalized() );
6923       eov._edges[0]->Set( _LayerEdge::NORMAL_UPDATED );
6924     }
6925   }
6926 }
6927
6928 //================================================================================
6929 /*!
6930  * \brief Modify normals of _LayerEdge's on _ConvexFace's
6931  */
6932 //================================================================================
6933
6934 bool _ViscousBuilder::updateNormalsOfConvexFaces( _SolidData&         data,
6935                                                   SMESH_MesherHelper& helper,
6936                                                   int                 stepNb )
6937 {
6938   SMESHDS_Mesh* meshDS = helper.GetMeshDS();
6939   bool isOK;
6940
6941   map< TGeomID, _ConvexFace >::iterator id2face = data._convexFaces.begin();
6942   for ( ; id2face != data._convexFaces.end(); ++id2face )
6943   {
6944     _ConvexFace & convFace = (*id2face).second;
6945     if ( convFace._normalsFixed )
6946       continue; // already fixed
6947     if ( convFace.CheckPrisms() )
6948       continue; // nothing to fix
6949
6950     convFace._normalsFixed = true;
6951
6952     BRepAdaptor_Surface surface ( convFace._face, false );
6953     BRepLProp_SLProps   surfProp( surface, 2, 1e-6 );
6954
6955     // check if the convex FACE is of spherical shape
6956
6957     Bnd_B3d centersBox; // bbox of centers of curvature of _LayerEdge's on VERTEXes
6958     Bnd_B3d nodesBox;
6959     gp_Pnt  center;
6960
6961     map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.begin();
6962     for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
6963     {
6964       _EdgesOnShape& eos = *(id2eos->second);
6965       if ( eos.ShapeType() == TopAbs_VERTEX )
6966       {
6967         _LayerEdge* ledge = eos._edges[ 0 ];
6968         if ( convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
6969           centersBox.Add( center );
6970       }
6971       for ( size_t i = 0; i < eos._edges.size(); ++i )
6972         nodesBox.Add( SMESH_TNodeXYZ( eos._edges[ i ]->_nodes[0] ));
6973     }
6974     if ( centersBox.IsVoid() )
6975     {
6976       debugMsg( "Error: centersBox.IsVoid()" );
6977       return false;
6978     }
6979     const bool isSpherical =
6980       ( centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
6981
6982     int nbEdges = helper.Count( convFace._face, TopAbs_EDGE, /*ignoreSame=*/false );
6983     vector < _CentralCurveOnEdge > centerCurves( nbEdges );
6984
6985     if ( isSpherical )
6986     {
6987       // set _LayerEdge::_normal as average of all normals
6988
6989       // WARNING: different density of nodes on EDGEs is not taken into account that
6990       // can lead to an improper new normal
6991
6992       gp_XYZ avgNormal( 0,0,0 );
6993       nbEdges = 0;
6994       id2eos = convFace._subIdToEOS.begin();
6995       for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
6996       {
6997         _EdgesOnShape& eos = *(id2eos->second);
6998         // set data of _CentralCurveOnEdge
6999         if ( eos.ShapeType() == TopAbs_EDGE )
7000         {
7001           _CentralCurveOnEdge& ceCurve = centerCurves[ nbEdges++ ];
7002           ceCurve.SetShapes( TopoDS::Edge( eos._shape ), convFace, data, helper );
7003           if ( !eos._sWOL.IsNull() )
7004             ceCurve._adjFace.Nullify();
7005           else
7006             ceCurve._ledges.insert( ceCurve._ledges.end(),
7007                                     eos._edges.begin(), eos._edges.end());
7008         }
7009         // summarize normals
7010         for ( size_t i = 0; i < eos._edges.size(); ++i )
7011           avgNormal += eos._edges[ i ]->_normal;
7012       }
7013       double normSize = avgNormal.SquareModulus();
7014       if ( normSize < 1e-200 )
7015       {
7016         debugMsg( "updateNormalsOfConvexFaces(): zero avgNormal" );
7017         return false;
7018       }
7019       avgNormal /= Sqrt( normSize );
7020
7021       // compute new _LayerEdge::_cosin on EDGEs
7022       double avgCosin = 0;
7023       int     nbCosin = 0;
7024       gp_Vec inFaceDir;
7025       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7026       {
7027         _CentralCurveOnEdge& ceCurve = centerCurves[ iE ];
7028         if ( ceCurve._adjFace.IsNull() )
7029           continue;
7030         for ( size_t iLE = 0; iLE < ceCurve._ledges.size(); ++iLE )
7031         {
7032           const SMDS_MeshNode* node = ceCurve._ledges[ iLE ]->_nodes[0];
7033           inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
7034           if ( isOK )
7035           {
7036             double angle = inFaceDir.Angle( avgNormal ); // [0,PI]
7037             ceCurve._ledges[ iLE ]->_cosin = Cos( angle );
7038             avgCosin += ceCurve._ledges[ iLE ]->_cosin;
7039             nbCosin++;
7040           }
7041         }
7042       }
7043       if ( nbCosin > 0 )
7044         avgCosin /= nbCosin;
7045
7046       // set _LayerEdge::_normal = avgNormal
7047       id2eos = convFace._subIdToEOS.begin();
7048       for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7049       {
7050         _EdgesOnShape& eos = *(id2eos->second);
7051         if ( eos.ShapeType() != TopAbs_EDGE )
7052           for ( size_t i = 0; i < eos._edges.size(); ++i )
7053             eos._edges[ i ]->_cosin = avgCosin;
7054
7055         for ( size_t i = 0; i < eos._edges.size(); ++i )
7056         {
7057           eos._edges[ i ]->SetNormal( avgNormal );
7058           eos._edges[ i ]->Set( _LayerEdge::NORMAL_UPDATED );
7059         }
7060       }
7061     }
7062     else // if ( isSpherical )
7063     {
7064       // We suppose that centers of curvature at all points of the FACE
7065       // lie on some curve, let's call it "central curve". For all _LayerEdge's
7066       // having a common center of curvature we define the same new normal
7067       // as a sum of normals of _LayerEdge's on EDGEs among them.
7068
7069       // get all centers of curvature for each EDGE
7070
7071       helper.SetSubShape( convFace._face );
7072       _LayerEdge* vertexLEdges[2], **edgeLEdge, **edgeLEdgeEnd;
7073
7074       TopExp_Explorer edgeExp( convFace._face, TopAbs_EDGE );
7075       for ( int iE = 0; edgeExp.More(); edgeExp.Next(), ++iE )
7076       {
7077         const TopoDS_Edge& edge = TopoDS::Edge( edgeExp.Current() );
7078
7079         // set adjacent FACE
7080         centerCurves[ iE ].SetShapes( edge, convFace, data, helper );
7081
7082         // get _LayerEdge's of the EDGE
7083         TGeomID edgeID = meshDS->ShapeToIndex( edge );
7084         _EdgesOnShape* eos = data.GetShapeEdges( edgeID );
7085         if ( !eos || eos->_edges.empty() )
7086         {
7087           // no _LayerEdge's on EDGE, use _LayerEdge's on VERTEXes
7088           for ( int iV = 0; iV < 2; ++iV )
7089           {
7090             TopoDS_Vertex v = helper.IthVertex( iV, edge );
7091             TGeomID     vID = meshDS->ShapeToIndex( v );
7092             eos = data.GetShapeEdges( vID );
7093             vertexLEdges[ iV ] = eos->_edges[ 0 ];
7094           }
7095           edgeLEdge    = &vertexLEdges[0];
7096           edgeLEdgeEnd = edgeLEdge + 2;
7097
7098           centerCurves[ iE ]._adjFace.Nullify();
7099         }
7100         else
7101         {
7102           if ( ! eos->_toSmooth )
7103             data.SortOnEdge( edge, eos->_edges );
7104           edgeLEdge    = &eos->_edges[ 0 ];
7105           edgeLEdgeEnd = edgeLEdge + eos->_edges.size();
7106           vertexLEdges[0] = eos->_edges.front()->_2neibors->_edges[0];
7107           vertexLEdges[1] = eos->_edges.back() ->_2neibors->_edges[1];
7108
7109           if ( ! eos->_sWOL.IsNull() )
7110             centerCurves[ iE ]._adjFace.Nullify();
7111         }
7112
7113         // Get curvature centers
7114
7115         centersBox.Clear();
7116
7117         if ( edgeLEdge[0]->IsOnEdge() &&
7118              convFace.GetCenterOfCurvature( vertexLEdges[0], surfProp, helper, center ))
7119         { // 1st VERTEX
7120           centerCurves[ iE ].Append( center, vertexLEdges[0] );
7121           centersBox.Add( center );
7122         }
7123         for ( ; edgeLEdge < edgeLEdgeEnd; ++edgeLEdge )
7124           if ( convFace.GetCenterOfCurvature( *edgeLEdge, surfProp, helper, center ))
7125           { // EDGE or VERTEXes
7126             centerCurves[ iE ].Append( center, *edgeLEdge );
7127             centersBox.Add( center );
7128           }
7129         if ( edgeLEdge[-1]->IsOnEdge() &&
7130              convFace.GetCenterOfCurvature( vertexLEdges[1], surfProp, helper, center ))
7131         { // 2nd VERTEX
7132           centerCurves[ iE ].Append( center, vertexLEdges[1] );
7133           centersBox.Add( center );
7134         }
7135         centerCurves[ iE ]._isDegenerated =
7136           ( centersBox.IsVoid() || centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
7137
7138       } // loop on EDGES of convFace._face to set up data of centerCurves
7139
7140       // Compute new normals for _LayerEdge's on EDGEs
7141
7142       double avgCosin = 0;
7143       int     nbCosin = 0;
7144       gp_Vec inFaceDir;
7145       for ( size_t iE1 = 0; iE1 < centerCurves.size(); ++iE1 )
7146       {
7147         _CentralCurveOnEdge& ceCurve = centerCurves[ iE1 ];
7148         if ( ceCurve._isDegenerated )
7149           continue;
7150         const vector< gp_Pnt >& centers = ceCurve._curvaCenters;
7151         vector< gp_XYZ > &   newNormals = ceCurve._normals;
7152         for ( size_t iC1 = 0; iC1 < centers.size(); ++iC1 )
7153         {
7154           isOK = false;
7155           for ( size_t iE2 = 0; iE2 < centerCurves.size() && !isOK; ++iE2 )
7156           {
7157             if ( iE1 != iE2 )
7158               isOK = centerCurves[ iE2 ].FindNewNormal( centers[ iC1 ], newNormals[ iC1 ]);
7159           }
7160           if ( isOK && !ceCurve._adjFace.IsNull() )
7161           {
7162             // compute new _LayerEdge::_cosin
7163             const SMDS_MeshNode* node = ceCurve._ledges[ iC1 ]->_nodes[0];
7164             inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
7165             if ( isOK )
7166             {
7167               double angle = inFaceDir.Angle( newNormals[ iC1 ] ); // [0,PI]
7168               ceCurve._ledges[ iC1 ]->_cosin = Cos( angle );
7169               avgCosin += ceCurve._ledges[ iC1 ]->_cosin;
7170               nbCosin++;
7171             }
7172           }
7173         }
7174       }
7175       // set new normals to _LayerEdge's of NOT degenerated central curves
7176       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7177       {
7178         if ( centerCurves[ iE ]._isDegenerated )
7179           continue;
7180         for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
7181         {
7182           centerCurves[ iE ]._ledges[ iLE ]->SetNormal( centerCurves[ iE ]._normals[ iLE ]);
7183           centerCurves[ iE ]._ledges[ iLE ]->Set( _LayerEdge::NORMAL_UPDATED );
7184         }
7185       }
7186       // set new normals to _LayerEdge's of     degenerated central curves
7187       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7188       {
7189         if ( !centerCurves[ iE ]._isDegenerated ||
7190              centerCurves[ iE ]._ledges.size() < 3 )
7191           continue;
7192         // new normal is an average of new normals at VERTEXes that
7193         // was computed on non-degenerated _CentralCurveOnEdge's
7194         gp_XYZ newNorm = ( centerCurves[ iE ]._ledges.front()->_normal +
7195                            centerCurves[ iE ]._ledges.back ()->_normal );
7196         double sz = newNorm.Modulus();
7197         if ( sz < 1e-200 )
7198           continue;
7199         newNorm /= sz;
7200         double newCosin = ( 0.5 * centerCurves[ iE ]._ledges.front()->_cosin +
7201                             0.5 * centerCurves[ iE ]._ledges.back ()->_cosin );
7202         for ( size_t iLE = 1, nb = centerCurves[ iE ]._ledges.size() - 1; iLE < nb; ++iLE )
7203         {
7204           centerCurves[ iE ]._ledges[ iLE ]->SetNormal( newNorm );
7205           centerCurves[ iE ]._ledges[ iLE ]->_cosin   = newCosin;
7206           centerCurves[ iE ]._ledges[ iLE ]->Set( _LayerEdge::NORMAL_UPDATED );
7207         }
7208       }
7209
7210       // Find new normals for _LayerEdge's based on FACE
7211
7212       if ( nbCosin > 0 )
7213         avgCosin /= nbCosin;
7214       const TGeomID faceID = meshDS->ShapeToIndex( convFace._face );
7215       map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.find( faceID );
7216       if ( id2eos != convFace._subIdToEOS.end() )
7217       {
7218         int iE = 0;
7219         gp_XYZ newNorm;
7220         _EdgesOnShape& eos = * ( id2eos->second );
7221         for ( size_t i = 0; i < eos._edges.size(); ++i )
7222         {
7223           _LayerEdge* ledge = eos._edges[ i ];
7224           if ( !convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
7225             continue;
7226           for ( size_t i = 0; i < centerCurves.size(); ++i, ++iE )
7227           {
7228             iE = iE % centerCurves.size();
7229             if ( centerCurves[ iE ]._isDegenerated )
7230               continue;
7231             newNorm.SetCoord( 0,0,0 );
7232             if ( centerCurves[ iE ].FindNewNormal( center, newNorm ))
7233             {
7234               ledge->SetNormal( newNorm );
7235               ledge->_cosin  = avgCosin;
7236               ledge->Set( _LayerEdge::NORMAL_UPDATED );
7237               break;
7238             }
7239           }
7240         }
7241       }
7242
7243     } // not a quasi-spherical FACE
7244
7245     // Update _LayerEdge's data according to a new normal
7246
7247     dumpFunction(SMESH_Comment("updateNormalsOfConvexFaces")<<data._index
7248                  <<"_F"<<meshDS->ShapeToIndex( convFace._face ));
7249
7250     id2eos = convFace._subIdToEOS.begin();
7251     for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7252     {
7253       _EdgesOnShape& eos = * ( id2eos->second );
7254       for ( size_t i = 0; i < eos._edges.size(); ++i )
7255       {
7256         _LayerEdge* & ledge = eos._edges[ i ];
7257         double len = ledge->_len;
7258         ledge->InvalidateStep( stepNb + 1, eos, /*restoreLength=*/true );
7259         ledge->SetCosin( ledge->_cosin );
7260         ledge->SetNewLength( len, eos, helper );
7261       }
7262       if ( eos.ShapeType() != TopAbs_FACE )
7263         for ( size_t i = 0; i < eos._edges.size(); ++i )
7264         {
7265           _LayerEdge* ledge = eos._edges[ i ];
7266           for ( size_t iN = 0; iN < ledge->_neibors.size(); ++iN )
7267           {
7268             _LayerEdge* neibor = ledge->_neibors[iN];
7269             if ( neibor->_nodes[0]->GetPosition()->GetDim() == 2 )
7270             {
7271               neibor->Set( _LayerEdge::NEAR_BOUNDARY );
7272               neibor->Set( _LayerEdge::MOVED );
7273               neibor->SetSmooLen( neibor->_len );
7274             }
7275           }
7276         }
7277     } // loop on sub-shapes of convFace._face
7278
7279     // Find FACEs adjacent to convFace._face that got necessity to smooth
7280     // as a result of normals modification
7281
7282     set< _EdgesOnShape* > adjFacesToSmooth;
7283     for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7284     {
7285       if ( centerCurves[ iE ]._adjFace.IsNull() ||
7286            centerCurves[ iE ]._adjFaceToSmooth )
7287         continue;
7288       for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
7289       {
7290         if ( centerCurves[ iE ]._ledges[ iLE ]->_cosin > theMinSmoothCosin )
7291         {
7292           adjFacesToSmooth.insert( data.GetShapeEdges( centerCurves[ iE ]._adjFace ));
7293           break;
7294         }
7295       }
7296     }
7297     data.AddShapesToSmooth( adjFacesToSmooth );
7298
7299     dumpFunctionEnd();
7300
7301
7302   } // loop on data._convexFaces
7303
7304   return true;
7305 }
7306
7307 //================================================================================
7308 /*!
7309  * \brief Finds a center of curvature of a surface at a _LayerEdge
7310  */
7311 //================================================================================
7312
7313 bool _ConvexFace::GetCenterOfCurvature( _LayerEdge*         ledge,
7314                                         BRepLProp_SLProps&  surfProp,
7315                                         SMESH_MesherHelper& helper,
7316                                         gp_Pnt &            center ) const
7317 {
7318   gp_XY uv = helper.GetNodeUV( _face, ledge->_nodes[0] );
7319   surfProp.SetParameters( uv.X(), uv.Y() );
7320   if ( !surfProp.IsCurvatureDefined() )
7321     return false;
7322
7323   const double oriFactor = ( _face.Orientation() == TopAbs_REVERSED ? +1. : -1. );
7324   double surfCurvatureMax = surfProp.MaxCurvature() * oriFactor;
7325   double surfCurvatureMin = surfProp.MinCurvature() * oriFactor;
7326   if ( surfCurvatureMin > surfCurvatureMax )
7327     center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMin * oriFactor );
7328   else
7329     center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMax * oriFactor );
7330
7331   return true;
7332 }
7333
7334 //================================================================================
7335 /*!
7336  * \brief Check that prisms are not distorted
7337  */
7338 //================================================================================
7339
7340 bool _ConvexFace::CheckPrisms() const
7341 {
7342   double vol = 0;
7343   for ( size_t i = 0; i < _simplexTestEdges.size(); ++i )
7344   {
7345     const _LayerEdge* edge = _simplexTestEdges[i];
7346     SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
7347     for ( size_t j = 0; j < edge->_simplices.size(); ++j )
7348       if ( !edge->_simplices[j].IsForward( edge->_nodes[0], tgtXYZ, vol ))
7349       {
7350         debugMsg( "Bad simplex of _simplexTestEdges ("
7351                   << " "<< edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
7352                   << " "<< edge->_simplices[j]._nPrev->GetID()
7353                   << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
7354         return false;
7355       }
7356   }
7357   return true;
7358 }
7359
7360 //================================================================================
7361 /*!
7362  * \brief Try to compute a new normal by interpolating normals of _LayerEdge's
7363  *        stored in this _CentralCurveOnEdge.
7364  *  \param [in] center - curvature center of a point of another _CentralCurveOnEdge.
7365  *  \param [in,out] newNormal - current normal at this point, to be redefined
7366  *  \return bool - true if succeeded.
7367  */
7368 //================================================================================
7369
7370 bool _CentralCurveOnEdge::FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal )
7371 {
7372   if ( this->_isDegenerated )
7373     return false;
7374
7375   // find two centers the given one lies between
7376
7377   for ( size_t i = 0, nb = _curvaCenters.size()-1;  i < nb;  ++i )
7378   {
7379     double sl2 = 1.001 * _segLength2[ i ];
7380
7381     double d1 = center.SquareDistance( _curvaCenters[ i ]);
7382     if ( d1 > sl2 )
7383       continue;
7384     
7385     double d2 = center.SquareDistance( _curvaCenters[ i+1 ]);
7386     if ( d2 > sl2 || d2 + d1 < 1e-100 )
7387       continue;
7388
7389     d1 = Sqrt( d1 );
7390     d2 = Sqrt( d2 );
7391     double r = d1 / ( d1 + d2 );
7392     gp_XYZ norm = (( 1. - r ) * _ledges[ i   ]->_normal +
7393                    (      r ) * _ledges[ i+1 ]->_normal );
7394     norm.Normalize();
7395
7396     newNormal += norm;
7397     double sz = newNormal.Modulus();
7398     if ( sz < 1e-200 )
7399       break;
7400     newNormal /= sz;
7401     return true;
7402   }
7403   return false;
7404 }
7405
7406 //================================================================================
7407 /*!
7408  * \brief Set shape members
7409  */
7410 //================================================================================
7411
7412 void _CentralCurveOnEdge::SetShapes( const TopoDS_Edge&  edge,
7413                                      const _ConvexFace&  convFace,
7414                                      _SolidData&         data,
7415                                      SMESH_MesherHelper& helper)
7416 {
7417   _edge = edge;
7418
7419   PShapeIteratorPtr fIt = helper.GetAncestors( edge, *helper.GetMesh(), TopAbs_FACE );
7420   while ( const TopoDS_Shape* F = fIt->next())
7421     if ( !convFace._face.IsSame( *F ))
7422     {
7423       _adjFace = TopoDS::Face( *F );
7424       _adjFaceToSmooth = false;
7425       // _adjFace already in a smoothing queue ?
7426       if ( _EdgesOnShape* eos = data.GetShapeEdges( _adjFace ))
7427         _adjFaceToSmooth = eos->_toSmooth;
7428       break;
7429     }
7430 }
7431
7432 //================================================================================
7433 /*!
7434  * \brief Looks for intersection of it's last segment with faces
7435  *  \param distance - returns shortest distance from the last node to intersection
7436  */
7437 //================================================================================
7438
7439 bool _LayerEdge::FindIntersection( SMESH_ElementSearcher&   searcher,
7440                                    double &                 distance,
7441                                    const double&            epsilon,
7442                                    _EdgesOnShape&           eos,
7443                                    const SMDS_MeshElement** intFace)
7444 {
7445   vector< const SMDS_MeshElement* > suspectFaces;
7446   double segLen;
7447   gp_Ax1 lastSegment = LastSegment( segLen, eos );
7448   searcher.GetElementsNearLine( lastSegment, SMDSAbs_Face, suspectFaces );
7449
7450   bool segmentIntersected = false;
7451   distance = Precision::Infinite();
7452   int iFace = -1; // intersected face
7453   for ( size_t j = 0 ; j < suspectFaces.size() /*&& !segmentIntersected*/; ++j )
7454   {
7455     const SMDS_MeshElement* face = suspectFaces[j];
7456     if ( face->GetNodeIndex( _nodes.back() ) >= 0 ||
7457          face->GetNodeIndex( _nodes[0]     ) >= 0 )
7458       continue; // face sharing _LayerEdge node
7459     const int nbNodes = face->NbCornerNodes();
7460     bool intFound = false;
7461     double dist;
7462     SMDS_MeshElement::iterator nIt = face->begin_nodes();
7463     if ( nbNodes == 3 )
7464     {
7465       intFound = SegTriaInter( lastSegment, *nIt++, *nIt++, *nIt++, dist, epsilon );
7466     }
7467     else
7468     {
7469       const SMDS_MeshNode* tria[3];
7470       tria[0] = *nIt++;
7471       tria[1] = *nIt++;
7472       for ( int n2 = 2; n2 < nbNodes && !intFound; ++n2 )
7473       {
7474         tria[2] = *nIt++;
7475         intFound = SegTriaInter(lastSegment, tria[0], tria[1], tria[2], dist, epsilon );
7476         tria[1] = tria[2];
7477       }
7478     }
7479     if ( intFound )
7480     {
7481       if ( dist < segLen*(1.01) && dist > -(_len*_lenFactor-segLen) )
7482         segmentIntersected = true;
7483       if ( distance > dist )
7484         distance = dist, iFace = j;
7485     }
7486   }
7487   if ( intFace ) *intFace = ( iFace != -1 ) ? suspectFaces[iFace] : 0;
7488
7489   distance -= segLen;
7490
7491   if ( segmentIntersected )
7492   {
7493 #ifdef __myDEBUG
7494     SMDS_MeshElement::iterator nIt = suspectFaces[iFace]->begin_nodes();
7495     gp_XYZ intP( lastSegment.Location().XYZ() + lastSegment.Direction().XYZ() * ( distance+segLen ));
7496     cout << "nodes: tgt " << _nodes.back()->GetID() << " src " << _nodes[0]->GetID()
7497          << ", intersection with face ("
7498          << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
7499          << ") at point (" << intP.X() << ", " << intP.Y() << ", " << intP.Z()
7500          << ") distance = " << distance << endl;
7501 #endif
7502   }
7503
7504   return segmentIntersected;
7505 }
7506
7507 //================================================================================
7508 /*!
7509  * \brief Returns a point used to check orientation of _simplices
7510  */
7511 //================================================================================
7512
7513 gp_XYZ _LayerEdge::PrevCheckPos( _EdgesOnShape* eos ) const
7514 {
7515   size_t i = Is( NORMAL_UPDATED ) ? _pos.size()-2 : 0;
7516
7517   if ( !eos || eos->_sWOL.IsNull() )
7518     return _pos[ i ];
7519
7520   if ( eos->SWOLType() == TopAbs_EDGE )
7521   {
7522     return BRepAdaptor_Curve( TopoDS::Edge( eos->_sWOL )).Value( _pos[i].X() ).XYZ();
7523   }
7524   //else //  TopAbs_FACE
7525
7526   return BRepAdaptor_Surface( TopoDS::Face( eos->_sWOL )).Value(_pos[i].X(), _pos[i].Y() ).XYZ();
7527 }
7528
7529 //================================================================================
7530 /*!
7531  * \brief Returns size and direction of the last segment
7532  */
7533 //================================================================================
7534
7535 gp_Ax1 _LayerEdge::LastSegment(double& segLen, _EdgesOnShape& eos) const
7536 {
7537   // find two non-coincident positions
7538   gp_XYZ orig = _pos.back();
7539   gp_XYZ vec;
7540   int iPrev = _pos.size() - 2;
7541   //const double tol = ( _len > 0 ) ? 0.3*_len : 1e-100; // adjusted for IPAL52478 + PAL22576
7542   const double tol = ( _len > 0 ) ? ( 1e-6 * _len ) : 1e-100;
7543   while ( iPrev >= 0 )
7544   {
7545     vec = orig - _pos[iPrev];
7546     if ( vec.SquareModulus() > tol*tol )
7547       break;
7548     else
7549       iPrev--;
7550   }
7551
7552   // make gp_Ax1
7553   gp_Ax1 segDir;
7554   if ( iPrev < 0 )
7555   {
7556     segDir.SetLocation( SMESH_TNodeXYZ( _nodes[0] ));
7557     segDir.SetDirection( _normal );
7558     segLen = 0;
7559   }
7560   else
7561   {
7562     gp_Pnt pPrev = _pos[ iPrev ];
7563     if ( !eos._sWOL.IsNull() )
7564     {
7565       TopLoc_Location loc;
7566       if ( eos.SWOLType() == TopAbs_EDGE )
7567       {
7568         double f,l;
7569         Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eos._sWOL ), loc, f,l);
7570         pPrev = curve->Value( pPrev.X() ).Transformed( loc );
7571       }
7572       else
7573       {
7574         Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face( eos._sWOL ), loc );
7575         pPrev = surface->Value( pPrev.X(), pPrev.Y() ).Transformed( loc );
7576       }
7577       vec = SMESH_TNodeXYZ( _nodes.back() ) - pPrev.XYZ();
7578     }
7579     segDir.SetLocation( pPrev );
7580     segDir.SetDirection( vec );
7581     segLen = vec.Modulus();
7582   }
7583
7584   return segDir;
7585 }
7586
7587 //================================================================================
7588 /*!
7589  * \brief Return the last position of the target node on a FACE. 
7590  *  \param [in] F - the FACE this _LayerEdge is inflated along
7591  *  \return gp_XY - result UV
7592  */
7593 //================================================================================
7594
7595 gp_XY _LayerEdge::LastUV( const TopoDS_Face& F, _EdgesOnShape& eos ) const
7596 {
7597   if ( F.IsSame( eos._sWOL )) // F is my FACE
7598     return gp_XY( _pos.back().X(), _pos.back().Y() );
7599
7600   if ( eos.SWOLType() != TopAbs_EDGE ) // wrong call
7601     return gp_XY( 1e100, 1e100 );
7602
7603   // _sWOL is EDGE of F; _pos.back().X() is the last U on the EDGE
7604   double f, l, u = _pos.back().X();
7605   Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( TopoDS::Edge(eos._sWOL), F, f,l);
7606   if ( !C2d.IsNull() && f <= u && u <= l )
7607     return C2d->Value( u ).XY();
7608
7609   return gp_XY( 1e100, 1e100 );
7610 }
7611
7612 //================================================================================
7613 /*!
7614  * \brief Test intersection of the last segment with a given triangle
7615  *   using Moller-Trumbore algorithm
7616  * Intersection is detected if distance to intersection is less than _LayerEdge._len
7617  */
7618 //================================================================================
7619
7620 bool _LayerEdge::SegTriaInter( const gp_Ax1& lastSegment,
7621                                const gp_XYZ& vert0,
7622                                const gp_XYZ& vert1,
7623                                const gp_XYZ& vert2,
7624                                double&       t,
7625                                const double& EPSILON) const
7626 {
7627   const gp_Pnt& orig = lastSegment.Location();
7628   const gp_Dir& dir  = lastSegment.Direction();
7629
7630   /* calculate distance from vert0 to ray origin */
7631   //gp_XYZ tvec = orig.XYZ() - vert0;
7632
7633   //if ( tvec * dir > EPSILON )
7634     // intersected face is at back side of the temporary face this _LayerEdge belongs to
7635     //return false;
7636
7637   gp_XYZ edge1 = vert1 - vert0;
7638   gp_XYZ edge2 = vert2 - vert0;
7639
7640   /* begin calculating determinant - also used to calculate U parameter */
7641   gp_XYZ pvec = dir.XYZ() ^ edge2;
7642
7643   /* if determinant is near zero, ray lies in plane of triangle */
7644   double det = edge1 * pvec;
7645
7646   const double ANGL_EPSILON = 1e-12;
7647   if ( det > -ANGL_EPSILON && det < ANGL_EPSILON )
7648     return false;
7649
7650   /* calculate distance from vert0 to ray origin */
7651   gp_XYZ tvec = orig.XYZ() - vert0;
7652
7653   /* calculate U parameter and test bounds */
7654   double u = ( tvec * pvec ) / det;
7655   //if (u < 0.0 || u > 1.0)
7656   if ( u < -EPSILON || u > 1.0 + EPSILON )
7657     return false;
7658
7659   /* prepare to test V parameter */
7660   gp_XYZ qvec = tvec ^ edge1;
7661
7662   /* calculate V parameter and test bounds */
7663   double v = (dir.XYZ() * qvec) / det;
7664   //if ( v < 0.0 || u + v > 1.0 )
7665   if ( v < -EPSILON || u + v > 1.0 + EPSILON )
7666     return false;
7667
7668   /* calculate t, ray intersects triangle */
7669   t = (edge2 * qvec) / det;
7670
7671   //return true;
7672   return t > 0.;
7673 }
7674
7675 //================================================================================
7676 /*!
7677  * \brief _LayerEdge, located at a concave VERTEX of a FACE, moves target nodes of
7678  *        neighbor _LayerEdge's by it's own inflation vector.
7679  *  \param [in] eov - EOS of the VERTEX
7680  *  \param [in] eos - EOS of the FACE
7681  *  \param [in] step - inflation step
7682  *  \param [in,out] badSmooEdges - not untangled _LayerEdge's
7683  */
7684 //================================================================================
7685
7686 void _LayerEdge::MoveNearConcaVer( const _EdgesOnShape*    eov,
7687                                    const _EdgesOnShape*    eos,
7688                                    const int               step,
7689                                    vector< _LayerEdge* > & badSmooEdges )
7690 {
7691   // check if any of _neibors is in badSmooEdges
7692   if ( std::find_first_of( _neibors.begin(), _neibors.end(),
7693                            badSmooEdges.begin(), badSmooEdges.end() ) == _neibors.end() )
7694     return;
7695
7696   // get all edges to move
7697
7698   set< _LayerEdge* > edges;
7699
7700   // find a distance between _LayerEdge on VERTEX and its neighbors
7701   gp_XYZ  curPosV = SMESH_TNodeXYZ( _nodes.back() );
7702   double dist2 = 0;
7703   for ( size_t i = 0; i < _neibors.size(); ++i )
7704   {
7705     _LayerEdge* nEdge = _neibors[i];
7706     if ( nEdge->_nodes[0]->getshapeId() == eos->_shapeID )
7707     {
7708       edges.insert( nEdge );
7709       dist2 = Max( dist2, ( curPosV - nEdge->_pos.back() ).SquareModulus() );
7710     }
7711   }
7712   // add _LayerEdge's close to curPosV
7713   size_t nbE;
7714   do {
7715     nbE = edges.size();
7716     for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
7717     {
7718       _LayerEdge* edgeF = *e;
7719       for ( size_t i = 0; i < edgeF->_neibors.size(); ++i )
7720       {
7721         _LayerEdge* nEdge = edgeF->_neibors[i];
7722         if ( nEdge->_nodes[0]->getshapeId() == eos->_shapeID &&
7723              dist2 > ( curPosV - nEdge->_pos.back() ).SquareModulus() )
7724           edges.insert( nEdge );
7725       }
7726     }
7727   }
7728   while ( nbE < edges.size() );
7729
7730   // move the target node of the got edges
7731
7732   gp_XYZ prevPosV = PrevPos();
7733   if ( eov->SWOLType() == TopAbs_EDGE )
7734   {
7735     BRepAdaptor_Curve curve ( TopoDS::Edge( eov->_sWOL ));
7736     prevPosV = curve.Value( prevPosV.X() ).XYZ();
7737   }
7738   else if ( eov->SWOLType() == TopAbs_FACE )
7739   {
7740     BRepAdaptor_Surface surface( TopoDS::Face( eov->_sWOL ));
7741     prevPosV = surface.Value( prevPosV.X(), prevPosV.Y() ).XYZ();
7742   }
7743
7744   SMDS_FacePosition* fPos;
7745   //double r = 1. - Min( 0.9, step / 10. );
7746   for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
7747   {
7748     _LayerEdge*       edgeF = *e;
7749     const gp_XYZ     prevVF = edgeF->PrevPos() - prevPosV;
7750     const gp_XYZ    newPosF = curPosV + prevVF;
7751     SMDS_MeshNode* tgtNodeF = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
7752     tgtNodeF->setXYZ( newPosF.X(), newPosF.Y(), newPosF.Z() );
7753     edgeF->_pos.back() = newPosF;
7754     dumpMoveComm( tgtNodeF, "MoveNearConcaVer" ); // debug
7755
7756     // set _curvature to make edgeF updated by putOnOffsetSurface()
7757     if ( !edgeF->_curvature )
7758       if (( fPos = dynamic_cast<SMDS_FacePosition*>( edgeF->_nodes[0]->GetPosition() )))
7759       {
7760         edgeF->_curvature = new _Curvature;
7761         edgeF->_curvature->_r = 0;
7762         edgeF->_curvature->_k = 0;
7763         edgeF->_curvature->_h2lenRatio = 0;
7764         edgeF->_curvature->_uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
7765       }
7766   }
7767   // gp_XYZ inflationVec( SMESH_TNodeXYZ( _nodes.back() ) -
7768   //                      SMESH_TNodeXYZ( _nodes[0]    ));
7769   // for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
7770   // {
7771   //   _LayerEdge*      edgeF = *e;
7772   //   gp_XYZ          newPos = SMESH_TNodeXYZ( edgeF->_nodes[0] ) + inflationVec;
7773   //   SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
7774   //   tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7775   //   edgeF->_pos.back() = newPosF;
7776   //   dumpMoveComm( tgtNode, "MoveNearConcaVer" ); // debug
7777   // }
7778
7779   // smooth _LayerEdge's around moved nodes
7780   //size_t nbBadBefore = badSmooEdges.size();
7781   for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
7782   {
7783     _LayerEdge* edgeF = *e;
7784     for ( size_t j = 0; j < edgeF->_neibors.size(); ++j )
7785       if ( edgeF->_neibors[j]->_nodes[0]->getshapeId() == eos->_shapeID )
7786         //&& !edges.count( edgeF->_neibors[j] ))
7787       {
7788         _LayerEdge* edgeFN = edgeF->_neibors[j];
7789         edgeFN->Unset( SMOOTHED );
7790         int nbBad = edgeFN->Smooth( step, /*isConcaFace=*/true, /*findBest=*/true );
7791         // if ( nbBad > 0 )
7792         // {
7793         //   gp_XYZ         newPos = SMESH_TNodeXYZ( edgeFN->_nodes[0] ) + inflationVec;
7794         //   const gp_XYZ& prevPos = edgeFN->_pos[ edgeFN->_pos.size()-2 ];
7795         //   int        nbBadAfter = edgeFN->_simplices.size();
7796         //   double vol;
7797         //   for ( size_t iS = 0; iS < edgeFN->_simplices.size(); ++iS )
7798         //   {
7799         //     nbBadAfter -= edgeFN->_simplices[iS].IsForward( &prevPos, &newPos, vol );
7800         //   }
7801         //   if ( nbBadAfter <= nbBad )
7802         //   {
7803         //     SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeFN->_nodes.back() );
7804         //     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7805         //     edgeF->_pos.back() = newPosF;
7806         //     dumpMoveComm( tgtNode, "MoveNearConcaVer 2" ); // debug
7807         //     nbBad = nbBadAfter;
7808         //   }
7809         // }
7810         if ( nbBad > 0 )
7811           badSmooEdges.push_back( edgeFN );
7812       }
7813   }
7814     // move a bit not smoothed around moved nodes
7815   //   for ( size_t i = nbBadBefore; i < badSmooEdges.size(); ++i )
7816   //   {
7817   //   _LayerEdge*      edgeF = badSmooEdges[i];
7818   //   SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
7819   //   gp_XYZ         newPos1 = SMESH_TNodeXYZ( edgeF->_nodes[0] ) + inflationVec;
7820   //   gp_XYZ         newPos2 = 0.5 * ( newPos1 + SMESH_TNodeXYZ( tgtNode ));
7821   //   tgtNode->setXYZ( newPos2.X(), newPos2.Y(), newPos2.Z() );
7822   //   edgeF->_pos.back() = newPosF;
7823   //   dumpMoveComm( tgtNode, "MoveNearConcaVer 2" ); // debug
7824   // }
7825 }
7826
7827 //================================================================================
7828 /*!
7829  * \brief Perform smooth of _LayerEdge's based on EDGE's
7830  *  \retval bool - true if node has been moved
7831  */
7832 //================================================================================
7833
7834 bool _LayerEdge::SmoothOnEdge(Handle(ShapeAnalysis_Surface)& surface,
7835                               const TopoDS_Face&             F,
7836                               SMESH_MesherHelper&            helper)
7837 {
7838   ASSERT( IsOnEdge() );
7839
7840   SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
7841   SMESH_TNodeXYZ oldPos( tgtNode );
7842   double dist01, distNewOld;
7843   
7844   SMESH_TNodeXYZ p0( _2neibors->tgtNode(0));
7845   SMESH_TNodeXYZ p1( _2neibors->tgtNode(1));
7846   dist01 = p0.Distance( _2neibors->tgtNode(1) );
7847
7848   gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
7849   double lenDelta = 0;
7850   if ( _curvature )
7851   {
7852     //lenDelta = _curvature->lenDelta( _len );
7853     lenDelta = _curvature->lenDeltaByDist( dist01 );
7854     newPos.ChangeCoord() += _normal * lenDelta;
7855   }
7856
7857   distNewOld = newPos.Distance( oldPos );
7858
7859   if ( F.IsNull() )
7860   {
7861     if ( _2neibors->_plnNorm )
7862     {
7863       // put newPos on the plane defined by source node and _plnNorm
7864       gp_XYZ new2src = SMESH_TNodeXYZ( _nodes[0] ) - newPos.XYZ();
7865       double new2srcProj = (*_2neibors->_plnNorm) * new2src;
7866       newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
7867     }
7868     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7869     _pos.back() = newPos.XYZ();
7870   }
7871   else
7872   {
7873     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7874     gp_XY uv( Precision::Infinite(), 0 );
7875     helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
7876     _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
7877
7878     newPos = surface->Value( uv );
7879     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7880   }
7881
7882   // commented for IPAL0052478
7883   // if ( _curvature && lenDelta < 0 )
7884   // {
7885   //   gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
7886   //   _len -= prevPos.Distance( oldPos );
7887   //   _len += prevPos.Distance( newPos );
7888   // }
7889   bool moved = distNewOld > dist01/50;
7890   //if ( moved )
7891   dumpMove( tgtNode ); // debug
7892
7893   return moved;
7894 }
7895
7896 //================================================================================
7897 /*!
7898  * \brief Perform 3D smooth of nodes inflated from FACE. No check of validity
7899  */
7900 //================================================================================
7901
7902 void _LayerEdge::SmoothWoCheck()
7903 {
7904   if ( Is( DIFFICULT ))
7905     return;
7906
7907   bool moved = Is( SMOOTHED );
7908   for ( size_t i = 0; i < _neibors.size()  &&  !moved; ++i )
7909     moved = _neibors[i]->Is( SMOOTHED );
7910   if ( !moved )
7911     return;
7912
7913   gp_XYZ newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
7914
7915   SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
7916   n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
7917   _pos.back() = newPos;
7918
7919   dumpMoveComm( n, SMESH_Comment("No check - ") << _funNames[ smooFunID() ]);
7920 }
7921
7922 //================================================================================
7923 /*!
7924  * \brief Checks validity of _neibors on EDGEs and VERTEXes
7925  */
7926 //================================================================================
7927
7928 int _LayerEdge::CheckNeiborsOnBoundary( vector< _LayerEdge* >* badNeibors, bool * needSmooth )
7929 {
7930   if ( ! Is( NEAR_BOUNDARY ))
7931     return 0;
7932
7933   int nbBad = 0;
7934   double vol;
7935   for ( size_t iN = 0; iN < _neibors.size(); ++iN )
7936   {
7937     _LayerEdge* eN = _neibors[iN];
7938     if ( eN->_nodes[0]->getshapeId() == _nodes[0]->getshapeId() )
7939       continue;
7940     if ( needSmooth )
7941       *needSmooth |= ( eN->Is( _LayerEdge::BLOCKED ) ||
7942                        eN->Is( _LayerEdge::NORMAL_UPDATED ) ||
7943                        eN->_pos.size() != _pos.size() );
7944
7945     SMESH_TNodeXYZ curPosN ( eN->_nodes.back() );
7946     SMESH_TNodeXYZ prevPosN( eN->_nodes[0] );
7947     for ( size_t i = 0; i < eN->_simplices.size(); ++i )
7948       if ( eN->_nodes.size() > 1 &&
7949            eN->_simplices[i].Includes( _nodes.back() ) &&
7950            !eN->_simplices[i].IsForward( &prevPosN, &curPosN, vol ))
7951       {
7952         ++nbBad;
7953         if ( badNeibors )
7954         {
7955           badNeibors->push_back( eN );
7956           debugMsg("Bad boundary simplex ( "
7957                    << " "<< eN->_nodes[0]->GetID()
7958                    << " "<< eN->_nodes.back()->GetID()
7959                    << " "<< eN->_simplices[i]._nPrev->GetID()
7960                    << " "<< eN->_simplices[i]._nNext->GetID() << " )" );
7961         }
7962         else
7963         {
7964           break;
7965         }
7966       }
7967   }
7968   return nbBad;
7969 }
7970
7971 //================================================================================
7972 /*!
7973  * \brief Perform 'smart' 3D smooth of nodes inflated from FACE
7974  *  \retval int - nb of bad simplices around this _LayerEdge
7975  */
7976 //================================================================================
7977
7978 int _LayerEdge::Smooth(const int step, bool findBest, vector< _LayerEdge* >& toSmooth )
7979 {
7980   if ( !Is( MOVED ) || Is( SMOOTHED ) || Is( BLOCKED ))
7981     return 0; // shape of simplices not changed
7982   if ( _simplices.size() < 2 )
7983     return 0; // _LayerEdge inflated along EDGE or FACE
7984
7985   if ( Is( DIFFICULT )) // || Is( ON_CONCAVE_FACE )
7986     findBest = true;
7987
7988   const gp_XYZ& curPos  = _pos.back();
7989   const gp_XYZ& prevPos = _pos[0]; //PrevPos();
7990
7991   // quality metrics (orientation) of tetras around _tgtNode
7992   int nbOkBefore = 0;
7993   double vol, minVolBefore = 1e100;
7994   for ( size_t i = 0; i < _simplices.size(); ++i )
7995   {
7996     nbOkBefore += _simplices[i].IsForward( &prevPos, &curPos, vol );
7997     minVolBefore = Min( minVolBefore, vol );
7998   }
7999   int nbBad = _simplices.size() - nbOkBefore;
8000
8001   bool bndNeedSmooth = false;
8002   if ( nbBad == 0 )
8003     nbBad = CheckNeiborsOnBoundary( 0, & bndNeedSmooth );
8004   if ( nbBad > 0 )
8005     Set( DISTORTED );
8006
8007   // evaluate min angle
8008   if ( nbBad == 0 && !findBest && !bndNeedSmooth )
8009   {
8010     size_t nbGoodAngles = _simplices.size();
8011     double angle;
8012     for ( size_t i = 0; i < _simplices.size(); ++i )
8013     {
8014       if ( !_simplices[i].IsMinAngleOK( curPos, angle ) && angle > _minAngle )
8015         --nbGoodAngles;
8016     }
8017     if ( nbGoodAngles == _simplices.size() )
8018     {
8019       Unset( MOVED );
8020       return 0;
8021     }
8022   }
8023   if ( Is( ON_CONCAVE_FACE ))
8024     findBest = true;
8025
8026   if ( step % 2 == 0 )
8027     findBest = false;
8028
8029   if ( Is( ON_CONCAVE_FACE ) && !findBest ) // alternate FUN_CENTROIDAL and FUN_LAPLACIAN
8030   {
8031     if ( _smooFunction == _funs[ FUN_LAPLACIAN ] )
8032       _smooFunction = _funs[ FUN_CENTROIDAL ];
8033     else
8034       _smooFunction = _funs[ FUN_LAPLACIAN ];
8035   }
8036
8037   // compute new position for the last _pos using different _funs
8038   gp_XYZ newPos;
8039   bool moved = false;
8040   for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
8041   {
8042     if ( iFun < 0 )
8043       newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
8044     else if ( _funs[ iFun ] == _smooFunction )
8045       continue; // _smooFunction again
8046     else if ( step > 1 )
8047       newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
8048     else
8049       break; // let "easy" functions improve elements around distorted ones
8050
8051     if ( _curvature )
8052     {
8053       double delta  = _curvature->lenDelta( _len );
8054       if ( delta > 0 )
8055         newPos += _normal * delta;
8056       else
8057       {
8058         double segLen = _normal * ( newPos - prevPos );
8059         if ( segLen + delta > 0 )
8060           newPos += _normal * delta;
8061       }
8062       // double segLenChange = _normal * ( curPos - newPos );
8063       // newPos += 0.5 * _normal * segLenChange;
8064     }
8065
8066     int nbOkAfter = 0;
8067     double minVolAfter = 1e100;
8068     for ( size_t i = 0; i < _simplices.size(); ++i )
8069     {
8070       nbOkAfter += _simplices[i].IsForward( &prevPos, &newPos, vol );
8071       minVolAfter = Min( minVolAfter, vol );
8072     }
8073     // get worse?
8074     if ( nbOkAfter < nbOkBefore )
8075       continue;
8076
8077     if (( findBest ) &&
8078         ( nbOkAfter == nbOkBefore ) &&
8079         ( minVolAfter <= minVolBefore ))
8080       continue;
8081
8082     nbBad        = _simplices.size() - nbOkAfter;
8083     minVolBefore = minVolAfter;
8084     nbOkBefore   = nbOkAfter;
8085     moved        = true;
8086
8087     SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
8088     n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
8089     _pos.back() = newPos;
8090
8091     dumpMoveComm( n, SMESH_Comment( _funNames[ iFun < 0 ? smooFunID() : iFun ] )
8092                   << (nbBad ? " --BAD" : ""));
8093
8094     if ( iFun > -1 )
8095     {
8096       continue; // look for a better function
8097     }
8098
8099     if ( !findBest )
8100       break;
8101
8102   } // loop on smoothing functions
8103
8104   if ( moved ) // notify _neibors
8105   {
8106     Set( SMOOTHED );
8107     for ( size_t i = 0; i < _neibors.size(); ++i )
8108       if ( !_neibors[i]->Is( MOVED ))
8109       {
8110         _neibors[i]->Set( MOVED );
8111         toSmooth.push_back( _neibors[i] );
8112       }
8113   }
8114
8115   return nbBad;
8116 }
8117
8118 //================================================================================
8119 /*!
8120  * \brief Perform 'smart' 3D smooth of nodes inflated from FACE
8121  *  \retval int - nb of bad simplices around this _LayerEdge
8122  */
8123 //================================================================================
8124
8125 int _LayerEdge::Smooth(const int step, const bool isConcaveFace, bool findBest )
8126 {
8127   if ( !_smooFunction )
8128     return 0; // _LayerEdge inflated along EDGE or FACE
8129   if ( Is( BLOCKED ))
8130     return 0; // not inflated
8131
8132   const gp_XYZ& curPos  = _pos.back();
8133   const gp_XYZ& prevPos = _pos[0]; //PrevCheckPos();
8134
8135   // quality metrics (orientation) of tetras around _tgtNode
8136   int nbOkBefore = 0;
8137   double vol, minVolBefore = 1e100;
8138   for ( size_t i = 0; i < _simplices.size(); ++i )
8139   {
8140     nbOkBefore += _simplices[i].IsForward( &prevPos, &curPos, vol );
8141     minVolBefore = Min( minVolBefore, vol );
8142   }
8143   int nbBad = _simplices.size() - nbOkBefore;
8144
8145   if ( isConcaveFace ) // alternate FUN_CENTROIDAL and FUN_LAPLACIAN
8146   {
8147     if      ( _smooFunction == _funs[ FUN_CENTROIDAL ] && step % 2 )
8148       _smooFunction = _funs[ FUN_LAPLACIAN ];
8149     else if ( _smooFunction == _funs[ FUN_LAPLACIAN ] && !( step % 2 ))
8150       _smooFunction = _funs[ FUN_CENTROIDAL ];
8151   }
8152
8153   // compute new position for the last _pos using different _funs
8154   gp_XYZ newPos;
8155   for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
8156   {
8157     if ( iFun < 0 )
8158       newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
8159     else if ( _funs[ iFun ] == _smooFunction )
8160       continue; // _smooFunction again
8161     else if ( step > 1 )
8162       newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
8163     else
8164       break; // let "easy" functions improve elements around distorted ones
8165
8166     if ( _curvature )
8167     {
8168       double delta  = _curvature->lenDelta( _len );
8169       if ( delta > 0 )
8170         newPos += _normal * delta;
8171       else
8172       {
8173         double segLen = _normal * ( newPos - prevPos );
8174         if ( segLen + delta > 0 )
8175           newPos += _normal * delta;
8176       }
8177       // double segLenChange = _normal * ( curPos - newPos );
8178       // newPos += 0.5 * _normal * segLenChange;
8179     }
8180
8181     int nbOkAfter = 0;
8182     double minVolAfter = 1e100;
8183     for ( size_t i = 0; i < _simplices.size(); ++i )
8184     {
8185       nbOkAfter += _simplices[i].IsForward( &prevPos, &newPos, vol );
8186       minVolAfter = Min( minVolAfter, vol );
8187     }
8188     // get worse?
8189     if ( nbOkAfter < nbOkBefore )
8190       continue;
8191     if (( isConcaveFace || findBest ) &&
8192         ( nbOkAfter == nbOkBefore ) &&
8193         ( minVolAfter <= minVolBefore )
8194         )
8195       continue;
8196
8197     nbBad        = _simplices.size() - nbOkAfter;
8198     minVolBefore = minVolAfter;
8199     nbOkBefore   = nbOkAfter;
8200
8201     SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
8202     n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
8203     _pos.back() = newPos;
8204
8205     dumpMoveComm( n, SMESH_Comment( _funNames[ iFun < 0 ? smooFunID() : iFun ] )
8206                   << ( nbBad ? "--BAD" : ""));
8207
8208     // commented for IPAL0052478
8209     // _len -= prevPos.Distance(SMESH_TNodeXYZ( n ));
8210     // _len += prevPos.Distance(newPos);
8211
8212     if ( iFun > -1 ) // findBest || the chosen _fun makes worse
8213     {
8214       //_smooFunction = _funs[ iFun ];
8215       // cout << "# " << _funNames[ iFun ] << "\t N:" << _nodes.back()->GetID()
8216       // << "\t nbBad: " << _simplices.size() - nbOkAfter
8217       // << " minVol: " << minVolAfter
8218       // << " " << newPos.X() << " " << newPos.Y() << " " << newPos.Z()
8219       // << endl;
8220       continue; // look for a better function
8221     }
8222
8223     if ( !findBest )
8224       break;
8225
8226   } // loop on smoothing functions
8227
8228   return nbBad;
8229 }
8230
8231 //================================================================================
8232 /*!
8233  * \brief Chooses a smoothing technic giving a position most close to an initial one.
8234  *        For a correct result, _simplices must contain nodes lying on geometry.
8235  */
8236 //================================================================================
8237
8238 void _LayerEdge::ChooseSmooFunction( const set< TGeomID >& concaveVertices,
8239                                      const TNode2Edge&     n2eMap)
8240 {
8241   if ( _smooFunction ) return;
8242
8243   // use smoothNefPolygon() near concaveVertices
8244   if ( !concaveVertices.empty() )
8245   {
8246     _smooFunction = _funs[ FUN_CENTROIDAL ];
8247
8248     Set( ON_CONCAVE_FACE );
8249
8250     for ( size_t i = 0; i < _simplices.size(); ++i )
8251     {
8252       if ( concaveVertices.count( _simplices[i]._nPrev->getshapeId() ))
8253       {
8254         _smooFunction = _funs[ FUN_NEFPOLY ];
8255
8256         // set FUN_CENTROIDAL to neighbor edges
8257         for ( i = 0; i < _neibors.size(); ++i )
8258         {
8259           if ( _neibors[i]->_nodes[0]->GetPosition()->GetDim() == 2 )
8260           {
8261             _neibors[i]->_smooFunction = _funs[ FUN_CENTROIDAL ];
8262           }
8263         }
8264         return;
8265       }
8266     }
8267
8268     // // this coice is done only if ( !concaveVertices.empty() ) for Grids/smesh/bugs_19/X1
8269     // // where the nodes are smoothed too far along a sphere thus creating
8270     // // inverted _simplices
8271     // double dist[theNbSmooFuns];
8272     // //double coef[theNbSmooFuns] = { 1., 1.2, 1.4, 1.4 };
8273     // double coef[theNbSmooFuns] = { 1., 1., 1., 1. };
8274
8275     // double minDist = Precision::Infinite();
8276     // gp_Pnt p = SMESH_TNodeXYZ( _nodes[0] );
8277     // for ( int i = 0; i < FUN_NEFPOLY; ++i )
8278     // {
8279     //   gp_Pnt newP = (this->*_funs[i])();
8280     //   dist[i] = p.SquareDistance( newP );
8281     //   if ( dist[i]*coef[i] < minDist )
8282     //   {
8283     //     _smooFunction = _funs[i];
8284     //     minDist = dist[i]*coef[i];
8285     //   }
8286     // }
8287   }
8288   else
8289   {
8290     _smooFunction = _funs[ FUN_LAPLACIAN ];
8291   }
8292   // int minDim = 3;
8293   // for ( size_t i = 0; i < _simplices.size(); ++i )
8294   //   minDim = Min( minDim, _simplices[i]._nPrev->GetPosition()->GetDim() );
8295   // if ( minDim == 0 )
8296   //   _smooFunction = _funs[ FUN_CENTROIDAL ];
8297   // else if ( minDim == 1 )
8298   //   _smooFunction = _funs[ FUN_CENTROIDAL ];
8299
8300
8301   // int iMin;
8302   // for ( int i = 0; i < FUN_NB; ++i )
8303   // {
8304   //   //cout << dist[i] << " ";
8305   //   if ( _smooFunction == _funs[i] ) {
8306   //     iMin = i;
8307   //     //debugMsg( fNames[i] );
8308   //     break;
8309   //   }
8310   // }
8311   // cout << _funNames[ iMin ] << "\t N:" << _nodes.back()->GetID() << endl;
8312 }
8313
8314 //================================================================================
8315 /*!
8316  * \brief Returns a name of _SmooFunction
8317  */
8318 //================================================================================
8319
8320 int _LayerEdge::smooFunID( _LayerEdge::PSmooFun fun) const
8321 {
8322   if ( !fun )
8323     fun = _smooFunction;
8324   for ( int i = 0; i < theNbSmooFuns; ++i )
8325     if ( fun == _funs[i] )
8326       return i;
8327
8328   return theNbSmooFuns;
8329 }
8330
8331 //================================================================================
8332 /*!
8333  * \brief Computes a new node position using Laplacian smoothing
8334  */
8335 //================================================================================
8336
8337 gp_XYZ _LayerEdge::smoothLaplacian()
8338 {
8339   gp_XYZ newPos (0,0,0);
8340   for ( size_t i = 0; i < _simplices.size(); ++i )
8341     newPos += SMESH_TNodeXYZ( _simplices[i]._nPrev );
8342   newPos /= _simplices.size();
8343
8344   return newPos;
8345 }
8346
8347 //================================================================================
8348 /*!
8349  * \brief Computes a new node position using angular-based smoothing
8350  */
8351 //================================================================================
8352
8353 gp_XYZ _LayerEdge::smoothAngular()
8354 {
8355   vector< gp_Vec > edgeDir;  edgeDir. reserve( _simplices.size() + 1 );
8356   vector< double > edgeSize; edgeSize.reserve( _simplices.size()     );
8357   vector< gp_XYZ > points;   points.  reserve( _simplices.size() + 1 );
8358
8359   gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
8360   gp_XYZ pN( 0,0,0 );
8361   for ( size_t i = 0; i < _simplices.size(); ++i )
8362   {
8363     gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
8364     edgeDir.push_back( p - pPrev );
8365     edgeSize.push_back( edgeDir.back().Magnitude() );
8366     if ( edgeSize.back() < numeric_limits<double>::min() )
8367     {
8368       edgeDir.pop_back();
8369       edgeSize.pop_back();
8370     }
8371     else
8372     {
8373       edgeDir.back() /= edgeSize.back();
8374       points.push_back( p );
8375       pN += p;
8376     }
8377     pPrev = p;
8378   }
8379   edgeDir.push_back ( edgeDir[0] );
8380   edgeSize.push_back( edgeSize[0] );
8381   pN /= points.size();
8382
8383   gp_XYZ newPos(0,0,0);
8384   double sumSize = 0;
8385   for ( size_t i = 0; i < points.size(); ++i )
8386   {
8387     gp_Vec toN    = pN - points[i];
8388     double toNLen = toN.Magnitude();
8389     if ( toNLen < numeric_limits<double>::min() )
8390     {
8391       newPos += pN;
8392       continue;
8393     }
8394     gp_Vec bisec    = edgeDir[i] + edgeDir[i+1];
8395     double bisecLen = bisec.SquareMagnitude();
8396     if ( bisecLen < numeric_limits<double>::min() )
8397     {
8398       gp_Vec norm = edgeDir[i] ^ toN;
8399       bisec = norm ^ edgeDir[i];
8400       bisecLen = bisec.SquareMagnitude();
8401     }
8402     bisecLen = Sqrt( bisecLen );
8403     bisec /= bisecLen;
8404
8405 #if 1
8406     gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * bisecLen;
8407     sumSize += bisecLen;
8408 #else
8409     gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * ( edgeSize[i] + edgeSize[i+1] );
8410     sumSize += ( edgeSize[i] + edgeSize[i+1] );
8411 #endif
8412     newPos += pNew;
8413   }
8414   newPos /= sumSize;
8415
8416   // project newPos to an average plane
8417
8418   gp_XYZ norm(0,0,0); // plane normal
8419   points.push_back( points[0] );
8420   for ( size_t i = 1; i < points.size(); ++i )
8421   {
8422     gp_XYZ vec1 = points[ i-1 ] - pN;
8423     gp_XYZ vec2 = points[ i   ] - pN;
8424     gp_XYZ cross = vec1 ^ vec2;
8425     try {
8426       cross.Normalize();
8427       if ( cross * norm < numeric_limits<double>::min() )
8428         norm += cross.Reversed();
8429       else
8430         norm += cross;
8431     }
8432     catch (Standard_Failure) { // if |cross| == 0.
8433     }
8434   }
8435   gp_XYZ vec = newPos - pN;
8436   double r   = ( norm * vec ) / norm.SquareModulus();  // param [0,1] on norm
8437   newPos     = newPos - r * norm;
8438
8439   return newPos;
8440 }
8441
8442 //================================================================================
8443 /*!
8444  * \brief Computes a new node position using weigthed node positions
8445  */
8446 //================================================================================
8447
8448 gp_XYZ _LayerEdge::smoothLengthWeighted()
8449 {
8450   vector< double > edgeSize; edgeSize.reserve( _simplices.size() + 1);
8451   vector< gp_XYZ > points;   points.  reserve( _simplices.size() );
8452
8453   gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
8454   for ( size_t i = 0; i < _simplices.size(); ++i )
8455   {
8456     gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
8457     edgeSize.push_back( ( p - pPrev ).Modulus() );
8458     if ( edgeSize.back() < numeric_limits<double>::min() )
8459     {
8460       edgeSize.pop_back();
8461     }
8462     else
8463     {
8464       points.push_back( p );
8465     }
8466     pPrev = p;
8467   }
8468   edgeSize.push_back( edgeSize[0] );
8469
8470   gp_XYZ newPos(0,0,0);
8471   double sumSize = 0;
8472   for ( size_t i = 0; i < points.size(); ++i )
8473   {
8474     newPos += points[i] * ( edgeSize[i] + edgeSize[i+1] );
8475     sumSize += edgeSize[i] + edgeSize[i+1];
8476   }
8477   newPos /= sumSize;
8478   return newPos;
8479 }
8480
8481 //================================================================================
8482 /*!
8483  * \brief Computes a new node position using angular-based smoothing
8484  */
8485 //================================================================================
8486
8487 gp_XYZ _LayerEdge::smoothCentroidal()
8488 {
8489   gp_XYZ newPos(0,0,0);
8490   gp_XYZ pN = SMESH_TNodeXYZ( _nodes.back() );
8491   double sumSize = 0;
8492   for ( size_t i = 0; i < _simplices.size(); ++i )
8493   {
8494     gp_XYZ p1 = SMESH_TNodeXYZ( _simplices[i]._nPrev );
8495     gp_XYZ p2 = SMESH_TNodeXYZ( _simplices[i]._nNext );
8496     gp_XYZ gc = ( pN + p1 + p2 ) / 3.;
8497     double size = (( p1 - pN ) ^ ( p2 - pN )).Modulus();
8498
8499     sumSize += size;
8500     newPos += gc * size;
8501   }
8502   newPos /= sumSize;
8503
8504   return newPos;
8505 }
8506
8507 //================================================================================
8508 /*!
8509  * \brief Computes a new node position located inside a Nef polygon
8510  */
8511 //================================================================================
8512
8513 gp_XYZ _LayerEdge::smoothNefPolygon()
8514 #ifdef OLD_NEF_POLYGON
8515 {
8516   gp_XYZ newPos(0,0,0);
8517
8518   // get a plane to search a solution on
8519
8520   vector< gp_XYZ > vecs( _simplices.size() + 1 );
8521   size_t i;
8522   const double tol = numeric_limits<double>::min();
8523   gp_XYZ center(0,0,0);
8524   for ( i = 0; i < _simplices.size(); ++i )
8525   {
8526     vecs[i] = ( SMESH_TNodeXYZ( _simplices[i]._nNext ) -
8527                 SMESH_TNodeXYZ( _simplices[i]._nPrev ));
8528     center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
8529   }
8530   vecs.back() = vecs[0];
8531   center /= _simplices.size();
8532
8533   gp_XYZ zAxis(0,0,0);
8534   for ( i = 0; i < _simplices.size(); ++i )
8535     zAxis += vecs[i] ^ vecs[i+1];
8536
8537   gp_XYZ yAxis;
8538   for ( i = 0; i < _simplices.size(); ++i )
8539   {
8540     yAxis = vecs[i];
8541     if ( yAxis.SquareModulus() > tol )
8542       break;
8543   }
8544   gp_XYZ xAxis = yAxis ^ zAxis;
8545   // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
8546   // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
8547   //                             p0.Distance( _simplices[2]._nPrev ));
8548   // gp_XYZ center = smoothLaplacian();
8549   // gp_XYZ xAxis, yAxis, zAxis;
8550   // for ( i = 0; i < _simplices.size(); ++i )
8551   // {
8552   //   xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8553   //   if ( xAxis.SquareModulus() > tol*tol )
8554   //     break;
8555   // }
8556   // for ( i = 1; i < _simplices.size(); ++i )
8557   // {
8558   //   yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8559   //   zAxis = xAxis ^ yAxis;
8560   //   if ( zAxis.SquareModulus() > tol*tol )
8561   //     break;
8562   // }
8563   // if ( i == _simplices.size() ) return newPos;
8564
8565   yAxis = zAxis ^ xAxis;
8566   xAxis /= xAxis.Modulus();
8567   yAxis /= yAxis.Modulus();
8568
8569   // get half-planes of _simplices
8570
8571   vector< _halfPlane > halfPlns( _simplices.size() );
8572   int nbHP = 0;
8573   for ( size_t i = 0; i < _simplices.size(); ++i )
8574   {
8575     gp_XYZ OP1 = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8576     gp_XYZ OP2 = SMESH_TNodeXYZ( _simplices[i]._nNext ) - center;
8577     gp_XY  p1( OP1 * xAxis, OP1 * yAxis );
8578     gp_XY  p2( OP2 * xAxis, OP2 * yAxis );
8579     gp_XY  vec12 = p2 - p1;
8580     double dist12 = vec12.Modulus();
8581     if ( dist12 < tol )
8582       continue;
8583     vec12 /= dist12;
8584     halfPlns[ nbHP ]._pos = p1;
8585     halfPlns[ nbHP ]._dir = vec12;
8586     halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
8587     ++nbHP;
8588   }
8589
8590   // intersect boundaries of half-planes, define state of intersection points
8591   // in relation to all half-planes and calculate internal point of a 2D polygon
8592
8593   double sumLen = 0;
8594   gp_XY newPos2D (0,0);
8595
8596   enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
8597   typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
8598   TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
8599
8600   vector< vector< TIntPntState > > allIntPnts( nbHP );
8601   for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
8602   {
8603     vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
8604     if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
8605
8606     int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
8607     int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
8608
8609     int nbNotOut = 0;
8610     const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
8611
8612     for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
8613     {
8614       if ( iHP1 == iHP2 ) continue;
8615
8616       TIntPntState & ips1 = intPnts1[ iHP2 ];
8617       if ( ips1.second == UNDEF )
8618       {
8619         // find an intersection point of boundaries of iHP1 and iHP2
8620
8621         if ( iHP2 == iPrev ) // intersection with neighbors is known
8622           ips1.first = halfPlns[ iHP1 ]._pos;
8623         else if ( iHP2 == iNext )
8624           ips1.first = halfPlns[ iHP2 ]._pos;
8625         else if ( !halfPlns[ iHP1 ].FindIntersection( halfPlns[ iHP2 ], ips1.first ))
8626           ips1.second = NO_INT;
8627
8628         // classify the found intersection point
8629         if ( ips1.second != NO_INT )
8630         {
8631           ips1.second = NOT_OUT;
8632           for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
8633             if ( i != iHP1 && i != iHP2 &&
8634                  halfPlns[ i ].IsOut( ips1.first, tol ))
8635               ips1.second = IS_OUT;
8636         }
8637         vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
8638         if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
8639         TIntPntState & ips2 = intPnts2[ iHP1 ];
8640         ips2 = ips1;
8641       }
8642       if ( ips1.second == NOT_OUT )
8643       {
8644         ++nbNotOut;
8645         segEnds[ bool(segEnds[0]) ] = & ips1.first;
8646       }
8647     }
8648
8649     // find a NOT_OUT segment of boundary which is located between
8650     // two NOT_OUT int points
8651
8652     if ( nbNotOut < 2 )
8653       continue; // no such a segment
8654
8655     if ( nbNotOut > 2 )
8656     {
8657       // sort points along the boundary
8658       map< double, TIntPntState* > ipsByParam;
8659       for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
8660       {
8661         TIntPntState & ips1 = intPnts1[ iHP2 ];
8662         if ( ips1.second != NO_INT )
8663         {
8664           gp_XY     op = ips1.first - halfPlns[ iHP1 ]._pos;
8665           double param = op * halfPlns[ iHP1 ]._dir;
8666           ipsByParam.insert( make_pair( param, & ips1 ));
8667         }
8668       }
8669       // look for two neighboring NOT_OUT points
8670       nbNotOut = 0;
8671       map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
8672       for ( ; u2ips != ipsByParam.end(); ++u2ips )
8673       {
8674         TIntPntState & ips1 = *(u2ips->second);
8675         if ( ips1.second == NOT_OUT )
8676           segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
8677         else if ( nbNotOut >= 2 )
8678           break;
8679         else
8680           nbNotOut = 0;
8681       }
8682     }
8683
8684     if ( nbNotOut >= 2 )
8685     {
8686       double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
8687       sumLen += len;
8688
8689       newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
8690     }
8691   }
8692
8693   if ( sumLen > 0 )
8694   {
8695     newPos2D /= sumLen;
8696     newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
8697   }
8698   else
8699   {
8700     newPos = center;
8701   }
8702
8703   return newPos;
8704 }
8705 #else // OLD_NEF_POLYGON
8706 { ////////////////////////////////// NEW
8707   gp_XYZ newPos(0,0,0);
8708
8709   // get a plane to search a solution on
8710
8711   size_t i;
8712   gp_XYZ center(0,0,0);
8713   for ( i = 0; i < _simplices.size(); ++i )
8714     center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
8715   center /= _simplices.size();
8716
8717   vector< gp_XYZ > vecs( _simplices.size() + 1 );
8718   for ( i = 0; i < _simplices.size(); ++i )
8719     vecs[i] = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8720   vecs.back() = vecs[0];
8721
8722   const double tol = numeric_limits<double>::min();
8723   gp_XYZ zAxis(0,0,0);
8724   for ( i = 0; i < _simplices.size(); ++i )
8725   {
8726     gp_XYZ cross = vecs[i] ^ vecs[i+1];
8727     try {
8728       cross.Normalize();
8729       if ( cross * zAxis < tol )
8730         zAxis += cross.Reversed();
8731       else
8732         zAxis += cross;
8733     }
8734     catch (Standard_Failure) { // if |cross| == 0.
8735     }
8736   }
8737
8738   gp_XYZ yAxis;
8739   for ( i = 0; i < _simplices.size(); ++i )
8740   {
8741     yAxis = vecs[i];
8742     if ( yAxis.SquareModulus() > tol )
8743       break;
8744   }
8745   gp_XYZ xAxis = yAxis ^ zAxis;
8746   // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
8747   // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
8748   //                             p0.Distance( _simplices[2]._nPrev ));
8749   // gp_XYZ center = smoothLaplacian();
8750   // gp_XYZ xAxis, yAxis, zAxis;
8751   // for ( i = 0; i < _simplices.size(); ++i )
8752   // {
8753   //   xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8754   //   if ( xAxis.SquareModulus() > tol*tol )
8755   //     break;
8756   // }
8757   // for ( i = 1; i < _simplices.size(); ++i )
8758   // {
8759   //   yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8760   //   zAxis = xAxis ^ yAxis;
8761   //   if ( zAxis.SquareModulus() > tol*tol )
8762   //     break;
8763   // }
8764   // if ( i == _simplices.size() ) return newPos;
8765
8766   yAxis = zAxis ^ xAxis;
8767   xAxis /= xAxis.Modulus();
8768   yAxis /= yAxis.Modulus();
8769
8770   // get half-planes of _simplices
8771
8772   vector< _halfPlane > halfPlns( _simplices.size() );
8773   int nbHP = 0;
8774   for ( size_t i = 0; i < _simplices.size(); ++i )
8775   {
8776     const gp_XYZ& OP1 = vecs[ i   ];
8777     const gp_XYZ& OP2 = vecs[ i+1 ];
8778     gp_XY  p1( OP1 * xAxis, OP1 * yAxis );
8779     gp_XY  p2( OP2 * xAxis, OP2 * yAxis );
8780     gp_XY  vec12 = p2 - p1;
8781     double dist12 = vec12.Modulus();
8782     if ( dist12 < tol )
8783       continue;
8784     vec12 /= dist12;
8785     halfPlns[ nbHP ]._pos = p1;
8786     halfPlns[ nbHP ]._dir = vec12;
8787     halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
8788     ++nbHP;
8789   }
8790
8791   // intersect boundaries of half-planes, define state of intersection points
8792   // in relation to all half-planes and calculate internal point of a 2D polygon
8793
8794   double sumLen = 0;
8795   gp_XY newPos2D (0,0);
8796
8797   enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
8798   typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
8799   TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
8800
8801   vector< vector< TIntPntState > > allIntPnts( nbHP );
8802   for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
8803   {
8804     vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
8805     if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
8806
8807     int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
8808     int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
8809
8810     int nbNotOut = 0;
8811     const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
8812
8813     for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
8814     {
8815       if ( iHP1 == iHP2 ) continue;
8816
8817       TIntPntState & ips1 = intPnts1[ iHP2 ];
8818       if ( ips1.second == UNDEF )
8819       {
8820         // find an intersection point of boundaries of iHP1 and iHP2
8821
8822         if ( iHP2 == iPrev ) // intersection with neighbors is known
8823           ips1.first = halfPlns[ iHP1 ]._pos;
8824         else if ( iHP2 == iNext )
8825           ips1.first = halfPlns[ iHP2 ]._pos;
8826         else if ( !halfPlns[ iHP1 ].FindIntersection( halfPlns[ iHP2 ], ips1.first ))
8827           ips1.second = NO_INT;
8828
8829         // classify the found intersection point
8830         if ( ips1.second != NO_INT )
8831         {
8832           ips1.second = NOT_OUT;
8833           for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
8834             if ( i != iHP1 && i != iHP2 &&
8835                  halfPlns[ i ].IsOut( ips1.first, tol ))
8836               ips1.second = IS_OUT;
8837         }
8838         vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
8839         if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
8840         TIntPntState & ips2 = intPnts2[ iHP1 ];
8841         ips2 = ips1;
8842       }
8843       if ( ips1.second == NOT_OUT )
8844       {
8845         ++nbNotOut;
8846         segEnds[ bool(segEnds[0]) ] = & ips1.first;
8847       }
8848     }
8849
8850     // find a NOT_OUT segment of boundary which is located between
8851     // two NOT_OUT int points
8852
8853     if ( nbNotOut < 2 )
8854       continue; // no such a segment
8855
8856     if ( nbNotOut > 2 )
8857     {
8858       // sort points along the boundary
8859       map< double, TIntPntState* > ipsByParam;
8860       for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
8861       {
8862         TIntPntState & ips1 = intPnts1[ iHP2 ];
8863         if ( ips1.second != NO_INT )
8864         {
8865           gp_XY     op = ips1.first - halfPlns[ iHP1 ]._pos;
8866           double param = op * halfPlns[ iHP1 ]._dir;
8867           ipsByParam.insert( make_pair( param, & ips1 ));
8868         }
8869       }
8870       // look for two neighboring NOT_OUT points
8871       nbNotOut = 0;
8872       map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
8873       for ( ; u2ips != ipsByParam.end(); ++u2ips )
8874       {
8875         TIntPntState & ips1 = *(u2ips->second);
8876         if ( ips1.second == NOT_OUT )
8877           segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
8878         else if ( nbNotOut >= 2 )
8879           break;
8880         else
8881           nbNotOut = 0;
8882       }
8883     }
8884
8885     if ( nbNotOut >= 2 )
8886     {
8887       double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
8888       sumLen += len;
8889
8890       newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
8891     }
8892   }
8893
8894   if ( sumLen > 0 )
8895   {
8896     newPos2D /= sumLen;
8897     newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
8898   }
8899   else
8900   {
8901     newPos = center;
8902   }
8903
8904   return newPos;
8905 }
8906 #endif // OLD_NEF_POLYGON
8907
8908 //================================================================================
8909 /*!
8910  * \brief Add a new segment to _LayerEdge during inflation
8911  */
8912 //================================================================================
8913
8914 void _LayerEdge::SetNewLength( double len, _EdgesOnShape& eos, SMESH_MesherHelper& helper )
8915 {
8916   if ( Is( BLOCKED ))
8917     return;
8918
8919   if ( len > _maxLen )
8920   {
8921     len = _maxLen;
8922     Block( eos.GetData() );
8923   }
8924   const double lenDelta = len - _len;
8925   if ( lenDelta < len * 1e-3  )
8926   {
8927     Block( eos.GetData() );
8928     return;
8929   }
8930
8931   SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
8932   gp_XYZ oldXYZ = SMESH_TNodeXYZ( n );
8933   gp_XYZ newXYZ;
8934   if ( eos._hyp.IsOffsetMethod() )
8935   {
8936     newXYZ = oldXYZ;
8937     gp_Vec faceNorm;
8938     SMDS_ElemIteratorPtr faceIt = _nodes[0]->GetInverseElementIterator( SMDSAbs_Face );
8939     while ( faceIt->more() )
8940     {
8941       const SMDS_MeshElement* face = faceIt->next();
8942       if ( !eos.GetNormal( face, faceNorm ))
8943         continue;
8944
8945       // translate plane of a face
8946       gp_XYZ baryCenter = oldXYZ + faceNorm.XYZ() * lenDelta;
8947
8948       // find point of intersection of the face plane located at baryCenter
8949       // and _normal located at newXYZ
8950       double d   = -( faceNorm.XYZ() * baryCenter ); // d of plane equation ax+by+cz+d=0
8951       double dot =  ( faceNorm.XYZ() * _normal );
8952       if ( dot < std::numeric_limits<double>::min() )
8953         dot = lenDelta * 1e-3;
8954       double step = -( faceNorm.XYZ() * newXYZ + d ) / dot;
8955       newXYZ += step * _normal;
8956     }
8957     _lenFactor = _normal * ( newXYZ - oldXYZ ) / lenDelta; // _lenFactor is used in InvalidateStep()
8958   }
8959   else
8960   {
8961     newXYZ = oldXYZ + _normal * lenDelta * _lenFactor;
8962   }
8963
8964   n->setXYZ( newXYZ.X(), newXYZ.Y(), newXYZ.Z() );
8965   _pos.push_back( newXYZ );
8966
8967   if ( !eos._sWOL.IsNull() )
8968   {
8969     double distXYZ[4];
8970     bool uvOK = false;
8971     if ( eos.SWOLType() == TopAbs_EDGE )
8972     {
8973       double u = Precision::Infinite(); // to force projection w/o distance check
8974       uvOK = helper.CheckNodeU( TopoDS::Edge( eos._sWOL ), n, u,
8975                                 /*tol=*/2*lenDelta, /*force=*/true, distXYZ );
8976       _pos.back().SetCoord( u, 0, 0 );
8977       if ( _nodes.size() > 1 && uvOK )
8978       {
8979         SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
8980         pos->SetUParameter( u );
8981       }
8982     }
8983     else //  TopAbs_FACE
8984     {
8985       gp_XY uv( Precision::Infinite(), 0 );
8986       uvOK = helper.CheckNodeUV( TopoDS::Face( eos._sWOL ), n, uv,
8987                                  /*tol=*/2*lenDelta, /*force=*/true, distXYZ );
8988       _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
8989       if ( _nodes.size() > 1 && uvOK )
8990       {
8991         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
8992         pos->SetUParameter( uv.X() );
8993         pos->SetVParameter( uv.Y() );
8994       }
8995     }
8996     if ( uvOK )
8997     {
8998       n->setXYZ( distXYZ[1], distXYZ[2], distXYZ[3]);
8999     }
9000     else
9001     {
9002       n->setXYZ( oldXYZ.X(), oldXYZ.Y(), oldXYZ.Z() );
9003       _pos.pop_back();
9004       Block( eos.GetData() );
9005       return;
9006     }
9007   }
9008
9009   _len = len;
9010
9011   // notify _neibors
9012   if ( eos.ShapeType() != TopAbs_FACE )
9013   {
9014     for ( size_t i = 0; i < _neibors.size(); ++i )
9015       //if (  _len > _neibors[i]->GetSmooLen() )
9016         _neibors[i]->Set( MOVED );
9017
9018     Set( MOVED );
9019   }
9020   dumpMove( n ); //debug
9021 }
9022
9023 //================================================================================
9024 /*!
9025  * \brief Set BLOCKED flag and propagate limited _maxLen to _neibors
9026  */
9027 //================================================================================
9028
9029 void _LayerEdge::Block( _SolidData& data )
9030 {
9031   //if ( Is( BLOCKED )) return;
9032   Set( BLOCKED );
9033
9034   _maxLen = _len;
9035   std::queue<_LayerEdge*> queue;
9036   queue.push( this );
9037
9038   gp_Pnt pSrc, pTgt, pSrcN, pTgtN;
9039   while ( !queue.empty() )
9040   {
9041     _LayerEdge* edge = queue.front(); queue.pop();
9042     pSrc = SMESH_TNodeXYZ( edge->_nodes[0] );
9043     pTgt = SMESH_TNodeXYZ( edge->_nodes.back() );
9044     for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
9045     {
9046       _LayerEdge* neibor = edge->_neibors[iN];
9047       if ( neibor->_maxLen < edge->_maxLen * 1.01 )
9048         continue;
9049       pSrcN = SMESH_TNodeXYZ( neibor->_nodes[0] );
9050       pTgtN = SMESH_TNodeXYZ( neibor->_nodes.back() );
9051       double minDist = pSrc.SquareDistance( pSrcN );
9052       minDist   = Min( pTgt.SquareDistance( pTgtN ), minDist );
9053       minDist   = Min( pSrc.SquareDistance( pTgtN ), minDist );
9054       minDist   = Min( pTgt.SquareDistance( pSrcN ), minDist );
9055       double newMaxLen = edge->_maxLen + 0.5 * Sqrt( minDist );
9056       //if ( edge->_nodes[0]->getshapeId() == neibor->_nodes[0]->getshapeId() ) viscous_layers_00/A3
9057       {
9058         newMaxLen *= edge->_lenFactor / neibor->_lenFactor;
9059       }
9060       if ( neibor->_maxLen > newMaxLen )
9061       {
9062         neibor->_maxLen = newMaxLen;
9063         if ( neibor->_maxLen < neibor->_len )
9064         {
9065           _EdgesOnShape* eos = data.GetShapeEdges( neibor );
9066           while ( neibor->_len > neibor->_maxLen &&
9067                   neibor->NbSteps() > 1 )
9068             neibor->InvalidateStep( neibor->NbSteps(), *eos, /*restoreLength=*/true );
9069           neibor->SetNewLength( neibor->_maxLen, *eos, data.GetHelper() );
9070           //neibor->Block( data );
9071         }
9072         queue.push( neibor );
9073       }
9074     }
9075   }
9076 }
9077
9078 //================================================================================
9079 /*!
9080  * \brief Remove last inflation step
9081  */
9082 //================================================================================
9083
9084 void _LayerEdge::InvalidateStep( size_t curStep, const _EdgesOnShape& eos, bool restoreLength )
9085 {
9086   if ( _pos.size() > curStep && _nodes.size() > 1 )
9087   {
9088     _pos.resize( curStep );
9089
9090     gp_Pnt      nXYZ = _pos.back();
9091     SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
9092     SMESH_TNodeXYZ curXYZ( n );
9093     if ( !eos._sWOL.IsNull() )
9094     {
9095       TopLoc_Location loc;
9096       if ( eos.SWOLType() == TopAbs_EDGE )
9097       {
9098         SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
9099         pos->SetUParameter( nXYZ.X() );
9100         double f,l;
9101         Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eos._sWOL ), loc, f,l);
9102         nXYZ = curve->Value( nXYZ.X() ).Transformed( loc );
9103       }
9104       else
9105       {
9106         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
9107         pos->SetUParameter( nXYZ.X() );
9108         pos->SetVParameter( nXYZ.Y() );
9109         Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(eos._sWOL), loc );
9110         nXYZ = surface->Value( nXYZ.X(), nXYZ.Y() ).Transformed( loc );
9111       }
9112     }
9113     n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
9114     dumpMove( n );
9115
9116     if ( restoreLength )
9117     {
9118       _len -= ( nXYZ.XYZ() - curXYZ ).Modulus() / _lenFactor;
9119     }
9120   }
9121 }
9122
9123 //================================================================================
9124 /*!
9125  * \brief Return index of a _pos distant from _normal
9126  */
9127 //================================================================================
9128
9129 int _LayerEdge::GetSmoothedPos( const double tol )
9130 {
9131   int iSmoothed = 0;
9132   for ( size_t i = 1; i < _pos.size() && !iSmoothed; ++i )
9133   {
9134     double normDist = ( _pos[i] - _pos[0] ).Crossed( _normal ).SquareModulus();
9135     if ( normDist > tol * tol )
9136       iSmoothed = i;
9137   }
9138   return iSmoothed;
9139 }
9140
9141 //================================================================================
9142 /*!
9143  * \brief Smooth a path formed by _pos of a _LayerEdge smoothed on FACE
9144  */
9145 //================================================================================
9146
9147 void _LayerEdge::SmoothPos( const vector< double >& segLen, const double tol )
9148 {
9149   if ( /*Is( NORMAL_UPDATED ) ||*/ _pos.size() <= 2 )
9150     return;
9151
9152   // find the 1st smoothed _pos
9153   int iSmoothed = GetSmoothedPos( tol );
9154   if ( !iSmoothed ) return;
9155
9156   //if ( 1 || Is( DISTORTED ))
9157   {
9158     gp_XYZ normal = _normal;
9159     if ( Is( NORMAL_UPDATED ))
9160       for ( size_t i = 1; i < _pos.size(); ++i )
9161       {
9162         normal = _pos[i] - _pos[0];
9163         double size = normal.Modulus();
9164         if ( size > RealSmall() )
9165         {
9166           normal /= size;
9167           break;
9168         }
9169       }
9170     const double r = 0.2;
9171     for ( int iter = 0; iter < 50; ++iter )
9172     {
9173       double minDot = 1;
9174       for ( size_t i = Max( 1, iSmoothed-1-iter ); i < _pos.size()-1; ++i )
9175       {
9176         gp_XYZ midPos = 0.5 * ( _pos[i-1] + _pos[i+1] );
9177         gp_XYZ newPos = ( 1-r ) * midPos + r * _pos[i];
9178         _pos[i] = newPos;
9179         double midLen = 0.5 * ( segLen[i-1] + segLen[i+1] );
9180         double newLen = ( 1-r ) * midLen + r * segLen[i];
9181         const_cast< double& >( segLen[i] ) = newLen;
9182         // check angle between normal and (_pos[i+1], _pos[i] )
9183         gp_XYZ posDir = _pos[i+1] - _pos[i];
9184         double size   = posDir.SquareModulus();
9185         if ( size > RealSmall() )
9186           minDot = Min( minDot, ( normal * posDir ) * ( normal * posDir ) / size );
9187       }
9188       if ( minDot > 0.5 * 0.5 )
9189         break;
9190     }
9191   }
9192   // else
9193   // {
9194   //   for ( size_t i = 1; i < _pos.size()-1; ++i )
9195   //   {
9196   //     if ((int) i < iSmoothed  &&  ( segLen[i] / segLen.back() < 0.5 ))
9197   //       continue;
9198
9199   //     double     wgt = segLen[i] / segLen.back();
9200   //     gp_XYZ normPos = _pos[0] + _normal * wgt * _len;
9201   //     gp_XYZ tgtPos  = ( 1 - wgt ) * _pos[0] +  wgt * _pos.back();
9202   //     gp_XYZ newPos  = ( 1 - wgt ) * normPos +  wgt * tgtPos;
9203   //     _pos[i] = newPos;
9204   //   }
9205   // }
9206 }
9207
9208 //================================================================================
9209 /*!
9210  * \brief Print flags
9211  */
9212 //================================================================================
9213
9214 std::string _LayerEdge::DumpFlags() const
9215 {
9216   SMESH_Comment dump;
9217   for ( int flag = 1; flag < 0x1000000; flag *= 2 )
9218     if ( _flags & flag )
9219     {
9220       EFlags f = (EFlags) flag;
9221       switch ( f ) {
9222       case TO_SMOOTH:       dump << "TO_SMOOTH";       break;
9223       case MOVED:           dump << "MOVED";           break;
9224       case SMOOTHED:        dump << "SMOOTHED";        break;
9225       case DIFFICULT:       dump << "DIFFICULT";       break;
9226       case ON_CONCAVE_FACE: dump << "ON_CONCAVE_FACE"; break;
9227       case BLOCKED:         dump << "BLOCKED";         break;
9228       case INTERSECTED:     dump << "INTERSECTED";     break;
9229       case NORMAL_UPDATED:  dump << "NORMAL_UPDATED";  break;
9230       case MARKED:          dump << "MARKED";          break;
9231       case MULTI_NORMAL:    dump << "MULTI_NORMAL";    break;
9232       case NEAR_BOUNDARY:   dump << "NEAR_BOUNDARY";   break;
9233       case SMOOTHED_C1:     dump << "SMOOTHED_C1";     break;
9234       case DISTORTED:       dump << "DISTORTED";       break;
9235       case RISKY_SWOL:      dump << "RISKY_SWOL";      break;
9236       case SHRUNK:          dump << "SHRUNK";          break;
9237       case UNUSED_FLAG:     dump << "UNUSED_FLAG";     break;
9238       }
9239       dump << " ";
9240     }
9241   cout << dump << endl;
9242   return dump;
9243 }
9244
9245 //================================================================================
9246 /*!
9247   case brief:
9248   default:
9249 */
9250 //================================================================================
9251
9252 bool _ViscousBuilder::refine(_SolidData& data)
9253 {
9254   SMESH_MesherHelper& helper = data.GetHelper();
9255   helper.SetElementsOnShape(false);
9256
9257   Handle(Geom_Curve) curve;
9258   Handle(ShapeAnalysis_Surface) surface;
9259   TopoDS_Edge geomEdge;
9260   TopoDS_Face geomFace;
9261   TopLoc_Location loc;
9262   double f,l, u = 0;
9263   gp_XY uv;
9264   vector< gp_XYZ > pos3D;
9265   bool isOnEdge;
9266   TGeomID prevBaseId = -1;
9267   TNode2Edge* n2eMap = 0;
9268   TNode2Edge::iterator n2e;
9269
9270   // Create intermediate nodes on each _LayerEdge
9271
9272   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
9273   {
9274     _EdgesOnShape& eos = data._edgesOnShape[iS];
9275     if ( eos._edges.empty() ) continue;
9276
9277     if ( eos._edges[0]->_nodes.size() < 2 )
9278       continue; // on _noShrinkShapes
9279
9280     // get data of a shrink shape
9281     isOnEdge = false;
9282     geomEdge.Nullify(); geomFace.Nullify();
9283     curve.Nullify(); surface.Nullify();
9284     if ( !eos._sWOL.IsNull() )
9285     {
9286       isOnEdge = ( eos.SWOLType() == TopAbs_EDGE );
9287       if ( isOnEdge )
9288       {
9289         geomEdge = TopoDS::Edge( eos._sWOL );
9290         curve    = BRep_Tool::Curve( geomEdge, loc, f,l);
9291       }
9292       else
9293       {
9294         geomFace = TopoDS::Face( eos._sWOL );
9295         surface  = helper.GetSurface( geomFace );
9296       }
9297     }
9298     else if ( eos.ShapeType() == TopAbs_FACE && eos._toSmooth )
9299     {
9300       geomFace = TopoDS::Face( eos._shape );
9301       surface  = helper.GetSurface( geomFace );
9302       // propagate _toSmooth back to _eosC1, which was unset in findShapesToSmooth()
9303       for ( size_t i = 0; i < eos._eosC1.size(); ++i )
9304       {
9305         eos._eosC1[ i ]->_toSmooth = true;
9306         for ( size_t j = 0; j < eos._eosC1[i]->_edges.size(); ++j )
9307           eos._eosC1[i]->_edges[j]->Set( _LayerEdge::SMOOTHED_C1 );
9308       }
9309     }
9310
9311     vector< double > segLen;
9312     for ( size_t i = 0; i < eos._edges.size(); ++i )
9313     {
9314       _LayerEdge& edge = *eos._edges[i];
9315       if ( edge._pos.size() < 2 )
9316         continue;
9317
9318       // get accumulated length of segments
9319       segLen.resize( edge._pos.size() );
9320       segLen[0] = 0.0;
9321       if ( eos._sWOL.IsNull() )
9322       {
9323         bool useNormal = true;
9324         bool   usePos  = false;
9325         bool smoothed  = false;
9326         double   preci = 0.1 * edge._len;
9327         if ( eos._toSmooth && edge._pos.size() > 2 )
9328         {
9329           smoothed = edge.GetSmoothedPos( preci );
9330         }
9331         if ( smoothed )
9332         {
9333           if ( !surface.IsNull() &&
9334                !data._convexFaces.count( eos._shapeID )) // edge smoothed on FACE
9335           {
9336             useNormal = usePos = false;
9337             gp_Pnt2d uv = helper.GetNodeUV( geomFace, edge._nodes[0] );
9338             for ( size_t j = 1; j < edge._pos.size() && !useNormal; ++j )
9339             {
9340               uv = surface->NextValueOfUV( uv, edge._pos[j], preci );
9341               if ( surface->Gap() < 2. * edge._len )
9342                 segLen[j] = surface->Gap();
9343               else
9344                 useNormal = true;
9345             }
9346           }
9347         }
9348         else if ( !edge.Is( _LayerEdge::NORMAL_UPDATED ))
9349         {
9350 #ifndef __NODES_AT_POS
9351           useNormal = usePos = false;
9352           edge._pos[1] = edge._pos.back();
9353           edge._pos.resize( 2 );
9354           segLen.resize( 2 );
9355           segLen[ 1 ] = edge._len;
9356 #endif
9357         }
9358         if ( useNormal && edge.Is( _LayerEdge::NORMAL_UPDATED ))
9359         {
9360           useNormal = usePos = false;
9361           _LayerEdge tmpEdge; // get original _normal
9362           tmpEdge._nodes.push_back( edge._nodes[0] );
9363           if ( !setEdgeData( tmpEdge, eos, helper, data ))
9364             usePos = true;
9365           else
9366             for ( size_t j = 1; j < edge._pos.size(); ++j )
9367               segLen[j] = ( edge._pos[j] - edge._pos[0] ) * tmpEdge._normal;
9368         }
9369         if ( useNormal )
9370         {
9371           for ( size_t j = 1; j < edge._pos.size(); ++j )
9372             segLen[j] = ( edge._pos[j] - edge._pos[0] ) * edge._normal;
9373         }
9374         if ( usePos )
9375         {
9376           for ( size_t j = 1; j < edge._pos.size(); ++j )
9377             segLen[j] = segLen[j-1] + ( edge._pos[j-1] - edge._pos[j] ).Modulus();
9378         }
9379         else
9380         {
9381           bool swapped = ( edge._pos.size() > 2 );
9382           while ( swapped )
9383           {
9384             swapped = false;
9385             for ( size_t j = 1; j < edge._pos.size()-1; ++j )
9386               if ( segLen[j] > segLen.back() )
9387               {
9388                 segLen.erase( segLen.begin() + j );
9389                 edge._pos.erase( edge._pos.begin() + j );
9390                 --j;
9391               }
9392               else if ( segLen[j] < segLen[j-1] )
9393               {
9394                 std::swap( segLen[j], segLen[j-1] );
9395                 std::swap( edge._pos[j], edge._pos[j-1] );
9396                 swapped = true;
9397               }
9398           }
9399         }
9400         // smooth a path formed by edge._pos
9401 #ifndef __NODES_AT_POS
9402         if (( smoothed ) /*&&
9403             ( eos.ShapeType() == TopAbs_FACE || edge.Is( _LayerEdge::SMOOTHED_C1 ))*/)
9404           edge.SmoothPos( segLen, preci );
9405 #endif
9406       }
9407       else if ( eos._isRegularSWOL ) // usual SWOL
9408       {
9409         for ( size_t j = 1; j < edge._pos.size(); ++j )
9410           segLen[j] = segLen[j-1] + (edge._pos[j-1] - edge._pos[j] ).Modulus();
9411       }
9412       else if ( !surface.IsNull() ) // SWOL surface with singularities
9413       {
9414         pos3D.resize( edge._pos.size() );
9415         for ( size_t j = 0; j < edge._pos.size(); ++j )
9416           pos3D[j] = surface->Value( edge._pos[j].X(), edge._pos[j].Y() ).XYZ();
9417
9418         for ( size_t j = 1; j < edge._pos.size(); ++j )
9419           segLen[j] = segLen[j-1] + ( pos3D[j-1] - pos3D[j] ).Modulus();
9420       }
9421
9422       // allocate memory for new nodes if it is not yet refined
9423       const SMDS_MeshNode* tgtNode = edge._nodes.back();
9424       if ( edge._nodes.size() == 2 )
9425       {
9426 #ifdef __NODES_AT_POS
9427         int nbNodes = edge._pos.size();
9428 #else
9429         int nbNodes = eos._hyp.GetNumberLayers() + 1;
9430 #endif
9431         edge._nodes.resize( nbNodes, 0 );
9432         edge._nodes[1] = 0;
9433         edge._nodes.back() = tgtNode;
9434       }
9435       // restore shapePos of the last node by already treated _LayerEdge of another _SolidData
9436       const TGeomID baseShapeId = edge._nodes[0]->getshapeId();
9437       if ( baseShapeId != prevBaseId )
9438       {
9439         map< TGeomID, TNode2Edge* >::iterator s2ne = data._s2neMap.find( baseShapeId );
9440         n2eMap = ( s2ne == data._s2neMap.end() ) ? 0 : s2ne->second;
9441         prevBaseId = baseShapeId;
9442       }
9443       _LayerEdge* edgeOnSameNode = 0;
9444       bool        useExistingPos = false;
9445       if ( n2eMap && (( n2e = n2eMap->find( edge._nodes[0] )) != n2eMap->end() ))
9446       {
9447         edgeOnSameNode = n2e->second;
9448         useExistingPos = ( edgeOnSameNode->_len < edge._len );
9449         const gp_XYZ& otherTgtPos = edgeOnSameNode->_pos.back();
9450         SMDS_PositionPtr  lastPos = tgtNode->GetPosition();
9451         if ( isOnEdge )
9452         {
9453           SMDS_EdgePosition* epos = static_cast<SMDS_EdgePosition*>( lastPos );
9454           epos->SetUParameter( otherTgtPos.X() );
9455         }
9456         else
9457         {
9458           SMDS_FacePosition* fpos = static_cast<SMDS_FacePosition*>( lastPos );
9459           fpos->SetUParameter( otherTgtPos.X() );
9460           fpos->SetVParameter( otherTgtPos.Y() );
9461         }
9462       }
9463       // calculate height of the first layer
9464       double h0;
9465       const double T = segLen.back(); //data._hyp.GetTotalThickness();
9466       const double f = eos._hyp.GetStretchFactor();
9467       const int    N = eos._hyp.GetNumberLayers();
9468       const double fPowN = pow( f, N );
9469       if ( fPowN - 1 <= numeric_limits<double>::min() )
9470         h0 = T / N;
9471       else
9472         h0 = T * ( f - 1 )/( fPowN - 1 );
9473
9474       const double zeroLen = std::numeric_limits<double>::min();
9475
9476       // create intermediate nodes
9477       double hSum = 0, hi = h0/f;
9478       size_t iSeg = 1;
9479       for ( size_t iStep = 1; iStep < edge._nodes.size(); ++iStep )
9480       {
9481         // compute an intermediate position
9482         hi *= f;
9483         hSum += hi;
9484         while ( hSum > segLen[iSeg] && iSeg < segLen.size()-1 )
9485           ++iSeg;
9486         int iPrevSeg = iSeg-1;
9487         while ( fabs( segLen[iPrevSeg] - segLen[iSeg]) <= zeroLen && iPrevSeg > 0 )
9488           --iPrevSeg;
9489         double   r = ( segLen[iSeg] - hSum ) / ( segLen[iSeg] - segLen[iPrevSeg] );
9490         gp_Pnt pos = r * edge._pos[iPrevSeg] + (1-r) * edge._pos[iSeg];
9491 #ifdef __NODES_AT_POS
9492         pos = edge._pos[ iStep ];
9493 #endif
9494         SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >( edge._nodes[ iStep ]);
9495         if ( !eos._sWOL.IsNull() )
9496         {
9497           // compute XYZ by parameters <pos>
9498           if ( isOnEdge )
9499           {
9500             u = pos.X();
9501             if ( !node )
9502               pos = curve->Value( u ).Transformed(loc);
9503           }
9504           else if ( eos._isRegularSWOL )
9505           {
9506             uv.SetCoord( pos.X(), pos.Y() );
9507             if ( !node )
9508               pos = surface->Value( pos.X(), pos.Y() );
9509           }
9510           else
9511           {
9512             uv.SetCoord( pos.X(), pos.Y() );
9513             gp_Pnt p = r * pos3D[ iPrevSeg ] + (1-r) * pos3D[ iSeg ];
9514             uv = surface->NextValueOfUV( uv, p, BRep_Tool::Tolerance( geomFace )).XY();
9515             if ( !node )
9516               pos = surface->Value( uv );
9517           }
9518         }
9519         // create or update the node
9520         if ( !node )
9521         {
9522           node = helper.AddNode( pos.X(), pos.Y(), pos.Z());
9523           if ( !eos._sWOL.IsNull() )
9524           {
9525             if ( isOnEdge )
9526               getMeshDS()->SetNodeOnEdge( node, geomEdge, u );
9527             else
9528               getMeshDS()->SetNodeOnFace( node, geomFace, uv.X(), uv.Y() );
9529           }
9530           else
9531           {
9532             getMeshDS()->SetNodeInVolume( node, helper.GetSubShapeID() );
9533           }
9534         }
9535         else
9536         {
9537           if ( !eos._sWOL.IsNull() )
9538           {
9539             // make average pos from new and current parameters
9540             if ( isOnEdge )
9541             {
9542               //u = 0.5 * ( u + helper.GetNodeU( geomEdge, node ));
9543               if ( useExistingPos )
9544                 u = helper.GetNodeU( geomEdge, node );
9545               pos = curve->Value( u ).Transformed(loc);
9546
9547               SMDS_EdgePosition* epos = static_cast<SMDS_EdgePosition*>( node->GetPosition() );
9548               epos->SetUParameter( u );
9549             }
9550             else
9551             {
9552               //uv = 0.5 * ( uv + helper.GetNodeUV( geomFace, node ));
9553               if ( useExistingPos )
9554                 uv = helper.GetNodeUV( geomFace, node );
9555               pos = surface->Value( uv );
9556
9557               SMDS_FacePosition* fpos = static_cast<SMDS_FacePosition*>( node->GetPosition() );
9558               fpos->SetUParameter( uv.X() );
9559               fpos->SetVParameter( uv.Y() );
9560             }
9561           }
9562           node->setXYZ( pos.X(), pos.Y(), pos.Z() );
9563         }
9564       } // loop on edge._nodes
9565
9566       if ( !eos._sWOL.IsNull() ) // prepare for shrink()
9567       {
9568         if ( isOnEdge )
9569           edge._pos.back().SetCoord( u, 0,0);
9570         else
9571           edge._pos.back().SetCoord( uv.X(), uv.Y() ,0);
9572
9573         if ( edgeOnSameNode )
9574           edgeOnSameNode->_pos.back() = edge._pos.back();
9575       }
9576
9577     } // loop on eos._edges to create nodes
9578
9579
9580     if ( !getMeshDS()->IsEmbeddedMode() )
9581       // Log node movement
9582       for ( size_t i = 0; i < eos._edges.size(); ++i )
9583       {
9584         SMESH_TNodeXYZ p ( eos._edges[i]->_nodes.back() );
9585         getMeshDS()->MoveNode( p._node, p.X(), p.Y(), p.Z() );
9586       }
9587   }
9588
9589
9590   // Create volumes
9591
9592   helper.SetElementsOnShape(true);
9593
9594   vector< vector<const SMDS_MeshNode*>* > nnVec;
9595   set< vector<const SMDS_MeshNode*>* >    nnSet;
9596   set< int >                       degenEdgeInd;
9597   vector<const SMDS_MeshElement*>     degenVols;
9598
9599   TopExp_Explorer exp( data._solid, TopAbs_FACE );
9600   for ( ; exp.More(); exp.Next() )
9601   {
9602     const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
9603     if ( data._ignoreFaceIds.count( faceID ))
9604       continue;
9605     const bool isReversedFace = data._reversedFaceIds.count( faceID );
9606     SMESHDS_SubMesh*    fSubM = getMeshDS()->MeshElements( exp.Current() );
9607     SMDS_ElemIteratorPtr  fIt = fSubM->GetElements();
9608     while ( fIt->more() )
9609     {
9610       const SMDS_MeshElement* face = fIt->next();
9611       const int            nbNodes = face->NbCornerNodes();
9612       nnVec.resize( nbNodes );
9613       nnSet.clear();
9614       degenEdgeInd.clear();
9615       size_t maxZ = 0, minZ = std::numeric_limits<size_t>::max();
9616       SMDS_NodeIteratorPtr nIt = face->nodeIterator();
9617       for ( int iN = 0; iN < nbNodes; ++iN )
9618       {
9619         const SMDS_MeshNode* n = nIt->next();
9620         _LayerEdge*       edge = data._n2eMap[ n ];
9621         const int i = isReversedFace ? nbNodes-1-iN : iN;
9622         nnVec[ i ] = & edge->_nodes;
9623         maxZ = std::max( maxZ, nnVec[ i ]->size() );
9624         minZ = std::min( minZ, nnVec[ i ]->size() );
9625
9626         if ( helper.HasDegeneratedEdges() )
9627           nnSet.insert( nnVec[ i ]);
9628       }
9629
9630       if ( maxZ == 0 )
9631         continue;
9632       if ( 0 < nnSet.size() && nnSet.size() < 3 )
9633         continue;
9634
9635       switch ( nbNodes )
9636       {
9637       case 3: // TRIA
9638       {
9639         // PENTA
9640         for ( size_t iZ = 1; iZ < minZ; ++iZ )
9641           helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
9642                             (*nnVec[0])[iZ],   (*nnVec[1])[iZ],   (*nnVec[2])[iZ]);
9643
9644         for ( size_t iZ = minZ; iZ < maxZ; ++iZ )
9645         {
9646           for ( int iN = 0; iN < nbNodes; ++iN )
9647             if ( nnVec[ iN ]->size() < iZ+1 )
9648               degenEdgeInd.insert( iN );
9649
9650           if ( degenEdgeInd.size() == 1 )  // PYRAM
9651           {
9652             int i2 = *degenEdgeInd.begin();
9653             int i0 = helper.WrapIndex( i2 - 1, nbNodes );
9654             int i1 = helper.WrapIndex( i2 + 1, nbNodes );
9655             helper.AddVolume( (*nnVec[i0])[iZ-1], (*nnVec[i1])[iZ-1],
9656                               (*nnVec[i1])[iZ  ], (*nnVec[i0])[iZ  ], (*nnVec[i2]).back());
9657           }
9658           else  // TETRA
9659           {
9660             int i3 = !degenEdgeInd.count(0) ? 0 : !degenEdgeInd.count(1) ? 1 : 2;
9661             helper.AddVolume( (*nnVec[  0 ])[ i3 == 0 ? iZ-1 : nnVec[0]->size()-1 ],
9662                               (*nnVec[  1 ])[ i3 == 1 ? iZ-1 : nnVec[1]->size()-1 ],
9663                               (*nnVec[  2 ])[ i3 == 2 ? iZ-1 : nnVec[2]->size()-1 ],
9664                               (*nnVec[ i3 ])[ iZ ]);
9665           }
9666         }
9667         break; // TRIA
9668       }
9669       case 4: // QUAD
9670       {
9671         // HEX
9672         for ( size_t iZ = 1; iZ < minZ; ++iZ )
9673           helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
9674                             (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
9675                             (*nnVec[0])[iZ],   (*nnVec[1])[iZ],
9676                             (*nnVec[2])[iZ],   (*nnVec[3])[iZ]);
9677
9678         for ( size_t iZ = minZ; iZ < maxZ; ++iZ )
9679         {
9680           for ( int iN = 0; iN < nbNodes; ++iN )
9681             if ( nnVec[ iN ]->size() < iZ+1 )
9682               degenEdgeInd.insert( iN );
9683
9684           switch ( degenEdgeInd.size() )
9685           {
9686           case 2: // PENTA
9687           {
9688             int i2 = *degenEdgeInd.begin();
9689             int i3 = *degenEdgeInd.rbegin();
9690             bool ok = ( i3 - i2 == 1 );
9691             if ( i2 == 0 && i3 == 3 ) { i2 = 3; i3 = 0; ok = true; }
9692             int i0 = helper.WrapIndex( i3 + 1, nbNodes );
9693             int i1 = helper.WrapIndex( i0 + 1, nbNodes );
9694
9695             const SMDS_MeshElement* vol =
9696               helper.AddVolume( nnVec[i3]->back(), (*nnVec[i0])[iZ], (*nnVec[i0])[iZ-1],
9697                                 nnVec[i2]->back(), (*nnVec[i1])[iZ], (*nnVec[i1])[iZ-1]);
9698             if ( !ok && vol )
9699               degenVols.push_back( vol );
9700           }
9701           break;
9702
9703           default: // degen HEX
9704           {
9705             const SMDS_MeshElement* vol =
9706               helper.AddVolume( nnVec[0]->size() > iZ-1 ? (*nnVec[0])[iZ-1] : nnVec[0]->back(),
9707                                 nnVec[1]->size() > iZ-1 ? (*nnVec[1])[iZ-1] : nnVec[1]->back(),
9708                                 nnVec[2]->size() > iZ-1 ? (*nnVec[2])[iZ-1] : nnVec[2]->back(),
9709                                 nnVec[3]->size() > iZ-1 ? (*nnVec[3])[iZ-1] : nnVec[3]->back(),
9710                                 nnVec[0]->size() > iZ   ? (*nnVec[0])[iZ]   : nnVec[0]->back(),
9711                                 nnVec[1]->size() > iZ   ? (*nnVec[1])[iZ]   : nnVec[1]->back(),
9712                                 nnVec[2]->size() > iZ   ? (*nnVec[2])[iZ]   : nnVec[2]->back(),
9713                                 nnVec[3]->size() > iZ   ? (*nnVec[3])[iZ]   : nnVec[3]->back());
9714             degenVols.push_back( vol );
9715           }
9716           }
9717         }
9718         break; // HEX
9719       }
9720       default:
9721         return error("Not supported type of element", data._index);
9722
9723       } // switch ( nbNodes )
9724     } // while ( fIt->more() )
9725   } // loop on FACEs
9726
9727   if ( !degenVols.empty() )
9728   {
9729     SMESH_ComputeErrorPtr& err = _mesh->GetSubMesh( data._solid )->GetComputeError();
9730     if ( !err || err->IsOK() )
9731     {
9732       err.reset( new SMESH_ComputeError( COMPERR_WARNING,
9733                                          "Bad quality volumes created" ));
9734       err->myBadElements.insert( err->myBadElements.end(),
9735                                  degenVols.begin(),degenVols.end() );
9736     }
9737   }
9738
9739   return true;
9740 }
9741
9742 //================================================================================
9743 /*!
9744  * \brief Shrink 2D mesh on faces to let space for inflated layers
9745  */
9746 //================================================================================
9747
9748 bool _ViscousBuilder::shrink(_SolidData& theData)
9749 {
9750   // make map of (ids of FACEs to shrink mesh on) to (list of _SolidData containing
9751   // _LayerEdge's inflated along FACE or EDGE)
9752   map< TGeomID, list< _SolidData* > > f2sdMap;
9753   for ( size_t i = 0 ; i < _sdVec.size(); ++i )
9754   {
9755     _SolidData& data = _sdVec[i];
9756     map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
9757     for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
9758       if ( s2s->second.ShapeType() == TopAbs_FACE && !_shrinkedFaces.Contains( s2s->second ))
9759       {
9760         f2sdMap[ getMeshDS()->ShapeToIndex( s2s->second )].push_back( &data );
9761
9762         // Put mesh faces on the shrinked FACE to the proxy sub-mesh to avoid
9763         // usage of mesh faces made in addBoundaryElements() by the 3D algo or
9764         // by StdMeshers_QuadToTriaAdaptor
9765         if ( SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( s2s->second ))
9766         {
9767           SMESH_ProxyMesh::SubMesh* proxySub =
9768             data._proxyMesh->getFaceSubM( TopoDS::Face( s2s->second ), /*create=*/true);
9769           if ( proxySub->NbElements() == 0 )
9770           {
9771             SMDS_ElemIteratorPtr fIt = smDS->GetElements();
9772             while ( fIt->more() )
9773             {
9774               const SMDS_MeshElement* f = fIt->next();
9775               // as a result 3D algo will use elements from proxySub and not from smDS
9776               proxySub->AddElement( f );
9777               f->setIsMarked( true );
9778
9779               // Mark nodes on the FACE to discriminate them from nodes
9780               // added by addBoundaryElements(); marked nodes are to be smoothed while shrink()
9781               for ( int iN = 0, nbN = f->NbNodes(); iN < nbN; ++iN )
9782               {
9783                 const SMDS_MeshNode* n = f->GetNode( iN );
9784                 if ( n->GetPosition()->GetDim() == 2 )
9785                   n->setIsMarked( true );
9786               }
9787             }
9788           }
9789         }
9790       }
9791   }
9792
9793   SMESH_MesherHelper helper( *_mesh );
9794   helper.ToFixNodeParameters( true );
9795
9796   // EDGEs to shrink
9797   map< TGeomID, _Shrinker1D > e2shrMap;
9798   vector< _EdgesOnShape* > subEOS;
9799   vector< _LayerEdge* > lEdges;
9800
9801   // loop on FACEs to srink mesh on
9802   map< TGeomID, list< _SolidData* > >::iterator f2sd = f2sdMap.begin();
9803   for ( ; f2sd != f2sdMap.end(); ++f2sd )
9804   {
9805     list< _SolidData* > & dataList = f2sd->second;
9806     if ( dataList.front()->_n2eMap.empty() ||
9807          dataList.back() ->_n2eMap.empty() )
9808       continue; // not yet computed
9809     if ( dataList.front() != &theData &&
9810          dataList.back()  != &theData )
9811       continue;
9812
9813     _SolidData&      data = *dataList.front();
9814     _SolidData*     data2 = dataList.size() > 1 ? dataList.back() : 0;
9815     const TopoDS_Face&  F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
9816     SMESH_subMesh*     sm = _mesh->GetSubMesh( F );
9817     SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
9818
9819     Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
9820
9821     _shrinkedFaces.Add( F );
9822     helper.SetSubShape( F );
9823
9824     // ===========================
9825     // Prepare data for shrinking
9826     // ===========================
9827
9828     // Collect nodes to smooth (they are marked at the beginning of this method)
9829     vector < const SMDS_MeshNode* > smoothNodes;
9830     {
9831       SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
9832       while ( nIt->more() )
9833       {
9834         const SMDS_MeshNode* n = nIt->next();
9835         if ( n->isMarked() )
9836           smoothNodes.push_back( n );
9837       }
9838     }
9839     // Find out face orientation
9840     double refSign = 1;
9841     const set<TGeomID> ignoreShapes;
9842     bool isOkUV;
9843     if ( !smoothNodes.empty() )
9844     {
9845       vector<_Simplex> simplices;
9846       _Simplex::GetSimplices( smoothNodes[0], simplices, ignoreShapes );
9847       helper.GetNodeUV( F, simplices[0]._nPrev, 0, &isOkUV ); // fix UV of simplex nodes
9848       helper.GetNodeUV( F, simplices[0]._nNext, 0, &isOkUV );
9849       gp_XY uv = helper.GetNodeUV( F, smoothNodes[0], 0, &isOkUV );
9850       if ( !simplices[0].IsForward(uv, smoothNodes[0], F, helper, refSign ))
9851         refSign = -1;
9852     }
9853
9854     // Find _LayerEdge's inflated along F
9855     subEOS.clear();
9856     lEdges.clear();
9857     {
9858       SMESH_subMeshIteratorPtr subIt = sm->getDependsOnIterator(/*includeSelf=*/false,
9859                                                                 /*complexFirst=*/true); //!!!
9860       while ( subIt->more() )
9861       {
9862         const TGeomID subID = subIt->next()->GetId();
9863         if ( data._noShrinkShapes.count( subID ))
9864           continue;
9865         _EdgesOnShape* eos = data.GetShapeEdges( subID );
9866         if ( !eos || eos->_sWOL.IsNull() )
9867           if ( data2 ) // check in adjacent SOLID
9868           {
9869             eos = data2->GetShapeEdges( subID );
9870             if ( !eos || eos->_sWOL.IsNull() )
9871               continue;
9872           }
9873         subEOS.push_back( eos );
9874
9875         for ( size_t i = 0; i < eos->_edges.size(); ++i )
9876         {
9877           lEdges.push_back( eos->_edges[ i ] );
9878           prepareEdgeToShrink( *eos->_edges[ i ], *eos, helper, smDS );
9879         }
9880       }
9881     }
9882
9883     dumpFunction(SMESH_Comment("beforeShrinkFace")<<f2sd->first); // debug
9884     SMDS_ElemIteratorPtr fIt = smDS->GetElements();
9885     while ( fIt->more() )
9886       if ( const SMDS_MeshElement* f = fIt->next() )
9887         dumpChangeNodes( f );
9888     dumpFunctionEnd();
9889
9890     // Replace source nodes by target nodes in mesh faces to shrink
9891     dumpFunction(SMESH_Comment("replNodesOnFace")<<f2sd->first); // debug
9892     const SMDS_MeshNode* nodes[20];
9893     for ( size_t iS = 0; iS < subEOS.size(); ++iS )
9894     {
9895       _EdgesOnShape& eos = * subEOS[ iS ];
9896       for ( size_t i = 0; i < eos._edges.size(); ++i )
9897       {
9898         _LayerEdge& edge = *eos._edges[i];
9899         const SMDS_MeshNode* srcNode = edge._nodes[0];
9900         const SMDS_MeshNode* tgtNode = edge._nodes.back();
9901         SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
9902         while ( fIt->more() )
9903         {
9904           const SMDS_MeshElement* f = fIt->next();
9905           if ( !smDS->Contains( f ) || !f->isMarked() )
9906             continue;
9907           SMDS_NodeIteratorPtr nIt = f->nodeIterator();
9908           for ( int iN = 0; nIt->more(); ++iN )
9909           {
9910             const SMDS_MeshNode* n = nIt->next();
9911             nodes[iN] = ( n == srcNode ? tgtNode : n );
9912           }
9913           helper.GetMeshDS()->ChangeElementNodes( f, nodes, f->NbNodes() );
9914           dumpChangeNodes( f );
9915         }
9916       }
9917     }
9918     dumpFunctionEnd();
9919
9920     // find out if a FACE is concave
9921     const bool isConcaveFace = isConcave( F, helper );
9922
9923     // Create _SmoothNode's on face F
9924     vector< _SmoothNode > nodesToSmooth( smoothNodes.size() );
9925     {
9926       dumpFunction(SMESH_Comment("fixUVOnFace")<<f2sd->first); // debug
9927       const bool sortSimplices = isConcaveFace;
9928       for ( size_t i = 0; i < smoothNodes.size(); ++i )
9929       {
9930         const SMDS_MeshNode* n = smoothNodes[i];
9931         nodesToSmooth[ i ]._node = n;
9932         // src nodes must be already replaced by tgt nodes to have tgt nodes in _simplices
9933         _Simplex::GetSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes, 0, sortSimplices);
9934         // fix up incorrect uv of nodes on the FACE
9935         helper.GetNodeUV( F, n, 0, &isOkUV);
9936         dumpMove( n );
9937       }
9938       dumpFunctionEnd();
9939     }
9940     //if ( nodesToSmooth.empty() ) continue;
9941
9942     // Find EDGE's to shrink and set simpices to LayerEdge's
9943     set< _Shrinker1D* > eShri1D;
9944     {
9945       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
9946       {
9947         _EdgesOnShape& eos = * subEOS[ iS ];
9948         if ( eos.SWOLType() == TopAbs_EDGE )
9949         {
9950           SMESH_subMesh* edgeSM = _mesh->GetSubMesh( eos._sWOL );
9951           _Shrinker1D& srinker  = e2shrMap[ edgeSM->GetId() ];
9952           eShri1D.insert( & srinker );
9953           srinker.AddEdge( eos._edges[0], eos, helper );
9954           VISCOUS_3D::ToClearSubWithMain( edgeSM, data._solid );
9955           // restore params of nodes on EGDE if the EDGE has been already
9956           // srinked while srinking other FACE
9957           srinker.RestoreParams();
9958         }
9959         for ( size_t i = 0; i < eos._edges.size(); ++i )
9960         {
9961           _LayerEdge& edge = * eos._edges[i];
9962           _Simplex::GetSimplices( /*tgtNode=*/edge._nodes.back(), edge._simplices, ignoreShapes );
9963
9964           // additionally mark tgt node; only marked nodes will be used in SetNewLength2d()
9965           // not-marked nodes are those added by refine()
9966           edge._nodes.back()->setIsMarked( true );
9967         }
9968       }
9969     }
9970
9971     bool toFixTria = false; // to improve quality of trias by diagonal swap
9972     if ( isConcaveFace )
9973     {
9974       const bool hasTria = _mesh->NbTriangles(), hasQuad = _mesh->NbQuadrangles();
9975       if ( hasTria != hasQuad ) {
9976         toFixTria = hasTria;
9977       }
9978       else {
9979         set<int> nbNodesSet;
9980         SMDS_ElemIteratorPtr fIt = smDS->GetElements();
9981         while ( fIt->more() && nbNodesSet.size() < 2 )
9982           nbNodesSet.insert( fIt->next()->NbCornerNodes() );
9983         toFixTria = ( *nbNodesSet.begin() == 3 );
9984       }
9985     }
9986
9987     // ==================
9988     // Perform shrinking
9989     // ==================
9990
9991     bool shrinked = true;
9992     int nbBad, shriStep=0, smooStep=0;
9993     _SmoothNode::SmoothType smoothType
9994       = isConcaveFace ? _SmoothNode::ANGULAR : _SmoothNode::LAPLACIAN;
9995     SMESH_Comment errMsg;
9996     while ( shrinked )
9997     {
9998       shriStep++;
9999       // Move boundary nodes (actually just set new UV)
10000       // -----------------------------------------------
10001       dumpFunction(SMESH_Comment("moveBoundaryOnF")<<f2sd->first<<"_st"<<shriStep ); // debug
10002       shrinked = false;
10003       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
10004       {
10005         _EdgesOnShape& eos = * subEOS[ iS ];
10006         for ( size_t i = 0; i < eos._edges.size(); ++i )
10007         {
10008           shrinked |= eos._edges[i]->SetNewLength2d( surface, F, eos, helper );
10009         }
10010       }
10011       dumpFunctionEnd();
10012
10013       // Move nodes on EDGE's
10014       // (XYZ is set as soon as a needed length reached in SetNewLength2d())
10015       set< _Shrinker1D* >::iterator shr = eShri1D.begin();
10016       for ( ; shr != eShri1D.end(); ++shr )
10017         (*shr)->Compute( /*set3D=*/false, helper );
10018
10019       // Smoothing in 2D
10020       // -----------------
10021       int nbNoImpSteps = 0;
10022       bool       moved = true;
10023       nbBad = 1;
10024       while (( nbNoImpSteps < 5 && nbBad > 0) && moved)
10025       {
10026         dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
10027
10028         int oldBadNb = nbBad;
10029         nbBad = 0;
10030         moved = false;
10031         // '% 5' minimizes NB FUNCTIONS on viscous_layers_00/B2 case
10032         _SmoothNode::SmoothType smooTy = ( smooStep % 5 ) ? smoothType : _SmoothNode::LAPLACIAN;
10033         for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
10034         {
10035           moved |= nodesToSmooth[i].Smooth( nbBad, surface, helper, refSign,
10036                                             smooTy, /*set3D=*/isConcaveFace);
10037         }
10038         if ( nbBad < oldBadNb )
10039           nbNoImpSteps = 0;
10040         else
10041           nbNoImpSteps++;
10042
10043         dumpFunctionEnd();
10044       }
10045
10046       errMsg.clear();
10047       if ( nbBad > 0 )
10048         errMsg << "Can't shrink 2D mesh on face " << f2sd->first;
10049       if ( shriStep > 200 )
10050         errMsg << "Infinite loop at shrinking 2D mesh on face " << f2sd->first;
10051       if ( !errMsg.empty() )
10052         break;
10053
10054       // Fix narrow triangles by swapping diagonals
10055       // ---------------------------------------
10056       if ( toFixTria )
10057       {
10058         set<const SMDS_MeshNode*> usedNodes;
10059         fixBadFaces( F, helper, /*is2D=*/true, shriStep, & usedNodes); // swap diagonals
10060
10061         // update working data
10062         set<const SMDS_MeshNode*>::iterator n;
10063         for ( size_t i = 0; i < nodesToSmooth.size() && !usedNodes.empty(); ++i )
10064         {
10065           n = usedNodes.find( nodesToSmooth[ i ]._node );
10066           if ( n != usedNodes.end())
10067           {
10068             _Simplex::GetSimplices( nodesToSmooth[ i ]._node,
10069                                     nodesToSmooth[ i ]._simplices,
10070                                     ignoreShapes, NULL,
10071                                     /*sortSimplices=*/ smoothType == _SmoothNode::ANGULAR );
10072             usedNodes.erase( n );
10073           }
10074         }
10075         for ( size_t i = 0; i < lEdges.size() && !usedNodes.empty(); ++i )
10076         {
10077           n = usedNodes.find( /*tgtNode=*/ lEdges[i]->_nodes.back() );
10078           if ( n != usedNodes.end())
10079           {
10080             _Simplex::GetSimplices( lEdges[i]->_nodes.back(),
10081                                     lEdges[i]->_simplices,
10082                                     ignoreShapes );
10083             usedNodes.erase( n );
10084           }
10085         }
10086       }
10087       // TODO: check effect of this additional smooth
10088       // additional laplacian smooth to increase allowed shrink step
10089       // for ( int st = 1; st; --st )
10090       // {
10091       //   dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
10092       //   for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
10093       //   {
10094       //     nodesToSmooth[i].Smooth( nbBad,surface,helper,refSign,
10095       //                              _SmoothNode::LAPLACIAN,/*set3D=*/false);
10096       //   }
10097       // }
10098
10099     } // while ( shrinked )
10100
10101     if ( !errMsg.empty() ) // Try to re-compute the shrink FACE
10102     {
10103       debugMsg( "Re-compute FACE " << f2sd->first << " because " << errMsg );
10104
10105       // remove faces
10106       SMESHDS_SubMesh* psm = data._proxyMesh->getFaceSubM( F );
10107       {
10108         vector< const SMDS_MeshElement* > facesToRm;
10109         if ( psm )
10110         {
10111           facesToRm.reserve( psm->NbElements() );
10112           for ( SMDS_ElemIteratorPtr ite = psm->GetElements(); ite->more(); )
10113             facesToRm.push_back( ite->next() );
10114
10115           for ( size_t i = 0 ; i < _sdVec.size(); ++i )
10116             if (( psm = _sdVec[i]._proxyMesh->getFaceSubM( F )))
10117               psm->Clear();
10118         }
10119         for ( size_t i = 0; i < facesToRm.size(); ++i )
10120           getMeshDS()->RemoveFreeElement( facesToRm[i], smDS, /*fromGroups=*/false );
10121       }
10122       // remove nodes
10123       {
10124         TIDSortedNodeSet nodesToKeep; // nodes of _LayerEdge to keep
10125         for ( size_t iS = 0; iS < subEOS.size(); ++iS ) {
10126           for ( size_t i = 0; i < subEOS[iS]->_edges.size(); ++i )
10127             nodesToKeep.insert( ++( subEOS[iS]->_edges[i]->_nodes.begin() ),
10128                                 subEOS[iS]->_edges[i]->_nodes.end() );
10129         }
10130         SMDS_NodeIteratorPtr itn = smDS->GetNodes();
10131         while ( itn->more() ) {
10132           const SMDS_MeshNode* n = itn->next();
10133           if ( !nodesToKeep.count( n ))
10134             getMeshDS()->RemoveFreeNode( n, smDS, /*fromGroups=*/false );
10135         }
10136       }
10137       // restore position and UV of target nodes
10138       gp_Pnt p;
10139       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
10140         for ( size_t i = 0; i < subEOS[iS]->_edges.size(); ++i )
10141         {
10142           _LayerEdge*       edge = subEOS[iS]->_edges[i];
10143           SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( edge->_nodes.back() );
10144           if ( edge->_pos.empty() ||
10145                edge->Is( _LayerEdge::SHRUNK )) continue;
10146           if ( subEOS[iS]->SWOLType() == TopAbs_FACE )
10147           {
10148             SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
10149             pos->SetUParameter( edge->_pos[0].X() );
10150             pos->SetVParameter( edge->_pos[0].Y() );
10151             p = surface->Value( edge->_pos[0].X(), edge->_pos[0].Y() );
10152           }
10153           else
10154           {
10155             SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
10156             pos->SetUParameter( edge->_pos[0].Coord( U_TGT ));
10157             p = BRepAdaptor_Curve( TopoDS::Edge( subEOS[iS]->_sWOL )).Value( pos->GetUParameter() );
10158           }
10159           tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
10160           dumpMove( tgtNode );
10161         }
10162       // shrink EDGE sub-meshes and set proxy sub-meshes
10163       UVPtStructVec uvPtVec;
10164       set< _Shrinker1D* >::iterator shrIt = eShri1D.begin();
10165       for ( shrIt = eShri1D.begin(); shrIt != eShri1D.end(); ++shrIt )
10166       {
10167         _Shrinker1D* shr = (*shrIt);
10168         shr->Compute( /*set3D=*/true, helper );
10169
10170         // set proxy mesh of EDGEs w/o layers
10171         map< double, const SMDS_MeshNode* > nodes;
10172         SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), shr->GeomEdge(),/*skipMedium=*/true, nodes);
10173         // remove refinement nodes
10174         const SMDS_MeshNode* sn0 = shr->SrcNode(0), *sn1 = shr->SrcNode(1);
10175         const SMDS_MeshNode* tn0 = shr->TgtNode(0), *tn1 = shr->TgtNode(1);
10176         map< double, const SMDS_MeshNode* >::iterator u2n = nodes.begin();
10177         if ( u2n->second == sn0 || u2n->second == sn1 )
10178         {
10179           while ( u2n->second != tn0 && u2n->second != tn1 )
10180             ++u2n;
10181           nodes.erase( nodes.begin(), u2n );
10182         }
10183         u2n = --nodes.end();
10184         if ( u2n->second == sn0 || u2n->second == sn1 )
10185         {
10186           while ( u2n->second != tn0 && u2n->second != tn1 )
10187             --u2n;
10188           nodes.erase( ++u2n, nodes.end() );
10189         }
10190         // set proxy sub-mesh
10191         uvPtVec.resize( nodes.size() );
10192         u2n = nodes.begin();
10193         BRepAdaptor_Curve2d curve( shr->GeomEdge(), F );
10194         for ( size_t i = 0; i < nodes.size(); ++i, ++u2n )
10195         {
10196           uvPtVec[ i ].node = u2n->second;
10197           uvPtVec[ i ].param = u2n->first;
10198           uvPtVec[ i ].SetUV( curve.Value( u2n->first ).XY() );
10199         }
10200         StdMeshers_FaceSide fSide( uvPtVec, F, shr->GeomEdge(), _mesh );
10201         StdMeshers_ViscousLayers2D::SetProxyMeshOfEdge( fSide );
10202       }
10203
10204       // set proxy mesh of EDGEs with layers
10205       vector< _LayerEdge* > edges;
10206       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
10207       {
10208         _EdgesOnShape& eos = * subEOS[ iS ];
10209         if ( eos.ShapeType() != TopAbs_EDGE ) continue;
10210
10211         const TopoDS_Edge& E = TopoDS::Edge( eos._shape );
10212         data.SortOnEdge( E, eos._edges );
10213
10214         edges.clear();
10215         if ( _EdgesOnShape* eov = data.GetShapeEdges( helper.IthVertex( 0, E, /*CumOri=*/false )))
10216           if ( !eov->_edges.empty() )
10217             edges.push_back( eov->_edges[0] ); // on 1st VERTEX
10218
10219         edges.insert( edges.end(), eos._edges.begin(), eos._edges.end() );
10220
10221         if ( _EdgesOnShape* eov = data.GetShapeEdges( helper.IthVertex( 1, E, /*CumOri=*/false )))
10222           if ( !eov->_edges.empty() )
10223             edges.push_back( eov->_edges[0] ); // on last VERTEX
10224
10225         uvPtVec.resize( edges.size() );
10226         for ( size_t i = 0; i < edges.size(); ++i )
10227         {
10228           uvPtVec[ i ].node = edges[i]->_nodes.back();
10229           uvPtVec[ i ].param = helper.GetNodeU( E, edges[i]->_nodes[0] );
10230           uvPtVec[ i ].SetUV( helper.GetNodeUV( F, edges[i]->_nodes.back() ));
10231         }
10232         BRep_Tool::Range( E, uvPtVec[0].param, uvPtVec.back().param );
10233         StdMeshers_FaceSide fSide( uvPtVec, F, E, _mesh );
10234         StdMeshers_ViscousLayers2D::SetProxyMeshOfEdge( fSide );
10235       }
10236       // temporary clear the FACE sub-mesh from faces made by refine()
10237       vector< const SMDS_MeshElement* > elems;
10238       elems.reserve( smDS->NbElements() + smDS->NbNodes() );
10239       for ( SMDS_ElemIteratorPtr ite = smDS->GetElements(); ite->more(); )
10240         elems.push_back( ite->next() );
10241       for ( SMDS_NodeIteratorPtr ite = smDS->GetNodes(); ite->more(); )
10242         elems.push_back( ite->next() );
10243       smDS->Clear();
10244
10245       // compute the mesh on the FACE
10246       sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
10247       sm->ComputeStateEngine( SMESH_subMesh::COMPUTE_SUBMESH );
10248
10249       // re-fill proxy sub-meshes of the FACE
10250       for ( size_t i = 0 ; i < _sdVec.size(); ++i )
10251         if (( psm = _sdVec[i]._proxyMesh->getFaceSubM( F )))
10252           for ( SMDS_ElemIteratorPtr ite = smDS->GetElements(); ite->more(); )
10253             psm->AddElement( ite->next() );
10254
10255       // re-fill smDS
10256       for ( size_t i = 0; i < elems.size(); ++i )
10257         smDS->AddElement( elems[i] );
10258
10259       if ( sm->GetComputeState() != SMESH_subMesh::COMPUTE_OK )
10260         return error( errMsg );
10261
10262     } // end of re-meshing in case of failed smoothing
10263     else
10264     {
10265       // No wrongly shaped faces remain; final smooth. Set node XYZ.
10266       bool isStructuredFixed = false;
10267       if ( SMESH_2D_Algo* algo = dynamic_cast<SMESH_2D_Algo*>( sm->GetAlgo() ))
10268         isStructuredFixed = algo->FixInternalNodes( *data._proxyMesh, F );
10269       if ( !isStructuredFixed )
10270       {
10271         if ( isConcaveFace ) // fix narrow faces by swapping diagonals
10272           fixBadFaces( F, helper, /*is2D=*/false, ++shriStep );
10273
10274         for ( int st = 3; st; --st )
10275         {
10276           switch( st ) {
10277           case 1: smoothType = _SmoothNode::LAPLACIAN; break;
10278           case 2: smoothType = _SmoothNode::LAPLACIAN; break;
10279           case 3: smoothType = _SmoothNode::ANGULAR; break;
10280           }
10281           dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
10282           for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
10283           {
10284             nodesToSmooth[i].Smooth( nbBad,surface,helper,refSign,
10285                                      smoothType,/*set3D=*/st==1 );
10286           }
10287           dumpFunctionEnd();
10288         }
10289       }
10290       if ( !getMeshDS()->IsEmbeddedMode() )
10291         // Log node movement
10292         for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
10293         {
10294           SMESH_TNodeXYZ p ( nodesToSmooth[i]._node );
10295           getMeshDS()->MoveNode( nodesToSmooth[i]._node, p.X(), p.Y(), p.Z() );
10296         }
10297     }
10298
10299     // Set an event listener to clear FACE sub-mesh together with SOLID sub-mesh
10300     VISCOUS_3D::ToClearSubWithMain( sm, data._solid );
10301     if ( data2 )
10302       VISCOUS_3D::ToClearSubWithMain( sm, data2->_solid );
10303
10304   } // loop on FACES to srink mesh on
10305
10306
10307   // Replace source nodes by target nodes in shrinked mesh edges
10308
10309   map< int, _Shrinker1D >::iterator e2shr = e2shrMap.begin();
10310   for ( ; e2shr != e2shrMap.end(); ++e2shr )
10311     e2shr->second.SwapSrcTgtNodes( getMeshDS() );
10312
10313   return true;
10314 }
10315
10316 //================================================================================
10317 /*!
10318  * \brief Computes 2d shrink direction and finds nodes limiting shrinking
10319  */
10320 //================================================================================
10321
10322 bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge&            edge,
10323                                            _EdgesOnShape&         eos,
10324                                            SMESH_MesherHelper&    helper,
10325                                            const SMESHDS_SubMesh* faceSubMesh)
10326 {
10327   const SMDS_MeshNode* srcNode = edge._nodes[0];
10328   const SMDS_MeshNode* tgtNode = edge._nodes.back();
10329
10330   if ( eos.SWOLType() == TopAbs_FACE )
10331   {
10332     if ( tgtNode->GetPosition()->GetDim() != 2 ) // not inflated edge
10333     {
10334       edge._pos.clear();
10335       edge.Set( _LayerEdge::SHRUNK );
10336       return srcNode == tgtNode;
10337     }
10338     gp_XY srcUV ( edge._pos[0].X(), edge._pos[0].Y() );          //helper.GetNodeUV( F, srcNode );
10339     gp_XY tgtUV = edge.LastUV( TopoDS::Face( eos._sWOL ), eos ); //helper.GetNodeUV( F, tgtNode );
10340     gp_Vec2d uvDir( srcUV, tgtUV );
10341     double uvLen = uvDir.Magnitude();
10342     uvDir /= uvLen;
10343     edge._normal.SetCoord( uvDir.X(),uvDir.Y(), 0 );
10344     edge._len = uvLen;
10345
10346     //edge._pos.resize(1);
10347     edge._pos[0].SetCoord( tgtUV.X(), tgtUV.Y(), 0 );
10348
10349     // set UV of source node to target node
10350     SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
10351     pos->SetUParameter( srcUV.X() );
10352     pos->SetVParameter( srcUV.Y() );
10353   }
10354   else // _sWOL is TopAbs_EDGE
10355   {
10356     if ( tgtNode->GetPosition()->GetDim() != 1 ) // not inflated edge
10357     {
10358       edge._pos.clear();
10359       edge.Set( _LayerEdge::SHRUNK );
10360       return srcNode == tgtNode;
10361     }
10362     const TopoDS_Edge&    E = TopoDS::Edge( eos._sWOL );
10363     SMESHDS_SubMesh* edgeSM = getMeshDS()->MeshElements( E );
10364     if ( !edgeSM || edgeSM->NbElements() == 0 )
10365       return error(SMESH_Comment("Not meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
10366
10367     const SMDS_MeshNode* n2 = 0;
10368     SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
10369     while ( eIt->more() && !n2 )
10370     {
10371       const SMDS_MeshElement* e = eIt->next();
10372       if ( !edgeSM->Contains(e)) continue;
10373       n2 = e->GetNode( 0 );
10374       if ( n2 == srcNode ) n2 = e->GetNode( 1 );
10375     }
10376     if ( !n2 )
10377       return error(SMESH_Comment("Wrongly meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
10378
10379     double uSrc = helper.GetNodeU( E, srcNode, n2 );
10380     double uTgt = helper.GetNodeU( E, tgtNode, srcNode );
10381     double u2   = helper.GetNodeU( E, n2,      srcNode );
10382
10383     //edge._pos.clear();
10384
10385     if ( fabs( uSrc-uTgt ) < 0.99 * fabs( uSrc-u2 ))
10386     {
10387       // tgtNode is located so that it does not make faces with wrong orientation
10388       edge.Set( _LayerEdge::SHRUNK );
10389       return true;
10390     }
10391     //edge._pos.resize(1);
10392     edge._pos[0].SetCoord( U_TGT, uTgt );
10393     edge._pos[0].SetCoord( U_SRC, uSrc );
10394     edge._pos[0].SetCoord( LEN_TGT, fabs( uSrc-uTgt ));
10395
10396     edge._simplices.resize( 1 );
10397     edge._simplices[0]._nPrev = n2;
10398
10399     // set U of source node to the target node
10400     SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
10401     pos->SetUParameter( uSrc );
10402   }
10403   return true;
10404 }
10405
10406 //================================================================================
10407 /*!
10408  * \brief Restore position of a sole node of a _LayerEdge based on _noShrinkShapes
10409  */
10410 //================================================================================
10411
10412 void _ViscousBuilder::restoreNoShrink( _LayerEdge& edge ) const
10413 {
10414   if ( edge._nodes.size() == 1 )
10415   {
10416     edge._pos.clear();
10417     edge._len = 0;
10418
10419     const SMDS_MeshNode* srcNode = edge._nodes[0];
10420     TopoDS_Shape S = SMESH_MesherHelper::GetSubShapeByNode( srcNode, getMeshDS() );
10421     if ( S.IsNull() ) return;
10422
10423     gp_Pnt p;
10424
10425     switch ( S.ShapeType() )
10426     {
10427     case TopAbs_EDGE:
10428     {
10429       double f,l;
10430       TopLoc_Location loc;
10431       Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( S ), loc, f, l );
10432       if ( curve.IsNull() ) return;
10433       SMDS_EdgePosition* ePos = static_cast<SMDS_EdgePosition*>( srcNode->GetPosition() );
10434       p = curve->Value( ePos->GetUParameter() );
10435       break;
10436     }
10437     case TopAbs_VERTEX:
10438     {
10439       p = BRep_Tool::Pnt( TopoDS::Vertex( S ));
10440       break;
10441     }
10442     default: return;
10443     }
10444     getMeshDS()->MoveNode( srcNode, p.X(), p.Y(), p.Z() );
10445     dumpMove( srcNode );
10446   }
10447 }
10448
10449 //================================================================================
10450 /*!
10451  * \brief Try to fix triangles with high aspect ratio by swaping diagonals
10452  */
10453 //================================================================================
10454
10455 void _ViscousBuilder::fixBadFaces(const TopoDS_Face&          F,
10456                                   SMESH_MesherHelper&         helper,
10457                                   const bool                  is2D,
10458                                   const int                   step,
10459                                   set<const SMDS_MeshNode*> * involvedNodes)
10460 {
10461   SMESH::Controls::AspectRatio qualifier;
10462   SMESH::Controls::TSequenceOfXYZ points(3), points1(3), points2(3);
10463   const double maxAspectRatio = is2D ? 4. : 2;
10464   _NodeCoordHelper xyz( F, helper, is2D );
10465
10466   // find bad triangles
10467
10468   vector< const SMDS_MeshElement* > badTrias;
10469   vector< double >                  badAspects;
10470   SMESHDS_SubMesh*      sm = helper.GetMeshDS()->MeshElements( F );
10471   SMDS_ElemIteratorPtr fIt = sm->GetElements();
10472   while ( fIt->more() )
10473   {
10474     const SMDS_MeshElement * f = fIt->next();
10475     if ( f->NbCornerNodes() != 3 ) continue;
10476     for ( int iP = 0; iP < 3; ++iP ) points(iP+1) = xyz( f->GetNode(iP));
10477     double aspect = qualifier.GetValue( points );
10478     if ( aspect > maxAspectRatio )
10479     {
10480       badTrias.push_back( f );
10481       badAspects.push_back( aspect );
10482     }
10483   }
10484   if ( step == 1 )
10485   {
10486     dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID());
10487     SMDS_ElemIteratorPtr fIt = sm->GetElements();
10488     while ( fIt->more() )
10489     {
10490       const SMDS_MeshElement * f = fIt->next();
10491       if ( f->NbCornerNodes() == 3 )
10492         dumpChangeNodes( f );
10493     }
10494     dumpFunctionEnd();
10495   }
10496   if ( badTrias.empty() )
10497     return;
10498
10499   // find couples of faces to swap diagonal
10500
10501   typedef pair < const SMDS_MeshElement* , const SMDS_MeshElement* > T2Trias;
10502   vector< T2Trias > triaCouples; 
10503
10504   TIDSortedElemSet involvedFaces, emptySet;
10505   for ( size_t iTia = 0; iTia < badTrias.size(); ++iTia )
10506   {
10507     T2Trias trias    [3];
10508     double  aspRatio [3];
10509     int i1, i2, i3;
10510
10511     if ( !involvedFaces.insert( badTrias[iTia] ).second )
10512       continue;
10513     for ( int iP = 0; iP < 3; ++iP )
10514       points(iP+1) = xyz( badTrias[iTia]->GetNode(iP));
10515
10516     // find triangles adjacent to badTrias[iTia] with better aspect ratio after diag-swaping
10517     int bestCouple = -1;
10518     for ( int iSide = 0; iSide < 3; ++iSide )
10519     {
10520       const SMDS_MeshNode* n1 = badTrias[iTia]->GetNode( iSide );
10521       const SMDS_MeshNode* n2 = badTrias[iTia]->GetNode(( iSide+1 ) % 3 );
10522       trias [iSide].first  = badTrias[iTia];
10523       trias [iSide].second = SMESH_MeshAlgos::FindFaceInSet( n1, n2, emptySet, involvedFaces,
10524                                                              & i1, & i2 );
10525       if (( ! trias[iSide].second ) ||
10526           ( trias[iSide].second->NbCornerNodes() != 3 ) ||
10527           ( ! sm->Contains( trias[iSide].second )))
10528         continue;
10529
10530       // aspect ratio of an adjacent tria
10531       for ( int iP = 0; iP < 3; ++iP )
10532         points2(iP+1) = xyz( trias[iSide].second->GetNode(iP));
10533       double aspectInit = qualifier.GetValue( points2 );
10534
10535       // arrange nodes as after diag-swaping
10536       if ( helper.WrapIndex( i1+1, 3 ) == i2 )
10537         i3 = helper.WrapIndex( i1-1, 3 );
10538       else
10539         i3 = helper.WrapIndex( i1+1, 3 );
10540       points1 = points;
10541       points1( 1+ iSide ) = points2( 1+ i3 );
10542       points2( 1+ i2    ) = points1( 1+ ( iSide+2 ) % 3 );
10543
10544       // aspect ratio after diag-swaping
10545       aspRatio[ iSide ] = qualifier.GetValue( points1 ) + qualifier.GetValue( points2 );
10546       if ( aspRatio[ iSide ] > aspectInit + badAspects[ iTia ] )
10547         continue;
10548
10549       // prevent inversion of a triangle
10550       gp_Vec norm1 = gp_Vec( points1(1), points1(3) ) ^ gp_Vec( points1(1), points1(2) );
10551       gp_Vec norm2 = gp_Vec( points2(1), points2(3) ) ^ gp_Vec( points2(1), points2(2) );
10552       if ( norm1 * norm2 < 0. && norm1.Angle( norm2 ) > 70./180.*M_PI )
10553         continue;
10554
10555       if ( bestCouple < 0 || aspRatio[ bestCouple ] > aspRatio[ iSide ] )
10556         bestCouple = iSide;
10557     }
10558
10559     if ( bestCouple >= 0 )
10560     {
10561       triaCouples.push_back( trias[bestCouple] );
10562       involvedFaces.insert ( trias[bestCouple].second );
10563     }
10564     else
10565     {
10566       involvedFaces.erase( badTrias[iTia] );
10567     }
10568   }
10569   if ( triaCouples.empty() )
10570     return;
10571
10572   // swap diagonals
10573
10574   SMESH_MeshEditor editor( helper.GetMesh() );
10575   dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
10576   for ( size_t i = 0; i < triaCouples.size(); ++i )
10577   {
10578     dumpChangeNodes( triaCouples[i].first );
10579     dumpChangeNodes( triaCouples[i].second );
10580     editor.InverseDiag( triaCouples[i].first, triaCouples[i].second );
10581   }
10582
10583   if ( involvedNodes )
10584     for ( size_t i = 0; i < triaCouples.size(); ++i )
10585     {
10586       involvedNodes->insert( triaCouples[i].first->begin_nodes(),
10587                              triaCouples[i].first->end_nodes() );
10588       involvedNodes->insert( triaCouples[i].second->begin_nodes(),
10589                              triaCouples[i].second->end_nodes() );
10590     }
10591
10592   // just for debug dump resulting triangles
10593   dumpFunction(SMESH_Comment("swapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
10594   for ( size_t i = 0; i < triaCouples.size(); ++i )
10595   {
10596     dumpChangeNodes( triaCouples[i].first );
10597     dumpChangeNodes( triaCouples[i].second );
10598   }
10599 }
10600
10601 //================================================================================
10602 /*!
10603  * \brief Move target node to it's final position on the FACE during shrinking
10604  */
10605 //================================================================================
10606
10607 bool _LayerEdge::SetNewLength2d( Handle(Geom_Surface)& surface,
10608                                  const TopoDS_Face&    F,
10609                                  _EdgesOnShape&        eos,
10610                                  SMESH_MesherHelper&   helper )
10611 {
10612   if ( Is( SHRUNK ))
10613     return false; // already at the target position
10614
10615   SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( _nodes.back() );
10616
10617   if ( eos.SWOLType() == TopAbs_FACE )
10618   {
10619     gp_XY    curUV = helper.GetNodeUV( F, tgtNode );
10620     gp_Pnt2d tgtUV( _pos[0].X(), _pos[0].Y() );
10621     gp_Vec2d uvDir( _normal.X(), _normal.Y() );
10622     const double uvLen = tgtUV.Distance( curUV );
10623     const double kSafe = Max( 0.5, 1. - 0.1 * _simplices.size() );
10624
10625     // Select shrinking step such that not to make faces with wrong orientation.
10626     double stepSize = 1e100;
10627     for ( size_t i = 0; i < _simplices.size(); ++i )
10628     {
10629       if ( !_simplices[i]._nPrev->isMarked() ||
10630            !_simplices[i]._nNext->isMarked() )
10631         continue; // simplex of quadrangle created by addBoundaryElements()
10632
10633       // find intersection of 2 lines: curUV-tgtUV and that connecting simplex nodes
10634       gp_XY uvN1 = helper.GetNodeUV( F, _simplices[i]._nPrev );
10635       gp_XY uvN2 = helper.GetNodeUV( F, _simplices[i]._nNext );
10636       gp_XY dirN = uvN2 - uvN1;
10637       double det = uvDir.Crossed( dirN );
10638       if ( Abs( det )  < std::numeric_limits<double>::min() ) continue;
10639       gp_XY dirN2Cur = curUV - uvN1;
10640       double step = dirN.Crossed( dirN2Cur ) / det;
10641       if ( step > 0 )
10642         stepSize = Min( step, stepSize );
10643     }
10644     gp_Pnt2d newUV;
10645     if ( uvLen <= stepSize )
10646     {
10647       newUV = tgtUV;
10648       Set( SHRUNK );
10649       //_pos.clear();
10650     }
10651     else if ( stepSize > 0 )
10652     {
10653       newUV = curUV + uvDir.XY() * stepSize * kSafe;
10654     }
10655     else
10656     {
10657       return true;
10658     }
10659     SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
10660     pos->SetUParameter( newUV.X() );
10661     pos->SetVParameter( newUV.Y() );
10662
10663 #ifdef __myDEBUG
10664     gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
10665     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
10666     dumpMove( tgtNode );
10667 #endif
10668   }
10669   else // _sWOL is TopAbs_EDGE
10670   {
10671     const TopoDS_Edge&      E = TopoDS::Edge( eos._sWOL );
10672     const SMDS_MeshNode*   n2 = _simplices[0]._nPrev;
10673     SMDS_EdgePosition* tgtPos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
10674
10675     const double u2     = helper.GetNodeU( E, n2, tgtNode );
10676     const double uSrc   = _pos[0].Coord( U_SRC );
10677     const double lenTgt = _pos[0].Coord( LEN_TGT );
10678
10679     double newU = _pos[0].Coord( U_TGT );
10680     if ( lenTgt < 0.99 * fabs( uSrc-u2 )) // n2 got out of src-tgt range
10681     {
10682       Set( _LayerEdge::SHRUNK );
10683       //_pos.clear();
10684     }
10685     else
10686     {
10687       newU = 0.1 * tgtPos->GetUParameter() + 0.9 * u2;
10688     }
10689     tgtPos->SetUParameter( newU );
10690 #ifdef __myDEBUG
10691     gp_XY newUV = helper.GetNodeUV( F, tgtNode, _nodes[0]);
10692     gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
10693     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
10694     dumpMove( tgtNode );
10695 #endif
10696   }
10697
10698   return true;
10699 }
10700
10701 //================================================================================
10702 /*!
10703  * \brief Perform smooth on the FACE
10704  *  \retval bool - true if the node has been moved
10705  */
10706 //================================================================================
10707
10708 bool _SmoothNode::Smooth(int&                  nbBad,
10709                          Handle(Geom_Surface)& surface,
10710                          SMESH_MesherHelper&   helper,
10711                          const double          refSign,
10712                          SmoothType            how,
10713                          bool                  set3D)
10714 {
10715   const TopoDS_Face& face = TopoDS::Face( helper.GetSubShape() );
10716
10717   // get uv of surrounding nodes
10718   vector<gp_XY> uv( _simplices.size() );
10719   for ( size_t i = 0; i < _simplices.size(); ++i )
10720     uv[i] = helper.GetNodeUV( face, _simplices[i]._nPrev, _node );
10721
10722   // compute new UV for the node
10723   gp_XY newPos (0,0);
10724   if ( how == TFI && _simplices.size() == 4 )
10725   {
10726     gp_XY corners[4];
10727     for ( size_t i = 0; i < _simplices.size(); ++i )
10728       if ( _simplices[i]._nOpp )
10729         corners[i] = helper.GetNodeUV( face, _simplices[i]._nOpp, _node );
10730       else
10731         throw SALOME_Exception(LOCALIZED("TFI smoothing: _Simplex::_nOpp not set!"));
10732
10733     newPos = helper.calcTFI ( 0.5, 0.5,
10734                               corners[0], corners[1], corners[2], corners[3],
10735                               uv[1], uv[2], uv[3], uv[0] );
10736   }
10737   else if ( how == ANGULAR )
10738   {
10739     newPos = computeAngularPos( uv, helper.GetNodeUV( face, _node ), refSign );
10740   }
10741   else if ( how == CENTROIDAL && _simplices.size() > 3 )
10742   {
10743     // average centers of diagonals wieghted with their reciprocal lengths
10744     if ( _simplices.size() == 4 )
10745     {
10746       double w1 = 1. / ( uv[2]-uv[0] ).SquareModulus();
10747       double w2 = 1. / ( uv[3]-uv[1] ).SquareModulus();
10748       newPos = ( w1 * ( uv[2]+uv[0] ) + w2 * ( uv[3]+uv[1] )) / ( w1+w2 ) / 2;
10749     }
10750     else
10751     {
10752       double sumWeight = 0;
10753       int nb = _simplices.size() == 4 ? 2 : _simplices.size();
10754       for ( int i = 0; i < nb; ++i )
10755       {
10756         int iFrom = i + 2;
10757         int iTo   = i + _simplices.size() - 1;
10758         for ( int j = iFrom; j < iTo; ++j )
10759         {
10760           int i2 = SMESH_MesherHelper::WrapIndex( j, _simplices.size() );
10761           double w = 1. / ( uv[i]-uv[i2] ).SquareModulus();
10762           sumWeight += w;
10763           newPos += w * ( uv[i]+uv[i2] );
10764         }
10765       }
10766       newPos /= 2 * sumWeight; // 2 is to get a middle between uv's
10767     }
10768   }
10769   else
10770   {
10771     // Laplacian smooth
10772     for ( size_t i = 0; i < _simplices.size(); ++i )
10773       newPos += uv[i];
10774     newPos /= _simplices.size();
10775   }
10776
10777   // count quality metrics (orientation) of triangles around the node
10778   int nbOkBefore = 0;
10779   gp_XY tgtUV = helper.GetNodeUV( face, _node );
10780   for ( size_t i = 0; i < _simplices.size(); ++i )
10781     nbOkBefore += _simplices[i].IsForward( tgtUV, _node, face, helper, refSign );
10782
10783   int nbOkAfter = 0;
10784   for ( size_t i = 0; i < _simplices.size(); ++i )
10785     nbOkAfter += _simplices[i].IsForward( newPos, _node, face, helper, refSign );
10786
10787   if ( nbOkAfter < nbOkBefore )
10788   {
10789     nbBad += _simplices.size() - nbOkBefore;
10790     return false;
10791   }
10792
10793   SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( _node->GetPosition() );
10794   pos->SetUParameter( newPos.X() );
10795   pos->SetVParameter( newPos.Y() );
10796
10797 #ifdef __myDEBUG
10798   set3D = true;
10799 #endif
10800   if ( set3D )
10801   {
10802     gp_Pnt p = surface->Value( newPos.X(), newPos.Y() );
10803     const_cast< SMDS_MeshNode* >( _node )->setXYZ( p.X(), p.Y(), p.Z() );
10804     dumpMove( _node );
10805   }
10806
10807   nbBad += _simplices.size() - nbOkAfter;
10808   return ( (tgtUV-newPos).SquareModulus() > 1e-10 );
10809 }
10810
10811 //================================================================================
10812 /*!
10813  * \brief Computes new UV using angle based smoothing technic
10814  */
10815 //================================================================================
10816
10817 gp_XY _SmoothNode::computeAngularPos(vector<gp_XY>& uv,
10818                                      const gp_XY&   uvToFix,
10819                                      const double   refSign)
10820 {
10821   uv.push_back( uv.front() );
10822
10823   vector< gp_XY >  edgeDir ( uv.size() );
10824   vector< double > edgeSize( uv.size() );
10825   for ( size_t i = 1; i < edgeDir.size(); ++i )
10826   {
10827     edgeDir [i-1] = uv[i] - uv[i-1];
10828     edgeSize[i-1] = edgeDir[i-1].Modulus();
10829     if ( edgeSize[i-1] < numeric_limits<double>::min() )
10830       edgeDir[i-1].SetX( 100 );
10831     else
10832       edgeDir[i-1] /= edgeSize[i-1] * refSign;
10833   }
10834   edgeDir.back()  = edgeDir.front();
10835   edgeSize.back() = edgeSize.front();
10836
10837   gp_XY  newPos(0,0);
10838   //int    nbEdges = 0;
10839   double sumSize = 0;
10840   for ( size_t i = 1; i < edgeDir.size(); ++i )
10841   {
10842     if ( edgeDir[i-1].X() > 1. ) continue;
10843     int i1 = i-1;
10844     while ( edgeDir[i].X() > 1. && ++i < edgeDir.size() );
10845     if ( i == edgeDir.size() ) break;
10846     gp_XY p = uv[i];
10847     gp_XY norm1( -edgeDir[i1].Y(), edgeDir[i1].X() );
10848     gp_XY norm2( -edgeDir[i].Y(),  edgeDir[i].X() );
10849     gp_XY bisec = norm1 + norm2;
10850     double bisecSize = bisec.Modulus();
10851     if ( bisecSize < numeric_limits<double>::min() )
10852     {
10853       bisec = -edgeDir[i1] + edgeDir[i];
10854       bisecSize = bisec.Modulus();
10855     }
10856     bisec /= bisecSize;
10857
10858     gp_XY  dirToN  = uvToFix - p;
10859     double distToN = dirToN.Modulus();
10860     if ( bisec * dirToN < 0 )
10861       distToN = -distToN;
10862
10863     newPos += ( p + bisec * distToN ) * ( edgeSize[i1] + edgeSize[i] );
10864     //++nbEdges;
10865     sumSize += edgeSize[i1] + edgeSize[i];
10866   }
10867   newPos /= /*nbEdges * */sumSize;
10868   return newPos;
10869 }
10870
10871 //================================================================================
10872 /*!
10873  * \brief Delete _SolidData
10874  */
10875 //================================================================================
10876
10877 _SolidData::~_SolidData()
10878 {
10879   TNode2Edge::iterator n2e = _n2eMap.begin();
10880   for ( ; n2e != _n2eMap.end(); ++n2e )
10881   {
10882     _LayerEdge* & e = n2e->second;
10883     if ( e )
10884     {
10885       delete e->_curvature;
10886       if ( e->_2neibors )
10887         delete e->_2neibors->_plnNorm;
10888       delete e->_2neibors;
10889     }
10890     delete e;
10891     e = 0;
10892   }
10893   _n2eMap.clear();
10894
10895   delete _helper;
10896   _helper = 0;
10897 }
10898
10899 //================================================================================
10900 /*!
10901  * \brief Keep a _LayerEdge inflated along the EDGE
10902  */
10903 //================================================================================
10904
10905 void _Shrinker1D::AddEdge( const _LayerEdge*   e,
10906                            _EdgesOnShape&      eos,
10907                            SMESH_MesherHelper& helper )
10908 {
10909   // init
10910   if ( _nodes.empty() )
10911   {
10912     _edges[0] = _edges[1] = 0;
10913     _done = false;
10914   }
10915   // check _LayerEdge
10916   if ( e == _edges[0] || e == _edges[1] || e->_nodes.size() < 2 )
10917     return;
10918   if ( eos.SWOLType() != TopAbs_EDGE )
10919     throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
10920   if ( _edges[0] && !_geomEdge.IsSame( eos._sWOL ))
10921     throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
10922
10923   // store _LayerEdge
10924   _geomEdge = TopoDS::Edge( eos._sWOL );
10925   double f,l;
10926   BRep_Tool::Range( _geomEdge, f,l );
10927   double u = helper.GetNodeU( _geomEdge, e->_nodes[0], e->_nodes.back());
10928   _edges[ u < 0.5*(f+l) ? 0 : 1 ] = e;
10929
10930   // Update _nodes
10931
10932   const SMDS_MeshNode* tgtNode0 = TgtNode( 0 );
10933   const SMDS_MeshNode* tgtNode1 = TgtNode( 1 );
10934
10935   if ( _nodes.empty() )
10936   {
10937     SMESHDS_SubMesh * eSubMesh = helper.GetMeshDS()->MeshElements( _geomEdge );
10938     if ( !eSubMesh || eSubMesh->NbNodes() < 1 )
10939       return;
10940     TopLoc_Location loc;
10941     Handle(Geom_Curve) C = BRep_Tool::Curve( _geomEdge, loc, f,l );
10942     GeomAdaptor_Curve aCurve(C, f,l);
10943     const double totLen = GCPnts_AbscissaPoint::Length(aCurve, f, l);
10944
10945     int nbExpectNodes = eSubMesh->NbNodes();
10946     _initU  .reserve( nbExpectNodes );
10947     _normPar.reserve( nbExpectNodes );
10948     _nodes  .reserve( nbExpectNodes );
10949     SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
10950     while ( nIt->more() )
10951     {
10952       const SMDS_MeshNode* node = nIt->next();
10953
10954       // skip refinement nodes
10955       if ( node->NbInverseElements(SMDSAbs_Edge) == 0 ||
10956            node == tgtNode0 || node == tgtNode1 )
10957         continue;
10958       bool hasMarkedFace = false;
10959       SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
10960       while ( fIt->more() && !hasMarkedFace )
10961         hasMarkedFace = fIt->next()->isMarked();
10962       if ( !hasMarkedFace )
10963         continue;
10964
10965       _nodes.push_back( node );
10966       _initU.push_back( helper.GetNodeU( _geomEdge, node ));
10967       double len = GCPnts_AbscissaPoint::Length(aCurve, f, _initU.back());
10968       _normPar.push_back(  len / totLen );
10969     }
10970   }
10971   else
10972   {
10973     // remove target node of the _LayerEdge from _nodes
10974     size_t nbFound = 0;
10975     for ( size_t i = 0; i < _nodes.size(); ++i )
10976       if ( !_nodes[i] || _nodes[i] == tgtNode0 || _nodes[i] == tgtNode1 )
10977         _nodes[i] = 0, nbFound++;
10978     if ( nbFound == _nodes.size() )
10979       _nodes.clear();
10980   }
10981 }
10982
10983 //================================================================================
10984 /*!
10985  * \brief Move nodes on EDGE from ends where _LayerEdge's are inflated
10986  */
10987 //================================================================================
10988
10989 void _Shrinker1D::Compute(bool set3D, SMESH_MesherHelper& helper)
10990 {
10991   if ( _done || _nodes.empty())
10992     return;
10993   const _LayerEdge* e = _edges[0];
10994   if ( !e ) e = _edges[1];
10995   if ( !e ) return;
10996
10997   _done =  (( !_edges[0] || _edges[0]->Is( _LayerEdge::SHRUNK )) &&
10998             ( !_edges[1] || _edges[1]->Is( _LayerEdge::SHRUNK )));
10999
11000   double f,l;
11001   if ( set3D || _done )
11002   {
11003     Handle(Geom_Curve) C = BRep_Tool::Curve(_geomEdge, f,l);
11004     GeomAdaptor_Curve aCurve(C, f,l);
11005
11006     if ( _edges[0] )
11007       f = helper.GetNodeU( _geomEdge, _edges[0]->_nodes.back(), _nodes[0] );
11008     if ( _edges[1] )
11009       l = helper.GetNodeU( _geomEdge, _edges[1]->_nodes.back(), _nodes.back() );
11010     double totLen = GCPnts_AbscissaPoint::Length( aCurve, f, l );
11011
11012     for ( size_t i = 0; i < _nodes.size(); ++i )
11013     {
11014       if ( !_nodes[i] ) continue;
11015       double len = totLen * _normPar[i];
11016       GCPnts_AbscissaPoint discret( aCurve, len, f );
11017       if ( !discret.IsDone() )
11018         return throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
11019       double u = discret.Parameter();
11020       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
11021       pos->SetUParameter( u );
11022       gp_Pnt p = C->Value( u );
11023       const_cast< SMDS_MeshNode*>( _nodes[i] )->setXYZ( p.X(), p.Y(), p.Z() );
11024     }
11025   }
11026   else
11027   {
11028     BRep_Tool::Range( _geomEdge, f,l );
11029     if ( _edges[0] )
11030       f = helper.GetNodeU( _geomEdge, _edges[0]->_nodes.back(), _nodes[0] );
11031     if ( _edges[1] )
11032       l = helper.GetNodeU( _geomEdge, _edges[1]->_nodes.back(), _nodes.back() );
11033     
11034     for ( size_t i = 0; i < _nodes.size(); ++i )
11035     {
11036       if ( !_nodes[i] ) continue;
11037       double u = f * ( 1-_normPar[i] ) + l * _normPar[i];
11038       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
11039       pos->SetUParameter( u );
11040     }
11041   }
11042 }
11043
11044 //================================================================================
11045 /*!
11046  * \brief Restore initial parameters of nodes on EDGE
11047  */
11048 //================================================================================
11049
11050 void _Shrinker1D::RestoreParams()
11051 {
11052   if ( _done )
11053     for ( size_t i = 0; i < _nodes.size(); ++i )
11054     {
11055       if ( !_nodes[i] ) continue;
11056       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
11057       pos->SetUParameter( _initU[i] );
11058     }
11059   _done = false;
11060 }
11061
11062 //================================================================================
11063 /*!
11064  * \brief Replace source nodes by target nodes in shrinked mesh edges
11065  */
11066 //================================================================================
11067
11068 void _Shrinker1D::SwapSrcTgtNodes( SMESHDS_Mesh* mesh )
11069 {
11070   const SMDS_MeshNode* nodes[3];
11071   for ( int i = 0; i < 2; ++i )
11072   {
11073     if ( !_edges[i] ) continue;
11074
11075     SMESHDS_SubMesh * eSubMesh = mesh->MeshElements( _geomEdge );
11076     if ( !eSubMesh ) return;
11077     const SMDS_MeshNode* srcNode = _edges[i]->_nodes[0];
11078     const SMDS_MeshNode* tgtNode = _edges[i]->_nodes.back();
11079     const SMDS_MeshNode* scdNode = _edges[i]->_nodes[1];
11080     SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
11081     while ( eIt->more() )
11082     {
11083       const SMDS_MeshElement* e = eIt->next();
11084       if ( !eSubMesh->Contains( e ) || e->GetNodeIndex( scdNode ) >= 0 )
11085           continue;
11086       SMDS_ElemIteratorPtr nIt = e->nodesIterator();
11087       for ( int iN = 0; iN < e->NbNodes(); ++iN )
11088       {
11089         const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
11090         nodes[iN] = ( n == srcNode ? tgtNode : n );
11091       }
11092       mesh->ChangeElementNodes( e, nodes, e->NbNodes() );
11093     }
11094   }
11095 }
11096
11097 //================================================================================
11098 /*!
11099  * \brief Creates 2D and 1D elements on boundaries of new prisms
11100  */
11101 //================================================================================
11102
11103 bool _ViscousBuilder::addBoundaryElements(_SolidData& data)
11104 {
11105   SMESH_MesherHelper helper( *_mesh );
11106
11107   vector< const SMDS_MeshNode* > faceNodes;
11108
11109   //for ( size_t i = 0; i < _sdVec.size(); ++i )
11110   {
11111     //_SolidData& data = _sdVec[i];
11112     TopTools_IndexedMapOfShape geomEdges;
11113     TopExp::MapShapes( data._solid, TopAbs_EDGE, geomEdges );
11114     for ( int iE = 1; iE <= geomEdges.Extent(); ++iE )
11115     {
11116       const TopoDS_Edge& E = TopoDS::Edge( geomEdges(iE));
11117       const TGeomID edgeID = getMeshDS()->ShapeToIndex( E );
11118       if ( data._noShrinkShapes.count( edgeID ))
11119         continue;
11120
11121       // Get _LayerEdge's based on E
11122
11123       map< double, const SMDS_MeshNode* > u2nodes;
11124       if ( !SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), E, /*ignoreMedium=*/false, u2nodes))
11125         continue;
11126
11127       vector< _LayerEdge* > ledges; ledges.reserve( u2nodes.size() );
11128       TNode2Edge & n2eMap = data._n2eMap;
11129       map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
11130       {
11131         //check if 2D elements are needed on E
11132         TNode2Edge::iterator n2e = n2eMap.find( u2n->second );
11133         if ( n2e == n2eMap.end() ) continue; // no layers on vertex
11134         ledges.push_back( n2e->second );
11135         u2n++;
11136         if (( n2e = n2eMap.find( u2n->second )) == n2eMap.end() )
11137           continue; // no layers on E
11138         ledges.push_back( n2eMap[ u2n->second ]);
11139
11140         const SMDS_MeshNode* tgtN0 = ledges[0]->_nodes.back();
11141         const SMDS_MeshNode* tgtN1 = ledges[1]->_nodes.back();
11142         int nbSharedPyram = 0;
11143         SMDS_ElemIteratorPtr vIt = tgtN0->GetInverseElementIterator(SMDSAbs_Volume);
11144         while ( vIt->more() )
11145         {
11146           const SMDS_MeshElement* v = vIt->next();
11147           nbSharedPyram += int( v->GetNodeIndex( tgtN1 ) >= 0 );
11148         }
11149         if ( nbSharedPyram > 1 )
11150           continue; // not free border of the pyramid
11151
11152         faceNodes.clear();
11153         faceNodes.push_back( ledges[0]->_nodes[0] );
11154         faceNodes.push_back( ledges[1]->_nodes[0] );
11155         if ( ledges[0]->_nodes.size() > 1 ) faceNodes.push_back( ledges[0]->_nodes[1] );
11156         if ( ledges[1]->_nodes.size() > 1 ) faceNodes.push_back( ledges[1]->_nodes[1] );
11157
11158         if ( getMeshDS()->FindElement( faceNodes, SMDSAbs_Face, /*noMedium=*/true))
11159           continue; // faces already created
11160       }
11161       for ( ++u2n; u2n != u2nodes.end(); ++u2n )
11162         ledges.push_back( n2eMap[ u2n->second ]);
11163
11164       // Find out orientation and type of face to create
11165
11166       bool reverse = false, isOnFace;
11167       TopoDS_Shape F;
11168
11169       map< TGeomID, TopoDS_Shape >::iterator e2f = data._shrinkShape2Shape.find( edgeID );
11170       if (( isOnFace = ( e2f != data._shrinkShape2Shape.end() )))
11171       {
11172         F = e2f->second.Oriented( TopAbs_FORWARD );
11173         reverse = ( helper.GetSubShapeOri( F, E ) == TopAbs_REVERSED );
11174         if ( helper.GetSubShapeOri( data._solid, F ) == TopAbs_REVERSED )
11175           reverse = !reverse, F.Reverse();
11176         if ( helper.IsReversedSubMesh( TopoDS::Face(F) ))
11177           reverse = !reverse;
11178       }
11179       else if ( !data._ignoreFaceIds.count( e2f->first ))
11180       {
11181         // find FACE with layers sharing E
11182         PShapeIteratorPtr fIt = helper.GetAncestors( E, *_mesh, TopAbs_FACE, &data._solid );
11183         if ( fIt->more() )
11184           F = *( fIt->next() );
11185       }
11186       // Find the sub-mesh to add new faces
11187       SMESHDS_SubMesh* sm = 0;
11188       if ( isOnFace )
11189         sm = getMeshDS()->MeshElements( F );
11190       else
11191         sm = data._proxyMesh->getFaceSubM( TopoDS::Face(F), /*create=*/true );
11192       if ( !sm )
11193         return error("error in addBoundaryElements()", data._index);
11194
11195       // Find a proxy sub-mesh of the FACE of an adjacent SOLID, which will use the new boundary
11196       // faces for 3D meshing (PAL23414)
11197       SMESHDS_SubMesh* adjSM = 0;
11198       if ( isOnFace )
11199       {
11200         const TGeomID   faceID = sm->GetID();
11201         PShapeIteratorPtr soIt = helper.GetAncestors( F, *_mesh, TopAbs_SOLID );
11202         while ( const TopoDS_Shape* solid = soIt->next() )
11203           if ( !solid->IsSame( data._solid ))
11204           {
11205             size_t iData = _solids.FindIndex( *solid ) - 1;
11206             if ( iData < _sdVec.size() &&
11207                  _sdVec[ iData ]._ignoreFaceIds.count( faceID ) &&
11208                  _sdVec[ iData ]._shrinkShape2Shape.count( edgeID ) == 0 )
11209             {
11210               SMESH_ProxyMesh::SubMesh* proxySub =
11211                 _sdVec[ iData ]._proxyMesh->getFaceSubM( TopoDS::Face( F ), /*create=*/false);
11212               if ( proxySub && proxySub->NbElements() > 0 )
11213                 adjSM = proxySub;
11214             }
11215           }
11216       }
11217
11218       // Make faces
11219       const int dj1 = reverse ? 0 : 1;
11220       const int dj2 = reverse ? 1 : 0;
11221       vector< const SMDS_MeshElement*> ff; // new faces row
11222       SMESHDS_Mesh* m = getMeshDS();
11223       for ( size_t j = 1; j < ledges.size(); ++j )
11224       {
11225         vector< const SMDS_MeshNode*>&  nn1 = ledges[j-dj1]->_nodes;
11226         vector< const SMDS_MeshNode*>&  nn2 = ledges[j-dj2]->_nodes;
11227         ff.resize( std::max( nn1.size(), nn2.size() ), NULL );
11228         if ( nn1.size() == nn2.size() )
11229         {
11230           if ( isOnFace )
11231             for ( size_t z = 1; z < nn1.size(); ++z )
11232               sm->AddElement( ff[z-1] = m->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
11233           else
11234             for ( size_t z = 1; z < nn1.size(); ++z )
11235               sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
11236         }
11237         else if ( nn1.size() == 1 )
11238         {
11239           if ( isOnFace )
11240             for ( size_t z = 1; z < nn2.size(); ++z )
11241               sm->AddElement( ff[z-1] = m->AddFace( nn1[0], nn2[z-1], nn2[z] ));
11242           else
11243             for ( size_t z = 1; z < nn2.size(); ++z )
11244               sm->AddElement( new SMDS_FaceOfNodes( nn1[0], nn2[z-1], nn2[z] ));
11245         }
11246         else
11247         {
11248           if ( isOnFace )
11249             for ( size_t z = 1; z < nn1.size(); ++z )
11250               sm->AddElement( ff[z-1] = m->AddFace( nn1[z-1], nn2[0], nn1[z] ));
11251           else
11252             for ( size_t z = 1; z < nn1.size(); ++z )
11253               sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[0], nn2[z] ));
11254         }
11255
11256         if ( adjSM ) // add faces to a proxy SM of the adjacent SOLID
11257         {
11258           for ( size_t z = 0; z < ff.size(); ++z )
11259             if ( ff[ z ])
11260               adjSM->AddElement( ff[ z ]);
11261           ff.clear();
11262         }
11263       }
11264
11265       // Make edges
11266       for ( int isFirst = 0; isFirst < 2; ++isFirst )
11267       {
11268         _LayerEdge* edge = isFirst ? ledges.front() : ledges.back();
11269         _EdgesOnShape* eos = data.GetShapeEdges( edge );
11270         if ( eos && eos->SWOLType() == TopAbs_EDGE )
11271         {
11272           vector< const SMDS_MeshNode*>&  nn = edge->_nodes;
11273           if ( nn.size() < 2 || nn[1]->NbInverseElements( SMDSAbs_Edge ) >= 2 )
11274             continue;
11275           helper.SetSubShape( eos->_sWOL );
11276           helper.SetElementsOnShape( true );
11277           for ( size_t z = 1; z < nn.size(); ++z )
11278             helper.AddEdge( nn[z-1], nn[z] );
11279         }
11280       }
11281
11282     } // loop on EDGE's
11283   } // loop on _SolidData's
11284
11285   return true;
11286 }